title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to merge multiple documents in MongoDB?
To merge multiple documents in MongoDB, use aggregate(). Let us create a collection with documents − > db.demo436.insertOne( ... { ... "_id" : "101", ... "Name": "Chris", ... "details" : [ ... { ... "CountryName" : "US", ... "Age" : 21 ... } ... ], ... "Price" : 50 ... } ... ); { "acknowledged" : true, "insertedId" : "101" } > db.demo436.insertOne( ... { ... "_id" : "102", ... "Name": "Chris", ... "details" : [ ... { ... "CountryName" : "UK", ... "Age" : 22 ... } ... ], ... "Price" : 78 ... } ... ); { "acknowledged" : true, "insertedId" : "102" } > db.demo436.insertOne( ... { ... "_id" : "103", ... "Name": "Chris", ... "details" : [ ... { ... "CountryName" : "US", ... "Age" : 21 ... } ... ], .. . "Price" : 50 ... } ... ); { "acknowledged" : true, "insertedId" : "103" } Display all documents from a collection with the help of find() method − > db.demo436.find(); This will produce the following output − { "_id" : "101", "Name" : "Chris", "details" : [ { "CountryName" : "US", "Age" : 21 } ], "Price" : 50 } { "_id" : "102", "Name" : "Chris", "details" : [ { "CountryName" : "UK", "Age" : 22 } ], "Price" : 78 } { "_id" : "103", "Name" : "Chris", "details" : [ { "CountryName" : "US", "Age" : 21 } ], "Price" : 50 } Following is the query to merge multiple documents in MongoDB − > db.demo436.aggregate([ ... {$sort: {_id: 1, Name: 1}}, ... {$unwind: '$details'}, ... {$group: {_id: '$Name', details: {$push: '$details'}, ... Price: {$sum: '$Price'}, ... id: {$last: {$concat: ["$_id", "_", "AppendedValue" ]}}, ... Name: {$last: '$Name'}}}, ... {$addFields: {Id: 'NewIdAppped', _id: '$id'}}, ... {$project: {"id": 0 }}]) This will produce the following output − { "_id" : "103_AppendedValue", "details" : [ { "CountryName" : "US", "Age" : 21 }, { "CountryName" : "UK", "Age" : 22 }, { "CountryName" : "US", "Age" : 21 } ], "Price" : 178, "Name" : "Chris", "Id" : "NewIdAppped" }
[ { "code": null, "e": 1163, "s": 1062, "text": "To merge multiple documents in MongoDB, use aggregate(). Let us create a collection with documents −" }, { "code": null, "e": 2075, "s": 1163, "text": "> db.demo436.insertOne(\n... {\n... \"_id\" : \"101\",\n... \"Name\": \"Chris\",\n... \"details\" : [\n... {\n... \"CountryName\" : \"US\",\n... \"Age\" : 21\n... }\n... ],\n... \"Price\" : 50\n... }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : \"101\" }\n> db.demo436.insertOne(\n... {\n... \"_id\" : \"102\",\n... \"Name\": \"Chris\",\n... \"details\" : [\n... {\n... \"CountryName\" : \"UK\",\n... \"Age\" : 22\n... }\n... ],\n... \"Price\" : 78\n... }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : \"102\" }\n> db.demo436.insertOne(\n... {\n... \"_id\" : \"103\",\n... \"Name\": \"Chris\",\n... \"details\" : [\n... {\n... \"CountryName\" : \"US\",\n... \"Age\" : 21\n... }\n... ],\n.. . \"Price\" : 50\n... }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : \"103\" }" }, { "code": null, "e": 2148, "s": 2075, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2169, "s": 2148, "text": "> db.demo436.find();" }, { "code": null, "e": 2210, "s": 2169, "text": "This will produce the following output −" }, { "code": null, "e": 2522, "s": 2210, "text": "{ \"_id\" : \"101\", \"Name\" : \"Chris\", \"details\" : [ { \"CountryName\" : \"US\", \"Age\" : 21 } ], \"Price\" : 50 }\n{ \"_id\" : \"102\", \"Name\" : \"Chris\", \"details\" : [ { \"CountryName\" : \"UK\", \"Age\" : 22 } ], \"Price\" : 78 }\n{ \"_id\" : \"103\", \"Name\" : \"Chris\", \"details\" : [ { \"CountryName\" : \"US\", \"Age\" : 21 } ], \"Price\" : 50 }" }, { "code": null, "e": 2586, "s": 2522, "text": "Following is the query to merge multiple documents in MongoDB −" }, { "code": null, "e": 2952, "s": 2586, "text": "> db.demo436.aggregate([\n... {$sort: {_id: 1, Name: 1}},\n... {$unwind: '$details'},\n... {$group: {_id: '$Name', details: {$push: '$details'},\n... Price: {$sum: '$Price'},\n... id: {$last: {$concat: [\"$_id\", \"_\", \"AppendedValue\" ]}},\n... Name: {$last: '$Name'}}},\n... {$addFields: {Id: 'NewIdAppped', _id: '$id'}},\n... {$project: {\"id\": 0 }}])" }, { "code": null, "e": 2993, "s": 2952, "text": "This will produce the following output −" }, { "code": null, "e": 3210, "s": 2993, "text": "{ \"_id\" : \"103_AppendedValue\", \"details\" : [ { \"CountryName\" : \"US\", \"Age\" : 21 }, { \"CountryName\" : \"UK\", \"Age\" : 22 }, { \"CountryName\" : \"US\", \"Age\" : 21 } ], \"Price\" : 178, \"Name\" : \"Chris\", \"Id\" : \"NewIdAppped\" }" } ]
How to find the functions inside a package in R?
There are so many packages in R and each of these packages have different objectives, thus, the number of functions in these packages are large enough to solve the problems in analysis. A package might have fifteen functions and the other might have hundred, it totally depends on the necessity. We can find the functions inside a package by using lsf.str function but we need to load the package prior to knowing the functions inside. library(BSDA) lsf.str("package:BSDA") CIsim : function (samples = 100, n = 30, mu = 0, sigma = 1, conf.level = 0.95, type = "Mean") Combinations : function (n, k) EDA : function (x, trim = 0.05) normarea : function (lower = -Inf, upper = Inf, m, sig) nsize : function (b, sigma = NULL, p = 0.5, conf.level = 0.95, type = "mu") ntester : function (actual.data) SIGN.test : function (x, y = NULL, md = 0, alternative = "two.sided", conf.level = 0.95, ...) SRS : function (POPvalues, n) tsum.test : function (mean.x, s.x = NULL, n.x = NULL, mean.y = NULL, s.y = NULL, n.y = NULL, alternative = "two.sided", mu = 0, var.equal = FALSE, conf.level = 0.95) z.test : function (x, y = NULL, alternative = "two.sided", mu = 0, sigma.x = NULL, sigma.y = NULL, conf.level = 0.95) zsum.test : function (mean.x, sigma.x = NULL, n.x = NULL, mean.y = NULL, sigma.y = NULL, n.y = NULL, alternative = "two.sided", mu = 0, conf.level = 0.95) library(sqldf) lsf.str("package:sqldf") read.csv.sql : function (file, sql = "select * from file", header = TRUE, sep = ",", row.names, eol, skip, filter, nrows, field.types, colClasses, dbname = tempfile(), drv = "SQLite", ...) read.csv2.sql : function (file, sql = "select * from file", header = TRUE, sep = ";", row.names, eol, skip, filter, nrows, field.types, colClasses, dbname = tempfile(), drv = "SQLite", ...) sqldf : function (x, stringsAsFactors = FALSE, row.names = FALSE, envir = parent.frame(), method = getOption("sqldf.method"), file.format = list(), dbname, drv = getOption("sqldf.driver"), user, password = "", host = "localhost", port, dll = getOption("sqldf.dll"), connection = getOption("sqldf.connection"), verbose = isTRUE(getOption("sqldf.verbose"))) library(rvest) lsf.str("package:rvest") %>% : function (lhs, rhs) back : function (x) follow_link : function (x, i, css, xpath, ...) google_form : function (x) guess_encoding : function (x) html : function (x, ..., encoding = "") html_attr : function (x, name, default = NA_character_) html_attrs : function (x) html_children : function (x) html_form : function (x) html_name : function (x) html_node : function (x, css, xpath) html_nodes : function (x, css, xpath) html_session : function (url, ...) html_table : function (x, header = NA, trim = TRUE, fill = FALSE, dec = ".") html_tag : function (x) html_text : function (x, trim = FALSE) is.session : function (x) jump_to : function (x, url, ...) minimal_html : function (title, html = "") pluck : function (x, i, type) repair_encoding : function (x, from = NULL) session_history : function (x) set_values : function (form, ...) submit_form : function (session, form, submit = NULL, ...) xml : function (x, ..., encoding = "") xml_node : function (x, css, xpath) xml_nodes : function (x, css, xpath) xml_tag : function (x)
[ { "code": null, "e": 1498, "s": 1062, "text": "There are so many packages in R and each of these packages have different objectives, thus, the number of functions in these packages are large enough to solve the problems in analysis. A package might have fifteen functions and the other might have hundred, it totally depends on the necessity. We can find the functions inside a package by using lsf.str function but we need to load the package prior to knowing the functions inside." }, { "code": null, "e": 2421, "s": 1498, "text": "library(BSDA)\nlsf.str(\"package:BSDA\")\nCIsim : function (samples = 100, n = 30, mu = 0, sigma = 1, conf.level = 0.95,\ntype = \"Mean\")\nCombinations : function (n, k)\nEDA : function (x, trim = 0.05)\nnormarea : function (lower = -Inf, upper = Inf, m, sig)\nnsize : function (b, sigma = NULL, p = 0.5, conf.level = 0.95, type = \"mu\")\nntester : function (actual.data)\nSIGN.test : function (x, y = NULL, md = 0, alternative = \"two.sided\", conf.level = 0.95,\n...)\nSRS : function (POPvalues, n)\ntsum.test : function (mean.x, s.x = NULL, n.x = NULL, mean.y = NULL, s.y = NULL, n.y = NULL,\nalternative = \"two.sided\", mu = 0, var.equal = FALSE, conf.level = 0.95)\nz.test : function (x, y = NULL, alternative = \"two.sided\", mu = 0, sigma.x = NULL,\nsigma.y = NULL, conf.level = 0.95)\nzsum.test : function (mean.x, sigma.x = NULL, n.x = NULL, mean.y = NULL, sigma.y = NULL,\nn.y = NULL, alternative = \"two.sided\", mu = 0, conf.level = 0.95)" }, { "code": null, "e": 3196, "s": 2421, "text": "library(sqldf)\nlsf.str(\"package:sqldf\")\nread.csv.sql : function (file, sql = \"select * from file\", header = TRUE, sep = \",\", row.names,\neol, skip, filter, nrows, field.types, colClasses, dbname = tempfile(),\ndrv = \"SQLite\", ...)\nread.csv2.sql : function (file, sql = \"select * from file\", header = TRUE, sep = \";\", row.names,\neol, skip, filter, nrows, field.types, colClasses, dbname = tempfile(),\ndrv = \"SQLite\", ...)\nsqldf : function (x, stringsAsFactors = FALSE, row.names = FALSE, envir = parent.frame(),\nmethod = getOption(\"sqldf.method\"), file.format = list(), dbname, drv = getOption(\"sqldf.driver\"),\nuser, password = \"\", host = \"localhost\", port, dll = getOption(\"sqldf.dll\"),\nconnection = getOption(\"sqldf.connection\"), verbose = isTRUE(getOption(\"sqldf.verbose\")))" }, { "code": null, "e": 4272, "s": 3196, "text": "library(rvest)\nlsf.str(\"package:rvest\")\n%>% : function (lhs, rhs)\nback : function (x)\nfollow_link : function (x, i, css, xpath, ...)\ngoogle_form : function (x)\nguess_encoding : function (x)\nhtml : function (x, ..., encoding = \"\")\nhtml_attr : function (x, name, default = NA_character_)\nhtml_attrs : function (x)\nhtml_children : function (x)\nhtml_form : function (x)\nhtml_name : function (x)\nhtml_node : function (x, css, xpath)\nhtml_nodes : function (x, css, xpath)\nhtml_session : function (url, ...)\nhtml_table : function (x, header = NA, trim = TRUE, fill = FALSE, dec = \".\")\nhtml_tag : function (x)\nhtml_text : function (x, trim = FALSE)\nis.session : function (x)\njump_to : function (x, url, ...)\nminimal_html : function (title, html = \"\")\npluck : function (x, i, type)\nrepair_encoding : function (x, from = NULL)\nsession_history : function (x)\nset_values : function (form, ...)\nsubmit_form : function (session, form, submit = NULL, ...)\nxml : function (x, ..., encoding = \"\")\nxml_node : function (x, css, xpath)\nxml_nodes : function (x, css, xpath)\nxml_tag : function (x)" } ]
crypto.generateKeyPairSync() Method in Node.js
The crypto.generateKeyPairSync() can be used to generate a new asymmetric key pair of the specified type in a sync flow. Supported types for generating key pair are: RSA, DSA, EC, Ed25519, Ed448, X25519, X448 and DH. The function behaves as if keyObject.export has been called on its result when a publicKeyEncoding or privateKeyEncoding is specified, else the respective part of keyObject is returned. The suggested type for public key is 'spki' and for private key it is 'pkcs8'. crypto.generateKeyPairSync(type, options) The above parameters are described as below − type – It holds the string type for which keys needs to be generated. Supported types are - RSA, DSA, EC, Ed25519, Ed448, X25519, X448 and DH. type – It holds the string type for which keys needs to be generated. Supported types are - RSA, DSA, EC, Ed25519, Ed448, X25519, X448 and DH. options – It can hold the following parameters −modulusLength – This holds the key size in bits for type (RSA, DSA).publicExponent – This holds the public exponent value for RSA algorithm.Default value is – 0x10001divisorLength – This holds the size of q in bits.namedCurve – This will hold the name of the curve to be used.prime – This will hold the prime parameter for types like DH.PrimeLength – This will hold the prime length in bits.generator – This parameter holds the custom generator value, Default: 2.groupName – This is the diffe-hellman group name for DH algorithm.publicKeyEncoding – This will hold the string value for public key encoding.privateKeyEncoding - This will hold the string value for private key encoding. options – It can hold the following parameters − modulusLength – This holds the key size in bits for type (RSA, DSA). modulusLength – This holds the key size in bits for type (RSA, DSA). publicExponent – This holds the public exponent value for RSA algorithm.Default value is – 0x10001 publicExponent – This holds the public exponent value for RSA algorithm. Default value is – 0x10001 divisorLength – This holds the size of q in bits. divisorLength – This holds the size of q in bits. namedCurve – This will hold the name of the curve to be used. namedCurve – This will hold the name of the curve to be used. prime – This will hold the prime parameter for types like DH. prime – This will hold the prime parameter for types like DH. PrimeLength – This will hold the prime length in bits. PrimeLength – This will hold the prime length in bits. generator – This parameter holds the custom generator value, Default: 2. generator – This parameter holds the custom generator value, Default: 2. groupName – This is the diffe-hellman group name for DH algorithm. groupName – This is the diffe-hellman group name for DH algorithm. publicKeyEncoding – This will hold the string value for public key encoding. publicKeyEncoding – This will hold the string value for public key encoding. privateKeyEncoding - This will hold the string value for private key encoding. privateKeyEncoding - This will hold the string value for private key encoding. Create a file with name – generateKeyPairSync.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below − node generateKeyPairSync.js generateKeyPairSync.js // Node.js program to demonstrate the flow of crypto.generateKeyPair() method // Importing generateKeyPairSync from crypto module const { generateKeyPairSync } = require('crypto'); //Getting the value of publicKye and privateKey in a sync process const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'secp256k1', // Implementing options publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' } }); // Printing the asymmetric key pair in a sync process console.log("The public key is: ", publicKey); console.log(); console.log("The private key is: ", privateKey); C:\home\node>> node generateKeyPairSync.js The public key is: <Buffer 30 56 30 10 06 07 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 0a 03 42 00 04 a1 76 dd f0 fe 96 cc 28 59 a5 45 16 58 86 ca 3b 56 1e 04 ee b0 de 28 67 0a 70 ... > The private key is: <Buffer 30 81 84 02 01 00 30 10 06 07 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 0a 04 6d 30 6b 02 01 01 04 20 e6 f0 69 2e b0 35 7d 0b 5c ba 76 fc dc 9f 95 ae d7 ... > Let's take a look at one more example. // Node.js program to demonstrate the flow of crypto.generateKeyPair() method // Importing generateKeyPairSync from crypto module const { generateKeyPairSync } = require('crypto'); //Getting the value of publicKye and privateKey in a sync process const { publicKey, privateKey } = generateKeyPairSync('dsa', { modulusLength: 570, //Implementing options publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' } }); // Printing asymmetric key pair after encoding console.log("Public Key is: ", publicKey) console.log("The public key value in base64 is: ", publicKey.toString('base64')); console.log("------------------------------------------------------") console.log("Private Key is: ", privateKey) console.log("The private key in base64 is: ", privateKey.toString('base64')); C:\home\node>> node generateKeyPairSync.js Public Key is: <Buffer 30 82 01 0f 30 81 bf 06 07 2a 86 48 ce 38 04 01 30 81 b3 02 49 00 9a 5c dd a3 ce 0e 8e 3e 0e ed 11 96 13 fe 1c a6 f6 35 27 0c 60 f9 51 ee dd 2c 75 12 ... > The public key value in base64 is: MIIBDzCBvwYHKoZIzjgEATCBswJJAJpc3aPODo4+Du0RlhP+HKb2NScMYPlR7t0sdRJhr0JWPvtRyF Wmn5ZAldFdDrUye5eQ+HmwgJboEWtCUm3b24CoLSQ74P1YkwIdAJs5rCSAIefaTT469xx+/8C3jS4W jYpHci0rft8CR3Fx1wxDFdCHJBqPlR7iGxd+7nZlChABL7UqCZMaiwCJ2ijVXc5dgr3Frudu7CbaAn RJStbqDjm5ppj4aaZV/9FmKvWVao9wA0sAAkhQtXOIWQrHde+fXoZLgPhbTBctPB1tcFztNmq2s3IO KGfo2kFUL6eJu811SSZ1scQFLVKc5DrZIdW7t3UqzEH+xCVxNkWtGQk= ------------------------------------------------------ Private Key is: <Buffer 30 81 e5 02 01 00 30 81 bf 06 07 2a 86 48 ce 38 04 01 30 81 b3 02 49 00 9a 5c dd a3 ce 0e 8e 3e 0e ed 11 96 13 fe 1c a6 f6 35 27 0c 60 f9 51 ee dd 2c ... > The private key in base64 is: MIHlAgEAMIG/BgcqhkjOOAQBMIGzAkkAmlzdo84Ojj4O7RGWE/4cpvY1Jwxg+VHu3Sx1EmGvQlY++1 HIVaaflkCV0V0OtTJ7l5D4ebCAlugRa0JSbdvbgKgtJDvg/ViTAh0AmzmsJIAh59pNPjr3HH7/wLeN LhaNikdyLSt+3wJHcXHXDEMV0IckGo+VHuIbF37udmUKEAEvtSoJkxqLAInaKNVdzl2CvcWu527sJt oCdElK1uoOObmmmPhpplX/0WYq9ZVqj3AEHgIcJ2ON17GGE4FrtkJak337GB+bAEkb+YjulN2rug==
[ { "code": null, "e": 1544, "s": 1062, "text": "The crypto.generateKeyPairSync() can be used to generate a new asymmetric key pair of the specified type in a sync flow. Supported types for generating key pair are: RSA, DSA, EC, Ed25519, Ed448, X25519, X448 and DH. The function behaves as if keyObject.export has been called on its result when a publicKeyEncoding or privateKeyEncoding is specified, else the respective part of keyObject is returned. The suggested type for public key is 'spki' and for private key it is 'pkcs8'." }, { "code": null, "e": 1586, "s": 1544, "text": "crypto.generateKeyPairSync(type, options)" }, { "code": null, "e": 1632, "s": 1586, "text": "The above parameters are described as below −" }, { "code": null, "e": 1775, "s": 1632, "text": "type – It holds the string type for which keys needs to be generated. Supported types are - RSA, DSA, EC, Ed25519, Ed448, X25519, X448 and DH." }, { "code": null, "e": 1918, "s": 1775, "text": "type – It holds the string type for which keys needs to be generated. Supported types are - RSA, DSA, EC, Ed25519, Ed448, X25519, X448 and DH." }, { "code": null, "e": 2650, "s": 1918, "text": "options – It can hold the following parameters −modulusLength – This holds the key size in bits for type (RSA, DSA).publicExponent – This holds the public exponent value for RSA algorithm.Default value is – 0x10001divisorLength – This holds the size of q in bits.namedCurve – This will hold the name of the curve to be used.prime – This will hold the prime parameter for types like DH.PrimeLength – This will hold the prime length in bits.generator – This parameter holds the custom generator value, Default: 2.groupName – This is the diffe-hellman group name for DH algorithm.publicKeyEncoding – This will hold the string value for public key encoding.privateKeyEncoding - This will hold the string value for private key encoding." }, { "code": null, "e": 2699, "s": 2650, "text": "options – It can hold the following parameters −" }, { "code": null, "e": 2768, "s": 2699, "text": "modulusLength – This holds the key size in bits for type (RSA, DSA)." }, { "code": null, "e": 2837, "s": 2768, "text": "modulusLength – This holds the key size in bits for type (RSA, DSA)." }, { "code": null, "e": 2936, "s": 2837, "text": "publicExponent – This holds the public exponent value for RSA algorithm.Default value is – 0x10001" }, { "code": null, "e": 3009, "s": 2936, "text": "publicExponent – This holds the public exponent value for RSA algorithm." }, { "code": null, "e": 3036, "s": 3009, "text": "Default value is – 0x10001" }, { "code": null, "e": 3086, "s": 3036, "text": "divisorLength – This holds the size of q in bits." }, { "code": null, "e": 3136, "s": 3086, "text": "divisorLength – This holds the size of q in bits." }, { "code": null, "e": 3198, "s": 3136, "text": "namedCurve – This will hold the name of the curve to be used." }, { "code": null, "e": 3260, "s": 3198, "text": "namedCurve – This will hold the name of the curve to be used." }, { "code": null, "e": 3322, "s": 3260, "text": "prime – This will hold the prime parameter for types like DH." }, { "code": null, "e": 3384, "s": 3322, "text": "prime – This will hold the prime parameter for types like DH." }, { "code": null, "e": 3439, "s": 3384, "text": "PrimeLength – This will hold the prime length in bits." }, { "code": null, "e": 3494, "s": 3439, "text": "PrimeLength – This will hold the prime length in bits." }, { "code": null, "e": 3567, "s": 3494, "text": "generator – This parameter holds the custom generator value, Default: 2." }, { "code": null, "e": 3640, "s": 3567, "text": "generator – This parameter holds the custom generator value, Default: 2." }, { "code": null, "e": 3707, "s": 3640, "text": "groupName – This is the diffe-hellman group name for DH algorithm." }, { "code": null, "e": 3774, "s": 3707, "text": "groupName – This is the diffe-hellman group name for DH algorithm." }, { "code": null, "e": 3851, "s": 3774, "text": "publicKeyEncoding – This will hold the string value for public key encoding." }, { "code": null, "e": 3928, "s": 3851, "text": "publicKeyEncoding – This will hold the string value for public key encoding." }, { "code": null, "e": 4007, "s": 3928, "text": "privateKeyEncoding - This will hold the string value for private key encoding." }, { "code": null, "e": 4086, "s": 4007, "text": "privateKeyEncoding - This will hold the string value for private key encoding." }, { "code": null, "e": 4264, "s": 4086, "text": "Create a file with name – generateKeyPairSync.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −" }, { "code": null, "e": 4292, "s": 4264, "text": "node generateKeyPairSync.js" }, { "code": null, "e": 4315, "s": 4292, "text": "generateKeyPairSync.js" }, { "code": null, "e": 4989, "s": 4315, "text": "// Node.js program to demonstrate the flow of crypto.generateKeyPair() method\n\n// Importing generateKeyPairSync from crypto module\nconst { generateKeyPairSync } = require('crypto');\n\n//Getting the value of publicKye and privateKey in a sync process\nconst { publicKey, privateKey } = generateKeyPairSync('ec', {\n namedCurve: 'secp256k1', // Implementing options\n publicKeyEncoding: {\n type: 'spki',\n format: 'der'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'der'\n }\n});\n\n// Printing the asymmetric key pair in a sync process\nconsole.log(\"The public key is: \", publicKey);\nconsole.log();\nconsole.log(\"The private key is: \", privateKey);" }, { "code": null, "e": 5400, "s": 4989, "text": "C:\\home\\node>> node generateKeyPairSync.js\nThe public key is: <Buffer 30 56 30 10 06 07 2a 86 48 ce 3d 02 01 06 05 2b 81\n04 00 0a 03 42 00 04 a1 76 dd f0 fe 96 cc 28 59 a5 45 16 58 86 ca 3b 56 1e 04\nee b0 de 28 67 0a 70 ... >\n\nThe private key is: <Buffer 30 81 84 02 01 00 30 10 06 07 2a 86 48 ce 3d 02\n01 06 05 2b 81 04 00 0a 04 6d 30 6b 02 01 01 04 20 e6 f0 69 2e b0 35 7d 0b 5c\nba 76 fc dc 9f 95 ae d7 ... >" }, { "code": null, "e": 5439, "s": 5400, "text": "Let's take a look at one more example." }, { "code": null, "e": 6312, "s": 5439, "text": "// Node.js program to demonstrate the flow of crypto.generateKeyPair() method\n\n// Importing generateKeyPairSync from crypto module\nconst { generateKeyPairSync } = require('crypto');\n\n//Getting the value of publicKye and privateKey in a sync process\nconst { publicKey, privateKey } = generateKeyPairSync('dsa', {\n modulusLength: 570, //Implementing options\n publicKeyEncoding: {\n type: 'spki',\n format: 'der'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'der'\n }\n});\n\n// Printing asymmetric key pair after encoding\nconsole.log(\"Public Key is: \", publicKey)\nconsole.log(\"The public key value in base64 is: \",\n publicKey.toString('base64'));\nconsole.log(\"------------------------------------------------------\")\nconsole.log(\"Private Key is: \", privateKey)\nconsole.log(\"The private key in base64 is: \",\n privateKey.toString('base64'));" }, { "code": null, "e": 7523, "s": 6312, "text": "C:\\home\\node>> node generateKeyPairSync.js\nPublic Key is: <Buffer 30 82 01 0f 30 81 bf 06 07 2a 86 48 ce 38 04 01 30 81\nb3 02 49 00 9a 5c dd a3 ce 0e 8e 3e 0e ed 11 96 13 fe 1c a6 f6 35 27 0c 60 f9\n51 ee dd 2c 75 12 ... >\nThe public key value in base64 is:\nMIIBDzCBvwYHKoZIzjgEATCBswJJAJpc3aPODo4+Du0RlhP+HKb2NScMYPlR7t0sdRJhr0JWPvtRyF\nWmn5ZAldFdDrUye5eQ+HmwgJboEWtCUm3b24CoLSQ74P1YkwIdAJs5rCSAIefaTT469xx+/8C3jS4W\njYpHci0rft8CR3Fx1wxDFdCHJBqPlR7iGxd+7nZlChABL7UqCZMaiwCJ2ijVXc5dgr3Frudu7CbaAn\nRJStbqDjm5ppj4aaZV/9FmKvWVao9wA0sAAkhQtXOIWQrHde+fXoZLgPhbTBctPB1tcFztNmq2s3IO\nKGfo2kFUL6eJu811SSZ1scQFLVKc5DrZIdW7t3UqzEH+xCVxNkWtGQk=\n------------------------------------------------------\nPrivate Key is: <Buffer 30 81 e5 02 01 00 30 81 bf 06 07 2a 86 48 ce 38 04 01\n30 81 b3 02 49 00 9a 5c dd a3 ce 0e 8e 3e 0e ed 11 96 13 fe 1c a6 f6 35 27 0c\n60 f9 51 ee dd 2c ... >\nThe private key in base64 is:\nMIHlAgEAMIG/BgcqhkjOOAQBMIGzAkkAmlzdo84Ojj4O7RGWE/4cpvY1Jwxg+VHu3Sx1EmGvQlY++1\nHIVaaflkCV0V0OtTJ7l5D4ebCAlugRa0JSbdvbgKgtJDvg/ViTAh0AmzmsJIAh59pNPjr3HH7/wLeN\nLhaNikdyLSt+3wJHcXHXDEMV0IckGo+VHuIbF37udmUKEAEvtSoJkxqLAInaKNVdzl2CvcWu527sJt\noCdElK1uoOObmmmPhpplX/0WYq9ZVqj3AEHgIcJ2ON17GGE4FrtkJak337GB+bAEkb+YjulN2rug==" } ]
Group Shifted String - GeeksforGeeks
23 Jun, 2021 Given an array of strings (all lowercase letters), the task is to group them in such a way that all strings in a group are shifted versions of each other. Two string S and T are called shifted if, S.length = T.length and S[i] = T[i] + K for 1 <= i <= S.length for a constant integer K For example strings, {acd, dfg, wyz, yab, mop} are shifted versions of each other. Input : str[] = {"acd", "dfg", "wyz", "yab", "mop", "bdfh", "a", "x", "moqs"}; Output : a x acd dfg wyz yab mop bdfh moqs All shifted strings are grouped together. We can see a pattern among the string of one group, the difference between consecutive characters for all character of the string are equal. As in the above example take acd, dfg and mopa c d -> 2 1 d f g -> 2 1 m o p -> 2 1Since the differences are the same, we can use this to identify strings that belong to the same group. The idea is to form a string of differences as key. If a string with the same difference string is found, then this string also belongs to the same group. For example, the above three strings have the same difference string, which is “21”. In the below implementation, we add ‘a’ to every difference and store 21 as “ba”. C++ Python3 Javascript /* C/C++ program to print groups of shifted strings together. */#include <bits/stdc++.h>using namespace std;const int ALPHA = 26; // Total lowercase letter // Method to a difference string for a given string.// If string is "adf" then difference string will be// "cb" (first difference 3 then difference 2)string getDiffString(string str){ string shift = ""; for (int i = 1; i < str.length(); i++) { int dif = str[i] - str[i-1]; if (dif < 0) dif += ALPHA; // Representing the difference as char shift += (dif + 'a'); } // This string will be 1 less length than str return shift;} // Method for grouping shifted stringvoid groupShiftedString(string str[], int n){ // map for storing indices of string which are // in same group map< string, vector<int> > groupMap; for (int i = 0; i < n; i++) { string diffStr = getDiffString(str[i]); groupMap[diffStr].push_back(i); } // iterating through map to print group for (auto it=groupMap.begin(); it!=groupMap.end(); it++) { vector<int> v = it->second; for (int i = 0; i < v.size(); i++) cout << str[v[i]] << " "; cout << endl; }} // Driver method to test above methodsint main(){ string str[] = {"acd", "dfg", "wyz", "yab", "mop", "bdfh", "a", "x", "moqs" }; int n = sizeof(str)/sizeof(str[0]); groupShiftedString(str, n); return 0;} # Python3 program to print groups# of shifted strings together. # Total lowercase letterALPHA = 26 # Method to a difference string# for a given string. If string# is "adf" then difference string# will be "cb" (first difference# 3 then difference 2)def getDiffString(str): shift="" for i in range(1, len(str)): dif = (ord(str[i]) - ord(str[i - 1])) if(dif < 0): dif += ALPHA # Representing the difference # as char shift += chr(dif + ord('a')) # This string will be 1 less # length than str return shift # Method for grouping# shifted stringdef groupShiftedString(str,n): # map for storing indices # of string which are # in same group groupMap = {} for i in range(n): diffStr = getDiffString(str[i]) if diffStr not in groupMap: groupMap[diffStr] = [i] else: groupMap[diffStr].append(i) # Iterating through map # to print group for it in groupMap: v = groupMap[it] for i in range(len(v)): print(str[v[i]], end = " ") print() # Driver codestr = ["acd", "dfg", "wyz", "yab", "mop","bdfh", "a", "x", "moqs"]n = len(str)groupShiftedString(str, n) # This code is contributed by avanitrachhadiya2155 <script> /* Javascript program to print groups of shifted strings together. */let ALPHA = 26; // Method to a difference string for a given string.// If string is "adf" then difference string will be// "cb" (first difference 3 then difference 2)function getDiffString(str){ let shift = ""; for (let i = 1; i < str.length; i++) { let dif = str[i] - str[i-1]; if (dif < 0) dif += ALPHA; // Representing the difference as char shift += (dif + 'a'); } // This string will be 1 less length than str return shift;} // Method for grouping shifted stringfunction groupShiftedString(str, n){ // map for storing indices of string which are // in same group let groupMap = new Map(); for (let i = 0; i < n; i++) { let diffStr = getDiffString(str[i]); if(!groupMap.has(diffStr)) groupMap.set(diffStr,[]); groupMap.get(diffStr).push(i); } // iterating through map to print group for (let [key, value] of groupMap.entries()) { let v = value; for (let i = 0; i < v.length; i++) document.write(str[v[i]]+" "); document.write("<br>") }} // Driver method to test above methodslet str=["acd", "dfg", "wyz", "yab", "mop", "bdfh", "a", "x", "moqs"];let n = str.length;groupShiftedString(str, n); // This code is contributed by ab2127</script> Output: a x acd dfg wyz yab mop bdfh moqs This article is contributed by Utkarsh Trivedi. 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. avanitrachhadiya2155 ab2127 Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Most frequent element in an array Counting frequencies of array elements Sorting a Map by value in C++ STL Double Hashing C++ program for hashing with chaining Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25136, "s": 25108, "text": "\n23 Jun, 2021" }, { "code": null, "e": 25334, "s": 25136, "text": "Given an array of strings (all lowercase letters), the task is to group them in such a way that all strings in a group are shifted versions of each other. Two string S and T are called shifted if, " }, { "code": null, "e": 25425, "s": 25334, "text": "S.length = T.length \nand\nS[i] = T[i] + K for \n1 <= i <= S.length for a constant integer K" }, { "code": null, "e": 25508, "s": 25425, "text": "For example strings, {acd, dfg, wyz, yab, mop} are shifted versions of each other." }, { "code": null, "e": 25709, "s": 25508, "text": "Input : str[] = {\"acd\", \"dfg\", \"wyz\", \"yab\", \"mop\",\n \"bdfh\", \"a\", \"x\", \"moqs\"};\n\nOutput : a x\n acd dfg wyz yab mop\n bdfh moqs\nAll shifted strings are grouped together." }, { "code": null, "e": 26359, "s": 25709, "text": "We can see a pattern among the string of one group, the difference between consecutive characters for all character of the string are equal. As in the above example take acd, dfg and mopa c d -> 2 1 d f g -> 2 1 m o p -> 2 1Since the differences are the same, we can use this to identify strings that belong to the same group. The idea is to form a string of differences as key. If a string with the same difference string is found, then this string also belongs to the same group. For example, the above three strings have the same difference string, which is “21”. In the below implementation, we add ‘a’ to every difference and store 21 as “ba”. " }, { "code": null, "e": 26363, "s": 26359, "text": "C++" }, { "code": null, "e": 26371, "s": 26363, "text": "Python3" }, { "code": null, "e": 26382, "s": 26371, "text": "Javascript" }, { "code": "/* C/C++ program to print groups of shifted strings together. */#include <bits/stdc++.h>using namespace std;const int ALPHA = 26; // Total lowercase letter // Method to a difference string for a given string.// If string is \"adf\" then difference string will be// \"cb\" (first difference 3 then difference 2)string getDiffString(string str){ string shift = \"\"; for (int i = 1; i < str.length(); i++) { int dif = str[i] - str[i-1]; if (dif < 0) dif += ALPHA; // Representing the difference as char shift += (dif + 'a'); } // This string will be 1 less length than str return shift;} // Method for grouping shifted stringvoid groupShiftedString(string str[], int n){ // map for storing indices of string which are // in same group map< string, vector<int> > groupMap; for (int i = 0; i < n; i++) { string diffStr = getDiffString(str[i]); groupMap[diffStr].push_back(i); } // iterating through map to print group for (auto it=groupMap.begin(); it!=groupMap.end(); it++) { vector<int> v = it->second; for (int i = 0; i < v.size(); i++) cout << str[v[i]] << \" \"; cout << endl; }} // Driver method to test above methodsint main(){ string str[] = {\"acd\", \"dfg\", \"wyz\", \"yab\", \"mop\", \"bdfh\", \"a\", \"x\", \"moqs\" }; int n = sizeof(str)/sizeof(str[0]); groupShiftedString(str, n); return 0;}", "e": 27895, "s": 26382, "text": null }, { "code": "# Python3 program to print groups# of shifted strings together. # Total lowercase letterALPHA = 26 # Method to a difference string# for a given string. If string# is \"adf\" then difference string# will be \"cb\" (first difference# 3 then difference 2)def getDiffString(str): shift=\"\" for i in range(1, len(str)): dif = (ord(str[i]) - ord(str[i - 1])) if(dif < 0): dif += ALPHA # Representing the difference # as char shift += chr(dif + ord('a')) # This string will be 1 less # length than str return shift # Method for grouping# shifted stringdef groupShiftedString(str,n): # map for storing indices # of string which are # in same group groupMap = {} for i in range(n): diffStr = getDiffString(str[i]) if diffStr not in groupMap: groupMap[diffStr] = [i] else: groupMap[diffStr].append(i) # Iterating through map # to print group for it in groupMap: v = groupMap[it] for i in range(len(v)): print(str[v[i]], end = \" \") print() # Driver codestr = [\"acd\", \"dfg\", \"wyz\", \"yab\", \"mop\",\"bdfh\", \"a\", \"x\", \"moqs\"]n = len(str)groupShiftedString(str, n) # This code is contributed by avanitrachhadiya2155", "e": 29195, "s": 27895, "text": null }, { "code": "<script> /* Javascript program to print groups of shifted strings together. */let ALPHA = 26; // Method to a difference string for a given string.// If string is \"adf\" then difference string will be// \"cb\" (first difference 3 then difference 2)function getDiffString(str){ let shift = \"\"; for (let i = 1; i < str.length; i++) { let dif = str[i] - str[i-1]; if (dif < 0) dif += ALPHA; // Representing the difference as char shift += (dif + 'a'); } // This string will be 1 less length than str return shift;} // Method for grouping shifted stringfunction groupShiftedString(str, n){ // map for storing indices of string which are // in same group let groupMap = new Map(); for (let i = 0; i < n; i++) { let diffStr = getDiffString(str[i]); if(!groupMap.has(diffStr)) groupMap.set(diffStr,[]); groupMap.get(diffStr).push(i); } // iterating through map to print group for (let [key, value] of groupMap.entries()) { let v = value; for (let i = 0; i < v.length; i++) document.write(str[v[i]]+\" \"); document.write(\"<br>\") }} // Driver method to test above methodslet str=[\"acd\", \"dfg\", \"wyz\", \"yab\", \"mop\", \"bdfh\", \"a\", \"x\", \"moqs\"];let n = str.length;groupShiftedString(str, n); // This code is contributed by ab2127</script>", "e": 30598, "s": 29195, "text": null }, { "code": null, "e": 30608, "s": 30598, "text": "Output: " }, { "code": null, "e": 30642, "s": 30608, "text": "a x\nacd dfg wyz yab mop\nbdfh moqs" }, { "code": null, "e": 31066, "s": 30642, "text": "This article is contributed by Utkarsh Trivedi. 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": 31087, "s": 31066, "text": "avanitrachhadiya2155" }, { "code": null, "e": 31094, "s": 31087, "text": "ab2127" }, { "code": null, "e": 31099, "s": 31094, "text": "Hash" }, { "code": null, "e": 31107, "s": 31099, "text": "Strings" }, { "code": null, "e": 31112, "s": 31107, "text": "Hash" }, { "code": null, "e": 31120, "s": 31112, "text": "Strings" }, { "code": null, "e": 31218, "s": 31120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31252, "s": 31218, "text": "Most frequent element in an array" }, { "code": null, "e": 31291, "s": 31252, "text": "Counting frequencies of array elements" }, { "code": null, "e": 31325, "s": 31291, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 31340, "s": 31325, "text": "Double Hashing" }, { "code": null, "e": 31378, "s": 31340, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 31424, "s": 31378, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31449, "s": 31424, "text": "Reverse a string in Java" }, { "code": null, "e": 31483, "s": 31449, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 31543, "s": 31483, "text": "Write a program to print all permutations of a given string" } ]
Add Titles to a Graph in R Programming - title() Function - GeeksforGeeks
20 Jul, 2020 title() function in R Language is used to add main title and axis title to a graph. This function can also be used to modify the existing titles. Syntax:title(main = NULL, sub = NULL, xlab = NULL, ylab = NULL, ...) Parameters:main: Main title of the graphsub: Defines subtitles Returns: Plot after title addition Example 1: # R program to add title to a Graph # Specifying axis valuesx<-1:5; y<-x*x # Creating a plotplot(x, y, main = "", xlab = "", ylab = "", col.axis = "darkgreen") # Calling title() functiontitle(main = "Graph ", sub = "Geeksforgeeks article", xlab = "X axis", ylab = "Y axis", cex.main = 4, font.main = 3, col.main = "darkgreen", cex.sub = 2, font.sub = 3, col.sub = "darkgreen", col.lab ="black" ) Output: In above example main title and sub titles are added to the plot. The arguments that can be used to change the font size are as follows: cex.main: size for main title cex.lab: text size for axis title cex.sub: text size of the sub-title Example 2: barplot(c(1, 10) )title(main = "PLOT ", sub = "Geeksforgeeks article", xlab = "X axis", ylab = "Y axis", # Change the colors col.main="darkgreen", col.lab="black", col.sub="darkgreen", # Titles in italic and bold font.main = 4, font.lab = 4, font.sub = 3, # Change font size cex.main = 3, cex.lab = 1.7, cex.sub = 2 ) Output: R Graphics-Functions R-Graphs R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) Filter data by multiple conditions in R using Dplyr How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Printing Output of an R Program Remove rows with NA in one column of R DataFrame How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 24658, "s": 24630, "text": "\n20 Jul, 2020" }, { "code": null, "e": 24804, "s": 24658, "text": "title() function in R Language is used to add main title and axis title to a graph. This function can also be used to modify the existing titles." }, { "code": null, "e": 24873, "s": 24804, "text": "Syntax:title(main = NULL, sub = NULL, xlab = NULL, ylab = NULL, ...)" }, { "code": null, "e": 24936, "s": 24873, "text": "Parameters:main: Main title of the graphsub: Defines subtitles" }, { "code": null, "e": 24971, "s": 24936, "text": "Returns: Plot after title addition" }, { "code": null, "e": 24982, "s": 24971, "text": "Example 1:" }, { "code": "# R program to add title to a Graph # Specifying axis valuesx<-1:5; y<-x*x # Creating a plotplot(x, y, main = \"\", xlab = \"\", ylab = \"\", col.axis = \"darkgreen\") # Calling title() functiontitle(main = \"Graph \", sub = \"Geeksforgeeks article\", xlab = \"X axis\", ylab = \"Y axis\", cex.main = 4, font.main = 3, col.main = \"darkgreen\", cex.sub = 2, font.sub = 3, col.sub = \"darkgreen\", col.lab =\"black\" )", "e": 25413, "s": 24982, "text": null }, { "code": null, "e": 25421, "s": 25413, "text": "Output:" }, { "code": null, "e": 25558, "s": 25421, "text": "In above example main title and sub titles are added to the plot. The arguments that can be used to change the font size are as follows:" }, { "code": null, "e": 25588, "s": 25558, "text": "cex.main: size for main title" }, { "code": null, "e": 25622, "s": 25588, "text": "cex.lab: text size for axis title" }, { "code": null, "e": 25658, "s": 25622, "text": "cex.sub: text size of the sub-title" }, { "code": null, "e": 25669, "s": 25658, "text": "Example 2:" }, { "code": "barplot(c(1, 10) )title(main = \"PLOT \", sub = \"Geeksforgeeks article\", xlab = \"X axis\", ylab = \"Y axis\", # Change the colors col.main=\"darkgreen\", col.lab=\"black\", col.sub=\"darkgreen\", # Titles in italic and bold font.main = 4, font.lab = 4, font.sub = 3, # Change font size cex.main = 3, cex.lab = 1.7, cex.sub = 2 )", "e": 26005, "s": 25669, "text": null }, { "code": null, "e": 26013, "s": 26005, "text": "Output:" }, { "code": null, "e": 26034, "s": 26013, "text": "R Graphics-Functions" }, { "code": null, "e": 26043, "s": 26034, "text": "R-Graphs" }, { "code": null, "e": 26054, "s": 26043, "text": "R Language" }, { "code": null, "e": 26152, "s": 26054, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26161, "s": 26152, "text": "Comments" }, { "code": null, "e": 26174, "s": 26161, "text": "Old Comments" }, { "code": null, "e": 26232, "s": 26174, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26264, "s": 26232, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26316, "s": 26264, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26360, "s": 26316, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26412, "s": 26360, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26444, "s": 26412, "text": "Printing Output of an R Program" }, { "code": null, "e": 26493, "s": 26444, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 26531, "s": 26493, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26566, "s": 26531, "text": "Group by function in R using Dplyr" } ]
Find minimum steps required to reach the end of a matrix in C++
Suppose we have a 2D matrix with positive integers. We have to find the minimum steps required to move from to the end of the matrix (rightmost bottom cell), If we are at cell (i, j), we can go to the cell (i, j+mat[i, j]) or (i+mat[i, j], j), We cannot cross the bounds. So if the matrix is like − The output will be 2. Path will be (0, 0) →(0, 2) → (2, 2) Here we will use the Dynamic programming approach to solve this. Suppose we are at cell (i, j), we want to reach (n-1, n-1) cell. We can use the recurrence relation like below − DP[i, j]=1+min ⁡(DP [i+arr [i , j] , j], DP[i , j+arr [ i , j]]) #include<iostream> #define N 3 using namespace std; int table[N][N]; bool temp_val[N][N]; int countSteps(int i, int j, int arr[][N]) { if (i == N - 1 and j == N - 1) return 0; if (i > N - 1 || j > N - 1) return INT_MAX; if (temp_val[i][j]) return table[i][j]; temp_val[i][j] = true; table[i][j] = 1 + min(countSteps(i + arr[i][j], j, arr), countSteps(i, j + arr[i][j], arr)); return table[i][j]; } int main() { int arr[N][N] = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } }; int ans = countSteps(0, 0, arr); if (ans >= INT_MAX) cout << -1; else cout <<"Number of steps: "<< ans; } Number of steps: 2
[ { "code": null, "e": 1361, "s": 1062, "text": "Suppose we have a 2D matrix with positive integers. We have to find the minimum steps required to move from to the end of the matrix (rightmost bottom cell), If we are at cell (i, j), we can go to the cell (i, j+mat[i, j]) or (i+mat[i, j], j), We cannot cross the bounds. So if the matrix is like −" }, { "code": null, "e": 1420, "s": 1361, "text": "The output will be 2. Path will be (0, 0) →(0, 2) → (2, 2)" }, { "code": null, "e": 1598, "s": 1420, "text": "Here we will use the Dynamic programming approach to solve this. Suppose we are at cell (i, j), we want to reach (n-1, n-1) cell. We can use the recurrence relation like below −" }, { "code": null, "e": 1663, "s": 1598, "text": "DP[i, j]=1+min ⁡(DP [i+arr [i , j] , j], DP[i , j+arr [ i , j]])" }, { "code": null, "e": 2299, "s": 1663, "text": "#include<iostream>\n#define N 3\nusing namespace std;\nint table[N][N];\nbool temp_val[N][N];\nint countSteps(int i, int j, int arr[][N]) {\n if (i == N - 1 and j == N - 1)\n return 0;\n if (i > N - 1 || j > N - 1)\n return INT_MAX;\n if (temp_val[i][j])\n return table[i][j];\n temp_val[i][j] = true;\n table[i][j] = 1 + min(countSteps(i + arr[i][j], j, arr), countSteps(i, j + arr[i][j], arr));\n return table[i][j];\n}\nint main() {\n int arr[N][N] = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } };\n int ans = countSteps(0, 0, arr);\n if (ans >= INT_MAX)\n cout << -1;\n else\n cout <<\"Number of steps: \"<< ans;\n}" }, { "code": null, "e": 2318, "s": 2299, "text": "Number of steps: 2" } ]
How can I set a MySQL database to use MyISAM by default?
To set the default storage engine, use the following syntax − set @@default_storage_engine = ’yourEngineType’; Now implement the above syntax to set the default engine to MyISAM. The query is as follows − mysql> set @@default_storage_engine = 'MyISAM'; Query OK, 0 rows affected (0.05 sec) Now you can check the default engine type with the help of SELECT statement. The query is as follows − mysql> select @@default_storage_engine; The following is the output displaying the engine as MyISAM − +--------------------------+ | @@default_storage_engine | +--------------------------+ | MyISAM | +--------------------------+ 1 row in set (0.00 sec) Now create a table and check for the default engine MyISAM. Let us create a table. The query to create a table is as follows − mysql> create table Followers -> ( -> FollowerId int, -> FollowerName varchar(20) -> ); Query OK, 0 rows affected (0.32 sec) Let us check the default engine type of the above table with the help of SHOW TABLE command. The query is as follows − mysql> SHOW TABLE STATUS WHERE Name = 'Followers'\G Name: followers Engine: MyISAM Version: 10 Row_format: Dynamic Rows: 0 Avg_row_length: 0 Data_length: 0 Max_data_length: 281474976710655 Index_length: 1024 Data_free: 0 Auto_increment: 1 Create_time: 2019 - 02 - 12 00: 42: 27 Update_time: 2019 - 02 - 12 00: 42: 28 Check_time: NULL Collation: utf8_general_ci Checksum: NULL Create_options: Comment: 1 row in set(0.00 sec) In MySQL version 8.0.12 the default engine is InnoDB but we have changed it above to MyISAM only for a session. If you restart the MySQL then the storage engine will be in the default MySQL mode i.e. InnoDB. Let’s restart MySQL. The query is as follows − mysql> restart; Query OK, 0 rows affected (0.20 sec) Now check the default engine type once again. It would be InnoDB now − mysql> select @@default_storage_engine; No connection. Trying to reconnect... Connection id: 8 Current database: sample +--------------------------+ | @@default_storage_engine | +--------------------------+ | InnoDB | +--------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1124, "s": 1062, "text": "To set the default storage engine, use the following syntax −" }, { "code": null, "e": 1173, "s": 1124, "text": "set @@default_storage_engine = ’yourEngineType’;" }, { "code": null, "e": 1267, "s": 1173, "text": "Now implement the above syntax to set the default engine to MyISAM. The query is as follows −" }, { "code": null, "e": 1352, "s": 1267, "text": "mysql> set @@default_storage_engine = 'MyISAM';\nQuery OK, 0 rows affected (0.05 sec)" }, { "code": null, "e": 1455, "s": 1352, "text": "Now you can check the default engine type with the help of SELECT statement. The query is as follows −" }, { "code": null, "e": 1495, "s": 1455, "text": "mysql> select @@default_storage_engine;" }, { "code": null, "e": 1557, "s": 1495, "text": "The following is the output displaying the engine as MyISAM −" }, { "code": null, "e": 1726, "s": 1557, "text": "+--------------------------+\n| @@default_storage_engine |\n+--------------------------+\n| MyISAM |\n+--------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1786, "s": 1726, "text": "Now create a table and check for the default engine MyISAM." }, { "code": null, "e": 1853, "s": 1786, "text": "Let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1990, "s": 1853, "text": "mysql> create table Followers\n -> (\n -> FollowerId int,\n -> FollowerName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.32 sec)" }, { "code": null, "e": 2109, "s": 1990, "text": "Let us check the default engine type of the above table with the help of SHOW TABLE command. The query is as follows −" }, { "code": null, "e": 2161, "s": 2109, "text": "mysql> SHOW TABLE STATUS WHERE Name = 'Followers'\\G" }, { "code": null, "e": 2533, "s": 2161, "text": "Name: followers\nEngine: MyISAM\nVersion: 10\nRow_format: Dynamic\nRows: 0\nAvg_row_length: 0\nData_length: 0\nMax_data_length: 281474976710655\nIndex_length: 1024\nData_free: 0\nAuto_increment: 1\nCreate_time: 2019 - 02 - 12 00: 42: 27\nUpdate_time: 2019 - 02 - 12 00: 42: 28\nCheck_time: NULL\nCollation: utf8_general_ci\nChecksum: NULL\nCreate_options:\nComment:\n1 row in set(0.00 sec)" }, { "code": null, "e": 2788, "s": 2533, "text": "In MySQL version 8.0.12 the default engine is InnoDB but we have changed it above to MyISAM only for a session. If you restart the MySQL then the storage engine will be in the default MySQL mode i.e. InnoDB. Let’s restart MySQL. The query is as follows −" }, { "code": null, "e": 2841, "s": 2788, "text": "mysql> restart;\nQuery OK, 0 rows affected (0.20 sec)" }, { "code": null, "e": 2912, "s": 2841, "text": "Now check the default engine type once again. It would be InnoDB now −" }, { "code": null, "e": 3201, "s": 2912, "text": "mysql> select @@default_storage_engine;\nNo connection. Trying to reconnect...\nConnection id: 8\nCurrent database: sample\n+--------------------------+\n| @@default_storage_engine |\n+--------------------------+\n| InnoDB |\n+--------------------------+\n1 row in set (0.00 sec)" } ]
Palindrome in both Decimal and Binary | Practice | GeeksforGeeks
Given a number N. check whether a given number N is palindrome or not in it's both formates (Decimal and Binary ). Example 1: Input: N = 7 Output: "Yes" Explanation: 7 is palindrome in it's decimal and also in it's binary (111).So answer is "Yes". Example 2: Input: N = 12 Output: "No" Explanation: 12 is not palindrome in it's decimal and also in it's binary (1100).So answer is "No". Your Task: You don't need to read input or print anything. Complete the function isDeciBinPalin() which takes N as input parameter and returns "Yes" if N is a palindrome in its both formates else returns "No". Expected Time Complexity: O(logN) Expected Auxiliary Space: O(1) Constraints: 1<= N <=107 0 mail2rajab012 months ago // Simple Java Solution class Solution { static boolean isPalindrome(String n){ String tmp=n; String r=""; for(int i=n.length()-1;i>=0;i--){ r +=n.charAt(i); } if(r.equals(n)){ return true; } return false; } static String isDeciBinPalin(long N){ // code here String tmp=Long.toBinaryString(N); if(isPalindrome(Long.toString(N)) && isPalindrome(tmp)){ return "Yes"; } return "No"; }} 0 rdm1233 months ago def isDeciBinPalin (self, N): k=str(N)[::-1] m=bin(N) m=m[2:] if(str(N)==k and m==m[::-1]): return "Yes" return "No" 0 Kartik Tyagi11 months ago Kartik Tyagi python sol:Execution Time:0.03 def isDeciBinPalin (self, N): num_str = str(N) binn = bin(N) binn = binn.replace("0b","") if ((num_str[::-1] == num_str) and (binn[::-1] == binn)): return "Yes" else: return "No" 0 NITIN SRIVASTAV1 year ago NITIN SRIVASTAV String str=String.valueOf(N); String check=""; for(int i=str.length()-1;i>=0;i--){ check+=str.charAt(i); } String s=Long.toBinaryString(N); String t=""; for(int i=s.length()-1;i>=0;i--){ t+=s.charAt(i); } if(check.compareToIgnoreCase(str) == 0 && t.compareToIgnoreCase(s)==0) return "Yes";return "No"; 0 SACHIN KUMAR1 year ago SACHIN KUMAR class Solution { public: string isDeciBinPalin(unsigned int N){ vector<int>v; while(N>0) { v.push_back(N%2); N/=2; } int i=0,j=v.size()-1; while(i<j) {="" if(v[i]!="v[j])" {="" return="" "no";="" }="" i++,j--;="" }="" return="" "yes";="" }="" };=""> 0 This comment was deleted. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 354, "s": 226, "text": "Given a number N. check whether a given number N is palindrome or not in it's both formates (Decimal and Binary ).\n\nExample 1:" }, { "code": null, "e": 479, "s": 354, "text": "Input: N = 7\nOutput: \"Yes\" \nExplanation: 7 is palindrome in it's decimal \nand also in it's binary (111).So answer is \"Yes\".\n" }, { "code": null, "e": 490, "s": 479, "text": "Example 2:" }, { "code": null, "e": 620, "s": 490, "text": "Input: N = 12\nOutput: \"No\"\nExplanation: 12 is not palindrome in it's decimal\nand also in it's binary (1100).So answer is \"No\". \n\n" }, { "code": null, "e": 925, "s": 620, "text": "\nYour Task: \nYou don't need to read input or print anything. Complete the function isDeciBinPalin() which takes N as input parameter and returns \"Yes\" if N is a palindrome in its both formates else returns \"No\".\n\nExpected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1<= N <=107" }, { "code": null, "e": 927, "s": 925, "text": "0" }, { "code": null, "e": 952, "s": 927, "text": "mail2rajab012 months ago" }, { "code": null, "e": 976, "s": 952, "text": "// Simple Java Solution" }, { "code": null, "e": 1454, "s": 978, "text": "class Solution { static boolean isPalindrome(String n){ String tmp=n; String r=\"\"; for(int i=n.length()-1;i>=0;i--){ r +=n.charAt(i); } if(r.equals(n)){ return true; } return false; } static String isDeciBinPalin(long N){ // code here String tmp=Long.toBinaryString(N); if(isPalindrome(Long.toString(N)) && isPalindrome(tmp)){ return \"Yes\"; } return \"No\"; }}" }, { "code": null, "e": 1456, "s": 1454, "text": "0" }, { "code": null, "e": 1475, "s": 1456, "text": "rdm1233 months ago" }, { "code": null, "e": 1632, "s": 1475, "text": "def isDeciBinPalin (self, N): k=str(N)[::-1] m=bin(N) m=m[2:] if(str(N)==k and m==m[::-1]): return \"Yes\" return \"No\"" }, { "code": null, "e": 1634, "s": 1632, "text": "0" }, { "code": null, "e": 1660, "s": 1634, "text": "Kartik Tyagi11 months ago" }, { "code": null, "e": 1673, "s": 1660, "text": "Kartik Tyagi" }, { "code": null, "e": 1943, "s": 1673, "text": "python sol:Execution Time:0.03 def isDeciBinPalin (self, N): num_str = str(N) binn = bin(N) binn = binn.replace(\"0b\",\"\") if ((num_str[::-1] == num_str) and (binn[::-1] == binn)): return \"Yes\" else: return \"No\"" }, { "code": null, "e": 1945, "s": 1943, "text": "0" }, { "code": null, "e": 1971, "s": 1945, "text": "NITIN SRIVASTAV1 year ago" }, { "code": null, "e": 1987, "s": 1971, "text": "NITIN SRIVASTAV" }, { "code": null, "e": 2377, "s": 1987, "text": "String str=String.valueOf(N); String check=\"\"; for(int i=str.length()-1;i>=0;i--){ check+=str.charAt(i); } String s=Long.toBinaryString(N); String t=\"\"; for(int i=s.length()-1;i>=0;i--){ t+=s.charAt(i); } if(check.compareToIgnoreCase(str) == 0 && t.compareToIgnoreCase(s)==0) return \"Yes\";return \"No\";" }, { "code": null, "e": 2379, "s": 2377, "text": "0" }, { "code": null, "e": 2402, "s": 2379, "text": "SACHIN KUMAR1 year ago" }, { "code": null, "e": 2415, "s": 2402, "text": "SACHIN KUMAR" }, { "code": null, "e": 2736, "s": 2415, "text": "class Solution { public: string isDeciBinPalin(unsigned int N){ vector<int>v; while(N>0) { v.push_back(N%2); N/=2; } int i=0,j=v.size()-1; while(i<j) {=\"\" if(v[i]!=\"v[j])\" {=\"\" return=\"\" \"no\";=\"\" }=\"\" i++,j--;=\"\" }=\"\" return=\"\" \"yes\";=\"\" }=\"\" };=\"\">" }, { "code": null, "e": 2738, "s": 2736, "text": "0" }, { "code": null, "e": 2764, "s": 2738, "text": "This comment was deleted." }, { "code": null, "e": 2910, "s": 2764, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 2946, "s": 2910, "text": " Login to access your submissions. " }, { "code": null, "e": 2956, "s": 2946, "text": "\nProblem\n" }, { "code": null, "e": 2966, "s": 2956, "text": "\nContest\n" }, { "code": null, "e": 3029, "s": 2966, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3177, "s": 3029, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3385, "s": 3177, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3491, "s": 3385, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
DAX Filter - HASONEVALUE function
Returns TRUE when the context for columnName has been filtered down to one distinct value only. Otherwise, returns FALSE. HASONEVALUE (<columnName>) columnName The name of a column. It cannot be an expression. TRUE or FALSE. = HASONEVALUE (Sales[Product]) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2123, "s": 2001, "text": "Returns TRUE when the context for columnName has been filtered down to one distinct value only. Otherwise, returns FALSE." }, { "code": null, "e": 2152, "s": 2123, "text": "HASONEVALUE (<columnName>) \n" }, { "code": null, "e": 2163, "s": 2152, "text": "columnName" }, { "code": null, "e": 2213, "s": 2163, "text": "The name of a column. It cannot be an expression." }, { "code": null, "e": 2228, "s": 2213, "text": "TRUE or FALSE." }, { "code": null, "e": 2260, "s": 2228, "text": "= HASONEVALUE (Sales[Product]) " }, { "code": null, "e": 2295, "s": 2260, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2309, "s": 2295, "text": " Abhay Gadiya" }, { "code": null, "e": 2342, "s": 2309, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2356, "s": 2342, "text": " Randy Minder" }, { "code": null, "e": 2391, "s": 2356, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2405, "s": 2391, "text": " Randy Minder" }, { "code": null, "e": 2412, "s": 2405, "text": " Print" }, { "code": null, "e": 2423, "s": 2412, "text": " Add Notes" } ]
Reinforcement Learning in Python with Flappy Bird | by Anthony Li | Towards Data Science
In 2014 the sleeper hit Flappy Bird took the mobile gaming world by storm. It has since been implemented in PyGame but most interestingly it lends itself well to reinforcement learning. The agent (bird) can only perform 2 actions (flap or do nothing) and is only interested in 1 environmental variable (the upcoming pipes). The simplicity of this problem makes it perfect for implementing reinforcement learning in Python from scratch. This article gives a higher level overview of this project. The code and results can be found on GitHub here. Q-learning is a model-free reinforcement learning algorithm which is generally used to learn the best action for an agent to take given a particular state. When the agent takes an action in a particular state it receives a reward (or penalty), and the goal of the agent is to maximise its total reward such that when taking an action it must also take the potential future reward into account. For Flappy Bird, the agent is the bird whose possible actions are to do nothing or flap, and whose current state is defined by: The x distance to the upcoming pipes The y distance to the upcoming bottom pipe The current y velocity v of the bird The distance y1 between the top and bottom upcoming pipes The first time a new state is reached, a Q-value is initialised (0 is fine), and the agent will carry out the default action and receive a reward. If a state has been encountered before, the agent will perform the action with the highest Q-value (the action which has been rewarded the most). The Q-value is then updated and the value inserted into the respective cell in a state×action Q-table. The Q-value is updated according to several parameters: # Update q values in a 2d arrayQ[state, action] = Q[state, action] + alpha * (reward + gamma * np.max(Q[new_state, :]) — Q[state, action]) Alpha α is the step-size and determines to what extent the old information is forgotten in favour of new information. Gamma γ determines the importance of future rewards. e.g. γ=0 means the agent will only consider its current reward. Q[state, action] is the current Q-value. The reward function was defined to penalise -1000 for a death and 0 otherwise, such that the agent’s focus is the get as high a score as possible. This ensures that the reward function has sufficient impact after each episode, vs an implementation where rewarding +1 for a score increase means that penalisation has little to no effect. With α=0.7 and γ=0.95 the agent was initially trained for around 10,000 episodes without any exploration, and is almost able to reach a score of 1 million. The y-axis has been logged so that the rolling increase in score can be seen more clearly. Although agent performed well after the initial training, it took exponentially longer to improve any further. This is because it takes a very long time for the agent to reach a scenario where it dies and even then it can only learn from that death once. By introducting experience replay the agent can attempt the difficult scenario multiples until it overcomes it or appears to be stuck in a resume loop (set to 100 attempts here). Upon passing the difficult scenario, upon failure it restarts from the beginning to avoid the maximum score reached from continously increasing. There is an initial improvement in agent performance as it is able to learn from more difficult scenarios, but its performance quickly drops below its previous maximum. This is known as catastrophic forgetting, which typically leads to an oscillation in agent performance as it unlearns and relearns the optimal actions to take. By repeatedly learning from the same scenario failure, the agent is overfitting and has forgotten the previously generalisable Q-values. To overcome catastrophic forgetting, alpha decay is added as the agent is trained, helping it to retain the information it learnt early on whilst still learning from rarer scenarios. In addition, the number of attempts to be considered stuck in a loop is reduced to 50 and during experience replay a “replay buffer” with all the actions taken is created. The Q-table is then updated from this in a mini-batch fashion, sampling 5 of the attempts once experience replay is complete. This agent is almost able to reach a score of 10 million. Although a drop in performance is observed as training continues past episode 10,000, it is able to recover from this initial forgetting. Whilst futher time is not spent training this agent, it would be expected that the agent performance would oscillate as it unlearns and relearns the optimal actions to take. As alpha continues to decay this should eventually enable the agent to remain stable around its maximum score. We now try freshly trained agent, introducing the exploration rate epsilon ε that gives a chance to explore a random action until it decays from 0.1 to 0 after 10,000 episodes, and alpha decay which decays alpha from 0.7 to 0.1 after 20,000 episodes. Due to the alpha and epsilon decay, this agent learns slower than in the initial training, but is much more stable once it has reached its optimum performance just below 1 million. This maximum score is lower than we experienced without exploration, likely due to alpha decay improving stability at the cost of the agent learning much more slowly. From above we can see the final best performing agent was trained with experience replay and a replay buffer. Agent performance was validated over 25 runs. The agent performs well, consistently passing 100,000 and reaching a maximum score above 5 million. It is able to pass most situations but is unable to live forever when more difficult scenarios appear, meaning it sometimes dies quite early on. Stability: The coefficient of variation (standard deviation / mean) is 0.967. This is expected since in a random environment the agent can only be fully stable once it can overcome every scenario and never die. Average score: The average score is 2,001,434. This is a strong score for the agent to consistently be able to reach, surpassing any human play. Maximum score: The maximum score reached in 25 runs is 6,720,279. This is a high score close to the default maximum training value of 10 million, again surpassing any human play. Longer training times, the best performing agent was trained for a total of 15 hours and only reached 10,674 episodes Implement prioritized experience replay Train an agent which never dies in the Flappy Bird environment Tony Xu, Use reinforcement learning to train a flappy bird NEVER to die (2020), https://towardsdatascience.com/use-reinforcement-learning-to-train-a-flappy-bird-never-to-die-35b9625aaecc
[ { "code": null, "e": 608, "s": 172, "text": "In 2014 the sleeper hit Flappy Bird took the mobile gaming world by storm. It has since been implemented in PyGame but most interestingly it lends itself well to reinforcement learning. The agent (bird) can only perform 2 actions (flap or do nothing) and is only interested in 1 environmental variable (the upcoming pipes). The simplicity of this problem makes it perfect for implementing reinforcement learning in Python from scratch." }, { "code": null, "e": 718, "s": 608, "text": "This article gives a higher level overview of this project. The code and results can be found on GitHub here." }, { "code": null, "e": 1240, "s": 718, "text": "Q-learning is a model-free reinforcement learning algorithm which is generally used to learn the best action for an agent to take given a particular state. When the agent takes an action in a particular state it receives a reward (or penalty), and the goal of the agent is to maximise its total reward such that when taking an action it must also take the potential future reward into account. For Flappy Bird, the agent is the bird whose possible actions are to do nothing or flap, and whose current state is defined by:" }, { "code": null, "e": 1277, "s": 1240, "text": "The x distance to the upcoming pipes" }, { "code": null, "e": 1320, "s": 1277, "text": "The y distance to the upcoming bottom pipe" }, { "code": null, "e": 1357, "s": 1320, "text": "The current y velocity v of the bird" }, { "code": null, "e": 1415, "s": 1357, "text": "The distance y1 between the top and bottom upcoming pipes" }, { "code": null, "e": 1811, "s": 1415, "text": "The first time a new state is reached, a Q-value is initialised (0 is fine), and the agent will carry out the default action and receive a reward. If a state has been encountered before, the agent will perform the action with the highest Q-value (the action which has been rewarded the most). The Q-value is then updated and the value inserted into the respective cell in a state×action Q-table." }, { "code": null, "e": 1867, "s": 1811, "text": "The Q-value is updated according to several parameters:" }, { "code": null, "e": 2006, "s": 1867, "text": "# Update q values in a 2d arrayQ[state, action] = Q[state, action] + alpha * (reward + gamma * np.max(Q[new_state, :]) — Q[state, action])" }, { "code": null, "e": 2124, "s": 2006, "text": "Alpha α is the step-size and determines to what extent the old information is forgotten in favour of new information." }, { "code": null, "e": 2241, "s": 2124, "text": "Gamma γ determines the importance of future rewards. e.g. γ=0 means the agent will only consider its current reward." }, { "code": null, "e": 2282, "s": 2241, "text": "Q[state, action] is the current Q-value." }, { "code": null, "e": 2619, "s": 2282, "text": "The reward function was defined to penalise -1000 for a death and 0 otherwise, such that the agent’s focus is the get as high a score as possible. This ensures that the reward function has sufficient impact after each episode, vs an implementation where rewarding +1 for a score increase means that penalisation has little to no effect." }, { "code": null, "e": 2866, "s": 2619, "text": "With α=0.7 and γ=0.95 the agent was initially trained for around 10,000 episodes without any exploration, and is almost able to reach a score of 1 million. The y-axis has been logged so that the rolling increase in score can be seen more clearly." }, { "code": null, "e": 3445, "s": 2866, "text": "Although agent performed well after the initial training, it took exponentially longer to improve any further. This is because it takes a very long time for the agent to reach a scenario where it dies and even then it can only learn from that death once. By introducting experience replay the agent can attempt the difficult scenario multiples until it overcomes it or appears to be stuck in a resume loop (set to 100 attempts here). Upon passing the difficult scenario, upon failure it restarts from the beginning to avoid the maximum score reached from continously increasing." }, { "code": null, "e": 3614, "s": 3445, "text": "There is an initial improvement in agent performance as it is able to learn from more difficult scenarios, but its performance quickly drops below its previous maximum." }, { "code": null, "e": 3911, "s": 3614, "text": "This is known as catastrophic forgetting, which typically leads to an oscillation in agent performance as it unlearns and relearns the optimal actions to take. By repeatedly learning from the same scenario failure, the agent is overfitting and has forgotten the previously generalisable Q-values." }, { "code": null, "e": 4392, "s": 3911, "text": "To overcome catastrophic forgetting, alpha decay is added as the agent is trained, helping it to retain the information it learnt early on whilst still learning from rarer scenarios. In addition, the number of attempts to be considered stuck in a loop is reduced to 50 and during experience replay a “replay buffer” with all the actions taken is created. The Q-table is then updated from this in a mini-batch fashion, sampling 5 of the attempts once experience replay is complete." }, { "code": null, "e": 4873, "s": 4392, "text": "This agent is almost able to reach a score of 10 million. Although a drop in performance is observed as training continues past episode 10,000, it is able to recover from this initial forgetting. Whilst futher time is not spent training this agent, it would be expected that the agent performance would oscillate as it unlearns and relearns the optimal actions to take. As alpha continues to decay this should eventually enable the agent to remain stable around its maximum score." }, { "code": null, "e": 5124, "s": 4873, "text": "We now try freshly trained agent, introducing the exploration rate epsilon ε that gives a chance to explore a random action until it decays from 0.1 to 0 after 10,000 episodes, and alpha decay which decays alpha from 0.7 to 0.1 after 20,000 episodes." }, { "code": null, "e": 5472, "s": 5124, "text": "Due to the alpha and epsilon decay, this agent learns slower than in the initial training, but is much more stable once it has reached its optimum performance just below 1 million. This maximum score is lower than we experienced without exploration, likely due to alpha decay improving stability at the cost of the agent learning much more slowly." }, { "code": null, "e": 5628, "s": 5472, "text": "From above we can see the final best performing agent was trained with experience replay and a replay buffer. Agent performance was validated over 25 runs." }, { "code": null, "e": 5873, "s": 5628, "text": "The agent performs well, consistently passing 100,000 and reaching a maximum score above 5 million. It is able to pass most situations but is unable to live forever when more difficult scenarios appear, meaning it sometimes dies quite early on." }, { "code": null, "e": 6084, "s": 5873, "text": "Stability: The coefficient of variation (standard deviation / mean) is 0.967. This is expected since in a random environment the agent can only be fully stable once it can overcome every scenario and never die." }, { "code": null, "e": 6229, "s": 6084, "text": "Average score: The average score is 2,001,434. This is a strong score for the agent to consistently be able to reach, surpassing any human play." }, { "code": null, "e": 6408, "s": 6229, "text": "Maximum score: The maximum score reached in 25 runs is 6,720,279. This is a high score close to the default maximum training value of 10 million, again surpassing any human play." }, { "code": null, "e": 6526, "s": 6408, "text": "Longer training times, the best performing agent was trained for a total of 15 hours and only reached 10,674 episodes" }, { "code": null, "e": 6566, "s": 6526, "text": "Implement prioritized experience replay" }, { "code": null, "e": 6629, "s": 6566, "text": "Train an agent which never dies in the Flappy Bird environment" } ]
How to use Null Coalescing Operator (??) in C#?
The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible. If the value of the first operand is null, then the operator returns the value of the second operand, otherwise, it returns the value of the first operand. The following is an example − Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { double? num1 = null; double? num2 = 6.32123; double num3; num3 = num1 ?? 9.77; Console.WriteLine(" Value of num3: {0}", num3); num3 = num2 ?? 9.77; Console.WriteLine(" Value of num3: {0}", num3); Console.ReadLine(); } } } Value of num3: 9.77 Value of num3: 6.32123
[ { "code": null, "e": 1290, "s": 1062, "text": "The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible." }, { "code": null, "e": 1446, "s": 1290, "text": "If the value of the first operand is null, then the operator returns the value of the second operand, otherwise, it returns the value of the first operand." }, { "code": null, "e": 1476, "s": 1446, "text": "The following is an example −" }, { "code": null, "e": 1487, "s": 1476, "text": " Live Demo" }, { "code": null, "e": 1885, "s": 1487, "text": "using System;\n\nnamespace Demo {\n\n class Program {\n\n static void Main(string[] args) {\n double? num1 = null;\n double? num2 = 6.32123;\n double num3;\n\n num3 = num1 ?? 9.77;\n Console.WriteLine(\" Value of num3: {0}\", num3);\n\n num3 = num2 ?? 9.77;\n Console.WriteLine(\" Value of num3: {0}\", num3);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 1928, "s": 1885, "text": "Value of num3: 9.77\nValue of num3: 6.32123" } ]
Python - Delete rows/columns from DataFrame using Pandas.drop()
Pandas is one of the most popular python library for data analysis and data wrangling. In this article we will see how we can create a pandas dataframe and then delete some selective rows ort columns from this data frame. In the below example we have the iris.csv file which is read into a data frame. We first have a look at the existing data frame and then apply the drop function to the index column by supplying the value we want to drop. As we can see at the bottom of the result set the number of rows has been reduced by 3. import pandas as pd # making data frame from csv file data = pd.read_csv("E:\\iris1.csv",index_col ="Id") print(data) # dropping passed values data.drop([6,9,10],inplace=True) # display print(data) Running the above code gives us the following result − SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species Id 1 5.1 3.5 1.4 0.2 Iris-setosa 2 4.9 3.0 1.4 0.2 Iris-setosa 3 4.7 3.2 1.3 0.2 Iris-setosa . .. ... .... ............ [150 rows x 5 columns] After Dropping SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species Id 1 5.1 3.5 1.4 0.2 Iris-setosa 2 4.9 3.0 1.4 0.2 Iris-setosa 3 4.7 3.2 1.3 0.2 Iris-setosa 149 6.2 3.4 5.4 2.3 Iris-virginica 150 5.9 3.0 5.1 1.8 Iris-virginica ...................... [147 rows x 5 columns] For dropping the columns form a pandas data frame, we use the axis parameter. Its value is set to one in the drop function and we supply the column names to be dropped. As you can see the number of columns in the result set gets reduced from 5 to 3. import pandas as pd # making data frame from csv file data = pd.read_csv("E:\\iris1.csv",index_col ="Id") print(data) # dropping passed values data.drop(['SepalWidthCm','PetalLengthCm'],axis=1,inplace=True) print("After Dropping") # display print(data) Running the above code gives us the following result − SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species Id 1 5.1 3.5 1.4 0.2 Iris-setosa 2 4.9 3.0 1.4 0.2 Iris-setosa 3 4.7 3.2 1.3 0.2 Iris-setosa . . .... .... ..... ....... [150 rows x 5 columns] After Dropping SepalLengthCm PetalWidthCm Species Id 1 5.1 0.2 Iris-setosa 2 4.9 0.2 Iris-setosa 3 4.7 0.2 Iris-setosa ......... [150 rows x 3 columns]
[ { "code": null, "e": 1284, "s": 1062, "text": "Pandas is one of the most popular python library for data analysis and data wrangling. In this article we will see how we can create a pandas dataframe and then delete some selective rows ort columns from this data frame." }, { "code": null, "e": 1593, "s": 1284, "text": "In the below example we have the iris.csv file which is read into a data frame. We first have a look at the existing data frame and then apply the drop function to the index column by supplying the value we want to drop. As we can see at the bottom of the result set the number of rows has been reduced by 3." }, { "code": null, "e": 1791, "s": 1593, "text": "import pandas as pd\n# making data frame from csv file\ndata = pd.read_csv(\"E:\\\\iris1.csv\",index_col =\"Id\")\nprint(data)\n# dropping passed values\ndata.drop([6,9,10],inplace=True)\n# display\nprint(data)" }, { "code": null, "e": 1846, "s": 1791, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2766, "s": 1846, "text": " SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species\nId\n1 5.1 3.5 1.4 0.2 Iris-setosa\n2 4.9 3.0 1.4 0.2 Iris-setosa\n3 4.7 3.2 1.3 0.2 Iris-setosa\n. .. ... .... ............\n[150 rows x 5 columns]\n\nAfter Dropping\n SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species\nId\n1 5.1 3.5 1.4 0.2 Iris-setosa\n2 4.9 3.0 1.4 0.2 Iris-setosa\n3 4.7 3.2 1.3 0.2 Iris-setosa\n149 6.2 3.4 5.4 2.3 Iris-virginica\n150 5.9 3.0 5.1 1.8 Iris-virginica\n......................\n[147 rows x 5 columns]" }, { "code": null, "e": 3016, "s": 2766, "text": "For dropping the columns form a pandas data frame, we use the axis parameter. Its value is set to one in the drop function and we supply the column names to be dropped. As you can see the number of columns in the result set gets reduced from 5 to 3." }, { "code": null, "e": 3269, "s": 3016, "text": "import pandas as pd\n# making data frame from csv file\ndata = pd.read_csv(\"E:\\\\iris1.csv\",index_col =\"Id\")\nprint(data)\n# dropping passed values\ndata.drop(['SepalWidthCm','PetalLengthCm'],axis=1,inplace=True)\nprint(\"After Dropping\")\n# display\nprint(data)" }, { "code": null, "e": 3324, "s": 3269, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3950, "s": 3324, "text": " SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species\nId\n1 5.1 3.5 1.4 0.2 Iris-setosa\n2 4.9 3.0 1.4 0.2 Iris-setosa\n3 4.7 3.2 1.3 0.2 Iris-setosa\n. . .... .... ..... .......\n[150 rows x 5 columns]\nAfter Dropping\n SepalLengthCm PetalWidthCm Species\nId\n1 5.1 0.2 Iris-setosa\n2 4.9 0.2 Iris-setosa\n3 4.7 0.2 Iris-setosa\n.........\n[150 rows x 3 columns]" } ]
Deploy Machine Learning App built using Streamlit and PyCaret on Google Kubernetes Engine | by Moez Ali | Towards Data Science
In our last post on deploying a machine learning pipeline in the cloud, we demonstrated how to develop a machine learning pipeline in PyCaret and deploy a trained model on Heroku PaaS as a web application built using a Streamlit open-source framework. If you haven’t heard about PyCaret before, you can read this announcement to learn more. In this tutorial, we will use the same machine learning pipeline and Streamlit app and demonstrate how to containerize and deploy them onto Google Kubernetes Engine. By the end of this tutorial, you will be able to build and host a fully functional containerized web app on Google Kubernetes Engine. This web app can be used to generate online predictions (one-by-one) and predictions by batch (by uploading a csv file) using a trained machine learning model. The final app looks like this: What is a Container, what is Docker, what is Kubernetes, and what is Google Kubernetes Engine? Build a Docker image and upload it onto Google Container Registry (GCR). Create a cluster on GCP and deploy a machine learning app as a web service. See a web app in action that uses a trained machine learning pipeline to predict new data points in real time. In the past, we have covered containerization using docker and deployment on cloud platforms like Azure, GCP and AWS. If you are interested in learning more about those, you can read the following tutorials: Build and deploy machine learning web app using PyCaret and Streamlit Deploy Machine Learning Pipeline on AWS Fargate Deploy Machine Learning Pipeline on Google Kubernetes Engine Deploy Machine Learning Pipeline on AWS Web Service Build and deploy your first machine learning web app on Heroku PaaS PyCaret is an open source, low-code machine learning library in Python that is used to train and deploy machine learning pipelines and models into production. PyCaret can be installed easily using pip. pip install pycaret Streamlit is an open-source Python library that makes it easy to build beautiful custom web-apps for machine learning and data science. Streamlit can be installed easily using pip. pip install streamlit Google Cloud Platform (GCP), offered by Google, is a suite of cloud computing services that runs on the same infrastructure that Google uses internally for its end-user products, such as Google Search, Gmail and YouTube. If you do not have an account with GCP, you can sign-up here. If you are signing up for the first time you will get free credits for 1 year. Before we get into Kubernetes, let’s understand what a container is and why we would need one? Have you ever had the problem where your code works fine on your computer but when a friend tries to run the exact same code, it doesn’t work? If your friend is repeating the exact same steps, he or she should get the same results, right? The one-word answer to this is the environment. Your friend’s environment is different than yours. What does an environment include? → A programing language such as Python and all the libraries and dependencies with the exact versions used when the application was built and tested. If we can create an environment that we can transfer to other machines (for example: your friend’s computer or a cloud service provider like Google Cloud Platform), we can reproduce the results anywhere. Hence, a container is a type of software that packages up an application and all its dependencies so the application runs reliably from one computing environment to another. What’s Docker then? Docker is a company that provides software (also called Docker) that allows users to build, run and manage containers. While Docker’s container are the most common, there are other less famous alternatives such as LXD and LXC that also provide container solutions. Now that you understand containers and docker specifically, let’s understand what Kubernetes is all about. Kubernetes is a powerful open-source system developed by Google back in 2014, for managing containerized applications. In simple words, Kubernetes is a system for running and coordinating containerized applications across a cluster of machines. It is a platform designed to completely manage the life cycle of containerized applications. ✔️ Load Balancing: Automatically distributes the load between containers. ✔️ Scaling: Automatically scale up or down by adding or removing containers when demand changes such as peak hours, weekends and holidays. ✔️ Storage: Keeps storage consistent with multiple instances of an application. ✔️ Self-healing Automatically restarts containers that fail and kills containers that don’t respond to your user-defined health check. ✔️ Automated Rollouts you can automate Kubernetes to create new containers for your deployment, remove existing containers and adopt all of their resources to the new container. Imagine a scenario where you have to run multiple docker containers on multiple machines to support an enterprise level ML application with varied workloads during day and night. As simple as it may sound, it is a lot of work to do manually. You need to start the right containers at the right time, figure out how they can talk to each other, handle storage considerations, and deal with failed containers or hardware. This is the problem Kubernetes is solving by allowing large numbers of containers to work together in harmony, reducing the operational burden. Google Kubernetes Engine is an implementation of Google’s open source Kubernetes on Google Cloud Platform. Simple! Other popular alternatives to GKE are Amazon ECS and Microsoft Azure Kubernetes Service. A Container is a type of software that packages up an application and all its dependencies so the application runs reliably from one computing environment to another. Docker is a software used for building and managing containers. Kubernetes is an open-source system for managing containerized applications in a clustered environment. Google Kubernetes Engine is an implementation of the open source Kubernetes framework on Google Cloud Platform. In this tutorial, we will use Google Kubernetes Engine. In order to follow along, you must have a Google Cloud Platform account. Click here to sign-up for free. An insurance company wants to improve its cash flow forecasting by better predicting patient charges using demographic and basic patient health risk metrics at the time of hospitalization. (data source) To build a web application that supports online (one-by-one) as well as batch prediction using trained machine learning model and pipeline. Train, validate and develop a machine learning pipeline using PyCaret. Build a front-end web application with two functionalities: (i) online prediction and (ii) batch prediction. Create a Dockerfile Deploy the web app on Google Kubernetes Engine. Once deployed, it will become publicly available and can be accessed via Web URL. Training and model validation are performed in an Integrated Development Environment (IDE) or Notebook either on your local machine or on cloud. If you haven’t used PyCaret before, click here to learn more about PyCaret or see Getting Started Tutorials on our website. In this tutorial, we have performed two experiments. The first experiment is performed with default preprocessing settings in PyCaret. The second experiment has some additional preprocessing tasks such as scaling and normalization, automatic feature engineering and binning continuous data into intervals. See the setup code for the second experiment: # Experiment No. 2from pycaret.regression import *r2 = setup(data, target = 'charges', session_id = 123, normalize = True, polynomial_features = True, trigonometry_features = True, feature_interaction=True, bin_numeric_features= ['age', 'bmi']) The magic happens with only a few lines of code. Notice that in Experiment 2 the transformed dataset has 62 features for training derived from only 6 features in the original dataset. All of the new features are the result of transformations and automatic feature engineering in PyCaret. Sample code for model training in PyCaret: # Model Training and Validation lr = create_model('lr') Notice the impact of transformations and automatic feature engineering. The R2 has increased by 10% with very little effort. We can compare the residual plot of linear regression model for both experiments and observe the impact of transformations and feature engineering on the heteroskedasticity of model. # plot residuals of trained modelplot_model(lr, plot = 'residuals') Machine learning is an iterative process. The number of iterations and techniques used within are dependent on how critical the task is and what the impact will be if predictions are wrong. The severity and impact of a machine learning model to predict a patient outcome in real-time in the ICU of a hospital is far more than a model built to predict customer churn. In this tutorial, we have performed only two iterations and the linear regression model from the second experiment will be used for deployment. At this stage, however, the model is still only an object within a Notebook / IDE. To save it as a file that can be transferred to and consumed by other applications, execute the following code: # save transformation pipeline and model save_model(lr, model_name = 'deployment_28042020') When you save a model in PyCaret, the entire transformation pipeline based on the configuration defined in the setup() function is created. All inter-dependencies are orchestrated automatically. See the pipeline and model stored in the ‘deployment_28042020’ variable: We have finished training and model selection. The final machine learning pipeline and linear regression model is now saved as a pickle file (deployment_28042020.pkl) that will be used in a web application to generate predictions on new datapoints. Now that our machine learning pipeline and model are ready to start building a front-end web application that can generate predictions on new datapoints. This application will support ‘Online’ as well as ‘Batch’ predictions through a csv file upload. Let’s breakdown the application code into three main parts: This section imports libraries, loads the trained model and creates a basic layout with a logo on top, a jpg image and a dropdown menu on the sidebar to toggle between ‘Online’ and ‘Batch’ prediction. This section deals with the initial app function, Online one-by-one predictions. We are using streamlit widgets such as number input, text input, drop down menu and checkbox to collect the datapoints used to train the model such as Age, Sex, BMI, Children, Smoker, Region. Predictions by batch is the second layer of the app’s functionality. The file_uploader widget in streamlit is used to upload a csv file and then called the native predict_model() function from PyCaret to generate predictions that are displayed using streamlit’s write() function. If you remember from Task 1 above we finalized a linear regression model that was trained on 62 features that were extracted from the 6 original features. The front-end of web application has an input form that collects only the six features i.e. age, sex, bmi, children, smoker, region. How do we transform these 6 features of a new data points into the 62 used to train the model? We do not need to worry about this part as PyCaret automatically handles this by orchestrating the transformation pipeline. When you call the predict function on a model trained using PyCaret, all transformations are applied automatically (in sequence) before generating predictions from the trained model. Testing AppOne final step before we publish the application on Heroku is to test the web app locally. Open Anaconda Prompt and navigate to your project folder and execute the following code: streamlit run app.py Now that we have a fully functional web application, we can start the process of containerizing and deploying the app on Google Kubernetes Engine. To containerize our application for deployment we need a docker image that becomes a container at runtime. A docker image is created using a Dockerfile. A Dockerfile is just a file with a set of instructions. The Dockerfile for this project looks like this: The last part of this Dockerfile (starting at line 23) is Streamlit specific and not needed generally. Dockerfile is case-sensitive and must be in the project folder with the other project files. If you would like to follow along you will have to fork this repository from GitHub. Follow through these simple 10 steps to deploy app on GKE Cluster. Sign-in to your GCP console and go to Manage Resources Click on Create New Project Click the Activate Cloud Shell button at the top right of the console window to open the Cloud Shell. Execute the following code in Cloud Shell to clone the GitHub repository used in this tutorial. git clone https://github.com/pycaret/pycaret-streamlit-google.git Execute the following code to set the PROJECT_ID environment variable. export PROJECT_ID=pycaret-streamlit-gcp pycaret-streamlit-gcp is the name of the project we chose in step 1 above. Build the docker image of the application and tag it for uploading by executing the following code: docker build -t gcr.io/${PROJECT_ID}/insurance-streamlit:v1 . You can check the available images by running the following code: docker images Authenticate to Container Registry (you need to run this only once): Authenticate to Container Registry (you need to run this only once): gcloud auth configure-docker 2. Execute the following code to upload the docker image to Google Container Registry: docker push gcr.io/${PROJECT_ID}/insurance-streamlit:v1 Now that the container is uploaded, you need a cluster to run the container. A cluster consists of a pool of Compute Engine VM instances, running Kubernetes. Set your project ID and Compute Engine zone options for the gcloud tool: Set your project ID and Compute Engine zone options for the gcloud tool: gcloud config set project $PROJECT_ID gcloud config set compute/zone us-central1 2. Create a cluster by executing the following code: gcloud container clusters create streamlit-cluster --num-nodes=2 To deploy and manage applications on a GKE cluster, you must communicate with the Kubernetes cluster management system. Execute the following command to deploy the application: kubectl create deployment insurance-streamlit --image=gcr.io/${PROJECT_ID}/insurance-streamlit:v1 By default, the containers you run on GKE are not accessible from the internet because they do not have external IP addresses. Execute the following code to expose the application to the internet: kubectl expose deployment insurance-streamlit --type=LoadBalancer --port 80 --target-port 8501 Execute the following code to get the status of the service. EXTERNAL-IP is the web address you can use in browser to view the published app. kubectl get service Note: By the time this story is published, the app will be removed from the public address to restrict resource consumption. Link to GitHub Repository for this tutorial Link to GitHub Repository for Microsoft Azure Deployment Link to GitHub Repository for Heroku Deployment We have received overwhelming support and feedback from the community. We are actively working on improving PyCaret and preparing for our next release. PyCaret 2.0.0 will be bigger and better. If you would like to share your feedback and help us improve further, you may fill this form on the website or leave a comment on our GitHub or LinkedIn page. Follow our LinkedIn and subscribe to our YouTube channel to learn more about PyCaret. As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python. ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining PyCaret getting started tutorials in Notebook: ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining PyCaret is an open source project. Everybody is welcome to contribute. If you would like to contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch. Please give us ⭐️ on our GitHub repo if you like PyCaret.
[ { "code": null, "e": 513, "s": 172, "text": "In our last post on deploying a machine learning pipeline in the cloud, we demonstrated how to develop a machine learning pipeline in PyCaret and deploy a trained model on Heroku PaaS as a web application built using a Streamlit open-source framework. If you haven’t heard about PyCaret before, you can read this announcement to learn more." }, { "code": null, "e": 679, "s": 513, "text": "In this tutorial, we will use the same machine learning pipeline and Streamlit app and demonstrate how to containerize and deploy them onto Google Kubernetes Engine." }, { "code": null, "e": 1004, "s": 679, "text": "By the end of this tutorial, you will be able to build and host a fully functional containerized web app on Google Kubernetes Engine. This web app can be used to generate online predictions (one-by-one) and predictions by batch (by uploading a csv file) using a trained machine learning model. The final app looks like this:" }, { "code": null, "e": 1099, "s": 1004, "text": "What is a Container, what is Docker, what is Kubernetes, and what is Google Kubernetes Engine?" }, { "code": null, "e": 1172, "s": 1099, "text": "Build a Docker image and upload it onto Google Container Registry (GCR)." }, { "code": null, "e": 1248, "s": 1172, "text": "Create a cluster on GCP and deploy a machine learning app as a web service." }, { "code": null, "e": 1359, "s": 1248, "text": "See a web app in action that uses a trained machine learning pipeline to predict new data points in real time." }, { "code": null, "e": 1567, "s": 1359, "text": "In the past, we have covered containerization using docker and deployment on cloud platforms like Azure, GCP and AWS. If you are interested in learning more about those, you can read the following tutorials:" }, { "code": null, "e": 1637, "s": 1567, "text": "Build and deploy machine learning web app using PyCaret and Streamlit" }, { "code": null, "e": 1685, "s": 1637, "text": "Deploy Machine Learning Pipeline on AWS Fargate" }, { "code": null, "e": 1746, "s": 1685, "text": "Deploy Machine Learning Pipeline on Google Kubernetes Engine" }, { "code": null, "e": 1798, "s": 1746, "text": "Deploy Machine Learning Pipeline on AWS Web Service" }, { "code": null, "e": 1866, "s": 1798, "text": "Build and deploy your first machine learning web app on Heroku PaaS" }, { "code": null, "e": 2068, "s": 1866, "text": "PyCaret is an open source, low-code machine learning library in Python that is used to train and deploy machine learning pipelines and models into production. PyCaret can be installed easily using pip." }, { "code": null, "e": 2088, "s": 2068, "text": "pip install pycaret" }, { "code": null, "e": 2269, "s": 2088, "text": "Streamlit is an open-source Python library that makes it easy to build beautiful custom web-apps for machine learning and data science. Streamlit can be installed easily using pip." }, { "code": null, "e": 2291, "s": 2269, "text": "pip install streamlit" }, { "code": null, "e": 2653, "s": 2291, "text": "Google Cloud Platform (GCP), offered by Google, is a suite of cloud computing services that runs on the same infrastructure that Google uses internally for its end-user products, such as Google Search, Gmail and YouTube. If you do not have an account with GCP, you can sign-up here. If you are signing up for the first time you will get free credits for 1 year." }, { "code": null, "e": 2748, "s": 2653, "text": "Before we get into Kubernetes, let’s understand what a container is and why we would need one?" }, { "code": null, "e": 3086, "s": 2748, "text": "Have you ever had the problem where your code works fine on your computer but when a friend tries to run the exact same code, it doesn’t work? If your friend is repeating the exact same steps, he or she should get the same results, right? The one-word answer to this is the environment. Your friend’s environment is different than yours." }, { "code": null, "e": 3270, "s": 3086, "text": "What does an environment include? → A programing language such as Python and all the libraries and dependencies with the exact versions used when the application was built and tested." }, { "code": null, "e": 3648, "s": 3270, "text": "If we can create an environment that we can transfer to other machines (for example: your friend’s computer or a cloud service provider like Google Cloud Platform), we can reproduce the results anywhere. Hence, a container is a type of software that packages up an application and all its dependencies so the application runs reliably from one computing environment to another." }, { "code": null, "e": 3668, "s": 3648, "text": "What’s Docker then?" }, { "code": null, "e": 3933, "s": 3668, "text": "Docker is a company that provides software (also called Docker) that allows users to build, run and manage containers. While Docker’s container are the most common, there are other less famous alternatives such as LXD and LXC that also provide container solutions." }, { "code": null, "e": 4040, "s": 3933, "text": "Now that you understand containers and docker specifically, let’s understand what Kubernetes is all about." }, { "code": null, "e": 4378, "s": 4040, "text": "Kubernetes is a powerful open-source system developed by Google back in 2014, for managing containerized applications. In simple words, Kubernetes is a system for running and coordinating containerized applications across a cluster of machines. It is a platform designed to completely manage the life cycle of containerized applications." }, { "code": null, "e": 4452, "s": 4378, "text": "✔️ Load Balancing: Automatically distributes the load between containers." }, { "code": null, "e": 4591, "s": 4452, "text": "✔️ Scaling: Automatically scale up or down by adding or removing containers when demand changes such as peak hours, weekends and holidays." }, { "code": null, "e": 4671, "s": 4591, "text": "✔️ Storage: Keeps storage consistent with multiple instances of an application." }, { "code": null, "e": 4806, "s": 4671, "text": "✔️ Self-healing Automatically restarts containers that fail and kills containers that don’t respond to your user-defined health check." }, { "code": null, "e": 4984, "s": 4806, "text": "✔️ Automated Rollouts you can automate Kubernetes to create new containers for your deployment, remove existing containers and adopt all of their resources to the new container." }, { "code": null, "e": 5226, "s": 4984, "text": "Imagine a scenario where you have to run multiple docker containers on multiple machines to support an enterprise level ML application with varied workloads during day and night. As simple as it may sound, it is a lot of work to do manually." }, { "code": null, "e": 5548, "s": 5226, "text": "You need to start the right containers at the right time, figure out how they can talk to each other, handle storage considerations, and deal with failed containers or hardware. This is the problem Kubernetes is solving by allowing large numbers of containers to work together in harmony, reducing the operational burden." }, { "code": null, "e": 5663, "s": 5548, "text": "Google Kubernetes Engine is an implementation of Google’s open source Kubernetes on Google Cloud Platform. Simple!" }, { "code": null, "e": 5752, "s": 5663, "text": "Other popular alternatives to GKE are Amazon ECS and Microsoft Azure Kubernetes Service." }, { "code": null, "e": 5919, "s": 5752, "text": "A Container is a type of software that packages up an application and all its dependencies so the application runs reliably from one computing environment to another." }, { "code": null, "e": 5983, "s": 5919, "text": "Docker is a software used for building and managing containers." }, { "code": null, "e": 6087, "s": 5983, "text": "Kubernetes is an open-source system for managing containerized applications in a clustered environment." }, { "code": null, "e": 6199, "s": 6087, "text": "Google Kubernetes Engine is an implementation of the open source Kubernetes framework on Google Cloud Platform." }, { "code": null, "e": 6360, "s": 6199, "text": "In this tutorial, we will use Google Kubernetes Engine. In order to follow along, you must have a Google Cloud Platform account. Click here to sign-up for free." }, { "code": null, "e": 6549, "s": 6360, "text": "An insurance company wants to improve its cash flow forecasting by better predicting patient charges using demographic and basic patient health risk metrics at the time of hospitalization." }, { "code": null, "e": 6563, "s": 6549, "text": "(data source)" }, { "code": null, "e": 6703, "s": 6563, "text": "To build a web application that supports online (one-by-one) as well as batch prediction using trained machine learning model and pipeline." }, { "code": null, "e": 6774, "s": 6703, "text": "Train, validate and develop a machine learning pipeline using PyCaret." }, { "code": null, "e": 6883, "s": 6774, "text": "Build a front-end web application with two functionalities: (i) online prediction and (ii) batch prediction." }, { "code": null, "e": 6903, "s": 6883, "text": "Create a Dockerfile" }, { "code": null, "e": 7033, "s": 6903, "text": "Deploy the web app on Google Kubernetes Engine. Once deployed, it will become publicly available and can be accessed via Web URL." }, { "code": null, "e": 7302, "s": 7033, "text": "Training and model validation are performed in an Integrated Development Environment (IDE) or Notebook either on your local machine or on cloud. If you haven’t used PyCaret before, click here to learn more about PyCaret or see Getting Started Tutorials on our website." }, { "code": null, "e": 7654, "s": 7302, "text": "In this tutorial, we have performed two experiments. The first experiment is performed with default preprocessing settings in PyCaret. The second experiment has some additional preprocessing tasks such as scaling and normalization, automatic feature engineering and binning continuous data into intervals. See the setup code for the second experiment:" }, { "code": null, "e": 7940, "s": 7654, "text": "# Experiment No. 2from pycaret.regression import *r2 = setup(data, target = 'charges', session_id = 123, normalize = True, polynomial_features = True, trigonometry_features = True, feature_interaction=True, bin_numeric_features= ['age', 'bmi'])" }, { "code": null, "e": 8228, "s": 7940, "text": "The magic happens with only a few lines of code. Notice that in Experiment 2 the transformed dataset has 62 features for training derived from only 6 features in the original dataset. All of the new features are the result of transformations and automatic feature engineering in PyCaret." }, { "code": null, "e": 8271, "s": 8228, "text": "Sample code for model training in PyCaret:" }, { "code": null, "e": 8327, "s": 8271, "text": "# Model Training and Validation lr = create_model('lr')" }, { "code": null, "e": 8635, "s": 8327, "text": "Notice the impact of transformations and automatic feature engineering. The R2 has increased by 10% with very little effort. We can compare the residual plot of linear regression model for both experiments and observe the impact of transformations and feature engineering on the heteroskedasticity of model." }, { "code": null, "e": 8703, "s": 8635, "text": "# plot residuals of trained modelplot_model(lr, plot = 'residuals')" }, { "code": null, "e": 9070, "s": 8703, "text": "Machine learning is an iterative process. The number of iterations and techniques used within are dependent on how critical the task is and what the impact will be if predictions are wrong. The severity and impact of a machine learning model to predict a patient outcome in real-time in the ICU of a hospital is far more than a model built to predict customer churn." }, { "code": null, "e": 9409, "s": 9070, "text": "In this tutorial, we have performed only two iterations and the linear regression model from the second experiment will be used for deployment. At this stage, however, the model is still only an object within a Notebook / IDE. To save it as a file that can be transferred to and consumed by other applications, execute the following code:" }, { "code": null, "e": 9501, "s": 9409, "text": "# save transformation pipeline and model save_model(lr, model_name = 'deployment_28042020')" }, { "code": null, "e": 9769, "s": 9501, "text": "When you save a model in PyCaret, the entire transformation pipeline based on the configuration defined in the setup() function is created. All inter-dependencies are orchestrated automatically. See the pipeline and model stored in the ‘deployment_28042020’ variable:" }, { "code": null, "e": 10018, "s": 9769, "text": "We have finished training and model selection. The final machine learning pipeline and linear regression model is now saved as a pickle file (deployment_28042020.pkl) that will be used in a web application to generate predictions on new datapoints." }, { "code": null, "e": 10329, "s": 10018, "text": "Now that our machine learning pipeline and model are ready to start building a front-end web application that can generate predictions on new datapoints. This application will support ‘Online’ as well as ‘Batch’ predictions through a csv file upload. Let’s breakdown the application code into three main parts:" }, { "code": null, "e": 10530, "s": 10329, "text": "This section imports libraries, loads the trained model and creates a basic layout with a logo on top, a jpg image and a dropdown menu on the sidebar to toggle between ‘Online’ and ‘Batch’ prediction." }, { "code": null, "e": 10803, "s": 10530, "text": "This section deals with the initial app function, Online one-by-one predictions. We are using streamlit widgets such as number input, text input, drop down menu and checkbox to collect the datapoints used to train the model such as Age, Sex, BMI, Children, Smoker, Region." }, { "code": null, "e": 11083, "s": 10803, "text": "Predictions by batch is the second layer of the app’s functionality. The file_uploader widget in streamlit is used to upload a csv file and then called the native predict_model() function from PyCaret to generate predictions that are displayed using streamlit’s write() function." }, { "code": null, "e": 11371, "s": 11083, "text": "If you remember from Task 1 above we finalized a linear regression model that was trained on 62 features that were extracted from the 6 original features. The front-end of web application has an input form that collects only the six features i.e. age, sex, bmi, children, smoker, region." }, { "code": null, "e": 11773, "s": 11371, "text": "How do we transform these 6 features of a new data points into the 62 used to train the model? We do not need to worry about this part as PyCaret automatically handles this by orchestrating the transformation pipeline. When you call the predict function on a model trained using PyCaret, all transformations are applied automatically (in sequence) before generating predictions from the trained model." }, { "code": null, "e": 11964, "s": 11773, "text": "Testing AppOne final step before we publish the application on Heroku is to test the web app locally. Open Anaconda Prompt and navigate to your project folder and execute the following code:" }, { "code": null, "e": 11985, "s": 11964, "text": "streamlit run app.py" }, { "code": null, "e": 12132, "s": 11985, "text": "Now that we have a fully functional web application, we can start the process of containerizing and deploying the app on Google Kubernetes Engine." }, { "code": null, "e": 12390, "s": 12132, "text": "To containerize our application for deployment we need a docker image that becomes a container at runtime. A docker image is created using a Dockerfile. A Dockerfile is just a file with a set of instructions. The Dockerfile for this project looks like this:" }, { "code": null, "e": 12586, "s": 12390, "text": "The last part of this Dockerfile (starting at line 23) is Streamlit specific and not needed generally. Dockerfile is case-sensitive and must be in the project folder with the other project files." }, { "code": null, "e": 12671, "s": 12586, "text": "If you would like to follow along you will have to fork this repository from GitHub." }, { "code": null, "e": 12738, "s": 12671, "text": "Follow through these simple 10 steps to deploy app on GKE Cluster." }, { "code": null, "e": 12793, "s": 12738, "text": "Sign-in to your GCP console and go to Manage Resources" }, { "code": null, "e": 12821, "s": 12793, "text": "Click on Create New Project" }, { "code": null, "e": 12923, "s": 12821, "text": "Click the Activate Cloud Shell button at the top right of the console window to open the Cloud Shell." }, { "code": null, "e": 13019, "s": 12923, "text": "Execute the following code in Cloud Shell to clone the GitHub repository used in this tutorial." }, { "code": null, "e": 13085, "s": 13019, "text": "git clone https://github.com/pycaret/pycaret-streamlit-google.git" }, { "code": null, "e": 13156, "s": 13085, "text": "Execute the following code to set the PROJECT_ID environment variable." }, { "code": null, "e": 13196, "s": 13156, "text": "export PROJECT_ID=pycaret-streamlit-gcp" }, { "code": null, "e": 13271, "s": 13196, "text": "pycaret-streamlit-gcp is the name of the project we chose in step 1 above." }, { "code": null, "e": 13371, "s": 13271, "text": "Build the docker image of the application and tag it for uploading by executing the following code:" }, { "code": null, "e": 13433, "s": 13371, "text": "docker build -t gcr.io/${PROJECT_ID}/insurance-streamlit:v1 ." }, { "code": null, "e": 13499, "s": 13433, "text": "You can check the available images by running the following code:" }, { "code": null, "e": 13513, "s": 13499, "text": "docker images" }, { "code": null, "e": 13582, "s": 13513, "text": "Authenticate to Container Registry (you need to run this only once):" }, { "code": null, "e": 13651, "s": 13582, "text": "Authenticate to Container Registry (you need to run this only once):" }, { "code": null, "e": 13680, "s": 13651, "text": "gcloud auth configure-docker" }, { "code": null, "e": 13767, "s": 13680, "text": "2. Execute the following code to upload the docker image to Google Container Registry:" }, { "code": null, "e": 13823, "s": 13767, "text": "docker push gcr.io/${PROJECT_ID}/insurance-streamlit:v1" }, { "code": null, "e": 13981, "s": 13823, "text": "Now that the container is uploaded, you need a cluster to run the container. A cluster consists of a pool of Compute Engine VM instances, running Kubernetes." }, { "code": null, "e": 14054, "s": 13981, "text": "Set your project ID and Compute Engine zone options for the gcloud tool:" }, { "code": null, "e": 14127, "s": 14054, "text": "Set your project ID and Compute Engine zone options for the gcloud tool:" }, { "code": null, "e": 14208, "s": 14127, "text": "gcloud config set project $PROJECT_ID gcloud config set compute/zone us-central1" }, { "code": null, "e": 14261, "s": 14208, "text": "2. Create a cluster by executing the following code:" }, { "code": null, "e": 14326, "s": 14261, "text": "gcloud container clusters create streamlit-cluster --num-nodes=2" }, { "code": null, "e": 14503, "s": 14326, "text": "To deploy and manage applications on a GKE cluster, you must communicate with the Kubernetes cluster management system. Execute the following command to deploy the application:" }, { "code": null, "e": 14601, "s": 14503, "text": "kubectl create deployment insurance-streamlit --image=gcr.io/${PROJECT_ID}/insurance-streamlit:v1" }, { "code": null, "e": 14798, "s": 14601, "text": "By default, the containers you run on GKE are not accessible from the internet because they do not have external IP addresses. Execute the following code to expose the application to the internet:" }, { "code": null, "e": 14893, "s": 14798, "text": "kubectl expose deployment insurance-streamlit --type=LoadBalancer --port 80 --target-port 8501" }, { "code": null, "e": 15035, "s": 14893, "text": "Execute the following code to get the status of the service. EXTERNAL-IP is the web address you can use in browser to view the published app." }, { "code": null, "e": 15055, "s": 15035, "text": "kubectl get service" }, { "code": null, "e": 15180, "s": 15055, "text": "Note: By the time this story is published, the app will be removed from the public address to restrict resource consumption." }, { "code": null, "e": 15224, "s": 15180, "text": "Link to GitHub Repository for this tutorial" }, { "code": null, "e": 15281, "s": 15224, "text": "Link to GitHub Repository for Microsoft Azure Deployment" }, { "code": null, "e": 15329, "s": 15281, "text": "Link to GitHub Repository for Heroku Deployment" }, { "code": null, "e": 15681, "s": 15329, "text": "We have received overwhelming support and feedback from the community. We are actively working on improving PyCaret and preparing for our next release. PyCaret 2.0.0 will be bigger and better. If you would like to share your feedback and help us improve further, you may fill this form on the website or leave a comment on our GitHub or LinkedIn page." }, { "code": null, "e": 15767, "s": 15681, "text": "Follow our LinkedIn and subscribe to our YouTube channel to learn more about PyCaret." }, { "code": null, "e": 15933, "s": 15767, "text": "As of the first release 1.0.0, PyCaret has the following modules available for use. Click on the links below to see the documentation and working examples in Python." }, { "code": null, "e": 16035, "s": 15933, "text": "ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining" }, { "code": null, "e": 16082, "s": 16035, "text": "PyCaret getting started tutorials in Notebook:" }, { "code": null, "e": 16184, "s": 16082, "text": "ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining" }, { "code": null, "e": 16393, "s": 16184, "text": "PyCaret is an open source project. Everybody is welcome to contribute. If you would like to contribute, please feel free to work on open issues. Pull requests are accepted with unit tests on dev-1.0.1 branch." } ]
How to Check Mentioned File Exists or not using JavaScript/jQuery ?
03 Aug, 2021 Sometimes we want to upload a file through the path of the file, but few times the file does not exist. In that case, we have to respond to users the given path does not find any file or does not exist in the mentioned file. Approach 1: Use ajax() method of jQuery to check if a file exists on a given URL or not. The ajax() method is used to trigger the asynchronous HTTP request. If the file exists, ajax() method will in turn call ajaxSuccess() method else it will call Error function. Example: This example illustrate the above approach.<!DOCTYPE html><html> <head> <title> How to check if file exist using jquery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align: center; } h1 { color: green; } #output { color: green; font-size: 20px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <label id="File_Path"> <b>Enter File Path:</b> </label> <input type="text" id="File_URL"> <button id="Check_File"> click here </button> <p id="output"></p> <script> $(document).ready(function() { $("#Check_File").click(function() { var url = $("#File_URL").val(); if (url != "") { $.ajax({ url: url, type: 'HEAD', error: function() { $("#output").text("File doesn't exists"); }, success: function() { $("#output").text('File exists'); } }); } else { $("#Output").text("Please enter File URL"); } }); }); </script></body> </html> <!DOCTYPE html><html> <head> <title> How to check if file exist using jquery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align: center; } h1 { color: green; } #output { color: green; font-size: 20px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <label id="File_Path"> <b>Enter File Path:</b> </label> <input type="text" id="File_URL"> <button id="Check_File"> click here </button> <p id="output"></p> <script> $(document).ready(function() { $("#Check_File").click(function() { var url = $("#File_URL").val(); if (url != "") { $.ajax({ url: url, type: 'HEAD', error: function() { $("#output").text("File doesn't exists"); }, success: function() { $("#output").text('File exists'); } }); } else { $("#Output").text("Please enter File URL"); } }); }); </script></body> </html> Output: Approach 2: Use XMLHttpRequest() method to trigger ajax request. If the HTTP status is 200 then file exists otherwise file is not present. Example: This example illustrate the above approach.<!DOCTYPE HTML><html> <head> <title> How to check if file exist or not on HTTP status is 200 </title> <style> body { text-align: center; } h1 { color: green; } #output { color: green; font-size: 20px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <label id="File_Path"> <b>Enter File Path: </b> </label> <input type="text" id="File_URL"> <button id="Check_File" onclick="checkFileExist()"> click here </button> <p id="output"></p> <script> var url = document.getElementById("File_URL"); var output = document.getElementById("output"); var http = new XMLHttpRequest(); function checkFileExist() { if (url.length === 0) { output.innerHTML = "Please enter File URL"; } else { http.open('HEAD', url, false); http.send(); if (http.status === 200) { output.innerHTML = "File exists"; } else { output.innerHTML = "File doesn't exists"; } } } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to check if file exist or not on HTTP status is 200 </title> <style> body { text-align: center; } h1 { color: green; } #output { color: green; font-size: 20px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <label id="File_Path"> <b>Enter File Path: </b> </label> <input type="text" id="File_URL"> <button id="Check_File" onclick="checkFileExist()"> click here </button> <p id="output"></p> <script> var url = document.getElementById("File_URL"); var output = document.getElementById("output"); var http = new XMLHttpRequest(); function checkFileExist() { if (url.length === 0) { output.innerHTML = "Please enter File URL"; } else { http.open('HEAD', url, false); http.send(); if (http.status === 200) { output.innerHTML = "File exists"; } else { output.innerHTML = "File doesn't exists"; } } } </script></body> </html> Output: HTTP status is not 200 so if the file exist it will show not exist until the status is 200. 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 JavaScript-Misc jQuery-Misc Picked JavaScript JQuery Web Technologies Web technologies Questions 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? jQuery | children() with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 253, "s": 28, "text": "Sometimes we want to upload a file through the path of the file, but few times the file does not exist. In that case, we have to respond to users the given path does not find any file or does not exist in the mentioned file." }, { "code": null, "e": 517, "s": 253, "text": "Approach 1: Use ajax() method of jQuery to check if a file exists on a given URL or not. The ajax() method is used to trigger the asynchronous HTTP request. If the file exists, ajax() method will in turn call ajaxSuccess() method else it will call Error function." }, { "code": null, "e": 2071, "s": 517, "text": "Example: This example illustrate the above approach.<!DOCTYPE html><html> <head> <title> How to check if file exist using jquery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align: center; } h1 { color: green; } #output { color: green; font-size: 20px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <label id=\"File_Path\"> <b>Enter File Path:</b> </label> <input type=\"text\" id=\"File_URL\"> <button id=\"Check_File\"> click here </button> <p id=\"output\"></p> <script> $(document).ready(function() { $(\"#Check_File\").click(function() { var url = $(\"#File_URL\").val(); if (url != \"\") { $.ajax({ url: url, type: 'HEAD', error: function() { $(\"#output\").text(\"File doesn't exists\"); }, success: function() { $(\"#output\").text('File exists'); } }); } else { $(\"#Output\").text(\"Please enter File URL\"); } }); }); </script></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> How to check if file exist using jquery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align: center; } h1 { color: green; } #output { color: green; font-size: 20px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <label id=\"File_Path\"> <b>Enter File Path:</b> </label> <input type=\"text\" id=\"File_URL\"> <button id=\"Check_File\"> click here </button> <p id=\"output\"></p> <script> $(document).ready(function() { $(\"#Check_File\").click(function() { var url = $(\"#File_URL\").val(); if (url != \"\") { $.ajax({ url: url, type: 'HEAD', error: function() { $(\"#output\").text(\"File doesn't exists\"); }, success: function() { $(\"#output\").text('File exists'); } }); } else { $(\"#Output\").text(\"Please enter File URL\"); } }); }); </script></body> </html>", "e": 3573, "s": 2071, "text": null }, { "code": null, "e": 3581, "s": 3573, "text": "Output:" }, { "code": null, "e": 3720, "s": 3581, "text": "Approach 2: Use XMLHttpRequest() method to trigger ajax request. If the HTTP status is 200 then file exists otherwise file is not present." }, { "code": null, "e": 5081, "s": 3720, "text": "Example: This example illustrate the above approach.<!DOCTYPE HTML><html> <head> <title> How to check if file exist or not on HTTP status is 200 </title> <style> body { text-align: center; } h1 { color: green; } #output { color: green; font-size: 20px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <label id=\"File_Path\"> <b>Enter File Path: </b> </label> <input type=\"text\" id=\"File_URL\"> <button id=\"Check_File\" onclick=\"checkFileExist()\"> click here </button> <p id=\"output\"></p> <script> var url = document.getElementById(\"File_URL\"); var output = document.getElementById(\"output\"); var http = new XMLHttpRequest(); function checkFileExist() { if (url.length === 0) { output.innerHTML = \"Please enter File URL\"; } else { http.open('HEAD', url, false); http.send(); if (http.status === 200) { output.innerHTML = \"File exists\"; } else { output.innerHTML = \"File doesn't exists\"; } } } </script></body> </html> " }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to check if file exist or not on HTTP status is 200 </title> <style> body { text-align: center; } h1 { color: green; } #output { color: green; font-size: 20px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <label id=\"File_Path\"> <b>Enter File Path: </b> </label> <input type=\"text\" id=\"File_URL\"> <button id=\"Check_File\" onclick=\"checkFileExist()\"> click here </button> <p id=\"output\"></p> <script> var url = document.getElementById(\"File_URL\"); var output = document.getElementById(\"output\"); var http = new XMLHttpRequest(); function checkFileExist() { if (url.length === 0) { output.innerHTML = \"Please enter File URL\"; } else { http.open('HEAD', url, false); http.send(); if (http.status === 200) { output.innerHTML = \"File exists\"; } else { output.innerHTML = \"File doesn't exists\"; } } } </script></body> </html> ", "e": 6390, "s": 5081, "text": null }, { "code": null, "e": 6490, "s": 6390, "text": "Output: HTTP status is not 200 so if the file exist it will show not exist until the status is 200." }, { "code": null, "e": 6758, "s": 6490, "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": 6767, "s": 6758, "text": "CSS-Misc" }, { "code": null, "e": 6777, "s": 6767, "text": "HTML-Misc" }, { "code": null, "e": 6793, "s": 6777, "text": "JavaScript-Misc" }, { "code": null, "e": 6805, "s": 6793, "text": "jQuery-Misc" }, { "code": null, "e": 6812, "s": 6805, "text": "Picked" }, { "code": null, "e": 6823, "s": 6812, "text": "JavaScript" }, { "code": null, "e": 6830, "s": 6823, "text": "JQuery" }, { "code": null, "e": 6847, "s": 6830, "text": "Web Technologies" }, { "code": null, "e": 6874, "s": 6847, "text": "Web technologies Questions" }, { "code": null, "e": 6972, "s": 6874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7033, "s": 6972, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7105, "s": 7033, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 7145, "s": 7105, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7197, "s": 7145, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 7238, "s": 7197, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 7284, "s": 7238, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 7313, "s": 7284, "text": "Form validation using jQuery" }, { "code": null, "e": 7376, "s": 7313, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 7429, "s": 7376, "text": "How to add options to a select element using jQuery?" } ]
Python – Modulo of tuple elements
27 Dec, 2019 Sometimes, while working with records, we can have a problem in which we may need to perform modulo of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of modulo using generator expression and mapping index of each tuple is done by zip(). # Python3 code to demonstrate working of# Tuple modulo# using zip() + generator expression # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Tuple modulo# using zip() + generator expressionres = tuple(ele1 % ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing resultprint("The modulus tuple : " + str(res)) The original tuple 1 : (10, 4, 5, 6) The original tuple 2 : (5, 6, 7, 5) The modulus tuple : (0, 4, 5, 1) Method #2 : Using map() + modThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of modulus using mod and mapping is done by map(). # Python3 code to demonstrate working of# Tuple modulo# using map() + modfrom operator import mod # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Tuple modulo# using map() + modres = tuple(map(mod, test_tup1, test_tup2)) # printing resultprint("The modulus tuple : " + str(res)) The original tuple 1 : (10, 4, 5, 6) The original tuple 2 : (5, 6, 7, 5) The modulus tuple : (0, 4, 5, 1) Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Dec, 2019" }, { "code": null, "e": 250, "s": 28, "text": "Sometimes, while working with records, we can have a problem in which we may need to perform modulo of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 481, "s": 250, "text": "Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of modulo using generator expression and mapping index of each tuple is done by zip()." }, { "code": "# Python3 code to demonstrate working of# Tuple modulo# using zip() + generator expression # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Tuple modulo# using zip() + generator expressionres = tuple(ele1 % ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # printing resultprint(\"The modulus tuple : \" + str(res))", "e": 947, "s": 481, "text": null }, { "code": null, "e": 1054, "s": 947, "text": "The original tuple 1 : (10, 4, 5, 6)\nThe original tuple 2 : (5, 6, 7, 5)\nThe modulus tuple : (0, 4, 5, 1)\n" }, { "code": null, "e": 1253, "s": 1056, "text": "Method #2 : Using map() + modThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of modulus using mod and mapping is done by map()." }, { "code": "# Python3 code to demonstrate working of# Tuple modulo# using map() + modfrom operator import mod # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Tuple modulo# using map() + modres = tuple(map(mod, test_tup1, test_tup2)) # printing resultprint(\"The modulus tuple : \" + str(res))", "e": 1684, "s": 1253, "text": null }, { "code": null, "e": 1791, "s": 1684, "text": "The original tuple 1 : (10, 4, 5, 6)\nThe original tuple 2 : (5, 6, 7, 5)\nThe modulus tuple : (0, 4, 5, 1)\n" }, { "code": null, "e": 1813, "s": 1791, "text": "Python tuple-programs" }, { "code": null, "e": 1820, "s": 1813, "text": "Python" }, { "code": null, "e": 1836, "s": 1820, "text": "Python Programs" }, { "code": null, "e": 1934, "s": 1836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1952, "s": 1934, "text": "Python Dictionary" }, { "code": null, "e": 1994, "s": 1952, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2029, "s": 1994, "text": "Read a file line by line in Python" }, { "code": null, "e": 2055, "s": 2029, "text": "Python String | replace()" }, { "code": null, "e": 2087, "s": 2055, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2130, "s": 2087, "text": "Python program to convert a list to string" }, { "code": null, "e": 2152, "s": 2130, "text": "Defaultdict in Python" }, { "code": null, "e": 2191, "s": 2152, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2229, "s": 2191, "text": "Python | Convert a list to dictionary" } ]
Kadane's Algorithm | Practice | GeeksforGeeks
Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number) which has the maximum sum and return its sum. Example 1: Input: N = 5 Arr[] = {1,2,3,-2,5} Output: 9 Explanation: Max subarray sum is 9 of elements (1, 2, 3, -2, 5) which is a contiguous subarray. Example 2: Input: N = 4 Arr[] = {-1,-2,-3,-4} Output: -1 Explanation: Max subarray sum is -1 of element (-1) Your Task: You don't need to read input or print anything. The task is to complete the function maxSubarraySum() which takes Arr[] and N as input parameters and returns the sum of subarray with maximum sum. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 106 -107 ≤ A[i] ≤ 107 0 abhishekips07in 3 hours Python Approach. class Solution: ##Complete this function #Function to find the sum of contiguous subarray with maximum sum. def maxSubArraySum(self,arr,N): ##Your code here curr=0 maxi=float('-inf') for i in arr: curr+=i maxi=max(curr,maxi) if curr<0: curr=0 return maxi 0 sakshianie24104 hours ago // { Driver Code Startsimport java.io.*; class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases while(t-->0){ //size of array int n = Integer.parseInt(br.readLine().trim()); int arr[] = new int[n]; String inputLine[] = br.readLine().trim().split(" "); //adding elements for(int i=0; i<n; i++){ arr[i] = Integer.parseInt(inputLine[i]); } Solution obj = new Solution(); //calling maxSubarraySum() function System.out.println(obj.maxSubarraySum(arr, n)); }}} // } Driver Code Ends class Solution{ // arr: input array // n: size of array //Function to find the sum of contiguous subarray with maximum sum. long maxSubarraySum(int arr[], int n){ // Your code here int maxsum=0; int currsum=0; for (int i=0:i<n;i++){ currsum+=arr[i]; if(currsum>maxsum){ maxsum=currsum; } If(currsum<0){ currsum=0;//discard } } } } 0 aliakbarqeqk7 hours ago class Solution{ long maxSubarraySum(int arr[], int n){ int flag=0,max=arr[0]; for(int i=0;i<n;i++) { if(arr[i]>=0) { flag=1; break; } else{ if(max<arr[i]) max=arr[i]; } } if(flag==0) { long res=max; return res; } else{ long curr=0, far=0; for(int i=0;i<n;i++) { curr = curr + arr[i]; if(curr>far) far=curr; if(curr<0) curr=0; } return far; } } } 0 aditirai630638 hours ago long maxSubarraySum(int nums[], int n){ long max = Integer.MIN_VALUE, sum = 0; for(int i=0;i<n;i++){ sum += nums[i]; max = Math.max(sum,max); if(sum<0) sum = 0; } return max; 0 madhavagrawal315 hours ago JAVA Solution : long maxSubarraySum(int nums[], int n){ long largestSum = nums[0]; long currentMax = nums[0]; for(int i=1; i<nums.length; i++){ //Continue with the same SubArray : currentMax += nums[i]; //Should I start a new SubArray : if(currentMax<nums[i]){ currentMax = nums[i]; } if(largestSum<currentMax){ largestSum = currentMax; } } return largestSum; } 0 pritamlanke2 days ago int maxi=INT_MIN; int sum=0; for(int i=0;i<n;i++){ sum+=arr[i]; maxi=max(maxi,sum); if(sum<=0)sum=0; } return maxi; +1 aniketg7212 days ago Easy Java Solution class Solution{ long maxSubarraySum(int arr[], int n){ long maxSum= Integer.MIN_VALUE; long sum=0; for(int i=0; i<n; i++){ sum+= arr[i]; maxSum= Math.max(maxSum, sum); if(sum<=0) sum= 0; } return maxSum; } } +1 sanyam goyal2 days ago Idea is to find middle of the array and than find the left_sum(from 0, mid) and right_sum(from mid+1, n-1) and the sum of elements which are crossing into both left_arr and right_arr. long maxSubarraySum(int arr[], int n){ return maximumSubArraySum(arr, 0, n-1); } private static Integer maximumSubArraySum(int[] A, int low, int high) { if(high == low) { return A[low]; } else { int mid = (low + high)/2; int leftSum = maximumSubArraySum(A, low, mid); int rightSum = maximumSubArraySum(A, mid+1, high); int crossSum = maximumCrossingSubArraySum(A,low,mid,high); if(leftSum >= rightSum && leftSum >=crossSum) { return leftSum; } else if(rightSum >= leftSum && rightSum >= crossSum) { return rightSum; } else { return crossSum; } } } private static Integer maximumCrossingSubArraySum(int[] A, int low, int mid, int high) { int leftSumSub = Integer.MIN_VALUE; int sum = 0; for(int i=mid;i>=low;i--) { sum = sum + A[i]; if(sum > leftSumSub) { leftSumSub = sum; } } int rightSumSub = Integer.MIN_VALUE; sum = 0; for(int i=mid+1;i<=high;i++) { sum = sum + A[i]; if(sum > rightSumSub) { rightSumSub = sum; } } return leftSumSub + rightSumSub; } +1 abhinayabhi1413 days ago long maxSubarraySum(int arr[], int n){ // Your code here long currsum =0; long maxsum =Long.MIN_VALUE; for(int i =0; i <n ;i++){// O(n) currsum += arr[i];// calculating all the sums if(currsum >maxsum){ // agr mera sum curr is grater than the max to update the value maxsum = currsum; } if(currsum < 0){ // at a point my curr is becoming 0 tabh refresh the value of curr to 0 currsum =0; } } return maxsum; } } 0 harshdeep57083 days ago Kadane's Algo. long long maxSubarraySum(int arr[], int N){ long sum=0; long maxi=INT_MIN; for(int i=0;i<N;i++) { sum+=arr[i]; maxi=max(sum,maxi); if(sum<0) sum=0; } return maxi; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 382, "s": 238, "text": "Given an array Arr[] of N integers. Find the contiguous sub-array(containing at least one number) which has the maximum sum and return its sum." }, { "code": null, "e": 394, "s": 382, "text": "\nExample 1:" }, { "code": null, "e": 536, "s": 394, "text": "Input:\nN = 5\nArr[] = {1,2,3,-2,5}\nOutput:\n9\nExplanation:\nMax subarray sum is 9\nof elements (1, 2, 3, -2, 5) which \nis a contiguous subarray.\n" }, { "code": null, "e": 547, "s": 536, "text": "Example 2:" }, { "code": null, "e": 646, "s": 547, "text": "Input:\nN = 4\nArr[] = {-1,-2,-3,-4}\nOutput:\n-1\nExplanation:\nMax subarray sum is -1 \nof element (-1)" }, { "code": null, "e": 854, "s": 646, "text": "\nYour Task:\nYou don't need to read input or print anything. The task is to complete the function maxSubarraySum() which takes Arr[] and N as input parameters and returns the sum of subarray with maximum sum." }, { "code": null, "e": 917, "s": 854, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 961, "s": 917, "text": "\nConstraints:\n1 ≤ N ≤ 106\n-107 ≤ A[i] ≤ 107" }, { "code": null, "e": 963, "s": 961, "text": "0" }, { "code": null, "e": 987, "s": 963, "text": "abhishekips07in 3 hours" }, { "code": null, "e": 1004, "s": 987, "text": "Python Approach." }, { "code": null, "e": 1364, "s": 1004, "text": "class Solution:\n ##Complete this function\n #Function to find the sum of contiguous subarray with maximum sum.\n def maxSubArraySum(self,arr,N):\n ##Your code here\n curr=0\n maxi=float('-inf')\n for i in arr:\n curr+=i\n maxi=max(curr,maxi)\n if curr<0:\n curr=0\n return maxi\n" }, { "code": null, "e": 1366, "s": 1364, "text": "0" }, { "code": null, "e": 1392, "s": 1366, "text": "sakshianie24104 hours ago" }, { "code": null, "e": 1433, "s": 1392, "text": "// { Driver Code Startsimport java.io.*;" }, { "code": null, "e": 2080, "s": 1433, "text": "class Main { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases while(t-->0){ //size of array int n = Integer.parseInt(br.readLine().trim()); int arr[] = new int[n]; String inputLine[] = br.readLine().trim().split(\" \"); //adding elements for(int i=0; i<n; i++){ arr[i] = Integer.parseInt(inputLine[i]); } Solution obj = new Solution(); //calling maxSubarraySum() function System.out.println(obj.maxSubarraySum(arr, n)); }}}" }, { "code": null, "e": 2102, "s": 2080, "text": "// } Driver Code Ends" }, { "code": null, "e": 2118, "s": 2102, "text": "class Solution{" }, { "code": null, "e": 2474, "s": 2118, "text": " // arr: input array // n: size of array //Function to find the sum of contiguous subarray with maximum sum. long maxSubarraySum(int arr[], int n){ // Your code here int maxsum=0; int currsum=0; for (int i=0:i<n;i++){ currsum+=arr[i]; if(currsum>maxsum){ maxsum=currsum; }" }, { "code": null, "e": 2534, "s": 2474, "text": " If(currsum<0){ currsum=0;//discard" }, { "code": null, "e": 2581, "s": 2534, "text": " } } } }" }, { "code": null, "e": 2585, "s": 2583, "text": "0" }, { "code": null, "e": 2609, "s": 2585, "text": "aliakbarqeqk7 hours ago" }, { "code": null, "e": 2625, "s": 2609, "text": "class Solution{" }, { "code": null, "e": 3317, "s": 2625, "text": " long maxSubarraySum(int arr[], int n){ int flag=0,max=arr[0]; for(int i=0;i<n;i++) { if(arr[i]>=0) { flag=1; break; } else{ if(max<arr[i]) max=arr[i]; } } if(flag==0) { long res=max; return res; } else{ long curr=0, far=0; for(int i=0;i<n;i++) { curr = curr + arr[i]; if(curr>far) far=curr; if(curr<0) curr=0; } return far; } } }" }, { "code": null, "e": 3319, "s": 3317, "text": "0" }, { "code": null, "e": 3344, "s": 3319, "text": "aditirai630638 hours ago" }, { "code": null, "e": 3547, "s": 3344, "text": "long maxSubarraySum(int nums[], int n){ long max = Integer.MIN_VALUE, sum = 0; for(int i=0;i<n;i++){ sum += nums[i]; max = Math.max(sum,max); if(sum<0) sum = 0; }" }, { "code": null, "e": 3560, "s": 3547, "text": " return max;" }, { "code": null, "e": 3562, "s": 3560, "text": "0" }, { "code": null, "e": 3589, "s": 3562, "text": "madhavagrawal315 hours ago" }, { "code": null, "e": 3605, "s": 3589, "text": "JAVA Solution :" }, { "code": null, "e": 4148, "s": 3605, "text": " long maxSubarraySum(int nums[], int n){\n \n long largestSum = nums[0];\n long currentMax = nums[0];\n \n for(int i=1; i<nums.length; i++){\n \n //Continue with the same SubArray :\n currentMax += nums[i];\n \n //Should I start a new SubArray :\n if(currentMax<nums[i]){\n currentMax = nums[i];\n }\n \n if(largestSum<currentMax){\n largestSum = currentMax;\n }\n }\n return largestSum; \n \n }" }, { "code": null, "e": 4150, "s": 4148, "text": "0" }, { "code": null, "e": 4172, "s": 4150, "text": "pritamlanke2 days ago" }, { "code": null, "e": 4342, "s": 4172, "text": "int maxi=INT_MIN; int sum=0; for(int i=0;i<n;i++){ sum+=arr[i]; maxi=max(maxi,sum); if(sum<=0)sum=0; } return maxi;" }, { "code": null, "e": 4345, "s": 4342, "text": "+1" }, { "code": null, "e": 4366, "s": 4345, "text": "aniketg7212 days ago" }, { "code": null, "e": 4385, "s": 4366, "text": "Easy Java Solution" }, { "code": null, "e": 4705, "s": 4385, "text": "class Solution{\n\n long maxSubarraySum(int arr[], int n){\n long maxSum= Integer.MIN_VALUE;\n long sum=0;\n for(int i=0; i<n; i++){\n sum+= arr[i];\n maxSum= Math.max(maxSum, sum);\n \n if(sum<=0) sum= 0;\n }\n return maxSum;\n \n }\n \n}" }, { "code": null, "e": 4708, "s": 4705, "text": "+1" }, { "code": null, "e": 4731, "s": 4708, "text": "sanyam goyal2 days ago" }, { "code": null, "e": 4915, "s": 4731, "text": "Idea is to find middle of the array and than find the left_sum(from 0, mid) and right_sum(from mid+1, n-1) and the sum of elements which are crossing into both left_arr and right_arr." }, { "code": null, "e": 6237, "s": 4917, "text": "long maxSubarraySum(int arr[], int n){\n return maximumSubArraySum(arr, 0, n-1);\n }\n \n private static Integer maximumSubArraySum(int[] A, int low, int high) {\n if(high == low) {\n return A[low];\n } else {\n int mid = (low + high)/2;\n int leftSum = maximumSubArraySum(A, low, mid);\n int rightSum = maximumSubArraySum(A, mid+1, high);\n int crossSum = maximumCrossingSubArraySum(A,low,mid,high);\n \n if(leftSum >= rightSum && leftSum >=crossSum) {\n return leftSum;\n } else if(rightSum >= leftSum && rightSum >= crossSum) {\n return rightSum;\n } else {\n return crossSum;\n }\n }\n }\n \n private static Integer maximumCrossingSubArraySum(int[] A, int low, int mid, int high) {\n int leftSumSub = Integer.MIN_VALUE;\n int sum = 0;\n for(int i=mid;i>=low;i--) {\n sum = sum + A[i];\n if(sum > leftSumSub) {\n leftSumSub = sum;\n }\n }\n \n int rightSumSub = Integer.MIN_VALUE;\n sum = 0;\n for(int i=mid+1;i<=high;i++) {\n sum = sum + A[i];\n if(sum > rightSumSub) {\n rightSumSub = sum;\n }\n }\n \n return leftSumSub + rightSumSub;\n }" }, { "code": null, "e": 6242, "s": 6239, "text": "+1" }, { "code": null, "e": 6267, "s": 6242, "text": "abhinayabhi1413 days ago" }, { "code": null, "e": 6830, "s": 6267, "text": " long maxSubarraySum(int arr[], int n){ // Your code here long currsum =0; long maxsum =Long.MIN_VALUE; for(int i =0; i <n ;i++){// O(n) currsum += arr[i];// calculating all the sums if(currsum >maxsum){ // agr mera sum curr is grater than the max to update the value maxsum = currsum; } if(currsum < 0){ // at a point my curr is becoming 0 tabh refresh the value of curr to 0 currsum =0; } } return maxsum; } }" }, { "code": null, "e": 6832, "s": 6830, "text": "0" }, { "code": null, "e": 6856, "s": 6832, "text": "harshdeep57083 days ago" }, { "code": null, "e": 7144, "s": 6856, "text": "Kadane's Algo. \n \n long long maxSubarraySum(int arr[], int N){\n long sum=0;\n long maxi=INT_MIN;\n for(int i=0;i<N;i++)\n {\n sum+=arr[i];\n maxi=max(sum,maxi);\n if(sum<0)\n sum=0;\n }\n return maxi;" }, { "code": null, "e": 7290, "s": 7144, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7326, "s": 7290, "text": " Login to access your submissions. " }, { "code": null, "e": 7336, "s": 7326, "text": "\nProblem\n" }, { "code": null, "e": 7346, "s": 7336, "text": "\nContest\n" }, { "code": null, "e": 7409, "s": 7346, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7594, "s": 7409, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7878, "s": 7594, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 8024, "s": 7878, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 8101, "s": 8024, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 8142, "s": 8101, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 8170, "s": 8142, "text": "Disable browser extensions." }, { "code": null, "e": 8241, "s": 8170, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 8428, "s": 8241, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Count of elements which are not at the correct position
28 Jun, 2022 Given an array arr[] of N elements and the task is to count the number of elements from this array which are not at the correct position. An element is said to be in an incorrect position if its position changes in the array when the array is sorted.Examples: Input: arr[] = {1, 2, 6, 2, 4, 5} Output: 4 Array in the sorted form will be {1, 2, 2, 4, 5, 6}Input: arr[] = {1, 2, 3, 4} Output: 0 All the elements are already sorted. Approach: First copy the array elements in another array say B[] then sort the given array. Start traversing the array and for every element if arr[i] != B[i] then it is the element which was not at the right position in the given array.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// elements which are not in// the correct position when sortedint cntElements(int arr[], int n){ // To store a copy of the // original array int copy_arr[n]; // Copy the elements of the given // array to the new array for (int i = 0; i < n; i++) copy_arr[i] = arr[i]; // To store the required count int count = 0; // Sort the original array sort(arr, arr + n); for (int i = 0; i < n; i++) { // If current element was not // at the right position if (arr[i] != copy_arr[i]) { count++; } } return count;} // Driver codeint main(){ int arr[] = { 1, 2, 6, 2, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << cntElements(arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of // elements which are not in // the correct position when sorted static int cntElements(int arr[], int n) { // To store a copy of the // original array int copy_arr[] = new int[n]; // Copy the elements of the given // array to the new array for (int i = 0; i < n; i++) copy_arr[i] = arr[i]; // To store the required count int count = 0; // Sort the original array Arrays.sort(arr); for (int i = 0; i < n; i++) { // If current element was not // at the right position if (arr[i] != copy_arr[i]) { count++; } } return count; } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 6, 2, 4, 5 }; int n = arr.length; System.out.println(cntElements(arr, n)); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to return the count of# elements which are not in# the correct position when sorteddef cntElements(arr, n) : # To store a copy of the # original array copy_arr = [0] * n # Copy the elements of the given # array to the new array for i in range(n): copy_arr[i] = arr[i] # To store the required count count = 0 # Sort the original array arr.sort() for i in range(n): # If current element was not # at the right position if (arr[i] != copy_arr[i]) : count += 1 return count # Driver codearr = [ 1, 2, 6, 2, 4, 5 ]n = len(arr) print(cntElements(arr, n)) # This code is contributed by# divyamohan123 // C# implementation of the approachusing System; class GFG{ // Function to return the count of // elements which are not in // the correct position when sorted static int cntElements(int [] arr, int n) { // To store a copy of the // original array int [] copy_arr = new int[n]; // Copy the elements of the given // array to the new array for (int i = 0; i < n; i++) copy_arr[i] = arr[i]; // To store the required count int count = 0; // Sort the original array Array.Sort(arr); for (int i = 0; i < n; i++) { // If current element was not // at the right position if (arr[i] != copy_arr[i]) { count++; } } return count; } // Driver code public static void Main (String[] args) { int [] arr = { 1, 2, 6, 2, 4, 5 }; int n = arr.Length; Console.WriteLine(cntElements(arr, n)); }} // This code is contributed by Mohit kumar <script>// Javascript implementation of the approach // Function to return the count of// elements which are not in// the correct position when sortedfunction cntElements(arr, n) { // To store a copy of the // original array let copy_arr = new Array(n); // Copy the elements of the given // array to the new array for (let i = 0; i < n; i++) copy_arr[i] = arr[i]; // To store the required count let count = 0; // Sort the original array arr.sort((a, b) => a - b); for (let i = 0; i < n; i++) { // If current element was not // at the right position if (arr[i] != copy_arr[i]) { count++; } } return count;} // Driver code let arr = [1, 2, 6, 2, 4, 5];let n = arr.length; document.write(cntElements(arr, n)); // This code is contributed by gfgking.</script> 4 Time Complexity: O(n*log(n))Auxiliary Space: O(n) divyamohan123 ankthon mohit kumar 29 gfgking pushpeshrajdx01 Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2022" }, { "code": null, "e": 290, "s": 28, "text": "Given an array arr[] of N elements and the task is to count the number of elements from this array which are not at the correct position. An element is said to be in an incorrect position if its position changes in the array when the array is sorted.Examples: " }, { "code": null, "e": 462, "s": 290, "text": "Input: arr[] = {1, 2, 6, 2, 4, 5} Output: 4 Array in the sorted form will be {1, 2, 2, 4, 5, 6}Input: arr[] = {1, 2, 3, 4} Output: 0 All the elements are already sorted. " }, { "code": null, "e": 754, "s": 464, "text": "Approach: First copy the array elements in another array say B[] then sort the given array. Start traversing the array and for every element if arr[i] != B[i] then it is the element which was not at the right position in the given array.Below is the implementation of the above approach: " }, { "code": null, "e": 758, "s": 754, "text": "C++" }, { "code": null, "e": 763, "s": 758, "text": "Java" }, { "code": null, "e": 771, "s": 763, "text": "Python3" }, { "code": null, "e": 774, "s": 771, "text": "C#" }, { "code": null, "e": 785, "s": 774, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// elements which are not in// the correct position when sortedint cntElements(int arr[], int n){ // To store a copy of the // original array int copy_arr[n]; // Copy the elements of the given // array to the new array for (int i = 0; i < n; i++) copy_arr[i] = arr[i]; // To store the required count int count = 0; // Sort the original array sort(arr, arr + n); for (int i = 0; i < n; i++) { // If current element was not // at the right position if (arr[i] != copy_arr[i]) { count++; } } return count;} // Driver codeint main(){ int arr[] = { 1, 2, 6, 2, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << cntElements(arr, n); return 0;}", "e": 1647, "s": 785, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of // elements which are not in // the correct position when sorted static int cntElements(int arr[], int n) { // To store a copy of the // original array int copy_arr[] = new int[n]; // Copy the elements of the given // array to the new array for (int i = 0; i < n; i++) copy_arr[i] = arr[i]; // To store the required count int count = 0; // Sort the original array Arrays.sort(arr); for (int i = 0; i < n; i++) { // If current element was not // at the right position if (arr[i] != copy_arr[i]) { count++; } } return count; } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 6, 2, 4, 5 }; int n = arr.length; System.out.println(cntElements(arr, n)); }} // This code is contributed by AnkitRai01", "e": 2752, "s": 1647, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count of# elements which are not in# the correct position when sorteddef cntElements(arr, n) : # To store a copy of the # original array copy_arr = [0] * n # Copy the elements of the given # array to the new array for i in range(n): copy_arr[i] = arr[i] # To store the required count count = 0 # Sort the original array arr.sort() for i in range(n): # If current element was not # at the right position if (arr[i] != copy_arr[i]) : count += 1 return count # Driver codearr = [ 1, 2, 6, 2, 4, 5 ]n = len(arr) print(cntElements(arr, n)) # This code is contributed by# divyamohan123", "e": 3495, "s": 2752, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of // elements which are not in // the correct position when sorted static int cntElements(int [] arr, int n) { // To store a copy of the // original array int [] copy_arr = new int[n]; // Copy the elements of the given // array to the new array for (int i = 0; i < n; i++) copy_arr[i] = arr[i]; // To store the required count int count = 0; // Sort the original array Array.Sort(arr); for (int i = 0; i < n; i++) { // If current element was not // at the right position if (arr[i] != copy_arr[i]) { count++; } } return count; } // Driver code public static void Main (String[] args) { int [] arr = { 1, 2, 6, 2, 4, 5 }; int n = arr.Length; Console.WriteLine(cntElements(arr, n)); }} // This code is contributed by Mohit kumar", "e": 4594, "s": 3495, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the count of// elements which are not in// the correct position when sortedfunction cntElements(arr, n) { // To store a copy of the // original array let copy_arr = new Array(n); // Copy the elements of the given // array to the new array for (let i = 0; i < n; i++) copy_arr[i] = arr[i]; // To store the required count let count = 0; // Sort the original array arr.sort((a, b) => a - b); for (let i = 0; i < n; i++) { // If current element was not // at the right position if (arr[i] != copy_arr[i]) { count++; } } return count;} // Driver code let arr = [1, 2, 6, 2, 4, 5];let n = arr.length; document.write(cntElements(arr, n)); // This code is contributed by gfgking.</script>", "e": 5441, "s": 4594, "text": null }, { "code": null, "e": 5443, "s": 5441, "text": "4" }, { "code": null, "e": 5495, "s": 5445, "text": "Time Complexity: O(n*log(n))Auxiliary Space: O(n)" }, { "code": null, "e": 5509, "s": 5495, "text": "divyamohan123" }, { "code": null, "e": 5517, "s": 5509, "text": "ankthon" }, { "code": null, "e": 5532, "s": 5517, "text": "mohit kumar 29" }, { "code": null, "e": 5540, "s": 5532, "text": "gfgking" }, { "code": null, "e": 5556, "s": 5540, "text": "pushpeshrajdx01" }, { "code": null, "e": 5563, "s": 5556, "text": "Arrays" }, { "code": null, "e": 5571, "s": 5563, "text": "Sorting" }, { "code": null, "e": 5578, "s": 5571, "text": "Arrays" }, { "code": null, "e": 5586, "s": 5578, "text": "Sorting" }, { "code": null, "e": 5684, "s": 5586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5716, "s": 5684, "text": "Introduction to Data Structures" }, { "code": null, "e": 5741, "s": 5716, "text": "Window Sliding Technique" }, { "code": null, "e": 5788, "s": 5741, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 5819, "s": 5788, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 5877, "s": 5819, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 5888, "s": 5877, "text": "Merge Sort" }, { "code": null, "e": 5910, "s": 5888, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 5920, "s": 5910, "text": "QuickSort" }, { "code": null, "e": 5935, "s": 5920, "text": "Insertion Sort" } ]
Implementation of Particle Swarm Optimization
31 Aug, 2021 Previous article Particle Swarm Optimization – An Overview talked about inspiration of particle swarm optimization (PSO) , it’s mathematical modelling and algorithm. In this article we will implement particle swarm optimization (PSO) for two fitness functions 1) Rastrigin function 2) Sphere function. The algorithm will run for a predefined number of maximum iterations and will try to find the minimum value of these fitness functions. Rastrigin function is a non-convex function and is often used as a performance test problem for optimization algorithms. Fig1: Rastrigin function for 2 variables For an optimization algorithm, rastrigin function is a very challenging one. Its complex behavior cause optimization algorithms to often stuck at local minima. Having a lot of cosine oscillations on the plane introduces the complex behavior to this function. Sphere function is a standard function for evaluating the performance of an optimization algorithm. Fig2: Sphere function for 2 variables Number of dimensions (d) = 3 Lower bound (minx) = -10.0 Upper bound (maxx) = 10.0 Number of particles (N) = 50 Maximum number of iterations (max_iter) = 100 inertia coefficient (w) = 0.729 cognitive coefficient (c1) = 1.49445 social coefficient (c2) = 1.49445 Fitness function Problem parameters ( mentioned above) Population size (N) and Maximum number of iterations (max_iter) Algorithm Specific hyper parameters ( w, c1, c2) The pseudocode of the particle swarm optimization is already described in the previous article. Data structures to store Swarm population, as well as a data structure to store data specific to individual particle, were also discussed. Python3 # python implementation of particle swarm optimization (PSO)# minimizing rastrigin and sphere function import randomimport math # cos() for Rastriginimport copy # array-copying convenienceimport sys # max float #-------fitness functions--------- # rastrigin functiondef fitness_rastrigin(position): fitnessVal = 0.0 for i in range(len(position)): xi = position[i] fitnessVal += (xi * xi) - (10 * math.cos(2 * math.pi * xi)) + 10 return fitnessVal #sphere functiondef fitness_sphere(position): fitnessVal = 0.0 for i in range(len(position)): xi = position[i] fitnessVal += (xi*xi); return fitnessVal;#------------------------- #particle classclass Particle: def __init__(self, fitness, dim, minx, maxx, seed): self.rnd = random.Random(seed) # initialize position of the particle with 0.0 value self.position = [0.0 for i in range(dim)] # initialize velocity of the particle with 0.0 value self.velocity = [0.0 for i in range(dim)] # initialize best particle position of the particle with 0.0 value self.best_part_pos = [0.0 for i in range(dim)] # loop dim times to calculate random position and velocity # range of position and velocity is [minx, max] for i in range(dim): self.position[i] = ((maxx - minx) * self.rnd.random() + minx) self.velocity[i] = ((maxx - minx) * self.rnd.random() + minx) # compute fitness of particle self.fitness = fitness(self.position) # curr fitness # initialize best position and fitness of this particle self.best_part_pos = copy.copy(self.position) self.best_part_fitnessVal = self.fitness # best fitness # particle swarm optimization functiondef pso(fitness, max_iter, n, dim, minx, maxx): # hyper parameters w = 0.729 # inertia c1 = 1.49445 # cognitive (particle) c2 = 1.49445 # social (swarm) rnd = random.Random(0) # create n random particles swarm = [Particle(fitness, dim, minx, maxx, i) for i in range(n)] # compute the value of best_position and best_fitness in swarm best_swarm_pos = [0.0 for i in range(dim)] best_swarm_fitnessVal = sys.float_info.max # swarm best # computer best particle of swarm and it's fitness for i in range(n): # check each particle if swarm[i].fitness < best_swarm_fitnessVal: best_swarm_fitnessVal = swarm[i].fitness best_swarm_pos = copy.copy(swarm[i].position) # main loop of pso Iter = 0 while Iter < max_iter: # after every 10 iterations # print iteration number and best fitness value so far if Iter % 10 == 0 and Iter > 1: print("Iter = " + str(Iter) + " best fitness = %.3f" % best_swarm_fitnessVal) for i in range(n): # process each particle # compute new velocity of curr particle for k in range(dim): r1 = rnd.random() # randomizations r2 = rnd.random() swarm[i].velocity[k] = ( (w * swarm[i].velocity[k]) + (c1 * r1 * (swarm[i].best_part_pos[k] - swarm[i].position[k])) + (c2 * r2 * (best_swarm_pos[k] -swarm[i].position[k])) ) # if velocity[k] is not in [minx, max] # then clip it if swarm[i].velocity[k] < minx: swarm[i].velocity[k] = minx elif swarm[i].velocity[k] > maxx: swarm[i].velocity[k] = maxx # compute new position using new velocity for k in range(dim): swarm[i].position[k] += swarm[i].velocity[k] # compute fitness of new position swarm[i].fitness = fitness(swarm[i].position) # is new position a new best for the particle? if swarm[i].fitness < swarm[i].best_part_fitnessVal: swarm[i].best_part_fitnessVal = swarm[i].fitness swarm[i].best_part_pos = copy.copy(swarm[i].position) # is new position a new best overall? if swarm[i].fitness < best_swarm_fitnessVal: best_swarm_fitnessVal = swarm[i].fitness best_swarm_pos = copy.copy(swarm[i].position) # for-each particle Iter += 1 #end_while return best_swarm_pos# end pso #----------------------------# Driver code for rastrigin function print("\nBegin particle swarm optimization on rastrigin function\n")dim = 3fitness = fitness_rastrigin print("Goal is to minimize Rastrigin's function in " + str(dim) + " variables")print("Function has known min = 0.0 at (", end="")for i in range(dim-1): print("0, ", end="")print("0)") num_particles = 50max_iter = 100 print("Setting num_particles = " + str(num_particles))print("Setting max_iter = " + str(max_iter))print("\nStarting PSO algorithm\n") best_position = pso(fitness, max_iter, num_particles, dim, -10.0, 10.0) print("\nPSO completed\n")print("\nBest solution found:")print(["%.6f"%best_position[k] for k in range(dim)])fitnessVal = fitness(best_position)print("fitness of best solution = %.6f" % fitnessVal) print("\nEnd particle swarm for rastrigin function\n") print()print() # Driver code for Sphere functionprint("\nBegin particle swarm optimization on sphere function\n")dim = 3fitness = fitness_sphere print("Goal is to minimize sphere function in " + str(dim) + " variables")print("Function has known min = 0.0 at (", end="")for i in range(dim-1): print("0, ", end="")print("0)") num_particles = 50max_iter = 100 print("Setting num_particles = " + str(num_particles))print("Setting max_iter = " + str(max_iter))print("\nStarting PSO algorithm\n") best_position = pso(fitness, max_iter, num_particles, dim, -10.0, 10.0) print("\nPSO completed\n")print("\nBest solution found:")print(["%.6f"%best_position[k] for k in range(dim)])fitnessVal = fitness(best_position)print("fitness of best solution = %.6f" % fitnessVal) print("\nEnd particle swarm for sphere function\n") Begin particle swarm optimization on rastrigin function Goal is to minimize Rastrigin's function in 3 variables Function has known min = 0.0 at (0, 0, 0) Setting num_particles = 50 Setting max_iter = 100 Starting PSO algorithm Iter = 10 best fitness = 8.463 Iter = 20 best fitness = 4.792 Iter = 30 best fitness = 2.223 Iter = 40 best fitness = 0.251 Iter = 50 best fitness = 0.251 Iter = 60 best fitness = 0.061 Iter = 70 best fitness = 0.007 Iter = 80 best fitness = 0.005 Iter = 90 best fitness = 0.000 PSO completed Best solution found: ['0.000618', '0.000013', '0.000616'] fitness of best solution = 0.000151 End particle swarm for rastrigin function Begin particle swarm optimization on sphere function Goal is to minimize sphere function in 3 variables Function has known min = 0.0 at (0, 0, 0) Setting num_particles = 50 Setting max_iter = 100 Starting PSO algorithm Iter = 10 best fitness = 0.189 Iter = 20 best fitness = 0.012 Iter = 30 best fitness = 0.001 Iter = 40 best fitness = 0.000 Iter = 50 best fitness = 0.000 Iter = 60 best fitness = 0.000 Iter = 70 best fitness = 0.000 Iter = 80 best fitness = 0.000 Iter = 90 best fitness = 0.000 PSO completed Best solution found: ['0.000004', '-0.000001', '0.000007'] fitness of best solution = 0.000000 End particle swarm for sphere function Research paper citation: Kennedy, J. and Eberhart, R., 1995, November. Particle swarm optimization. In Proceedings of ICNN’95-international conference on neural networks (Vol. 4, pp. 1942-1948). IEEE. Inspiration of the implementation: https://fr.mathworks.com/matlabcentral/fileexchange/67429-a-simple-implementation-of-particle-swarm-optimization-pso-algorithm rajeev0719singh Artificial Intelligence Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2021" }, { "code": null, "e": 470, "s": 28, "text": "Previous article Particle Swarm Optimization – An Overview talked about inspiration of particle swarm optimization (PSO) , it’s mathematical modelling and algorithm. In this article we will implement particle swarm optimization (PSO) for two fitness functions 1) Rastrigin function 2) Sphere function. The algorithm will run for a predefined number of maximum iterations and will try to find the minimum value of these fitness functions." }, { "code": null, "e": 591, "s": 470, "text": "Rastrigin function is a non-convex function and is often used as a performance test problem for optimization algorithms." }, { "code": null, "e": 632, "s": 591, "text": "Fig1: Rastrigin function for 2 variables" }, { "code": null, "e": 891, "s": 632, "text": "For an optimization algorithm, rastrigin function is a very challenging one. Its complex behavior cause optimization algorithms to often stuck at local minima. Having a lot of cosine oscillations on the plane introduces the complex behavior to this function." }, { "code": null, "e": 991, "s": 891, "text": "Sphere function is a standard function for evaluating the performance of an optimization algorithm." }, { "code": null, "e": 1029, "s": 991, "text": "Fig2: Sphere function for 2 variables" }, { "code": null, "e": 1058, "s": 1029, "text": "Number of dimensions (d) = 3" }, { "code": null, "e": 1085, "s": 1058, "text": "Lower bound (minx) = -10.0" }, { "code": null, "e": 1111, "s": 1085, "text": "Upper bound (maxx) = 10.0" }, { "code": null, "e": 1140, "s": 1111, "text": "Number of particles (N) = 50" }, { "code": null, "e": 1186, "s": 1140, "text": "Maximum number of iterations (max_iter) = 100" }, { "code": null, "e": 1218, "s": 1186, "text": "inertia coefficient (w) = 0.729" }, { "code": null, "e": 1255, "s": 1218, "text": "cognitive coefficient (c1) = 1.49445" }, { "code": null, "e": 1289, "s": 1255, "text": "social coefficient (c2) = 1.49445" }, { "code": null, "e": 1306, "s": 1289, "text": "Fitness function" }, { "code": null, "e": 1344, "s": 1306, "text": "Problem parameters ( mentioned above)" }, { "code": null, "e": 1409, "s": 1344, "text": "Population size (N) and Maximum number of iterations (max_iter)" }, { "code": null, "e": 1458, "s": 1409, "text": "Algorithm Specific hyper parameters ( w, c1, c2)" }, { "code": null, "e": 1693, "s": 1458, "text": "The pseudocode of the particle swarm optimization is already described in the previous article. Data structures to store Swarm population, as well as a data structure to store data specific to individual particle, were also discussed." }, { "code": null, "e": 1701, "s": 1693, "text": "Python3" }, { "code": "# python implementation of particle swarm optimization (PSO)# minimizing rastrigin and sphere function import randomimport math # cos() for Rastriginimport copy # array-copying convenienceimport sys # max float #-------fitness functions--------- # rastrigin functiondef fitness_rastrigin(position): fitnessVal = 0.0 for i in range(len(position)): xi = position[i] fitnessVal += (xi * xi) - (10 * math.cos(2 * math.pi * xi)) + 10 return fitnessVal #sphere functiondef fitness_sphere(position): fitnessVal = 0.0 for i in range(len(position)): xi = position[i] fitnessVal += (xi*xi); return fitnessVal;#------------------------- #particle classclass Particle: def __init__(self, fitness, dim, minx, maxx, seed): self.rnd = random.Random(seed) # initialize position of the particle with 0.0 value self.position = [0.0 for i in range(dim)] # initialize velocity of the particle with 0.0 value self.velocity = [0.0 for i in range(dim)] # initialize best particle position of the particle with 0.0 value self.best_part_pos = [0.0 for i in range(dim)] # loop dim times to calculate random position and velocity # range of position and velocity is [minx, max] for i in range(dim): self.position[i] = ((maxx - minx) * self.rnd.random() + minx) self.velocity[i] = ((maxx - minx) * self.rnd.random() + minx) # compute fitness of particle self.fitness = fitness(self.position) # curr fitness # initialize best position and fitness of this particle self.best_part_pos = copy.copy(self.position) self.best_part_fitnessVal = self.fitness # best fitness # particle swarm optimization functiondef pso(fitness, max_iter, n, dim, minx, maxx): # hyper parameters w = 0.729 # inertia c1 = 1.49445 # cognitive (particle) c2 = 1.49445 # social (swarm) rnd = random.Random(0) # create n random particles swarm = [Particle(fitness, dim, minx, maxx, i) for i in range(n)] # compute the value of best_position and best_fitness in swarm best_swarm_pos = [0.0 for i in range(dim)] best_swarm_fitnessVal = sys.float_info.max # swarm best # computer best particle of swarm and it's fitness for i in range(n): # check each particle if swarm[i].fitness < best_swarm_fitnessVal: best_swarm_fitnessVal = swarm[i].fitness best_swarm_pos = copy.copy(swarm[i].position) # main loop of pso Iter = 0 while Iter < max_iter: # after every 10 iterations # print iteration number and best fitness value so far if Iter % 10 == 0 and Iter > 1: print(\"Iter = \" + str(Iter) + \" best fitness = %.3f\" % best_swarm_fitnessVal) for i in range(n): # process each particle # compute new velocity of curr particle for k in range(dim): r1 = rnd.random() # randomizations r2 = rnd.random() swarm[i].velocity[k] = ( (w * swarm[i].velocity[k]) + (c1 * r1 * (swarm[i].best_part_pos[k] - swarm[i].position[k])) + (c2 * r2 * (best_swarm_pos[k] -swarm[i].position[k])) ) # if velocity[k] is not in [minx, max] # then clip it if swarm[i].velocity[k] < minx: swarm[i].velocity[k] = minx elif swarm[i].velocity[k] > maxx: swarm[i].velocity[k] = maxx # compute new position using new velocity for k in range(dim): swarm[i].position[k] += swarm[i].velocity[k] # compute fitness of new position swarm[i].fitness = fitness(swarm[i].position) # is new position a new best for the particle? if swarm[i].fitness < swarm[i].best_part_fitnessVal: swarm[i].best_part_fitnessVal = swarm[i].fitness swarm[i].best_part_pos = copy.copy(swarm[i].position) # is new position a new best overall? if swarm[i].fitness < best_swarm_fitnessVal: best_swarm_fitnessVal = swarm[i].fitness best_swarm_pos = copy.copy(swarm[i].position) # for-each particle Iter += 1 #end_while return best_swarm_pos# end pso #----------------------------# Driver code for rastrigin function print(\"\\nBegin particle swarm optimization on rastrigin function\\n\")dim = 3fitness = fitness_rastrigin print(\"Goal is to minimize Rastrigin's function in \" + str(dim) + \" variables\")print(\"Function has known min = 0.0 at (\", end=\"\")for i in range(dim-1): print(\"0, \", end=\"\")print(\"0)\") num_particles = 50max_iter = 100 print(\"Setting num_particles = \" + str(num_particles))print(\"Setting max_iter = \" + str(max_iter))print(\"\\nStarting PSO algorithm\\n\") best_position = pso(fitness, max_iter, num_particles, dim, -10.0, 10.0) print(\"\\nPSO completed\\n\")print(\"\\nBest solution found:\")print([\"%.6f\"%best_position[k] for k in range(dim)])fitnessVal = fitness(best_position)print(\"fitness of best solution = %.6f\" % fitnessVal) print(\"\\nEnd particle swarm for rastrigin function\\n\") print()print() # Driver code for Sphere functionprint(\"\\nBegin particle swarm optimization on sphere function\\n\")dim = 3fitness = fitness_sphere print(\"Goal is to minimize sphere function in \" + str(dim) + \" variables\")print(\"Function has known min = 0.0 at (\", end=\"\")for i in range(dim-1): print(\"0, \", end=\"\")print(\"0)\") num_particles = 50max_iter = 100 print(\"Setting num_particles = \" + str(num_particles))print(\"Setting max_iter = \" + str(max_iter))print(\"\\nStarting PSO algorithm\\n\") best_position = pso(fitness, max_iter, num_particles, dim, -10.0, 10.0) print(\"\\nPSO completed\\n\")print(\"\\nBest solution found:\")print([\"%.6f\"%best_position[k] for k in range(dim)])fitnessVal = fitness(best_position)print(\"fitness of best solution = %.6f\" % fitnessVal) print(\"\\nEnd particle swarm for sphere function\\n\")", "e": 7488, "s": 1701, "text": null }, { "code": null, "e": 8814, "s": 7488, "text": "Begin particle swarm optimization on rastrigin function\n\nGoal is to minimize Rastrigin's function in 3 variables\nFunction has known min = 0.0 at (0, 0, 0)\nSetting num_particles = 50\nSetting max_iter = 100\n\nStarting PSO algorithm\n\nIter = 10 best fitness = 8.463\nIter = 20 best fitness = 4.792\nIter = 30 best fitness = 2.223\nIter = 40 best fitness = 0.251\nIter = 50 best fitness = 0.251\nIter = 60 best fitness = 0.061\nIter = 70 best fitness = 0.007\nIter = 80 best fitness = 0.005\nIter = 90 best fitness = 0.000\n\nPSO completed\n\n\nBest solution found:\n['0.000618', '0.000013', '0.000616']\nfitness of best solution = 0.000151\n\nEnd particle swarm for rastrigin function\n\n\n\n\nBegin particle swarm optimization on sphere function\n\nGoal is to minimize sphere function in 3 variables\nFunction has known min = 0.0 at (0, 0, 0)\nSetting num_particles = 50\nSetting max_iter = 100\n\nStarting PSO algorithm\n\nIter = 10 best fitness = 0.189\nIter = 20 best fitness = 0.012\nIter = 30 best fitness = 0.001\nIter = 40 best fitness = 0.000\nIter = 50 best fitness = 0.000\nIter = 60 best fitness = 0.000\nIter = 70 best fitness = 0.000\nIter = 80 best fitness = 0.000\nIter = 90 best fitness = 0.000\n\nPSO completed\n\n\nBest solution found:\n['0.000004', '-0.000001', '0.000007']\nfitness of best solution = 0.000000\n\nEnd particle swarm for sphere function" }, { "code": null, "e": 9015, "s": 8814, "text": "Research paper citation: Kennedy, J. and Eberhart, R., 1995, November. Particle swarm optimization. In Proceedings of ICNN’95-international conference on neural networks (Vol. 4, pp. 1942-1948). IEEE." }, { "code": null, "e": 9177, "s": 9015, "text": "Inspiration of the implementation: https://fr.mathworks.com/matlabcentral/fileexchange/67429-a-simple-implementation-of-particle-swarm-optimization-pso-algorithm" }, { "code": null, "e": 9193, "s": 9177, "text": "rajeev0719singh" }, { "code": null, "e": 9217, "s": 9193, "text": "Artificial Intelligence" }, { "code": null, "e": 9234, "s": 9217, "text": "Machine Learning" }, { "code": null, "e": 9251, "s": 9234, "text": "Machine Learning" } ]
How to open a website in Android’s web browser from any application?
This example demonstrates how do I open a website in Android’s web browser from any application. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btnAmazon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Amazon" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = findViewById(R.id.btnAmazon); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = "http://www.amazon.com"; startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } }); } } 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": 1284, "s": 1187, "text": "This example demonstrates how do I open a website in Android’s web browser from any application." }, { "code": null, "e": 1413, "s": 1284, "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": 1478, "s": 1413, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2011, "s": 1478, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btnAmazon\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Amazon\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2068, "s": 2011, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2789, "s": 2068, "text": "import android.content.Intent;\nimport android.net.Uri;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Button button = findViewById(R.id.btnAmazon);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String url = \"http://www.amazon.com\";\n startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));\n }\n });\n }\n}" }, { "code": null, "e": 2844, "s": 2789, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3514, "s": 2844, "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": 3861, "s": 3514, "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": 3902, "s": 3861, "text": "Click here to download the project code." } ]
Closest Pair of Points | O(nlogn) Implementation
25 Jun, 2022 We are given an array of n points in the plane, and the problem is to find out the closest pair of points in the array. This problem arises in a number of applications. For example, in air-traffic control, you may want to monitor planes that come too close together, since this may indicate a possible collision. Recall the following formula for distance between two points p and q. We have discussed a divide and conquer solution for this problem. The time complexity of the implementation provided in the previous post is O(n (Logn)^2). In this post, we discuss implementation with time complexity as O(nLogn). Following is a recap of the algorithm discussed in the previous post.1) We sort all points according to x coordinates.2) Divide all points in two halves.3) Recursively find the smallest distances in both subarrays.4) Take the minimum of two smallest distances. Let the minimum be d. 5) Create an array strip[] that stores all points which are at most d distance away from the middle line dividing the two sets.6) Find the smallest distance in strip[]. 7) Return the minimum of d and the smallest distance calculated in above step 6.The great thing about the above approach is, if the array strip[] is sorted according to y coordinate, then we can find the smallest distance in strip[] in O(n) time. In the implementation discussed in the previous post, strip[] was explicitly sorted in every recursive call that made the time complexity O(n (Logn)^2), assuming that the sorting step takes O(nLogn) time. In this post, we discuss an implementation where the time complexity is O(nLogn). The idea is to presort all points according to y coordinates. Let the sorted array be Py[]. When we make recursive calls, we need to divide points of Py[] also according to the vertical line. We can do that by simply processing every point and comparing its x coordinate with x coordinate of the middle line.Following is C++ implementation of O(nLogn) approach. CPP // A divide and conquer program in C++ to find the smallest distance from a// given set of points. #include <iostream>#include <float.h>#include <stdlib.h>#include <math.h>using namespace std; // A structure to represent a Point in 2D planestruct Point{ int x, y;}; /* Following two functions are needed for library function qsort(). Refer: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */ // Needed to sort array of points according to X coordinateint compareX(const void* a, const void* b){ Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->x != p2->x) ? (p1->x - p2->x) : (p1->y - p2->y);}// Needed to sort array of points according to Y coordinateint compareY(const void* a, const void* b){ Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->y != p2->y) ? (p1->y - p2->y) : (p1->x - p2->x);} // A utility function to find the distance between two pointsfloat dist(Point p1, Point p2){ return sqrt( (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) );} // A Brute Force method to return the smallest distance between two points// in P[] of size nfloat bruteForce(Point P[], int n){ float min = FLT_MAX; for (int i = 0; i < n; ++i) for (int j = i+1; j < n; ++j) if (dist(P[i], P[j]) < min) min = dist(P[i], P[j]); return min;} // A utility function to find a minimum of two float valuesfloat min(float x, float y){ return (x < y)? x : y;} // A utility function to find the distance between the closest points of// strip of a given size. All points in strip[] are sorted according to// y coordinate. They all have an upper bound on minimum distance as d.// Note that this method seems to be a O(n^2) method, but it's a O(n)// method as the inner loop runs at most 6 timesfloat stripClosest(Point strip[], int size, float d){ float min = d; // Initialize the minimum distance as d // Pick all points one by one and try the next points till the difference // between y coordinates is smaller than d. // This is a proven fact that this loop runs at most 6 times for (int i = 0; i < size; ++i) for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j) if (dist(strip[i],strip[j]) < min) min = dist(strip[i], strip[j]); return min;} // A recursive function to find the smallest distance. The array Px contains// all points sorted according to x coordinates and Py contains all points// sorted according to y coordinatesfloat closestUtil(Point Px[], Point Py[], int n){ // If there are 2 or 3 points, then use brute force if (n <= 3) return bruteForce(Px, n); // Find the middle point int mid = n/2; Point midPoint = Px[mid]; // Divide points in y sorted array around the vertical line. // Assumption: All x coordinates are distinct. Point Pyl[mid]; // y sorted points on left of vertical line Point Pyr[n-mid]; // y sorted points on right of vertical line int li = 0, ri = 0; // indexes of left and right subarrays for (int i = 0; i < n; i++) { if ((Py[i].x < midPoint.x || (Py[i].x == midPoint.x && Py[i].y < midPoint.y)) && li<mid) Pyl[li++] = Py[i]; else Pyr[ri++] = Py[i]; } // Consider the vertical line passing through the middle point // calculate the smallest distance dl on left of middle point and // dr on right side float dl = closestUtil(Px, Pyl, mid); float dr = closestUtil(Px + mid, Pyr, n-mid); // Find the smaller of two distances float d = min(dl, dr); // Build an array strip[] that contains points close (closer than d) // to the line passing through the middle point Point strip[n]; int j = 0; for (int i = 0; i < n; i++) if (abs(Py[i].x - midPoint.x) < d) strip[j] = Py[i], j++; // Find the closest points in strip. Return the minimum of d and closest // distance is strip[] return stripClosest(strip, j, d);} // The main function that finds the smallest distance// This method mainly uses closestUtil()float closest(Point P[], int n){ Point Px[n]; Point Py[n]; for (int i = 0; i < n; i++) { Px[i] = P[i]; Py[i] = P[i]; } qsort(Px, n, sizeof(Point), compareX); qsort(Py, n, sizeof(Point), compareY); // Use recursive function closestUtil() to find the smallest distance return closestUtil(Px, Py, n);} // Driver program to test above functionsint main(){ Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; int n = sizeof(P) / sizeof(P[0]); cout << "The smallest distance is " << closest(P, n); return 0;} The smallest distance is 1.41421 Time Complexity:Let Time complexity of above algorithm be T(n). Let us assume that we use a O(nLogn) sorting algorithm. The above algorithm divides all points in two sets and recursively calls for two sets. After dividing, it finds the strip in O(n) time. Also, it takes O(n) time to divide the Py array around the mid vertical line. Finally finds the closest points in strip in O(n) time. So T(n) can be expressed as follows T(n) = 2T(n/2) + O(n) + O(n) + O(n) T(n) = 2T(n/2) + O(n) T(n) = T(nLogn) Auxiliary Space: O(log n), as implicit stack is created during recursive callsReferences: http://www.cs.umd.edu/class/fall2013/cmsc451/Lects/lect10.pdf http://www.youtube.com/watch?v=vS4Zn1a9KUc http://www.youtube.com/watch?v=T3T7T8Ym20M http://en.wikipedia.org/wiki/Closest_pair_of_points_problemPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Akanksha_Rai Milan1999 sabitjehadulkarim _shinchancode Divide and Conquer Geometric Divide and Conquer Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Jun, 2022" }, { "code": null, "e": 2014, "s": 52, "text": "We are given an array of n points in the plane, and the problem is to find out the closest pair of points in the array. This problem arises in a number of applications. For example, in air-traffic control, you may want to monitor planes that come too close together, since this may indicate a possible collision. Recall the following formula for distance between two points p and q. We have discussed a divide and conquer solution for this problem. The time complexity of the implementation provided in the previous post is O(n (Logn)^2). In this post, we discuss implementation with time complexity as O(nLogn). Following is a recap of the algorithm discussed in the previous post.1) We sort all points according to x coordinates.2) Divide all points in two halves.3) Recursively find the smallest distances in both subarrays.4) Take the minimum of two smallest distances. Let the minimum be d. 5) Create an array strip[] that stores all points which are at most d distance away from the middle line dividing the two sets.6) Find the smallest distance in strip[]. 7) Return the minimum of d and the smallest distance calculated in above step 6.The great thing about the above approach is, if the array strip[] is sorted according to y coordinate, then we can find the smallest distance in strip[] in O(n) time. In the implementation discussed in the previous post, strip[] was explicitly sorted in every recursive call that made the time complexity O(n (Logn)^2), assuming that the sorting step takes O(nLogn) time. In this post, we discuss an implementation where the time complexity is O(nLogn). The idea is to presort all points according to y coordinates. Let the sorted array be Py[]. When we make recursive calls, we need to divide points of Py[] also according to the vertical line. We can do that by simply processing every point and comparing its x coordinate with x coordinate of the middle line.Following is C++ implementation of O(nLogn) approach. " }, { "code": null, "e": 2018, "s": 2014, "text": "CPP" }, { "code": "// A divide and conquer program in C++ to find the smallest distance from a// given set of points. #include <iostream>#include <float.h>#include <stdlib.h>#include <math.h>using namespace std; // A structure to represent a Point in 2D planestruct Point{ int x, y;}; /* Following two functions are needed for library function qsort(). Refer: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */ // Needed to sort array of points according to X coordinateint compareX(const void* a, const void* b){ Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->x != p2->x) ? (p1->x - p2->x) : (p1->y - p2->y);}// Needed to sort array of points according to Y coordinateint compareY(const void* a, const void* b){ Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->y != p2->y) ? (p1->y - p2->y) : (p1->x - p2->x);} // A utility function to find the distance between two pointsfloat dist(Point p1, Point p2){ return sqrt( (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) );} // A Brute Force method to return the smallest distance between two points// in P[] of size nfloat bruteForce(Point P[], int n){ float min = FLT_MAX; for (int i = 0; i < n; ++i) for (int j = i+1; j < n; ++j) if (dist(P[i], P[j]) < min) min = dist(P[i], P[j]); return min;} // A utility function to find a minimum of two float valuesfloat min(float x, float y){ return (x < y)? x : y;} // A utility function to find the distance between the closest points of// strip of a given size. All points in strip[] are sorted according to// y coordinate. They all have an upper bound on minimum distance as d.// Note that this method seems to be a O(n^2) method, but it's a O(n)// method as the inner loop runs at most 6 timesfloat stripClosest(Point strip[], int size, float d){ float min = d; // Initialize the minimum distance as d // Pick all points one by one and try the next points till the difference // between y coordinates is smaller than d. // This is a proven fact that this loop runs at most 6 times for (int i = 0; i < size; ++i) for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j) if (dist(strip[i],strip[j]) < min) min = dist(strip[i], strip[j]); return min;} // A recursive function to find the smallest distance. The array Px contains// all points sorted according to x coordinates and Py contains all points// sorted according to y coordinatesfloat closestUtil(Point Px[], Point Py[], int n){ // If there are 2 or 3 points, then use brute force if (n <= 3) return bruteForce(Px, n); // Find the middle point int mid = n/2; Point midPoint = Px[mid]; // Divide points in y sorted array around the vertical line. // Assumption: All x coordinates are distinct. Point Pyl[mid]; // y sorted points on left of vertical line Point Pyr[n-mid]; // y sorted points on right of vertical line int li = 0, ri = 0; // indexes of left and right subarrays for (int i = 0; i < n; i++) { if ((Py[i].x < midPoint.x || (Py[i].x == midPoint.x && Py[i].y < midPoint.y)) && li<mid) Pyl[li++] = Py[i]; else Pyr[ri++] = Py[i]; } // Consider the vertical line passing through the middle point // calculate the smallest distance dl on left of middle point and // dr on right side float dl = closestUtil(Px, Pyl, mid); float dr = closestUtil(Px + mid, Pyr, n-mid); // Find the smaller of two distances float d = min(dl, dr); // Build an array strip[] that contains points close (closer than d) // to the line passing through the middle point Point strip[n]; int j = 0; for (int i = 0; i < n; i++) if (abs(Py[i].x - midPoint.x) < d) strip[j] = Py[i], j++; // Find the closest points in strip. Return the minimum of d and closest // distance is strip[] return stripClosest(strip, j, d);} // The main function that finds the smallest distance// This method mainly uses closestUtil()float closest(Point P[], int n){ Point Px[n]; Point Py[n]; for (int i = 0; i < n; i++) { Px[i] = P[i]; Py[i] = P[i]; } qsort(Px, n, sizeof(Point), compareX); qsort(Py, n, sizeof(Point), compareY); // Use recursive function closestUtil() to find the smallest distance return closestUtil(Px, Py, n);} // Driver program to test above functionsint main(){ Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; int n = sizeof(P) / sizeof(P[0]); cout << \"The smallest distance is \" << closest(P, n); return 0;}", "e": 6653, "s": 2018, "text": null }, { "code": null, "e": 6686, "s": 6653, "text": "The smallest distance is 1.41421" }, { "code": null, "e": 7186, "s": 6686, "text": "Time Complexity:Let Time complexity of above algorithm be T(n). Let us assume that we use a O(nLogn) sorting algorithm. The above algorithm divides all points in two sets and recursively calls for two sets. After dividing, it finds the strip in O(n) time. Also, it takes O(n) time to divide the Py array around the mid vertical line. Finally finds the closest points in strip in O(n) time. So T(n) can be expressed as follows T(n) = 2T(n/2) + O(n) + O(n) + O(n) T(n) = 2T(n/2) + O(n) T(n) = T(nLogn)" }, { "code": null, "e": 7608, "s": 7186, "text": "Auxiliary Space: O(log n), as implicit stack is created during recursive callsReferences: http://www.cs.umd.edu/class/fall2013/cmsc451/Lects/lect10.pdf http://www.youtube.com/watch?v=vS4Zn1a9KUc http://www.youtube.com/watch?v=T3T7T8Ym20M http://en.wikipedia.org/wiki/Closest_pair_of_points_problemPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 7621, "s": 7608, "text": "Akanksha_Rai" }, { "code": null, "e": 7631, "s": 7621, "text": "Milan1999" }, { "code": null, "e": 7649, "s": 7631, "text": "sabitjehadulkarim" }, { "code": null, "e": 7663, "s": 7649, "text": "_shinchancode" }, { "code": null, "e": 7682, "s": 7663, "text": "Divide and Conquer" }, { "code": null, "e": 7692, "s": 7682, "text": "Geometric" }, { "code": null, "e": 7711, "s": 7692, "text": "Divide and Conquer" }, { "code": null, "e": 7721, "s": 7711, "text": "Geometric" } ]
Sudoku | Backtracking-7
17 Jun, 2022 Given a partially filled 9×9 2D array ‘grid[9][9]’, the goal is to assign digits (from 1 to 9) to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one instance of the digits from 1 to 9. Example: Input: grid = { {3, 0, 6, 5, 0, 8, 4, 0, 0}, {5, 2, 0, 0, 0, 0, 0, 0, 0}, {0, 8, 7, 0, 0, 0, 0, 3, 1}, {0, 0, 3, 0, 1, 0, 0, 8, 0}, {9, 0, 0, 8, 6, 3, 0, 0, 5}, {0, 5, 0, 0, 9, 0, 6, 0, 0}, {1, 3, 0, 0, 0, 0, 2, 5, 0}, {0, 0, 0, 0, 0, 0, 0, 7, 4}, {0, 0, 5, 2, 0, 6, 3, 0, 0} } Output: 3 1 6 5 7 8 4 9 2 5 2 9 1 3 4 7 6 8 4 8 7 6 2 9 5 3 1 2 6 3 4 1 5 9 8 7 9 7 4 8 6 3 1 2 5 8 5 1 7 9 2 6 4 3 1 3 8 9 4 7 2 5 6 6 9 2 3 5 1 8 7 4 7 4 5 2 8 6 3 1 9 Explanation: Each row, column and 3*3 box of the output matrix contains unique numbers. Input: grid = { { 3, 1, 6, 5, 7, 8, 4, 9, 2 }, { 5, 2, 9, 1, 3, 4, 7, 6, 8 }, { 4, 8, 7, 6, 2, 9, 5, 3, 1 }, { 2, 6, 3, 0, 1, 5, 9, 8, 7 }, { 9, 7, 4, 8, 6, 0, 1, 2, 5 }, { 8, 5, 1, 7, 9, 2, 6, 4, 3 }, { 1, 3, 8, 0, 4, 7, 2, 0, 6 }, { 6, 9, 2, 3, 5, 1, 8, 7, 4 }, { 7, 4, 5, 0, 8, 6, 3, 1, 0 } }; Output: 3 1 6 5 7 8 4 9 2 5 2 9 1 3 4 7 6 8 4 8 7 6 2 9 5 3 1 2 6 3 4 1 5 9 8 7 9 7 4 8 6 3 1 2 5 8 5 1 7 9 2 6 4 3 1 3 8 9 4 7 2 5 6 6 9 2 3 5 1 8 7 4 7 4 5 2 8 6 3 1 9 Explanation: Each row, column and 3*3 box of the output matrix contains unique numbers. Method 1: Simple. Approach: The naive approach is to generate all possible configurations of numbers from 1 to 9 to fill the empty cells. Try every configuration one by one until the correct configuration is found, i.e. for every unassigned position fill the position with a number from 1 to 9. After filling all the unassigned position check if the matrix is safe or not. If safe print else recurs for other cases. 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. Algorithm: Create a function that checks if the given matrix is valid sudoku or not. Keep Hashmap for the row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true;Create a recursive function that takes a grid and the current row and column index.Check some base cases. If the index is at the end of the matrix, i.e. i=N-1 and j=N then check if the grid is safe or not, if safe print the grid and return true else return false. The other base case is when the value of column is N, i.e j = N, then move to next row, i.e. i++ and j = 0.if the current index is not assigned then fill the element from 1 to 9 and recur for all 9 cases with the index of next element, i.e. i, j+1. if the recursive call returns true then break the loop and return true.if the current index is assigned then call the recursive function with index of next element, i.e. i, j+1 Create a function that checks if the given matrix is valid sudoku or not. Keep Hashmap for the row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true; Create a recursive function that takes a grid and the current row and column index. Check some base cases. If the index is at the end of the matrix, i.e. i=N-1 and j=N then check if the grid is safe or not, if safe print the grid and return true else return false. The other base case is when the value of column is N, i.e j = N, then move to next row, i.e. i++ and j = 0. if the current index is not assigned then fill the element from 1 to 9 and recur for all 9 cases with the index of next element, i.e. i, j+1. if the recursive call returns true then break the loop and return true. if the current index is assigned then call the recursive function with index of next element, i.e. i, j+1 Implementation: C++ C Java Python3 C# Javascript #include <iostream> using namespace std; // N is the size of the 2D matrix N*N#define N 9 /* A utility function to print grid */void print(int arr[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << arr[i][j] << " "; cout << endl; }} // Checks whether it will be// legal to assign num to the// given row, colbool isSafe(int grid[N][N], int row, int col, int num){ // Check if we find the same num // in the similar row , we // return false for (int x = 0; x <= 8; x++) if (grid[row][x] == num) return false; // Check if we find the same num in // the similar column , we // return false for (int x = 0; x <= 8; x++) if (grid[x][col] == num) return false; // Check if we find the same num in // the particular 3*3 matrix, // we return false int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow][j + startCol] == num) return false; return true;} /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */bool solveSudoku(int grid[N][N], int row, int col){ // Check if we have reached the 8th // row and 9th column (0 // indexed matrix) , we are // returning true to avoid // further backtracking if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row and // column start from 0 if (col == N) { row++; col = 0; } // Check if the current position of // the grid already contains // value >0, we iterate for next column if (grid[row][col] > 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num <= N; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we // move to next column if (isSafe(grid, row, col, num)) { /* Assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row][col] = num; // Checking for next possibility with next // column if (solveSudoku(grid, row, col + 1)) return true; } // Removing the assigned num , // since our assumption // was wrong , and we go for // next assumption with // diff num value grid[row][col] = 0; } return false;} // Driver Codeint main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)) print(grid); else cout << "no solution exists " << endl; return 0; // This is code is contributed by Pradeep Mondal P} #include <stdio.h>#include <stdlib.h> // N is the size of the 2D matrix N*N#define N 9 /* A utility function to print grid */void print(int arr[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%d ",arr[i][j]); printf("\n"); }} // Checks whether it will be legal // to assign num to the// given row, colint isSafe(int grid[N][N], int row, int col, int num){ // Check if we find the same num // in the similar row , we return 0 for (int x = 0; x <= 8; x++) if (grid[row][x] == num) return 0; // Check if we find the same num in the // similar column , we return 0 for (int x = 0; x <= 8; x++) if (grid[x][col] == num) return 0; // Check if we find the same num in the // particular 3*3 matrix, we return 0 int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow][j + startCol] == num) return 0; return 1;} /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */int solveSudoku(int grid[N][N], int row, int col){ // Check if we have reached the 8th row // and 9th column (0 // indexed matrix) , we are // returning true to avoid // further backtracking if (row == N - 1 && col == N) return 1; // Check if column value becomes 9 , // we move to next row and // column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already contains // value >0, we iterate for next column if (grid[row][col] > 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num <= N; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we move to next column if (isSafe(grid, row, col, num)==1) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row][col] = num; // Checking for next possibility with next // column if (solveSudoku(grid, row, col + 1)==1) return 1; } // Removing the assigned num , // since our assumption // was wrong , and we go for next // assumption with // diff num value grid[row][col] = 0; } return 0;} int main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)==1) print(grid); else printf("No solution exists"); return 0; // This is code is contributed by Pradeep Mondal P} // Java program for above approachpublic class Sudoku { // N is the size of the 2D matrix N*N static int N = 9; /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ static boolean solveSudoku(int grid[][], int row, int col) { /*if we have reached the 8th row and 9th column (0 indexed matrix) , we are returning true to avoid further backtracking */ if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row // and column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already // contains value >0, we iterate // for next column if (grid[row][col] != 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num < 10; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we move to next column if (isSafe(grid, row, col, num)) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row][col] = num; // Checking for next // possibility with next column if (solveSudoku(grid, row, col + 1)) return true; } /* removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value */ grid[row][col] = 0; } return false; } /* A utility function to print grid */ static void print(int[][] grid) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(grid[i][j] + " "); System.out.println(); } } // Check whether it will be legal // to assign num to the // given row, col static boolean isSafe(int[][] grid, int row, int col, int num) { // Check if we find the same num // in the similar row , we // return false for (int x = 0; x <= 8; x++) if (grid[row][x] == num) return false; // Check if we find the same num // in the similar column , // we return false for (int x = 0; x <= 8; x++) if (grid[x][col] == num) return false; // Check if we find the same num // in the particular 3*3 // matrix, we return false int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow][j + startCol] == num) return false; return true; } // Driver Code public static void main(String[] args) { int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)) print(grid); else System.out.println("No Solution exists"); } // This is code is contributed by Pradeep Mondal P} # N is the size of the 2D matrix N*NN = 9 # A utility function to print griddef printing(arr): for i in range(N): for j in range(N): print(arr[i][j], end = " ") print() # Checks whether it will be# legal to assign num to the# given row, coldef isSafe(grid, row, col, num): # Check if we find the same num # in the similar row , we # return false for x in range(9): if grid[row][x] == num: return False # Check if we find the same num in # the similar column , we # return false for x in range(9): if grid[x][col] == num: return False # Check if we find the same num in # the particular 3*3 matrix, # we return false startRow = row - row % 3 startCol = col - col % 3 for i in range(3): for j in range(3): if grid[i + startRow][j + startCol] == num: return False return True # Takes a partially filled-in grid and attempts# to assign values to all unassigned locations in# such a way to meet the requirements for# Sudoku solution (non-duplication across rows,# columns, and boxes) */def solveSudoku(grid, row, col): # Check if we have reached the 8th # row and 9th column (0 # indexed matrix) , we are # returning true to avoid # further backtracking if (row == N - 1 and col == N): return True # Check if column value becomes 9 , # we move to next row and # column start from 0 if col == N: row += 1 col = 0 # Check if the current position of # the grid already contains # value >0, we iterate for next column if grid[row][col] > 0: return solveSudoku(grid, row, col + 1) for num in range(1, N + 1, 1): # Check if it is safe to place # the num (1-9) in the # given row ,col ->we # move to next column if isSafe(grid, row, col, num): # Assigning the num in # the current (row,col) # position of the grid # and assuming our assigned # num in the position # is correct grid[row][col] = num # Checking for next possibility with next # column if solveSudoku(grid, row, col + 1): return True # Removing the assigned num , # since our assumption # was wrong , and we go for # next assumption with # diff num value grid[row][col] = 0 return False # Driver Code # 0 means unassigned cellsgrid = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] if (solveSudoku(grid, 0, 0)): printing(grid)else: print("no solution exists ") # This code is contributed by sudhanshgupta2019a // C# program for above approachusing System;class GFG { // N is the size of the 2D matrix N*N static int N = 9; /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ static bool solveSudoku(int[,] grid, int row, int col) { /*if we have reached the 8th row and 9th column (0 indexed matrix) , we are returning true to avoid further backtracking */ if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row // and column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already // contains value >0, we iterate // for next column if (grid[row,col] != 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num < 10; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we move to next column if (isSafe(grid, row, col, num)) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row,col] = num; // Checking for next // possibility with next column if (solveSudoku(grid, row, col + 1)) return true; } /* removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value */ grid[row,col] = 0; } return false; } /* A utility function to print grid */ static void print(int[,] grid) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(grid[i,j] + " "); Console.WriteLine(); } } // Check whether it will be legal // to assign num to the // given row, col static bool isSafe(int[,] grid, int row, int col, int num) { // Check if we find the same num // in the similar row , we // return false for (int x = 0; x <= 8; x++) if (grid[row,x] == num) return false; // Check if we find the same num // in the similar column , // we return false for (int x = 0; x <= 8; x++) if (grid[x,col] == num) return false; // Check if we find the same num // in the particular 3*3 // matrix, we return false int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow,j + startCol] == num) return false; return true; } // Driver code static void Main() { int[,] grid = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)) print(grid); else Console.WriteLine("No Solution exists"); }} // This code is contributed by divyesh072019. <script> // Javascript program for above approach // N is the size of the 2D matrix N*Nlet N = 9; /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */function solveSudoku(grid, row, col){ /* If we have reached the 8th row and 9th column (0 indexed matrix) , we are returning true to avoid further backtracking */ if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row // and column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already // contains value >0, we iterate // for next column if (grid[row][col] != 0) return solveSudoku(grid, row, col + 1); for(let num = 1; num < 10; num++) { // Check if it is safe to place // the num (1-9) in the given // row ,col ->we move to next column if (isSafe(grid, row, col, num)) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row][col] = num; // Checking for next // possibility with next column if (solveSudoku(grid, row, col + 1)) return true; } /* removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value */ grid[row][col] = 0; } return false;} /* A utility function to print grid */function print(grid){ for(let i = 0; i < N; i++) { for(let j = 0; j < N; j++) document.write(grid[i][j] + " "); document.write("<br>"); }} // Check whether it will be legal// to assign num to the// given row, colfunction isSafe(grid, row, col, num){ // Check if we find the same num // in the similar row , we // return false for(let x = 0; x <= 8; x++) if (grid[row][x] == num) return false; // Check if we find the same num // in the similar column , // we return false for(let x = 0; x <= 8; x++) if (grid[x][col] == num) return false; // Check if we find the same num // in the particular 3*3 // matrix, we return false let startRow = row - row % 3, startCol = col - col % 3; for(let i = 0; i < 3; i++) for(let j = 0; j < 3; j++) if (grid[i + startRow][j + startCol] == num) return false; return true;} // Driver Codelet grid = [ [ 3, 0, 6, 5, 0, 8, 4, 0, 0 ], [ 5, 2, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 8, 7, 0, 0, 0, 0, 3, 1 ], [ 0, 0, 3, 0, 1, 0, 0, 8, 0 ], [ 9, 0, 0, 8, 6, 3, 0, 0, 5 ], [ 0, 5, 0, 0, 9, 0, 6, 0, 0 ], [ 1, 3, 0, 0, 0, 0, 2, 5, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 7, 4 ], [ 0, 0, 5, 2, 0, 6, 3, 0, 0 ] ] if (solveSudoku(grid, 0, 0)) print(grid)else document.write("no solution exists ") // This code is contributed by rag2127 </script> 3 1 6 5 7 8 4 9 2 5 2 9 1 3 4 7 6 8 4 8 7 6 2 9 5 3 1 2 6 3 4 1 5 9 8 7 9 7 4 8 6 3 1 2 5 8 5 1 7 9 2 6 4 3 1 3 8 9 4 7 2 5 6 6 9 2 3 5 1 8 7 4 7 4 5 2 8 6 3 1 9 Complexity Analysis: Time complexity: O(9^(n*n)). For every unassigned index, there are 9 possible options so the time complexity is O(9^(n*n)). Space Complexity: O(n*n). To store the output array a matrix is needed. Method 2: Backtracking. Approach: Like all other Backtracking problems, Sudoku can be solved by one by one assigning numbers to empty cells. Before assigning a number, check whether it is safe to assign. Check that the same number is not present in the current row, current column and current 3X3 subgrid. After checking for safety, assign the number, and recursively check whether this assignment leads to a solution or not. If the assignment doesn’t lead to a solution, then try the next number for the current empty cell. And if none of the number (1 to 9) leads to a solution, return false and print no solution exists. Algorithm: Create a function that checks after assigning the current index the grid becomes unsafe or not. Keep Hashmap for a row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true; hashMap can be avoided by using loops.Create a recursive function that takes a grid.Check for any unassigned location. If present then assign a number from 1 to 9, check if assigning the number to current index makes the grid unsafe or not, if safe then recursively call the function for all safe cases from 0 to 9. if any recursive call returns true, end the loop and return true. If no recursive call returns true then return false.If there is no unassigned location then return true. Create a function that checks after assigning the current index the grid becomes unsafe or not. Keep Hashmap for a row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true; hashMap can be avoided by using loops. Create a recursive function that takes a grid. Check for any unassigned location. If present then assign a number from 1 to 9, check if assigning the number to current index makes the grid unsafe or not, if safe then recursively call the function for all safe cases from 0 to 9. if any recursive call returns true, end the loop and return true. If no recursive call returns true then return false. If there is no unassigned location then return true. Implementation: C++ C Java Python C# Javascript // A Backtracking program in// C++ to solve Sudoku problem#include <bits/stdc++.h>using namespace std; // UNASSIGNED is used for empty// cells in sudoku grid#define UNASSIGNED 0 // N is used for the size of Sudoku grid.// Size will be NxN#define N 9 // This function finds an entry in grid// that is still unassignedbool FindUnassignedLocation(int grid[N][N], int& row, int& col); // Checks whether it will be legal// to assign num to the given row, colbool isSafe(int grid[N][N], int row, int col, int num); /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */bool SolveSudoku(int grid[N][N]){ int row, col; // If there is no unassigned location, // we are done if (!FindUnassignedLocation(grid, row, col)) // success! return true; // Consider digits 1 to 9 for (int num = 1; num <= 9; num++) { // Check if looks promising if (isSafe(grid, row, col, num)) { // Make tentative assignment grid[row][col] = num; // Return, if success if (SolveSudoku(grid)) return true; // Failure, unmake & try again grid[row][col] = UNASSIGNED; } } // This triggers backtracking return false;} /* Searches the grid to find an entry that isstill unassigned. If found, the referenceparameters row, col will be set the locationthat is unassigned, and true is returned.If no unassigned entries remain, false is returned. */bool FindUnassignedLocation(int grid[N][N], int& row, int& col){ for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (grid[row][col] == UNASSIGNED) return true; return false;} /* Returns a boolean which indicates whetheran assigned entry in the specified row matchesthe given number. */bool UsedInRow(int grid[N][N], int row, int num){ for (int col = 0; col < N; col++) if (grid[row][col] == num) return true; return false;} /* Returns a boolean which indicates whetheran assigned entry in the specified columnmatches the given number. */bool UsedInCol(int grid[N][N], int col, int num){ for (int row = 0; row < N; row++) if (grid[row][col] == num) return true; return false;} /* Returns a boolean which indicates whetheran assigned entry within the specified 3x3 boxmatches the given number. */bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num){ for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) if (grid[row + boxStartRow] [col + boxStartCol] == num) return true; return false;} /* Returns a boolean which indicates whetherit will be legal to assign num to the givenrow, col location. */bool isSafe(int grid[N][N], int row, int col, int num){ /* Check if 'num' is not already placed in current row, current column and current 3x3 box */ return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) && !UsedInBox(grid, row - row % 3, col - col % 3, num) && grid[row][col] == UNASSIGNED;} /* A utility function to print grid */void printGrid(int grid[N][N]){ for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) cout << grid[row][col] << " "; cout << endl; }} // Driver Codeint main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (SolveSudoku(grid) == true) printGrid(grid); else cout << "No solution exists"; return 0;} // This is code is contributed by rathbhupendra // A Backtracking program in C// to solve Sudoku problem#include <stdio.h> // UNASSIGNED is used for empty// cells in sudoku grid#define UNASSIGNED 0 // N is used for the size of// Sudoku grid. The size will be NxN#define N 9 // This function finds an entry// in grid that is still unassignedbool FindUnassignedLocation(int grid[N][N], int& row, int& col); // Checks whether it will be legal// to assign num to the given row, colbool isSafe(int grid[N][N], int row, int col, int num); /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */bool SolveSudoku(int grid[N][N]){ int row, col; // Check If there is no unassigned // location, we are done if (!FindUnassignedLocation(grid, row, col)) return true; // success! //Cconsider digits 1 to 9 for (int num = 1; num <= 9; num++) { // Check if looks promising if (isSafe(grid, row, col, num)) { // Make tentative assignment grid[row][col] = num; // Return, if success, yay! if (SolveSudoku(grid)) return true; // Failure, unmake & try again grid[row][col] = UNASSIGNED; } } // This triggers backtracking return false;} /* Searches the grid to find an entry that is still unassigned. If found, the reference parameters row, col will be set the location that is unassigned, and true is returned. If no unassigned entries remain, false is returned. */bool FindUnassignedLocation( int grid[N][N], int& row, int& col){ for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (grid[row][col] == UNASSIGNED) return true; return false;} /* Returns a boolean which indicates whether an assigned entry in the specified row matches the given number. */bool UsedInRow( int grid[N][N], int row, int num){ for (int col = 0; col < N; col++) if (grid[row][col] == num) return true; return false;} /* Returns a boolean which indicates whether an assigned entry in the specified column matches the given number. */bool UsedInCol( int grid[N][N], int col, int num){ for (int row = 0; row < N; row++) if (grid[row][col] == num) return true; return false;} /* Returns a boolean which indicates whether an assigned entry within the specified 3x3 box matches the given number. */bool UsedInBox( int grid[N][N], int boxStartRow, int boxStartCol, int num){ for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) if ( grid[row + boxStartRow] [col + boxStartCol] == num) return true; return false;} /* Returns a boolean which indicateswhether it will be legal to assign num to the given row, col location. */bool isSafe( int grid[N][N], int row, int col, int num){ /* Check if 'num' is not already placed in current row, current column and current 3x3 box */ return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) && !UsedInBox(grid, row - row % 3, col - col % 3, num) && grid[row][col] == UNASSIGNED;} /* A utility function to print grid */void printGrid(int grid[N][N]){ for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) printf("%2d", grid[row][col]); printf("\n"); }} /* Driver Program to test above functions */int main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (SolveSudoku(grid) == true) printGrid(grid); else printf("No solution exists"); return 0;} /* A Backtracking program inJava to solve Sudoku problem */class GFG{ public static boolean isSafe(int[][] board, int row, int col, int num) { // Row has the unique (row-clash) for (int d = 0; d < board.length; d++) { // Check if the number we are trying to // place is already present in // that row, return false; if (board[row][d] == num) { return false; } } // Column has the unique numbers (column-clash) for (int r = 0; r < board.length; r++) { // Check if the number // we are trying to // place is already present in // that column, return false; if (board[r][col] == num) { return false; } } // Corresponding square has // unique number (box-clash) int sqrt = (int)Math.sqrt(board.length); int boxRowStart = row - row % sqrt; int boxColStart = col - col % sqrt; for (int r = boxRowStart; r < boxRowStart + sqrt; r++) { for (int d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r][d] == num) { return false; } } } // if there is no clash, it's safe return true; } public static boolean solveSudoku( int[][] board, int n) { int row = -1; int col = -1; boolean isEmpty = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 0) { row = i; col = j; // We still have some remaining // missing values in Sudoku isEmpty = false; break; } } if (!isEmpty) { break; } } // No empty space left if (isEmpty) { return true; } // Else for each-row backtrack for (int num = 1; num <= n; num++) { if (isSafe(board, row, col, num)) { board[row][col] = num; if (solveSudoku(board, n)) { // print(board, n); return true; } else { // replace it board[row][col] = 0; } } } return false; } public static void print( int[][] board, int N) { // We got the answer, just print it for (int r = 0; r < N; r++) { for (int d = 0; d < N; d++) { System.out.print(board[r][d]); System.out.print(" "); } System.out.print("\n"); if ((r + 1) % (int)Math.sqrt(N) == 0) { System.out.print(""); } } } // Driver Code public static void main(String args[]) { int[][] board = new int[][] { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; int N = board.length; if (solveSudoku(board, N)) { // print solution print(board, N); } else { System.out.println("No solution"); } }} // This code is contributed// by MohanDas # A Backtracking program# in Python to solve Sudoku problem # A Utility Function to print the Griddef print_grid(arr): for i in range(9): for j in range(9): print arr[i][j], print ('n') # Function to Find the entry in# the Grid that is still not used# Searches the grid to find an# entry that is still unassigned. If# found, the reference parameters# row, col will be set the location# that is unassigned, and true is# returned. If no unassigned entries# remains, false is returned.# 'l' is a list variable that has# been passed from the solve_sudoku function# to keep track of incrementation# of Rows and Columnsdef find_empty_location(arr, l): for row in range(9): for col in range(9): if(arr[row][col]== 0): l[0]= row l[1]= col return True return False # Returns a boolean which indicates# whether any assigned entry# in the specified row matches# the given number.def used_in_row(arr, row, num): for i in range(9): if(arr[row][i] == num): return True return False # Returns a boolean which indicates# whether any assigned entry# in the specified column matches# the given number.def used_in_col(arr, col, num): for i in range(9): if(arr[i][col] == num): return True return False # Returns a boolean which indicates# whether any assigned entry# within the specified 3x3 box# matches the given numberdef used_in_box(arr, row, col, num): for i in range(3): for j in range(3): if(arr[i + row][j + col] == num): return True return False # Checks whether it will be legal# to assign num to the given row, col# Returns a boolean which indicates# whether it will be legal to assign# num to the given row, col location.def check_location_is_safe(arr, row, col, num): # Check if 'num' is not already # placed in current row, # current column and current 3x3 box return not used_in_row(arr, row, num) and not used_in_col(arr, col, num) and not used_in_box(arr, row - row % 3, col - col % 3, num) # Takes a partially filled-in grid# and attempts to assign values to# all unassigned locations in such a# way to meet the requirements# for Sudoku solution (non-duplication# across rows, columns, and boxes)def solve_sudoku(arr): # 'l' is a list variable that keeps the # record of row and col in # find_empty_location Function l =[0, 0] # If there is no unassigned # location, we are done if(not find_empty_location(arr, l)): return True # Assigning list values to row and col # that we got from the above Function row = l[0] col = l[1] # consider digits 1 to 9 for num in range(1, 10): # if looks promising if(check_location_is_safe(arr, row, col, num)): # make tentative assignment arr[row][col]= num # return, if success, # ya ! if(solve_sudoku(arr)): return True # failure, unmake & try again arr[row][col] = 0 # this triggers backtracking return False # Driver main function to test above functionsif __name__=="__main__": # creating a 2D array for the grid grid =[[0 for x in range(9)]for y in range(9)] # assigning values to the grid grid =[[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] # if success print the grid if(solve_sudoku(grid)): print_grid(grid) else: print "No solution exists" # The above code has been contributed by Harshit Sidhwa. /* A Backtracking program inC# to solve Sudoku problem */using System; class GFG{ public static bool isSafe(int[, ] board, int row, int col, int num) { // Row has the unique (row-clash) for (int d = 0; d < board.GetLength(0); d++) { // Check if the number // we are trying to // place is already present in // that row, return false; if (board[row, d] == num) { return false; } } // Column has the unique numbers (column-clash) for (int r = 0; r < board.GetLength(0); r++) { // Check if the number // we are trying to // place is already present in // that column, return false; if (board[r, col] == num) { return false; } } // corresponding square has // unique number (box-clash) int sqrt = (int)Math.Sqrt(board.GetLength(0)); int boxRowStart = row - row % sqrt; int boxColStart = col - col % sqrt; for (int r = boxRowStart; r < boxRowStart + sqrt; r++) { for (int d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r, d] == num) { return false; } } } // if there is no clash, it's safe return true; } public static bool solveSudoku(int[, ] board, int n) { int row = -1; int col = -1; bool isEmpty = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i, j] == 0) { row = i; col = j; // We still have some remaining // missing values in Sudoku isEmpty = false; break; } } if (!isEmpty) { break; } } // no empty space left if (isEmpty) { return true; } // else for each-row backtrack for (int num = 1; num <= n; num++) { if (isSafe(board, row, col, num)) { board[row, col] = num; if (solveSudoku(board, n)) { // Print(board, n); return true; } else { // Replace it board[row, col] = 0; } } } return false; } public static void print(int[, ] board, int N) { // We got the answer, just print it for (int r = 0; r < N; r++) { for (int d = 0; d < N; d++) { Console.Write(board[r, d]); Console.Write(" "); } Console.Write("\n"); if ((r + 1) % (int)Math.Sqrt(N) == 0) { Console.Write(""); } } } // Driver Code public static void Main(String[] args) { int[, ] board = new int[, ] { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; int N = board.GetLength(0); if (solveSudoku(board, N)) { // print solution print(board, N); } else { Console.Write("No solution"); } }} // This code has been contributed by 29AjayKumar <script> /* A Backtracking program inJavascript to solve Sudoku problem */ function isSafe(board, row, col, num){ // Row has the unique (row-clash) for(let d = 0; d < board.length; d++) { // Check if the number we are trying to // place is already present in // that row, return false; if (board[row][d] == num) { return false; } } // Column has the unique numbers (column-clash) for(let r = 0; r < board.length; r++) { // Check if the number // we are trying to // place is already present in // that column, return false; if (board[r][col] == num) { return false; } } // Corresponding square has // unique number (box-clash) let sqrt = Math.floor(Math.sqrt(board.length)); let boxRowStart = row - row % sqrt; let boxColStart = col - col % sqrt; for(let r = boxRowStart; r < boxRowStart + sqrt; r++) { for(let d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r][d] == num) { return false; } } } // If there is no clash, it's safe return true;} function solveSudoku(board, n){ let row = -1; let col = -1; let isEmpty = true; for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { if (board[i][j] == 0) { row = i; col = j; // We still have some remaining // missing values in Sudoku isEmpty = false; break; } } if (!isEmpty) { break; } } // No empty space left if (isEmpty) { return true; } // Else for each-row backtrack for(let num = 1; num <= n; num++) { if (isSafe(board, row, col, num)) { board[row][col] = num; if (solveSudoku(board, n)) { // print(board, n); return true; } else { // Replace it board[row][col] = 0; } } } return false;} function print(board, N){ // We got the answer, just print it for(let r = 0; r < N; r++) { for(let d = 0; d < N; d++) { document.write(board[r][d]); document.write(" "); } document.write("<br>"); if ((r + 1) % Math.floor(Math.sqrt(N)) == 0) { document.write(""); } }} // Driver Codelet board = [ [ 3, 0, 6, 5, 0, 8, 4, 0, 0 ], [ 5, 2, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 8, 7, 0, 0, 0, 0, 3, 1 ], [ 0, 0, 3, 0, 1, 0, 0, 8, 0 ], [ 9, 0, 0, 8, 6, 3, 0, 0, 5 ], [ 0, 5, 0, 0, 9, 0, 6, 0, 0 ], [ 1, 3, 0, 0, 0, 0, 2, 5, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 7, 4 ], [ 0, 0, 5, 2, 0, 6, 3, 0, 0 ] ]; let N = board.length; if (solveSudoku(board, N)){ // Print solution print(board, N);}else{ document.write("No solution");} // This code is contributed by avanitrachhadiya2155 </script> 3 1 6 5 7 8 4 9 2 5 2 9 1 3 4 7 6 8 4 8 7 6 2 9 5 3 1 2 6 3 4 1 5 9 8 7 9 7 4 8 6 3 1 2 5 8 5 1 7 9 2 6 4 3 1 3 8 9 4 7 2 5 6 6 9 2 3 5 1 8 7 4 7 4 5 2 8 6 3 1 9 Complexity Analysis: Time complexity: O(9^(n*n)). For every unassigned index, there are 9 possible options so the time complexity is O(9^(n*n)). The time complexity remains the same but there will be some early pruning so the time taken will be much less than the naive algorithm but the upper bound time complexity remains the same. Space Complexity: O(n*n). To store the output array a matrix is needed. Method 3: Using Bit Masks. Approach: This method is a slight optimization to the above 2 methods. For each row/column/box create a bitmask and for each element in the grid set the bit at position ‘value’ to 1 in the corresponding bitmasks, for O(1) checks. Algorithm: Create 3 arrays of size N (one for rows, columns, and boxes).The boxes are indexed from 0 to 8. (in order to find the box-index of an element we use the following formula: row / 3 * 3 + column / 3).Map the initial values of the grid first.Each time we add/remove an element to/from the grid set the bit to 1/0 to the corresponding bitmasks. Create 3 arrays of size N (one for rows, columns, and boxes). The boxes are indexed from 0 to 8. (in order to find the box-index of an element we use the following formula: row / 3 * 3 + column / 3). Map the initial values of the grid first. Each time we add/remove an element to/from the grid set the bit to 1/0 to the corresponding bitmasks. Implementation: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; #define N 9 // Bitmasks for each row/column/boxint row[N], col[N], box[N];bool seted = false; // Utility function to find the box index// of an element at position [i][j] in the gridint getBox(int i,int j){ return i / 3 * 3 + j / 3;} // Utility function to check if a number// is present in the corresponding row/column/boxbool isSafe(int i,int j,int number){ return !((row[i] >> number) & 1) && !((col[j] >> number) & 1) && !((box[getBox(i,j)] >> number) & 1);} // Utility function to set the initial values of a Sudoku board// (map the values in the bitmasks)void setInitialValues(int grid[N][N]){ for (int i = 0; i < N;i++) for (int j = 0; j < N; j++) row[i] |= 1 << grid[i][j], col[j] |= 1 << grid[i][j], box[getBox(i, j)] |= 1 << grid[i][j];} /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */bool SolveSudoku(int grid[N][N] ,int i, int j){ // Set the initial values if(!seted) seted = true, setInitialValues(grid); if(i == N - 1 && j == N) return true; if(j == N) j = 0, i++; if(grid[i][j]) return SolveSudoku(grid, i, j + 1); for (int nr = 1; nr <= N;nr++) { if(isSafe(i, j, nr)) { /* Assign nr in the current (i, j) position and add nr to each bitmask */ grid[i][j] = nr; row[i] |= 1 << nr; col[j] |= 1 << nr; box[getBox(i, j)] |= 1 << nr; if(SolveSudoku(grid, i,j + 1)) return true; // Remove nr from each bitmask // and search for another possibility row[i] &= ~(1 << nr); col[j] &= ~(1 << nr); box[getBox(i, j)] &= ~(1 << nr); } grid[i][j] = 0; } return false;} // Utility function to print the solved gridvoid print(int grid[N][N]){ for (int i = 0; i < N; i++, cout << '\n') for (int j = 0; j < N; j++) cout << grid[i][j] << ' ';} // Driver Codeint main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 }}; if (SolveSudoku(grid,0 ,0)) print(grid); else cout << "No solution exists\n"; return 0;} // This code is contributed // by Gatea David /*package whatever //do not write package name here */import java.io.*; class GFG { static int N = 9; // Bitmasks for each row/column/box static int row[] = new int[N] , col[] = new int[N], box[] = new int[N]; static Boolean seted = false; // Utility function to find the box index // of an element at position [i][j] in the grid static int getBox(int i,int j) { return i / 3 * 3 + j / 3; } // Utility function to check if a number // is present in the corresponding row/column/box static Boolean isSafe(int i,int j,int number) { return ((row[i] >> number) & 1) == 0 && ((col[j] >> number) & 1) == 0 && ((box[getBox(i,j)] >> number) & 1) == 0; } // Utility function to set the initial values of a Sudoku board // (map the values in the bitmasks) static void setInitialValues(int grid[][]) { for (int i = 0; i < grid.length;i++){ for (int j = 0; j < grid.length; j++){ row[i] |= 1 << grid[i][j]; col[j] |= 1 << grid[i][j]; box[getBox(i, j)] |= 1 << grid[i][j]; } } } /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ static Boolean SolveSudoku(int grid[][] ,int i, int j) { // Set the initial values if(!seted){ seted = true; setInitialValues(grid); } if(i == N - 1 && j == N) return true; if(j == N){ j = 0; i++; } if(grid[i][j]>0) return SolveSudoku(grid, i, j + 1); for (int nr = 1; nr <= N;nr++) { if(isSafe(i, j, nr)) { /* Assign nr in the current (i, j) position and add nr to each bitmask */ grid[i][j] = nr; row[i] |= 1 << nr; col[j] |= 1 << nr; box[getBox(i, j)] |= 1 << nr; if(SolveSudoku(grid, i,j + 1)) return true; // Remove nr from each bitmask // and search for another possibility row[i] &= ~(1 << nr); col[j] &= ~(1 << nr); box[getBox(i, j)] &= ~(1 << nr); } grid[i][j] = 0; } return false; } // Utility function to print the solved grid static void print(int grid[][]) { for (int i = 0; i < grid.length; i++){ for (int j = 0; j < grid[0].length; j++){ System.out.printf("%d ",grid[i][j]); } System.out.println(); } } // Driver code public static void main(String args[]) { // 0 means unassigned cells int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 }}; if (SolveSudoku(grid,0 ,0)) print(grid); else System.out.println("No solution exists"); }} // This code is contributed by shinjanpatra. # N is the size of the 2D matrix N*NN = 9 # A utility function to print griddef printing(arr): for i in range(N): for j in range(N): print(arr[i][j], end = " ") print() # Checks whether it will be# legal to assign num to the# given row, coldef isSafe(grid, row, col, num): # Check if we find the same num # in the similar row , we # return false for x in range(9): if grid[row][x] == num: return False # Check if we find the same num in # the similar column , we # return false for x in range(9): if grid[x][col] == num: return False # Check if we find the same num in # the particular 3*3 matrix, # we return false startRow = row - row % 3 startCol = col - col % 3 for i in range(3): for j in range(3): if grid[i + startRow][j + startCol] == num: return False return True # Takes a partially filled-in grid and attempts# to assign values to all unassigned locations in# such a way to meet the requirements for# Sudoku solution (non-duplication across rows,# columns, and boxes) */def solveSudoku(grid, row, col): # Check if we have reached the 8th # row and 9th column (0 # indexed matrix) , we are # returning true to avoid # further backtracking if (row == N - 1 and col == N): return True # Check if column value becomes 9 , # we move to next row and # column start from 0 if col == N: row += 1 col = 0 # Check if the current position of # the grid already contains # value >0, we iterate for next column if grid[row][col] > 0: return solveSudoku(grid, row, col + 1) for num in range(1, N + 1, 1): # Check if it is safe to place # the num (1-9) in the # given row ,col ->we # move to next column if isSafe(grid, row, col, num): # Assigning the num in # the current (row,col) # position of the grid # and assuming our assigned # num in the position # is correct grid[row][col] = num # Checking for next possibility with next # column if solveSudoku(grid, row, col + 1): return True # Removing the assigned num , # since our assumption # was wrong , and we go for # next assumption with # diff num value grid[row][col] = 0 return False # Driver Code # 0 means unassigned cellsgrid = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] if (solveSudoku(grid, 0, 0)): printing(grid)else: print("no solution exists ") # This code is contributed by sanjoy_62. // C# program for above approachusing System;class GFG { // N is the size of the 2D matrix N*N static int N = 9; // Bitmasks for each row/column/boxstatic int[] row = new int[N];static int[] col = new int[N];static int[] box = new int[N]; static bool seted = false; /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ static bool solveSudoku(int[,] grid, int row, int col) { /*if we have reached the 8th row and 9th column (0 indexed matrix) , we are returning true to avoid further backtracking */ if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row // and column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already // contains value >0, we iterate // for next column if (grid[row,col] != 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num < 10; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we move to next column if (isSafe(grid, row, col, num)) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row,col] = num; // Checking for next // possibility with next column if (solveSudoku(grid, row, col + 1)) return true; } /* removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value */ grid[row,col] = 0; } return false; } /* A utility function to print grid */ static void print(int[,] grid) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(grid[i,j] + " "); Console.WriteLine(); } } // Check whether it will be legal // to assign num to the // given row, col static bool isSafe(int[,] grid, int row, int col, int num) { // Check if we find the same num // in the similar row , we // return false for (int x = 0; x <= 8; x++) if (grid[row,x] == num) return false; // Check if we find the same num // in the similar column , // we return false for (int x = 0; x <= 8; x++) if (grid[x,col] == num) return false; // Check if we find the same num // in the particular 3*3 // matrix, we return false int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow,j + startCol] == num) return false; return true; } // Driver code static void Main() { int[,] grid = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)) print(grid); else Console.WriteLine("No Solution exists"); }} // This code is contributed by code_hunt. <script> const N = 9 // Bitmasks for each row/column/boxlet row = new Array(N), col = new Array(N), box = new Array(N);let seted = false; // Utility function to find the box index// of an element at position [i][j] in the gridfunction getBox(i,j){ return Math.floor(i / 3) * 3 + Math.floor(j / 3);} // Utility function to check if a number// is present in the coresponding row/column/boxfunction isSafe(i,j,number){ return !((row[i] >> number) & 1) && !((col[j] >> number) & 1) && !((box[getBox(i,j)] >> number) & 1);} // Utility function to set the initial values of a Sudoku board// (map the values in the bitmasks)function setInitialValues(grid){ for (let i = 0; i < N;i++) for (let j = 0; j < N; j++) row[i] |= 1 << grid[i][j], col[j] |= 1 << grid[i][j], box[getBox(i, j)] |= 1 << grid[i][j];} /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */function SolveSudoku(grid ,i, j){ // Set the initial values if(!seted){ seted = true, setInitialValues(grid); } if(i == N - 1 && j == N) return true; if(j == N){ j = 0; i++; } if(grid[i][j]) return SolveSudoku(grid, i, j + 1); for (let nr = 1; nr <= N;nr++) { if(isSafe(i, j, nr)) { /* Assign nr in the current (i, j) position and add nr to each bitmask */ grid[i][j] = nr; row[i] |= 1 << nr; col[j] |= 1 << nr; box[getBox(i, j)] |= 1 << nr; if(SolveSudoku(grid, i,j + 1)) return true; // Remove nr from each bitmask // and search for another possibility row[i] &= ~(1 << nr); col[j] &= ~(1 << nr); box[getBox(i, j)] &= ~(1 << nr); } grid[i][j] = 0; } return false;} // Utility function to print the solved gridfunction print(grid){ for (let i = 0; i < N; i++){ for (let j = 0; j < N; j++){ document.write(grid[i][j]," "); } document.write("</br>"); }} // Driver Code // 0 means unassigned cells let grid = [ [ 3, 0, 6, 5, 0, 8, 4, 0, 0 ], [ 5, 2, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 8, 7, 0, 0, 0, 0, 3, 1 ], [ 0, 0, 3, 0, 1, 0, 0, 8, 0 ], [ 9, 0, 0, 8, 6, 3, 0, 0, 5 ], [ 0, 5, 0, 0, 9, 0, 6, 0, 0 ], [ 1, 3, 0, 0, 0, 0, 2, 5, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 7, 4 ], [ 0, 0, 5, 2, 0, 6, 3, 0, 0 ]]; if (SolveSudoku(grid,0 ,0)) print(grid); else document.write("No solution exists","</br>"); // This code is contributed by shinjanpatra </script> 3 1 6 5 7 8 4 9 2 5 2 9 1 3 4 7 6 8 4 8 7 6 2 9 5 3 1 2 6 3 4 1 5 9 8 7 9 7 4 8 6 3 1 2 5 8 5 1 7 9 2 6 4 3 1 3 8 9 4 7 2 5 6 6 9 2 3 5 1 8 7 4 7 4 5 2 8 6 3 1 9 Complexity Analysis: Time complexity: O(9^(n*n)). For every unassigned index, there are 9 possible options so the time complexity is O(9^(n*n)). The time complexity remains the same but checking if a number is safe to use is much faster, O(1). Space Complexity: O(n*n). To store the output array a matrix is needed, and 3 extra arrays of size n are needed for the bitmasks. Mohan Das Nikash 29AjayKumar rathbhupendra ManasChhabra2 andrew1234 pradeepmondalp patiladarsh98032321212 sudhanshugupta2019a divyesh072019 rag2127 avanitrachhadiya2155 abhishek0719kadiyan simmytarika5 davidgatea21 surinderdawra388 shinjanpatra sanjoy_62 code_hunt hardikkoriintern Amazon Directi Flipkart Google MakeMyTrip MAQ Software Microsoft Ola Cabs Oracle PayPal Zoho Backtracking Matrix Zoho Flipkart Amazon Microsoft MakeMyTrip Ola Cabs Oracle MAQ Software Directi Google PayPal Matrix Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Generate all the binary strings of N bits Print all paths from a given source to a destination Print all permutations of a string in Java Find if there is a path of more than k length from a source Matrix Chain Multiplication | DP-8 Print a given matrix in spiral form Program to find largest element in an array The Celebrity Problem Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jun, 2022" }, { "code": null, "e": 275, "s": 52, "text": "Given a partially filled 9×9 2D array ‘grid[9][9]’, the goal is to assign digits (from 1 to 9) to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one instance of the digits from 1 to 9. " }, { "code": null, "e": 285, "s": 275, "text": "Example: " }, { "code": null, "e": 1733, "s": 285, "text": "Input:\ngrid = { {3, 0, 6, 5, 0, 8, 4, 0, 0}, \n {5, 2, 0, 0, 0, 0, 0, 0, 0}, \n {0, 8, 7, 0, 0, 0, 0, 3, 1}, \n {0, 0, 3, 0, 1, 0, 0, 8, 0}, \n {9, 0, 0, 8, 6, 3, 0, 0, 5}, \n {0, 5, 0, 0, 9, 0, 6, 0, 0}, \n {1, 3, 0, 0, 0, 0, 2, 5, 0}, \n {0, 0, 0, 0, 0, 0, 0, 7, 4}, \n {0, 0, 5, 2, 0, 6, 3, 0, 0} }\nOutput:\n 3 1 6 5 7 8 4 9 2\n 5 2 9 1 3 4 7 6 8\n 4 8 7 6 2 9 5 3 1\n 2 6 3 4 1 5 9 8 7\n 9 7 4 8 6 3 1 2 5\n 8 5 1 7 9 2 6 4 3\n 1 3 8 9 4 7 2 5 6\n 6 9 2 3 5 1 8 7 4\n 7 4 5 2 8 6 3 1 9\nExplanation: Each row, column and 3*3 box of \nthe output matrix contains unique numbers.\n\nInput: \ngrid = { { 3, 1, 6, 5, 7, 8, 4, 9, 2 },\n { 5, 2, 9, 1, 3, 4, 7, 6, 8 },\n { 4, 8, 7, 6, 2, 9, 5, 3, 1 },\n { 2, 6, 3, 0, 1, 5, 9, 8, 7 },\n { 9, 7, 4, 8, 6, 0, 1, 2, 5 },\n { 8, 5, 1, 7, 9, 2, 6, 4, 3 },\n { 1, 3, 8, 0, 4, 7, 2, 0, 6 },\n { 6, 9, 2, 3, 5, 1, 8, 7, 4 },\n { 7, 4, 5, 0, 8, 6, 3, 1, 0 } };\nOutput:\n 3 1 6 5 7 8 4 9 2 \n 5 2 9 1 3 4 7 6 8 \n 4 8 7 6 2 9 5 3 1 \n 2 6 3 4 1 5 9 8 7 \n 9 7 4 8 6 3 1 2 5 \n 8 5 1 7 9 2 6 4 3 \n 1 3 8 9 4 7 2 5 6 \n 6 9 2 3 5 1 8 7 4 \n 7 4 5 2 8 6 3 1 9 \nExplanation: Each row, column and 3*3 box of \nthe output matrix contains unique numbers." }, { "code": null, "e": 1751, "s": 1733, "text": "Method 1: Simple." }, { "code": null, "e": 2149, "s": 1751, "text": "Approach: The naive approach is to generate all possible configurations of numbers from 1 to 9 to fill the empty cells. Try every configuration one by one until the correct configuration is found, i.e. for every unassigned position fill the position with a number from 1 to 9. After filling all the unassigned position check if the matrix is safe or not. If safe print else recurs for other cases." }, { "code": null, "e": 2158, "s": 2149, "text": "Chapters" }, { "code": null, "e": 2185, "s": 2158, "text": "descriptions off, selected" }, { "code": null, "e": 2235, "s": 2185, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 2258, "s": 2235, "text": "captions off, selected" }, { "code": null, "e": 2266, "s": 2258, "text": "English" }, { "code": null, "e": 2290, "s": 2266, "text": "This is a modal window." }, { "code": null, "e": 2359, "s": 2290, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 2381, "s": 2359, "text": "End of dialog window." }, { "code": null, "e": 2393, "s": 2381, "text": "Algorithm: " }, { "code": null, "e": 3291, "s": 2393, "text": "Create a function that checks if the given matrix is valid sudoku or not. Keep Hashmap for the row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true;Create a recursive function that takes a grid and the current row and column index.Check some base cases. If the index is at the end of the matrix, i.e. i=N-1 and j=N then check if the grid is safe or not, if safe print the grid and return true else return false. The other base case is when the value of column is N, i.e j = N, then move to next row, i.e. i++ and j = 0.if the current index is not assigned then fill the element from 1 to 9 and recur for all 9 cases with the index of next element, i.e. i, j+1. if the recursive call returns true then break the loop and return true.if the current index is assigned then call the recursive function with index of next element, i.e. i, j+1" }, { "code": null, "e": 3500, "s": 3291, "text": "Create a function that checks if the given matrix is valid sudoku or not. Keep Hashmap for the row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true;" }, { "code": null, "e": 3584, "s": 3500, "text": "Create a recursive function that takes a grid and the current row and column index." }, { "code": null, "e": 3873, "s": 3584, "text": "Check some base cases. If the index is at the end of the matrix, i.e. i=N-1 and j=N then check if the grid is safe or not, if safe print the grid and return true else return false. The other base case is when the value of column is N, i.e j = N, then move to next row, i.e. i++ and j = 0." }, { "code": null, "e": 4087, "s": 3873, "text": "if the current index is not assigned then fill the element from 1 to 9 and recur for all 9 cases with the index of next element, i.e. i, j+1. if the recursive call returns true then break the loop and return true." }, { "code": null, "e": 4193, "s": 4087, "text": "if the current index is assigned then call the recursive function with index of next element, i.e. i, j+1" }, { "code": null, "e": 4209, "s": 4193, "text": "Implementation:" }, { "code": null, "e": 4213, "s": 4209, "text": "C++" }, { "code": null, "e": 4215, "s": 4213, "text": "C" }, { "code": null, "e": 4220, "s": 4215, "text": "Java" }, { "code": null, "e": 4228, "s": 4220, "text": "Python3" }, { "code": null, "e": 4231, "s": 4228, "text": "C#" }, { "code": null, "e": 4242, "s": 4231, "text": "Javascript" }, { "code": "#include <iostream> using namespace std; // N is the size of the 2D matrix N*N#define N 9 /* A utility function to print grid */void print(int arr[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << arr[i][j] << \" \"; cout << endl; }} // Checks whether it will be// legal to assign num to the// given row, colbool isSafe(int grid[N][N], int row, int col, int num){ // Check if we find the same num // in the similar row , we // return false for (int x = 0; x <= 8; x++) if (grid[row][x] == num) return false; // Check if we find the same num in // the similar column , we // return false for (int x = 0; x <= 8; x++) if (grid[x][col] == num) return false; // Check if we find the same num in // the particular 3*3 matrix, // we return false int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow][j + startCol] == num) return false; return true;} /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */bool solveSudoku(int grid[N][N], int row, int col){ // Check if we have reached the 8th // row and 9th column (0 // indexed matrix) , we are // returning true to avoid // further backtracking if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row and // column start from 0 if (col == N) { row++; col = 0; } // Check if the current position of // the grid already contains // value >0, we iterate for next column if (grid[row][col] > 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num <= N; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we // move to next column if (isSafe(grid, row, col, num)) { /* Assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row][col] = num; // Checking for next possibility with next // column if (solveSudoku(grid, row, col + 1)) return true; } // Removing the assigned num , // since our assumption // was wrong , and we go for // next assumption with // diff num value grid[row][col] = 0; } return false;} // Driver Codeint main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)) print(grid); else cout << \"no solution exists \" << endl; return 0; // This is code is contributed by Pradeep Mondal P}", "e": 7802, "s": 4242, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> // N is the size of the 2D matrix N*N#define N 9 /* A utility function to print grid */void print(int arr[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\"%d \",arr[i][j]); printf(\"\\n\"); }} // Checks whether it will be legal // to assign num to the// given row, colint isSafe(int grid[N][N], int row, int col, int num){ // Check if we find the same num // in the similar row , we return 0 for (int x = 0; x <= 8; x++) if (grid[row][x] == num) return 0; // Check if we find the same num in the // similar column , we return 0 for (int x = 0; x <= 8; x++) if (grid[x][col] == num) return 0; // Check if we find the same num in the // particular 3*3 matrix, we return 0 int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow][j + startCol] == num) return 0; return 1;} /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */int solveSudoku(int grid[N][N], int row, int col){ // Check if we have reached the 8th row // and 9th column (0 // indexed matrix) , we are // returning true to avoid // further backtracking if (row == N - 1 && col == N) return 1; // Check if column value becomes 9 , // we move to next row and // column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already contains // value >0, we iterate for next column if (grid[row][col] > 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num <= N; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we move to next column if (isSafe(grid, row, col, num)==1) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row][col] = num; // Checking for next possibility with next // column if (solveSudoku(grid, row, col + 1)==1) return 1; } // Removing the assigned num , // since our assumption // was wrong , and we go for next // assumption with // diff num value grid[row][col] = 0; } return 0;} int main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)==1) print(grid); else printf(\"No solution exists\"); return 0; // This is code is contributed by Pradeep Mondal P}", "e": 11291, "s": 7802, "text": null }, { "code": "// Java program for above approachpublic class Sudoku { // N is the size of the 2D matrix N*N static int N = 9; /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ static boolean solveSudoku(int grid[][], int row, int col) { /*if we have reached the 8th row and 9th column (0 indexed matrix) , we are returning true to avoid further backtracking */ if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row // and column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already // contains value >0, we iterate // for next column if (grid[row][col] != 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num < 10; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we move to next column if (isSafe(grid, row, col, num)) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row][col] = num; // Checking for next // possibility with next column if (solveSudoku(grid, row, col + 1)) return true; } /* removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value */ grid[row][col] = 0; } return false; } /* A utility function to print grid */ static void print(int[][] grid) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(grid[i][j] + \" \"); System.out.println(); } } // Check whether it will be legal // to assign num to the // given row, col static boolean isSafe(int[][] grid, int row, int col, int num) { // Check if we find the same num // in the similar row , we // return false for (int x = 0; x <= 8; x++) if (grid[row][x] == num) return false; // Check if we find the same num // in the similar column , // we return false for (int x = 0; x <= 8; x++) if (grid[x][col] == num) return false; // Check if we find the same num // in the particular 3*3 // matrix, we return false int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow][j + startCol] == num) return false; return true; } // Driver Code public static void main(String[] args) { int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)) print(grid); else System.out.println(\"No Solution exists\"); } // This is code is contributed by Pradeep Mondal P}", "e": 15217, "s": 11291, "text": null }, { "code": "# N is the size of the 2D matrix N*NN = 9 # A utility function to print griddef printing(arr): for i in range(N): for j in range(N): print(arr[i][j], end = \" \") print() # Checks whether it will be# legal to assign num to the# given row, coldef isSafe(grid, row, col, num): # Check if we find the same num # in the similar row , we # return false for x in range(9): if grid[row][x] == num: return False # Check if we find the same num in # the similar column , we # return false for x in range(9): if grid[x][col] == num: return False # Check if we find the same num in # the particular 3*3 matrix, # we return false startRow = row - row % 3 startCol = col - col % 3 for i in range(3): for j in range(3): if grid[i + startRow][j + startCol] == num: return False return True # Takes a partially filled-in grid and attempts# to assign values to all unassigned locations in# such a way to meet the requirements for# Sudoku solution (non-duplication across rows,# columns, and boxes) */def solveSudoku(grid, row, col): # Check if we have reached the 8th # row and 9th column (0 # indexed matrix) , we are # returning true to avoid # further backtracking if (row == N - 1 and col == N): return True # Check if column value becomes 9 , # we move to next row and # column start from 0 if col == N: row += 1 col = 0 # Check if the current position of # the grid already contains # value >0, we iterate for next column if grid[row][col] > 0: return solveSudoku(grid, row, col + 1) for num in range(1, N + 1, 1): # Check if it is safe to place # the num (1-9) in the # given row ,col ->we # move to next column if isSafe(grid, row, col, num): # Assigning the num in # the current (row,col) # position of the grid # and assuming our assigned # num in the position # is correct grid[row][col] = num # Checking for next possibility with next # column if solveSudoku(grid, row, col + 1): return True # Removing the assigned num , # since our assumption # was wrong , and we go for # next assumption with # diff num value grid[row][col] = 0 return False # Driver Code # 0 means unassigned cellsgrid = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] if (solveSudoku(grid, 0, 0)): printing(grid)else: print(\"no solution exists \") # This code is contributed by sudhanshgupta2019a", "e": 18220, "s": 15217, "text": null }, { "code": "// C# program for above approachusing System;class GFG { // N is the size of the 2D matrix N*N static int N = 9; /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ static bool solveSudoku(int[,] grid, int row, int col) { /*if we have reached the 8th row and 9th column (0 indexed matrix) , we are returning true to avoid further backtracking */ if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row // and column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already // contains value >0, we iterate // for next column if (grid[row,col] != 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num < 10; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we move to next column if (isSafe(grid, row, col, num)) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row,col] = num; // Checking for next // possibility with next column if (solveSudoku(grid, row, col + 1)) return true; } /* removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value */ grid[row,col] = 0; } return false; } /* A utility function to print grid */ static void print(int[,] grid) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(grid[i,j] + \" \"); Console.WriteLine(); } } // Check whether it will be legal // to assign num to the // given row, col static bool isSafe(int[,] grid, int row, int col, int num) { // Check if we find the same num // in the similar row , we // return false for (int x = 0; x <= 8; x++) if (grid[row,x] == num) return false; // Check if we find the same num // in the similar column , // we return false for (int x = 0; x <= 8; x++) if (grid[x,col] == num) return false; // Check if we find the same num // in the particular 3*3 // matrix, we return false int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow,j + startCol] == num) return false; return true; } // Driver code static void Main() { int[,] grid = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)) print(grid); else Console.WriteLine(\"No Solution exists\"); }} // This code is contributed by divyesh072019.", "e": 21629, "s": 18220, "text": null }, { "code": "<script> // Javascript program for above approach // N is the size of the 2D matrix N*Nlet N = 9; /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */function solveSudoku(grid, row, col){ /* If we have reached the 8th row and 9th column (0 indexed matrix) , we are returning true to avoid further backtracking */ if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row // and column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already // contains value >0, we iterate // for next column if (grid[row][col] != 0) return solveSudoku(grid, row, col + 1); for(let num = 1; num < 10; num++) { // Check if it is safe to place // the num (1-9) in the given // row ,col ->we move to next column if (isSafe(grid, row, col, num)) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row][col] = num; // Checking for next // possibility with next column if (solveSudoku(grid, row, col + 1)) return true; } /* removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value */ grid[row][col] = 0; } return false;} /* A utility function to print grid */function print(grid){ for(let i = 0; i < N; i++) { for(let j = 0; j < N; j++) document.write(grid[i][j] + \" \"); document.write(\"<br>\"); }} // Check whether it will be legal// to assign num to the// given row, colfunction isSafe(grid, row, col, num){ // Check if we find the same num // in the similar row , we // return false for(let x = 0; x <= 8; x++) if (grid[row][x] == num) return false; // Check if we find the same num // in the similar column , // we return false for(let x = 0; x <= 8; x++) if (grid[x][col] == num) return false; // Check if we find the same num // in the particular 3*3 // matrix, we return false let startRow = row - row % 3, startCol = col - col % 3; for(let i = 0; i < 3; i++) for(let j = 0; j < 3; j++) if (grid[i + startRow][j + startCol] == num) return false; return true;} // Driver Codelet grid = [ [ 3, 0, 6, 5, 0, 8, 4, 0, 0 ], [ 5, 2, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 8, 7, 0, 0, 0, 0, 3, 1 ], [ 0, 0, 3, 0, 1, 0, 0, 8, 0 ], [ 9, 0, 0, 8, 6, 3, 0, 0, 5 ], [ 0, 5, 0, 0, 9, 0, 6, 0, 0 ], [ 1, 3, 0, 0, 0, 0, 2, 5, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 7, 4 ], [ 0, 0, 5, 2, 0, 6, 3, 0, 0 ] ] if (solveSudoku(grid, 0, 0)) print(grid)else document.write(\"no solution exists \") // This code is contributed by rag2127 </script>", "e": 24928, "s": 21629, "text": null }, { "code": null, "e": 25098, "s": 24928, "text": "3 1 6 5 7 8 4 9 2 \n5 2 9 1 3 4 7 6 8 \n4 8 7 6 2 9 5 3 1 \n2 6 3 4 1 5 9 8 7 \n9 7 4 8 6 3 1 2 5 \n8 5 1 7 9 2 6 4 3 \n1 3 8 9 4 7 2 5 6 \n6 9 2 3 5 1 8 7 4 \n7 4 5 2 8 6 3 1 9" }, { "code": null, "e": 25122, "s": 25098, "text": " Complexity Analysis: " }, { "code": null, "e": 25246, "s": 25122, "text": "Time complexity: O(9^(n*n)). For every unassigned index, there are 9 possible options so the time complexity is O(9^(n*n))." }, { "code": null, "e": 25318, "s": 25246, "text": "Space Complexity: O(n*n). To store the output array a matrix is needed." }, { "code": null, "e": 25343, "s": 25318, "text": "Method 2: Backtracking. " }, { "code": null, "e": 25943, "s": 25343, "text": "Approach: Like all other Backtracking problems, Sudoku can be solved by one by one assigning numbers to empty cells. Before assigning a number, check whether it is safe to assign. Check that the same number is not present in the current row, current column and current 3X3 subgrid. After checking for safety, assign the number, and recursively check whether this assignment leads to a solution or not. If the assignment doesn’t lead to a solution, then try the next number for the current empty cell. And if none of the number (1 to 9) leads to a solution, return false and print no solution exists." }, { "code": null, "e": 25955, "s": 25943, "text": "Algorithm: " }, { "code": null, "e": 26671, "s": 25955, "text": "Create a function that checks after assigning the current index the grid becomes unsafe or not. Keep Hashmap for a row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true; hashMap can be avoided by using loops.Create a recursive function that takes a grid.Check for any unassigned location. If present then assign a number from 1 to 9, check if assigning the number to current index makes the grid unsafe or not, if safe then recursively call the function for all safe cases from 0 to 9. if any recursive call returns true, end the loop and return true. If no recursive call returns true then return false.If there is no unassigned location then return true." }, { "code": null, "e": 26939, "s": 26671, "text": "Create a function that checks after assigning the current index the grid becomes unsafe or not. Keep Hashmap for a row, column and boxes. If any number has a frequency greater than 1 in the hashMap return false else return true; hashMap can be avoided by using loops." }, { "code": null, "e": 26986, "s": 26939, "text": "Create a recursive function that takes a grid." }, { "code": null, "e": 27337, "s": 26986, "text": "Check for any unassigned location. If present then assign a number from 1 to 9, check if assigning the number to current index makes the grid unsafe or not, if safe then recursively call the function for all safe cases from 0 to 9. if any recursive call returns true, end the loop and return true. If no recursive call returns true then return false." }, { "code": null, "e": 27390, "s": 27337, "text": "If there is no unassigned location then return true." }, { "code": null, "e": 27406, "s": 27390, "text": "Implementation:" }, { "code": null, "e": 27410, "s": 27406, "text": "C++" }, { "code": null, "e": 27412, "s": 27410, "text": "C" }, { "code": null, "e": 27417, "s": 27412, "text": "Java" }, { "code": null, "e": 27424, "s": 27417, "text": "Python" }, { "code": null, "e": 27427, "s": 27424, "text": "C#" }, { "code": null, "e": 27438, "s": 27427, "text": "Javascript" }, { "code": "// A Backtracking program in// C++ to solve Sudoku problem#include <bits/stdc++.h>using namespace std; // UNASSIGNED is used for empty// cells in sudoku grid#define UNASSIGNED 0 // N is used for the size of Sudoku grid.// Size will be NxN#define N 9 // This function finds an entry in grid// that is still unassignedbool FindUnassignedLocation(int grid[N][N], int& row, int& col); // Checks whether it will be legal// to assign num to the given row, colbool isSafe(int grid[N][N], int row, int col, int num); /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */bool SolveSudoku(int grid[N][N]){ int row, col; // If there is no unassigned location, // we are done if (!FindUnassignedLocation(grid, row, col)) // success! return true; // Consider digits 1 to 9 for (int num = 1; num <= 9; num++) { // Check if looks promising if (isSafe(grid, row, col, num)) { // Make tentative assignment grid[row][col] = num; // Return, if success if (SolveSudoku(grid)) return true; // Failure, unmake & try again grid[row][col] = UNASSIGNED; } } // This triggers backtracking return false;} /* Searches the grid to find an entry that isstill unassigned. If found, the referenceparameters row, col will be set the locationthat is unassigned, and true is returned.If no unassigned entries remain, false is returned. */bool FindUnassignedLocation(int grid[N][N], int& row, int& col){ for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (grid[row][col] == UNASSIGNED) return true; return false;} /* Returns a boolean which indicates whetheran assigned entry in the specified row matchesthe given number. */bool UsedInRow(int grid[N][N], int row, int num){ for (int col = 0; col < N; col++) if (grid[row][col] == num) return true; return false;} /* Returns a boolean which indicates whetheran assigned entry in the specified columnmatches the given number. */bool UsedInCol(int grid[N][N], int col, int num){ for (int row = 0; row < N; row++) if (grid[row][col] == num) return true; return false;} /* Returns a boolean which indicates whetheran assigned entry within the specified 3x3 boxmatches the given number. */bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num){ for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) if (grid[row + boxStartRow] [col + boxStartCol] == num) return true; return false;} /* Returns a boolean which indicates whetherit will be legal to assign num to the givenrow, col location. */bool isSafe(int grid[N][N], int row, int col, int num){ /* Check if 'num' is not already placed in current row, current column and current 3x3 box */ return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) && !UsedInBox(grid, row - row % 3, col - col % 3, num) && grid[row][col] == UNASSIGNED;} /* A utility function to print grid */void printGrid(int grid[N][N]){ for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) cout << grid[row][col] << \" \"; cout << endl; }} // Driver Codeint main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (SolveSudoku(grid) == true) printGrid(grid); else cout << \"No solution exists\"; return 0;} // This is code is contributed by rathbhupendra", "e": 31779, "s": 27438, "text": null }, { "code": "// A Backtracking program in C// to solve Sudoku problem#include <stdio.h> // UNASSIGNED is used for empty// cells in sudoku grid#define UNASSIGNED 0 // N is used for the size of// Sudoku grid. The size will be NxN#define N 9 // This function finds an entry// in grid that is still unassignedbool FindUnassignedLocation(int grid[N][N], int& row, int& col); // Checks whether it will be legal// to assign num to the given row, colbool isSafe(int grid[N][N], int row, int col, int num); /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */bool SolveSudoku(int grid[N][N]){ int row, col; // Check If there is no unassigned // location, we are done if (!FindUnassignedLocation(grid, row, col)) return true; // success! //Cconsider digits 1 to 9 for (int num = 1; num <= 9; num++) { // Check if looks promising if (isSafe(grid, row, col, num)) { // Make tentative assignment grid[row][col] = num; // Return, if success, yay! if (SolveSudoku(grid)) return true; // Failure, unmake & try again grid[row][col] = UNASSIGNED; } } // This triggers backtracking return false;} /* Searches the grid to find an entry that is still unassigned. If found, the reference parameters row, col will be set the location that is unassigned, and true is returned. If no unassigned entries remain, false is returned. */bool FindUnassignedLocation( int grid[N][N], int& row, int& col){ for (row = 0; row < N; row++) for (col = 0; col < N; col++) if (grid[row][col] == UNASSIGNED) return true; return false;} /* Returns a boolean which indicates whether an assigned entry in the specified row matches the given number. */bool UsedInRow( int grid[N][N], int row, int num){ for (int col = 0; col < N; col++) if (grid[row][col] == num) return true; return false;} /* Returns a boolean which indicates whether an assigned entry in the specified column matches the given number. */bool UsedInCol( int grid[N][N], int col, int num){ for (int row = 0; row < N; row++) if (grid[row][col] == num) return true; return false;} /* Returns a boolean which indicates whether an assigned entry within the specified 3x3 box matches the given number. */bool UsedInBox( int grid[N][N], int boxStartRow, int boxStartCol, int num){ for (int row = 0; row < 3; row++) for (int col = 0; col < 3; col++) if ( grid[row + boxStartRow] [col + boxStartCol] == num) return true; return false;} /* Returns a boolean which indicateswhether it will be legal to assign num to the given row, col location. */bool isSafe( int grid[N][N], int row, int col, int num){ /* Check if 'num' is not already placed in current row, current column and current 3x3 box */ return !UsedInRow(grid, row, num) && !UsedInCol(grid, col, num) && !UsedInBox(grid, row - row % 3, col - col % 3, num) && grid[row][col] == UNASSIGNED;} /* A utility function to print grid */void printGrid(int grid[N][N]){ for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) printf(\"%2d\", grid[row][col]); printf(\"\\n\"); }} /* Driver Program to test above functions */int main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (SolveSudoku(grid) == true) printGrid(grid); else printf(\"No solution exists\"); return 0;}", "e": 36131, "s": 31779, "text": null }, { "code": "/* A Backtracking program inJava to solve Sudoku problem */class GFG{ public static boolean isSafe(int[][] board, int row, int col, int num) { // Row has the unique (row-clash) for (int d = 0; d < board.length; d++) { // Check if the number we are trying to // place is already present in // that row, return false; if (board[row][d] == num) { return false; } } // Column has the unique numbers (column-clash) for (int r = 0; r < board.length; r++) { // Check if the number // we are trying to // place is already present in // that column, return false; if (board[r][col] == num) { return false; } } // Corresponding square has // unique number (box-clash) int sqrt = (int)Math.sqrt(board.length); int boxRowStart = row - row % sqrt; int boxColStart = col - col % sqrt; for (int r = boxRowStart; r < boxRowStart + sqrt; r++) { for (int d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r][d] == num) { return false; } } } // if there is no clash, it's safe return true; } public static boolean solveSudoku( int[][] board, int n) { int row = -1; int col = -1; boolean isEmpty = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 0) { row = i; col = j; // We still have some remaining // missing values in Sudoku isEmpty = false; break; } } if (!isEmpty) { break; } } // No empty space left if (isEmpty) { return true; } // Else for each-row backtrack for (int num = 1; num <= n; num++) { if (isSafe(board, row, col, num)) { board[row][col] = num; if (solveSudoku(board, n)) { // print(board, n); return true; } else { // replace it board[row][col] = 0; } } } return false; } public static void print( int[][] board, int N) { // We got the answer, just print it for (int r = 0; r < N; r++) { for (int d = 0; d < N; d++) { System.out.print(board[r][d]); System.out.print(\" \"); } System.out.print(\"\\n\"); if ((r + 1) % (int)Math.sqrt(N) == 0) { System.out.print(\"\"); } } } // Driver Code public static void main(String args[]) { int[][] board = new int[][] { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; int N = board.length; if (solveSudoku(board, N)) { // print solution print(board, N); } else { System.out.println(\"No solution\"); } }} // This code is contributed// by MohanDas", "e": 40061, "s": 36131, "text": null }, { "code": "# A Backtracking program# in Python to solve Sudoku problem # A Utility Function to print the Griddef print_grid(arr): for i in range(9): for j in range(9): print arr[i][j], print ('n') # Function to Find the entry in# the Grid that is still not used# Searches the grid to find an# entry that is still unassigned. If# found, the reference parameters# row, col will be set the location# that is unassigned, and true is# returned. If no unassigned entries# remains, false is returned.# 'l' is a list variable that has# been passed from the solve_sudoku function# to keep track of incrementation# of Rows and Columnsdef find_empty_location(arr, l): for row in range(9): for col in range(9): if(arr[row][col]== 0): l[0]= row l[1]= col return True return False # Returns a boolean which indicates# whether any assigned entry# in the specified row matches# the given number.def used_in_row(arr, row, num): for i in range(9): if(arr[row][i] == num): return True return False # Returns a boolean which indicates# whether any assigned entry# in the specified column matches# the given number.def used_in_col(arr, col, num): for i in range(9): if(arr[i][col] == num): return True return False # Returns a boolean which indicates# whether any assigned entry# within the specified 3x3 box# matches the given numberdef used_in_box(arr, row, col, num): for i in range(3): for j in range(3): if(arr[i + row][j + col] == num): return True return False # Checks whether it will be legal# to assign num to the given row, col# Returns a boolean which indicates# whether it will be legal to assign# num to the given row, col location.def check_location_is_safe(arr, row, col, num): # Check if 'num' is not already # placed in current row, # current column and current 3x3 box return not used_in_row(arr, row, num) and not used_in_col(arr, col, num) and not used_in_box(arr, row - row % 3, col - col % 3, num) # Takes a partially filled-in grid# and attempts to assign values to# all unassigned locations in such a# way to meet the requirements# for Sudoku solution (non-duplication# across rows, columns, and boxes)def solve_sudoku(arr): # 'l' is a list variable that keeps the # record of row and col in # find_empty_location Function l =[0, 0] # If there is no unassigned # location, we are done if(not find_empty_location(arr, l)): return True # Assigning list values to row and col # that we got from the above Function row = l[0] col = l[1] # consider digits 1 to 9 for num in range(1, 10): # if looks promising if(check_location_is_safe(arr, row, col, num)): # make tentative assignment arr[row][col]= num # return, if success, # ya ! if(solve_sudoku(arr)): return True # failure, unmake & try again arr[row][col] = 0 # this triggers backtracking return False # Driver main function to test above functionsif __name__==\"__main__\": # creating a 2D array for the grid grid =[[0 for x in range(9)]for y in range(9)] # assigning values to the grid grid =[[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] # if success print the grid if(solve_sudoku(grid)): print_grid(grid) else: print \"No solution exists\" # The above code has been contributed by Harshit Sidhwa.", "e": 44051, "s": 40061, "text": null }, { "code": "/* A Backtracking program inC# to solve Sudoku problem */using System; class GFG{ public static bool isSafe(int[, ] board, int row, int col, int num) { // Row has the unique (row-clash) for (int d = 0; d < board.GetLength(0); d++) { // Check if the number // we are trying to // place is already present in // that row, return false; if (board[row, d] == num) { return false; } } // Column has the unique numbers (column-clash) for (int r = 0; r < board.GetLength(0); r++) { // Check if the number // we are trying to // place is already present in // that column, return false; if (board[r, col] == num) { return false; } } // corresponding square has // unique number (box-clash) int sqrt = (int)Math.Sqrt(board.GetLength(0)); int boxRowStart = row - row % sqrt; int boxColStart = col - col % sqrt; for (int r = boxRowStart; r < boxRowStart + sqrt; r++) { for (int d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r, d] == num) { return false; } } } // if there is no clash, it's safe return true; } public static bool solveSudoku(int[, ] board, int n) { int row = -1; int col = -1; bool isEmpty = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i, j] == 0) { row = i; col = j; // We still have some remaining // missing values in Sudoku isEmpty = false; break; } } if (!isEmpty) { break; } } // no empty space left if (isEmpty) { return true; } // else for each-row backtrack for (int num = 1; num <= n; num++) { if (isSafe(board, row, col, num)) { board[row, col] = num; if (solveSudoku(board, n)) { // Print(board, n); return true; } else { // Replace it board[row, col] = 0; } } } return false; } public static void print(int[, ] board, int N) { // We got the answer, just print it for (int r = 0; r < N; r++) { for (int d = 0; d < N; d++) { Console.Write(board[r, d]); Console.Write(\" \"); } Console.Write(\"\\n\"); if ((r + 1) % (int)Math.Sqrt(N) == 0) { Console.Write(\"\"); } } } // Driver Code public static void Main(String[] args) { int[, ] board = new int[, ] { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; int N = board.GetLength(0); if (solveSudoku(board, N)) { // print solution print(board, N); } else { Console.Write(\"No solution\"); } }} // This code has been contributed by 29AjayKumar", "e": 48119, "s": 44051, "text": null }, { "code": "<script> /* A Backtracking program inJavascript to solve Sudoku problem */ function isSafe(board, row, col, num){ // Row has the unique (row-clash) for(let d = 0; d < board.length; d++) { // Check if the number we are trying to // place is already present in // that row, return false; if (board[row][d] == num) { return false; } } // Column has the unique numbers (column-clash) for(let r = 0; r < board.length; r++) { // Check if the number // we are trying to // place is already present in // that column, return false; if (board[r][col] == num) { return false; } } // Corresponding square has // unique number (box-clash) let sqrt = Math.floor(Math.sqrt(board.length)); let boxRowStart = row - row % sqrt; let boxColStart = col - col % sqrt; for(let r = boxRowStart; r < boxRowStart + sqrt; r++) { for(let d = boxColStart; d < boxColStart + sqrt; d++) { if (board[r][d] == num) { return false; } } } // If there is no clash, it's safe return true;} function solveSudoku(board, n){ let row = -1; let col = -1; let isEmpty = true; for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { if (board[i][j] == 0) { row = i; col = j; // We still have some remaining // missing values in Sudoku isEmpty = false; break; } } if (!isEmpty) { break; } } // No empty space left if (isEmpty) { return true; } // Else for each-row backtrack for(let num = 1; num <= n; num++) { if (isSafe(board, row, col, num)) { board[row][col] = num; if (solveSudoku(board, n)) { // print(board, n); return true; } else { // Replace it board[row][col] = 0; } } } return false;} function print(board, N){ // We got the answer, just print it for(let r = 0; r < N; r++) { for(let d = 0; d < N; d++) { document.write(board[r][d]); document.write(\" \"); } document.write(\"<br>\"); if ((r + 1) % Math.floor(Math.sqrt(N)) == 0) { document.write(\"\"); } }} // Driver Codelet board = [ [ 3, 0, 6, 5, 0, 8, 4, 0, 0 ], [ 5, 2, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 8, 7, 0, 0, 0, 0, 3, 1 ], [ 0, 0, 3, 0, 1, 0, 0, 8, 0 ], [ 9, 0, 0, 8, 6, 3, 0, 0, 5 ], [ 0, 5, 0, 0, 9, 0, 6, 0, 0 ], [ 1, 3, 0, 0, 0, 0, 2, 5, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 7, 4 ], [ 0, 0, 5, 2, 0, 6, 3, 0, 0 ] ]; let N = board.length; if (solveSudoku(board, N)){ // Print solution print(board, N);}else{ document.write(\"No solution\");} // This code is contributed by avanitrachhadiya2155 </script>", "e": 51375, "s": 48119, "text": null }, { "code": null, "e": 51545, "s": 51375, "text": "3 1 6 5 7 8 4 9 2 \n5 2 9 1 3 4 7 6 8 \n4 8 7 6 2 9 5 3 1 \n2 6 3 4 1 5 9 8 7 \n9 7 4 8 6 3 1 2 5 \n8 5 1 7 9 2 6 4 3 \n1 3 8 9 4 7 2 5 6 \n6 9 2 3 5 1 8 7 4 \n7 4 5 2 8 6 3 1 9" }, { "code": null, "e": 51568, "s": 51545, "text": "Complexity Analysis: " }, { "code": null, "e": 51881, "s": 51568, "text": "Time complexity: O(9^(n*n)). For every unassigned index, there are 9 possible options so the time complexity is O(9^(n*n)). The time complexity remains the same but there will be some early pruning so the time taken will be much less than the naive algorithm but the upper bound time complexity remains the same." }, { "code": null, "e": 51953, "s": 51881, "text": "Space Complexity: O(n*n). To store the output array a matrix is needed." }, { "code": null, "e": 51980, "s": 51953, "text": "Method 3: Using Bit Masks." }, { "code": null, "e": 52211, "s": 51980, "text": "Approach: This method is a slight optimization to the above 2 methods. For each row/column/box create a bitmask and for each element in the grid set the bit at position ‘value’ to 1 in the corresponding bitmasks, for O(1) checks." }, { "code": null, "e": 52223, "s": 52211, "text": "Algorithm: " }, { "code": null, "e": 52564, "s": 52223, "text": "Create 3 arrays of size N (one for rows, columns, and boxes).The boxes are indexed from 0 to 8. (in order to find the box-index of an element we use the following formula: row / 3 * 3 + column / 3).Map the initial values of the grid first.Each time we add/remove an element to/from the grid set the bit to 1/0 to the corresponding bitmasks." }, { "code": null, "e": 52626, "s": 52564, "text": "Create 3 arrays of size N (one for rows, columns, and boxes)." }, { "code": null, "e": 52764, "s": 52626, "text": "The boxes are indexed from 0 to 8. (in order to find the box-index of an element we use the following formula: row / 3 * 3 + column / 3)." }, { "code": null, "e": 52806, "s": 52764, "text": "Map the initial values of the grid first." }, { "code": null, "e": 52908, "s": 52806, "text": "Each time we add/remove an element to/from the grid set the bit to 1/0 to the corresponding bitmasks." }, { "code": null, "e": 52924, "s": 52908, "text": "Implementation:" }, { "code": null, "e": 52928, "s": 52924, "text": "C++" }, { "code": null, "e": 52933, "s": 52928, "text": "Java" }, { "code": null, "e": 52941, "s": 52933, "text": "Python3" }, { "code": null, "e": 52944, "s": 52941, "text": "C#" }, { "code": null, "e": 52955, "s": 52944, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; #define N 9 // Bitmasks for each row/column/boxint row[N], col[N], box[N];bool seted = false; // Utility function to find the box index// of an element at position [i][j] in the gridint getBox(int i,int j){ return i / 3 * 3 + j / 3;} // Utility function to check if a number// is present in the corresponding row/column/boxbool isSafe(int i,int j,int number){ return !((row[i] >> number) & 1) && !((col[j] >> number) & 1) && !((box[getBox(i,j)] >> number) & 1);} // Utility function to set the initial values of a Sudoku board// (map the values in the bitmasks)void setInitialValues(int grid[N][N]){ for (int i = 0; i < N;i++) for (int j = 0; j < N; j++) row[i] |= 1 << grid[i][j], col[j] |= 1 << grid[i][j], box[getBox(i, j)] |= 1 << grid[i][j];} /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */bool SolveSudoku(int grid[N][N] ,int i, int j){ // Set the initial values if(!seted) seted = true, setInitialValues(grid); if(i == N - 1 && j == N) return true; if(j == N) j = 0, i++; if(grid[i][j]) return SolveSudoku(grid, i, j + 1); for (int nr = 1; nr <= N;nr++) { if(isSafe(i, j, nr)) { /* Assign nr in the current (i, j) position and add nr to each bitmask */ grid[i][j] = nr; row[i] |= 1 << nr; col[j] |= 1 << nr; box[getBox(i, j)] |= 1 << nr; if(SolveSudoku(grid, i,j + 1)) return true; // Remove nr from each bitmask // and search for another possibility row[i] &= ~(1 << nr); col[j] &= ~(1 << nr); box[getBox(i, j)] &= ~(1 << nr); } grid[i][j] = 0; } return false;} // Utility function to print the solved gridvoid print(int grid[N][N]){ for (int i = 0; i < N; i++, cout << '\\n') for (int j = 0; j < N; j++) cout << grid[i][j] << ' ';} // Driver Codeint main(){ // 0 means unassigned cells int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 }}; if (SolveSudoku(grid,0 ,0)) print(grid); else cout << \"No solution exists\\n\"; return 0;} // This code is contributed // by Gatea David", "e": 55885, "s": 52955, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*; class GFG { static int N = 9; // Bitmasks for each row/column/box static int row[] = new int[N] , col[] = new int[N], box[] = new int[N]; static Boolean seted = false; // Utility function to find the box index // of an element at position [i][j] in the grid static int getBox(int i,int j) { return i / 3 * 3 + j / 3; } // Utility function to check if a number // is present in the corresponding row/column/box static Boolean isSafe(int i,int j,int number) { return ((row[i] >> number) & 1) == 0 && ((col[j] >> number) & 1) == 0 && ((box[getBox(i,j)] >> number) & 1) == 0; } // Utility function to set the initial values of a Sudoku board // (map the values in the bitmasks) static void setInitialValues(int grid[][]) { for (int i = 0; i < grid.length;i++){ for (int j = 0; j < grid.length; j++){ row[i] |= 1 << grid[i][j]; col[j] |= 1 << grid[i][j]; box[getBox(i, j)] |= 1 << grid[i][j]; } } } /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ static Boolean SolveSudoku(int grid[][] ,int i, int j) { // Set the initial values if(!seted){ seted = true; setInitialValues(grid); } if(i == N - 1 && j == N) return true; if(j == N){ j = 0; i++; } if(grid[i][j]>0) return SolveSudoku(grid, i, j + 1); for (int nr = 1; nr <= N;nr++) { if(isSafe(i, j, nr)) { /* Assign nr in the current (i, j) position and add nr to each bitmask */ grid[i][j] = nr; row[i] |= 1 << nr; col[j] |= 1 << nr; box[getBox(i, j)] |= 1 << nr; if(SolveSudoku(grid, i,j + 1)) return true; // Remove nr from each bitmask // and search for another possibility row[i] &= ~(1 << nr); col[j] &= ~(1 << nr); box[getBox(i, j)] &= ~(1 << nr); } grid[i][j] = 0; } return false; } // Utility function to print the solved grid static void print(int grid[][]) { for (int i = 0; i < grid.length; i++){ for (int j = 0; j < grid[0].length; j++){ System.out.printf(\"%d \",grid[i][j]); } System.out.println(); } } // Driver code public static void main(String args[]) { // 0 means unassigned cells int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 }}; if (SolveSudoku(grid,0 ,0)) print(grid); else System.out.println(\"No solution exists\"); }} // This code is contributed by shinjanpatra.", "e": 59047, "s": 55885, "text": null }, { "code": "# N is the size of the 2D matrix N*NN = 9 # A utility function to print griddef printing(arr): for i in range(N): for j in range(N): print(arr[i][j], end = \" \") print() # Checks whether it will be# legal to assign num to the# given row, coldef isSafe(grid, row, col, num): # Check if we find the same num # in the similar row , we # return false for x in range(9): if grid[row][x] == num: return False # Check if we find the same num in # the similar column , we # return false for x in range(9): if grid[x][col] == num: return False # Check if we find the same num in # the particular 3*3 matrix, # we return false startRow = row - row % 3 startCol = col - col % 3 for i in range(3): for j in range(3): if grid[i + startRow][j + startCol] == num: return False return True # Takes a partially filled-in grid and attempts# to assign values to all unassigned locations in# such a way to meet the requirements for# Sudoku solution (non-duplication across rows,# columns, and boxes) */def solveSudoku(grid, row, col): # Check if we have reached the 8th # row and 9th column (0 # indexed matrix) , we are # returning true to avoid # further backtracking if (row == N - 1 and col == N): return True # Check if column value becomes 9 , # we move to next row and # column start from 0 if col == N: row += 1 col = 0 # Check if the current position of # the grid already contains # value >0, we iterate for next column if grid[row][col] > 0: return solveSudoku(grid, row, col + 1) for num in range(1, N + 1, 1): # Check if it is safe to place # the num (1-9) in the # given row ,col ->we # move to next column if isSafe(grid, row, col, num): # Assigning the num in # the current (row,col) # position of the grid # and assuming our assigned # num in the position # is correct grid[row][col] = num # Checking for next possibility with next # column if solveSudoku(grid, row, col + 1): return True # Removing the assigned num , # since our assumption # was wrong , and we go for # next assumption with # diff num value grid[row][col] = 0 return False # Driver Code # 0 means unassigned cellsgrid = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] if (solveSudoku(grid, 0, 0)): printing(grid)else: print(\"no solution exists \") # This code is contributed by sanjoy_62.", "e": 62022, "s": 59047, "text": null }, { "code": "// C# program for above approachusing System;class GFG { // N is the size of the 2D matrix N*N static int N = 9; // Bitmasks for each row/column/boxstatic int[] row = new int[N];static int[] col = new int[N];static int[] box = new int[N]; static bool seted = false; /* Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) */ static bool solveSudoku(int[,] grid, int row, int col) { /*if we have reached the 8th row and 9th column (0 indexed matrix) , we are returning true to avoid further backtracking */ if (row == N - 1 && col == N) return true; // Check if column value becomes 9 , // we move to next row // and column start from 0 if (col == N) { row++; col = 0; } // Check if the current position // of the grid already // contains value >0, we iterate // for next column if (grid[row,col] != 0) return solveSudoku(grid, row, col + 1); for (int num = 1; num < 10; num++) { // Check if it is safe to place // the num (1-9) in the // given row ,col ->we move to next column if (isSafe(grid, row, col, num)) { /* assigning the num in the current (row,col) position of the grid and assuming our assigned num in the position is correct */ grid[row,col] = num; // Checking for next // possibility with next column if (solveSudoku(grid, row, col + 1)) return true; } /* removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value */ grid[row,col] = 0; } return false; } /* A utility function to print grid */ static void print(int[,] grid) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(grid[i,j] + \" \"); Console.WriteLine(); } } // Check whether it will be legal // to assign num to the // given row, col static bool isSafe(int[,] grid, int row, int col, int num) { // Check if we find the same num // in the similar row , we // return false for (int x = 0; x <= 8; x++) if (grid[row,x] == num) return false; // Check if we find the same num // in the similar column , // we return false for (int x = 0; x <= 8; x++) if (grid[x,col] == num) return false; // Check if we find the same num // in the particular 3*3 // matrix, we return false int startRow = row - row % 3, startCol = col - col % 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (grid[i + startRow,j + startCol] == num) return false; return true; } // Driver code static void Main() { int[,] grid = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 } }; if (solveSudoku(grid, 0, 0)) print(grid); else Console.WriteLine(\"No Solution exists\"); }} // This code is contributed by code_hunt.", "e": 65584, "s": 62022, "text": null }, { "code": "<script> const N = 9 // Bitmasks for each row/column/boxlet row = new Array(N), col = new Array(N), box = new Array(N);let seted = false; // Utility function to find the box index// of an element at position [i][j] in the gridfunction getBox(i,j){ return Math.floor(i / 3) * 3 + Math.floor(j / 3);} // Utility function to check if a number// is present in the coresponding row/column/boxfunction isSafe(i,j,number){ return !((row[i] >> number) & 1) && !((col[j] >> number) & 1) && !((box[getBox(i,j)] >> number) & 1);} // Utility function to set the initial values of a Sudoku board// (map the values in the bitmasks)function setInitialValues(grid){ for (let i = 0; i < N;i++) for (let j = 0; j < N; j++) row[i] |= 1 << grid[i][j], col[j] |= 1 << grid[i][j], box[getBox(i, j)] |= 1 << grid[i][j];} /* Takes a partially filled-in grid and attemptsto assign values to all unassigned locations insuch a way to meet the requirements forSudoku solution (non-duplication across rows,columns, and boxes) */function SolveSudoku(grid ,i, j){ // Set the initial values if(!seted){ seted = true, setInitialValues(grid); } if(i == N - 1 && j == N) return true; if(j == N){ j = 0; i++; } if(grid[i][j]) return SolveSudoku(grid, i, j + 1); for (let nr = 1; nr <= N;nr++) { if(isSafe(i, j, nr)) { /* Assign nr in the current (i, j) position and add nr to each bitmask */ grid[i][j] = nr; row[i] |= 1 << nr; col[j] |= 1 << nr; box[getBox(i, j)] |= 1 << nr; if(SolveSudoku(grid, i,j + 1)) return true; // Remove nr from each bitmask // and search for another possibility row[i] &= ~(1 << nr); col[j] &= ~(1 << nr); box[getBox(i, j)] &= ~(1 << nr); } grid[i][j] = 0; } return false;} // Utility function to print the solved gridfunction print(grid){ for (let i = 0; i < N; i++){ for (let j = 0; j < N; j++){ document.write(grid[i][j],\" \"); } document.write(\"</br>\"); }} // Driver Code // 0 means unassigned cells let grid = [ [ 3, 0, 6, 5, 0, 8, 4, 0, 0 ], [ 5, 2, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 8, 7, 0, 0, 0, 0, 3, 1 ], [ 0, 0, 3, 0, 1, 0, 0, 8, 0 ], [ 9, 0, 0, 8, 6, 3, 0, 0, 5 ], [ 0, 5, 0, 0, 9, 0, 6, 0, 0 ], [ 1, 3, 0, 0, 0, 0, 2, 5, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 7, 4 ], [ 0, 0, 5, 2, 0, 6, 3, 0, 0 ]]; if (SolveSudoku(grid,0 ,0)) print(grid); else document.write(\"No solution exists\",\"</br>\"); // This code is contributed by shinjanpatra </script>", "e": 68514, "s": 65584, "text": null }, { "code": null, "e": 68685, "s": 68514, "text": "3 1 6 5 7 8 4 9 2 \n5 2 9 1 3 4 7 6 8 \n4 8 7 6 2 9 5 3 1 \n2 6 3 4 1 5 9 8 7 \n9 7 4 8 6 3 1 2 5 \n8 5 1 7 9 2 6 4 3 \n1 3 8 9 4 7 2 5 6 \n6 9 2 3 5 1 8 7 4 \n7 4 5 2 8 6 3 1 9 " }, { "code": null, "e": 68709, "s": 68685, "text": " Complexity Analysis: " }, { "code": null, "e": 68932, "s": 68709, "text": "Time complexity: O(9^(n*n)). For every unassigned index, there are 9 possible options so the time complexity is O(9^(n*n)). The time complexity remains the same but checking if a number is safe to use is much faster, O(1)." }, { "code": null, "e": 69062, "s": 68932, "text": "Space Complexity: O(n*n). To store the output array a matrix is needed, and 3 extra arrays of size n are needed for the bitmasks." }, { "code": null, "e": 69072, "s": 69062, "text": "Mohan Das" }, { "code": null, "e": 69079, "s": 69072, "text": "Nikash" }, { "code": null, "e": 69091, "s": 69079, "text": "29AjayKumar" }, { "code": null, "e": 69105, "s": 69091, "text": "rathbhupendra" }, { "code": null, "e": 69119, "s": 69105, "text": "ManasChhabra2" }, { "code": null, "e": 69130, "s": 69119, "text": "andrew1234" }, { "code": null, "e": 69145, "s": 69130, "text": "pradeepmondalp" }, { "code": null, "e": 69168, "s": 69145, "text": "patiladarsh98032321212" }, { "code": null, "e": 69188, "s": 69168, "text": "sudhanshugupta2019a" }, { "code": null, "e": 69202, "s": 69188, "text": "divyesh072019" }, { "code": null, "e": 69210, "s": 69202, "text": "rag2127" }, { "code": null, "e": 69231, "s": 69210, "text": "avanitrachhadiya2155" }, { "code": null, "e": 69251, "s": 69231, "text": "abhishek0719kadiyan" }, { "code": null, "e": 69264, "s": 69251, "text": "simmytarika5" }, { "code": null, "e": 69277, "s": 69264, "text": "davidgatea21" }, { "code": null, "e": 69294, "s": 69277, "text": "surinderdawra388" }, { "code": null, "e": 69307, "s": 69294, "text": "shinjanpatra" }, { "code": null, "e": 69317, "s": 69307, "text": "sanjoy_62" }, { "code": null, "e": 69327, "s": 69317, "text": "code_hunt" }, { "code": null, "e": 69344, "s": 69327, "text": "hardikkoriintern" }, { "code": null, "e": 69351, "s": 69344, "text": "Amazon" }, { "code": null, "e": 69359, "s": 69351, "text": "Directi" }, { "code": null, "e": 69368, "s": 69359, "text": "Flipkart" }, { "code": null, "e": 69375, "s": 69368, "text": "Google" }, { "code": null, "e": 69386, "s": 69375, "text": "MakeMyTrip" }, { "code": null, "e": 69399, "s": 69386, "text": "MAQ Software" }, { "code": null, "e": 69409, "s": 69399, "text": "Microsoft" }, { "code": null, "e": 69418, "s": 69409, "text": "Ola Cabs" }, { "code": null, "e": 69425, "s": 69418, "text": "Oracle" }, { "code": null, "e": 69432, "s": 69425, "text": "PayPal" }, { "code": null, "e": 69437, "s": 69432, "text": "Zoho" }, { "code": null, "e": 69450, "s": 69437, "text": "Backtracking" }, { "code": null, "e": 69457, "s": 69450, "text": "Matrix" }, { "code": null, "e": 69462, "s": 69457, "text": "Zoho" }, { "code": null, "e": 69471, "s": 69462, "text": "Flipkart" }, { "code": null, "e": 69478, "s": 69471, "text": "Amazon" }, { "code": null, "e": 69488, "s": 69478, "text": "Microsoft" }, { "code": null, "e": 69499, "s": 69488, "text": "MakeMyTrip" }, { "code": null, "e": 69508, "s": 69499, "text": "Ola Cabs" }, { "code": null, "e": 69515, "s": 69508, "text": "Oracle" }, { "code": null, "e": 69528, "s": 69515, "text": "MAQ Software" }, { "code": null, "e": 69536, "s": 69528, "text": "Directi" }, { "code": null, "e": 69543, "s": 69536, "text": "Google" }, { "code": null, "e": 69550, "s": 69543, "text": "PayPal" }, { "code": null, "e": 69557, "s": 69550, "text": "Matrix" }, { "code": null, "e": 69570, "s": 69557, "text": "Backtracking" }, { "code": null, "e": 69668, "s": 69570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 69753, "s": 69668, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 69795, "s": 69753, "text": "Generate all the binary strings of N bits" }, { "code": null, "e": 69848, "s": 69795, "text": "Print all paths from a given source to a destination" }, { "code": null, "e": 69891, "s": 69848, "text": "Print all permutations of a string in Java" }, { "code": null, "e": 69951, "s": 69891, "text": "Find if there is a path of more than k length from a source" }, { "code": null, "e": 69986, "s": 69951, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 70022, "s": 69986, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 70066, "s": 70022, "text": "Program to find largest element in an array" }, { "code": null, "e": 70088, "s": 70066, "text": "The Celebrity Problem" } ]
How to convert Python date string mm/dd/yyyy to datetime?
You can convert a string to date object using the strptime function. Provide the date string and the format in which the date is specified. import datetime date_str = '29/12/2017' # The date - 29 Dec 2017 format_str = '%d/%m/%Y' # The format datetime_obj = datetime.datetime.strptime(date_str, format_str) print(datetime_obj.date()) This will give the output − 2017-12-29
[ { "code": null, "e": 1328, "s": 1187, "text": "You can convert a string to date object using the strptime function. Provide the date string and the format in which the date is specified. " }, { "code": null, "e": 1521, "s": 1328, "text": "import datetime\ndate_str = '29/12/2017' # The date - 29 Dec 2017\nformat_str = '%d/%m/%Y' # The format\ndatetime_obj = datetime.datetime.strptime(date_str, format_str)\nprint(datetime_obj.date())" }, { "code": null, "e": 1549, "s": 1521, "text": "This will give the output −" }, { "code": null, "e": 1560, "s": 1549, "text": "2017-12-29" } ]
Python NLTK | tokenize.regexp()
07 Jun, 2019 With the help of NLTK tokenize.regexp() module, we are able to extract the tokens from string by using regular expression with RegexpTokenizer() method. Syntax : tokenize.RegexpTokenizer()Return : Return array of tokens using regular expression Example #1 :In this example we are using RegexpTokenizer() method to extract the stream of tokens with the help of regular expressions. # import RegexpTokenizer() method from nltkfrom nltk.tokenize import RegexpTokenizer # Create a reference variable for Class RegexpTokenizertk = RegexpTokenizer('\s+', gaps = True) # Create a string inputgfg = "I love Python" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek) Output : [‘I’, ‘love’, ‘Python’] Example #2 : # import RegexpTokenizer() method from nltkfrom nltk.tokenize import RegexpTokenizer # Create a reference variable for Class RegexpTokenizertk = RegexpTokenizer('\s+', gaps = True) # Create a string inputgfg = "Geeks for Geeks" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek) Output : [‘Geeks’, ‘for’, ‘Geeks’] Python-nltk Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jun, 2019" }, { "code": null, "e": 181, "s": 28, "text": "With the help of NLTK tokenize.regexp() module, we are able to extract the tokens from string by using regular expression with RegexpTokenizer() method." }, { "code": null, "e": 273, "s": 181, "text": "Syntax : tokenize.RegexpTokenizer()Return : Return array of tokens using regular expression" }, { "code": null, "e": 409, "s": 273, "text": "Example #1 :In this example we are using RegexpTokenizer() method to extract the stream of tokens with the help of regular expressions." }, { "code": "# import RegexpTokenizer() method from nltkfrom nltk.tokenize import RegexpTokenizer # Create a reference variable for Class RegexpTokenizertk = RegexpTokenizer('\\s+', gaps = True) # Create a string inputgfg = \"I love Python\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)", "e": 704, "s": 409, "text": null }, { "code": null, "e": 713, "s": 704, "text": "Output :" }, { "code": null, "e": 737, "s": 713, "text": "[‘I’, ‘love’, ‘Python’]" }, { "code": null, "e": 750, "s": 737, "text": "Example #2 :" }, { "code": "# import RegexpTokenizer() method from nltkfrom nltk.tokenize import RegexpTokenizer # Create a reference variable for Class RegexpTokenizertk = RegexpTokenizer('\\s+', gaps = True) # Create a string inputgfg = \"Geeks for Geeks\" # Use tokenize methodgeek = tk.tokenize(gfg) print(geek)", "e": 1047, "s": 750, "text": null }, { "code": null, "e": 1056, "s": 1047, "text": "Output :" }, { "code": null, "e": 1082, "s": 1056, "text": "[‘Geeks’, ‘for’, ‘Geeks’]" }, { "code": null, "e": 1094, "s": 1082, "text": "Python-nltk" }, { "code": null, "e": 1101, "s": 1094, "text": "Python" } ]
Latches in Digital Logic
21 Jun, 2022 Latches are basic storage elements that operate with signal levels (rather than signal transitions). Latches controlled by a clock transition are flip-flops. Latches are level-sensitive devices. Latches are useful for the design of the asynchronous sequential circuit. Latches are sequential circuit with two stable states. These are sensitive to the input voltage applied and does not depend on the clock pulse. Flip flops that do not use clock pulse are referred to as latch. SR (Set-Reset) Latch – They are also known as preset and clear states. The SR latch forms the basic building blocks of all other types of flip-flops. SR Latch is a circuit with: (i) 2 cross-coupled NOR gate or 2 cross-coupled NAND gate. (ii) 2 input S for SET and R for RESET. (iii) 2 output Q, Q’. Under normal conditions, both the input remains 0. The following is the RS Latch with NAND gates: Case-1: S’=R’=1 (S=R=0) – If Q = 1, Q and R’ inputs for 2nd NAND gate are both 1. If Q = 0, Q and R’ inputs for 2nd NAND gate are 0 and 1 respectively. Case-2: S’=0, R’=1 (S=1, R=0) – As S’=0, the output of 1st NAND gate, Q = 1(SET state). In 2nd NAND gate, as Q and R’ inputs are 1, Q’=0. Case-3: S’= 1, R’= 0 (S=0, R=1) – As R’=0, the output of 2nd NAND gate, Q’ = 1. In 1st NAND gate, as Q and S’ inputs are 1, Q=0(RESET state). Case-4: S’= R’= 0 (S=R=1) – When S=R=1, both Q and Q’ becomes 1 which is not allowed. So, the input condition is prohibited. The SR Latch using NOR gate is shown below: Gated SR Latch – A Gated SR latch is a SR latch with enable input which works when enable is 1 and retain the previous state when enable is 0. Gated D Latch – D latch is similar to SR latch with some modifications made. Here, the inputs are complements of each other. The letter in the D latch stands for “data” as this latch stores single bit temporarily. The design of D latch with Enable signal is given below: The truth table for the D-Latch is shown below: As the output is same as the input D, D latch is also called as Transparent Latch. Considering the truth table, the characteristic equation for D latch with enable input can be given as: Q(n+1) = EN.D + EN'.Q(n) Reference: DIGITAL ELECTRONICS – Atul P. Godse, Mrs. Deepali A. Godse manikandan20061999 animeshmaru16 dishaagrawal1 Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 532, "s": 54, "text": "Latches are basic storage elements that operate with signal levels (rather than signal transitions). Latches controlled by a clock transition are flip-flops. Latches are level-sensitive devices. Latches are useful for the design of the asynchronous sequential circuit. Latches are sequential circuit with two stable states. These are sensitive to the input voltage applied and does not depend on the clock pulse. Flip flops that do not use clock pulse are referred to as latch." }, { "code": null, "e": 682, "s": 532, "text": "SR (Set-Reset) Latch – They are also known as preset and clear states. The SR latch forms the basic building blocks of all other types of flip-flops." }, { "code": null, "e": 832, "s": 682, "text": "SR Latch is a circuit with: (i) 2 cross-coupled NOR gate or 2 cross-coupled NAND gate. (ii) 2 input S for SET and R for RESET. (iii) 2 output Q, Q’. " }, { "code": null, "e": 933, "s": 834, "text": "Under normal conditions, both the input remains 0. The following is the RS Latch with NAND gates: " }, { "code": null, "e": 1088, "s": 935, "text": "Case-1: S’=R’=1 (S=R=0) – If Q = 1, Q and R’ inputs for 2nd NAND gate are both 1. If Q = 0, Q and R’ inputs for 2nd NAND gate are 0 and 1 respectively. " }, { "code": null, "e": 1229, "s": 1090, "text": "Case-2: S’=0, R’=1 (S=1, R=0) – As S’=0, the output of 1st NAND gate, Q = 1(SET state). In 2nd NAND gate, as Q and R’ inputs are 1, Q’=0. " }, { "code": null, "e": 1374, "s": 1231, "text": "Case-3: S’= 1, R’= 0 (S=0, R=1) – As R’=0, the output of 2nd NAND gate, Q’ = 1. In 1st NAND gate, as Q and S’ inputs are 1, Q=0(RESET state). " }, { "code": null, "e": 1502, "s": 1376, "text": "Case-4: S’= R’= 0 (S=R=1) – When S=R=1, both Q and Q’ becomes 1 which is not allowed. So, the input condition is prohibited. " }, { "code": null, "e": 1547, "s": 1502, "text": "The SR Latch using NOR gate is shown below: " }, { "code": null, "e": 1693, "s": 1549, "text": "Gated SR Latch – A Gated SR latch is a SR latch with enable input which works when enable is 1 and retain the previous state when enable is 0. " }, { "code": null, "e": 1910, "s": 1695, "text": "Gated D Latch – D latch is similar to SR latch with some modifications made. Here, the inputs are complements of each other. The letter in the D latch stands for “data” as this latch stores single bit temporarily." }, { "code": null, "e": 1968, "s": 1910, "text": "The design of D latch with Enable signal is given below: " }, { "code": null, "e": 2020, "s": 1970, "text": "The truth table for the D-Latch is shown below: " }, { "code": null, "e": 2209, "s": 2020, "text": "As the output is same as the input D, D latch is also called as Transparent Latch. Considering the truth table, the characteristic equation for D latch with enable input can be given as: " }, { "code": null, "e": 2234, "s": 2209, "text": "Q(n+1) = EN.D + EN'.Q(n)" }, { "code": null, "e": 2305, "s": 2234, "text": "Reference: DIGITAL ELECTRONICS – Atul P. Godse, Mrs. Deepali A. Godse " }, { "code": null, "e": 2324, "s": 2305, "text": "manikandan20061999" }, { "code": null, "e": 2338, "s": 2324, "text": "animeshmaru16" }, { "code": null, "e": 2352, "s": 2338, "text": "dishaagrawal1" }, { "code": null, "e": 2387, "s": 2352, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 2395, "s": 2387, "text": "GATE CS" } ]
Console.SetWindowPosition() Method in C#
14 Mar, 2019 Console.SetWindowPosition(Int32, Int32) Method in C# is used to set the position of the console window relative to the screen buffer. Syntax: public static void SetWindowposition(int left, int top); Parameters:left: It is the column position of the upper left corner of the console window.top: It is the row position of the upper left corner of the console window. Exceptions: ArgumentOutOfRangeException: When left or top is less than 0 or left + WindowWidth > BufferWidth or top + Windowheight > BufferHeight. SecurityException: If the user doesn’t have the permission to perform this action. Example: // C# Program to illustrate the use of // Console.WindowPosition() methodusing System;using System.Text;using System.IO; class GFG { // Main Method public static void Main(string[] args) { Console.SetWindowSize(20, 20); // setting buffer size Console.SetBufferSize(80, 80); // using the method Console.SetWindowPosition(0, 0); Console.WriteLine("Hello GFG!"); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }} Output: When Console.WindowPosition() method is not used: Reference: https://docs.microsoft.com/en-us/dotnet/api/system.console.setwindowposition?view=netframework-4.7.2 CSharp-Console-Class CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Mar, 2019" }, { "code": null, "e": 187, "s": 53, "text": "Console.SetWindowPosition(Int32, Int32) Method in C# is used to set the position of the console window relative to the screen buffer." }, { "code": null, "e": 252, "s": 187, "text": "Syntax: public static void SetWindowposition(int left, int top);" }, { "code": null, "e": 418, "s": 252, "text": "Parameters:left: It is the column position of the upper left corner of the console window.top: It is the row position of the upper left corner of the console window." }, { "code": null, "e": 430, "s": 418, "text": "Exceptions:" }, { "code": null, "e": 565, "s": 430, "text": "ArgumentOutOfRangeException: When left or top is less than 0 or left + WindowWidth > BufferWidth or top + Windowheight > BufferHeight." }, { "code": null, "e": 648, "s": 565, "text": "SecurityException: If the user doesn’t have the permission to perform this action." }, { "code": null, "e": 657, "s": 648, "text": "Example:" }, { "code": "// C# Program to illustrate the use of // Console.WindowPosition() methodusing System;using System.Text;using System.IO; class GFG { // Main Method public static void Main(string[] args) { Console.SetWindowSize(20, 20); // setting buffer size Console.SetBufferSize(80, 80); // using the method Console.SetWindowPosition(0, 0); Console.WriteLine(\"Hello GFG!\"); Console.Write(\"Press any key to continue . . . \"); Console.ReadKey(true); }}", "e": 1173, "s": 657, "text": null }, { "code": null, "e": 1181, "s": 1173, "text": "Output:" }, { "code": null, "e": 1231, "s": 1181, "text": "When Console.WindowPosition() method is not used:" }, { "code": null, "e": 1242, "s": 1231, "text": "Reference:" }, { "code": null, "e": 1343, "s": 1242, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.console.setwindowposition?view=netframework-4.7.2" }, { "code": null, "e": 1364, "s": 1343, "text": "CSharp-Console-Class" }, { "code": null, "e": 1378, "s": 1364, "text": "CSharp-method" }, { "code": null, "e": 1385, "s": 1378, "text": "Picked" }, { "code": null, "e": 1388, "s": 1385, "text": "C#" } ]
Google Online Challenge for Summer Internship 2021
01 Oct, 2020 The Google online challenge 2020 for summer internships 2021 was held on Sept 26. It was a 60-minute online test having 2 questions to code. First Question: You are given an array A with N integers. you are required to answer Q queries of the following types. Determine the count of distinct prime numbers which divides all the numbers in a given range L to R. NOTE:1 based Indexing. 1 <=N,Q<= 10^5; 1 <= A[i] <= 10^5; 1 <= L <= R <= N Input: No of test cases Array size i.e N N array elements No of Queries i.e Q Q queries Output: Return count of distinct prime numbers which divides all the numbers in a given range for each query Sample Input: 1 6 4 6 3 18 36 54 3 1 2 3 6 4 6 Sample output: 1 1 2 I do not remember the second question exactly. But It was also based on arrays. Prepare for query-based array questions, MO’s algorithm, Segment tree(if possible) standard questions like range sum queries, update range queries, etc. Google Marketing Internship Interview Experiences Google Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021 Zoho Interview Experience (Off-Campus ) 2022 Microsoft Interview Experience for SWE Intern Microsoft Interview Experience for SWE Intern (On-Campus) Cisco Interview Experience for Network Engineer (On-Campus) 2021 Amazon Interview Questions Amazon Interview Experience for SDE 1 Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience SDE-2 (3 Years Experienced) Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Oct, 2020" }, { "code": null, "e": 195, "s": 54, "text": "The Google online challenge 2020 for summer internships 2021 was held on Sept 26. It was a 60-minute online test having 2 questions to code." }, { "code": null, "e": 314, "s": 195, "text": "First Question: You are given an array A with N integers. you are required to answer Q queries of the following types." }, { "code": null, "e": 438, "s": 314, "text": "Determine the count of distinct prime numbers which divides all the numbers in a given range L to R. NOTE:1 based Indexing." }, { "code": null, "e": 454, "s": 438, "text": "1 <=N,Q<= 10^5;" }, { "code": null, "e": 473, "s": 454, "text": "1 <= A[i] <= 10^5;" }, { "code": null, "e": 490, "s": 473, "text": "1 <= L <= R <= N" }, { "code": null, "e": 498, "s": 490, "text": "Input: " }, { "code": null, "e": 579, "s": 498, "text": "No of test cases\nArray size i.e N\nN array elements\nNo of Queries i.e Q\nQ queries" }, { "code": null, "e": 688, "s": 579, "text": "Output: Return count of distinct prime numbers which divides all the numbers in a given range for each query" }, { "code": null, "e": 704, "s": 688, "text": "Sample Input: " }, { "code": null, "e": 737, "s": 704, "text": "1\n6\n4 6 3 18 36 54\n3\n1 2\n3 6\n4 6" }, { "code": null, "e": 752, "s": 737, "text": "Sample output:" }, { "code": null, "e": 758, "s": 752, "text": "1\n1\n2" }, { "code": null, "e": 991, "s": 758, "text": "I do not remember the second question exactly. But It was also based on arrays. Prepare for query-based array questions, MO’s algorithm, Segment tree(if possible) standard questions like range sum queries, update range queries, etc." }, { "code": null, "e": 998, "s": 991, "text": "Google" }, { "code": null, "e": 1008, "s": 998, "text": "Marketing" }, { "code": null, "e": 1019, "s": 1008, "text": "Internship" }, { "code": null, "e": 1041, "s": 1019, "text": "Interview Experiences" }, { "code": null, "e": 1048, "s": 1041, "text": "Google" }, { "code": null, "e": 1146, "s": 1048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1229, "s": 1146, "text": "Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021" }, { "code": null, "e": 1274, "s": 1229, "text": "Zoho Interview Experience (Off-Campus ) 2022" }, { "code": null, "e": 1320, "s": 1274, "text": "Microsoft Interview Experience for SWE Intern" }, { "code": null, "e": 1378, "s": 1320, "text": "Microsoft Interview Experience for SWE Intern (On-Campus)" }, { "code": null, "e": 1443, "s": 1378, "text": "Cisco Interview Experience for Network Engineer (On-Campus) 2021" }, { "code": null, "e": 1470, "s": 1443, "text": "Amazon Interview Questions" }, { "code": null, "e": 1508, "s": 1470, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 1568, "s": 1508, "text": "Commonly Asked Java Programming Interview Questions | Set 2" }, { "code": null, "e": 1624, "s": 1568, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" } ]
How to Include *.so Library in Android Studio?
16 Jun, 2021 The SO file stands for Shared Library. You compile all C++ code into the.SO file when you write it in C or C++. The SO file is a shared object library that may be dynamically loaded during Android runtime. Library files are larger, often ranging from 2MB to 10MB in size. As a result, the app becomes bloated. Another thing to keep in mind is that several.SO files need to be included in the APK to support several architectures such as armeabi and x86. .so files are the ABI Files, ABI stands for Application Binary Interface. The ABI specifies how your app’s machine code should communicate with the OS during execution. The NDK is a software development kit. As a result, files are compared to these definitions. So what if you want to include some .so files in your Android App or Android Project, well there are several ways to do that, but we will be finding out the perfect ones that can help you get the library included in no time! Keep on reading this article! Create a folder called “jniLibs” in your app, along with the directories that contain your *.so. The “jniLibs” folder should be established alongside your “Java” and “Assets” directories. It is feasible to avoid creating a new folder and maintain your *.so files in the libs folder! In that case, just place your *.so files in the libs folder (following the same architecture as Solution 1: libs/armeabi/.so, for example) and update your app’s build.gradle file to include the jniLibs source directory. Put your .so files in the libs folder as shown in the folder to add them Figure 1. Understanding the Structure of the .jar & so file Then add this code to your project compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar') task copyJniLibs(type: Copy) { from 'libs/armeabi' into 'src/main/jniLibs/armeabi' } tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn(copyJniLibs) } clean.dependsOn 'cleanCopyJniLibs' If you’re using Android Studio 4.1.2, and have tried to specify the NDK Path in File -> Project Structure -> SDK Location Now you’ll need to manually configure the NDK version in local.properties and establish a jniLibs folder with the ABIs and their corresponding. so files in the build.gradle and defining the ABI filters and NDK version. That’s it for this article, hope you got your perfect solution on how to Include the .so file! Android-Studio Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget How to Add Views Dynamically and Store Data in Arraylist in Android? Introduction to Android Development Animation in Android with Example Fragment Lifecycle in Android Data Binding in Android with Example
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2021" }, { "code": null, "e": 770, "s": 54, "text": "The SO file stands for Shared Library. You compile all C++ code into the.SO file when you write it in C or C++. The SO file is a shared object library that may be dynamically loaded during Android runtime. Library files are larger, often ranging from 2MB to 10MB in size. As a result, the app becomes bloated. Another thing to keep in mind is that several.SO files need to be included in the APK to support several architectures such as armeabi and x86. .so files are the ABI Files, ABI stands for Application Binary Interface. The ABI specifies how your app’s machine code should communicate with the OS during execution. The NDK is a software development kit. As a result, files are compared to these definitions." }, { "code": null, "e": 1025, "s": 770, "text": "So what if you want to include some .so files in your Android App or Android Project, well there are several ways to do that, but we will be finding out the perfect ones that can help you get the library included in no time! Keep on reading this article!" }, { "code": null, "e": 1213, "s": 1025, "text": "Create a folder called “jniLibs” in your app, along with the directories that contain your *.so. The “jniLibs” folder should be established alongside your “Java” and “Assets” directories." }, { "code": null, "e": 1528, "s": 1213, "text": "It is feasible to avoid creating a new folder and maintain your *.so files in the libs folder! In that case, just place your *.so files in the libs folder (following the same architecture as Solution 1: libs/armeabi/.so, for example) and update your app’s build.gradle file to include the jniLibs source directory." }, { "code": null, "e": 1601, "s": 1528, "text": "Put your .so files in the libs folder as shown in the folder to add them" }, { "code": null, "e": 1661, "s": 1601, "text": "Figure 1. Understanding the Structure of the .jar & so file" }, { "code": null, "e": 1696, "s": 1661, "text": "Then add this code to your project" }, { "code": null, "e": 1771, "s": 1696, "text": "compile fileTree(dir: \"$buildDir/native-libs\", include: 'native-libs.jar')" }, { "code": null, "e": 1982, "s": 1771, "text": "task copyJniLibs(type: Copy) {\n from 'libs/armeabi'\n into 'src/main/jniLibs/armeabi'\n}\ntasks.withType(JavaCompile) {\n compileTask -> compileTask.dependsOn(copyJniLibs)\n}\nclean.dependsOn 'cleanCopyJniLibs'" }, { "code": null, "e": 2054, "s": 1982, "text": "If you’re using Android Studio 4.1.2, and have tried to specify the NDK" }, { "code": null, "e": 2104, "s": 2054, "text": "Path in File -> Project Structure -> SDK Location" }, { "code": null, "e": 2418, "s": 2104, "text": "Now you’ll need to manually configure the NDK version in local.properties and establish a jniLibs folder with the ABIs and their corresponding. so files in the build.gradle and defining the ABI filters and NDK version. That’s it for this article, hope you got your perfect solution on how to Include the .so file!" }, { "code": null, "e": 2433, "s": 2418, "text": "Android-Studio" }, { "code": null, "e": 2440, "s": 2433, "text": "Picked" }, { "code": null, "e": 2448, "s": 2440, "text": "Android" }, { "code": null, "e": 2456, "s": 2448, "text": "Android" }, { "code": null, "e": 2554, "s": 2456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2586, "s": 2554, "text": "Android SDK and it's Components" }, { "code": null, "e": 2625, "s": 2586, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 2667, "s": 2625, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 2718, "s": 2667, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 2741, "s": 2718, "text": "Flutter - Stack Widget" }, { "code": null, "e": 2810, "s": 2741, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 2846, "s": 2810, "text": "Introduction to Android Development" }, { "code": null, "e": 2880, "s": 2846, "text": "Animation in Android with Example" }, { "code": null, "e": 2910, "s": 2880, "text": "Fragment Lifecycle in Android" } ]
Number of rectangles in a circle of radius R
16 Jul, 2021 Given a circular sheet of radius R and the task is to find the total number of rectangles with integral length and width that can be cut from the circular sheet, one at a time. Examples: Input: R = 2 Output: 8 8 rectangles can be cut from a circular sheet of radius 2. These are: 1×1, 1×2, 2×1, 2×2, 1×3, 3×1, 2×3, 3×2.Input: R = 1 Output: 1 Only one rectangle with dimensions 1 X 1 is possible. Approach Consider the following diagram, Its easy to see, that ABCD is the largest rectangle that can be formed in the given circle with radius R and centre O, having dimensions a X bDrop a perpendicular AO such that, ∠AOD = ∠AOB = 90° Consider the following diagram for further analysis, Consider triangles AOD and AOB, In these triangles, AO = AO (Common Side) ∠AOD = ∠AOB = 90° OD = OB = R Thus, by SAS congruence ▵AOD ≅ ▵AOB ∴ AD = AB by CPCT(i.e Corresponding Parts on Congruent Triangles) or, a = b => The rectangle ABCD is a square The diameter BD is the maximum diagonal the rectangle can have to be able to be cut from the Circular Sheet.Thus, all the combinations of a and b can be checked to form all possible rectangles, and if the diagonal of any such rectangle is less than or equal to the length of the diagonal of the largest rectangle formed (i.e 2 * R, where R is the Radius of the circle as explained above)Now, the maximum length of a and b will always be strictly less than the diameter of the circle so all possible values of a and b will lie in the closed interval [1, (2 * R – 1)].Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the number of rectangles// that can be cut from a circle of Radius R#include <bits/stdc++.h>using namespace std; // Function to return the total possible// rectangles that can be cut from the circleint countRectangles(int radius){ int rectangles = 0; // Diameter = 2 * Radius int diameter = 2 * radius; // Square of diameter which is the square // of the maximum length diagonal int diameterSquare = diameter * diameter; // generate all combinations of a and b // in the range (1, (2 * Radius - 1))(Both inclusive) for (int a = 1; a < 2 * radius; a++) { for (int b = 1; b < 2 * radius; b++) { // Calculate the Diagonal length of // this rectangle int diagonalLengthSquare = (a * a + b * b); // If this rectangle's Diagonal Length // is less than the Diameter, it is a // valid rectangle, thus increment counter if (diagonalLengthSquare <= diameterSquare) { rectangles++; } } } return rectangles;} // Driver Codeint main(){ // Radius of the circle int radius = 2; int totalRectangles; totalRectangles = countRectangles(radius); cout << totalRectangles << " rectangles can be" << "cut from a circle of Radius " << radius; return 0;} // Java program to find the// number of rectangles that// can be cut from a circle// of Radius Rimport java.io.*; class GFG{ // Function to return// the total possible// rectangles that can// be cut from the circlestatic int countRectangles(int radius){ int rectangles = 0; // Diameter = 2 * Radius int diameter = 2 * radius; // Square of diameter // which is the square // of the maximum length // diagonal int diameterSquare = diameter * diameter; // generate all combinations // of a and b in the range // (1, (2 * Radius - 1)) // (Both inclusive) for (int a = 1; a < 2 * radius; a++) { for (int b = 1; b < 2 * radius; b++) { // Calculate the // Diagonal length of // this rectangle int diagonalLengthSquare = (a * a + b * b); // If this rectangle's Diagonal // Length is less than the Diameter, // it is a valid rectangle, thus // increment counter if (diagonalLengthSquare <= diameterSquare) { rectangles++; } } } return rectangles;} // Driver Codepublic static void main (String[] args){ // Radius of the circleint radius = 2; int totalRectangles;totalRectangles = countRectangles(radius);System.out.println(totalRectangles + " rectangles can be " + "cut from a circle of" + " Radius " + radius);}} // This code is contributed// by anuj_67. # Python3 program to find# the number of rectangles# that can be cut from a# circle of Radius R Function# to return the total possible# rectangles that can be cut# from the circledef countRectangles(radius): rectangles = 0 # Diameter = 2 * Radius diameter = 2 * radius # Square of diameter which # is the square of the # maximum length diagonal diameterSquare = diameter * diameter # generate all combinations # of a and b in the range # (1, (2 * Radius - 1))(Both inclusive) for a in range(1, 2 * radius): for b in range(1, 2 * radius): # Calculate the Diagonal # length of this rectangle diagonalLengthSquare = (a * a + b * b) # If this rectangle's Diagonal # Length is less than the # Diameter, it is a valid # rectangle, thus increment counter if (diagonalLengthSquare <= diameterSquare) : rectangles += 1 return rectangles # Driver Code # Radius of the circleradius = 2totalRectangles = countRectangles(radius)print(totalRectangles , "rectangles can be" , "cut from a circle of Radius" , radius) # This code is contributed by Smita // C# program to find the// number of rectangles that// can be cut from a circle// of Radius Rusing System; class GFG{ // Function to return// the total possible// rectangles that can// be cut from the circlestatic int countRectangles(int radius){ int rectangles = 0; // Diameter = 2 * Radius int diameter = 2 * radius; // Square of diameter // which is the square // of the maximum length // diagonal int diameterSquare = diameter * diameter; // generate all combinations // of a and b in the range // (1, (2 * Radius - 1)) // (Both inclusive) for (int a = 1; a < 2 * radius; a++) { for (int b = 1; b < 2 * radius; b++) { // Calculate the // Diagonal length of // this rectangle int diagonalLengthSquare = (a * a + b * b); // If this rectangle's // Diagonal Length is // less than the Diameter, // it is a valid rectangle, // thus increment counter if (diagonalLengthSquare <= diameterSquare) { rectangles++; } } } return rectangles;} // Driver Codepublic static void Main (){ // Radius of the circleint radius = 2; int totalRectangles;totalRectangles = countRectangles(radius);Console.WriteLine(totalRectangles + " rectangles can be " + "cut from a circle of" + " Radius " + radius);}} // This code is contributed// by anuj_67. <?php// PHP program to find the// number of rectangles that// can be cut from a circle// of Radius R // Function to return the// total possible rectangles// that can be cut from the circlefunction countRectangles($radius){ $rectangles = 0; // Diameter = 2 * $Radius $diameter = 2 * $radius; // Square of diameter which // is the square of the // maximum length diagonal $diameterSquare = $diameter * $diameter; // generate all combinations // of a and b in the range // (1, (2 * Radius - 1))(Both inclusive) for ($a = 1; $a < 2 * $radius; $a++) { for ($b = 1; $b < 2 * $radius; $b++) { // Calculate the Diagonal // length of this rectangle $diagonalLengthSquare = ($a * $a + $b * $b); // If this rectangle's Diagonal // Length is less than the // Diameter, it is a valid // rectangle, thus increment counter if ($diagonalLengthSquare <= $diameterSquare) { $rectangles++; } } } return $rectangles;} // Driver Code // Radius of the circle$radius = 2; $totalRectangles;$totalRectangles = countRectangles($radius);echo $totalRectangles , " rectangles can be " , "cut from a circle of Radius " , $radius; // This code is contributed// by anuj_67.?> <script>// java script program to find the// number of rectangles that// can be cut from a circle// of Radius R // Function to return the// total possible rectangles// that can be cut from the circlefunction countRectangles(radius){ let rectangles = 0; // Diameter = 2 * $Radius let diameter = 2 * radius; // Square of diameter which // is the square of the // maximum length diagonal let diameterSquare = diameter * diameter; // generate all combinations // of a and b in the range // (1, (2 * Radius - 1))(Both inclusive) for (let a = 1;a < 2 * radius; a++) { for (let b = 1; b < 2 * radius; b++) { // Calculate the Diagonal // length of this rectangle let diagonalLengthSquare = (a * a + b * b); // If this rectangle's Diagonal // Length is less than the // Diameter, it is a valid // rectangle, thus increment counter if (diagonalLengthSquare <= diameterSquare) { rectangles++; } } } return rectangles;} // Driver Code // Radius of the circlelet radius = 2; let totalRectangles;totalRectangles = countRectangles(radius);document.write( totalRectangles + " rectangles can be cut from a circle of Radius " +radius); // This code is contributed by sravan kumar</script> 8 rectangles can be cut from a circle of Radius 2 Time Complexity: O(R2), where R is the Radius of the Circle vt_m Smitha Dinesh Semwal sravankumar8128 surinderdawra388 sagar0719kumar circle math square-rectangle triangle Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jul, 2021" }, { "code": null, "e": 243, "s": 54, "text": "Given a circular sheet of radius R and the task is to find the total number of rectangles with integral length and width that can be cut from the circular sheet, one at a time. Examples: " }, { "code": null, "e": 454, "s": 243, "text": "Input: R = 2 Output: 8 8 rectangles can be cut from a circular sheet of radius 2. These are: 1×1, 1×2, 2×1, 2×2, 1×3, 3×1, 2×3, 3×2.Input: R = 1 Output: 1 Only one rectangle with dimensions 1 X 1 is possible. " }, { "code": null, "e": 499, "s": 456, "text": "Approach Consider the following diagram, " }, { "code": null, "e": 749, "s": 499, "text": "Its easy to see, that ABCD is the largest rectangle that can be formed in the given circle with radius R and centre O, having dimensions a X bDrop a perpendicular AO such that, ∠AOD = ∠AOB = 90° Consider the following diagram for further analysis, " }, { "code": null, "e": 1003, "s": 751, "text": "Consider triangles AOD and AOB,\nIn these triangles,\nAO = AO (Common Side)\n∠AOD = ∠AOB = 90° \nOD = OB = R\nThus, by SAS congruence ▵AOD ≅ ▵AOB\n∴ AD = AB by CPCT(i.e Corresponding Parts on Congruent Triangles)\nor, a = b\n=> The rectangle ABCD is a square " }, { "code": null, "e": 1622, "s": 1003, "text": "The diameter BD is the maximum diagonal the rectangle can have to be able to be cut from the Circular Sheet.Thus, all the combinations of a and b can be checked to form all possible rectangles, and if the diagonal of any such rectangle is less than or equal to the length of the diagonal of the largest rectangle formed (i.e 2 * R, where R is the Radius of the circle as explained above)Now, the maximum length of a and b will always be strictly less than the diameter of the circle so all possible values of a and b will lie in the closed interval [1, (2 * R – 1)].Below is the implementation of the above approach: " }, { "code": null, "e": 1626, "s": 1622, "text": "C++" }, { "code": null, "e": 1631, "s": 1626, "text": "Java" }, { "code": null, "e": 1639, "s": 1631, "text": "Python3" }, { "code": null, "e": 1642, "s": 1639, "text": "C#" }, { "code": null, "e": 1646, "s": 1642, "text": "PHP" }, { "code": null, "e": 1657, "s": 1646, "text": "Javascript" }, { "code": "// C++ program to find the number of rectangles// that can be cut from a circle of Radius R#include <bits/stdc++.h>using namespace std; // Function to return the total possible// rectangles that can be cut from the circleint countRectangles(int radius){ int rectangles = 0; // Diameter = 2 * Radius int diameter = 2 * radius; // Square of diameter which is the square // of the maximum length diagonal int diameterSquare = diameter * diameter; // generate all combinations of a and b // in the range (1, (2 * Radius - 1))(Both inclusive) for (int a = 1; a < 2 * radius; a++) { for (int b = 1; b < 2 * radius; b++) { // Calculate the Diagonal length of // this rectangle int diagonalLengthSquare = (a * a + b * b); // If this rectangle's Diagonal Length // is less than the Diameter, it is a // valid rectangle, thus increment counter if (diagonalLengthSquare <= diameterSquare) { rectangles++; } } } return rectangles;} // Driver Codeint main(){ // Radius of the circle int radius = 2; int totalRectangles; totalRectangles = countRectangles(radius); cout << totalRectangles << \" rectangles can be\" << \"cut from a circle of Radius \" << radius; return 0;}", "e": 2996, "s": 1657, "text": null }, { "code": "// Java program to find the// number of rectangles that// can be cut from a circle// of Radius Rimport java.io.*; class GFG{ // Function to return// the total possible// rectangles that can// be cut from the circlestatic int countRectangles(int radius){ int rectangles = 0; // Diameter = 2 * Radius int diameter = 2 * radius; // Square of diameter // which is the square // of the maximum length // diagonal int diameterSquare = diameter * diameter; // generate all combinations // of a and b in the range // (1, (2 * Radius - 1)) // (Both inclusive) for (int a = 1; a < 2 * radius; a++) { for (int b = 1; b < 2 * radius; b++) { // Calculate the // Diagonal length of // this rectangle int diagonalLengthSquare = (a * a + b * b); // If this rectangle's Diagonal // Length is less than the Diameter, // it is a valid rectangle, thus // increment counter if (diagonalLengthSquare <= diameterSquare) { rectangles++; } } } return rectangles;} // Driver Codepublic static void main (String[] args){ // Radius of the circleint radius = 2; int totalRectangles;totalRectangles = countRectangles(radius);System.out.println(totalRectangles + \" rectangles can be \" + \"cut from a circle of\" + \" Radius \" + radius);}} // This code is contributed// by anuj_67.", "e": 4589, "s": 2996, "text": null }, { "code": "# Python3 program to find# the number of rectangles# that can be cut from a# circle of Radius R Function# to return the total possible# rectangles that can be cut# from the circledef countRectangles(radius): rectangles = 0 # Diameter = 2 * Radius diameter = 2 * radius # Square of diameter which # is the square of the # maximum length diagonal diameterSquare = diameter * diameter # generate all combinations # of a and b in the range # (1, (2 * Radius - 1))(Both inclusive) for a in range(1, 2 * radius): for b in range(1, 2 * radius): # Calculate the Diagonal # length of this rectangle diagonalLengthSquare = (a * a + b * b) # If this rectangle's Diagonal # Length is less than the # Diameter, it is a valid # rectangle, thus increment counter if (diagonalLengthSquare <= diameterSquare) : rectangles += 1 return rectangles # Driver Code # Radius of the circleradius = 2totalRectangles = countRectangles(radius)print(totalRectangles , \"rectangles can be\" , \"cut from a circle of Radius\" , radius) # This code is contributed by Smita", "e": 5862, "s": 4589, "text": null }, { "code": "// C# program to find the// number of rectangles that// can be cut from a circle// of Radius Rusing System; class GFG{ // Function to return// the total possible// rectangles that can// be cut from the circlestatic int countRectangles(int radius){ int rectangles = 0; // Diameter = 2 * Radius int diameter = 2 * radius; // Square of diameter // which is the square // of the maximum length // diagonal int diameterSquare = diameter * diameter; // generate all combinations // of a and b in the range // (1, (2 * Radius - 1)) // (Both inclusive) for (int a = 1; a < 2 * radius; a++) { for (int b = 1; b < 2 * radius; b++) { // Calculate the // Diagonal length of // this rectangle int diagonalLengthSquare = (a * a + b * b); // If this rectangle's // Diagonal Length is // less than the Diameter, // it is a valid rectangle, // thus increment counter if (diagonalLengthSquare <= diameterSquare) { rectangles++; } } } return rectangles;} // Driver Codepublic static void Main (){ // Radius of the circleint radius = 2; int totalRectangles;totalRectangles = countRectangles(radius);Console.WriteLine(totalRectangles + \" rectangles can be \" + \"cut from a circle of\" + \" Radius \" + radius);}} // This code is contributed// by anuj_67.", "e": 7475, "s": 5862, "text": null }, { "code": "<?php// PHP program to find the// number of rectangles that// can be cut from a circle// of Radius R // Function to return the// total possible rectangles// that can be cut from the circlefunction countRectangles($radius){ $rectangles = 0; // Diameter = 2 * $Radius $diameter = 2 * $radius; // Square of diameter which // is the square of the // maximum length diagonal $diameterSquare = $diameter * $diameter; // generate all combinations // of a and b in the range // (1, (2 * Radius - 1))(Both inclusive) for ($a = 1; $a < 2 * $radius; $a++) { for ($b = 1; $b < 2 * $radius; $b++) { // Calculate the Diagonal // length of this rectangle $diagonalLengthSquare = ($a * $a + $b * $b); // If this rectangle's Diagonal // Length is less than the // Diameter, it is a valid // rectangle, thus increment counter if ($diagonalLengthSquare <= $diameterSquare) { $rectangles++; } } } return $rectangles;} // Driver Code // Radius of the circle$radius = 2; $totalRectangles;$totalRectangles = countRectangles($radius);echo $totalRectangles , \" rectangles can be \" , \"cut from a circle of Radius \" , $radius; // This code is contributed// by anuj_67.?>", "e": 8895, "s": 7475, "text": null }, { "code": "<script>// java script program to find the// number of rectangles that// can be cut from a circle// of Radius R // Function to return the// total possible rectangles// that can be cut from the circlefunction countRectangles(radius){ let rectangles = 0; // Diameter = 2 * $Radius let diameter = 2 * radius; // Square of diameter which // is the square of the // maximum length diagonal let diameterSquare = diameter * diameter; // generate all combinations // of a and b in the range // (1, (2 * Radius - 1))(Both inclusive) for (let a = 1;a < 2 * radius; a++) { for (let b = 1; b < 2 * radius; b++) { // Calculate the Diagonal // length of this rectangle let diagonalLengthSquare = (a * a + b * b); // If this rectangle's Diagonal // Length is less than the // Diameter, it is a valid // rectangle, thus increment counter if (diagonalLengthSquare <= diameterSquare) { rectangles++; } } } return rectangles;} // Driver Code // Radius of the circlelet radius = 2; let totalRectangles;totalRectangles = countRectangles(radius);document.write( totalRectangles + \" rectangles can be cut from a circle of Radius \" +radius); // This code is contributed by sravan kumar</script>", "e": 10327, "s": 8895, "text": null }, { "code": null, "e": 10377, "s": 10327, "text": "8 rectangles can be cut from a circle of Radius 2" }, { "code": null, "e": 10440, "s": 10379, "text": "Time Complexity: O(R2), where R is the Radius of the Circle " }, { "code": null, "e": 10445, "s": 10440, "text": "vt_m" }, { "code": null, "e": 10466, "s": 10445, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 10482, "s": 10466, "text": "sravankumar8128" }, { "code": null, "e": 10499, "s": 10482, "text": "surinderdawra388" }, { "code": null, "e": 10514, "s": 10499, "text": "sagar0719kumar" }, { "code": null, "e": 10521, "s": 10514, "text": "circle" }, { "code": null, "e": 10526, "s": 10521, "text": "math" }, { "code": null, "e": 10543, "s": 10526, "text": "square-rectangle" }, { "code": null, "e": 10552, "s": 10543, "text": "triangle" }, { "code": null, "e": 10562, "s": 10552, "text": "Geometric" }, { "code": null, "e": 10572, "s": 10562, "text": "Geometric" } ]
Sum of all substrings of a string representing a number | Set 1
08 Jul, 2022 Given an integer represented as a string, we need to get the sum of all possible substrings of this string. Examples: Input : num = “1234” Output : 1670 Sum = 1 + 2 + 3 + 4 + 12 + 23 + 34 + 123 + 234 + 1234 = 1670 Input : num = “421” Output : 491 Sum = 4 + 2 + 1 + 42 + 21 + 421 = 491 We can solve this problem by using dynamic programming. We can write a summation of all substrings on basis of the digit at which they are ending in that case, Sum of all substrings = sumofdigit[0] + sumofdigit[1] + sumofdigit[2] ... + sumofdigit[n-1] where n is length of string.Where sumofdigit[i] stores the sum of all substring ending at ith index digit, in the above example, Example : num = "1234" sumofdigit[0] = 1 = 1 sumofdigit[1] = 2 + 12 = 14 sumofdigit[2] = 3 + 23 + 123 = 149 sumofdigit[3] = 4 + 34 + 234 + 1234 = 1506 Result = 1670 Now we can get the relation between sumofdigit values and can solve the question iteratively. Each sumofdigit can be represented in terms of previous value as shown below, For above example, sumofdigit[3] = 4 + 34 + 234 + 1234 = 4 + 30 + 4 + 230 + 4 + 1230 + 4 = 4*4 + 10*(3 + 23 +123) = 4*4 + 10*(sumofdigit[2]) In general, sumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1] Using the above relation we can solve the problem in linear time. In the below code a complete array is taken to store sumofdigit, as each sumofdigit value requires just the previous value, we can solve this problem without allocating the complete array also. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to print sum of all substring of// a number represented as a string#include <bits/stdc++.h>using namespace std; // Utility method to convert character digit to// integer digitint toDigit(char ch){ return (ch - '0');} // Returns sum of all substring of numint sumOfSubstrings(string num){ int n = num.length(); // allocate memory equal to length of string int sumofdigit[n]; // initialize first value with first digit sumofdigit[0] = toDigit(num[0]); int res = sumofdigit[0]; // loop over all digits of string for (int i = 1; i < n; i++) { int numi = toDigit(num[i]); // update each sumofdigit from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value to the result res += sumofdigit[i]; } return res;} // Driver code to test above methodsint main(){ string num = "1234"; cout << sumOfSubstrings(num) << endl; return 0;} // Java program to print sum of all substring of// a number represented as a stringimport java.util.Arrays; class GFG { // Returns sum of all substring of num public static int sumOfSubstrings(String num) { int n = num.length(); // allocate memory equal to length of string int sumofdigit[] = new int[n]; // initialize first value with first digit sumofdigit[0] = num.charAt(0) - '0'; int res = sumofdigit[0]; // loop over all digits of string for (int i = 1; i < n; i++) { int numi = num.charAt(i) - '0'; // update each sumofdigit from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value to the result res += sumofdigit[i]; } return res; } // Driver code to test above methods public static void main(String[] args) { String num = "1234"; System.out.println(sumOfSubstrings(num)); }}// This code is contributed by Arnav Kr. Mandal. # Python program to print# sum of all substring of# a number represented as# a string # Returns sum of all# substring of numdef sumOfSubstrings(num): n = len(num) # allocate memory equal # to length of string sumofdigit = [] # initialize first value # with first digit sumofdigit.append(int(num[0])) res = sumofdigit[0] # loop over all # digits of string for i in range(1, n): numi = int(num[i]) # update each sumofdigit # from previous value sumofdigit.append((i + 1) * numi + 10 * sumofdigit[i - 1]) # add current value # to the result res += sumofdigit[i] return res # Driver codenum = "1234"print(sumOfSubstrings(num)) # This code is contributed# by Sanjit_Prasad // C# program to print sum of// all substring of a number// represented as a stringusing System; class GFG { // Returns sum of all // substring of num public static int sumOfSubstrings(String num) { int n = num.Length; // allocate memory equal to // length of string int[] sumofdigit = new int[n]; // initialize first value // with first digit sumofdigit[0] = num[0] - '0'; int res = sumofdigit[0]; // loop over all digits // of string for (int i = 1; i < n; i++) { int numi = num[i] - '0'; // update each sumofdigit // from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value // to the result res += sumofdigit[i]; } return res; } // Driver code public static void Main() { String num = "1234"; Console.Write(sumOfSubstrings(num)); }} // This code is contributed by Nitin Mittal. <?php// PHP program to print sum of all// substring of a number represented// as a string // Method to convert character// digit to integer digitfunction toDigit($ch){ return ($ch - '0');} // Returns sum of all// substring of numfunction sumOfSubstrings($num){ $n = strlen($num); // allocate memory equal to // length of string $sumofdigit[$n] = 0; // initialize first value // with first digit $sumofdigit[0] = toDigit($num[0]); $res = $sumofdigit[0]; // loop over all digits of string for($i = 1; $i < $n; $i++) { $numi = toDigit($num[$i]); // update each sumofdigit // from previous value $sumofdigit[$i] = ($i + 1) * $numi + 10 * $sumofdigit[$i - 1]; // add current value to the result $res += $sumofdigit[$i]; } return $res;} // Driver Code $num = "1234"; echo sumOfSubstrings($num) ; // This code is contributed by nitin mittal.?> <script> // Javascript program to print sum of // all substring of a number // represented as a string // Returns sum of all // substring of num function sumOfSubstrings(num) { let n = num.length; // allocate memory equal to // length of string let sumofdigit = new Array(n); // initialize first value // with first digit sumofdigit[0] = num[0].charCodeAt() - '0'.charCodeAt(); let res = sumofdigit[0]; // loop over all digits // of string for (let i = 1; i < n; i++) { let numi = num[i].charCodeAt() - '0'.charCodeAt(); // update each sumofdigit // from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value // to the result res += sumofdigit[i]; } return res; } let num = "1234"; document.write(sumOfSubstrings(num)); </script> 1670 Time Complexity: O(n) where n is the length of the input string. Auxiliary Space: O(n) Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space) O(1) space approach: The approach is the same as described above. What we have observed that at the current index we are dependent on the current sum + previous index sum so instead of storing in a dp array we can store it in two variables current and prev. Implementation: C++14 Java Python3 C# Javascript // C++ program to print sum of all substring of// a number represented as a string#include <bits/stdc++.h>using namespace std; // Utility method to convert character digit to// integer digitint toDigit(char ch){ return (ch - '0');} // Returns sum of all substring of numint sumOfSubstrings(string num){ int n = num.length(); // storing prev value int prev = toDigit(num[0]); int res = prev; // ans int current = 0; // substrings sum upto current index // loop over all digits of string for (int i = 1; i < n; i++) { int numi = toDigit(num[i]); // update each sumofdigit from previous value current = (i + 1) * numi + 10 * prev; // add current value to the result res += current; prev = current; // update previous } return res;} // Driver code to test above methodsint main(){ string num = "1234"; cout << sumOfSubstrings(num) << endl; return 0;} // Java program to print// sum of all subString of// a number represented as a Stringimport java.util.*;class GFG{ // Utility method to// convert character// digit to integer digitstatic int toDigit(char ch){ return (ch - '0');} // Returns sum of all subString of numstatic int sumOfSubStrings(String num){ int n = num.length(); // Storing prev value int prev = toDigit(num.charAt(0)); int res = prev; int current = 0; // SubStrings sum upto current index // loop over all digits of String for (int i = 1; i < n; i++) { int numi = toDigit(num.charAt(i)); // Update each sumofdigit // from previous value current = (i + 1) * numi + 10 * prev; // Add current value to the result res += current; // Update previous prev = current; } return res;} // Driver code to test above methodspublic static void main(String[] args){ String num = "1234"; System.out.print(sumOfSubStrings(num) + "\n");}} // This code is contributed by gauravrajput1 # Python3 program to print sum of all substring of# a number represented as a string # Returns sum of all substring of numdef sumOfSubstrings(num) : n = len(num) # storing prev value prev = int(num[0]) res = prev # ans current = 0 # substrings sum upto current index # loop over all digits of string for i in range(1, n) : numi = int(num[i]) # update each sumofdigit from previous value current = (i + 1) * numi + 10 * prev # add current value to the result res += current prev = current # update previous return res num = "1234"print(sumOfSubstrings(num)) # This code is contributed by divyeshrabadiya07 // C# program to print sum of all substring of// a number represented as a stringusing System;class GFG { // Utility method to // convert character // digit to integer digit static int toDigit(char ch) { return (ch - '0'); } // Returns sum of all subString of num static int sumOfSubStrings(string num) { int n = num.Length; // Storing prev value int prev = toDigit(num[0]); int res = prev; int current = 0; // SubStrings sum upto current index // loop over all digits of String for (int i = 1; i < n; i++) { int numi = toDigit(num[i]); // Update each sumofdigit // from previous value current = (i + 1) * numi + 10 * prev; // Add current value to the result res += current; // Update previous prev = current; } return res; } static void Main() { string num = "1234"; Console.WriteLine(sumOfSubStrings(num)); }} // This code is contributed by divyesh072019 <script> // JavaScript program to print// sum of all subString of// a number represented as a String // Utility method to// convert character// digit to integer digitfunction toDigit(ch){ return (ch - '0');} // Returns sum of all subString of numfunction sumOfSubStrings(num){ let n = num.length; // Storing prev value let prev = toDigit(num[0]); let res = prev; let current = 0; // SubStrings sum upto current index // loop over all digits of String for (let i = 1; i < n; i++) { let numi = toDigit(num[i]); // Update each sumofdigit // from previous value current = (i + 1) * numi + 10 * prev; // Add current value to the result res += current; // Update previous prev = current; } return res;} // Driver Code let num = "1234"; document.write(sumOfSubStrings(num) + "\n"); </script> 1670 Time complexity: O(n)Auxiliary Space: O(1) This article is contributed by Utkarsh Trivedi. 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. nitin mittal Sanjit_Prasad md1844 Akanksha_Rai GauravRajput1 divyesh072019 divyeshrabadiya07 mukesh07 sanjoy_62 simranarora5sos surbhikumaridav hardikkoriintern number-digits Dynamic Programming Strings Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Sieve of Eratosthenes Matrix Chain Multiplication | DP-8 Write a program to reverse an array or string Reverse a string in Java C++ Data Types Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 162, "s": 54, "text": "Given an integer represented as a string, we need to get the sum of all possible substrings of this string." }, { "code": null, "e": 174, "s": 162, "text": "Examples: " }, { "code": null, "e": 356, "s": 174, "text": "Input : num = “1234”\nOutput : 1670\nSum = 1 + 2 + 3 + 4 + 12 + 23 +\n 34 + 123 + 234 + 1234 \n = 1670\n\nInput : num = “421”\nOutput : 491\nSum = 4 + 2 + 1 + 42 + 21 + 421 = 491" }, { "code": null, "e": 738, "s": 356, "text": "We can solve this problem by using dynamic programming. We can write a summation of all substrings on basis of the digit at which they are ending in that case, Sum of all substrings = sumofdigit[0] + sumofdigit[1] + sumofdigit[2] ... + sumofdigit[n-1] where n is length of string.Where sumofdigit[i] stores the sum of all substring ending at ith index digit, in the above example, " }, { "code": null, "e": 907, "s": 738, "text": "Example : num = \"1234\"\nsumofdigit[0] = 1 = 1\nsumofdigit[1] = 2 + 12 = 14\nsumofdigit[2] = 3 + 23 + 123 = 149\nsumofdigit[3] = 4 + 34 + 234 + 1234 = 1506\nResult = 1670" }, { "code": null, "e": 1080, "s": 907, "text": "Now we can get the relation between sumofdigit values and can solve the question iteratively. Each sumofdigit can be represented in terms of previous value as shown below, " }, { "code": null, "e": 1319, "s": 1080, "text": "For above example,\nsumofdigit[3] = 4 + 34 + 234 + 1234\n = 4 + 30 + 4 + 230 + 4 + 1230 + 4\n = 4*4 + 10*(3 + 23 +123)\n = 4*4 + 10*(sumofdigit[2])\nIn general, \nsumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1]" }, { "code": null, "e": 1580, "s": 1319, "text": "Using the above relation we can solve the problem in linear time. In the below code a complete array is taken to store sumofdigit, as each sumofdigit value requires just the previous value, we can solve this problem without allocating the complete array also. " }, { "code": null, "e": 1596, "s": 1580, "text": "Implementation:" }, { "code": null, "e": 1600, "s": 1596, "text": "C++" }, { "code": null, "e": 1605, "s": 1600, "text": "Java" }, { "code": null, "e": 1613, "s": 1605, "text": "Python3" }, { "code": null, "e": 1616, "s": 1613, "text": "C#" }, { "code": null, "e": 1620, "s": 1616, "text": "PHP" }, { "code": null, "e": 1631, "s": 1620, "text": "Javascript" }, { "code": "// C++ program to print sum of all substring of// a number represented as a string#include <bits/stdc++.h>using namespace std; // Utility method to convert character digit to// integer digitint toDigit(char ch){ return (ch - '0');} // Returns sum of all substring of numint sumOfSubstrings(string num){ int n = num.length(); // allocate memory equal to length of string int sumofdigit[n]; // initialize first value with first digit sumofdigit[0] = toDigit(num[0]); int res = sumofdigit[0]; // loop over all digits of string for (int i = 1; i < n; i++) { int numi = toDigit(num[i]); // update each sumofdigit from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value to the result res += sumofdigit[i]; } return res;} // Driver code to test above methodsint main(){ string num = \"1234\"; cout << sumOfSubstrings(num) << endl; return 0;}", "e": 2589, "s": 1631, "text": null }, { "code": "// Java program to print sum of all substring of// a number represented as a stringimport java.util.Arrays; class GFG { // Returns sum of all substring of num public static int sumOfSubstrings(String num) { int n = num.length(); // allocate memory equal to length of string int sumofdigit[] = new int[n]; // initialize first value with first digit sumofdigit[0] = num.charAt(0) - '0'; int res = sumofdigit[0]; // loop over all digits of string for (int i = 1; i < n; i++) { int numi = num.charAt(i) - '0'; // update each sumofdigit from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value to the result res += sumofdigit[i]; } return res; } // Driver code to test above methods public static void main(String[] args) { String num = \"1234\"; System.out.println(sumOfSubstrings(num)); }}// This code is contributed by Arnav Kr. Mandal.", "e": 3635, "s": 2589, "text": null }, { "code": "# Python program to print# sum of all substring of# a number represented as# a string # Returns sum of all# substring of numdef sumOfSubstrings(num): n = len(num) # allocate memory equal # to length of string sumofdigit = [] # initialize first value # with first digit sumofdigit.append(int(num[0])) res = sumofdigit[0] # loop over all # digits of string for i in range(1, n): numi = int(num[i]) # update each sumofdigit # from previous value sumofdigit.append((i + 1) * numi + 10 * sumofdigit[i - 1]) # add current value # to the result res += sumofdigit[i] return res # Driver codenum = \"1234\"print(sumOfSubstrings(num)) # This code is contributed# by Sanjit_Prasad", "e": 4417, "s": 3635, "text": null }, { "code": "// C# program to print sum of// all substring of a number// represented as a stringusing System; class GFG { // Returns sum of all // substring of num public static int sumOfSubstrings(String num) { int n = num.Length; // allocate memory equal to // length of string int[] sumofdigit = new int[n]; // initialize first value // with first digit sumofdigit[0] = num[0] - '0'; int res = sumofdigit[0]; // loop over all digits // of string for (int i = 1; i < n; i++) { int numi = num[i] - '0'; // update each sumofdigit // from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value // to the result res += sumofdigit[i]; } return res; } // Driver code public static void Main() { String num = \"1234\"; Console.Write(sumOfSubstrings(num)); }} // This code is contributed by Nitin Mittal.", "e": 5457, "s": 4417, "text": null }, { "code": "<?php// PHP program to print sum of all// substring of a number represented// as a string // Method to convert character// digit to integer digitfunction toDigit($ch){ return ($ch - '0');} // Returns sum of all// substring of numfunction sumOfSubstrings($num){ $n = strlen($num); // allocate memory equal to // length of string $sumofdigit[$n] = 0; // initialize first value // with first digit $sumofdigit[0] = toDigit($num[0]); $res = $sumofdigit[0]; // loop over all digits of string for($i = 1; $i < $n; $i++) { $numi = toDigit($num[$i]); // update each sumofdigit // from previous value $sumofdigit[$i] = ($i + 1) * $numi + 10 * $sumofdigit[$i - 1]; // add current value to the result $res += $sumofdigit[$i]; } return $res;} // Driver Code $num = \"1234\"; echo sumOfSubstrings($num) ; // This code is contributed by nitin mittal.?>", "e": 6427, "s": 5457, "text": null }, { "code": "<script> // Javascript program to print sum of // all substring of a number // represented as a string // Returns sum of all // substring of num function sumOfSubstrings(num) { let n = num.length; // allocate memory equal to // length of string let sumofdigit = new Array(n); // initialize first value // with first digit sumofdigit[0] = num[0].charCodeAt() - '0'.charCodeAt(); let res = sumofdigit[0]; // loop over all digits // of string for (let i = 1; i < n; i++) { let numi = num[i].charCodeAt() - '0'.charCodeAt(); // update each sumofdigit // from previous value sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1]; // add current value // to the result res += sumofdigit[i]; } return res; } let num = \"1234\"; document.write(sumOfSubstrings(num)); </script>", "e": 7425, "s": 6427, "text": null }, { "code": null, "e": 7430, "s": 7425, "text": "1670" }, { "code": null, "e": 7519, "s": 7432, "text": "Time Complexity: O(n) where n is the length of the input string. Auxiliary Space: O(n)" }, { "code": null, "e": 7606, "s": 7519, "text": "Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)" }, { "code": null, "e": 7627, "s": 7606, "text": "O(1) space approach:" }, { "code": null, "e": 7864, "s": 7627, "text": "The approach is the same as described above. What we have observed that at the current index we are dependent on the current sum + previous index sum so instead of storing in a dp array we can store it in two variables current and prev." }, { "code": null, "e": 7880, "s": 7864, "text": "Implementation:" }, { "code": null, "e": 7886, "s": 7880, "text": "C++14" }, { "code": null, "e": 7891, "s": 7886, "text": "Java" }, { "code": null, "e": 7899, "s": 7891, "text": "Python3" }, { "code": null, "e": 7902, "s": 7899, "text": "C#" }, { "code": null, "e": 7913, "s": 7902, "text": "Javascript" }, { "code": "// C++ program to print sum of all substring of// a number represented as a string#include <bits/stdc++.h>using namespace std; // Utility method to convert character digit to// integer digitint toDigit(char ch){ return (ch - '0');} // Returns sum of all substring of numint sumOfSubstrings(string num){ int n = num.length(); // storing prev value int prev = toDigit(num[0]); int res = prev; // ans int current = 0; // substrings sum upto current index // loop over all digits of string for (int i = 1; i < n; i++) { int numi = toDigit(num[i]); // update each sumofdigit from previous value current = (i + 1) * numi + 10 * prev; // add current value to the result res += current; prev = current; // update previous } return res;} // Driver code to test above methodsint main(){ string num = \"1234\"; cout << sumOfSubstrings(num) << endl; return 0;}", "e": 8851, "s": 7913, "text": null }, { "code": "// Java program to print// sum of all subString of// a number represented as a Stringimport java.util.*;class GFG{ // Utility method to// convert character// digit to integer digitstatic int toDigit(char ch){ return (ch - '0');} // Returns sum of all subString of numstatic int sumOfSubStrings(String num){ int n = num.length(); // Storing prev value int prev = toDigit(num.charAt(0)); int res = prev; int current = 0; // SubStrings sum upto current index // loop over all digits of String for (int i = 1; i < n; i++) { int numi = toDigit(num.charAt(i)); // Update each sumofdigit // from previous value current = (i + 1) * numi + 10 * prev; // Add current value to the result res += current; // Update previous prev = current; } return res;} // Driver code to test above methodspublic static void main(String[] args){ String num = \"1234\"; System.out.print(sumOfSubStrings(num) + \"\\n\");}} // This code is contributed by gauravrajput1", "e": 9834, "s": 8851, "text": null }, { "code": "# Python3 program to print sum of all substring of# a number represented as a string # Returns sum of all substring of numdef sumOfSubstrings(num) : n = len(num) # storing prev value prev = int(num[0]) res = prev # ans current = 0 # substrings sum upto current index # loop over all digits of string for i in range(1, n) : numi = int(num[i]) # update each sumofdigit from previous value current = (i + 1) * numi + 10 * prev # add current value to the result res += current prev = current # update previous return res num = \"1234\"print(sumOfSubstrings(num)) # This code is contributed by divyeshrabadiya07", "e": 10527, "s": 9834, "text": null }, { "code": "// C# program to print sum of all substring of// a number represented as a stringusing System;class GFG { // Utility method to // convert character // digit to integer digit static int toDigit(char ch) { return (ch - '0'); } // Returns sum of all subString of num static int sumOfSubStrings(string num) { int n = num.Length; // Storing prev value int prev = toDigit(num[0]); int res = prev; int current = 0; // SubStrings sum upto current index // loop over all digits of String for (int i = 1; i < n; i++) { int numi = toDigit(num[i]); // Update each sumofdigit // from previous value current = (i + 1) * numi + 10 * prev; // Add current value to the result res += current; // Update previous prev = current; } return res; } static void Main() { string num = \"1234\"; Console.WriteLine(sumOfSubStrings(num)); }} // This code is contributed by divyesh072019", "e": 11594, "s": 10527, "text": null }, { "code": "<script> // JavaScript program to print// sum of all subString of// a number represented as a String // Utility method to// convert character// digit to integer digitfunction toDigit(ch){ return (ch - '0');} // Returns sum of all subString of numfunction sumOfSubStrings(num){ let n = num.length; // Storing prev value let prev = toDigit(num[0]); let res = prev; let current = 0; // SubStrings sum upto current index // loop over all digits of String for (let i = 1; i < n; i++) { let numi = toDigit(num[i]); // Update each sumofdigit // from previous value current = (i + 1) * numi + 10 * prev; // Add current value to the result res += current; // Update previous prev = current; } return res;} // Driver Code let num = \"1234\"; document.write(sumOfSubStrings(num) + \"\\n\"); </script>", "e": 12435, "s": 11594, "text": null }, { "code": null, "e": 12440, "s": 12435, "text": "1670" }, { "code": null, "e": 12485, "s": 12442, "text": "Time complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 12784, "s": 12485, "text": "This article is contributed by Utkarsh Trivedi. 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": 12797, "s": 12784, "text": "nitin mittal" }, { "code": null, "e": 12811, "s": 12797, "text": "Sanjit_Prasad" }, { "code": null, "e": 12818, "s": 12811, "text": "md1844" }, { "code": null, "e": 12831, "s": 12818, "text": "Akanksha_Rai" }, { "code": null, "e": 12845, "s": 12831, "text": "GauravRajput1" }, { "code": null, "e": 12859, "s": 12845, "text": "divyesh072019" }, { "code": null, "e": 12877, "s": 12859, "text": "divyeshrabadiya07" }, { "code": null, "e": 12886, "s": 12877, "text": "mukesh07" }, { "code": null, "e": 12896, "s": 12886, "text": "sanjoy_62" }, { "code": null, "e": 12912, "s": 12896, "text": "simranarora5sos" }, { "code": null, "e": 12928, "s": 12912, "text": "surbhikumaridav" }, { "code": null, "e": 12945, "s": 12928, "text": "hardikkoriintern" }, { "code": null, "e": 12959, "s": 12945, "text": "number-digits" }, { "code": null, "e": 12979, "s": 12959, "text": "Dynamic Programming" }, { "code": null, "e": 12987, "s": 12979, "text": "Strings" }, { "code": null, "e": 12995, "s": 12987, "text": "Strings" }, { "code": null, "e": 13015, "s": 12995, "text": "Dynamic Programming" }, { "code": null, "e": 13113, "s": 13015, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13140, "s": 13113, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 13178, "s": 13140, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 13211, "s": 13178, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 13233, "s": 13211, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 13268, "s": 13233, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 13314, "s": 13268, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 13339, "s": 13314, "text": "Reverse a string in Java" }, { "code": null, "e": 13354, "s": 13339, "text": "C++ Data Types" }, { "code": null, "e": 13414, "s": 13354, "text": "Write a program to print all permutations of a given string" } ]
Keras - Permute Layers
Permute is also used to change the shape of the input using pattern. For example, if Permute with argument (2, 1) is applied to layer having input shape as (batch_size, 3, 2), then the output shape of the layer will be (batch_size, 2, 3) Permute has one argument as follows − keras.layers.Permute(dims) A simple example to use Permute layers is as follows − >>> from keras.models import Sequential >>> from keras.layers import Activation, Dense, Permute >>> >>> >>> model = Sequential() >>> layer_1 = Dense(16, input_shape = (8, 8)) >>> model.add(layer_1) >>> layer_2 = Permute((2, 1)) >>> model.add(layer_2) >>> layer_2.input_shape (None, 8, 16) >>> layer_2.output_shape (None, 16, 8) >>> where, (2, 1) is set as pattern. 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2289, "s": 2051, "text": "Permute is also used to change the shape of the input using pattern. For example, if Permute with argument (2, 1) is applied to layer having input shape as (batch_size, 3, 2), then the output shape of the layer will be (batch_size, 2, 3)" }, { "code": null, "e": 2327, "s": 2289, "text": "Permute has one argument as follows −" }, { "code": null, "e": 2355, "s": 2327, "text": "keras.layers.Permute(dims)\n" }, { "code": null, "e": 2410, "s": 2355, "text": "A simple example to use Permute layers is as follows −" }, { "code": null, "e": 2752, "s": 2410, "text": ">>> from keras.models import Sequential \n>>> from keras.layers import Activation, Dense, Permute \n>>> \n>>> \n>>> model = Sequential() \n>>> layer_1 = Dense(16, input_shape = (8, 8)) \n>>> model.add(layer_1) \n>>> layer_2 = Permute((2, 1)) \n>>> model.add(layer_2) \n>>> layer_2.input_shape (None, 8, 16) \n>>> layer_2.output_shape (None, 16, 8)\n>>>" }, { "code": null, "e": 2785, "s": 2752, "text": "where, (2, 1) is set as pattern." }, { "code": null, "e": 2819, "s": 2785, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 2836, "s": 2819, "text": " Abhilash Nelson" }, { "code": null, "e": 2869, "s": 2836, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 2891, "s": 2869, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 2924, "s": 2891, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 2946, "s": 2924, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 2979, "s": 2946, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 3001, "s": 2979, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3034, "s": 3001, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 3056, "s": 3034, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3089, "s": 3056, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 3100, "s": 3089, "text": " Mike West" }, { "code": null, "e": 3107, "s": 3100, "text": " Print" }, { "code": null, "e": 3118, "s": 3107, "text": " Add Notes" } ]
Understanding the Structure of Matplotlib | by Soner Yıldırım | Towards Data Science
Matplotlib is a widely used python data visualization library. It provides many different kinds of 2D and 3D plots that are very useful for data analysis and machine learning tasks. Matplotlib offers flexibility. There are multiple ways to create plots. In order to master matplotlib, it is necessary to have a thorough understanding of its structure. Matplotlib consists of three main layers. If you’re not a develepor, you’re not likely to use or deal with the backend layer. It has three abstract classes: FigureCanvas: Defines the area on which the figure is drawn. Renderer: It is the tool to draw on FigureCanvas. Event: Handles user inputs such as keybord strokes and mouse clicks. It is similar to how we do drawing on paper. Consider you want to draw a painting. You get a blank paper (FigureCanvas) and a brush (Renderer). You ask your friend what to draw (Event). Artist layer is composed of one object which is Artist. Everything that we see on a plot produced by matplotlib is an Artist instance. Titles, lines, texts, axis labels are all instances of Artist. Figure is the main Artist object that holds everything together. Let’s create a Figure: #importing matplotlibimport matplotlib.pyplot as plt%matplotlib inline#creating a figure artistfig = plt.figure(figsize=(10,6))<Figure size 720x432 with 0 Axes> We have created a figure but it does not have anything to show. Think of it as a container that hold the components of a plot together. There are two types of artist objects: Composite: Figure, Axes Primitive: Line, Circle, Text We need to add one or more Axes to Figure to be able to create an actual plot. Let’s see it on the action. fig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111) We have added an Axes to the Figure we created earlier. We now have kind of an empty plot: Please note that we have used the scripting layer to produce these plots. I just wanted to show the idea of Artist objects. Note: We have used object-oriented style where we explicitly define instances of Artist objects. The other option is called pyplot style where we let pyplot to create figure and axes objects. We will stick to the object-oriented style throughout this post. This is the layer where we are most likely to deal with. Scripting layer is the matplotlib.pyplot interface. Thus, when we create plots using “plt” after the following command, scripting layer is what we play with. import matplotlib.pyplot as plt Scripting layer automates the process of putting everthing together. Thus, it is easier to use than the Artist layer. Let’s create some plots that actually look like a plot. #create array to be plottedimport numpy as npser = np.random.randn(50)#create the plotfig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111)ax.plot(ser) We have created a Figure and Axes. Then called plot function on the Axes object and pass the array to be plotted. The rendered plot is: This figure has 1 Axes but a figure can contain multiple Axes. Let’s create one with multiple Axes: #arrays to be plottedser1 = np.random.randn(50)ser2 = ser1**2#create figure and axesfig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharey=True,figsize=(10,6))#plot the arrays on axesax1.plot(ser1)ax2.plot(ser2) We created the figure and axes (ax1 and ax2) with one line of code using subplots function. Matplotlib offers a highly flexible working environment. We have full control over the plots we created. Recall that everything we see on a matplotlib figure is an instance of Artist. Let’s add different types of Artists to the plot above. ser1 = np.random.randn(50)ser2 = ser1**2fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(12,6))ax1.plot(ser1)ax1.grid()ax1.set_title('First Series', fontsize=15)ax1.set_ylabel('Values', fontsize=12)ax1.set_xlabel('Timesteps', fontsize=12)ax2.plot(ser2)ax2.set_title('Second Series', fontsize=15)ax2.text(25,-1, 'First Series Squared', fontsize=12)ax2.set_xlabel('Timesteps', fontsize=12) In addition to the titles and axis labels, we have added grid lines to the first axes and a text artist to the second axes. The plot we have produced: There is so much more we can do with matplotlib. As with any other tool, it requires lots of practice to master. However, a concrete and fundamental first step is to learn the basics and the structure. After that, we can create more advanced plots by practicing. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 354, "s": 172, "text": "Matplotlib is a widely used python data visualization library. It provides many different kinds of 2D and 3D plots that are very useful for data analysis and machine learning tasks." }, { "code": null, "e": 524, "s": 354, "text": "Matplotlib offers flexibility. There are multiple ways to create plots. In order to master matplotlib, it is necessary to have a thorough understanding of its structure." }, { "code": null, "e": 566, "s": 524, "text": "Matplotlib consists of three main layers." }, { "code": null, "e": 681, "s": 566, "text": "If you’re not a develepor, you’re not likely to use or deal with the backend layer. It has three abstract classes:" }, { "code": null, "e": 742, "s": 681, "text": "FigureCanvas: Defines the area on which the figure is drawn." }, { "code": null, "e": 792, "s": 742, "text": "Renderer: It is the tool to draw on FigureCanvas." }, { "code": null, "e": 861, "s": 792, "text": "Event: Handles user inputs such as keybord strokes and mouse clicks." }, { "code": null, "e": 1047, "s": 861, "text": "It is similar to how we do drawing on paper. Consider you want to draw a painting. You get a blank paper (FigureCanvas) and a brush (Renderer). You ask your friend what to draw (Event)." }, { "code": null, "e": 1103, "s": 1047, "text": "Artist layer is composed of one object which is Artist." }, { "code": null, "e": 1182, "s": 1103, "text": "Everything that we see on a plot produced by matplotlib is an Artist instance." }, { "code": null, "e": 1333, "s": 1182, "text": "Titles, lines, texts, axis labels are all instances of Artist. Figure is the main Artist object that holds everything together. Let’s create a Figure:" }, { "code": null, "e": 1494, "s": 1333, "text": "#importing matplotlibimport matplotlib.pyplot as plt%matplotlib inline#creating a figure artistfig = plt.figure(figsize=(10,6))<Figure size 720x432 with 0 Axes>" }, { "code": null, "e": 1630, "s": 1494, "text": "We have created a figure but it does not have anything to show. Think of it as a container that hold the components of a plot together." }, { "code": null, "e": 1669, "s": 1630, "text": "There are two types of artist objects:" }, { "code": null, "e": 1693, "s": 1669, "text": "Composite: Figure, Axes" }, { "code": null, "e": 1723, "s": 1693, "text": "Primitive: Line, Circle, Text" }, { "code": null, "e": 1830, "s": 1723, "text": "We need to add one or more Axes to Figure to be able to create an actual plot. Let’s see it on the action." }, { "code": null, "e": 1888, "s": 1830, "text": "fig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111)" }, { "code": null, "e": 1979, "s": 1888, "text": "We have added an Axes to the Figure we created earlier. We now have kind of an empty plot:" }, { "code": null, "e": 2103, "s": 1979, "text": "Please note that we have used the scripting layer to produce these plots. I just wanted to show the idea of Artist objects." }, { "code": null, "e": 2295, "s": 2103, "text": "Note: We have used object-oriented style where we explicitly define instances of Artist objects. The other option is called pyplot style where we let pyplot to create figure and axes objects." }, { "code": null, "e": 2360, "s": 2295, "text": "We will stick to the object-oriented style throughout this post." }, { "code": null, "e": 2575, "s": 2360, "text": "This is the layer where we are most likely to deal with. Scripting layer is the matplotlib.pyplot interface. Thus, when we create plots using “plt” after the following command, scripting layer is what we play with." }, { "code": null, "e": 2607, "s": 2575, "text": "import matplotlib.pyplot as plt" }, { "code": null, "e": 2725, "s": 2607, "text": "Scripting layer automates the process of putting everthing together. Thus, it is easier to use than the Artist layer." }, { "code": null, "e": 2781, "s": 2725, "text": "Let’s create some plots that actually look like a plot." }, { "code": null, "e": 2937, "s": 2781, "text": "#create array to be plottedimport numpy as npser = np.random.randn(50)#create the plotfig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111)ax.plot(ser)" }, { "code": null, "e": 3073, "s": 2937, "text": "We have created a Figure and Axes. Then called plot function on the Axes object and pass the array to be plotted. The rendered plot is:" }, { "code": null, "e": 3173, "s": 3073, "text": "This figure has 1 Axes but a figure can contain multiple Axes. Let’s create one with multiple Axes:" }, { "code": null, "e": 3403, "s": 3173, "text": "#arrays to be plottedser1 = np.random.randn(50)ser2 = ser1**2#create figure and axesfig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharey=True,figsize=(10,6))#plot the arrays on axesax1.plot(ser1)ax2.plot(ser2)" }, { "code": null, "e": 3495, "s": 3403, "text": "We created the figure and axes (ax1 and ax2) with one line of code using subplots function." }, { "code": null, "e": 3735, "s": 3495, "text": "Matplotlib offers a highly flexible working environment. We have full control over the plots we created. Recall that everything we see on a matplotlib figure is an instance of Artist. Let’s add different types of Artists to the plot above." }, { "code": null, "e": 4162, "s": 3735, "text": "ser1 = np.random.randn(50)ser2 = ser1**2fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(12,6))ax1.plot(ser1)ax1.grid()ax1.set_title('First Series', fontsize=15)ax1.set_ylabel('Values', fontsize=12)ax1.set_xlabel('Timesteps', fontsize=12)ax2.plot(ser2)ax2.set_title('Second Series', fontsize=15)ax2.text(25,-1, 'First Series Squared', fontsize=12)ax2.set_xlabel('Timesteps', fontsize=12)" }, { "code": null, "e": 4313, "s": 4162, "text": "In addition to the titles and axis labels, we have added grid lines to the first axes and a text artist to the second axes. The plot we have produced:" }, { "code": null, "e": 4576, "s": 4313, "text": "There is so much more we can do with matplotlib. As with any other tool, it requires lots of practice to master. However, a concrete and fundamental first step is to learn the basics and the structure. After that, we can create more advanced plots by practicing." } ]
Matplotlib Tutorial - GeeksforGeeks
07 Jul, 2021 Matplotlib is easy to use and an amazing visualizing library in Python. It is built on NumPy arrays and designed to work with the broader SciPy stack and consists of several plots like line, bar, scatter, histogram, etc. In this article, we will learn about Python plotting with Matplotlib from basics to advance with the help of a huge dataset containing information about different types of plots and their customizations. Table Of Content Getting Started Pyplot Figure class Axes Class Setting Limits and Tick labels Multiple Plots What is a Legend? Creating Different Types of Plots Line GraphBar chartHistogramsScatter PlotPie Chart3D Plots Line Graph Bar chart Histograms Scatter Plot Pie Chart 3D Plots Working with Images Customizing Plots in Matplotlib More articles on Matplotlib Exercises, Applications, and Projects Recent Articles on Matplotlib !!! Before we start learning about Matplotlib we first have to set up the environment and will also see how to use Matplotlib with Jupyter Notebook: Environment Setup for Matplotlib Using Matplotlib with Jupyter Notebook After learning about the environment setup and how to use Matplotlib with Jupyter let’s create a simple plot. We will be plotting two lists containing the X, Y coordinates for the plot. Example: Python3 import matplotlib.pyplot as plt # initializing the data x = [10, 20, 30, 40] y = [20, 30, 40, 50] # plotting the data plt.plot(x, y) # Adding the title plt.title("Simple Plot") # Adding the labels plt.ylabel("y-axis") plt.xlabel("x-axis") plt.show() Output: In the above example, the elements of X and Y provides the coordinates for the x axis and y axis and a straight line is plotted against those coordinates. For a detailed introduction to Matplotlib and to see how basic charts are plotted refer to the below article. Introduction to Matplotlib Simple Plot in Python using Matplotlib In the above article, you might have seen Pyplot was imported in code and must have wondered what is Pyplot. Don’t worry we will discuss the Pyplot in the next section. Pyplot is a Matplotlib module that provides a MATLAB like interface. Pyplot provides functions that interact with the figure i.e. creates a figure, decorates the plot with labels, creates plotting area in a figure. Syntax: matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs) Example: Python3 # Python program to show pyplot module import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.axis([0, 6, 0, 20]) plt.show() Output: Refer to the below articles to get detailed information about Pyplot and functions associated with this class. Pyplot in Matplotlib Matplotlib.pyplot.plot() function in Python Matplotlib.pyplot.title() in Python matplotlib.pyplot.imshow() in Python Matplotlib.pyplot.legend() in Python Matplotlib.pyplot.subplots() in Python Matplotlib.pyplot.colors() in Python Matplotlib.pyplot.grid() in Python >>> More Functions on Pyplot class Matplotlib take care of the creation of inbuilt defaults like Figure and Axes. Don’t worry about these terms we will study about them in detail in the below section but let’s take a brief about these terms. Figure: This class is the top-level container for all the plots means it is the overall window or page on which everything is drawn. A figure object can be considered as a box-like container that can hold one or more axes. Axes: This class is the most basic and flexible component for creating sub-plots. You might confuse axes as the plural of axis but it is an individual plot or graph. A given figure may contain many axes but a given axes can only be in one figure. Figure class is the top-level container that contains one or more axes. It is the overall window or page on which everything is drawn. Syntax: class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None) Example 1: Python3 # Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure # Creating a new figure with width = 5 inches # and height = 4 inches fig = plt.figure(figsize =(5, 4)) # Creating a new axes for the figure ax = fig.add_axes([1, 1, 1, 1]) # Adding the data to be plotted ax.plot([2, 3, 4, 5, 5, 6, 6], [5, 7, 1, 3, 4, 6 ,8]) plt.show() Output: Example 2: Creating multiple plots Python3 # Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure # Creating a new figure with width = 5 inches # and height = 4 inches fig = plt.figure(figsize =(5, 4)) # Creating first axes for the figure ax1 = fig.add_axes([1, 1, 1, 1]) # Creating second axes for the figure ax2 = fig.add_axes([1, 0.5, 0.5, 0.5]) # Adding the data to be plotted ax1.plot([2, 3, 4, 5, 5, 6, 6], [5, 7, 1, 3, 4, 6 ,8]) ax2.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6]) plt.show() Output: Refer to the below articles to get detailed information about the Figure class and functions associated with it. Matplotlib.figure.Figure() in Python Matplotlib.figure.Figure.add_axes() in Python Matplotlib.figure.Figure.clear() in Python Matplotlib.figure.Figure.colorbar() in Python Matplotlib.figure.Figure.get_figwidth() in Python Matplotlib.figure.Figure.get_figheight() in Python Matplotlib.figure.Figure.subplots() in Python >>> More Functions in Figure Class Axes class is the most basic and flexible unit for creating sub-plots. A given figure may contain many axes, but a given axes can only be present in one figure. The axes() function creates the axes object. Let’s see the below example. Syntax: matplotlib.pyplot.axis(*args, emit=True, **kwargs) Example 1: Python3 # Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure # Creating the axes object with argument as # [left, bottom, width, height] ax = plt.axes([1, 1, 1, 1]) Output: Example 2: Python3 # Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure fig = plt.figure(figsize = (5, 4)) # Adding the axes to the figure ax = fig.add_axes([1, 1, 1, 1]) # plotting 1st dataset to the figure ax1 = ax.plot([1, 2, 3, 4], [1, 2, 3, 4]) # plotting 2nd dataset to the figure ax2 = ax.plot([1, 2, 3, 4], [2, 3, 4, 5]) plt.show() Output: Refer to the below articles to get detailed information about the axes class and functions associated with it. Matplotlib – Axes Class Matplotlib.axes.Axes.update() in Python Matplotlib.axes.Axes.draw() in Python Matplotlib.axes.Axes.get_figure() in Python Matplotlib.axes.Axes.set_figure() in Python Matplotlib.axes.Axes.properties() in Python >>> More Functions on Axes Class You might have seen that Matplotlib automatically sets the values and the markers(points) of the x and y axis, however, it is possible to set the limit and markers manually. set_xlim() and set_ylim() functions are used to set the limits of the x-axis and y-axis respectively. Similarly, set_xticklabels() and set_yticklabels() functions are used to set tick labels. Example: Python3 # Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure x = [3, 1, 3] y = [3, 2, 1] # Creating a new figure with width = 5 inches # and height = 4 inches fig = plt.figure(figsize =(5, 4)) # Creating first axes for the figure ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Adding the data to be plotted ax.plot(x, y) ax.set_xlim(1, 2) ax.set_xticklabels(( "one", "two", "three", "four", "five", "six")) plt.show() Output: Till now you must have got a basic idea about Matplotlib and plotting some simple plots, now what if you want to plot multiple plots in the same figure. This can be done using multiple ways. One way was discussed above using the add_axes() method of the figure class. Let’s see various ways multiple plots can be added with the help of examples. Method 1: Using the add_axes() method The add_axes() method figure module of matplotlib library is used to add an axes to the figure. Syntax: add_axes(self, *args, **kwargs) Example: Python3 # Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure # Creating a new figure with width = 5 inches # and height = 4 inches fig = plt.figure(figsize =(5, 4)) # Creating first axes for the figure ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Creating second axes for the figure ax2 = fig.add_axes([0.5, 0.5, 0.3, 0.3]) # Adding the data to be plotted ax1.plot([5, 4, 3, 2, 1], [2, 3, 4, 5, 6]) ax2.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6]) plt.show() Output: The add_axes() method adds the plot in the same figure by creating another axes object. Method 2: Using subplot() method. This method adds another plot to the current figure at the specified grid position. Syntax: subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(ax) Example: Python3 import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3] y = [3, 2, 1] z = [1, 3, 1] # Creating figure object plt.figure() # addind first subplot plt.subplot(121) plt.plot(x, y) # addding second subplot plt.subplot(122) plt.plot(z, y) Output: Note: Subplot() function have the following disadvantages – It does not allow adding multiple subplots at the same time. It deletes the preexisting plot of the figure. Method 3: Using subplots() method This function is used to create figure and multiple subplots at the same time. Syntax: matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw) Example: Python3 import matplotlib.pyplot as plt # Creating the figure and subplots # according the argument passed fig, axes = plt.subplots(1, 2) # plotting the data in the 1st subplot axes[0].plot([1, 2, 3, 4], [1, 2, 3, 4]) # plotting the data in the 1st subplot only axes[0].plot([1, 2, 3, 4], [4, 3, 2, 1]) # plotting the data in the 2nd subplot only axes[1].plot([1, 2, 3, 4], [1, 1, 1, 1]) Output: Method 4: Using subplot2grid() method This function give additional flexibility in creating axes object at a specified location inside a grid. It also helps in spanning the axes object across multiple rows or columns. In simpler words, this function is used to create multiple charts within the same figure. Syntax: Plt.subplot2grid(shape, location, rowspan, colspan) Example: Python3 import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3] y = [3, 2, 1] z = [1, 3, 1] # adding the subplots axes1 = plt.subplot2grid ( (7, 1), (0, 0), rowspan = 2, colspan = 1) axes2 = plt.subplot2grid ( (7, 1), (2, 0), rowspan = 2, colspan = 1) axes3 = plt.subplot2grid ( (7, 1), (4, 0), rowspan = 2, colspan = 1) # plotting the data axes1.plot(x, y) axes2.plot(x, z) axes3.plot(z, y) Output: Refer to the below articles to get detailed information about subplots How to create multiple subplots in Matplotlib in Python? How to Add Title to Subplots in Matplotlib? How to Set a Single Main Title for All the Subplots in Matplotlib? How to Turn Off the Axes for Subplots in Matplotlib? How to Create Different Subplot Sizes in Matplotlib? How to set the spacing between subplots in Matplotlib in Python? Matplotlib Sub plotting using object oriented API Make subplots span multiple grid rows and columns in Matplotlib A legend is an area describing the elements of the graph. In simple terms, it reflects the data displayed in the graph’s Y-axis. It generally appears as the box containing a small sample of each color on the graph and a small description of what this data means. A Legend can be created using the legend() method. The attribute Loc in the legend() is used to specify the location of the legend. The default value of loc is loc=”best” (upper left). The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure. The attribute bbox_to_anchor=(x, y) of legend() function is used to specify the coordinates of the legend, and the attribute ncol represents the number of columns that the legend has. Its default value is 1. Syntax: matplotlib.pyplot.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2) Example: Python3 import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3] y = [3, 2, 1] plt.plot(x, y) plt.plot(y, x) # Adding the legends plt.legend(["blue", "orange"]) plt.show() Output: Refer to the below articles to get detailed information about the legend – Matplotlib.pyplot.legend() in Python Matplotlib.axes.Axes.legend() in Python Change the legend position in Matplotlib How to Change Legend Font Size in Matplotlib? How Change the vertical spacing between legend entries in Matplotlib? Use multiple columns in a Matplotlib legend How to Create a Single Legend for All Subplots in Matplotlib? How to manually add a legend with a color box on a Matplotlib figure ? How to Place Legend Outside of the Plot in Matplotlib? How to Remove the Legend in Matplotlib? Remove the legend border in Matplotlib Till now you all must have seen that we are working with only the line charts as they are easy to plot and understand. Line Chart is used to represent a relationship between two data X and Y on a different axis. It is plotted using the pot() function. Let’s see the below example Example: Python3 import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3] y = [3, 2, 1] # This will plot a simple line chart # with elements of x as x axis and y # as y axis plt.plot(x, y) plt.title("Line Chart") # Adding the legends plt.legend(["Line"]) plt.show() Output: Refer to the below article to get detailed information about line chart. Line chart in Matplotlib Line plot styles in Matplotlib Plot a Horizontal line in Matplotlib Plot a Vertical line in Matplotlib Plot Multiple lines in Matplotlib Change the line opacity in Matplotlib Increase the thickness of a line with Matplotlib Plot line graph from NumPy array How to Fill Between Multiple Lines in Matplotlib? A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. It can be created using the bar() method. Syntax: plt.bar(x, height, width, bottom, align) Example: Python3 import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3, 12, 2, 4, 4] y = [3, 2, 1, 4, 5, 6, 7] # This will plot a simple bar chart plt.bar(x, y) # Title to the plot plt.title("Bar Chart") # Adding the legends plt.legend(["bar"]) plt.show() Output: Refer to the below articles to get detailed information about Bar charts – Bar Plot in Matplotlib Draw a horizontal bar chart with Matplotlib Create a stacked bar plot in Matplotlib Stacked Percentage Bar Plot In MatPlotLib Plotting back-to-back bar charts Matplotlib How to display the value of each bar in a bar chart using Matplotlib? How To Annotate Bars in Barplot with Matplotlib in Python? How to Annotate Bars in Grouped Barplot in Python? A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. To create a histogram the first step is to create a bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals. Bins are clearly identified as consecutive, non-overlapping intervals of variables. The hist() function is used to compute and create histogram of x. Syntax: matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, \*, data=None, \*\*kwargs) Example: Python3 import matplotlib.pyplot as plt # data to display on plots x = [1, 2, 3, 4, 5, 6, 7, 4] # This will plot a simple histogram plt.hist(x, bins = [1, 2, 3, 4, 5, 6, 7]) # Title to the plot plt.title("Histogram") # Adding the legends plt.legend(["bar"]) plt.show() Output: Refer to the below articles to get detailed information about histograms. Plotting Histogram in Python using Matplotlib Create a cumulative histogram in Matplotlib How to plot two histograms together in Matplotlib? Overlapping Histograms with Matplotlib in Python Bin Size in Matplotlib Histogram Compute the histogram of a set of data using NumPy in Python Plot 2-D Histogram in Python using Matplotlib Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot. Syntax: matplotlib.pyplot.scatter(x_axis_data, y_axis_data, s=None, c=None, marker=None, cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None) Example: Python3 import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3, 12, 2, 4, 4] y = [3, 2, 1, 4, 5, 6, 7] # This will plot a simple scatter chart plt.scatter(x, y) # Adding legend to the plot plt.legend("A") # Title to the plot plt.title("Scatter chart") plt.show() Output: Refer to the below articles to get detailed information about the scatter plot. matplotlib.pyplot.scatter() in Python How to add a legend to a scatter plot in Matplotlib ? How to Connect Scatterplot Points With Line in Matplotlib? How to create a Scatter Plot with several colors in Matplotlib? How to increase the size of scatter points in Matplotlib ? A Pie Chart is a circular statistical plot that can display only one series of data. The area of the chart is the total percentage of the given data. The area of slices of the pie represents the percentage of the parts of the data. The slices of pie are called wedges. The area of the wedge is determined by the length of the arc of the wedge. It can be created using the pie() method. Syntax: matplotlib.pyplot.pie(data, explode=None, labels=None, colors=None, autopct=None, shadow=False) Example: Python3 import matplotlib.pyplot as plt # data to display on plots x = [1, 2, 3, 4] # this will explode the 1st wedge # i.e. will separate the 1st wedge # from the chart e =(0.1, 0, 0, 0) # This will plot a simple pie chart plt.pie(x, explode = e) # Title to the plot plt.title("Pie chart") plt.show() Output: Refer to the below articles to get detailed information about pie charts. matplotlib.axes.Axes.pie() in Python Plot a pie chart in Python using Matplotlib How to set border for wedges in Matplotlib pie chart? Radially displace pie chart wedge in Matplotlib Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3D utilities were developed upon the 2D and thus, we have a 3D implementation of data available today. Example: Python3 import matplotlib.pyplot as plt # Creating the figure object fig = plt.figure() # keeping the projection = 3d # ctreates the 3d plot ax = plt.axes(projection = '3d') Output: The above code lets the creation of a 3D plot in Matplotlib. We can create different types of 3D plots like scatter plots, contour plots, surface plots, etc. Let’s create a simple 3D line plot. Example: Python3 import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] z = [1, 8, 27, 64, 125] # Creating the figure object fig = plt.figure() # keeping the projection = 3d # ctreates the 3d plot ax = plt.axes(projection = '3d') ax.plot3D(z, y, x) Output: Refer to the below articles to get detailed information about 3D plots. Three-dimensional Plotting in Python using Matplotlib 3D Scatter Plotting in Python using Matplotlib 3D Surface plotting in Python using Matplotlib 3D Wireframe plotting in Python using Matplotlib 3D Contour Plotting in Python using Matplotlib Tri-Surface Plot in Python using Matplotlib Surface plots and Contour plots in Python How to change angle of 3D plot in Python? How to animate 3D Graph using Matplotlib? Draw contours on an unstructured triangular grid in Python using Matplotlib The image module in matplotlib library is used for working with images in Python. The image module also includes two useful methods which are imread which is used to read images and imshow which is used to display the image. Example: Python3 # importing required libraries import matplotlib.pyplot as plt import matplotlib.image as img # reading the image testImage = img.imread('g4g.png') # displaying the image plt.imshow(testImage) Output: Refer to the below articles to get detailed information about working with images using Matplotlib. Working with Images in Python using Matplotlib Working with PNG Images using Matplotlib How to Display an Image in Grayscale in Matplotlib? Plot a Point or a Line on an Image with Matplotlib How to Draw Rectangle on Image in Matplotlib? How to Display an OpenCV image in Python with Matplotlib? Calculate the area of an image using Matplotlib Style Plots using Matplotlib Change plot size in Matplotlib – Python How to Change the Transparency of a Graph Plot in Matplotlib with Python? How to Change the Color of a Graph Plot in Matplotlib with Python? How to Change Fonts in matplotlib? How to change the font size of the Title in a Matplotlib figure ? How to Set Tick Labels Font Size in Matplotlib? How to Set Plot Background Color in Matplotlib? How to generate a random color for a Matplotlib plot in Python? Add Text Inside the Plot in Matplotlib How to add text to Matplotlib? How to change Matplotlib color bar size in Python? How to manually add a legend with a color box on a Matplotlib figure ? How to change the size of axis labels in Matplotlib? How to Hide Axis Text Ticks or Tick Labels in Matplotlib? How To Adjust Position of Axis Labels in Matplotlib? Hide Axis, Borders and White Spaces in Matplotlib How to Create an Empty Figure with Matplotlib in Python? Change the x or y interval of a Matplotlib figure How to add a grid on a figure in Matplotlib? How to change the size of figures drawn with matplotlib? Place plots side by side in Matplotlib How to Reverse Axes in Matplotlib? How to remove the frame from a Matplotlib figure in Python? Use different y-axes on the left and right of a Matplotlib plot How to Add a Y-Axis Label to the Secondary Y-Axis in Matplotlib? How to plot a simple vector field in Matplotlib ? Difference Between cla(), clf() and close() Methods in Matplotlib Make filled polygons between two horizontal curves in Python using Matplotlib How to Save a Plot to a File Using Matplotlib? How to Plot Logarithmic Axes in Matplotlib? How to put the y-axis in logarithmic scale with Matplotlib ? How to draw 2D Heatmap using Matplotlib in python? Plotting Correlation Matrix using Python Plot Candlestick Chart using mplfinance module in Python Autocorrelation plot using Matplotlib Stem and Leaf Plots in Python Python | Basic Gantt chart using Matplotlib How to Plot List of X, Y Coordinates in Matplotlib? How to put the origin in the center of the figure with Matplotlib ? How to Draw a Circle Using Matplotlib in Python? How to Plot Mean and Standard Deviation in Pandas? How to plot a complex number in Python using Matplotlib ? 3D Sine Wave Using Matplotlib – Python Plotting A Square Wave Using Matplotlib, Numpy And Scipy How to Make a Square Plot With Equal Axes in Matplotlib? Plotting a Sawtooth Wave using Matplotlib Visualizing Bubble sort using Python Visualization of Merge sort using Matplotlib Visualization of Quick sort using Matplotlib Insertion Sort Visualization using Matplotlib in Python 3D Visualisation of Quick Sort using Matplotlib in Python 3D Visualisation of Merge Sort using Matplotlib 3D Visualisation of Insertion Sort using Matplotlib in Python How to plot a normal distribution with Matplotlib in Python ? Normal Distribution Plot using Numpy and Matplotlib How to Create a Poisson Probability Mass Function Plot in Python? Find all peaks amplitude lies above 0 Using Scipy How to plot ricker curve using SciPy – Python? How to Plot a Confidence Interval in Python? How To Highlight a Time Range in Time Series Plot in Python with Matplotlib? How to Make a Time Series Plot with Rolling Average in Python? Digital Band Pass Butterworth Filter in Python Digital Band Reject Butterworth Filter in Python Digital High Pass Butterworth Filter in Python Digital Low Pass Butterworth Filter in Python Design an IIR Notch Filter to Denoise Signal using Python Design an IIR Bandpass Chebyshev Type-2 Filter using Scipy – Python Visualizing Tiff File Using Matplotlib and GDAL using Python Plotting Various Sounds on Graphs using Python and Matplotlib COVID-19 Data Visualization using matplotlib in Python Analyzing selling price of used cars using Python clintra Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Read JSON file using Python Taking input in Python Enumerate() in Python Read a file line by line in Python Different ways to create Pandas Dataframe Iterate over a list in Python
[ { "code": null, "e": 29935, "s": 29907, "text": "\n07 Jul, 2021" }, { "code": null, "e": 30157, "s": 29935, "text": "Matplotlib is easy to use and an amazing visualizing library in Python. It is built on NumPy arrays and designed to work with the broader SciPy stack and consists of several plots like line, bar, scatter, histogram, etc. " }, { "code": null, "e": 30361, "s": 30157, "text": "In this article, we will learn about Python plotting with Matplotlib from basics to advance with the help of a huge dataset containing information about different types of plots and their customizations." }, { "code": null, "e": 30379, "s": 30361, "text": "Table Of Content " }, { "code": null, "e": 30395, "s": 30379, "text": "Getting Started" }, { "code": null, "e": 30402, "s": 30395, "text": "Pyplot" }, { "code": null, "e": 30415, "s": 30402, "text": "Figure class" }, { "code": null, "e": 30426, "s": 30415, "text": "Axes Class" }, { "code": null, "e": 30457, "s": 30426, "text": "Setting Limits and Tick labels" }, { "code": null, "e": 30472, "s": 30457, "text": "Multiple Plots" }, { "code": null, "e": 30490, "s": 30472, "text": "What is a Legend?" }, { "code": null, "e": 30583, "s": 30490, "text": "Creating Different Types of Plots Line GraphBar chartHistogramsScatter PlotPie Chart3D Plots" }, { "code": null, "e": 30594, "s": 30583, "text": "Line Graph" }, { "code": null, "e": 30604, "s": 30594, "text": "Bar chart" }, { "code": null, "e": 30615, "s": 30604, "text": "Histograms" }, { "code": null, "e": 30628, "s": 30615, "text": "Scatter Plot" }, { "code": null, "e": 30638, "s": 30628, "text": "Pie Chart" }, { "code": null, "e": 30647, "s": 30638, "text": "3D Plots" }, { "code": null, "e": 30667, "s": 30647, "text": "Working with Images" }, { "code": null, "e": 30699, "s": 30667, "text": "Customizing Plots in Matplotlib" }, { "code": null, "e": 30727, "s": 30699, "text": "More articles on Matplotlib" }, { "code": null, "e": 30765, "s": 30727, "text": "Exercises, Applications, and Projects" }, { "code": null, "e": 30801, "s": 30767, "text": "Recent Articles on Matplotlib !!!" }, { "code": null, "e": 30948, "s": 30803, "text": "Before we start learning about Matplotlib we first have to set up the environment and will also see how to use Matplotlib with Jupyter Notebook:" }, { "code": null, "e": 30983, "s": 30950, "text": "Environment Setup for Matplotlib" }, { "code": null, "e": 31022, "s": 30983, "text": "Using Matplotlib with Jupyter Notebook" }, { "code": null, "e": 31208, "s": 31022, "text": "After learning about the environment setup and how to use Matplotlib with Jupyter let’s create a simple plot. We will be plotting two lists containing the X, Y coordinates for the plot." }, { "code": null, "e": 31219, "s": 31210, "text": "Example:" }, { "code": null, "e": 31229, "s": 31221, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # initializing the data x = [10, 20, 30, 40] y = [20, 30, 40, 50] # plotting the data plt.plot(x, y) # Adding the title plt.title(\"Simple Plot\") # Adding the labels plt.ylabel(\"y-axis\") plt.xlabel(\"x-axis\") plt.show()", "e": 31501, "s": 31229, "text": null }, { "code": null, "e": 31509, "s": 31501, "text": "Output:" }, { "code": null, "e": 31776, "s": 31511, "text": "In the above example, the elements of X and Y provides the coordinates for the x axis and y axis and a straight line is plotted against those coordinates. For a detailed introduction to Matplotlib and to see how basic charts are plotted refer to the below article." }, { "code": null, "e": 31805, "s": 31778, "text": "Introduction to Matplotlib" }, { "code": null, "e": 31844, "s": 31805, "text": "Simple Plot in Python using Matplotlib" }, { "code": null, "e": 32014, "s": 31844, "text": "In the above article, you might have seen Pyplot was imported in code and must have wondered what is Pyplot. Don’t worry we will discuss the Pyplot in the next section. " }, { "code": null, "e": 32231, "s": 32016, "text": "Pyplot is a Matplotlib module that provides a MATLAB like interface. Pyplot provides functions that interact with the figure i.e. creates a figure, decorates the plot with labels, creates plotting area in a figure." }, { "code": null, "e": 32241, "s": 32233, "text": "Syntax:" }, { "code": null, "e": 32320, "s": 32243, "text": "matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)" }, { "code": null, "e": 32331, "s": 32322, "text": "Example:" }, { "code": null, "e": 32341, "s": 32333, "text": "Python3" }, { "code": "# Python program to show pyplot module import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.axis([0, 6, 0, 20]) plt.show()", "e": 32496, "s": 32341, "text": null }, { "code": null, "e": 32504, "s": 32496, "text": "Output:" }, { "code": null, "e": 32615, "s": 32504, "text": "Refer to the below articles to get detailed information about Pyplot and functions associated with this class." }, { "code": null, "e": 32636, "s": 32615, "text": "Pyplot in Matplotlib" }, { "code": null, "e": 32680, "s": 32636, "text": "Matplotlib.pyplot.plot() function in Python" }, { "code": null, "e": 32716, "s": 32680, "text": "Matplotlib.pyplot.title() in Python" }, { "code": null, "e": 32753, "s": 32716, "text": "matplotlib.pyplot.imshow() in Python" }, { "code": null, "e": 32790, "s": 32753, "text": "Matplotlib.pyplot.legend() in Python" }, { "code": null, "e": 32829, "s": 32790, "text": "Matplotlib.pyplot.subplots() in Python" }, { "code": null, "e": 32866, "s": 32829, "text": "Matplotlib.pyplot.colors() in Python" }, { "code": null, "e": 32901, "s": 32866, "text": "Matplotlib.pyplot.grid() in Python" }, { "code": null, "e": 32936, "s": 32901, "text": ">>> More Functions on Pyplot class" }, { "code": null, "e": 33143, "s": 32936, "text": "Matplotlib take care of the creation of inbuilt defaults like Figure and Axes. Don’t worry about these terms we will study about them in detail in the below section but let’s take a brief about these terms." }, { "code": null, "e": 33366, "s": 33143, "text": "Figure: This class is the top-level container for all the plots means it is the overall window or page on which everything is drawn. A figure object can be considered as a box-like container that can hold one or more axes." }, { "code": null, "e": 33613, "s": 33366, "text": "Axes: This class is the most basic and flexible component for creating sub-plots. You might confuse axes as the plural of axis but it is an individual plot or graph. A given figure may contain many axes but a given axes can only be in one figure." }, { "code": null, "e": 33748, "s": 33613, "text": "Figure class is the top-level container that contains one or more axes. It is the overall window or page on which everything is drawn." }, { "code": null, "e": 33756, "s": 33748, "text": "Syntax:" }, { "code": null, "e": 33934, "s": 33756, "text": "class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None)" }, { "code": null, "e": 33945, "s": 33934, "text": "Example 1:" }, { "code": null, "e": 33953, "s": 33945, "text": "Python3" }, { "code": "# Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure # Creating a new figure with width = 5 inches # and height = 4 inches fig = plt.figure(figsize =(5, 4)) # Creating a new axes for the figure ax = fig.add_axes([1, 1, 1, 1]) # Adding the data to be plotted ax.plot([2, 3, 4, 5, 5, 6, 6], [5, 7, 1, 3, 4, 6 ,8]) plt.show()", "e": 34355, "s": 33953, "text": null }, { "code": null, "e": 34363, "s": 34355, "text": "Output:" }, { "code": null, "e": 34402, "s": 34367, "text": "Example 2: Creating multiple plots" }, { "code": null, "e": 34412, "s": 34404, "text": "Python3" }, { "code": "# Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure # Creating a new figure with width = 5 inches # and height = 4 inches fig = plt.figure(figsize =(5, 4)) # Creating first axes for the figure ax1 = fig.add_axes([1, 1, 1, 1]) # Creating second axes for the figure ax2 = fig.add_axes([1, 0.5, 0.5, 0.5]) # Adding the data to be plotted ax1.plot([2, 3, 4, 5, 5, 6, 6], [5, 7, 1, 3, 4, 6 ,8]) ax2.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6]) plt.show()", "e": 34942, "s": 34412, "text": null }, { "code": null, "e": 34950, "s": 34942, "text": "Output:" }, { "code": null, "e": 35067, "s": 34954, "text": "Refer to the below articles to get detailed information about the Figure class and functions associated with it." }, { "code": null, "e": 35106, "s": 35069, "text": "Matplotlib.figure.Figure() in Python" }, { "code": null, "e": 35152, "s": 35106, "text": "Matplotlib.figure.Figure.add_axes() in Python" }, { "code": null, "e": 35195, "s": 35152, "text": "Matplotlib.figure.Figure.clear() in Python" }, { "code": null, "e": 35241, "s": 35195, "text": "Matplotlib.figure.Figure.colorbar() in Python" }, { "code": null, "e": 35291, "s": 35241, "text": "Matplotlib.figure.Figure.get_figwidth() in Python" }, { "code": null, "e": 35342, "s": 35291, "text": "Matplotlib.figure.Figure.get_figheight() in Python" }, { "code": null, "e": 35388, "s": 35342, "text": "Matplotlib.figure.Figure.subplots() in Python" }, { "code": null, "e": 35425, "s": 35390, "text": ">>> More Functions in Figure Class" }, { "code": null, "e": 35662, "s": 35427, "text": "Axes class is the most basic and flexible unit for creating sub-plots. A given figure may contain many axes, but a given axes can only be present in one figure. The axes() function creates the axes object. Let’s see the below example." }, { "code": null, "e": 35672, "s": 35664, "text": "Syntax:" }, { "code": null, "e": 35725, "s": 35674, "text": "matplotlib.pyplot.axis(*args, emit=True, **kwargs)" }, { "code": null, "e": 35736, "s": 35725, "text": "Example 1:" }, { "code": null, "e": 35746, "s": 35738, "text": "Python3" }, { "code": "# Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure # Creating the axes object with argument as # [left, bottom, width, height] ax = plt.axes([1, 1, 1, 1])", "e": 35971, "s": 35746, "text": null }, { "code": null, "e": 35979, "s": 35971, "text": "Output:" }, { "code": null, "e": 35995, "s": 35983, "text": "Example 2: " }, { "code": null, "e": 36005, "s": 35997, "text": "Python3" }, { "code": "# Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure fig = plt.figure(figsize = (5, 4)) # Adding the axes to the figure ax = fig.add_axes([1, 1, 1, 1]) # plotting 1st dataset to the figure ax1 = ax.plot([1, 2, 3, 4], [1, 2, 3, 4]) # plotting 2nd dataset to the figure ax2 = ax.plot([1, 2, 3, 4], [2, 3, 4, 5]) plt.show()", "e": 36403, "s": 36005, "text": null }, { "code": null, "e": 36411, "s": 36403, "text": "Output:" }, { "code": null, "e": 36524, "s": 36413, "text": "Refer to the below articles to get detailed information about the axes class and functions associated with it." }, { "code": null, "e": 36550, "s": 36526, "text": "Matplotlib – Axes Class" }, { "code": null, "e": 36590, "s": 36550, "text": "Matplotlib.axes.Axes.update() in Python" }, { "code": null, "e": 36628, "s": 36590, "text": "Matplotlib.axes.Axes.draw() in Python" }, { "code": null, "e": 36672, "s": 36628, "text": "Matplotlib.axes.Axes.get_figure() in Python" }, { "code": null, "e": 36716, "s": 36672, "text": "Matplotlib.axes.Axes.set_figure() in Python" }, { "code": null, "e": 36760, "s": 36716, "text": "Matplotlib.axes.Axes.properties() in Python" }, { "code": null, "e": 36793, "s": 36760, "text": ">>> More Functions on Axes Class" }, { "code": null, "e": 37165, "s": 36799, "text": "You might have seen that Matplotlib automatically sets the values and the markers(points) of the x and y axis, however, it is possible to set the limit and markers manually. set_xlim() and set_ylim() functions are used to set the limits of the x-axis and y-axis respectively. Similarly, set_xticklabels() and set_yticklabels() functions are used to set tick labels." }, { "code": null, "e": 37176, "s": 37167, "text": "Example:" }, { "code": null, "e": 37186, "s": 37178, "text": "Python3" }, { "code": "# Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure x = [3, 1, 3] y = [3, 2, 1] # Creating a new figure with width = 5 inches # and height = 4 inches fig = plt.figure(figsize =(5, 4)) # Creating first axes for the figure ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Adding the data to be plotted ax.plot(x, y) ax.set_xlim(1, 2) ax.set_xticklabels(( \"one\", \"two\", \"three\", \"four\", \"five\", \"six\")) plt.show()", "e": 37683, "s": 37186, "text": null }, { "code": null, "e": 37691, "s": 37683, "text": "Output:" }, { "code": null, "e": 38041, "s": 37695, "text": "Till now you must have got a basic idea about Matplotlib and plotting some simple plots, now what if you want to plot multiple plots in the same figure. This can be done using multiple ways. One way was discussed above using the add_axes() method of the figure class. Let’s see various ways multiple plots can be added with the help of examples." }, { "code": null, "e": 38082, "s": 38043, "text": "Method 1: Using the add_axes() method " }, { "code": null, "e": 38180, "s": 38084, "text": "The add_axes() method figure module of matplotlib library is used to add an axes to the figure." }, { "code": null, "e": 38190, "s": 38182, "text": "Syntax:" }, { "code": null, "e": 38224, "s": 38192, "text": "add_axes(self, *args, **kwargs)" }, { "code": null, "e": 38235, "s": 38226, "text": "Example:" }, { "code": null, "e": 38245, "s": 38237, "text": "Python3" }, { "code": "# Python program to show pyplot module import matplotlib.pyplot as plt from matplotlib.figure import Figure # Creating a new figure with width = 5 inches # and height = 4 inches fig = plt.figure(figsize =(5, 4)) # Creating first axes for the figure ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # Creating second axes for the figure ax2 = fig.add_axes([0.5, 0.5, 0.3, 0.3]) # Adding the data to be plotted ax1.plot([5, 4, 3, 2, 1], [2, 3, 4, 5, 6]) ax2.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6]) plt.show()", "e": 38773, "s": 38245, "text": null }, { "code": null, "e": 38781, "s": 38773, "text": "Output:" }, { "code": null, "e": 38871, "s": 38783, "text": "The add_axes() method adds the plot in the same figure by creating another axes object." }, { "code": null, "e": 38908, "s": 38873, "text": "Method 2: Using subplot() method. " }, { "code": null, "e": 38994, "s": 38910, "text": "This method adds another plot to the current figure at the specified grid position." }, { "code": null, "e": 39004, "s": 38996, "text": "Syntax:" }, { "code": null, "e": 39045, "s": 39006, "text": "subplot(nrows, ncols, index, **kwargs)" }, { "code": null, "e": 39069, "s": 39045, "text": "subplot(pos, **kwargs) " }, { "code": null, "e": 39081, "s": 39069, "text": "subplot(ax)" }, { "code": null, "e": 39090, "s": 39081, "text": "Example:" }, { "code": null, "e": 39100, "s": 39092, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3] y = [3, 2, 1] z = [1, 3, 1] # Creating figure object plt.figure() # addind first subplot plt.subplot(121) plt.plot(x, y) # addding second subplot plt.subplot(122) plt.plot(z, y)", "e": 39387, "s": 39100, "text": null }, { "code": null, "e": 39395, "s": 39387, "text": "Output:" }, { "code": null, "e": 39456, "s": 39395, "text": "Note: Subplot() function have the following disadvantages – " }, { "code": null, "e": 39517, "s": 39456, "text": "It does not allow adding multiple subplots at the same time." }, { "code": null, "e": 39564, "s": 39517, "text": "It deletes the preexisting plot of the figure." }, { "code": null, "e": 39598, "s": 39564, "text": "Method 3: Using subplots() method" }, { "code": null, "e": 39677, "s": 39598, "text": "This function is used to create figure and multiple subplots at the same time." }, { "code": null, "e": 39685, "s": 39677, "text": "Syntax:" }, { "code": null, "e": 39817, "s": 39685, "text": "matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)" }, { "code": null, "e": 39826, "s": 39817, "text": "Example:" }, { "code": null, "e": 39834, "s": 39826, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Creating the figure and subplots # according the argument passed fig, axes = plt.subplots(1, 2) # plotting the data in the 1st subplot axes[0].plot([1, 2, 3, 4], [1, 2, 3, 4]) # plotting the data in the 1st subplot only axes[0].plot([1, 2, 3, 4], [4, 3, 2, 1]) # plotting the data in the 2nd subplot only axes[1].plot([1, 2, 3, 4], [1, 1, 1, 1])", "e": 40233, "s": 39834, "text": null }, { "code": null, "e": 40241, "s": 40233, "text": "Output:" }, { "code": null, "e": 40283, "s": 40245, "text": "Method 4: Using subplot2grid() method" }, { "code": null, "e": 40555, "s": 40285, "text": "This function give additional flexibility in creating axes object at a specified location inside a grid. It also helps in spanning the axes object across multiple rows or columns. In simpler words, this function is used to create multiple charts within the same figure." }, { "code": null, "e": 40565, "s": 40557, "text": "Syntax:" }, { "code": null, "e": 40619, "s": 40567, "text": "Plt.subplot2grid(shape, location, rowspan, colspan)" }, { "code": null, "e": 40630, "s": 40621, "text": "Example:" }, { "code": null, "e": 40640, "s": 40632, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3] y = [3, 2, 1] z = [1, 3, 1] # adding the subplots axes1 = plt.subplot2grid ( (7, 1), (0, 0), rowspan = 2, colspan = 1) axes2 = plt.subplot2grid ( (7, 1), (2, 0), rowspan = 2, colspan = 1) axes3 = plt.subplot2grid ( (7, 1), (4, 0), rowspan = 2, colspan = 1) # plotting the data axes1.plot(x, y) axes2.plot(x, z) axes3.plot(z, y)", "e": 41080, "s": 40640, "text": null }, { "code": null, "e": 41088, "s": 41080, "text": "Output:" }, { "code": null, "e": 41163, "s": 41092, "text": "Refer to the below articles to get detailed information about subplots" }, { "code": null, "e": 41222, "s": 41165, "text": "How to create multiple subplots in Matplotlib in Python?" }, { "code": null, "e": 41266, "s": 41222, "text": "How to Add Title to Subplots in Matplotlib?" }, { "code": null, "e": 41333, "s": 41266, "text": "How to Set a Single Main Title for All the Subplots in Matplotlib?" }, { "code": null, "e": 41386, "s": 41333, "text": "How to Turn Off the Axes for Subplots in Matplotlib?" }, { "code": null, "e": 41439, "s": 41386, "text": "How to Create Different Subplot Sizes in Matplotlib?" }, { "code": null, "e": 41504, "s": 41439, "text": "How to set the spacing between subplots in Matplotlib in Python?" }, { "code": null, "e": 41554, "s": 41504, "text": "Matplotlib Sub plotting using object oriented API" }, { "code": null, "e": 41618, "s": 41554, "text": "Make subplots span multiple grid rows and columns in Matplotlib" }, { "code": null, "e": 41883, "s": 41620, "text": "A legend is an area describing the elements of the graph. In simple terms, it reflects the data displayed in the graph’s Y-axis. It generally appears as the box containing a small sample of each color on the graph and a small description of what this data means." }, { "code": null, "e": 42204, "s": 41885, "text": "A Legend can be created using the legend() method. The attribute Loc in the legend() is used to specify the location of the legend. The default value of loc is loc=”best” (upper left). The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure." }, { "code": null, "e": 42414, "s": 42206, "text": "The attribute bbox_to_anchor=(x, y) of legend() function is used to specify the coordinates of the legend, and the attribute ncol represents the number of columns that the legend has. Its default value is 1." }, { "code": null, "e": 42424, "s": 42416, "text": "Syntax:" }, { "code": null, "e": 42507, "s": 42426, "text": "matplotlib.pyplot.legend([“blue”, “green”], bbox_to_anchor=(0.75, 1.15), ncol=2)" }, { "code": null, "e": 42518, "s": 42509, "text": "Example:" }, { "code": null, "e": 42528, "s": 42520, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3] y = [3, 2, 1] plt.plot(x, y) plt.plot(y, x) # Adding the legends plt.legend([\"blue\", \"orange\"]) plt.show()", "e": 42728, "s": 42528, "text": null }, { "code": null, "e": 42736, "s": 42728, "text": "Output:" }, { "code": null, "e": 42816, "s": 42740, "text": "Refer to the below articles to get detailed information about the legend – " }, { "code": null, "e": 42855, "s": 42818, "text": "Matplotlib.pyplot.legend() in Python" }, { "code": null, "e": 42895, "s": 42855, "text": "Matplotlib.axes.Axes.legend() in Python" }, { "code": null, "e": 42936, "s": 42895, "text": "Change the legend position in Matplotlib" }, { "code": null, "e": 42982, "s": 42936, "text": "How to Change Legend Font Size in Matplotlib?" }, { "code": null, "e": 43052, "s": 42982, "text": "How Change the vertical spacing between legend entries in Matplotlib?" }, { "code": null, "e": 43096, "s": 43052, "text": "Use multiple columns in a Matplotlib legend" }, { "code": null, "e": 43158, "s": 43096, "text": "How to Create a Single Legend for All Subplots in Matplotlib?" }, { "code": null, "e": 43229, "s": 43158, "text": "How to manually add a legend with a color box on a Matplotlib figure ?" }, { "code": null, "e": 43284, "s": 43229, "text": "How to Place Legend Outside of the Plot in Matplotlib?" }, { "code": null, "e": 43324, "s": 43284, "text": "How to Remove the Legend in Matplotlib?" }, { "code": null, "e": 43363, "s": 43324, "text": "Remove the legend border in Matplotlib" }, { "code": null, "e": 43647, "s": 43367, "text": "Till now you all must have seen that we are working with only the line charts as they are easy to plot and understand. Line Chart is used to represent a relationship between two data X and Y on a different axis. It is plotted using the pot() function. Let’s see the below example" }, { "code": null, "e": 43658, "s": 43649, "text": "Example:" }, { "code": null, "e": 43668, "s": 43660, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3] y = [3, 2, 1] # This will plot a simple line chart # with elements of x as x axis and y # as y axis plt.plot(x, y) plt.title(\"Line Chart\") # Adding the legends plt.legend([\"Line\"]) plt.show()", "e": 43959, "s": 43668, "text": null }, { "code": null, "e": 43967, "s": 43959, "text": "Output:" }, { "code": null, "e": 44044, "s": 43971, "text": "Refer to the below article to get detailed information about line chart." }, { "code": null, "e": 44071, "s": 44046, "text": "Line chart in Matplotlib" }, { "code": null, "e": 44102, "s": 44071, "text": "Line plot styles in Matplotlib" }, { "code": null, "e": 44139, "s": 44102, "text": "Plot a Horizontal line in Matplotlib" }, { "code": null, "e": 44174, "s": 44139, "text": "Plot a Vertical line in Matplotlib" }, { "code": null, "e": 44208, "s": 44174, "text": "Plot Multiple lines in Matplotlib" }, { "code": null, "e": 44246, "s": 44208, "text": "Change the line opacity in Matplotlib" }, { "code": null, "e": 44295, "s": 44246, "text": "Increase the thickness of a line with Matplotlib" }, { "code": null, "e": 44328, "s": 44295, "text": "Plot line graph from NumPy array" }, { "code": null, "e": 44378, "s": 44328, "text": "How to Fill Between Multiple Lines in Matplotlib?" }, { "code": null, "e": 44726, "s": 44380, "text": "A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. It can be created using the bar() method." }, { "code": null, "e": 44736, "s": 44728, "text": "Syntax:" }, { "code": null, "e": 44779, "s": 44738, "text": "plt.bar(x, height, width, bottom, align)" }, { "code": null, "e": 44788, "s": 44779, "text": "Example:" }, { "code": null, "e": 44798, "s": 44790, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3, 12, 2, 4, 4] y = [3, 2, 1, 4, 5, 6, 7] # This will plot a simple bar chart plt.bar(x, y) # Title to the plot plt.title(\"Bar Chart\") # Adding the legends plt.legend([\"bar\"]) plt.show()", "e": 45079, "s": 44798, "text": null }, { "code": null, "e": 45087, "s": 45079, "text": "Output:" }, { "code": null, "e": 45166, "s": 45091, "text": "Refer to the below articles to get detailed information about Bar charts –" }, { "code": null, "e": 45191, "s": 45168, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 45235, "s": 45191, "text": "Draw a horizontal bar chart with Matplotlib" }, { "code": null, "e": 45275, "s": 45235, "text": "Create a stacked bar plot in Matplotlib" }, { "code": null, "e": 45317, "s": 45275, "text": "Stacked Percentage Bar Plot In MatPlotLib" }, { "code": null, "e": 45361, "s": 45317, "text": "Plotting back-to-back bar charts Matplotlib" }, { "code": null, "e": 45431, "s": 45361, "text": "How to display the value of each bar in a bar chart using Matplotlib?" }, { "code": null, "e": 45490, "s": 45431, "text": "How To Annotate Bars in Barplot with Matplotlib in Python?" }, { "code": null, "e": 45541, "s": 45490, "text": "How to Annotate Bars in Grouped Barplot in Python?" }, { "code": null, "e": 46092, "s": 45541, "text": "A histogram is basically used to represent data in the form of some groups. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. To create a histogram the first step is to create a bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals. Bins are clearly identified as consecutive, non-overlapping intervals of variables. The hist() function is used to compute and create histogram of x." }, { "code": null, "e": 46102, "s": 46094, "text": "Syntax:" }, { "code": null, "e": 46356, "s": 46104, "text": "matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, \\*, data=None, \\*\\*kwargs)" }, { "code": null, "e": 46365, "s": 46356, "text": "Example:" }, { "code": null, "e": 46375, "s": 46367, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # data to display on plots x = [1, 2, 3, 4, 5, 6, 7, 4] # This will plot a simple histogram plt.hist(x, bins = [1, 2, 3, 4, 5, 6, 7]) # Title to the plot plt.title(\"Histogram\") # Adding the legends plt.legend([\"bar\"]) plt.show()", "e": 46657, "s": 46375, "text": null }, { "code": null, "e": 46665, "s": 46657, "text": "Output:" }, { "code": null, "e": 46743, "s": 46669, "text": "Refer to the below articles to get detailed information about histograms." }, { "code": null, "e": 46791, "s": 46745, "text": "Plotting Histogram in Python using Matplotlib" }, { "code": null, "e": 46835, "s": 46791, "text": "Create a cumulative histogram in Matplotlib" }, { "code": null, "e": 46886, "s": 46835, "text": "How to plot two histograms together in Matplotlib?" }, { "code": null, "e": 46935, "s": 46886, "text": "Overlapping Histograms with Matplotlib in Python" }, { "code": null, "e": 46968, "s": 46935, "text": "Bin Size in Matplotlib Histogram" }, { "code": null, "e": 47029, "s": 46968, "text": "Compute the histogram of a set of data using NumPy in Python" }, { "code": null, "e": 47075, "s": 47029, "text": "Plot 2-D Histogram in Python using Matplotlib" }, { "code": null, "e": 47277, "s": 47075, "text": "Scatter plots are used to observe relationship between variables and uses dots to represent the relationship between them. The scatter() method in the matplotlib library is used to draw a scatter plot." }, { "code": null, "e": 47287, "s": 47279, "text": "Syntax:" }, { "code": null, "e": 47449, "s": 47289, "text": "matplotlib.pyplot.scatter(x_axis_data, y_axis_data, s=None, c=None, marker=None, cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None)" }, { "code": null, "e": 47458, "s": 47449, "text": "Example:" }, { "code": null, "e": 47468, "s": 47460, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # data to display on plots x = [3, 1, 3, 12, 2, 4, 4] y = [3, 2, 1, 4, 5, 6, 7] # This will plot a simple scatter chart plt.scatter(x, y) # Adding legend to the plot plt.legend(\"A\") # Title to the plot plt.title(\"Scatter chart\") plt.show()", "e": 47762, "s": 47468, "text": null }, { "code": null, "e": 47770, "s": 47762, "text": "Output:" }, { "code": null, "e": 47854, "s": 47774, "text": "Refer to the below articles to get detailed information about the scatter plot." }, { "code": null, "e": 47894, "s": 47856, "text": "matplotlib.pyplot.scatter() in Python" }, { "code": null, "e": 47948, "s": 47894, "text": "How to add a legend to a scatter plot in Matplotlib ?" }, { "code": null, "e": 48007, "s": 47948, "text": "How to Connect Scatterplot Points With Line in Matplotlib?" }, { "code": null, "e": 48071, "s": 48007, "text": "How to create a Scatter Plot with several colors in Matplotlib?" }, { "code": null, "e": 48130, "s": 48071, "text": "How to increase the size of scatter points in Matplotlib ?" }, { "code": null, "e": 48518, "s": 48132, "text": "A Pie Chart is a circular statistical plot that can display only one series of data. The area of the chart is the total percentage of the given data. The area of slices of the pie represents the percentage of the parts of the data. The slices of pie are called wedges. The area of the wedge is determined by the length of the arc of the wedge. It can be created using the pie() method." }, { "code": null, "e": 48528, "s": 48520, "text": "Syntax:" }, { "code": null, "e": 48626, "s": 48530, "text": "matplotlib.pyplot.pie(data, explode=None, labels=None, colors=None, autopct=None, shadow=False)" }, { "code": null, "e": 48635, "s": 48626, "text": "Example:" }, { "code": null, "e": 48645, "s": 48637, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # data to display on plots x = [1, 2, 3, 4] # this will explode the 1st wedge # i.e. will separate the 1st wedge # from the chart e =(0.1, 0, 0, 0) # This will plot a simple pie chart plt.pie(x, explode = e) # Title to the plot plt.title(\"Pie chart\") plt.show()", "e": 48965, "s": 48645, "text": null }, { "code": null, "e": 48973, "s": 48965, "text": "Output:" }, { "code": null, "e": 49051, "s": 48977, "text": "Refer to the below articles to get detailed information about pie charts." }, { "code": null, "e": 49090, "s": 49053, "text": "matplotlib.axes.Axes.pie() in Python" }, { "code": null, "e": 49134, "s": 49090, "text": "Plot a pie chart in Python using Matplotlib" }, { "code": null, "e": 49188, "s": 49134, "text": "How to set border for wedges in Matplotlib pie chart?" }, { "code": null, "e": 49236, "s": 49188, "text": "Radially displace pie chart wedge in Matplotlib" }, { "code": null, "e": 49469, "s": 49238, "text": "Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3D utilities were developed upon the 2D and thus, we have a 3D implementation of data available today." }, { "code": null, "e": 49480, "s": 49471, "text": "Example:" }, { "code": null, "e": 49490, "s": 49482, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # Creating the figure object fig = plt.figure() # keeping the projection = 3d # ctreates the 3d plot ax = plt.axes(projection = '3d')", "e": 49667, "s": 49490, "text": null }, { "code": null, "e": 49675, "s": 49667, "text": "Output:" }, { "code": null, "e": 49873, "s": 49679, "text": "The above code lets the creation of a 3D plot in Matplotlib. We can create different types of 3D plots like scatter plots, contour plots, surface plots, etc. Let’s create a simple 3D line plot." }, { "code": null, "e": 49884, "s": 49875, "text": "Example:" }, { "code": null, "e": 49894, "s": 49886, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] z = [1, 8, 27, 64, 125] # Creating the figure object fig = plt.figure() # keeping the projection = 3d # ctreates the 3d plot ax = plt.axes(projection = '3d') ax.plot3D(z, y, x)", "e": 50164, "s": 49894, "text": null }, { "code": null, "e": 50172, "s": 50164, "text": "Output:" }, { "code": null, "e": 50248, "s": 50176, "text": "Refer to the below articles to get detailed information about 3D plots." }, { "code": null, "e": 50304, "s": 50250, "text": "Three-dimensional Plotting in Python using Matplotlib" }, { "code": null, "e": 50351, "s": 50304, "text": "3D Scatter Plotting in Python using Matplotlib" }, { "code": null, "e": 50398, "s": 50351, "text": "3D Surface plotting in Python using Matplotlib" }, { "code": null, "e": 50447, "s": 50398, "text": "3D Wireframe plotting in Python using Matplotlib" }, { "code": null, "e": 50494, "s": 50447, "text": "3D Contour Plotting in Python using Matplotlib" }, { "code": null, "e": 50538, "s": 50494, "text": "Tri-Surface Plot in Python using Matplotlib" }, { "code": null, "e": 50580, "s": 50538, "text": "Surface plots and Contour plots in Python" }, { "code": null, "e": 50622, "s": 50580, "text": "How to change angle of 3D plot in Python?" }, { "code": null, "e": 50664, "s": 50622, "text": "How to animate 3D Graph using Matplotlib?" }, { "code": null, "e": 50740, "s": 50664, "text": "Draw contours on an unstructured triangular grid in Python using Matplotlib" }, { "code": null, "e": 50967, "s": 50742, "text": "The image module in matplotlib library is used for working with images in Python. The image module also includes two useful methods which are imread which is used to read images and imshow which is used to display the image." }, { "code": null, "e": 50978, "s": 50969, "text": "Example:" }, { "code": null, "e": 50988, "s": 50980, "text": "Python3" }, { "code": "# importing required libraries import matplotlib.pyplot as plt import matplotlib.image as img # reading the image testImage = img.imread('g4g.png') # displaying the image plt.imshow(testImage) ", "e": 51200, "s": 50988, "text": null }, { "code": null, "e": 51208, "s": 51200, "text": "Output:" }, { "code": null, "e": 51308, "s": 51208, "text": "Refer to the below articles to get detailed information about working with images using Matplotlib." }, { "code": null, "e": 51355, "s": 51308, "text": "Working with Images in Python using Matplotlib" }, { "code": null, "e": 51396, "s": 51355, "text": "Working with PNG Images using Matplotlib" }, { "code": null, "e": 51448, "s": 51396, "text": "How to Display an Image in Grayscale in Matplotlib?" }, { "code": null, "e": 51499, "s": 51448, "text": "Plot a Point or a Line on an Image with Matplotlib" }, { "code": null, "e": 51545, "s": 51499, "text": "How to Draw Rectangle on Image in Matplotlib?" }, { "code": null, "e": 51603, "s": 51545, "text": "How to Display an OpenCV image in Python with Matplotlib?" }, { "code": null, "e": 51651, "s": 51603, "text": "Calculate the area of an image using Matplotlib" }, { "code": null, "e": 51680, "s": 51651, "text": "Style Plots using Matplotlib" }, { "code": null, "e": 51720, "s": 51680, "text": "Change plot size in Matplotlib – Python" }, { "code": null, "e": 51794, "s": 51720, "text": "How to Change the Transparency of a Graph Plot in Matplotlib with Python?" }, { "code": null, "e": 51861, "s": 51794, "text": "How to Change the Color of a Graph Plot in Matplotlib with Python?" }, { "code": null, "e": 51896, "s": 51861, "text": "How to Change Fonts in matplotlib?" }, { "code": null, "e": 51962, "s": 51896, "text": "How to change the font size of the Title in a Matplotlib figure ?" }, { "code": null, "e": 52010, "s": 51962, "text": "How to Set Tick Labels Font Size in Matplotlib?" }, { "code": null, "e": 52058, "s": 52010, "text": "How to Set Plot Background Color in Matplotlib?" }, { "code": null, "e": 52122, "s": 52058, "text": "How to generate a random color for a Matplotlib plot in Python?" }, { "code": null, "e": 52161, "s": 52122, "text": "Add Text Inside the Plot in Matplotlib" }, { "code": null, "e": 52192, "s": 52161, "text": "How to add text to Matplotlib?" }, { "code": null, "e": 52243, "s": 52192, "text": "How to change Matplotlib color bar size in Python?" }, { "code": null, "e": 52314, "s": 52243, "text": "How to manually add a legend with a color box on a Matplotlib figure ?" }, { "code": null, "e": 52367, "s": 52314, "text": "How to change the size of axis labels in Matplotlib?" }, { "code": null, "e": 52425, "s": 52367, "text": "How to Hide Axis Text Ticks or Tick Labels in Matplotlib?" }, { "code": null, "e": 52478, "s": 52425, "text": "How To Adjust Position of Axis Labels in Matplotlib?" }, { "code": null, "e": 52528, "s": 52478, "text": "Hide Axis, Borders and White Spaces in Matplotlib" }, { "code": null, "e": 52585, "s": 52528, "text": "How to Create an Empty Figure with Matplotlib in Python?" }, { "code": null, "e": 52635, "s": 52585, "text": "Change the x or y interval of a Matplotlib figure" }, { "code": null, "e": 52680, "s": 52635, "text": "How to add a grid on a figure in Matplotlib?" }, { "code": null, "e": 52737, "s": 52680, "text": "How to change the size of figures drawn with matplotlib?" }, { "code": null, "e": 52776, "s": 52737, "text": "Place plots side by side in Matplotlib" }, { "code": null, "e": 52811, "s": 52776, "text": "How to Reverse Axes in Matplotlib?" }, { "code": null, "e": 52871, "s": 52811, "text": "How to remove the frame from a Matplotlib figure in Python?" }, { "code": null, "e": 52935, "s": 52871, "text": "Use different y-axes on the left and right of a Matplotlib plot" }, { "code": null, "e": 53000, "s": 52935, "text": "How to Add a Y-Axis Label to the Secondary Y-Axis in Matplotlib?" }, { "code": null, "e": 53050, "s": 53000, "text": "How to plot a simple vector field in Matplotlib ?" }, { "code": null, "e": 53116, "s": 53050, "text": "Difference Between cla(), clf() and close() Methods in Matplotlib" }, { "code": null, "e": 53194, "s": 53116, "text": "Make filled polygons between two horizontal curves in Python using Matplotlib" }, { "code": null, "e": 53241, "s": 53194, "text": "How to Save a Plot to a File Using Matplotlib?" }, { "code": null, "e": 53285, "s": 53241, "text": "How to Plot Logarithmic Axes in Matplotlib?" }, { "code": null, "e": 53346, "s": 53285, "text": "How to put the y-axis in logarithmic scale with Matplotlib ?" }, { "code": null, "e": 53397, "s": 53346, "text": "How to draw 2D Heatmap using Matplotlib in python?" }, { "code": null, "e": 53438, "s": 53397, "text": "Plotting Correlation Matrix using Python" }, { "code": null, "e": 53495, "s": 53438, "text": "Plot Candlestick Chart using mplfinance module in Python" }, { "code": null, "e": 53533, "s": 53495, "text": "Autocorrelation plot using Matplotlib" }, { "code": null, "e": 53563, "s": 53533, "text": "Stem and Leaf Plots in Python" }, { "code": null, "e": 53607, "s": 53563, "text": "Python | Basic Gantt chart using Matplotlib" }, { "code": null, "e": 53659, "s": 53607, "text": "How to Plot List of X, Y Coordinates in Matplotlib?" }, { "code": null, "e": 53727, "s": 53659, "text": "How to put the origin in the center of the figure with Matplotlib ?" }, { "code": null, "e": 53776, "s": 53727, "text": "How to Draw a Circle Using Matplotlib in Python?" }, { "code": null, "e": 53827, "s": 53776, "text": "How to Plot Mean and Standard Deviation in Pandas?" }, { "code": null, "e": 53885, "s": 53827, "text": "How to plot a complex number in Python using Matplotlib ?" }, { "code": null, "e": 53924, "s": 53885, "text": "3D Sine Wave Using Matplotlib – Python" }, { "code": null, "e": 53981, "s": 53924, "text": "Plotting A Square Wave Using Matplotlib, Numpy And Scipy" }, { "code": null, "e": 54038, "s": 53981, "text": "How to Make a Square Plot With Equal Axes in Matplotlib?" }, { "code": null, "e": 54080, "s": 54038, "text": "Plotting a Sawtooth Wave using Matplotlib" }, { "code": null, "e": 54117, "s": 54080, "text": "Visualizing Bubble sort using Python" }, { "code": null, "e": 54162, "s": 54117, "text": "Visualization of Merge sort using Matplotlib" }, { "code": null, "e": 54207, "s": 54162, "text": "Visualization of Quick sort using Matplotlib" }, { "code": null, "e": 54263, "s": 54207, "text": "Insertion Sort Visualization using Matplotlib in Python" }, { "code": null, "e": 54321, "s": 54263, "text": "3D Visualisation of Quick Sort using Matplotlib in Python" }, { "code": null, "e": 54369, "s": 54321, "text": "3D Visualisation of Merge Sort using Matplotlib" }, { "code": null, "e": 54431, "s": 54369, "text": "3D Visualisation of Insertion Sort using Matplotlib in Python" }, { "code": null, "e": 54493, "s": 54431, "text": "How to plot a normal distribution with Matplotlib in Python ?" }, { "code": null, "e": 54545, "s": 54493, "text": "Normal Distribution Plot using Numpy and Matplotlib" }, { "code": null, "e": 54611, "s": 54545, "text": "How to Create a Poisson Probability Mass Function Plot in Python?" }, { "code": null, "e": 54661, "s": 54611, "text": "Find all peaks amplitude lies above 0 Using Scipy" }, { "code": null, "e": 54708, "s": 54661, "text": "How to plot ricker curve using SciPy – Python?" }, { "code": null, "e": 54753, "s": 54708, "text": "How to Plot a Confidence Interval in Python?" }, { "code": null, "e": 54830, "s": 54753, "text": "How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?" }, { "code": null, "e": 54893, "s": 54830, "text": "How to Make a Time Series Plot with Rolling Average in Python?" }, { "code": null, "e": 54940, "s": 54893, "text": "Digital Band Pass Butterworth Filter in Python" }, { "code": null, "e": 54989, "s": 54940, "text": "Digital Band Reject Butterworth Filter in Python" }, { "code": null, "e": 55036, "s": 54989, "text": "Digital High Pass Butterworth Filter in Python" }, { "code": null, "e": 55082, "s": 55036, "text": "Digital Low Pass Butterworth Filter in Python" }, { "code": null, "e": 55140, "s": 55082, "text": "Design an IIR Notch Filter to Denoise Signal using Python" }, { "code": null, "e": 55208, "s": 55140, "text": "Design an IIR Bandpass Chebyshev Type-2 Filter using Scipy – Python" }, { "code": null, "e": 55269, "s": 55208, "text": "Visualizing Tiff File Using Matplotlib and GDAL using Python" }, { "code": null, "e": 55331, "s": 55269, "text": "Plotting Various Sounds on Graphs using Python and Matplotlib" }, { "code": null, "e": 55386, "s": 55331, "text": "COVID-19 Data Visualization using matplotlib in Python" }, { "code": null, "e": 55436, "s": 55386, "text": "Analyzing selling price of used cars using Python" }, { "code": null, "e": 55444, "s": 55436, "text": "clintra" }, { "code": null, "e": 55462, "s": 55444, "text": "Python-matplotlib" }, { "code": null, "e": 55469, "s": 55462, "text": "Python" }, { "code": null, "e": 55567, "s": 55469, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55576, "s": 55567, "text": "Comments" }, { "code": null, "e": 55589, "s": 55576, "text": "Old Comments" }, { "code": null, "e": 55639, "s": 55589, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 55661, "s": 55639, "text": "Python map() function" }, { "code": null, "e": 55705, "s": 55661, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 55723, "s": 55705, "text": "Python Dictionary" }, { "code": null, "e": 55751, "s": 55723, "text": "Read JSON file using Python" }, { "code": null, "e": 55774, "s": 55751, "text": "Taking input in Python" }, { "code": null, "e": 55796, "s": 55774, "text": "Enumerate() in Python" }, { "code": null, "e": 55831, "s": 55796, "text": "Read a file line by line in Python" }, { "code": null, "e": 55873, "s": 55831, "text": "Different ways to create Pandas Dataframe" } ]
What is the importance of jmod format in Java 9?
Java 9 has introduced a new format called "jmod" to encapsulate modules. The jmod files can be designed to handle more content types than jar files. It can also package local codes, configuration files, local commands, and other types of data. The "jmod" format hasn't support at runtime and can be based on zip format currently. The jmod format can be used at both compile and link time and can be found in JDK_HOME\jmods directory, where JDK_HOME is a directory. The files in jmod format have a ".jmod" extension. Java 9 comes with a new tool called jmod, and it is located in the JDK_HOME\bin directory. It can be used to create a jmod file, list the contents of a jmod file, print a description of a module, and record the hash value of the module used. jmod <subcommand> <options> <jmod-file> The jmod command contains at least one of the following subcommands: create extract list describe hash The list and describe subcommands don't accept any options. The <jmod-file> is the jmod file to be created or the existing jmod file to be described.
[ { "code": null, "e": 1578, "s": 1062, "text": "Java 9 has introduced a new format called \"jmod\" to encapsulate modules. The jmod files can be designed to handle more content types than jar files. It can also package local codes, configuration files, local commands, and other types of data. The \"jmod\" format hasn't support at runtime and can be based on zip format currently. The jmod format can be used at both compile and link time and can be found in JDK_HOME\\jmods directory, where JDK_HOME is a directory. The files in jmod format have a \".jmod\" extension." }, { "code": null, "e": 1820, "s": 1578, "text": "Java 9 comes with a new tool called jmod, and it is located in the JDK_HOME\\bin directory. It can be used to create a jmod file, list the contents of a jmod file, print a description of a module, and record the hash value of the module used." }, { "code": null, "e": 1860, "s": 1820, "text": "jmod <subcommand> <options> <jmod-file>" }, { "code": null, "e": 1929, "s": 1860, "text": "The jmod command contains at least one of the following subcommands:" }, { "code": null, "e": 1936, "s": 1929, "text": "create" }, { "code": null, "e": 1944, "s": 1936, "text": "extract" }, { "code": null, "e": 1949, "s": 1944, "text": "list" }, { "code": null, "e": 1958, "s": 1949, "text": "describe" }, { "code": null, "e": 1963, "s": 1958, "text": "hash" }, { "code": null, "e": 2113, "s": 1963, "text": "The list and describe subcommands don't accept any options. The <jmod-file> is the jmod file to be created or the existing jmod file to be described." } ]
PySpark for Data Science Workflows | by Ben Weber | Towards Data Science
Demonstrated experience in PySpark is one of the most desirable competencies that employers are looking for when building data science teams, because it enables these teams to own live data products. While I’ve previously blogged about PySpark, Parallelization, and UDFs, I wanted to provide a proper overview of this topic as a book chapter. I’m sharing this complete chapter, because I want to encourage the adoption of PySpark as a tool for data scientists. All code examples from this post are available here, and all prerequisites are covered in the sample chapters here. You might want to grab some snacks before diving in! Spark is a general-purpose computing framework that can scale to massive data volumes. It builds upon prior big data tools such as Hadoop and MapReduce, while providing significant improvements in the expressivity of the languages it supports. One of the core components of Spark is resilient distributed datasets (RDD), which enable clusters of machines to perform workloads in a coordinated, and fault-tolerant process. In more recent versions of Spark, the Dataframe API provides an abstraction on top of RDDs that resembles the same data structure in R and Pandas. PySpark is the Python interface to Spark, and it provides an API for working with large-scale datasets in a distributed computing environment. PySpark is an extremely valuable tool for data scientists, because it can streamline the process for translating prototype models into production-grade model workflows. At Zynga, our data science team owns a number of production-grade systems that provide useful signals to our game and marketing teams. By using PySpark, we’ve been able to reduce the amount of support we need from engineering teams to scale up models from concept to production. Up until now in this book, all of the models we’ve built and deployed have been targeted at single machines. While we are able to scale up model serving to multiple machines using Lambda, ECS, and GKS, these containers worked in isolation and there was no coordination among nodes in these environments. With PySpark, we can build model workflows that are designed to operate in cluster environments for both model training and model serving. The result is that data scientists can now tackle much larger-scale problems than previously possible using prior Python tools. PySpark provides a nice tradeoff between an expressive programming language and APIs to Spark versus more legacy options such as MapReduce. A general trend is that the use of Hadoop is dropping as more data science and engineering teams are switching to Spark ecosystems. In Chapter 7 we’ll explore another distributed computing ecosystem for data science called Cloud Dataflow, but for now Spark is the open-source leader in this space. PySpark was one of the main motivations for me to switch from R to Python for data science workflows. The goal of this chapter is to provide an introduction to PySpark for Python programmers that shows how to build large-scale model pipelines for batch scoring applications, where you may have billions of records and millions of users that need to be scored. While production-grade systems will typically push results to application databases, in this chapter we’ll focus on batch processes that pull in data from a lake and push results back to the data lake for other systems to use. We’ll explore pipelines that perform model applications for both AWS and GCP. While the data sets used in this Chapter rely on AWS and GCP for storage, the Spark environment does not have to run on either of these platforms and instead can run on Azure, other clouds, or on-pem Spark clusters. We’ll cover a variety of different topics in this chapter to show different use cases of PySpark for scalable model pipelines. After showing how to make data available to Spark on S3, we’ll cover some of the basics of PySpark focusing on Dataframe operations. Next, we’ll build out a predictive model pipeline that reads in data from S3, performs batch model predictions, and then writes the results to S3. We’ll follow this by showing off how a newer feature called Pandas UDFs can be used with PySpark to perform distributed deep learning and feature engineering. To conclude, we’ll build another batch model pipeline now using GCP and then discuss how to productize workflows in a Spark ecosystem. There’s a variety of ways to both configure Spark clusters and submit commands to a cluster for execution. When getting started with PySpark as a data scientist, my recommendation is to use a freely-available notebook environment for getting up and running with Spark as quick as possible. While PySpark may not perform quite as well as Java or Scala for large-scale workflows, the ease of development in an interactive programming environment is worth the tradeoff. Based on your organization, you may be starting from scratch for Spark or using an existing solution. Here are the types of Spark deployments I’ve seen in practice: Self Hosted: An engineering team manages a set of clusters and provides console and notebook access. Cloud Solutions: AWS provides a managed Spark option called EMR and GCP has Cloud DataProc. Vendor Solutions: Databricks, Cloudera, and other vendors provide fully-managed Spark environments. There’s a number of different factors to consider when choosing a Spark ecosystem, including cost, scalability, and feature sets. As you scale the size of the team using Spark, additional considerations are whether an ecosystem supports multi-tenancy, where multiple jobs can run concurrently on the same cluster, and isolation where one job failing should not kill other jobs. Self-hosted solutions require significant engineering work to support these additional considerations, so many organizations use cloud or vendor solutions for Spark. In this book, we’ll use the Databricks Community Edition, which provides all of the baseline features needed for learning Spark in a collaborative notebook environment. Spark is a rapidly evolving ecosystem, and it’s difficult to author books about this subject that do not quickly become out of date as the platform evolves. Another issue is that many books target Scala rather than Python for the majority of coding examples. My advice for readers that want to dig deeper into the Spark ecosystem is to explore books based on the broader Spark ecosystem, such as (Karau et al. 2015). You’ll likely need to read through Scala or Java code examples, but the majority of content covered will be relevant to PySpark. A Spark environment is a cluster of machines with a single driver node and one or more worker nodes. The driver machine is the master node in the cluster and is responsible for coordinating the workloads to perform. In general, workloads will be distributed across the worker nodes when performing operations on Spark dataframe. However, when working with native Python objects, such as lists or dictionaries, objects will be instantiated on the driver node. Ideally, you want all of your workloads to be operating on worker nodes, so that the execution of the steps to perform is distributed across the cluster, and not bottlenecked by the driver node. However, there are some types of operations in PySpark where the driver has to perform all of the work. The most common situation where this happens is when using Pandas dataframes in your workloads. When you use toPandas or other commands to convert a data set to a Pandas object, all of the data is loaded into memory on the driver node, which can crash the driver node when working with large data sets. In PySpark, the majority of commands are lazily executed, meaning that an operation is not performed until an output is explicitly needed. For example, a join operation between two Spark dataframes will not immediately cause the join operation to be performed, which is how Pandas works. Instead, the join is performed once an output is added to the chain of operations to perform, such as displaying a sample of the resulting dataframe. One of the key differences between Pandas operations, where operations are eagerly performed and pulled into memory, is that PySpark operations are lazily performed and not pulled into memory until needed. One of the benefits of this approach is that the graph of operations to perform can be optimized before being sent to the cluster to execute. In general, nodes in a Spark cluster should be considered ephemeral, because a cluster can be resized during execution. Additionally, some vendors may spin up a new cluster when scheduling a job to run. This means that common operations in Python, such as saving files to disk, do not map directly to PySpark. Instead, using a distributed computing environment means that you need to use a persistent file store such as S3 when saving data. This is important for logging, because a worker node may crash and it may not be possible to ssh into the node for debugging. Most Spark deployments have a logging system set up to help with this issue, but it’s good practice to log workflow status to persistent storage. One of the quickest ways to get up and running with PySpark is to use a hosted notebook environment. Databricks is the largest Spark vendor and provides a free version for getting started called Community Edition [13]. We’ll use this environment to get started with Spark and build AWS and GCP model pipelines. The first step is to create a login on the Databricks website for the community edition. Next, perform the following steps to spin up a test cluster after logging in: Click on “Clusters” on the left navigation barClick “Create Cluster”Assign a name, “DSP”Select the most recent runtime (non-beta)Click “Create Cluster” Click on “Clusters” on the left navigation bar Click “Create Cluster” Assign a name, “DSP” Select the most recent runtime (non-beta) Click “Create Cluster” After a few minutes we’ll have a cluster set up that we can use for submitting Spark commands. Before attaching a notebook to the cluster, we’ll first set up the libraries that we’ll use throughout this chapter. Instead of using pip to install libraries, we’ll use the Databricks UI, which makes sure that every node in the cluster has the same set of libraries installed. We’ll use both Maven and PyPI to install libraries on the clusters. To install the BigQuery connector, perform the following steps: Click on “Clusters” on the left navigation barSelect the “DSP” clusterClick on the “Libraries” tabSelect “Install New”Click on the “Maven” tab.Set coordinates to com.spotify:spark-bigquery_2.11:0.2.2Click install Click on “Clusters” on the left navigation bar Select the “DSP” cluster Click on the “Libraries” tab Select “Install New” Click on the “Maven” tab. Set coordinates to com.spotify:spark-bigquery_2.11:0.2.2 Click install The UI will then show the status as resolving, and then installing, and then installed. We also need to attach a few Python libraries that are not pre-installed on a new Databricks cluster. Standard libraries such as Pandas are installed, but you might need to upgrade to a more recent version since the libraries pre-installed by Databricks can lag significantly. To install a Python library on Databricks, perform the same steps as before up to step 5. Next, instead of selecting “Maven” choose “PyPI”. Under Package, specify the package you want to install and then click “Install”. To follow along with all of the sections in this chapter, you’ll need to install the following Python packages: koalas — for Dataframe conversion featuretools — for feature generation tensorflow — for a deep learning backend keras — for a deep learning model You’ll now have a cluster set up capable of performing distributed feature engineering and deep learning. We’ll start with basic Spark commands, show off newer functionality such as the Koalas library, and then dig into these more advanced topics. After set up, your cluster library setup should look like Figure 6.1. To ensure that everything is set up successfully, restart the cluster and check the status of the installed libraries. Now that we have provisioned a cluster and set up the required libraries, we can create a notebook to start submitting commands to the cluster. To create a new notebook, perform the following steps: Click on “Databricks” on the left navigation barUnder “Common Tasks”, select “New Notebook”Assign a name “CH6”Select “Python” as the languageselect “DSP” as the clusterClick “Create” Click on “Databricks” on the left navigation bar Under “Common Tasks”, select “New Notebook” Assign a name “CH6” Select “Python” as the language select “DSP” as the cluster Click “Create” The result will be a notebook environment where you can start running Python and PySpark commands, such as print("Hello World!"). An example notebook running this command is shown in Figure 6.2. We now have a PySpark environment up and running that we can use to build distributed model pipelines. Data is essential for PySpark workflows. Spark supports a variety of methods for reading in data sets, including connecting to data lakes and data warehouses, as well as loading sample data sets from libraries, such as the Boston housing data set. Since the theme of this book is building scalable pipelines, we’ll focus on using data layers that work with distributed workflows. To get started with PySpark, we’ll stage input data for a modeling pipeline on S3, and then read in the data set as a Spark dataframe. This section will show how to stage data to S3, set up credentials for accessing the data from Spark, and fetching the data from S3 into a Spark dataframe. The first step is to set up a bucket on S3 for storing the data set we want to load. To perform this step, run the following operations on the command line. aws s3api create-bucket --bucket dsp-ch6 --region us-east-1aws s3 ls After running the command to create a new bucket, we use the ls command to verify that the bucket has been successfully created. Next, we’ll download the games data set to the EC2 instance and then move the file to S3 using the cp command, as shown in the snippet below. wget https://github.com/bgweber/Twitch/raw/master/ Recommendations/games-expand.csvaws s3 cp games-expand.csv s3://dsp-ch6/csv/games-expand.csv In addition to staging the games data set to S3, we’ll also copy a subset of the CSV files from the Kaggle NHL data set, which we set up in Section 1.5.2. Run the following commands to stage the plays and stats CSV files from the NHL data set to S3. aws s3 cp game_plays.csv s3://dsp-ch6/csv/game_plays.csvaws s3 cp game_skater_stats.csv s3://dsp-ch6/csv/game_skater_stats.csvaws s3 ls s3://dsp-ch6/csv/ We now have all of the data sets needed for the code examples in this chapter. In order to read in these data sets from Spark, we’ll need to set up S3 credentials for interacting with S3 from the Spark cluster. For production environments, it is better to use IAM roles to manage access instead of using access keys. However, the community edition of Databricks constrains how much configuration is allowed, so we’ll use access keys to get up and running with the examples in this chapter. We already set up a user for accessing S3 from an EC2 instance. To create a set of credentials for accessing S3 programmatically, perform the following steps from the AWS console: Search for and select “IAM”Click on “Users”Select the user created in Section 3.3.2, “S3_Lambda”Click “Security Credentials”Click “Create Access Key” Search for and select “IAM” Click on “Users” Select the user created in Section 3.3.2, “S3_Lambda” Click “Security Credentials” Click “Create Access Key” The result will be an access key and a secret key enabling access to S3. Save these values in a secure location, as we’ll use them in the notebook to connect to the data sets on S3. Once you are done with this chapter, it is recommended to revoke these credentials. Now that we have credentials set up for access, we can return to the Databricks notebook to read in the data set. To enable access to S3, we need to set the access key and secret key in the Hadoop configuration of the cluster. To set these keys, run the PySpark commands shown in the snippet below. You’ll need to replace the access and secret keys with the credentials we just create for the S3_Lambda role. AWS_ACCESS_KEY = "AK..."AWS_SECRET_KEY = "dC..."sc._jsc.hadoopConfiguration().set( "fs.s3n.awsAccessKeyId", AWS_ACCESS_KEY)sc._jsc.hadoopConfiguration().set( "fs.s3n.awsSecretAccessKey", AWS_SECRET_KEY) We can now read the data set into a Spark dataframe using the read command, as shown below. This command uses the spark context to issue a read command and reads in the data set using the CSV input reader. We also specify that the CSV file includes a header row and that we want Spark to infer the data types for the columns. When reading in CSV files, Spark eagerly fetches the data set into memory, which can cause issues for larger data sets. When working with large CSV files, it’s a best practice to split up large data sets into multiple files and then read in the files using a wildcard in the input path. When using other file formats, such as Parquet or AVRO, Spark lazily fetches the data sets. games_df = spark.read.csv("s3://dsp-ch6/csv/games-expand.csv", header=True, inferSchema = True)display(games_df) The display command in the snippet above is a utility function provided by Databricks that samples the input dataframe and shows a table representation of the frame, as shown in Figure 6.3. It is similar to the head function in Pandas, but provides additional functionality such as transforming the sampled dataframe into a plot. We’ll explore the plotting functionality in Section 6.3.3. Now that we have data loaded into a Spark dataframe, we can begin exploring the PySpark language, which enables data scientists to build production-grade model pipelines. PySpark is a powerful language for both exploratory analysis and building machine learning pipelines. The core data type in PySpark is the Spark dataframe, which is similar to Pandas dataframes, but is designed to execute in a distributed environment. While the Spark Dataframe API does provide a familiar interface for Python programmers, there are significant differences in the way that commands issued to these objects are executed. A key difference is that Spark commands are lazily executed, which means that commands such as iloc are not available on these objects. While working with Spark dataframes can seem constraining, the benefit is that PySpark can scale to much larger data sets than Pandas. This section will walk through common operations for Spark dataframes, including persisting data, converting between different dataframe types, transforming dataframes, and using user-defined functions. We’ll use the NHL stats data set, which provides user-level summaries of player performance for each game. To load this data set as a Spark dataframe, run the commands in the snippet below. stats_df = spark.read.csv("s3://dsp-ch6/csv/game_skater_stats.csv", header=True, inferSchema = True)display(stats_df) A common operation in PySpark is saving a dataframe to persistent storage, or reading in a data set from a storage layer. While PySpark can work with databases such as Redshift, it performs much better when using distributed files stores such as S3 or GCS. In this chapter we’ll use these types of storage layers as the outputs of model pipelines, but it’s also useful to stage data to S3 as intermediate steps within a workflow. For example, in the AutoModel [14] system at Zynga, we stage the output of the feature generation step to S3 before using MLlib to train and apply model predictions. The data storage layer to use will depend on your cloud platform. For AWS, S3 works well with Spark for distributed data reads and writes. When using S3 or other data lakes, Spark supports a variety of different file formats for persisting data. Parquet is typically the industry standard when working with Spark, but we’ll also explore Avro and ORC in addition to CSV. Avro is a better format for streaming data pipelines, and ORC is useful when working with legacy data pipelines. To show the range of data formats supported by Spark, we’ll take the stats data set and write it to AVRO, then Parquet, then ORC, and finally CSV. After performing this round trip of data IO, we’ll end up with our initial Spark dataframe. To start, we’ll save the stats dataframe in Avro format, using the code snippet shown below. This code writes the dataframe to S3 in Avro format using the Databricks Avro writer, and then reads in the results using the same library. The result of performing these steps is that we now have a Spark dataframe pointing to the Avro files on S3. Since PySpark lazily evaluates operations, the Avro files are not pulled to the Spark cluster until an output needs to be created from this data set. # AVRO writeavro_path = "s3://dsp-ch6/avro/game_skater_stats/"stats_df.write.mode('overwrite').format( "com.databricks.spark.avro").save(avro_path)# AVRO read avro_df = sqlContext.read.format( "com.databricks.spark.avro").load(avro_path) Avro is a distributed file format that is record based, while the Parquet and OR formats are column based. It is useful for the streaming workflows that we’ll explore in Chapter 9, because it compresses records for distributed data processing. The output of saving the stats dataframe in Avro format is shown in the snippet below, which shows a subset of the status files and data files generated when persisting a dataframe to S3 as Avro. Like most scalable data formats, Avro will write records to several files, based on partitions if specified, in order to enable efficient read and write operations. aws s3 ls s3://dsp-ch6/avro/game_skater_stats/2019-11-27 23:02:43 1455 _committed_15886175782508531572019-11-27 22:36:31 1455 _committed_16007797309378807952019-11-27 23:02:40 0 _started_15886175782508531572019-11-27 23:31:42 0 _started_69420741361908385862019-11-27 23:31:47 1486327 part-00000-tid-6942074136190838586- c6806d0e-9e3d-40fc-b212-61c3d45c1bc3-15-1-c000.avro2019-11-27 23:31:43 44514 part-00007-tid-6942074136190838586- c6806d0e-9e3d-40fc-b212-61c3d45c1bc3-22-1-c000.avro Parquet on S3 is currently the standard approach for building data lakes on AWS, and tools such as Delta Lake are leveraging this format to provide highly-scalable data platforms. Parquet is a columnar-oriented file format that is designed for efficient reads when only a subset of columns are being accessed for an operation, such as when using Spark SQL. Parquet is a native format for Spark, which means that PySpark has built-in functions for both reading and writing files in this format. An example of writing the stats dataframe as Parquet files and reading in the result as a new dataframe is shown in the snippet below. In this example, we haven’t set a partition key, but as with Avro, the dataframe will be split up into multiple files in order to support highly-performant read and write operations. When working with large-scale data sets, it’s useful to set partition keys for the file export using the repartition function. After this section, we’ll use Parquet as the primary file format when working with Spark. # parquet outparquet_path = "s3a://dsp-ch6/games-parquet/"avro_df.write.mode('overwrite').parquet(parquet_path)# parquet inparquet_df = sqlContext.read.parquet(parquet_path) ORC is a another columnar format that works well with Spark. The main benefit over Parquet is that it can support improved compression, at the cost of additional compute cost. I’m including it in this chapter, because some legacy systems still use this format. An example of writing the stats dataframe to ORC and reading the results back into a Spark dataframe is shown in the snippet below. Like the Avro format, the ORC write command will distribute the dataframe to multiple files based on the size. # orc outorc_path = "s3a://dsp-ch6/games-orc/"parquet_df.write.mode('overwrite').orc(orc_path)# orc inorc_df = sqlContext.read.orc(orc_path) To complete our round trip of file formats, we’ll write the results back to S3 in the CSV format. To make sure that we write a single file rather than a batch of files, we’ll use the coalesce command to collect the data to a single node before exporting it.This is a command that will fail with large data sets, and in general it’s best to avoid using the CSV format when using Spark. However, CSV files are still a common format for sharing data, so it’s useful to understand how to export to this format. # CSV outcsv_path = "s3a://dsp-ch6/games-csv-out/"orc_df.coalesce(1).write.mode('overwrite').format( "com.databricks.spark.csv").option("header","true").save(csv_path) # and CSV to finish the round trip csv_df = spark.read.csv(csv_path, header=True, inferSchema = True) The resulting dataframe is the same as the dataframe that we first read in from S3, but if the data types are not trivial to infer, then the CSV format can cause problems. When persisting data with PySpark, it’s best to use file formats that describe the schema of the data being persisted. While it’s best to work with Spark dataframes when authoring PySpark workloads, it’s often necessary to translate between different formats based on your use case. For example, you might need to perform a Pandas operation, such as selecting a specific element from a dataframe. When this is required, you can use the toPandas function to pull a Spark dataframe into the memory of the driver node. The code snippet below shows how to perform this task, display the results, and then convert the Pandas dataframe back to a Spark dataframe. In general, it’s best to avoid Pandas when authoring PySpark workflows, because it prevents distribution and scale, but it’s often the best way of expressing a command to execute. stats_pd = stats_df.toPandas()stats_df = sqlContext.createDataFrame(stats_pd) To bridge the gap between Pandas and Spark dataframes, Databricks introduced a new library called Koalas that resembles the Pandas API for Spark-backed dataframes. The result is that you can author Python code that works with Pandas commands that can scale to Spark-scale data sets. An example of converting a Spark dataframe to Koalas and back to Spark is shown in the following snippet. After converting the stats dataframe to Koalas, the snippet shows how to calculate the average time on ice as well as index into the Koalas frame. The intent of Koalas is to provide a Pandas interface to Spark dataframes, and as the Koalas library matures more Python modules may be able to take advantage of Spark. The output from the snippet shows that the average time on ice was 993 seconds per game. import databricks.koalas as ksstats_ks = stats_df.to_koalas()stats_df = stats_ks.to_spark()print(stats_ks['timeOnIce'].mean())print(stats_ks.iloc[:1, 1:2]) During the development of this book, Koalas is still preliminary and only partially implemented, but it looks to provide a familiar interface for Python coders. Both Pandas and Spark dataframes can work with Koalas, and the snippet below shows how to go from Spark to Koalas to Pandas to Spark, and Spark to Pandas to Koalas to Spark. # spark -> koalas -> pandas -> sparkdf = sqlContext.createDataFrame(stats_df.to_koalas().toPandas())# spark -> pandas -> koalas -> sparkdf = ks.from_pandas(stats_df.toPandas()).to_spark() In general, you’ll be working with Spark dataframes when authoring code in a PySpark environment. However, it’s useful to be able to work with different object types as necessary to build model workflows. Koalas and Pandas UDFs provide powerful tools for porting workloads to large-scale data ecosystems. The PySpark Dataframe API provides a variety of useful functions for aggregating, filtering, pivoting, and summarizing data. While some of this functionality maps well to Pandas operations, my recommendation for quickly getting up and running with munging data in PySpark is to use the SQL interface to dataframes in Spark called Spark SQL. If you’re already using the pandasql or framequery libraries, then Spark SQL should provide a familiar interface. If you’re new to these libraries, then the SQL interface still provides an approachable way of working with the Spark ecosystem. We’ll cover the Dataframe API later in this section, but first start with the SQL interface to get up and running. Exploratory data analysis (EDA) is one of the key steps in a data science workflow for understanding the shape of a data set. To work through this process in PySpark, we’ll load the stats data set into a dataframe, expose it as a view, and then calculate summary statistics. The snippet below shows how to load the NHL stats data set, expose it as a view to Spark, and then run a query against the dataframe. The aggregated dataframe is then visualized using the display command in Databricks. stats_df = spark.read.csv("s3://dsp-ch6/csv/game_skater_stats.csv", header=True, inferSchema = True)stats_df.createOrReplaceTempView("stats")new_df = spark.sql(""" select player_id, sum(1) as games, sum(goals) as goals from stats group by 1 order by 3 desc limit 5""")display(new_df) An output of this code block is shown in Figure 6.4. It shows the highest scoring players in the NHL dataset by ranking the results based on the total number of goals. One of the powerful features of Spark is that the SQL query will not operate against the dataframe until a result set is needed. This means that commands in a notebook can set up multiple data transformation steps for Spark dataframes, which are not performed until a later step needs to execute the graph of operations defined in a code block. Spark SQL is expressive, fast, and my go-to method for working with big data sets in a Spark environment. While prior Spark versions performed better with the Dataframe API versus Spark SQL, the difference in performance is now trivial and you should use the transformation tools that provide the best iteration speed for working with large data sets. With Spark SQL, you can join dataframes, run nested queries, set up temp tables, and mix expressive Spark operations with SQL operations. For example, if you want to look at the distribution of goals versus shots in the NHL stats data, you can run the following command on the dataframe. display(spark.sql(""" select cast(goals/shots * 50 as int)/50.0 as Goals_per_shot ,sum(1) as Players from ( select player_id, sum(shots) as shots, sum(goals) as goals from stats group by 1 having goals >= 5 ) group by 1 order by 1""")) This query restricts the ratio of goals to shots to players with more than 5 goals, to prevent outliers such as goalies scoring during power plays. We’ll use the display command to output the result set as a table and then use Databricks to display the output as a graph. Many Spark ecosystems have ways of visualizing results, and the Databricks environment provides this capability through the display command, which works well with both tabular and pivot table data. After running the above command, you can click on the chart icon and choose dimensions and measures which show the distribution of goals versus shots, as visualized in Figure 6.5. While I’m an advocate of using SQL to transform data, since it scales to different programming environments, it’s useful to get familiar with some of the basic dataframe operations in PySpark. The code snippet below shows how to perform common operations including dropping columns, selecting a subset of columns, and adding new columns to a Spark dataframe. Like prior commands, all of these operations are lazily performed. There are some syntax differences from Pandas, but the general commands used for transforming data sets should be familiar. from pyspark.sql.functions import lit# dropping columnscopy_df = stats_df.drop('game_id', 'player_id')# selection columns copy_df = copy_df.select('assists', 'goals', 'shots')# adding columnscopy_df = copy_df.withColumn("league", lit('NHL'))display(copy_df) One of the common operations to perform between dataframes is a join. This is easy to express in a Spark SQL query, but sometimes it is preferable to do this programmatically with the Dataframe API. The code snippet below shows how to join two dataframes together, when joining on the game_id and player_id fields. The league column which is a literal will be joined with the rest of the stats dataframe. This is a trivial example where we are adding a new column onto a small dataframe, but the join operation from the Dataframe API can scale to massive data sets. copy_df = stats_df.select('game_id', 'player_id'). withColumn("league", lit('NHL'))df = copy_df.join(stats_df, ['game_id', 'player_id'])display(df) The result set from the join operation above is shown in Figure 6.6. Spark supports a variety of different join types, and in this example we used an inner join to append league the league column to the stats dataframe. It’s also possible to perform aggregation operations on a dataframe, such as calculating sums and averages of columns. An example of computing the average time on ice for players in the stats data set, and total number of goals scored is shown in the snippet below. The groupBy command uses the player_id as the column for collapsing the data set, and the agg command specifies the aggregations to perform. summary_df = stats_df.groupBy("player_id").agg( {'timeOnIce':'avg', 'goals':'sum'})display(summary_df) The snippet creates a dataframe with player_id, timeOnIce, and goals columns. We’ll again use the plotting functionality in Databricks to visualize the results, but this time select the scatter plot option. The resulting plot of goals versus time on ice is shown in Figure 6.7. We’ve worked through introductory examples to get up and running with dataframes in PySpark, focusing on operations that are useful for munging data prior to training machine learning models. These types of operations, in combination with reading and writing dataframes provides a useful set of skills for performing exploratory analysis on massive data sets. While PySpark provides a great deal of functionality for working with dataframes, it often lacks core functionality provided in Python libraries, such as curve-fitting functions in SciPy. While it’s possible to use the toPandas function to convert dataframes into the Pandas format for Python libraries, this approach breaks when using large data sets. Pandas UDFs are a newer feature in PySpark that help data scientists work around this problem, by distributing the Pandas conversion across the worker nodes in a Spark cluster. With a Pandas UDF, you define a group by operation to partition the data set into dataframes that are small enough to fit into the memory of worker nodes, and then author a function that takes in a Pandas dataframe as the input parameter and returns a transformed Pandas dataframe as the result. Behind the scenes, PySpark uses the PyArrow library to efficiently translate dataframes from Spark to Pandas and back from Pandas to Spark. This approach enables Python libraries, such as Keras, to be scaled up to a large cluster of machines. This section will walk through an example problem where we need to use an existing Python library and show how to translate the workflow into a scalable solution using Pandas UDFs. The question we are looking to answer is understanding if there is a positive or negative relationship between the shots and hits attributes in the stats data set. To calculate this relationship, we can use the leastsq function in SciPy, as shown in the snippet below. This example creates a Pandas dataframe for a single player_id, and then fits a simple linear regression between these attributes. The output is the coefficients used to fit the least-squares operation, and in this case the number of shots was not strongly correlated with the number of hits. sample_pd = spark.sql(""" select * from stats where player_id = 8471214""").toPandas()# Import python libraries from scipy.optimize import leastsqimport numpy as np# Define a function to fitdef fit(params, x, y): return (y - (params[0] + x * params[1] )) # Fit the curve and show the results result = leastsq(fit, [1,0], args=(sample_pd.shots,sample_pd.hits))print(result) Now we want to perform this operation for every player in the stats data set. To scale to this volume, we’ll first partition by player_id, as shown by the groupBy operation in the code snippet below. Next, We’ll run the analyze_player function for each of these partitioned data sets using the apply command. While the stats_df dataframe used as input to this operation and the players_df dataframe returned are Spark dataframes, the sampled_pd dataframe and the dataframe returned by the analyze player function are Pandas. The Pandas UDF annotation provides a hint to PySpark for how to distribute this workload so that it can scale the operation across the cluster of worker nodes rather than eagerly pulling all of the data to the driver node. Like most Spark operations, Pandas UDFs are lazily evaluated and will not be executed until and output value is needed. Our initial example now translated to use Pandas UDFs is shown below. After defining additional modules to include, we specify the schema of the dataframe that will be returned from the operation. The schema object defines the structure of the Spark dataframe that will return from applying the analyze player function. The next step in the code block lists an annotation that defines this function as a grouped map operation, which means that it works on dataframes rather than scalar values. As before, we’ll use the leastsq function to fit the shots and hits attributes. After calculating the coefficients for this curve fitting, we create a new Pandas dataframe with the player id, and regression coefficients. The display command at the end of this code block will force the Pandas UDF to execute, which will create a partition for each of the players in the data set, apply the least squares operation, and merge the results back together into a large Spark dataframe. # Load necessary librariesfrom pyspark.sql.functions import pandas_udf, PandasUDFTypefrom pyspark.sql.types import *import pandas as pd# Create the schema for the resulting data frameschema = StructType([StructField('ID', LongType(), True), StructField('p0', DoubleType(), True), StructField('p1', DoubleType(), True)])# Define the UDF, input and outputs are Pandas DFs@pandas_udf(schema, PandasUDFType.GROUPED_MAP)def analize_player(sample_pd): # return empty params in not enough data if (len(sample_pd.shots) <= 1): return pd.DataFrame({'ID': [sample_pd.player_id[0]], 'p0': [ 0 ], 'p1': [ 0 ]}) # Perform curve fitting result = leastsq(fit, [1, 0], args=(sample_pd.shots, sample_pd.hits)) # Return the parameters as a Pandas DF return pd.DataFrame({'ID': [sample_pd.player_id[0]], 'p0': [result[0][0]], 'p1': [result[0][1]]}) # perform the UDF and show the results player_df = stats_df.groupby('player_id').apply(analyze_player)display(player_df) The key capability that Pandas UDFs provide is that they enable Python libraries to be used in a distributed environment, as long as you have a good way of partitioning your data. This means that libraries such as Featuretools, which were not initially designed to work in a distributed environment, can be scaled up to a large cluster. The result of applying the Pandas UDF from above on the stats data set is shown in Figure 6.8. This feature enables a mostly seamless translation between different dataframe formats. To further demonstrate the value of Pandas UDFs, we’ll apply them to distributing a feature generation pipeline and a deep learning pipeline. However, there are some issues when using Pandas UDFs in workflows, because they can make debugging more of a challenge and sometimes fail due to data type mismatches between Spark and Pandas. While PySpark provides a familiar environment for Python programmers, it’s good to follow a few best practices to make sure you are using Spark efficiently. Here are a set of recommendations I’ve compiled based on my experience porting a few projections from Python to PySpark: Avoid dictionaries: Using Python data types such as dictionaries means that the code might not be executable in a distributed mode. Instead of using keys to index values in a dictionary, consider adding another column to a dataframe that can be used as a filter. This recommendation applies to other Python types including lists that are not distributable in PySpark. Limit Pandas usage: Calling toPandas will cause all data to be loaded into memory on the driver node, and prevents operations from being performed in a distributed mode. It’s fine to use this function when data has already been aggregated and you want to make use of familiar Python plotting tools, but it should not be used for large dataframes. Avoid loops: Instead of using for loops, it’s often possible to use functional approaches such as group by and apply to achieve the same result. Using this pattern means that code can be parallelized by supported execution environments. I’ve noticed that focusing on using this pattern in Python has also resulted in cleaning code that is easier to translate to PySpark. Minimize eager operations: In order for your pipeline to be as scalable as possible, it’s good to avoid eager operations that pull full dataframes into memory. For example, reading in CSVs is an eager operation, and my work around is to stage the dataframe to S3 as Parquet before using it in later pipeline steps. Use SQL: There are libraries that provide SQL operations against dataframes in both Python and PySpark. If you’re working with someone else’s Python code, it can be tricky to decipher what some of the Pandas operations are achieving. If you plan on porting your code from Python to PySpark, then using a SQL library for Pandas can make this translation easier. By following these best practices when writing PySpark code, I’ve been able to improve both my Python and PySpark data science workflows. Now that we’ve covered loading and transforming data with PySpark, we can now use the machine learning libraries in PySpark to build a predictive model. The core library for building predictive models in PySpark is called MLlib. This library provides a suite of supervised and unsupervised algorithms. While this library does not have complete coverage of all of the algorithms in sklearn, it provides functionality for the majority of the types of operations needed for data science workflows. In this chapter, we’ll show how to apply MLlib to a classification problem and save the outputs from the model application to a data lake. games_df = spark.read.csv("s3://dsp-ch6/csv/games-expand.csv", header=True, inferSchema = True)games_df.createOrReplaceTempView("games_df")games_df = spark.sql(""" select *, row_number() over (order by rand()) as user_id ,case when rand() > 0.7 then 1 else 0 end as test from games_df""") The first step in the pipeline is loading the data set that we want to use for model training. The snippet above shows how to load the games data set, and append two additional attributes to the loaded dataframe using Spark SQL. The result of running this query is that about 30% of users will be assigned a test label which we’ll use for model application, and each record is assigned a unique user ID which we’ll use when saving the model predictions. The next step is splitting up the data set into train and test dataframes. For this pipeline, we’ll use the test dataframe as the data set for model application, where we predict user behavior. An example of splitting up the dataframes using the test column is shown in the snippet below. This should result in roughly 16.1k training users and 6.8k test users. trainDF = games_df.filter("test == 0")testDF = games_df.filter("test == 1")print("Train " + str(trainDF.count()))print("Test " + str(testDF.count())) MLlib requires that the input data is formatted using vector data types in Spark. To transform our dataframe into this format, we can use the VectorAssembler class to combine a range of columns into a single vector column. The code snippet below shows how to use this class to merge the first 10 columns in the dataframe into a new vector column called features. After applying this command to the training dataframe using the transform function, we use the select function to only retrieve the values we need from the dataframe for model training and application. For the training dataframe, we only need the label and features, and with the test dataframe we also select the user ID. from pyspark.ml.feature import VectorAssembler# create a vector representationassembler = VectorAssembler( inputCols= trainDF.schema.names[0:10], outputCol="features" )trainVec = assembler.transform(trainDF).select('label', 'features')testVec = assembler.transform(testDF).select( 'label', 'features', 'user_id')display(testVec) The display command shows the result of transforming our test dataset into vector types usable by MLlib. The output dataframe is visualized in Figure 6.9. Now that we have prepared our training and test data sets, we can use the logistic regression algorithm provided by MLlib to fit the training dataframe. We first create a logistic regression object and define the columns to use as labels and features. Next, we use the fit function to train the model on the training data set. In the last step in the snippet below, we use the transform function to apply the model to our test data set. from pyspark.ml.classification import LogisticRegression# specify the columns for the modellr = LogisticRegression(featuresCol='features', labelCol='label')# fit on training datamodel = lr.fit(trainVec)# predict on test data predDF = model.transform(testVec) The resulting dataframe now has a probability column, as shown in Figure 6.10. This column is a 2-element array with the probabilities for class 0 and 1. To test the accuracy of the logistic regression model on the test data set, we can use the binary classification evaluator in Mlib to calculate the ROC metric, as shown in the snippet below. For my run of the model, the ROC metric has a value of 0.761. from pyspark.ml.evaluation import BinaryClassificationEvaluatorroc = BinaryClassificationEvaluator().evaluate(predDF)print(roc) In a production pipeline, there will not be labels for the users that need predictions, meaning that you’ll need to perform cross validation to select the best model for making predictions. An example of this approach is covered in Section 6.7. In this case, we are using a single data set to keep code examples short, but a similar pipeline can be used in a production workflows. Now that we have the model predictions for our test users, we need to retrieve the predicted label in order to create a dataframe to persist to a data lake. Since the probability column created by MLlib is an array, we’ll need to define a UDF that retrieves the second element as our propensity column, as shown in the snippet below. from pyspark.sql.functions import udffrom pyspark.sql.types import FloatType# split out the array into a column secondElement = udf(lambda v:float(v[1]),FloatType())predDF = predDF.select("*", secondElement("probability").alias("propensity"))display(predDF) After running this code block, the dataframe will have an additional column called propensity as shown in Figure 6.10. The final step in this batch prediction pipeline is to save the results to S3. We’ll use the select function to retrieve the relevant columns from the predictions dataframe, and then use the write function on the dataframe to persist the results as Parquet on S3. # save results to S3results_df = predDF.select("user_id", "propensity")results_path = "s3a://dsp-ch6/game-predictions/"results_df.write.mode('overwrite').parquet(results_path) We now have all of the building blocks needed to create a PySpark pipeline that can fetch data from a storage layer, train a predictive model, and write the results to persistent storage. We’ll cover how to schedule this type of pipeline in Section 6.8. When developing models, it’s useful to inspect the output to see if the distribution of model predictions matches expectations. We can use Spark SQL to perform an aggregation on the model outputs and then use the display command to perform this process directly in Databricks, as shown in the snippet below. The result of performing these steps on the model predictions is shown in Figure 6.11. # plot the predictions predDF .createOrReplaceTempView("predDF ")plotDF = spark.sql(""" select cast(propensity*100 as int)/100 as propensity, label, sum(1) as users from predDF group by 1, 2 order by 1, 2 """)# table outputdisplay(plotDF) MLlib can be applied to a wide variety of problems using a large suite of algorithms. While we explored logistic regression in this section, the libraries provides a number of different classification approaches, and there are other types of operations supported including regression and clustering. While MLlib provides scalable implementations for classic machine learning algorithms, it does not natively support deep learning libraries such as Tensorflow and PyTorch. There are libraries that parallelize the training of deep learning models on Spark, but the data set needs to be able to fit in memory on each worker node, and these approaches are best used for distributed hyperparameter tuning on medium-sized data sets. For the model application stage, where we already have a deep learning model trained but need to apply the resulting model to a large user base, we can use Pandas UDFs. With Pandas UDFs, we can partition and distribute our data set, run the resulting dataframes against a Keras model, and then compile the results back into a single large Spark dataframe. This section will show how we can take the Keras model that we built in Section 1.6.3, and scale it to larger data sets using PySpark and Pandas UDFs. However, we still have the requirement that the data used for training the model can fit into memory on the driver node. We’ll use the same data sets from the prior section, where we split the games data set into training and test sets of users. This is a relatively small data set, so we can use the toPandas operation to load the dataframe onto the driver node, as shown in the snippet below. The result is a dataframe and list that we can provide as input to train a Keras deep learning model. # build model on the driver node train_pd = trainDF.toPandas()x_train = train_pd.iloc[:,0:10]y_train = train_pd['label'] When using PyPI to install TensorFlow on the Spark cluster, the installed version of the library should be 2.0 or greater. This differs from Version 1 of TensorFlow, which we used in prior chapters. The main impact in terms of the code snippets is that Tensorflow 2 now has a built-in AUC function that no longer requires the workflow we previously applied. We’ll use the same approach as before to train a Keras model. The code snippet below shows how to set up a network with an input layer, dropout later, single hidden layer, and an output layer, optimized with rmsprop and a cross entropy loss. In the model application phase, we’ll reuse the model object in a Pandas UDFs to distribute the workload. import tensorflow as tfimport kerasfrom keras import models, layersmodel = models.Sequential()model.add(layers.Dense(64, activation='relu', input_shape=(10,)))model.add(layers.Dropout(0.1))model.add(layers.Dense(64, activation='relu'))model.add(layers.Dense(1, activation='sigmoid'))model.compile(optimizer='rmsprop', loss='binary_crossentropy')history = model.fit(x_train, y_train, epochs=100, batch_size=100, validation_split = .2, verbose=0) To test for overfitting, we can plot the results of the training and validation data sets, as shown in Figure 6.12. The snippet below shows how to use matplotlib to display the losses over time for these data sets. While the training loss continued to decrease over additional epochs, the validation loss stopped improving after 20 epochs, but did not noticeably increase over time. import matplotlib.pyplot as pltloss = history.history['loss']val_loss = history.history['val_loss']epochs = range(1, len(loss) + 1)fig = plt.figure(figsize=(10,6) )plt.plot(epochs, loss, 'bo', label='Training Loss')plt.plot(epochs, val_loss, 'b', label='Validation Loss')plt.legend()plt.show()display(fig) Now that we have a trained deep learning model, we can use PySpark to apply it in a scalable pipeline. The first step is determining how to partition the set of users that need to be scored. For this data set, we can assign the user base into 100 different buckets, as shown in the snippet below. This randomly assigns each user into 1 of 100 buckets, which means that after applying the group by step, each dataframe that gets translated to Pandas will be roughly 1% the size of the original dataframe. If you have a large data set, you may need to use thousands of buckets to distribute the data set, and maybe more. # set up partitioning for the train data frametestDF.createOrReplaceTempView("testDF ")partitionedDF = spark.sql(""" select *, cast(rand()*100 as int) as partition_id from testDF """) The next step is to define the Pandas UDF that will apply the Keras model. We’ll define an output schema of a user ID and propensity score, as shown below. The UDF uses the predict function on the model object we previously trained to create a prediction column on the passed in dataframe. The return command selects the two relevant columns that we defined for the schema object. The group by command partitions the data set using our bucketing approach, and the apply command performs the Keras model application across the cluster of worker nodes. The result is a Spark dataframe visualized with the display command, as shown in Figure 6.13. from pyspark.sql.functions import pandas_udf, PandasUDFTypefrom pyspark.sql.types import *schema = StructType([StructField('user_id', LongType(), True), StructField('propensity', DoubleType(),True)])@pandas_udf(schema, PandasUDFType.GROUPED_MAP)def apply_keras(pd): pd['propensity'] = model.predict(pd.iloc[:,0:10]) return pd[['user_id', 'propensity']]results_df=partitionedDF.groupby('partition_id').apply(apply_keras)display(results_df) One thing to note is that there are limitations on the types of objects that you can reference in a Pandas UDFs. In this example, we referenced the model object, which was created on the driver node when training the model. When variables in PySpark are transferred from the driver node to workers nodes for distributed operations, a copy of the variable is made, because synchronizing variables across a cluster would be inefficient. This means that any changes made to a variable within a Pandas UDF will not apply to the original object. It’s also why data types such as Python lists and dictionaries should be avoided when using UDFs. Functions work in a similar way, in Section 6.3.4 we used the fit function in a Pandas UDF where the function was initially defined on the driver node. Spark also provides broadcast variables for sharing variables in a cluster, but ideally distributed code segments should avoid sharing state through variables if possible. Feature engineering is a key step in a data science workflow, and sometimes it is necessary to use Python libraries to implement this functionality. For example, the AutoModel system at Zynga uses the Featuretools library to generate hundreds of features from raw tracking events, which are then used as input to classification models. To scale up the automated feature engineering approach that we first explored in Section 1.7, we can use Pandas UDFs to distribute the feature application process. Like the prior section, we need to sample data when determining the transformation to perform, but when applying the transformation we can scale to massive data sets. For this section, we’ll use the game plays data set from the NHL Kaggle example, which includes detailed play-by-play descriptions of the events that occurred during each match. Our goal is to transform the deep and narrow dataframe into a shallow and wide dataframe that summarizes each game as a single record with hundreds of columns. An example of loading this data in PySpark and selecting the relevant columns is shown in the snippet below. Before calling toPandas, we use the filter function to sample 0.3% of the records, and then cast the result to a Pandas frame, which has a shape of 10,717 rows and 16 columns. plays_df = spark.read.csv("s3://dsp-ch6/csv/game_plays.csv", header=True, inferSchema = True).drop( 'secondaryType', 'periodType', 'dateTime', 'rink_side')plays_pd = plays_df.filter("rand() < 0.003").toPandas()plays_pd.shape We’ll use the same two-step process covered in Section 1.7 where we first one-hot encode the categorical features in the dataframe, and then apply deep feature synthesis to the data set. The code snippet below shows how to perform the encoding process using the Featuretools library. The output is a transformation of the initial dataframe that now has 20 dummy variables instead of the event and description variables. import featuretools as ftfrom featuretools import Featurees = ft.EntitySet(id="plays")es = es.entity_from_dataframe(entity_id="plays",dataframe=plays_pd, index="play_id", variable_types = { "event": ft.variable_types.Categorical, "description": ft.variable_types.Categorical })f1 = Feature(es["plays"]["event"])f2 = Feature(es["plays"]["description"])encoded, defs = ft.encode_features(plays_pd, [f1, f2], top_n=10)encoded.reset_index(inplace=True) The next step is using the dfs function to perform deep feature synthesis on our encoded dataframe. The input dataframe will have a record per play, while the output dataframe will have a single record per game after collapsing the detailed events into a wide column representation using a variety of different aggregations. es = ft.EntitySet(id="plays")es = es.entity_from_dataframe(entity_id="plays", dataframe=encoded, index="play_id")es = es.normalize_entity(base_entity_id="plays", new_entity_id="games", index="game_id")features, transform=ft.dfs(entityset=es, target_entity="games",max_depth=2)features.reset_index(inplace=True) One of the new steps that we need to perform versus the prior approach, is that we need to determine what the schema will be for the generated features, since this is needed as an input to the Pandas UDF annotation. To figure out what the generated schema is for the generated dataframe, we can create a Spark dataframe and then retrieve the schema from the Spark dataframe. Before converting the Pandas dataframe, we need to modify the column names in the generated dataframe to remove special characters, as shown in the snippet below. The resulting Spark schema for the feature application step is displayed in Figure 6.14. features.columns = features.columns.str.replace("[(). =]", "")schema = sqlContext.createDataFrame(features).schemafeatures.columns We now have the required schema for defining a Pandas UDF. Unlike the past UDFs we defined, the schema may change between different runs based on the feature transformation aggregations selected by Featuretools. In these steps, we also created a defs object that defines the feature transformations to use for encoding and a transform object that defines the transformations to perform deep feature synthesis. Like the model object in the past section, copies of these objects will be passed to the Pandas UDF executing on worker nodes. To enable our approach to scale across a cluster of worker nodes, we need to define a column to use for partitioning. Like the prior section, we can bucket events into different sets of data to ensure that the UDF process can scale. One difference from before is that we need all of the plays from a specific game to be grouped into the same partition. To achieve this result, we can partition by the game_id rather than the player_id. An example of this approach in shown in the code snippet below. Additionally, we can use the hash function on the game ID to randomize the value, resulting in more balanced buckets. # bucket IDs plays_df.createOrReplaceTempView("plays_df")plays_df = spark.sql(""" select *, abs(hash(game_id))%1000 as partition_id from plays_df """) We can now apply feature transformation to the full data set, using the Pandas UDF defined below. The plays dataframe is partitioned by the bucket before being passed to the generate features function. This function uses the previously generated feature transformations to ensure that the same transformation is applied across all of the worker nodes. The input Pandas dataframe is a narrow and deep representation of play data, while the returned dataframe is a shallow and wide representation of game summaries. from pyspark.sql.functions import pandas_udf, PandasUDFType@pandas_udf(schema, PandasUDFType.GROUPED_MAP)def gen_features(plays_pd): es = ft.EntitySet(id="plays") es = es.entity_from_dataframe(entity_id="plays", dataframe=plays_pd, index="play_id", variable_types = { "event": ft.variable_types.Categorical, "description": ft.variable_types.Categorical }) encoded_features = ft.calculate_feature_matrix(defs, es) encoded_features.reset_index(inplace=True) es = ft.EntitySet(id="plays") es = es.entity_from_dataframe(entity_id="plays", dataframe=encoded, index="play_id") es = es.normalize_entity(base_entity_id="plays", new_entity_id="games", index="game_id") generated = ft.calculate_feature_matrix(transform,es).fillna(0) generated.reset_index(inplace=True) generated.columns = generated.columns.str.replace("[(). =]","") return generated features_df = plays_df.groupby('partition_id').apply(gen_features)display(features_df) The output of the display command is shown in Figure 6.15. We’ve now worked through feature generation and deep learning in scalable model pipelines. Now that we have a transformed data set, we can join the result with additional features, such as the label that we are looking to predict, and develop a complete model pipeline. A common workflow for batch model pipelines is reading input data from a lake, applying a machine learning model, and then writing the results to an application database. In GCP, BigQuery serves as the data lake and Cloud Bigtable can serve as an application database. We’ll build and end-to-end pipeline with these components in the next chapter, but for now we’ll get hands on with a subset of the GCP components directly in Spark. While there is a Spark connector for BigQuery [15], enabling large-scale PySpark pipelines to be built using BigQuery directly, there are some issues with this library that make it quite complicated to set up for our Databricks environment. For example, we would need to rebuild some of the JAR files and shade the dependencies. One alternative is to use the Python BigQuey connector that we explored in Section 5.1, but this approach is not distributed and will eagerly pull the query results to the driver node as a Pandas dataframe. For this chapter, we’ll explore a workflow where we unload query results to Cloud Storage, and then read in the data set from GCS as the initial step in the pipeline. Similarly, for model output we’ll save the results to GCS, where the output is available for pushing to Bigtable. To productize this type of workflow, Airflow could be used to chain these different actions together. The first step we’ll perform is exporting the results of a BigQuery query to GCS, which can be performed manually using the BigQuery UI. This is possible to perform directly in Spark, but as I mentioned the setup is quite involved to configure with the current version of the connector library. We’ll use the natality data set for this pipeline, which lists attributes about a child delivery, such as birth weight. create table dsp_demo.natality as ( select * from `bigquery-public-data.samples.natality` order by rand() limit 10000 ) To create a data set, we’ll sample 10k records from the natality public data set in BigQuery. To export this result set to GCS, we need to create a table on BigQuery with the data that we want to export. The SQL for creating this data sample is shown in the snippet above. To export this data to GCS, perform the following steps: Browse to the GCP ConsoleSearch for “BigQuery”Paste the Query from the snippet above into the query editorClick RunIn the left navigation pane, select the new table, “dsp_demo.natality”Click “Export”, and then “Export to GCS”Set the location, “/dsp_model_store/natality/avro”Use “Avro” as export formatClick “Export” Browse to the GCP Console Search for “BigQuery” Paste the Query from the snippet above into the query editor Click Run In the left navigation pane, select the new table, “dsp_demo.natality” Click “Export”, and then “Export to GCS” Set the location, “/dsp_model_store/natality/avro” Use “Avro” as export format Click “Export” After performing these steps, the sampled natality data will be saved to GCS in Avro format. The confirmation dialog from exporting the data set is shown in Figure 6.16. We now have the data saved to GCS in a format that works well with Spark. We now have a data set that we can use as input to a PySpark pipeline, but we don’t yet have access to the bucket on GCS from our Spark environment. With AWS, we were able to set up programmatic access to S3 using an access and secret key. With GCP, the process is a bit more complicated because we need to move the json credentials file to the driver node of the cluster in order to read and write files on GCS. One of the challenges with using Spark is that you may not have SSH access to the driver node, which means that we’ll need to use persistent storage to move the file to the driver machine. This isn’t recommended for production environments, but instead is being shown as a proof of concept. The best practice for managing credentials in a production environment is to use IAM roles. aws s3 cp dsdemo.json s3://dsp-ch6/secrets/dsdemo.jsonaws s3 ls s3://dsp-ch6/secrets/ To move the json file to the driver node, we can first copy the credentials file to S3, as shown in the snippet above. Now we can switch back to Databricks and author the model pipeline. To copy the file to the driver node, we can read in the file using the sc Spark context to read the file line by line. This is different from all of our prior operations where we have read in data sets as dataframes. After reading the file, we then create a file on the driver node using the Python open and write functions. Again, this is an unusual action to perform in Spark, because you typically want to write to persistent storage rather than local storage. The result of performing these steps is that the credentials file will now be available locally on the driver node in the cluster. creds_file = '/databricks/creds.json'creds = sc.textFile('s3://dsp-ch6/secrets/dsdemo.json')with open(creds_file, 'w') as file: for line in creds.take(100): file.write(line + "\n") Now that we have the json credentials file moved to the driver local storage, we can set up the Hadoop configuration needed to access data on GCS. The code snippet below shows how to configure the project ID, file system implementation, and credentials file location. After running these commands, we now have access to read and write files on GCS. sc._jsc.hadoopConfiguration().set("fs.gs.impl", "com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem")sc._jsc.hadoopConfiguration().set("fs.gs.project.id", "your_project_id")sc._jsc.hadoopConfiguration().set( "mapred.bq.auth.service.account.json.keyfile", creds_file)sc._jsc.hadoopConfiguration().set( "fs.gs.auth.service.account.json.keyfile", creds_file) To read in the natality data set, we can use the read function with the Avro setting to fetch the data set. Since we are using the Avro format, the dataframe will be lazily loaded and the data is not retrieved until the display command is used to sample the data set, as shown in the snippet below. natality_path = "gs://dsp_model_store/natality/avro"natality_df = spark.read.format("avro").load(natality_path)display(natality_df) Before we can use MLlib to build a regression model, we need to perform a few transformations on the data set to select a subset of the features, cast data types, and split records into training and test groups. We’ll also use the fillna function as shown below in order to replace any null values in the dataframe with zeros. For this modeling exercise, we’ll build a regression model that predicts the birth weight of a baby using a few different features including the marriage status of the mother and parent ages. The prepared dataframe is shown in Figure 6.17. natality_df.createOrReplaceTempView("natality_df")natality_df = spark.sql("""SELECT year, plurality, apgar_5min, mother_age, father_age, gestation_weeks, ever_born ,case when mother_married = true then 1 else 0 end as mother_married ,weight_pounds as weight ,case when rand() < 0.5 then 1 else 0 end as testfrom natality_df """).fillna(0)trainDF = natality_df.filter("test == 0")testDF = natality_df.filter("test == 1")display(natality_df) Next, we’ll translate our dataframe into the vector data types that MLlib requires as input. The process for transforming the natality data set is shown in the snippet below. After executing the transform function, we now have training and test data sets we can use as input to a regression model. The label we are building a model to predict is the weight column. from pyspark.ml.feature import VectorAssembler# create a vector representationassembler = VectorAssembler(inputCols= trainDF.schema.names[0:8], outputCol="features" )trainVec = assembler.transform(trainDF).select('weight','features')testVec = assembler.transform(testDF).select('weight', 'features') MLlib provides a set of utilities for performing cross validation and hyperparameter tuning in a model workflow. The code snippet below shows how to perform this process for a random forest regression model. Instead of calling fit directly on the model object, we wrap the model object with a cross validator object that explores different parameter settings, such as tree depth and number of trees. This workflow is similar to the grid search functions in sklearn. After searching through the parameter space, and using cross validation based on the number of folds, the random forest model is retrained on the complete training data set before being applied to make predictions on the test data set. The result is a dataframe with the actual weight and predicted birth weight. from pyspark.ml.tuning import ParamGridBuilder from pyspark.ml.regression import RandomForestRegressorfrom pyspark.ml.tuning import CrossValidatorfrom pyspark.ml.evaluation import RegressionEvaluatorfolds = 3rf_trees = [ 50, 100 ]rf_depth = [ 4, 5 ] rf= RandomForestRegressor(featuresCol='features',labelCol='weight')paramGrid = ParamGridBuilder().addGrid(rf.numTrees, rf_trees). ddGrid(rf.maxDepth, rf_depth).build()crossval = CrossValidator(estimator=rf, estimatorParamMaps = paramGrid, evaluator=RegressionEvaluator( labelCol='weight'), numFolds = folds) rfModel = crossval.fit(trainVec) predsDF = rfModel.transform(testVec).select("weight", "prediction") In the final step of our GCP model pipeline, we’ll save the results to GCS, so that other applications or processes in a workflow can make use of the predictions. The code snippet below shows how to write the dataframe to GCS in Avro format. To ensure that different runs of the pipeline do not overwrite past predictions, we append a timestamp to the export path. import timeout_path = "gs://dsp_model_store/natality/preds-{time}/". format(time = int(time.time()*1000))predsDF.write.mode('overwrite').format("avro").save(out_path)print(out_path) Using GCP components with PySpark took a bit of effort to configure, but in this case we are running Spark in a different cloud provider than where we are reading and writing data. In a production environment, you’ll most likely be running Spark in the same cloud as where you are working with data sets, which means that you can leverage IAM roles for properly managing access to different services. Once you’ve tested a batch model pipeline in a notebook environment, there are a few different ways of scheduling the pipeline to run on a regular schedule. For example, you may want a churn prediction model for a mobile game to run every morning and publish the scores to an application database. Similar to the workflow tools we covered in Chapter 5, a PySpark pipeline should have monitoring in place for any failures that may occur. There’s a few different approaches for scheduling PySpark jobs to run: Workflow Tools: Airflow, Azkaban, and Luigi all support running spark jobs as part of a workflow. Cloud Tools: EMR on AWS and Dataproc on GCP support scheduled Spark jobs. Vendor Tools: Databricks supports setting up job schedules with monitoring through the web UI. Spark Submit: If you already have a cluster provisioned, use can issue spark-submit commands using a tool such as crontab. Vendor and cloud tools are typically easier to get up and running, because they provide options for provisioning clusters as part of the workflow. For example, with Databricks you can define the type of cluster to spin up for running a notebook on a schedule. When using a workflow tool, such as Airflow, you’ll need to add additional steps to your workflow in order to spin up and terminate clusters. Most workflow tools provide connectors to EMR for managing clusters as part of a workflow. The Spark submit option is useful when first getting started with scheduling Spark jobs, but it’s doesn’t support managing clusters as part of a workflow. Spark jobs can run on ephemeral or persistent clusters. An ephemeral cluster is a Spark cluster that is provisioned to perform a set of tasks and then terminated, such as running a churn model pipeline. A persistent cluster is a long-running cluster than may support interactive notebooks, such as the Databricks cluster we set up at the start of this chapter. Persistent clusters are useful for development, but can be expensive if the hardware spun up for the cluster is under utilized. Some vendors support auto scaling of clusters to reduce the costs of long-running persistent clusters. Ephemeral clusters are useful, because spinning up a new cluster to perform a task enables isolation of failure across tasks, and it means that different model pipelines can use different library versions. In addition to setting up tools for scheduling jobs and alerting on job failures, it’s useful to set up additional data and model quality checks for Spark model pipelines. For example, I’ve set up Spark jobs that perform audit tasks, such as making sure that an application database has predictions for the current day, and trigger alerts if prediction data is stale. It’s also a good practice to log metrics, such as the ROC of a cross-validated model, as part of a Spark pipeline. We’ll cover this in more detail in Chapter 11. PySpark is a powerful tool for data scientists to build scalable analyses and model pipelines. It a highly desirable skill set for companies, because it enables data science teams to own more of the process of building and owning data products. There’s a variety of ways to set up an environment for PySpark, and in this chapter we explored a free notebook environment from one of the popular Spark vendors. This chapter focused on batch model pipelines, where the goal is to create a set of predictions for a large number of users on a regular schedule. We explored pipelines for both AWS and GCP deployments, where the data sources and data outputs are data lakes. One of the issues with these types of pipelines is that predictions may be quite stale by the time that a prediction is used. In Chapter 9, we’ll explore streaming pipelines for PySpark, where the latency of model predictions is minimized. PySpark is a highly expressive language for authoring model pipelines, because it supports all Python functionality, but does require some workarounds to get code to execute across a cluster of workers nodes. In the next chapter, we’ll explore Dataflow, a runtime for the Apache Beam library, which also enables large-scale distributed Python pipelines, but is more constrained in the types of operations that you can perform. Karau, Holden, Andy Konwinski, Patrick Wendell, and Matei Zaharia. 2015. Learning Spark: Lightning-Fast Big Data Analysis. 1st ed. O’Reilly Media. 13. https://community.cloud.databricks.com/↩︎14. https://www.gamasutra.com/blogs/BenWeber/20190426/340293/↩︎15. https://github.com/spotify/spark-bigquery/↩︎ Ben Weber is a distinguished data scientist at Zynga. We are hiring!
[ { "code": null, "e": 801, "s": 171, "text": "Demonstrated experience in PySpark is one of the most desirable competencies that employers are looking for when building data science teams, because it enables these teams to own live data products. While I’ve previously blogged about PySpark, Parallelization, and UDFs, I wanted to provide a proper overview of this topic as a book chapter. I’m sharing this complete chapter, because I want to encourage the adoption of PySpark as a tool for data scientists. All code examples from this post are available here, and all prerequisites are covered in the sample chapters here. You might want to grab some snacks before diving in!" }, { "code": null, "e": 1513, "s": 801, "text": "Spark is a general-purpose computing framework that can scale to massive data volumes. It builds upon prior big data tools such as Hadoop and MapReduce, while providing significant improvements in the expressivity of the languages it supports. One of the core components of Spark is resilient distributed datasets (RDD), which enable clusters of machines to perform workloads in a coordinated, and fault-tolerant process. In more recent versions of Spark, the Dataframe API provides an abstraction on top of RDDs that resembles the same data structure in R and Pandas. PySpark is the Python interface to Spark, and it provides an API for working with large-scale datasets in a distributed computing environment." }, { "code": null, "e": 1961, "s": 1513, "text": "PySpark is an extremely valuable tool for data scientists, because it can streamline the process for translating prototype models into production-grade model workflows. At Zynga, our data science team owns a number of production-grade systems that provide useful signals to our game and marketing teams. By using PySpark, we’ve been able to reduce the amount of support we need from engineering teams to scale up models from concept to production." }, { "code": null, "e": 3072, "s": 1961, "text": "Up until now in this book, all of the models we’ve built and deployed have been targeted at single machines. While we are able to scale up model serving to multiple machines using Lambda, ECS, and GKS, these containers worked in isolation and there was no coordination among nodes in these environments. With PySpark, we can build model workflows that are designed to operate in cluster environments for both model training and model serving. The result is that data scientists can now tackle much larger-scale problems than previously possible using prior Python tools. PySpark provides a nice tradeoff between an expressive programming language and APIs to Spark versus more legacy options such as MapReduce. A general trend is that the use of Hadoop is dropping as more data science and engineering teams are switching to Spark ecosystems. In Chapter 7 we’ll explore another distributed computing ecosystem for data science called Cloud Dataflow, but for now Spark is the open-source leader in this space. PySpark was one of the main motivations for me to switch from R to Python for data science workflows." }, { "code": null, "e": 3851, "s": 3072, "text": "The goal of this chapter is to provide an introduction to PySpark for Python programmers that shows how to build large-scale model pipelines for batch scoring applications, where you may have billions of records and millions of users that need to be scored. While production-grade systems will typically push results to application databases, in this chapter we’ll focus on batch processes that pull in data from a lake and push results back to the data lake for other systems to use. We’ll explore pipelines that perform model applications for both AWS and GCP. While the data sets used in this Chapter rely on AWS and GCP for storage, the Spark environment does not have to run on either of these platforms and instead can run on Azure, other clouds, or on-pem Spark clusters." }, { "code": null, "e": 4552, "s": 3851, "text": "We’ll cover a variety of different topics in this chapter to show different use cases of PySpark for scalable model pipelines. After showing how to make data available to Spark on S3, we’ll cover some of the basics of PySpark focusing on Dataframe operations. Next, we’ll build out a predictive model pipeline that reads in data from S3, performs batch model predictions, and then writes the results to S3. We’ll follow this by showing off how a newer feature called Pandas UDFs can be used with PySpark to perform distributed deep learning and feature engineering. To conclude, we’ll build another batch model pipeline now using GCP and then discuss how to productize workflows in a Spark ecosystem." }, { "code": null, "e": 5019, "s": 4552, "text": "There’s a variety of ways to both configure Spark clusters and submit commands to a cluster for execution. When getting started with PySpark as a data scientist, my recommendation is to use a freely-available notebook environment for getting up and running with Spark as quick as possible. While PySpark may not perform quite as well as Java or Scala for large-scale workflows, the ease of development in an interactive programming environment is worth the tradeoff." }, { "code": null, "e": 5184, "s": 5019, "text": "Based on your organization, you may be starting from scratch for Spark or using an existing solution. Here are the types of Spark deployments I’ve seen in practice:" }, { "code": null, "e": 5285, "s": 5184, "text": "Self Hosted: An engineering team manages a set of clusters and provides console and notebook access." }, { "code": null, "e": 5377, "s": 5285, "text": "Cloud Solutions: AWS provides a managed Spark option called EMR and GCP has Cloud DataProc." }, { "code": null, "e": 5477, "s": 5377, "text": "Vendor Solutions: Databricks, Cloudera, and other vendors provide fully-managed Spark environments." }, { "code": null, "e": 6190, "s": 5477, "text": "There’s a number of different factors to consider when choosing a Spark ecosystem, including cost, scalability, and feature sets. As you scale the size of the team using Spark, additional considerations are whether an ecosystem supports multi-tenancy, where multiple jobs can run concurrently on the same cluster, and isolation where one job failing should not kill other jobs. Self-hosted solutions require significant engineering work to support these additional considerations, so many organizations use cloud or vendor solutions for Spark. In this book, we’ll use the Databricks Community Edition, which provides all of the baseline features needed for learning Spark in a collaborative notebook environment." }, { "code": null, "e": 6736, "s": 6190, "text": "Spark is a rapidly evolving ecosystem, and it’s difficult to author books about this subject that do not quickly become out of date as the platform evolves. Another issue is that many books target Scala rather than Python for the majority of coding examples. My advice for readers that want to dig deeper into the Spark ecosystem is to explore books based on the broader Spark ecosystem, such as (Karau et al. 2015). You’ll likely need to read through Scala or Java code examples, but the majority of content covered will be relevant to PySpark." }, { "code": null, "e": 7195, "s": 6736, "text": "A Spark environment is a cluster of machines with a single driver node and one or more worker nodes. The driver machine is the master node in the cluster and is responsible for coordinating the workloads to perform. In general, workloads will be distributed across the worker nodes when performing operations on Spark dataframe. However, when working with native Python objects, such as lists or dictionaries, objects will be instantiated on the driver node." }, { "code": null, "e": 7797, "s": 7195, "text": "Ideally, you want all of your workloads to be operating on worker nodes, so that the execution of the steps to perform is distributed across the cluster, and not bottlenecked by the driver node. However, there are some types of operations in PySpark where the driver has to perform all of the work. The most common situation where this happens is when using Pandas dataframes in your workloads. When you use toPandas or other commands to convert a data set to a Pandas object, all of the data is loaded into memory on the driver node, which can crash the driver node when working with large data sets." }, { "code": null, "e": 8583, "s": 7797, "text": "In PySpark, the majority of commands are lazily executed, meaning that an operation is not performed until an output is explicitly needed. For example, a join operation between two Spark dataframes will not immediately cause the join operation to be performed, which is how Pandas works. Instead, the join is performed once an output is added to the chain of operations to perform, such as displaying a sample of the resulting dataframe. One of the key differences between Pandas operations, where operations are eagerly performed and pulled into memory, is that PySpark operations are lazily performed and not pulled into memory until needed. One of the benefits of this approach is that the graph of operations to perform can be optimized before being sent to the cluster to execute." }, { "code": null, "e": 9296, "s": 8583, "text": "In general, nodes in a Spark cluster should be considered ephemeral, because a cluster can be resized during execution. Additionally, some vendors may spin up a new cluster when scheduling a job to run. This means that common operations in Python, such as saving files to disk, do not map directly to PySpark. Instead, using a distributed computing environment means that you need to use a persistent file store such as S3 when saving data. This is important for logging, because a worker node may crash and it may not be possible to ssh into the node for debugging. Most Spark deployments have a logging system set up to help with this issue, but it’s good practice to log workflow status to persistent storage." }, { "code": null, "e": 9607, "s": 9296, "text": "One of the quickest ways to get up and running with PySpark is to use a hosted notebook environment. Databricks is the largest Spark vendor and provides a free version for getting started called Community Edition [13]. We’ll use this environment to get started with Spark and build AWS and GCP model pipelines." }, { "code": null, "e": 9774, "s": 9607, "text": "The first step is to create a login on the Databricks website for the community edition. Next, perform the following steps to spin up a test cluster after logging in:" }, { "code": null, "e": 9926, "s": 9774, "text": "Click on “Clusters” on the left navigation barClick “Create Cluster”Assign a name, “DSP”Select the most recent runtime (non-beta)Click “Create Cluster”" }, { "code": null, "e": 9973, "s": 9926, "text": "Click on “Clusters” on the left navigation bar" }, { "code": null, "e": 9996, "s": 9973, "text": "Click “Create Cluster”" }, { "code": null, "e": 10017, "s": 9996, "text": "Assign a name, “DSP”" }, { "code": null, "e": 10059, "s": 10017, "text": "Select the most recent runtime (non-beta)" }, { "code": null, "e": 10082, "s": 10059, "text": "Click “Create Cluster”" }, { "code": null, "e": 10587, "s": 10082, "text": "After a few minutes we’ll have a cluster set up that we can use for submitting Spark commands. Before attaching a notebook to the cluster, we’ll first set up the libraries that we’ll use throughout this chapter. Instead of using pip to install libraries, we’ll use the Databricks UI, which makes sure that every node in the cluster has the same set of libraries installed. We’ll use both Maven and PyPI to install libraries on the clusters. To install the BigQuery connector, perform the following steps:" }, { "code": null, "e": 10800, "s": 10587, "text": "Click on “Clusters” on the left navigation barSelect the “DSP” clusterClick on the “Libraries” tabSelect “Install New”Click on the “Maven” tab.Set coordinates to com.spotify:spark-bigquery_2.11:0.2.2Click install" }, { "code": null, "e": 10847, "s": 10800, "text": "Click on “Clusters” on the left navigation bar" }, { "code": null, "e": 10872, "s": 10847, "text": "Select the “DSP” cluster" }, { "code": null, "e": 10901, "s": 10872, "text": "Click on the “Libraries” tab" }, { "code": null, "e": 10922, "s": 10901, "text": "Select “Install New”" }, { "code": null, "e": 10948, "s": 10922, "text": "Click on the “Maven” tab." }, { "code": null, "e": 11005, "s": 10948, "text": "Set coordinates to com.spotify:spark-bigquery_2.11:0.2.2" }, { "code": null, "e": 11019, "s": 11005, "text": "Click install" }, { "code": null, "e": 11384, "s": 11019, "text": "The UI will then show the status as resolving, and then installing, and then installed. We also need to attach a few Python libraries that are not pre-installed on a new Databricks cluster. Standard libraries such as Pandas are installed, but you might need to upgrade to a more recent version since the libraries pre-installed by Databricks can lag significantly." }, { "code": null, "e": 11717, "s": 11384, "text": "To install a Python library on Databricks, perform the same steps as before up to step 5. Next, instead of selecting “Maven” choose “PyPI”. Under Package, specify the package you want to install and then click “Install”. To follow along with all of the sections in this chapter, you’ll need to install the following Python packages:" }, { "code": null, "e": 11751, "s": 11717, "text": "koalas — for Dataframe conversion" }, { "code": null, "e": 11789, "s": 11751, "text": "featuretools — for feature generation" }, { "code": null, "e": 11830, "s": 11789, "text": "tensorflow — for a deep learning backend" }, { "code": null, "e": 11864, "s": 11830, "text": "keras — for a deep learning model" }, { "code": null, "e": 12301, "s": 11864, "text": "You’ll now have a cluster set up capable of performing distributed feature engineering and deep learning. We’ll start with basic Spark commands, show off newer functionality such as the Koalas library, and then dig into these more advanced topics. After set up, your cluster library setup should look like Figure 6.1. To ensure that everything is set up successfully, restart the cluster and check the status of the installed libraries." }, { "code": null, "e": 12500, "s": 12301, "text": "Now that we have provisioned a cluster and set up the required libraries, we can create a notebook to start submitting commands to the cluster. To create a new notebook, perform the following steps:" }, { "code": null, "e": 12683, "s": 12500, "text": "Click on “Databricks” on the left navigation barUnder “Common Tasks”, select “New Notebook”Assign a name “CH6”Select “Python” as the languageselect “DSP” as the clusterClick “Create”" }, { "code": null, "e": 12732, "s": 12683, "text": "Click on “Databricks” on the left navigation bar" }, { "code": null, "e": 12776, "s": 12732, "text": "Under “Common Tasks”, select “New Notebook”" }, { "code": null, "e": 12796, "s": 12776, "text": "Assign a name “CH6”" }, { "code": null, "e": 12828, "s": 12796, "text": "Select “Python” as the language" }, { "code": null, "e": 12856, "s": 12828, "text": "select “DSP” as the cluster" }, { "code": null, "e": 12871, "s": 12856, "text": "Click “Create”" }, { "code": null, "e": 13169, "s": 12871, "text": "The result will be a notebook environment where you can start running Python and PySpark commands, such as print(\"Hello World!\"). An example notebook running this command is shown in Figure 6.2. We now have a PySpark environment up and running that we can use to build distributed model pipelines." }, { "code": null, "e": 13684, "s": 13169, "text": "Data is essential for PySpark workflows. Spark supports a variety of methods for reading in data sets, including connecting to data lakes and data warehouses, as well as loading sample data sets from libraries, such as the Boston housing data set. Since the theme of this book is building scalable pipelines, we’ll focus on using data layers that work with distributed workflows. To get started with PySpark, we’ll stage input data for a modeling pipeline on S3, and then read in the data set as a Spark dataframe." }, { "code": null, "e": 13997, "s": 13684, "text": "This section will show how to stage data to S3, set up credentials for accessing the data from Spark, and fetching the data from S3 into a Spark dataframe. The first step is to set up a bucket on S3 for storing the data set we want to load. To perform this step, run the following operations on the command line." }, { "code": null, "e": 14066, "s": 13997, "text": "aws s3api create-bucket --bucket dsp-ch6 --region us-east-1aws s3 ls" }, { "code": null, "e": 14337, "s": 14066, "text": "After running the command to create a new bucket, we use the ls command to verify that the bucket has been successfully created. Next, we’ll download the games data set to the EC2 instance and then move the file to S3 using the cp command, as shown in the snippet below." }, { "code": null, "e": 14508, "s": 14337, "text": "wget https://github.com/bgweber/Twitch/raw/master/ Recommendations/games-expand.csvaws s3 cp games-expand.csv s3://dsp-ch6/csv/games-expand.csv" }, { "code": null, "e": 14758, "s": 14508, "text": "In addition to staging the games data set to S3, we’ll also copy a subset of the CSV files from the Kaggle NHL data set, which we set up in Section 1.5.2. Run the following commands to stage the plays and stats CSV files from the NHL data set to S3." }, { "code": null, "e": 14931, "s": 14758, "text": "aws s3 cp game_plays.csv s3://dsp-ch6/csv/game_plays.csvaws s3 cp game_skater_stats.csv s3://dsp-ch6/csv/game_skater_stats.csvaws s3 ls s3://dsp-ch6/csv/" }, { "code": null, "e": 15142, "s": 14931, "text": "We now have all of the data sets needed for the code examples in this chapter. In order to read in these data sets from Spark, we’ll need to set up S3 credentials for interacting with S3 from the Spark cluster." }, { "code": null, "e": 15601, "s": 15142, "text": "For production environments, it is better to use IAM roles to manage access instead of using access keys. However, the community edition of Databricks constrains how much configuration is allowed, so we’ll use access keys to get up and running with the examples in this chapter. We already set up a user for accessing S3 from an EC2 instance. To create a set of credentials for accessing S3 programmatically, perform the following steps from the AWS console:" }, { "code": null, "e": 15751, "s": 15601, "text": "Search for and select “IAM”Click on “Users”Select the user created in Section 3.3.2, “S3_Lambda”Click “Security Credentials”Click “Create Access Key”" }, { "code": null, "e": 15779, "s": 15751, "text": "Search for and select “IAM”" }, { "code": null, "e": 15796, "s": 15779, "text": "Click on “Users”" }, { "code": null, "e": 15850, "s": 15796, "text": "Select the user created in Section 3.3.2, “S3_Lambda”" }, { "code": null, "e": 15879, "s": 15850, "text": "Click “Security Credentials”" }, { "code": null, "e": 15905, "s": 15879, "text": "Click “Create Access Key”" }, { "code": null, "e": 16171, "s": 15905, "text": "The result will be an access key and a secret key enabling access to S3. Save these values in a secure location, as we’ll use them in the notebook to connect to the data sets on S3. Once you are done with this chapter, it is recommended to revoke these credentials." }, { "code": null, "e": 16580, "s": 16171, "text": "Now that we have credentials set up for access, we can return to the Databricks notebook to read in the data set. To enable access to S3, we need to set the access key and secret key in the Hadoop configuration of the cluster. To set these keys, run the PySpark commands shown in the snippet below. You’ll need to replace the access and secret keys with the credentials we just create for the S3_Lambda role." }, { "code": null, "e": 16825, "s": 16580, "text": "AWS_ACCESS_KEY = \"AK...\"AWS_SECRET_KEY = \"dC...\"sc._jsc.hadoopConfiguration().set( \"fs.s3n.awsAccessKeyId\", AWS_ACCESS_KEY)sc._jsc.hadoopConfiguration().set( \"fs.s3n.awsSecretAccessKey\", AWS_SECRET_KEY)" }, { "code": null, "e": 17530, "s": 16825, "text": "We can now read the data set into a Spark dataframe using the read command, as shown below. This command uses the spark context to issue a read command and reads in the data set using the CSV input reader. We also specify that the CSV file includes a header row and that we want Spark to infer the data types for the columns. When reading in CSV files, Spark eagerly fetches the data set into memory, which can cause issues for larger data sets. When working with large CSV files, it’s a best practice to split up large data sets into multiple files and then read in the files using a wildcard in the input path. When using other file formats, such as Parquet or AVRO, Spark lazily fetches the data sets." }, { "code": null, "e": 17672, "s": 17530, "text": "games_df = spark.read.csv(\"s3://dsp-ch6/csv/games-expand.csv\", header=True, inferSchema = True)display(games_df)" }, { "code": null, "e": 18061, "s": 17672, "text": "The display command in the snippet above is a utility function provided by Databricks that samples the input dataframe and shows a table representation of the frame, as shown in Figure 6.3. It is similar to the head function in Pandas, but provides additional functionality such as transforming the sampled dataframe into a plot. We’ll explore the plotting functionality in Section 6.3.3." }, { "code": null, "e": 18232, "s": 18061, "text": "Now that we have data loaded into a Spark dataframe, we can begin exploring the PySpark language, which enables data scientists to build production-grade model pipelines." }, { "code": null, "e": 18940, "s": 18232, "text": "PySpark is a powerful language for both exploratory analysis and building machine learning pipelines. The core data type in PySpark is the Spark dataframe, which is similar to Pandas dataframes, but is designed to execute in a distributed environment. While the Spark Dataframe API does provide a familiar interface for Python programmers, there are significant differences in the way that commands issued to these objects are executed. A key difference is that Spark commands are lazily executed, which means that commands such as iloc are not available on these objects. While working with Spark dataframes can seem constraining, the benefit is that PySpark can scale to much larger data sets than Pandas." }, { "code": null, "e": 19333, "s": 18940, "text": "This section will walk through common operations for Spark dataframes, including persisting data, converting between different dataframe types, transforming dataframes, and using user-defined functions. We’ll use the NHL stats data set, which provides user-level summaries of player performance for each game. To load this data set as a Spark dataframe, run the commands in the snippet below." }, { "code": null, "e": 19486, "s": 19333, "text": "stats_df = spark.read.csv(\"s3://dsp-ch6/csv/game_skater_stats.csv\", header=True, inferSchema = True)display(stats_df)" }, { "code": null, "e": 20082, "s": 19486, "text": "A common operation in PySpark is saving a dataframe to persistent storage, or reading in a data set from a storage layer. While PySpark can work with databases such as Redshift, it performs much better when using distributed files stores such as S3 or GCS. In this chapter we’ll use these types of storage layers as the outputs of model pipelines, but it’s also useful to stage data to S3 as intermediate steps within a workflow. For example, in the AutoModel [14] system at Zynga, we stage the output of the feature generation step to S3 before using MLlib to train and apply model predictions." }, { "code": null, "e": 20565, "s": 20082, "text": "The data storage layer to use will depend on your cloud platform. For AWS, S3 works well with Spark for distributed data reads and writes. When using S3 or other data lakes, Spark supports a variety of different file formats for persisting data. Parquet is typically the industry standard when working with Spark, but we’ll also explore Avro and ORC in addition to CSV. Avro is a better format for streaming data pipelines, and ORC is useful when working with legacy data pipelines." }, { "code": null, "e": 21296, "s": 20565, "text": "To show the range of data formats supported by Spark, we’ll take the stats data set and write it to AVRO, then Parquet, then ORC, and finally CSV. After performing this round trip of data IO, we’ll end up with our initial Spark dataframe. To start, we’ll save the stats dataframe in Avro format, using the code snippet shown below. This code writes the dataframe to S3 in Avro format using the Databricks Avro writer, and then reads in the results using the same library. The result of performing these steps is that we now have a Spark dataframe pointing to the Avro files on S3. Since PySpark lazily evaluates operations, the Avro files are not pulled to the Spark cluster until an output needs to be created from this data set." }, { "code": null, "e": 21578, "s": 21296, "text": "# AVRO writeavro_path = \"s3://dsp-ch6/avro/game_skater_stats/\"stats_df.write.mode('overwrite').format( \"com.databricks.spark.avro\").save(avro_path)# AVRO read avro_df = sqlContext.read.format( \"com.databricks.spark.avro\").load(avro_path)" }, { "code": null, "e": 22183, "s": 21578, "text": "Avro is a distributed file format that is record based, while the Parquet and OR formats are column based. It is useful for the streaming workflows that we’ll explore in Chapter 9, because it compresses records for distributed data processing. The output of saving the stats dataframe in Avro format is shown in the snippet below, which shows a subset of the status files and data files generated when persisting a dataframe to S3 as Avro. Like most scalable data formats, Avro will write records to several files, based on partitions if specified, in order to enable efficient read and write operations." }, { "code": null, "e": 22734, "s": 22183, "text": "aws s3 ls s3://dsp-ch6/avro/game_skater_stats/2019-11-27 23:02:43 1455 _committed_15886175782508531572019-11-27 22:36:31 1455 _committed_16007797309378807952019-11-27 23:02:40 0 _started_15886175782508531572019-11-27 23:31:42 0 _started_69420741361908385862019-11-27 23:31:47 1486327 part-00000-tid-6942074136190838586- c6806d0e-9e3d-40fc-b212-61c3d45c1bc3-15-1-c000.avro2019-11-27 23:31:43 44514 part-00007-tid-6942074136190838586- c6806d0e-9e3d-40fc-b212-61c3d45c1bc3-22-1-c000.avro" }, { "code": null, "e": 23228, "s": 22734, "text": "Parquet on S3 is currently the standard approach for building data lakes on AWS, and tools such as Delta Lake are leveraging this format to provide highly-scalable data platforms. Parquet is a columnar-oriented file format that is designed for efficient reads when only a subset of columns are being accessed for an operation, such as when using Spark SQL. Parquet is a native format for Spark, which means that PySpark has built-in functions for both reading and writing files in this format." }, { "code": null, "e": 23763, "s": 23228, "text": "An example of writing the stats dataframe as Parquet files and reading in the result as a new dataframe is shown in the snippet below. In this example, we haven’t set a partition key, but as with Avro, the dataframe will be split up into multiple files in order to support highly-performant read and write operations. When working with large-scale data sets, it’s useful to set partition keys for the file export using the repartition function. After this section, we’ll use Parquet as the primary file format when working with Spark." }, { "code": null, "e": 23937, "s": 23763, "text": "# parquet outparquet_path = \"s3a://dsp-ch6/games-parquet/\"avro_df.write.mode('overwrite').parquet(parquet_path)# parquet inparquet_df = sqlContext.read.parquet(parquet_path)" }, { "code": null, "e": 24441, "s": 23937, "text": "ORC is a another columnar format that works well with Spark. The main benefit over Parquet is that it can support improved compression, at the cost of additional compute cost. I’m including it in this chapter, because some legacy systems still use this format. An example of writing the stats dataframe to ORC and reading the results back into a Spark dataframe is shown in the snippet below. Like the Avro format, the ORC write command will distribute the dataframe to multiple files based on the size." }, { "code": null, "e": 24582, "s": 24441, "text": "# orc outorc_path = \"s3a://dsp-ch6/games-orc/\"parquet_df.write.mode('overwrite').orc(orc_path)# orc inorc_df = sqlContext.read.orc(orc_path)" }, { "code": null, "e": 25089, "s": 24582, "text": "To complete our round trip of file formats, we’ll write the results back to S3 in the CSV format. To make sure that we write a single file rather than a batch of files, we’ll use the coalesce command to collect the data to a single node before exporting it.This is a command that will fail with large data sets, and in general it’s best to avoid using the CSV format when using Spark. However, CSV files are still a common format for sharing data, so it’s useful to understand how to export to this format." }, { "code": null, "e": 25360, "s": 25089, "text": "# CSV outcsv_path = \"s3a://dsp-ch6/games-csv-out/\"orc_df.coalesce(1).write.mode('overwrite').format( \"com.databricks.spark.csv\").option(\"header\",\"true\").save(csv_path) # and CSV to finish the round trip csv_df = spark.read.csv(csv_path, header=True, inferSchema = True)" }, { "code": null, "e": 25651, "s": 25360, "text": "The resulting dataframe is the same as the dataframe that we first read in from S3, but if the data types are not trivial to infer, then the CSV format can cause problems. When persisting data with PySpark, it’s best to use file formats that describe the schema of the data being persisted." }, { "code": null, "e": 26369, "s": 25651, "text": "While it’s best to work with Spark dataframes when authoring PySpark workloads, it’s often necessary to translate between different formats based on your use case. For example, you might need to perform a Pandas operation, such as selecting a specific element from a dataframe. When this is required, you can use the toPandas function to pull a Spark dataframe into the memory of the driver node. The code snippet below shows how to perform this task, display the results, and then convert the Pandas dataframe back to a Spark dataframe. In general, it’s best to avoid Pandas when authoring PySpark workflows, because it prevents distribution and scale, but it’s often the best way of expressing a command to execute." }, { "code": null, "e": 26447, "s": 26369, "text": "stats_pd = stats_df.toPandas()stats_df = sqlContext.createDataFrame(stats_pd)" }, { "code": null, "e": 27241, "s": 26447, "text": "To bridge the gap between Pandas and Spark dataframes, Databricks introduced a new library called Koalas that resembles the Pandas API for Spark-backed dataframes. The result is that you can author Python code that works with Pandas commands that can scale to Spark-scale data sets. An example of converting a Spark dataframe to Koalas and back to Spark is shown in the following snippet. After converting the stats dataframe to Koalas, the snippet shows how to calculate the average time on ice as well as index into the Koalas frame. The intent of Koalas is to provide a Pandas interface to Spark dataframes, and as the Koalas library matures more Python modules may be able to take advantage of Spark. The output from the snippet shows that the average time on ice was 993 seconds per game." }, { "code": null, "e": 27397, "s": 27241, "text": "import databricks.koalas as ksstats_ks = stats_df.to_koalas()stats_df = stats_ks.to_spark()print(stats_ks['timeOnIce'].mean())print(stats_ks.iloc[:1, 1:2])" }, { "code": null, "e": 27732, "s": 27397, "text": "During the development of this book, Koalas is still preliminary and only partially implemented, but it looks to provide a familiar interface for Python coders. Both Pandas and Spark dataframes can work with Koalas, and the snippet below shows how to go from Spark to Koalas to Pandas to Spark, and Spark to Pandas to Koalas to Spark." }, { "code": null, "e": 27920, "s": 27732, "text": "# spark -> koalas -> pandas -> sparkdf = sqlContext.createDataFrame(stats_df.to_koalas().toPandas())# spark -> pandas -> koalas -> sparkdf = ks.from_pandas(stats_df.toPandas()).to_spark()" }, { "code": null, "e": 28225, "s": 27920, "text": "In general, you’ll be working with Spark dataframes when authoring code in a PySpark environment. However, it’s useful to be able to work with different object types as necessary to build model workflows. Koalas and Pandas UDFs provide powerful tools for porting workloads to large-scale data ecosystems." }, { "code": null, "e": 28924, "s": 28225, "text": "The PySpark Dataframe API provides a variety of useful functions for aggregating, filtering, pivoting, and summarizing data. While some of this functionality maps well to Pandas operations, my recommendation for quickly getting up and running with munging data in PySpark is to use the SQL interface to dataframes in Spark called Spark SQL. If you’re already using the pandasql or framequery libraries, then Spark SQL should provide a familiar interface. If you’re new to these libraries, then the SQL interface still provides an approachable way of working with the Spark ecosystem. We’ll cover the Dataframe API later in this section, but first start with the SQL interface to get up and running." }, { "code": null, "e": 29418, "s": 28924, "text": "Exploratory data analysis (EDA) is one of the key steps in a data science workflow for understanding the shape of a data set. To work through this process in PySpark, we’ll load the stats data set into a dataframe, expose it as a view, and then calculate summary statistics. The snippet below shows how to load the NHL stats data set, expose it as a view to Spark, and then run a query against the dataframe. The aggregated dataframe is then visualized using the display command in Databricks." }, { "code": null, "e": 29741, "s": 29418, "text": "stats_df = spark.read.csv(\"s3://dsp-ch6/csv/game_skater_stats.csv\", header=True, inferSchema = True)stats_df.createOrReplaceTempView(\"stats\")new_df = spark.sql(\"\"\" select player_id, sum(1) as games, sum(goals) as goals from stats group by 1 order by 3 desc limit 5\"\"\")display(new_df)" }, { "code": null, "e": 30254, "s": 29741, "text": "An output of this code block is shown in Figure 6.4. It shows the highest scoring players in the NHL dataset by ranking the results based on the total number of goals. One of the powerful features of Spark is that the SQL query will not operate against the dataframe until a result set is needed. This means that commands in a notebook can set up multiple data transformation steps for Spark dataframes, which are not performed until a later step needs to execute the graph of operations defined in a code block." }, { "code": null, "e": 30894, "s": 30254, "text": "Spark SQL is expressive, fast, and my go-to method for working with big data sets in a Spark environment. While prior Spark versions performed better with the Dataframe API versus Spark SQL, the difference in performance is now trivial and you should use the transformation tools that provide the best iteration speed for working with large data sets. With Spark SQL, you can join dataframes, run nested queries, set up temp tables, and mix expressive Spark operations with SQL operations. For example, if you want to look at the distribution of goals versus shots in the NHL stats data, you can run the following command on the dataframe." }, { "code": null, "e": 31155, "s": 30894, "text": "display(spark.sql(\"\"\" select cast(goals/shots * 50 as int)/50.0 as Goals_per_shot ,sum(1) as Players from ( select player_id, sum(shots) as shots, sum(goals) as goals from stats group by 1 having goals >= 5 ) group by 1 order by 1\"\"\"))" }, { "code": null, "e": 31805, "s": 31155, "text": "This query restricts the ratio of goals to shots to players with more than 5 goals, to prevent outliers such as goalies scoring during power plays. We’ll use the display command to output the result set as a table and then use Databricks to display the output as a graph. Many Spark ecosystems have ways of visualizing results, and the Databricks environment provides this capability through the display command, which works well with both tabular and pivot table data. After running the above command, you can click on the chart icon and choose dimensions and measures which show the distribution of goals versus shots, as visualized in Figure 6.5." }, { "code": null, "e": 32355, "s": 31805, "text": "While I’m an advocate of using SQL to transform data, since it scales to different programming environments, it’s useful to get familiar with some of the basic dataframe operations in PySpark. The code snippet below shows how to perform common operations including dropping columns, selecting a subset of columns, and adding new columns to a Spark dataframe. Like prior commands, all of these operations are lazily performed. There are some syntax differences from Pandas, but the general commands used for transforming data sets should be familiar." }, { "code": null, "e": 32613, "s": 32355, "text": "from pyspark.sql.functions import lit# dropping columnscopy_df = stats_df.drop('game_id', 'player_id')# selection columns copy_df = copy_df.select('assists', 'goals', 'shots')# adding columnscopy_df = copy_df.withColumn(\"league\", lit('NHL'))display(copy_df)" }, { "code": null, "e": 33179, "s": 32613, "text": "One of the common operations to perform between dataframes is a join. This is easy to express in a Spark SQL query, but sometimes it is preferable to do this programmatically with the Dataframe API. The code snippet below shows how to join two dataframes together, when joining on the game_id and player_id fields. The league column which is a literal will be joined with the rest of the stats dataframe. This is a trivial example where we are adding a new column onto a small dataframe, but the join operation from the Dataframe API can scale to massive data sets." }, { "code": null, "e": 33352, "s": 33179, "text": "copy_df = stats_df.select('game_id', 'player_id'). withColumn(\"league\", lit('NHL'))df = copy_df.join(stats_df, ['game_id', 'player_id'])display(df)" }, { "code": null, "e": 33572, "s": 33352, "text": "The result set from the join operation above is shown in Figure 6.6. Spark supports a variety of different join types, and in this example we used an inner join to append league the league column to the stats dataframe." }, { "code": null, "e": 33979, "s": 33572, "text": "It’s also possible to perform aggregation operations on a dataframe, such as calculating sums and averages of columns. An example of computing the average time on ice for players in the stats data set, and total number of goals scored is shown in the snippet below. The groupBy command uses the player_id as the column for collapsing the data set, and the agg command specifies the aggregations to perform." }, { "code": null, "e": 34110, "s": 33979, "text": "summary_df = stats_df.groupBy(\"player_id\").agg( {'timeOnIce':'avg', 'goals':'sum'})display(summary_df)" }, { "code": null, "e": 34388, "s": 34110, "text": "The snippet creates a dataframe with player_id, timeOnIce, and goals columns. We’ll again use the plotting functionality in Databricks to visualize the results, but this time select the scatter plot option. The resulting plot of goals versus time on ice is shown in Figure 6.7." }, { "code": null, "e": 34748, "s": 34388, "text": "We’ve worked through introductory examples to get up and running with dataframes in PySpark, focusing on operations that are useful for munging data prior to training machine learning models. These types of operations, in combination with reading and writing dataframes provides a useful set of skills for performing exploratory analysis on massive data sets." }, { "code": null, "e": 35817, "s": 34748, "text": "While PySpark provides a great deal of functionality for working with dataframes, it often lacks core functionality provided in Python libraries, such as curve-fitting functions in SciPy. While it’s possible to use the toPandas function to convert dataframes into the Pandas format for Python libraries, this approach breaks when using large data sets. Pandas UDFs are a newer feature in PySpark that help data scientists work around this problem, by distributing the Pandas conversion across the worker nodes in a Spark cluster. With a Pandas UDF, you define a group by operation to partition the data set into dataframes that are small enough to fit into the memory of worker nodes, and then author a function that takes in a Pandas dataframe as the input parameter and returns a transformed Pandas dataframe as the result. Behind the scenes, PySpark uses the PyArrow library to efficiently translate dataframes from Spark to Pandas and back from Pandas to Spark. This approach enables Python libraries, such as Keras, to be scaled up to a large cluster of machines." }, { "code": null, "e": 36560, "s": 35817, "text": "This section will walk through an example problem where we need to use an existing Python library and show how to translate the workflow into a scalable solution using Pandas UDFs. The question we are looking to answer is understanding if there is a positive or negative relationship between the shots and hits attributes in the stats data set. To calculate this relationship, we can use the leastsq function in SciPy, as shown in the snippet below. This example creates a Pandas dataframe for a single player_id, and then fits a simple linear regression between these attributes. The output is the coefficients used to fit the least-squares operation, and in this case the number of shots was not strongly correlated with the number of hits." }, { "code": null, "e": 36939, "s": 36560, "text": "sample_pd = spark.sql(\"\"\" select * from stats where player_id = 8471214\"\"\").toPandas()# Import python libraries from scipy.optimize import leastsqimport numpy as np# Define a function to fitdef fit(params, x, y): return (y - (params[0] + x * params[1] )) # Fit the curve and show the results result = leastsq(fit, [1,0], args=(sample_pd.shots,sample_pd.hits))print(result)" }, { "code": null, "e": 37807, "s": 36939, "text": "Now we want to perform this operation for every player in the stats data set. To scale to this volume, we’ll first partition by player_id, as shown by the groupBy operation in the code snippet below. Next, We’ll run the analyze_player function for each of these partitioned data sets using the apply command. While the stats_df dataframe used as input to this operation and the players_df dataframe returned are Spark dataframes, the sampled_pd dataframe and the dataframe returned by the analyze player function are Pandas. The Pandas UDF annotation provides a hint to PySpark for how to distribute this workload so that it can scale the operation across the cluster of worker nodes rather than eagerly pulling all of the data to the driver node. Like most Spark operations, Pandas UDFs are lazily evaluated and will not be executed until and output value is needed." }, { "code": null, "e": 38782, "s": 37807, "text": "Our initial example now translated to use Pandas UDFs is shown below. After defining additional modules to include, we specify the schema of the dataframe that will be returned from the operation. The schema object defines the structure of the Spark dataframe that will return from applying the analyze player function. The next step in the code block lists an annotation that defines this function as a grouped map operation, which means that it works on dataframes rather than scalar values. As before, we’ll use the leastsq function to fit the shots and hits attributes. After calculating the coefficients for this curve fitting, we create a new Pandas dataframe with the player id, and regression coefficients. The display command at the end of this code block will force the Pandas UDF to execute, which will create a partition for each of the players in the data set, apply the least squares operation, and merge the results back together into a large Spark dataframe." }, { "code": null, "e": 39912, "s": 38782, "text": "# Load necessary librariesfrom pyspark.sql.functions import pandas_udf, PandasUDFTypefrom pyspark.sql.types import *import pandas as pd# Create the schema for the resulting data frameschema = StructType([StructField('ID', LongType(), True), StructField('p0', DoubleType(), True), StructField('p1', DoubleType(), True)])# Define the UDF, input and outputs are Pandas DFs@pandas_udf(schema, PandasUDFType.GROUPED_MAP)def analize_player(sample_pd): # return empty params in not enough data if (len(sample_pd.shots) <= 1): return pd.DataFrame({'ID': [sample_pd.player_id[0]], 'p0': [ 0 ], 'p1': [ 0 ]}) # Perform curve fitting result = leastsq(fit, [1, 0], args=(sample_pd.shots, sample_pd.hits)) # Return the parameters as a Pandas DF return pd.DataFrame({'ID': [sample_pd.player_id[0]], 'p0': [result[0][0]], 'p1': [result[0][1]]}) # perform the UDF and show the results player_df = stats_df.groupby('player_id').apply(analyze_player)display(player_df)" }, { "code": null, "e": 40432, "s": 39912, "text": "The key capability that Pandas UDFs provide is that they enable Python libraries to be used in a distributed environment, as long as you have a good way of partitioning your data. This means that libraries such as Featuretools, which were not initially designed to work in a distributed environment, can be scaled up to a large cluster. The result of applying the Pandas UDF from above on the stats data set is shown in Figure 6.8. This feature enables a mostly seamless translation between different dataframe formats." }, { "code": null, "e": 40767, "s": 40432, "text": "To further demonstrate the value of Pandas UDFs, we’ll apply them to distributing a feature generation pipeline and a deep learning pipeline. However, there are some issues when using Pandas UDFs in workflows, because they can make debugging more of a challenge and sometimes fail due to data type mismatches between Spark and Pandas." }, { "code": null, "e": 41045, "s": 40767, "text": "While PySpark provides a familiar environment for Python programmers, it’s good to follow a few best practices to make sure you are using Spark efficiently. Here are a set of recommendations I’ve compiled based on my experience porting a few projections from Python to PySpark:" }, { "code": null, "e": 41413, "s": 41045, "text": "Avoid dictionaries: Using Python data types such as dictionaries means that the code might not be executable in a distributed mode. Instead of using keys to index values in a dictionary, consider adding another column to a dataframe that can be used as a filter. This recommendation applies to other Python types including lists that are not distributable in PySpark." }, { "code": null, "e": 41760, "s": 41413, "text": "Limit Pandas usage: Calling toPandas will cause all data to be loaded into memory on the driver node, and prevents operations from being performed in a distributed mode. It’s fine to use this function when data has already been aggregated and you want to make use of familiar Python plotting tools, but it should not be used for large dataframes." }, { "code": null, "e": 42131, "s": 41760, "text": "Avoid loops: Instead of using for loops, it’s often possible to use functional approaches such as group by and apply to achieve the same result. Using this pattern means that code can be parallelized by supported execution environments. I’ve noticed that focusing on using this pattern in Python has also resulted in cleaning code that is easier to translate to PySpark." }, { "code": null, "e": 42446, "s": 42131, "text": "Minimize eager operations: In order for your pipeline to be as scalable as possible, it’s good to avoid eager operations that pull full dataframes into memory. For example, reading in CSVs is an eager operation, and my work around is to stage the dataframe to S3 as Parquet before using it in later pipeline steps." }, { "code": null, "e": 42807, "s": 42446, "text": "Use SQL: There are libraries that provide SQL operations against dataframes in both Python and PySpark. If you’re working with someone else’s Python code, it can be tricky to decipher what some of the Pandas operations are achieving. If you plan on porting your code from Python to PySpark, then using a SQL library for Pandas can make this translation easier." }, { "code": null, "e": 42945, "s": 42807, "text": "By following these best practices when writing PySpark code, I’ve been able to improve both my Python and PySpark data science workflows." }, { "code": null, "e": 43579, "s": 42945, "text": "Now that we’ve covered loading and transforming data with PySpark, we can now use the machine learning libraries in PySpark to build a predictive model. The core library for building predictive models in PySpark is called MLlib. This library provides a suite of supervised and unsupervised algorithms. While this library does not have complete coverage of all of the algorithms in sklearn, it provides functionality for the majority of the types of operations needed for data science workflows. In this chapter, we’ll show how to apply MLlib to a classification problem and save the outputs from the model application to a data lake." }, { "code": null, "e": 43905, "s": 43579, "text": "games_df = spark.read.csv(\"s3://dsp-ch6/csv/games-expand.csv\", header=True, inferSchema = True)games_df.createOrReplaceTempView(\"games_df\")games_df = spark.sql(\"\"\" select *, row_number() over (order by rand()) as user_id ,case when rand() > 0.7 then 1 else 0 end as test from games_df\"\"\")" }, { "code": null, "e": 44359, "s": 43905, "text": "The first step in the pipeline is loading the data set that we want to use for model training. The snippet above shows how to load the games data set, and append two additional attributes to the loaded dataframe using Spark SQL. The result of running this query is that about 30% of users will be assigned a test label which we’ll use for model application, and each record is assigned a unique user ID which we’ll use when saving the model predictions." }, { "code": null, "e": 44720, "s": 44359, "text": "The next step is splitting up the data set into train and test dataframes. For this pipeline, we’ll use the test dataframe as the data set for model application, where we predict user behavior. An example of splitting up the dataframes using the test column is shown in the snippet below. This should result in roughly 16.1k training users and 6.8k test users." }, { "code": null, "e": 44870, "s": 44720, "text": "trainDF = games_df.filter(\"test == 0\")testDF = games_df.filter(\"test == 1\")print(\"Train \" + str(trainDF.count()))print(\"Test \" + str(testDF.count()))" }, { "code": null, "e": 45556, "s": 44870, "text": "MLlib requires that the input data is formatted using vector data types in Spark. To transform our dataframe into this format, we can use the VectorAssembler class to combine a range of columns into a single vector column. The code snippet below shows how to use this class to merge the first 10 columns in the dataframe into a new vector column called features. After applying this command to the training dataframe using the transform function, we use the select function to only retrieve the values we need from the dataframe for model training and application. For the training dataframe, we only need the label and features, and with the test dataframe we also select the user ID." }, { "code": null, "e": 45934, "s": 45556, "text": "from pyspark.ml.feature import VectorAssembler# create a vector representationassembler = VectorAssembler( inputCols= trainDF.schema.names[0:10], outputCol=\"features\" )trainVec = assembler.transform(trainDF).select('label', 'features')testVec = assembler.transform(testDF).select( 'label', 'features', 'user_id')display(testVec)" }, { "code": null, "e": 46089, "s": 45934, "text": "The display command shows the result of transforming our test dataset into vector types usable by MLlib. The output dataframe is visualized in Figure 6.9." }, { "code": null, "e": 46526, "s": 46089, "text": "Now that we have prepared our training and test data sets, we can use the logistic regression algorithm provided by MLlib to fit the training dataframe. We first create a logistic regression object and define the columns to use as labels and features. Next, we use the fit function to train the model on the training data set. In the last step in the snippet below, we use the transform function to apply the model to our test data set." }, { "code": null, "e": 46785, "s": 46526, "text": "from pyspark.ml.classification import LogisticRegression# specify the columns for the modellr = LogisticRegression(featuresCol='features', labelCol='label')# fit on training datamodel = lr.fit(trainVec)# predict on test data predDF = model.transform(testVec)" }, { "code": null, "e": 47192, "s": 46785, "text": "The resulting dataframe now has a probability column, as shown in Figure 6.10. This column is a 2-element array with the probabilities for class 0 and 1. To test the accuracy of the logistic regression model on the test data set, we can use the binary classification evaluator in Mlib to calculate the ROC metric, as shown in the snippet below. For my run of the model, the ROC metric has a value of 0.761." }, { "code": null, "e": 47320, "s": 47192, "text": "from pyspark.ml.evaluation import BinaryClassificationEvaluatorroc = BinaryClassificationEvaluator().evaluate(predDF)print(roc)" }, { "code": null, "e": 47701, "s": 47320, "text": "In a production pipeline, there will not be labels for the users that need predictions, meaning that you’ll need to perform cross validation to select the best model for making predictions. An example of this approach is covered in Section 6.7. In this case, we are using a single data set to keep code examples short, but a similar pipeline can be used in a production workflows." }, { "code": null, "e": 48035, "s": 47701, "text": "Now that we have the model predictions for our test users, we need to retrieve the predicted label in order to create a dataframe to persist to a data lake. Since the probability column created by MLlib is an array, we’ll need to define a UDF that retrieves the second element as our propensity column, as shown in the snippet below." }, { "code": null, "e": 48310, "s": 48035, "text": "from pyspark.sql.functions import udffrom pyspark.sql.types import FloatType# split out the array into a column secondElement = udf(lambda v:float(v[1]),FloatType())predDF = predDF.select(\"*\", secondElement(\"probability\").alias(\"propensity\"))display(predDF) " }, { "code": null, "e": 48693, "s": 48310, "text": "After running this code block, the dataframe will have an additional column called propensity as shown in Figure 6.10. The final step in this batch prediction pipeline is to save the results to S3. We’ll use the select function to retrieve the relevant columns from the predictions dataframe, and then use the write function on the dataframe to persist the results as Parquet on S3." }, { "code": null, "e": 48869, "s": 48693, "text": "# save results to S3results_df = predDF.select(\"user_id\", \"propensity\")results_path = \"s3a://dsp-ch6/game-predictions/\"results_df.write.mode('overwrite').parquet(results_path)" }, { "code": null, "e": 49123, "s": 48869, "text": "We now have all of the building blocks needed to create a PySpark pipeline that can fetch data from a storage layer, train a predictive model, and write the results to persistent storage. We’ll cover how to schedule this type of pipeline in Section 6.8." }, { "code": null, "e": 49518, "s": 49123, "text": "When developing models, it’s useful to inspect the output to see if the distribution of model predictions matches expectations. We can use Spark SQL to perform an aggregation on the model outputs and then use the display command to perform this process directly in Databricks, as shown in the snippet below. The result of performing these steps on the model predictions is shown in Figure 6.11." }, { "code": null, "e": 49773, "s": 49518, "text": "# plot the predictions predDF .createOrReplaceTempView(\"predDF \")plotDF = spark.sql(\"\"\" select cast(propensity*100 as int)/100 as propensity, label, sum(1) as users from predDF group by 1, 2 order by 1, 2 \"\"\")# table outputdisplay(plotDF) " }, { "code": null, "e": 50073, "s": 49773, "text": "MLlib can be applied to a wide variety of problems using a large suite of algorithms. While we explored logistic regression in this section, the libraries provides a number of different classification approaches, and there are other types of operations supported including regression and clustering." }, { "code": null, "e": 50501, "s": 50073, "text": "While MLlib provides scalable implementations for classic machine learning algorithms, it does not natively support deep learning libraries such as Tensorflow and PyTorch. There are libraries that parallelize the training of deep learning models on Spark, but the data set needs to be able to fit in memory on each worker node, and these approaches are best used for distributed hyperparameter tuning on medium-sized data sets." }, { "code": null, "e": 51129, "s": 50501, "text": "For the model application stage, where we already have a deep learning model trained but need to apply the resulting model to a large user base, we can use Pandas UDFs. With Pandas UDFs, we can partition and distribute our data set, run the resulting dataframes against a Keras model, and then compile the results back into a single large Spark dataframe. This section will show how we can take the Keras model that we built in Section 1.6.3, and scale it to larger data sets using PySpark and Pandas UDFs. However, we still have the requirement that the data used for training the model can fit into memory on the driver node." }, { "code": null, "e": 51505, "s": 51129, "text": "We’ll use the same data sets from the prior section, where we split the games data set into training and test sets of users. This is a relatively small data set, so we can use the toPandas operation to load the dataframe onto the driver node, as shown in the snippet below. The result is a dataframe and list that we can provide as input to train a Keras deep learning model." }, { "code": null, "e": 51626, "s": 51505, "text": "# build model on the driver node train_pd = trainDF.toPandas()x_train = train_pd.iloc[:,0:10]y_train = train_pd['label']" }, { "code": null, "e": 51984, "s": 51626, "text": "When using PyPI to install TensorFlow on the Spark cluster, the installed version of the library should be 2.0 or greater. This differs from Version 1 of TensorFlow, which we used in prior chapters. The main impact in terms of the code snippets is that Tensorflow 2 now has a built-in AUC function that no longer requires the workflow we previously applied." }, { "code": null, "e": 52332, "s": 51984, "text": "We’ll use the same approach as before to train a Keras model. The code snippet below shows how to set up a network with an input layer, dropout later, single hidden layer, and an output layer, optimized with rmsprop and a cross entropy loss. In the model application phase, we’ll reuse the model object in a Pandas UDFs to distribute the workload." }, { "code": null, "e": 52794, "s": 52332, "text": "import tensorflow as tfimport kerasfrom keras import models, layersmodel = models.Sequential()model.add(layers.Dense(64, activation='relu', input_shape=(10,)))model.add(layers.Dropout(0.1))model.add(layers.Dense(64, activation='relu'))model.add(layers.Dense(1, activation='sigmoid'))model.compile(optimizer='rmsprop', loss='binary_crossentropy')history = model.fit(x_train, y_train, epochs=100, batch_size=100, validation_split = .2, verbose=0)" }, { "code": null, "e": 53177, "s": 52794, "text": "To test for overfitting, we can plot the results of the training and validation data sets, as shown in Figure 6.12. The snippet below shows how to use matplotlib to display the losses over time for these data sets. While the training loss continued to decrease over additional epochs, the validation loss stopped improving after 20 epochs, but did not noticeably increase over time." }, { "code": null, "e": 53483, "s": 53177, "text": "import matplotlib.pyplot as pltloss = history.history['loss']val_loss = history.history['val_loss']epochs = range(1, len(loss) + 1)fig = plt.figure(figsize=(10,6) )plt.plot(epochs, loss, 'bo', label='Training Loss')plt.plot(epochs, val_loss, 'b', label='Validation Loss')plt.legend()plt.show()display(fig)" }, { "code": null, "e": 54102, "s": 53483, "text": "Now that we have a trained deep learning model, we can use PySpark to apply it in a scalable pipeline. The first step is determining how to partition the set of users that need to be scored. For this data set, we can assign the user base into 100 different buckets, as shown in the snippet below. This randomly assigns each user into 1 of 100 buckets, which means that after applying the group by step, each dataframe that gets translated to Pandas will be roughly 1% the size of the original dataframe. If you have a large data set, you may need to use thousands of buckets to distribute the data set, and maybe more." }, { "code": null, "e": 54288, "s": 54102, "text": "# set up partitioning for the train data frametestDF.createOrReplaceTempView(\"testDF \")partitionedDF = spark.sql(\"\"\" select *, cast(rand()*100 as int) as partition_id from testDF \"\"\")" }, { "code": null, "e": 54933, "s": 54288, "text": "The next step is to define the Pandas UDF that will apply the Keras model. We’ll define an output schema of a user ID and propensity score, as shown below. The UDF uses the predict function on the model object we previously trained to create a prediction column on the passed in dataframe. The return command selects the two relevant columns that we defined for the schema object. The group by command partitions the data set using our bucketing approach, and the apply command performs the Keras model application across the cluster of worker nodes. The result is a Spark dataframe visualized with the display command, as shown in Figure 6.13." }, { "code": null, "e": 55398, "s": 54933, "text": "from pyspark.sql.functions import pandas_udf, PandasUDFTypefrom pyspark.sql.types import *schema = StructType([StructField('user_id', LongType(), True), StructField('propensity', DoubleType(),True)])@pandas_udf(schema, PandasUDFType.GROUPED_MAP)def apply_keras(pd): pd['propensity'] = model.predict(pd.iloc[:,0:10]) return pd[['user_id', 'propensity']]results_df=partitionedDF.groupby('partition_id').apply(apply_keras)display(results_df)" }, { "code": null, "e": 56361, "s": 55398, "text": "One thing to note is that there are limitations on the types of objects that you can reference in a Pandas UDFs. In this example, we referenced the model object, which was created on the driver node when training the model. When variables in PySpark are transferred from the driver node to workers nodes for distributed operations, a copy of the variable is made, because synchronizing variables across a cluster would be inefficient. This means that any changes made to a variable within a Pandas UDF will not apply to the original object. It’s also why data types such as Python lists and dictionaries should be avoided when using UDFs. Functions work in a similar way, in Section 6.3.4 we used the fit function in a Pandas UDF where the function was initially defined on the driver node. Spark also provides broadcast variables for sharing variables in a cluster, but ideally distributed code segments should avoid sharing state through variables if possible." }, { "code": null, "e": 57028, "s": 56361, "text": "Feature engineering is a key step in a data science workflow, and sometimes it is necessary to use Python libraries to implement this functionality. For example, the AutoModel system at Zynga uses the Featuretools library to generate hundreds of features from raw tracking events, which are then used as input to classification models. To scale up the automated feature engineering approach that we first explored in Section 1.7, we can use Pandas UDFs to distribute the feature application process. Like the prior section, we need to sample data when determining the transformation to perform, but when applying the transformation we can scale to massive data sets." }, { "code": null, "e": 57651, "s": 57028, "text": "For this section, we’ll use the game plays data set from the NHL Kaggle example, which includes detailed play-by-play descriptions of the events that occurred during each match. Our goal is to transform the deep and narrow dataframe into a shallow and wide dataframe that summarizes each game as a single record with hundreds of columns. An example of loading this data in PySpark and selecting the relevant columns is shown in the snippet below. Before calling toPandas, we use the filter function to sample 0.3% of the records, and then cast the result to a Pandas frame, which has a shape of 10,717 rows and 16 columns." }, { "code": null, "e": 57899, "s": 57651, "text": "plays_df = spark.read.csv(\"s3://dsp-ch6/csv/game_plays.csv\", header=True, inferSchema = True).drop( 'secondaryType', 'periodType', 'dateTime', 'rink_side')plays_pd = plays_df.filter(\"rand() < 0.003\").toPandas()plays_pd.shape" }, { "code": null, "e": 58319, "s": 57899, "text": "We’ll use the same two-step process covered in Section 1.7 where we first one-hot encode the categorical features in the dataframe, and then apply deep feature synthesis to the data set. The code snippet below shows how to perform the encoding process using the Featuretools library. The output is a transformation of the initial dataframe that now has 20 dummy variables instead of the event and description variables." }, { "code": null, "e": 58825, "s": 58319, "text": "import featuretools as ftfrom featuretools import Featurees = ft.EntitySet(id=\"plays\")es = es.entity_from_dataframe(entity_id=\"plays\",dataframe=plays_pd, index=\"play_id\", variable_types = { \"event\": ft.variable_types.Categorical, \"description\": ft.variable_types.Categorical })f1 = Feature(es[\"plays\"][\"event\"])f2 = Feature(es[\"plays\"][\"description\"])encoded, defs = ft.encode_features(plays_pd, [f1, f2], top_n=10)encoded.reset_index(inplace=True)" }, { "code": null, "e": 59150, "s": 58825, "text": "The next step is using the dfs function to perform deep feature synthesis on our encoded dataframe. The input dataframe will have a record per play, while the output dataframe will have a single record per game after collapsing the detailed events into a wide column representation using a variety of different aggregations." }, { "code": null, "e": 59554, "s": 59150, "text": "es = ft.EntitySet(id=\"plays\")es = es.entity_from_dataframe(entity_id=\"plays\", dataframe=encoded, index=\"play_id\")es = es.normalize_entity(base_entity_id=\"plays\", new_entity_id=\"games\", index=\"game_id\")features, transform=ft.dfs(entityset=es, target_entity=\"games\",max_depth=2)features.reset_index(inplace=True)" }, { "code": null, "e": 60181, "s": 59554, "text": "One of the new steps that we need to perform versus the prior approach, is that we need to determine what the schema will be for the generated features, since this is needed as an input to the Pandas UDF annotation. To figure out what the generated schema is for the generated dataframe, we can create a Spark dataframe and then retrieve the schema from the Spark dataframe. Before converting the Pandas dataframe, we need to modify the column names in the generated dataframe to remove special characters, as shown in the snippet below. The resulting Spark schema for the feature application step is displayed in Figure 6.14." }, { "code": null, "e": 60312, "s": 60181, "text": "features.columns = features.columns.str.replace(\"[(). =]\", \"\")schema = sqlContext.createDataFrame(features).schemafeatures.columns" }, { "code": null, "e": 60849, "s": 60312, "text": "We now have the required schema for defining a Pandas UDF. Unlike the past UDFs we defined, the schema may change between different runs based on the feature transformation aggregations selected by Featuretools. In these steps, we also created a defs object that defines the feature transformations to use for encoding and a transform object that defines the transformations to perform deep feature synthesis. Like the model object in the past section, copies of these objects will be passed to the Pandas UDF executing on worker nodes." }, { "code": null, "e": 61467, "s": 60849, "text": "To enable our approach to scale across a cluster of worker nodes, we need to define a column to use for partitioning. Like the prior section, we can bucket events into different sets of data to ensure that the UDF process can scale. One difference from before is that we need all of the plays from a specific game to be grouped into the same partition. To achieve this result, we can partition by the game_id rather than the player_id. An example of this approach in shown in the code snippet below. Additionally, we can use the hash function on the game ID to randomize the value, resulting in more balanced buckets." }, { "code": null, "e": 61621, "s": 61467, "text": "# bucket IDs plays_df.createOrReplaceTempView(\"plays_df\")plays_df = spark.sql(\"\"\" select *, abs(hash(game_id))%1000 as partition_id from plays_df \"\"\")" }, { "code": null, "e": 62135, "s": 61621, "text": "We can now apply feature transformation to the full data set, using the Pandas UDF defined below. The plays dataframe is partitioned by the bucket before being passed to the generate features function. This function uses the previously generated feature transformations to ensure that the same transformation is applied across all of the worker nodes. The input Pandas dataframe is a narrow and deep representation of play data, while the returned dataframe is a shallow and wide representation of game summaries." }, { "code": null, "e": 63216, "s": 62135, "text": "from pyspark.sql.functions import pandas_udf, PandasUDFType@pandas_udf(schema, PandasUDFType.GROUPED_MAP)def gen_features(plays_pd): es = ft.EntitySet(id=\"plays\") es = es.entity_from_dataframe(entity_id=\"plays\", dataframe=plays_pd, index=\"play_id\", variable_types = { \"event\": ft.variable_types.Categorical, \"description\": ft.variable_types.Categorical }) encoded_features = ft.calculate_feature_matrix(defs, es) encoded_features.reset_index(inplace=True) es = ft.EntitySet(id=\"plays\") es = es.entity_from_dataframe(entity_id=\"plays\", dataframe=encoded, index=\"play_id\") es = es.normalize_entity(base_entity_id=\"plays\", new_entity_id=\"games\", index=\"game_id\") generated = ft.calculate_feature_matrix(transform,es).fillna(0) generated.reset_index(inplace=True) generated.columns = generated.columns.str.replace(\"[(). =]\",\"\") return generated features_df = plays_df.groupby('partition_id').apply(gen_features)display(features_df)" }, { "code": null, "e": 63545, "s": 63216, "text": "The output of the display command is shown in Figure 6.15. We’ve now worked through feature generation and deep learning in scalable model pipelines. Now that we have a transformed data set, we can join the result with additional features, such as the label that we are looking to predict, and develop a complete model pipeline." }, { "code": null, "e": 63979, "s": 63545, "text": "A common workflow for batch model pipelines is reading input data from a lake, applying a machine learning model, and then writing the results to an application database. In GCP, BigQuery serves as the data lake and Cloud Bigtable can serve as an application database. We’ll build and end-to-end pipeline with these components in the next chapter, but for now we’ll get hands on with a subset of the GCP components directly in Spark." }, { "code": null, "e": 64898, "s": 63979, "text": "While there is a Spark connector for BigQuery [15], enabling large-scale PySpark pipelines to be built using BigQuery directly, there are some issues with this library that make it quite complicated to set up for our Databricks environment. For example, we would need to rebuild some of the JAR files and shade the dependencies. One alternative is to use the Python BigQuey connector that we explored in Section 5.1, but this approach is not distributed and will eagerly pull the query results to the driver node as a Pandas dataframe. For this chapter, we’ll explore a workflow where we unload query results to Cloud Storage, and then read in the data set from GCS as the initial step in the pipeline. Similarly, for model output we’ll save the results to GCS, where the output is available for pushing to Bigtable. To productize this type of workflow, Airflow could be used to chain these different actions together." }, { "code": null, "e": 65313, "s": 64898, "text": "The first step we’ll perform is exporting the results of a BigQuery query to GCS, which can be performed manually using the BigQuery UI. This is possible to perform directly in Spark, but as I mentioned the setup is quite involved to configure with the current version of the connector library. We’ll use the natality data set for this pipeline, which lists attributes about a child delivery, such as birth weight." }, { "code": null, "e": 65437, "s": 65313, "text": "create table dsp_demo.natality as ( select * from `bigquery-public-data.samples.natality` order by rand() limit 10000 )" }, { "code": null, "e": 65767, "s": 65437, "text": "To create a data set, we’ll sample 10k records from the natality public data set in BigQuery. To export this result set to GCS, we need to create a table on BigQuery with the data that we want to export. The SQL for creating this data sample is shown in the snippet above. To export this data to GCS, perform the following steps:" }, { "code": null, "e": 66084, "s": 65767, "text": "Browse to the GCP ConsoleSearch for “BigQuery”Paste the Query from the snippet above into the query editorClick RunIn the left navigation pane, select the new table, “dsp_demo.natality”Click “Export”, and then “Export to GCS”Set the location, “/dsp_model_store/natality/avro”Use “Avro” as export formatClick “Export”" }, { "code": null, "e": 66110, "s": 66084, "text": "Browse to the GCP Console" }, { "code": null, "e": 66132, "s": 66110, "text": "Search for “BigQuery”" }, { "code": null, "e": 66193, "s": 66132, "text": "Paste the Query from the snippet above into the query editor" }, { "code": null, "e": 66203, "s": 66193, "text": "Click Run" }, { "code": null, "e": 66274, "s": 66203, "text": "In the left navigation pane, select the new table, “dsp_demo.natality”" }, { "code": null, "e": 66315, "s": 66274, "text": "Click “Export”, and then “Export to GCS”" }, { "code": null, "e": 66366, "s": 66315, "text": "Set the location, “/dsp_model_store/natality/avro”" }, { "code": null, "e": 66394, "s": 66366, "text": "Use “Avro” as export format" }, { "code": null, "e": 66409, "s": 66394, "text": "Click “Export”" }, { "code": null, "e": 66653, "s": 66409, "text": "After performing these steps, the sampled natality data will be saved to GCS in Avro format. The confirmation dialog from exporting the data set is shown in Figure 6.16. We now have the data saved to GCS in a format that works well with Spark." }, { "code": null, "e": 67449, "s": 66653, "text": "We now have a data set that we can use as input to a PySpark pipeline, but we don’t yet have access to the bucket on GCS from our Spark environment. With AWS, we were able to set up programmatic access to S3 using an access and secret key. With GCP, the process is a bit more complicated because we need to move the json credentials file to the driver node of the cluster in order to read and write files on GCS. One of the challenges with using Spark is that you may not have SSH access to the driver node, which means that we’ll need to use persistent storage to move the file to the driver machine. This isn’t recommended for production environments, but instead is being shown as a proof of concept. The best practice for managing credentials in a production environment is to use IAM roles." }, { "code": null, "e": 67536, "s": 67449, "text": "aws s3 cp dsdemo.json s3://dsp-ch6/secrets/dsdemo.jsonaws s3 ls s3://dsp-ch6/secrets/" }, { "code": null, "e": 68318, "s": 67536, "text": "To move the json file to the driver node, we can first copy the credentials file to S3, as shown in the snippet above. Now we can switch back to Databricks and author the model pipeline. To copy the file to the driver node, we can read in the file using the sc Spark context to read the file line by line. This is different from all of our prior operations where we have read in data sets as dataframes. After reading the file, we then create a file on the driver node using the Python open and write functions. Again, this is an unusual action to perform in Spark, because you typically want to write to persistent storage rather than local storage. The result of performing these steps is that the credentials file will now be available locally on the driver node in the cluster." }, { "code": null, "e": 68509, "s": 68318, "text": "creds_file = '/databricks/creds.json'creds = sc.textFile('s3://dsp-ch6/secrets/dsdemo.json')with open(creds_file, 'w') as file: for line in creds.take(100): file.write(line + \"\\n\")" }, { "code": null, "e": 68858, "s": 68509, "text": "Now that we have the json credentials file moved to the driver local storage, we can set up the Hadoop configuration needed to access data on GCS. The code snippet below shows how to configure the project ID, file system implementation, and credentials file location. After running these commands, we now have access to read and write files on GCS." }, { "code": null, "e": 69297, "s": 68858, "text": "sc._jsc.hadoopConfiguration().set(\"fs.gs.impl\", \"com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem\")sc._jsc.hadoopConfiguration().set(\"fs.gs.project.id\", \"your_project_id\")sc._jsc.hadoopConfiguration().set( \"mapred.bq.auth.service.account.json.keyfile\", creds_file)sc._jsc.hadoopConfiguration().set( \"fs.gs.auth.service.account.json.keyfile\", creds_file)" }, { "code": null, "e": 69596, "s": 69297, "text": "To read in the natality data set, we can use the read function with the Avro setting to fetch the data set. Since we are using the Avro format, the dataframe will be lazily loaded and the data is not retrieved until the display command is used to sample the data set, as shown in the snippet below." }, { "code": null, "e": 69728, "s": 69596, "text": "natality_path = \"gs://dsp_model_store/natality/avro\"natality_df = spark.read.format(\"avro\").load(natality_path)display(natality_df)" }, { "code": null, "e": 70295, "s": 69728, "text": "Before we can use MLlib to build a regression model, we need to perform a few transformations on the data set to select a subset of the features, cast data types, and split records into training and test groups. We’ll also use the fillna function as shown below in order to replace any null values in the dataframe with zeros. For this modeling exercise, we’ll build a regression model that predicts the birth weight of a baby using a few different features including the marriage status of the mother and parent ages. The prepared dataframe is shown in Figure 6.17." }, { "code": null, "e": 70789, "s": 70295, "text": "natality_df.createOrReplaceTempView(\"natality_df\")natality_df = spark.sql(\"\"\"SELECT year, plurality, apgar_5min, mother_age, father_age, gestation_weeks, ever_born ,case when mother_married = true then 1 else 0 end as mother_married ,weight_pounds as weight ,case when rand() < 0.5 then 1 else 0 end as testfrom natality_df \"\"\").fillna(0)trainDF = natality_df.filter(\"test == 0\")testDF = natality_df.filter(\"test == 1\")display(natality_df)" }, { "code": null, "e": 71154, "s": 70789, "text": "Next, we’ll translate our dataframe into the vector data types that MLlib requires as input. The process for transforming the natality data set is shown in the snippet below. After executing the transform function, we now have training and test data sets we can use as input to a regression model. The label we are building a model to predict is the weight column." }, { "code": null, "e": 71481, "s": 71154, "text": "from pyspark.ml.feature import VectorAssembler# create a vector representationassembler = VectorAssembler(inputCols= trainDF.schema.names[0:8], outputCol=\"features\" )trainVec = assembler.transform(trainDF).select('weight','features')testVec = assembler.transform(testDF).select('weight', 'features')" }, { "code": null, "e": 72260, "s": 71481, "text": "MLlib provides a set of utilities for performing cross validation and hyperparameter tuning in a model workflow. The code snippet below shows how to perform this process for a random forest regression model. Instead of calling fit directly on the model object, we wrap the model object with a cross validator object that explores different parameter settings, such as tree depth and number of trees. This workflow is similar to the grid search functions in sklearn. After searching through the parameter space, and using cross validation based on the number of folds, the random forest model is retrained on the complete training data set before being applied to make predictions on the test data set. The result is a dataframe with the actual weight and predicted birth weight." }, { "code": null, "e": 73006, "s": 72260, "text": "from pyspark.ml.tuning import ParamGridBuilder from pyspark.ml.regression import RandomForestRegressorfrom pyspark.ml.tuning import CrossValidatorfrom pyspark.ml.evaluation import RegressionEvaluatorfolds = 3rf_trees = [ 50, 100 ]rf_depth = [ 4, 5 ] rf= RandomForestRegressor(featuresCol='features',labelCol='weight')paramGrid = ParamGridBuilder().addGrid(rf.numTrees, rf_trees). ddGrid(rf.maxDepth, rf_depth).build()crossval = CrossValidator(estimator=rf, estimatorParamMaps = paramGrid, evaluator=RegressionEvaluator( labelCol='weight'), numFolds = folds) rfModel = crossval.fit(trainVec) predsDF = rfModel.transform(testVec).select(\"weight\", \"prediction\") " }, { "code": null, "e": 73371, "s": 73006, "text": "In the final step of our GCP model pipeline, we’ll save the results to GCS, so that other applications or processes in a workflow can make use of the predictions. The code snippet below shows how to write the dataframe to GCS in Avro format. To ensure that different runs of the pipeline do not overwrite past predictions, we append a timestamp to the export path." }, { "code": null, "e": 73581, "s": 73371, "text": "import timeout_path = \"gs://dsp_model_store/natality/preds-{time}/\". format(time = int(time.time()*1000))predsDF.write.mode('overwrite').format(\"avro\").save(out_path)print(out_path)" }, { "code": null, "e": 73982, "s": 73581, "text": "Using GCP components with PySpark took a bit of effort to configure, but in this case we are running Spark in a different cloud provider than where we are reading and writing data. In a production environment, you’ll most likely be running Spark in the same cloud as where you are working with data sets, which means that you can leverage IAM roles for properly managing access to different services." }, { "code": null, "e": 74490, "s": 73982, "text": "Once you’ve tested a batch model pipeline in a notebook environment, there are a few different ways of scheduling the pipeline to run on a regular schedule. For example, you may want a churn prediction model for a mobile game to run every morning and publish the scores to an application database. Similar to the workflow tools we covered in Chapter 5, a PySpark pipeline should have monitoring in place for any failures that may occur. There’s a few different approaches for scheduling PySpark jobs to run:" }, { "code": null, "e": 74588, "s": 74490, "text": "Workflow Tools: Airflow, Azkaban, and Luigi all support running spark jobs as part of a workflow." }, { "code": null, "e": 74662, "s": 74588, "text": "Cloud Tools: EMR on AWS and Dataproc on GCP support scheduled Spark jobs." }, { "code": null, "e": 74757, "s": 74662, "text": "Vendor Tools: Databricks supports setting up job schedules with monitoring through the web UI." }, { "code": null, "e": 74880, "s": 74757, "text": "Spark Submit: If you already have a cluster provisioned, use can issue spark-submit commands using a tool such as crontab." }, { "code": null, "e": 75528, "s": 74880, "text": "Vendor and cloud tools are typically easier to get up and running, because they provide options for provisioning clusters as part of the workflow. For example, with Databricks you can define the type of cluster to spin up for running a notebook on a schedule. When using a workflow tool, such as Airflow, you’ll need to add additional steps to your workflow in order to spin up and terminate clusters. Most workflow tools provide connectors to EMR for managing clusters as part of a workflow. The Spark submit option is useful when first getting started with scheduling Spark jobs, but it’s doesn’t support managing clusters as part of a workflow." }, { "code": null, "e": 76326, "s": 75528, "text": "Spark jobs can run on ephemeral or persistent clusters. An ephemeral cluster is a Spark cluster that is provisioned to perform a set of tasks and then terminated, such as running a churn model pipeline. A persistent cluster is a long-running cluster than may support interactive notebooks, such as the Databricks cluster we set up at the start of this chapter. Persistent clusters are useful for development, but can be expensive if the hardware spun up for the cluster is under utilized. Some vendors support auto scaling of clusters to reduce the costs of long-running persistent clusters. Ephemeral clusters are useful, because spinning up a new cluster to perform a task enables isolation of failure across tasks, and it means that different model pipelines can use different library versions." }, { "code": null, "e": 76856, "s": 76326, "text": "In addition to setting up tools for scheduling jobs and alerting on job failures, it’s useful to set up additional data and model quality checks for Spark model pipelines. For example, I’ve set up Spark jobs that perform audit tasks, such as making sure that an application database has predictions for the current day, and trigger alerts if prediction data is stale. It’s also a good practice to log metrics, such as the ROC of a cross-validated model, as part of a Spark pipeline. We’ll cover this in more detail in Chapter 11." }, { "code": null, "e": 77264, "s": 76856, "text": "PySpark is a powerful tool for data scientists to build scalable analyses and model pipelines. It a highly desirable skill set for companies, because it enables data science teams to own more of the process of building and owning data products. There’s a variety of ways to set up an environment for PySpark, and in this chapter we explored a free notebook environment from one of the popular Spark vendors." }, { "code": null, "e": 77763, "s": 77264, "text": "This chapter focused on batch model pipelines, where the goal is to create a set of predictions for a large number of users on a regular schedule. We explored pipelines for both AWS and GCP deployments, where the data sources and data outputs are data lakes. One of the issues with these types of pipelines is that predictions may be quite stale by the time that a prediction is used. In Chapter 9, we’ll explore streaming pipelines for PySpark, where the latency of model predictions is minimized." }, { "code": null, "e": 78190, "s": 77763, "text": "PySpark is a highly expressive language for authoring model pipelines, because it supports all Python functionality, but does require some workarounds to get code to execute across a cluster of workers nodes. In the next chapter, we’ll explore Dataflow, a runtime for the Apache Beam library, which also enables large-scale distributed Python pipelines, but is more constrained in the types of operations that you can perform." }, { "code": null, "e": 78337, "s": 78190, "text": "Karau, Holden, Andy Konwinski, Patrick Wendell, and Matei Zaharia. 2015. Learning Spark: Lightning-Fast Big Data Analysis. 1st ed. O’Reilly Media." }, { "code": null, "e": 78494, "s": 78337, "text": "13. https://community.cloud.databricks.com/↩︎14. https://www.gamasutra.com/blogs/BenWeber/20190426/340293/↩︎15. https://github.com/spotify/spark-bigquery/↩︎" } ]
C Program for Muller Method
We are given with a function f(x) on a floating number x and we can have three initial guesses for the root of the function. The task is to find the root of the function where f(x) can be any algebraic or transcendental function. What is Muller Method? Muller method was first presented by David E. Muller in 1956. A Muller’s method is root finding algorithm which starts with three initial approximations to find the root and then join them with a second degree polynomial (a parabola), then the quadratic formula is used to find a root of the quadratic for the next approximation. That is if x0, x1 and x 2 are the initial approximations then x3 is obtained by solving the quadratic which is obtained by means of x0, x 1 and x2. Then two values among x0, x1 and x2 which are close to x3 are chosen for the next iteration. Benefit of learning Muller method? Muller method, is one of the root-finding method like bisection method, Regula-Flasi Method, Secant Method etc. having advantages such as − The rate of convergence in Muller method is higher than other methods. Rate of convergence in Muller method is 1.84 whereas it is 1.62 in secant and linear method and 1 for both Regula-flasi and bisection method. Rate of convergence is how much we move closer to the root at each step. So, Muller Method is faster. As it is slower than Newton-Raphson, which has rate of convergence of 2, but the computation of derivate at each step is better in Muller method. Hence, Muller Method is an efficient method. Working of Muller Method − Let us assume three distinct initial roots x0, x1 and x2. Now draw a parabola, through the values of function f(x) for the points- x0, x1 and x2. The equation of the parabola, p(x), will be− p(x )=c+b( x – x 2)+a ( x – x2)2; where a, b and c are the constants. Now, find the intersection of the parabola with the x-axis like x3. How to find the intersection of parabola with the x-axis i.e. x3 −Finding x3, the root of p(x), where, p (x ) = c+b ( x – x 2)+a ( x – x2)2 such that p(x3) = c+b( x3 – x 2)+a ( x3 – x2)2 = 0, apply the quadratic formula to p(x). As we have to take that one which is closer to x2 from the 2 roots, we will use the equation −X3−X2=−2cb±b2−4acnow, as the p(x) should be closer to x2, so we will take that value whose denominator is greater out of two from the above equation.To find a, b and c for the above equation, put x in p(x) as x0, x1, x2 and let these values be p(x0), p(x1) and p(x2) which will be as follows −p (x 0) = c+b ( x0 – x 2)+a ( x0 – x2)2 = f ( x0) p ( x1) = c+b (x 1 – x2)+a( x 1 – x2)2 = f ( x1) p(x 2) = c+b( x 2– x2) + a( x 2–x2)2 = c = f ( x2)So, we have three equations for the three variables-a, b and c.Now put the following expressions for the x3-x2 and obtain the root of p(x) = x3. Finding x3, the root of p(x), where, p (x ) = c+b ( x – x 2)+a ( x – x2)2 such that p(x3) = c+b( x3 – x 2)+a ( x3 – x2)2 = 0, apply the quadratic formula to p(x). As we have to take that one which is closer to x2 from the 2 roots, we will use the equation −X3−X2=−2cb±b2−4acnow, as the p(x) should be closer to x2, so we will take that value whose denominator is greater out of two from the above equation. Finding x3, the root of p(x), where, p (x ) = c+b ( x – x 2)+a ( x – x2)2 such that p(x3) = c+b( x3 – x 2)+a ( x3 – x2)2 = 0, apply the quadratic formula to p(x). As we have to take that one which is closer to x2 from the 2 roots, we will use the equation − now, as the p(x) should be closer to x2, so we will take that value whose denominator is greater out of two from the above equation. To find a, b and c for the above equation, put x in p(x) as x0, x1, x2 and let these values be p(x0), p(x1) and p(x2) which will be as follows −p (x 0) = c+b ( x0 – x 2)+a ( x0 – x2)2 = f ( x0) p ( x1) = c+b (x 1 – x2)+a( x 1 – x2)2 = f ( x1) p(x 2) = c+b( x 2– x2) + a( x 2–x2)2 = c = f ( x2) To find a, b and c for the above equation, put x in p(x) as x0, x1, x2 and let these values be p(x0), p(x1) and p(x2) which will be as follows − p (x 0) = c+b ( x0 – x 2)+a ( x0 – x2)2 = f ( x0) p ( x1) = c+b (x 1 – x2)+a( x 1 – x2)2 = f ( x1) p(x 2) = c+b( x 2– x2) + a( x 2–x2)2 = c = f ( x2) So, we have three equations for the three variables-a, b and c.Now put the following expressions for the x3-x2 and obtain the root of p(x) = x3. So, we have three equations for the three variables-a, b and c. Now put the following expressions for the x3-x2 and obtain the root of p(x) = x3. If x3 is very much closer to x2 then x3 becomes the root of f(x), else repeat the process of finding the next x3, form the previous x1, x2, x3 as the new x0, x1, x2. Input: a = 1, b = 3, c = 2 Output: The root is 1.368809 Input: a = 1, b = 5, c = 3 Output: The root is 3.000001 Start Step 1-> Declare and initialize a const MAX = 10000; Step 2-> In Function float f(float x) Return 1*pow(x, 3) + 2*x*x + 10*x – 20 Step 3-> In function int muller(float a, float b, float c) Declare i,result Loop For i = 0 and ++i Initialize f1 = result returned from calling function f(a) Initialize f2 = result returned from calling function f(b) Initialize f3 = result returned from calling function f(c) Set d1 = f1 - f3 Set d2 = f2 - f3 Set h1 = a - c Set h2 = b - c Set a0 = f3 Set a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2))) / ((h1*h2) * (h1-h2))) Set a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))) Set x = ((-2*a0) / (a1 + abs(sqrt(a1*a1-4*a0*a2)))) Set y = ((-2*a0) / (a1-abs(sqrt(a1*a1-4*a0*a2)))) If x >= y result = x + c Else result = y + c End if Set m = result*100 Set n = c*100 Set m = floor(m) and n = floor(n) If m == n Break End If Set a = b and b = c and c = result If i > MAX Print “Root can't be found using Muller method” Break End If End for If i <= MAX Print result Step 4-> In function int main() Declare and initialize the inputs a = 1, b = 3, c = 2 Call the function muller(a, b, c) Stop Live Demo #include <stdio.h> #include <math.h> const int MAX = 10000; //this function to find f(n) float f(float x) { // f(x) = x ^ 3 + 2x ^ 2 + 10x - 20 return 1*pow(x, 3) + 2*x*x + 10*x - 20; } int muller(float a, float b, float c) { int i; float result; for (i = 0;;++i) { // Calculating various constants required // to calculate x3 float f1 = f(a); float f2 = f(b); float f3 = f(c); float d1 = f1 - f3; float d2 = f2 - f3; float h1 = a - c; float h2 = b - c; float a0 = f3; float a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2))) / ((h1*h2) * (h1-h2))); float a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2))); float x = ((-2*a0) / (a1 + abs(sqrt(a1*a1-4*a0*a2)))); float y = ((-2*a0) / (a1-abs(sqrt(a1*a1-4*a0*a2)))); // Taking the root which is closer to x2 if (x >= y) result = x + c; else result = y + c; // checking for resemblance of x3 with x2 till // two decimal places float m = result*100; float n = c*100; m = floor(m); n = floor(n); if (m == n) break; a = b; b = c; c = result; if (i > MAX) { printf("Root can't be found using Muller method\n"); break; } } if (i <= MAX) printf("The root is %f", result); return 0; } // main function int main() { float a = 1, b = 3, c = 2; muller(a, b, c); return 0; } The root is 1.368809
[ { "code": null, "e": 1292, "s": 1062, "text": "We are given with a function f(x) on a floating number x and we can have three initial guesses for the root of the function. The task is to find the root of the function where f(x) can be any algebraic or transcendental function." }, { "code": null, "e": 1315, "s": 1292, "text": "What is Muller Method?" }, { "code": null, "e": 1886, "s": 1315, "text": "Muller method was first presented by David E. Muller in 1956. A Muller’s method is root finding algorithm which starts with three initial approximations to find the root and then join them with a second degree polynomial (a parabola), then the quadratic formula is used to find a root of the quadratic for the next approximation. That is if x0, x1 and x 2 are the initial approximations then x3 is obtained by solving the quadratic which is obtained by means of x0, x 1 and x2. Then two values among x0, x1 and x2 which are close to x3 are chosen for the next iteration." }, { "code": null, "e": 1921, "s": 1886, "text": "Benefit of learning Muller method?" }, { "code": null, "e": 2061, "s": 1921, "text": "Muller method, is one of the root-finding method like bisection method, Regula-Flasi Method, Secant Method etc. having advantages such as −" }, { "code": null, "e": 2376, "s": 2061, "text": "The rate of convergence in Muller method is higher than other methods. Rate of convergence in Muller method is 1.84 whereas it is 1.62 in secant and linear method and 1 for both Regula-flasi and bisection method. Rate of convergence is how much we move closer to the root at each step. So, Muller Method is faster." }, { "code": null, "e": 2567, "s": 2376, "text": "As it is slower than Newton-Raphson, which has rate of convergence of 2, but the computation of derivate at each step is better in Muller method.\nHence, Muller Method is an efficient method." }, { "code": null, "e": 2594, "s": 2567, "text": "Working of Muller Method −" }, { "code": null, "e": 2652, "s": 2594, "text": "Let us assume three distinct initial roots x0, x1 and x2." }, { "code": null, "e": 2740, "s": 2652, "text": "Now draw a parabola, through the values of function f(x) for the points- x0, x1 and x2." }, { "code": null, "e": 2785, "s": 2740, "text": "The equation of the parabola, p(x), will be−" }, { "code": null, "e": 2855, "s": 2785, "text": "p(x )=c+b( x – x 2)+a ( x – x2)2; where a, b and c are the constants." }, { "code": null, "e": 2923, "s": 2855, "text": "Now, find the intersection of the parabola with the x-axis like x3." }, { "code": null, "e": 3833, "s": 2923, "text": "How to find the intersection of parabola with the x-axis i.e. x3 −Finding x3, the root of p(x), where, p (x ) = c+b ( x – x 2)+a ( x – x2)2 such that p(x3) = c+b( x3 – x 2)+a ( x3 – x2)2 = 0, apply the quadratic formula to p(x). As we have to take that one which is closer to x2 from the 2 roots, we will use the equation −X3−X2=−2cb±b2−4acnow, as the p(x) should be closer to x2, so we will take that value whose denominator is greater out of two from the above equation.To find a, b and c for the above equation, put x in p(x) as x0, x1, x2 and let these values be p(x0), p(x1) and p(x2) which will be as follows −p (x 0) = c+b ( x0 – x 2)+a ( x0 – x2)2 = f ( x0) p ( x1) = c+b (x 1 – x2)+a( x 1 – x2)2 = f ( x1)\np(x 2) = c+b( x 2– x2) + a( x 2–x2)2 = c = f ( x2)So, we have three equations for the three variables-a, b and c.Now put the following expressions for the x3-x2 and obtain the root of p(x) = x3." }, { "code": null, "e": 4240, "s": 3833, "text": "Finding x3, the root of p(x), where, p (x ) = c+b ( x – x 2)+a ( x – x2)2 such that p(x3) = c+b( x3 – x 2)+a ( x3 – x2)2 = 0, apply the quadratic formula to p(x). As we have to take that one which is closer to x2 from the 2 roots, we will use the equation −X3−X2=−2cb±b2−4acnow, as the p(x) should be closer to x2, so we will take that value whose denominator is greater out of two from the above equation." }, { "code": null, "e": 4498, "s": 4240, "text": "Finding x3, the root of p(x), where, p (x ) = c+b ( x – x 2)+a ( x – x2)2 such that p(x3) = c+b( x3 – x 2)+a ( x3 – x2)2 = 0, apply the quadratic formula to p(x). As we have to take that one which is closer to x2 from the 2 roots, we will use the equation −" }, { "code": null, "e": 4631, "s": 4498, "text": "now, as the p(x) should be closer to x2, so we will take that value whose denominator is greater out of two from the above equation." }, { "code": null, "e": 4925, "s": 4631, "text": "To find a, b and c for the above equation, put x in p(x) as x0, x1, x2 and let these values be p(x0), p(x1) and p(x2) which will be as follows −p (x 0) = c+b ( x0 – x 2)+a ( x0 – x2)2 = f ( x0) p ( x1) = c+b (x 1 – x2)+a( x 1 – x2)2 = f ( x1)\np(x 2) = c+b( x 2– x2) + a( x 2–x2)2 = c = f ( x2)" }, { "code": null, "e": 5070, "s": 4925, "text": "To find a, b and c for the above equation, put x in p(x) as x0, x1, x2 and let these values be p(x0), p(x1) and p(x2) which will be as follows −" }, { "code": null, "e": 5220, "s": 5070, "text": "p (x 0) = c+b ( x0 – x 2)+a ( x0 – x2)2 = f ( x0) p ( x1) = c+b (x 1 – x2)+a( x 1 – x2)2 = f ( x1)\np(x 2) = c+b( x 2– x2) + a( x 2–x2)2 = c = f ( x2)" }, { "code": null, "e": 5365, "s": 5220, "text": "So, we have three equations for the three variables-a, b and c.Now put the following expressions for the x3-x2 and obtain the root of p(x) = x3." }, { "code": null, "e": 5429, "s": 5365, "text": "So, we have three equations for the three variables-a, b and c." }, { "code": null, "e": 5511, "s": 5429, "text": "Now put the following expressions for the x3-x2 and obtain the root of p(x) = x3." }, { "code": null, "e": 5677, "s": 5511, "text": "If x3 is very much closer to x2 then x3 becomes the root of f(x), else repeat the process of finding the next x3, form the previous x1, x2, x3 as the new x0, x1, x2." }, { "code": null, "e": 5790, "s": 5677, "text": "Input: a = 1, b = 3, c = 2\nOutput: The root is 1.368809\n\nInput: a = 1, b = 5, c = 3\nOutput: The root is 3.000001" }, { "code": null, "e": 7093, "s": 5790, "text": "Start\nStep 1-> Declare and initialize a const MAX = 10000;\nStep 2-> In Function float f(float x)\n Return 1*pow(x, 3) + 2*x*x + 10*x – 20\nStep 3-> In function int muller(float a, float b, float c)\n Declare i,result\n Loop For i = 0 and ++i\n Initialize f1 = result returned from calling function f(a)\n Initialize f2 = result returned from calling function f(b)\n Initialize f3 = result returned from calling function f(c)\n Set d1 = f1 - f3\n Set d2 = f2 - f3\n Set h1 = a - c\n Set h2 = b - c\n Set a0 = f3\n Set a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2))) / ((h1*h2) * (h1-h2)))\n Set a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2)))\n Set x = ((-2*a0) / (a1 + abs(sqrt(a1*a1-4*a0*a2))))\n Set y = ((-2*a0) / (a1-abs(sqrt(a1*a1-4*a0*a2))))\n If x >= y\n result = x + c\n Else\n result = y + c\n End if\n Set m = result*100\n Set n = c*100\n Set m = floor(m) and n = floor(n)\n If m == n\n Break\n End If\n Set a = b and b = c and c = result\n If i > MAX\n Print “Root can't be found using Muller method”\n Break\n End If\n End for\n If i <= MAX\n Print result\nStep 4-> In function int main()\n Declare and initialize the inputs a = 1, b = 3, c = 2\n Call the function muller(a, b, c)\nStop" }, { "code": null, "e": 7104, "s": 7093, "text": " Live Demo" }, { "code": null, "e": 8600, "s": 7104, "text": "#include <stdio.h>\n#include <math.h>\nconst int MAX = 10000;\n//this function to find f(n)\nfloat f(float x) {\n // f(x) = x ^ 3 + 2x ^ 2 + 10x - 20\n return 1*pow(x, 3) + 2*x*x + 10*x - 20;\n}\nint muller(float a, float b, float c) {\n int i;\n float result;\n for (i = 0;;++i) {\n // Calculating various constants required\n // to calculate x3\n float f1 = f(a);\n float f2 = f(b);\n float f3 = f(c);\n float d1 = f1 - f3;\n float d2 = f2 - f3;\n float h1 = a - c;\n float h2 = b - c;\n float a0 = f3;\n float a1 = (((d2*pow(h1, 2)) - (d1*pow(h2, 2))) / ((h1*h2) * (h1-h2)));\n float a2 = (((d1*h2) - (d2*h1))/((h1*h2) * (h1-h2)));\n float x = ((-2*a0) / (a1 + abs(sqrt(a1*a1-4*a0*a2))));\n float y = ((-2*a0) / (a1-abs(sqrt(a1*a1-4*a0*a2))));\n // Taking the root which is closer to x2\n if (x >= y)\n result = x + c;\n else\n result = y + c;\n // checking for resemblance of x3 with x2 till\n // two decimal places\n float m = result*100;\n float n = c*100;\n m = floor(m);\n n = floor(n);\n if (m == n)\n break;\n a = b;\n b = c;\n c = result;\n if (i > MAX) {\n printf(\"Root can't be found using Muller method\\n\");\n break;\n }\n }\n if (i <= MAX)\n printf(\"The root is %f\", result);\n return 0;\n}\n// main function\nint main() {\n float a = 1, b = 3, c = 2;\n muller(a, b, c);\n return 0;\n}" }, { "code": null, "e": 8621, "s": 8600, "text": "The root is 1.368809" } ]
Java public Keyword
❮ Java Keywords Second accesses a public Main class with public attributes: /* Code from filename: Main.java public class Main { public String fname = "John"; public String lname = "Doe"; public String email = "[email protected]"; public int age = 24; } */ class Second { public static void main(String[] args) { Main myObj = new Main(); System.out.println("Name: " + myObj.fname + " " + myObj.lname); System.out.println("Email: " + myObj.email); System.out.println("Age: " + myObj.age); } } Try it Yourself » The public keyword is an access modifier used for classes, attributes, methods and constructors, making them accessible by any other class. Read more about modifiers in our Java Modifiers Tutorial. ❮ Java Keywords 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": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 79, "s": 18, "text": "Second accesses a public \nMain class with public attributes:" }, { "code": null, "e": 520, "s": 79, "text": "/* Code from filename: Main.java\npublic class Main {\n public String fname = \"John\";\n public String lname = \"Doe\";\n public String email = \"[email protected]\";\n public int age = 24;\n}\n*/\n\nclass Second {\n public static void main(String[] args) {\n Main myObj = new Main();\n System.out.println(\"Name: \" + myObj.fname + \" \" + myObj.lname);\n System.out.println(\"Email: \" + myObj.email);\n System.out.println(\"Age: \" + myObj.age);\n }\n}\n" }, { "code": null, "e": 540, "s": 520, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 680, "s": 540, "text": "The public keyword is an access modifier used for classes, attributes, methods and constructors, making them accessible by any other class." }, { "code": null, "e": 738, "s": 680, "text": "Read more about modifiers in our Java Modifiers Tutorial." }, { "code": null, "e": 756, "s": 738, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 789, "s": 756, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 831, "s": 789, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 938, "s": 831, "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": 957, "s": 938, "text": "[email protected]" } ]
Building Custom Callbacks with Keras and TensorFlow 2 | by B. Chen | Towards Data Science
Callbacks are an important type of object in Keras and TensorFlow. They are designed to be able to monitor the model performance in metrics at certain points in the training run and perform some actions that might depend on those performances in metric values. Keras has provided a number of built-in callbacks, for example, EarlyStopping, CSVLogger, ModelCheckpoint, LearningRateScheduler etc. Apart from these popular built-in callbacks, there is a base class called Callback which allows us to create our own callbacks and perform some custom actions. In this article, you will learn what is the Callback base class, what it can do, and how to build your own callbacks. If you want to learn more about those built-in callbacks, please check out the following article: towardsdatascience.com Here is the outline of this article. What is the Callback base class? Creating a model for demonstration 1. Building a custom callback for training 2. Building a custom callback for testing 3. Building a custom callback for prediction 4. Custom callback applications Please check out Notebook for the source code. In TensorFlow, all callbacks are stored in the tensorflow.keras.callbacks module. Inside that module, there is a base class called Callback which all other callbacks inherit from. You can also subclass the Callback base class yourself to create your own callbacks. The base class Callback is constructed with the following methods that will be called at the appropriate time. Global methods on_(train|test|predict)_begin(self, logs=None) : called at the beginning of fit(), evaluate(), and predict(). on_(train|test|predict)_end(self, logs=None) : called at the end of fit(), evaluate(), and predict(). Batch-level method (training, testing, and predicting) on_(train|test|predict)_batch_begin(self, batch, logs=None): Called right before processing a batch during training/testing/predicting. on_(train|test|predict)_batch_end(self, batch, logs=None): Called at the end of training/testing/predicting a batch. Within this method, logs is a dict containing the metrics results. Epoch-level method (training only) on_epoch_begin(self, epoch, logs=None): Called at the beginning of an epoch during training. on_epoch_end(self, epoch, logs=None): Called at the end of an epoch during training. For the demonstration purpose, we will build an image classifier to tackle Fashion MNIST, which is a dataset that has 70,000 grayscale images of 28-by-28 pixels with 10 classes. Keras provides some utility functions to fetch and load common datasets, including Fashion MNIST. Let’s load Fashion MNIST fashion_mnist = keras.datasets.fashion_mnist(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data() The dataset is already split into a training set and a test set. Here is the shape and data type of the training set: >>> X_train_full.shape(60000, 28, 28)>>> X_train_full.dtypedtype('uint8') We are going to train the neural network using Gradient Descent, we must scale the input feature down to the 0–1 range. And for faster training on a local machine, let’s just use the first 10,000 images. X_train, y_train = X_train_full[:10000]/255.0, y_train_full[:10000] Now let’s build the neural network! There are 3 ways to create a machine learning model with Keras and TensorFlow 2.0. Since we are building a simple fully connected neural network and for simplicity, let’s use the easiest way: Sequential Model with Sequential(). from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Flattendef create_model(): model = Sequential([ Flatten(input_shape=(28, 28)), Dense(300, activation='relu'), Dense(100, activation='relu'), Dense(10, activation='softmax'), ]) model.compile( optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) return model Our model has the following specifications: The first layer (also known as the input layer) has the input_shape to set the input size (28, 28) which matches the training data. The input layer is a Flatten layer whose role is simply to convert each input image into a 1D array. And then it is followed by 2 Dense layers, one with 300 units, and the other with 100 units. Both of them use the relu activation function. The output Dense layer has 10 units and the softmax activation function. model = create_model()model.summary() Firstly, let’s import the base class Callback from tensorflow.keras.callbacks import Callback Then, we create a new class TrainningCallback() with the methods that will be called at the training time. class TrainingCallback(Callback): def on_train_begin(self, logs=None): print("Starting training...") def on_epoch_begin(self, epoch, logs=None): print(f"Starting epoch {epoch}") def on_train_batch_begin(self, batch, logs=None): print(f"Training: Starting batch {batch}") def on_train_batch_end(self, batch, logs=None): print(f"Training: Finished batch {batch}, loss is {logs['loss']}") def on_epoch_end(self, epoch, logs=None): print(f"Finished epoch {epoch}, loss is {logs['loss']}, accuracy is {logs['accuracy']}") def on_train_end(self, logs=None): print("Finished training") Next, to use it for training, we just need to pass TrainingCallback() to the callbacks argument in the model.fit() method. history = model.fit( X_train, y_train, epochs=2, validation_split=0.20, batch_size=4000, // A large value for demo purpose verbose=2, callbacks=[TrainingCallback()]) We can see that TrainingCallback() get passed in a list to the callbacks argument. It is a list because in practice we might be passing a number of callbacks for performing different tasks, for example, debugging, learning rate schedules, or any other built-in callbacks. By executing the statement, you should get an output like below: Similarly, we can implement a custom callback TestingCallback() for testing. class TestingCallback(Callback): def on_test_begin(self, logs=None): print("Starting testing ...") def on_test_batch_begin(self, batch, logs=None): print(f"Testing: Starting batch {batch}") def on_test_batch_end(self, batch, logs=None): print(f"Testing: Finished batch {batch}") def on_test_end(self, logs=None): print("Finished testing") To use it for testing, pass it to the callbacks argument in the model.valutate() method. model.evaluate( X_test, y_test, verbose=False, callbacks=[TestingCallback()], batch_size=2000, // A large value for demo purpose) By executing the statement, you should get an output like below: Starting testing ...Testing: Starting batch 0Testing: Finished batch 0Testing: Starting batch 1Testing: Finished batch 1Testing: Starting batch 2Testing: Finished batch 2Testing: Starting batch 3Testing: Finished batch 3Testing: Starting batch 4Testing: Finished batch 4Finished testing[85.61210479736329, 0.8063] Similarly, we can implement a custom callback PredictionCallback() for prediction. class PredictionCallback(Callback): def on_predict_begin(self, logs=None): print("Starting prediction ...") def on_predict_batch_begin(self, batch, logs=None): print(f"Prediction: Starting batch {batch}") def on_predict_batch_end(self, batch, logs=None): print(f"Prediction: Finish batch {batch}") def on_predict_end(self, logs=None): print("Finished prediction") To use it for prediction, we just need to pass it to the callbacks argument in the model.predict() method. model.predict( X_test, verbose=False, callbacks=[PredictionCallback()], batch_size=2000, // A large value for demo purpose) By executing the statement, you should get an output like below: Starting prediction ...Prediction: Starting batch 0Prediction: Finish batch 0Prediction: Starting batch 1Prediction: Finish batch 1Prediction: Starting batch 2Prediction: Finish batch 2Prediction: Starting batch 3Prediction: Finish batch 3Prediction: Starting batch 4Prediction: Finish batch 4Finished predictionarray([......]) A main application of callback is to perform some actions depend on performance metrics, for example: Real-time plotting during training Stop training when a metric has stopped improving Save model at the end of every epoch Adjust learning rate (or other hyperparameters) according to a defined schedule etc In this section, we are going to show you some examples of Keras custom callback applications. Real-time plotting during training Early stopping at minimum loss Learning rate scheduling This first example shows the creation of a Callback that shows a live, real-time update of loss as your training progresses. import numpy as npimport tensorflow as tffig = plt.figure(figsize=(12,4))# Create plot inside the figureax = fig.add_subplot()ax.set_xlabel('Epoch #')ax.set_ylabel('loss')class TrainingPlot(tf.keras.callbacks.Callback): def on_train_begin(self, logs={}): # Initialize the lists for holding losses self.losses = [] def on_epoch_end(self, epoch, logs={}): # Append the losses to the lists self.losses.append(logs['loss']) # Plot epochs = np.arange(0, len(self.losses)) ax.plot(epochs, self.losses, "b-") fig.canvas.draw() self.losses=[] is initialized in on_train_begin() for holding losses. The real-time plot is implemented at the end of each epochon_epoch_end() by calling ax.plot(epochs, self.losses, "b-") and fig.canvas.draw() . To use it for training, we just need to pass it to the callbacks argument in the model.fit() method. model = create_model()history = model.fit( X_train, y_train, epochs=20, validation_split=0.20, batch_size=64, verbose=2, callbacks=[TrainingPlot()]) By executing the statement, you should get a live real-time output like below: Note: this example is originally from Keras guide “Writing your own callbacks”, please check out the official documentation for details. This example shows the creation of a Callback that stops training when the minimum of loss has been reached, by setting the attribute self.model.stop_training (boolean). Optionally, you can provide an argument patience to specify how many epochs we should wait before stopping after having reached a local minimum. To use it for training: model = create_model()history = model.fit( X_train, y_train, epochs=50, validation_split=0.20, batch_size=64, verbose=2, callbacks=[EarlyStoppingAtMinLoss()]) In this run, our training was stopped at epoch 28 as the minimum of loss has been reached Note: this example is originally from Keras guide “Writing your own callbacks”, please check out the official documentation for details. This example shows how a custom Callback can be used to dynamically change the learning rate of the optimizer during the course of training. To use it model = create_model()history = model.fit( X_train, y_train, epochs=15, validation_split=0.20, batch_size=64, verbose=2, callbacks=[CustomLearningRateScheduler(lr_schedule)]) Keras provides a base class called Callback which allows us to subclass it and create our own callbacks. It is really useful for debugging and perform some actions depend on performance metrics. I hope this article will help you to save time in creating your own custom callback and perform some custom actions. I recommend you to check out the documentation for the Callbacks API and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. A practical introduction to Keras Callbacks in TensorFlow 2 Learning Rate Schedules in practice The Google’s 7 steps of Machine Learning in practice: a TensorFlow example for structured data 3 ways to create a Machine Learning Model with Keras and TensorFlow 2.0 Batch normalization in practice: an example with Keras and TensorFlow 2.0 Early stopping in Practice: an example with Keras and TensorFlow More can be found from my Github
[ { "code": null, "e": 433, "s": 172, "text": "Callbacks are an important type of object in Keras and TensorFlow. They are designed to be able to monitor the model performance in metrics at certain points in the training run and perform some actions that might depend on those performances in metric values." }, { "code": null, "e": 845, "s": 433, "text": "Keras has provided a number of built-in callbacks, for example, EarlyStopping, CSVLogger, ModelCheckpoint, LearningRateScheduler etc. Apart from these popular built-in callbacks, there is a base class called Callback which allows us to create our own callbacks and perform some custom actions. In this article, you will learn what is the Callback base class, what it can do, and how to build your own callbacks." }, { "code": null, "e": 943, "s": 845, "text": "If you want to learn more about those built-in callbacks, please check out the following article:" }, { "code": null, "e": 966, "s": 943, "text": "towardsdatascience.com" }, { "code": null, "e": 1003, "s": 966, "text": "Here is the outline of this article." }, { "code": null, "e": 1036, "s": 1003, "text": "What is the Callback base class?" }, { "code": null, "e": 1071, "s": 1036, "text": "Creating a model for demonstration" }, { "code": null, "e": 1114, "s": 1071, "text": "1. Building a custom callback for training" }, { "code": null, "e": 1156, "s": 1114, "text": "2. Building a custom callback for testing" }, { "code": null, "e": 1201, "s": 1156, "text": "3. Building a custom callback for prediction" }, { "code": null, "e": 1233, "s": 1201, "text": "4. Custom callback applications" }, { "code": null, "e": 1280, "s": 1233, "text": "Please check out Notebook for the source code." }, { "code": null, "e": 1545, "s": 1280, "text": "In TensorFlow, all callbacks are stored in the tensorflow.keras.callbacks module. Inside that module, there is a base class called Callback which all other callbacks inherit from. You can also subclass the Callback base class yourself to create your own callbacks." }, { "code": null, "e": 1656, "s": 1545, "text": "The base class Callback is constructed with the following methods that will be called at the appropriate time." }, { "code": null, "e": 1671, "s": 1656, "text": "Global methods" }, { "code": null, "e": 1781, "s": 1671, "text": "on_(train|test|predict)_begin(self, logs=None) : called at the beginning of fit(), evaluate(), and predict()." }, { "code": null, "e": 1883, "s": 1781, "text": "on_(train|test|predict)_end(self, logs=None) : called at the end of fit(), evaluate(), and predict()." }, { "code": null, "e": 1938, "s": 1883, "text": "Batch-level method (training, testing, and predicting)" }, { "code": null, "e": 2074, "s": 1938, "text": "on_(train|test|predict)_batch_begin(self, batch, logs=None): Called right before processing a batch during training/testing/predicting." }, { "code": null, "e": 2258, "s": 2074, "text": "on_(train|test|predict)_batch_end(self, batch, logs=None): Called at the end of training/testing/predicting a batch. Within this method, logs is a dict containing the metrics results." }, { "code": null, "e": 2293, "s": 2258, "text": "Epoch-level method (training only)" }, { "code": null, "e": 2386, "s": 2293, "text": "on_epoch_begin(self, epoch, logs=None): Called at the beginning of an epoch during training." }, { "code": null, "e": 2471, "s": 2386, "text": "on_epoch_end(self, epoch, logs=None): Called at the end of an epoch during training." }, { "code": null, "e": 2649, "s": 2471, "text": "For the demonstration purpose, we will build an image classifier to tackle Fashion MNIST, which is a dataset that has 70,000 grayscale images of 28-by-28 pixels with 10 classes." }, { "code": null, "e": 2772, "s": 2649, "text": "Keras provides some utility functions to fetch and load common datasets, including Fashion MNIST. Let’s load Fashion MNIST" }, { "code": null, "e": 2891, "s": 2772, "text": "fashion_mnist = keras.datasets.fashion_mnist(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()" }, { "code": null, "e": 3009, "s": 2891, "text": "The dataset is already split into a training set and a test set. Here is the shape and data type of the training set:" }, { "code": null, "e": 3083, "s": 3009, "text": ">>> X_train_full.shape(60000, 28, 28)>>> X_train_full.dtypedtype('uint8')" }, { "code": null, "e": 3287, "s": 3083, "text": "We are going to train the neural network using Gradient Descent, we must scale the input feature down to the 0–1 range. And for faster training on a local machine, let’s just use the first 10,000 images." }, { "code": null, "e": 3355, "s": 3287, "text": "X_train, y_train = X_train_full[:10000]/255.0, y_train_full[:10000]" }, { "code": null, "e": 3619, "s": 3355, "text": "Now let’s build the neural network! There are 3 ways to create a machine learning model with Keras and TensorFlow 2.0. Since we are building a simple fully connected neural network and for simplicity, let’s use the easiest way: Sequential Model with Sequential()." }, { "code": null, "e": 4060, "s": 3619, "text": "from tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Dense, Flattendef create_model(): model = Sequential([ Flatten(input_shape=(28, 28)), Dense(300, activation='relu'), Dense(100, activation='relu'), Dense(10, activation='softmax'), ]) model.compile( optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) return model" }, { "code": null, "e": 4104, "s": 4060, "text": "Our model has the following specifications:" }, { "code": null, "e": 4337, "s": 4104, "text": "The first layer (also known as the input layer) has the input_shape to set the input size (28, 28) which matches the training data. The input layer is a Flatten layer whose role is simply to convert each input image into a 1D array." }, { "code": null, "e": 4477, "s": 4337, "text": "And then it is followed by 2 Dense layers, one with 300 units, and the other with 100 units. Both of them use the relu activation function." }, { "code": null, "e": 4550, "s": 4477, "text": "The output Dense layer has 10 units and the softmax activation function." }, { "code": null, "e": 4588, "s": 4550, "text": "model = create_model()model.summary()" }, { "code": null, "e": 4634, "s": 4588, "text": "Firstly, let’s import the base class Callback" }, { "code": null, "e": 4682, "s": 4634, "text": "from tensorflow.keras.callbacks import Callback" }, { "code": null, "e": 4789, "s": 4682, "text": "Then, we create a new class TrainningCallback() with the methods that will be called at the training time." }, { "code": null, "e": 5460, "s": 4789, "text": "class TrainingCallback(Callback): def on_train_begin(self, logs=None): print(\"Starting training...\") def on_epoch_begin(self, epoch, logs=None): print(f\"Starting epoch {epoch}\") def on_train_batch_begin(self, batch, logs=None): print(f\"Training: Starting batch {batch}\") def on_train_batch_end(self, batch, logs=None): print(f\"Training: Finished batch {batch}, loss is {logs['loss']}\") def on_epoch_end(self, epoch, logs=None): print(f\"Finished epoch {epoch}, loss is {logs['loss']}, accuracy is {logs['accuracy']}\") def on_train_end(self, logs=None): print(\"Finished training\")" }, { "code": null, "e": 5583, "s": 5460, "text": "Next, to use it for training, we just need to pass TrainingCallback() to the callbacks argument in the model.fit() method." }, { "code": null, "e": 5776, "s": 5583, "text": "history = model.fit( X_train, y_train, epochs=2, validation_split=0.20, batch_size=4000, // A large value for demo purpose verbose=2, callbacks=[TrainingCallback()])" }, { "code": null, "e": 6048, "s": 5776, "text": "We can see that TrainingCallback() get passed in a list to the callbacks argument. It is a list because in practice we might be passing a number of callbacks for performing different tasks, for example, debugging, learning rate schedules, or any other built-in callbacks." }, { "code": null, "e": 6113, "s": 6048, "text": "By executing the statement, you should get an output like below:" }, { "code": null, "e": 6190, "s": 6113, "text": "Similarly, we can implement a custom callback TestingCallback() for testing." }, { "code": null, "e": 6593, "s": 6190, "text": "class TestingCallback(Callback): def on_test_begin(self, logs=None): print(\"Starting testing ...\") def on_test_batch_begin(self, batch, logs=None): print(f\"Testing: Starting batch {batch}\") def on_test_batch_end(self, batch, logs=None): print(f\"Testing: Finished batch {batch}\") def on_test_end(self, logs=None): print(\"Finished testing\")" }, { "code": null, "e": 6682, "s": 6593, "text": "To use it for testing, pass it to the callbacks argument in the model.valutate() method." }, { "code": null, "e": 6831, "s": 6682, "text": "model.evaluate( X_test, y_test, verbose=False, callbacks=[TestingCallback()], batch_size=2000, // A large value for demo purpose)" }, { "code": null, "e": 6896, "s": 6831, "text": "By executing the statement, you should get an output like below:" }, { "code": null, "e": 7210, "s": 6896, "text": "Starting testing ...Testing: Starting batch 0Testing: Finished batch 0Testing: Starting batch 1Testing: Finished batch 1Testing: Starting batch 2Testing: Finished batch 2Testing: Starting batch 3Testing: Finished batch 3Testing: Starting batch 4Testing: Finished batch 4Finished testing[85.61210479736329, 0.8063]" }, { "code": null, "e": 7293, "s": 7210, "text": "Similarly, we can implement a custom callback PredictionCallback() for prediction." }, { "code": null, "e": 7717, "s": 7293, "text": "class PredictionCallback(Callback): def on_predict_begin(self, logs=None): print(\"Starting prediction ...\") def on_predict_batch_begin(self, batch, logs=None): print(f\"Prediction: Starting batch {batch}\") def on_predict_batch_end(self, batch, logs=None): print(f\"Prediction: Finish batch {batch}\") def on_predict_end(self, logs=None): print(\"Finished prediction\")" }, { "code": null, "e": 7824, "s": 7717, "text": "To use it for prediction, we just need to pass it to the callbacks argument in the model.predict() method." }, { "code": null, "e": 7964, "s": 7824, "text": "model.predict( X_test, verbose=False, callbacks=[PredictionCallback()], batch_size=2000, // A large value for demo purpose)" }, { "code": null, "e": 8029, "s": 7964, "text": "By executing the statement, you should get an output like below:" }, { "code": null, "e": 8357, "s": 8029, "text": "Starting prediction ...Prediction: Starting batch 0Prediction: Finish batch 0Prediction: Starting batch 1Prediction: Finish batch 1Prediction: Starting batch 2Prediction: Finish batch 2Prediction: Starting batch 3Prediction: Finish batch 3Prediction: Starting batch 4Prediction: Finish batch 4Finished predictionarray([......])" }, { "code": null, "e": 8459, "s": 8357, "text": "A main application of callback is to perform some actions depend on performance metrics, for example:" }, { "code": null, "e": 8494, "s": 8459, "text": "Real-time plotting during training" }, { "code": null, "e": 8544, "s": 8494, "text": "Stop training when a metric has stopped improving" }, { "code": null, "e": 8581, "s": 8544, "text": "Save model at the end of every epoch" }, { "code": null, "e": 8661, "s": 8581, "text": "Adjust learning rate (or other hyperparameters) according to a defined schedule" }, { "code": null, "e": 8665, "s": 8661, "text": "etc" }, { "code": null, "e": 8760, "s": 8665, "text": "In this section, we are going to show you some examples of Keras custom callback applications." }, { "code": null, "e": 8795, "s": 8760, "text": "Real-time plotting during training" }, { "code": null, "e": 8826, "s": 8795, "text": "Early stopping at minimum loss" }, { "code": null, "e": 8851, "s": 8826, "text": "Learning rate scheduling" }, { "code": null, "e": 8976, "s": 8851, "text": "This first example shows the creation of a Callback that shows a live, real-time update of loss as your training progresses." }, { "code": null, "e": 9570, "s": 8976, "text": "import numpy as npimport tensorflow as tffig = plt.figure(figsize=(12,4))# Create plot inside the figureax = fig.add_subplot()ax.set_xlabel('Epoch #')ax.set_ylabel('loss')class TrainingPlot(tf.keras.callbacks.Callback): def on_train_begin(self, logs={}): # Initialize the lists for holding losses self.losses = [] def on_epoch_end(self, epoch, logs={}): # Append the losses to the lists self.losses.append(logs['loss']) # Plot epochs = np.arange(0, len(self.losses)) ax.plot(epochs, self.losses, \"b-\") fig.canvas.draw()" }, { "code": null, "e": 9783, "s": 9570, "text": "self.losses=[] is initialized in on_train_begin() for holding losses. The real-time plot is implemented at the end of each epochon_epoch_end() by calling ax.plot(epochs, self.losses, \"b-\") and fig.canvas.draw() ." }, { "code": null, "e": 9884, "s": 9783, "text": "To use it for training, we just need to pass it to the callbacks argument in the model.fit() method." }, { "code": null, "e": 10059, "s": 9884, "text": "model = create_model()history = model.fit( X_train, y_train, epochs=20, validation_split=0.20, batch_size=64, verbose=2, callbacks=[TrainingPlot()])" }, { "code": null, "e": 10138, "s": 10059, "text": "By executing the statement, you should get a live real-time output like below:" }, { "code": null, "e": 10275, "s": 10138, "text": "Note: this example is originally from Keras guide “Writing your own callbacks”, please check out the official documentation for details." }, { "code": null, "e": 10590, "s": 10275, "text": "This example shows the creation of a Callback that stops training when the minimum of loss has been reached, by setting the attribute self.model.stop_training (boolean). Optionally, you can provide an argument patience to specify how many epochs we should wait before stopping after having reached a local minimum." }, { "code": null, "e": 10614, "s": 10590, "text": "To use it for training:" }, { "code": null, "e": 10799, "s": 10614, "text": "model = create_model()history = model.fit( X_train, y_train, epochs=50, validation_split=0.20, batch_size=64, verbose=2, callbacks=[EarlyStoppingAtMinLoss()])" }, { "code": null, "e": 10889, "s": 10799, "text": "In this run, our training was stopped at epoch 28 as the minimum of loss has been reached" }, { "code": null, "e": 11026, "s": 10889, "text": "Note: this example is originally from Keras guide “Writing your own callbacks”, please check out the official documentation for details." }, { "code": null, "e": 11167, "s": 11026, "text": "This example shows how a custom Callback can be used to dynamically change the learning rate of the optimizer during the course of training." }, { "code": null, "e": 11177, "s": 11167, "text": "To use it" }, { "code": null, "e": 11378, "s": 11177, "text": "model = create_model()history = model.fit( X_train, y_train, epochs=15, validation_split=0.20, batch_size=64, verbose=2, callbacks=[CustomLearningRateScheduler(lr_schedule)])" }, { "code": null, "e": 11573, "s": 11378, "text": "Keras provides a base class called Callback which allows us to subclass it and create our own callbacks. It is really useful for debugging and perform some actions depend on performance metrics." }, { "code": null, "e": 11802, "s": 11573, "text": "I hope this article will help you to save time in creating your own custom callback and perform some custom actions. I recommend you to check out the documentation for the Callbacks API and to know about other things you can do." }, { "code": null, "e": 11954, "s": 11802, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 12014, "s": 11954, "text": "A practical introduction to Keras Callbacks in TensorFlow 2" }, { "code": null, "e": 12050, "s": 12014, "text": "Learning Rate Schedules in practice" }, { "code": null, "e": 12145, "s": 12050, "text": "The Google’s 7 steps of Machine Learning in practice: a TensorFlow example for structured data" }, { "code": null, "e": 12217, "s": 12145, "text": "3 ways to create a Machine Learning Model with Keras and TensorFlow 2.0" }, { "code": null, "e": 12291, "s": 12217, "text": "Batch normalization in practice: an example with Keras and TensorFlow 2.0" }, { "code": null, "e": 12356, "s": 12291, "text": "Early stopping in Practice: an example with Keras and TensorFlow" } ]
JavaScript | async function expression
08 Oct, 2021 Async function expression is used to define an async function inside an expression in JavaScript. The async function is declared using the async keyword. Syntax: async function [function_name]([param1[, param2[, ..., paramN]]]) { // Statements } Parameters: function_name: This parameter holds the function name. This function name is local to the function body. If function name is ommitted then it becomes anonymous function. paramN: It is the name of parameter that to be passed into the function. Statements: It contains the body of the function. Return Value: It returns a promise to return the value or else throw an exception, whenever an error occurs.Example 1: In this example “GeeksforGeeks” is printed first and after an interval of 1000 ms, “GFG” is printed. javascript <script> function cb() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve("GFG") }, 1000) }) } async function course() { console.log("GeeksforGeeks"); const result = await cb(); console.log(result); } course();</script> Output: GeeksforGeeks GFG Example 2: Here, a file is made gfg.txt and as soon as the file is read it prints “Read the file” in the console. Else it prints “error” when either the location of the file is wrong or it is not unable to read the file due to any other reason. javascript <script> async function gfg() { try { let f1 = await fs.promises.readFile("gfg.txt") console.log("Read the file") } catch (err) { console.log("error"); } } gfg();</script> Output: When file read: Read the file When file is not read(error thrown) error Example 3: This is an example of async function working in parallel. javascript <script> function cb() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve("GFG") }, 2000) }) } function cb1() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve("GFG1") }, 1000) }) } async function course() { console.log("GeeksforGeeks"); const result1 = await cb1(); const result = await cb(); console.log(result1); console.log(result); } course();</script> Output: GeeksforGeeks GFG1 GFG Supported Browsers: Google Chrome 55 and above Edge 15 and above Firefox 52 and above Safari 10.1 and above Opera 42 and above riarawal99 ysachin2314 javascript-basics Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 192, "s": 28, "text": "Async function expression is used to define an async function inside an expression in JavaScript. The async function is declared using the async keyword. Syntax: " }, { "code": null, "e": 280, "s": 192, "text": "async function [function_name]([param1[, param2[, ..., paramN]]]) {\n // Statements\n}" }, { "code": null, "e": 294, "s": 280, "text": "Parameters: " }, { "code": null, "e": 464, "s": 294, "text": "function_name: This parameter holds the function name. This function name is local to the function body. If function name is ommitted then it becomes anonymous function." }, { "code": null, "e": 537, "s": 464, "text": "paramN: It is the name of parameter that to be passed into the function." }, { "code": null, "e": 587, "s": 537, "text": "Statements: It contains the body of the function." }, { "code": null, "e": 808, "s": 587, "text": "Return Value: It returns a promise to return the value or else throw an exception, whenever an error occurs.Example 1: In this example “GeeksforGeeks” is printed first and after an interval of 1000 ms, “GFG” is printed. " }, { "code": null, "e": 819, "s": 808, "text": "javascript" }, { "code": "<script> function cb() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(\"GFG\") }, 1000) }) } async function course() { console.log(\"GeeksforGeeks\"); const result = await cb(); console.log(result); } course();</script>", "e": 1160, "s": 819, "text": null }, { "code": null, "e": 1170, "s": 1160, "text": "Output: " }, { "code": null, "e": 1188, "s": 1170, "text": "GeeksforGeeks\nGFG" }, { "code": null, "e": 1435, "s": 1188, "text": "Example 2: Here, a file is made gfg.txt and as soon as the file is read it prints “Read the file” in the console. Else it prints “error” when either the location of the file is wrong or it is not unable to read the file due to any other reason. " }, { "code": null, "e": 1446, "s": 1435, "text": "javascript" }, { "code": "<script> async function gfg() { try { let f1 = await fs.promises.readFile(\"gfg.txt\") console.log(\"Read the file\") } catch (err) { console.log(\"error\"); } } gfg();</script>", "e": 1688, "s": 1446, "text": null }, { "code": null, "e": 1698, "s": 1688, "text": "Output: " }, { "code": null, "e": 1716, "s": 1698, "text": "When file read: " }, { "code": null, "e": 1730, "s": 1716, "text": "Read the file" }, { "code": null, "e": 1768, "s": 1730, "text": "When file is not read(error thrown) " }, { "code": null, "e": 1774, "s": 1768, "text": "error" }, { "code": null, "e": 1844, "s": 1774, "text": "Example 3: This is an example of async function working in parallel. " }, { "code": null, "e": 1855, "s": 1844, "text": "javascript" }, { "code": "<script> function cb() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(\"GFG\") }, 2000) }) } function cb1() { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(\"GFG1\") }, 1000) }) } async function course() { console.log(\"GeeksforGeeks\"); const result1 = await cb1(); const result = await cb(); console.log(result1); console.log(result); } course();</script>", "e": 2441, "s": 1855, "text": null }, { "code": null, "e": 2451, "s": 2441, "text": "Output: " }, { "code": null, "e": 2474, "s": 2451, "text": "GeeksforGeeks\nGFG1\nGFG" }, { "code": null, "e": 2496, "s": 2474, "text": "Supported Browsers: " }, { "code": null, "e": 2523, "s": 2496, "text": "Google Chrome 55 and above" }, { "code": null, "e": 2541, "s": 2523, "text": "Edge 15 and above" }, { "code": null, "e": 2562, "s": 2541, "text": "Firefox 52 and above" }, { "code": null, "e": 2584, "s": 2562, "text": "Safari 10.1 and above" }, { "code": null, "e": 2603, "s": 2584, "text": "Opera 42 and above" }, { "code": null, "e": 2616, "s": 2605, "text": "riarawal99" }, { "code": null, "e": 2628, "s": 2616, "text": "ysachin2314" }, { "code": null, "e": 2646, "s": 2628, "text": "javascript-basics" }, { "code": null, "e": 2653, "s": 2646, "text": "Picked" }, { "code": null, "e": 2664, "s": 2653, "text": "JavaScript" }, { "code": null, "e": 2681, "s": 2664, "text": "Web Technologies" } ]
Maximize the profit after selling the tickets
28 Jun, 2022 Given array seats[] where seat[i] is the number of vacant seats in the ith row in a stadium for a cricket match. There are N people in a queue waiting to buy the tickets. Each seat costs equal to the number of vacant seats in the row it belongs to. The task is to maximize the profit by selling the tickets to N people. Examples: Input: seats[] = {2, 1, 1}, N = 3 Output: 4 Person 1: Sell the seat in the row with 2 vacant seats, seats = {1, 1, 1} Person 2: All the rows have 1 vacant seat each, seats[] = {0, 1, 1} Person 3: seats[] = {0, 0, 1} Input: seats[] = {2, 3, 4, 5, 1}, N = 6 Output: 22 Approach: In order to maximize the profit, the ticket must be for the seat in a row which has the maximum number of vacant seats and the number of vacant seats in that row will be decrement by 1 as one of the seats has just been sold. All the persons can be sold a seat ticket until there are vacant seats. This can be computed efficiently with the help of a priority_queue. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximized profitint maxProfit(int seats[], int k, int n){ // Push all the vacant seats // in a priority queue priority_queue<int> pq; for (int i = 0; i < k; i++) pq.push(seats[i]); // To store the maximized profit int profit = 0; // To count the people that // have been sold a ticket int c = 0; while (c < n) { // Get the maximum number of // vacant seats for any row int top = pq.top(); // Remove it from the queue pq.pop(); // If there are no vacant seats if (top == 0) break; // Update the profit profit = profit + top; // Push the updated status of the // vacant seats in the current row pq.push(top - 1); // Update the count of persons c++; } return profit;} // Driver codeint main(){ int seats[] = { 2, 3, 4, 5, 1 }; int k = sizeof(seats) / sizeof(int); int n = 6; cout << maxProfit(seats, k, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG { // Function to return the maximized profitstatic int maxProfit(int seats[], int k, int n){ // Push all the vacant seats // in a priority queue PriorityQueue<Integer> pq; pq = new PriorityQueue<>(Collections.reverseOrder()); for(int i = 0; i < k; i++) pq.add(seats[i]); // To store the maximized profit int profit = 0; // To count the people that // have been sold a ticket int c = 0; while (c < n) { // Get the maximum number of // vacant seats for any row int top = pq.remove(); // If there are no vacant seats if (top == 0) break; // Update the profit profit = profit + top; // Push the updated status of the // vacant seats in the current row pq.add(top - 1); // Update the count of persons c++; } return profit;} // Driver Codepublic static void main(String args[]){ int seats[] = { 2, 3, 4, 5, 1 }; int k = seats.length; int n = 6; System.out.println(maxProfit(seats, k ,n));}} // This code is contributed by rutvik_56 # Python3 implementation of the approachimport heapq# Function to return the maximized profit def maxProfit(seats, k, n): # Push all the vacant seats # in a max heap pq = seats # for maintaining the property of max heap heapq._heapify_max(pq) # To store the maximized profit profit = 0 while n > 0: # updating the profit value # with maximum number of vacant seats profit += pq[0] pq[0] -= 1 # If there are no vacant seats if pq[0] == 0: break # for maintaining the property of max heap heapq._heapify_max(pq) # decrementing the ticket count n -= 1 return profit # Driver Codeseats = [2, 3, 4, 5, 1]k = len(seats)n = 6print(maxProfit(seats, k, n)) '''Code is written by Rajat Kumar (GLAU)''' // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the maximized profitstatic int maxProfit(int[] seats, int k, int n){ // Push all the vacant seats // in a priority queue List<int> pq = new List<int>(); for(int i = 0; i < k; i++) pq.Add(seats[i]); // To store the maximized profit int profit = 0; // To count the people that // have been sold a ticket int c = 0; while (c < n) { // Get the maximum number of // vacant seats for any row pq.Sort(); pq.Reverse(); int top = pq[0]; // Remove it from the queue pq.RemoveAt(0); // If there are no vacant seats if (top == 0) break; // Update the profit profit = profit + top; // Push the updated status of the // vacant seats in the current row pq.Add(top - 1); // Update the count of persons c++; } return profit;} // Driver Codestatic void Main(){ int[] seats = { 2, 3, 4, 5, 1 }; int k = seats.Length; int n = 6; Console.Write(maxProfit(seats, k, n));}} // This code is contributed by divyeshrabadiya07 <script> // Javascript implementation of the approach // Function to return the maximized profit function maxProfit(seats, k, n) { // Push all the vacant seats // in a priority queue let priorityQueue = counter.map((item) => item); // To store the maximized profit let profit = 0; while (n != 0) { // Get the maximum number of // vacant seats for any row priorityQueue.sort((a,b) => b - a); let top = priorityQueue[0]; // Remove it from the queue priorityQueue.shift(); // If there are no vacant seats if (top == 0) break; // Update the profit profit = profit + top; // Push the updated status of the // vacant seats in the current row priorityQueue.push(top - 1); // Update the count of persons n--; } return profit; } let seats = [ 2, 3, 4, 5, 1 ]; let k = seats.length; let n = 6; document.write(maxProfit(seats, k, n)); </script> 22 Time complexity: O(n*log(n)) Auxiliary Space: O(n) Sliding Window approach: The problem can also be solved using the sliding window technique. For each person we need to sell ticket that has the maximum price and decrement its value by 1. Sort the array seats. Maintain two pointers pointing at the current maximum and next maximum number of seats . We iterate till our n>0 and there is a second largest element in the array. In each iteration if seats[i] > seats[j] ,we add the value at seats[i] ,min(n, i-j) times to our answer and decrement the value at ith index else we find j such that seats[j]<seats[i]. If there is no such j we break. If at the end of iteration our n>0 and seats[i]!=0 we add seats[i] till n>0 and seats[i]!=0. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std;int maxProfit(int seats[],int k, int n){ sort(seats,seats+k); int ans = 0; int i = k - 1; int j = k - 2; while (n > 0 && j >= 0) { if (seats[i] > seats[j]) { ans = ans + min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } else { while (j >= 0 && seats[j] == seats[i]) j--; if (j < 0) break; ans = ans + min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } } while (n > 0 && seats[i] != 0) { ans = ans + min(n, k) * seats[i]; n -= k; seats[i]--; } return ans;}int main(){ int seats[] = { 2, 3, 4, 5, 1 }; int k = sizeof(seats) / sizeof(int); int n = 6; cout << maxProfit(seats, k, n); return 0;} // Java program for the above approach import java.util.Arrays; class GFG { static int maxProfit(int seats[], int k, int n) { Arrays.sort(seats, 0, k); int ans = 0; int i = k - 1; int j = k - 2; while (n > 0 && j >= 0) { if (seats[i] > seats[j]) { ans = ans + Math.min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } else { while (j >= 0 && seats[j] == seats[i]) j--; if (j < 0) break; ans = ans + Math.min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } } while (n > 0 && seats[i] != 0) { ans = ans + Math.min(n, k) * seats[i]; n -= k; seats[i]--; } return ans; } public static void main(String[] args) { int seats[] = { 2, 3, 4, 5, 1 }; int k = seats.length; int n = 6; System.out.println(maxProfit(seats, k, n)); }} // This code is contributed by rajsanghavi9. # Python3 program for the above approachdef maxProfit(seats,k, n): seats.sort() ans = 0 i = k - 1 j = k - 2 while (n > 0 and j >= 0): if (seats[i] > seats[j]): ans = ans + min(n, (i - j)) * seats[i] n = n - (i - j) seats[i] -= 1 else: while (j >= 0 and seats[j] == seats[i]): j -= 1 if (j < 0): break ans = ans + min(n, (i - j)) * seats[i] n = n - (i - j) seats[i] -= 1 while (n > 0 and seats[i] != 0): ans = ans + min(n, k) * seats[i] n -= k seats[i] -= 1 return ans seats = [2, 3, 4, 5, 1]k = len(seats)n = 6print(maxProfit(seats, k, n)) # This code is contributed by shinjanpatra // C# program for the above approach using System; class GFG { static int maxProfit(int []seats, int k, int n) { Array.Sort(seats, 0, k); int ans = 0; int i = k - 1; int j = k - 2; while (n > 0 && j >= 0) { if (seats[i] > seats[j]) { ans = ans + Math.Min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } else { while (j >= 0 && seats[j] == seats[i]) j--; if (j < 0) break; ans = ans + Math.Min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } } while (n > 0 && seats[i] != 0) { ans = ans + Math.Min(n, k) * seats[i]; n -= k; seats[i]--; } return ans; } public static void Main(String[] args) { int []seats = { 2, 3, 4, 5, 1 }; int k = seats.Length; int n = 6; Console.Write(maxProfit(seats, k, n)); }} // This code is contributed by shivanisinghss2110 <script> function maxProfit(seats,k, n){ seats.sort(); var ans = 0; var i = k - 1; var j = k - 2; while (n > 0 && j >= 0) { if (seats[i] > seats[j]) { ans = ans + Math.min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } else { while (j >= 0 && seats[j] == seats[i]) j--; if (j < 0) break; ans = ans + Math.min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } } while (n > 0 && seats[i] != 0) { ans = ans + Math.min(n, k) * seats[i]; n -= k; seats[i]--; } return ans;} var seats = [2, 3, 4, 5, 1];var k = seats.length;var n = 6;document.write(maxProfit(seats, k, n)); // This code is contributed by rrrtnx.</script> 22 Time Complexity: O(k logk), where k is the size of the given array of seatsAuxiliary Space: O(1) ankthon rutvik_56 divyeshrabadiya07 decode2207 parthagarwal1962000 rajsanghavi9 shivanisinghss2110 rrrtnx sumitgumber28 rajatkumargla19 suryap shinjanpatra singhh3010 Microsoft priority-queue Arrays Heap Microsoft Arrays Heap priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2022" }, { "code": null, "e": 374, "s": 54, "text": "Given array seats[] where seat[i] is the number of vacant seats in the ith row in a stadium for a cricket match. There are N people in a queue waiting to buy the tickets. Each seat costs equal to the number of vacant seats in the row it belongs to. The task is to maximize the profit by selling the tickets to N people." }, { "code": null, "e": 385, "s": 374, "text": "Examples: " }, { "code": null, "e": 601, "s": 385, "text": "Input: seats[] = {2, 1, 1}, N = 3 Output: 4 Person 1: Sell the seat in the row with 2 vacant seats, seats = {1, 1, 1} Person 2: All the rows have 1 vacant seat each, seats[] = {0, 1, 1} Person 3: seats[] = {0, 0, 1}" }, { "code": null, "e": 654, "s": 601, "text": "Input: seats[] = {2, 3, 4, 5, 1}, N = 6 Output: 22 " }, { "code": null, "e": 1029, "s": 654, "text": "Approach: In order to maximize the profit, the ticket must be for the seat in a row which has the maximum number of vacant seats and the number of vacant seats in that row will be decrement by 1 as one of the seats has just been sold. All the persons can be sold a seat ticket until there are vacant seats. This can be computed efficiently with the help of a priority_queue." }, { "code": null, "e": 1081, "s": 1029, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1087, "s": 1081, "text": "C++14" }, { "code": null, "e": 1092, "s": 1087, "text": "Java" }, { "code": null, "e": 1100, "s": 1092, "text": "Python3" }, { "code": null, "e": 1103, "s": 1100, "text": "C#" }, { "code": null, "e": 1114, "s": 1103, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximized profitint maxProfit(int seats[], int k, int n){ // Push all the vacant seats // in a priority queue priority_queue<int> pq; for (int i = 0; i < k; i++) pq.push(seats[i]); // To store the maximized profit int profit = 0; // To count the people that // have been sold a ticket int c = 0; while (c < n) { // Get the maximum number of // vacant seats for any row int top = pq.top(); // Remove it from the queue pq.pop(); // If there are no vacant seats if (top == 0) break; // Update the profit profit = profit + top; // Push the updated status of the // vacant seats in the current row pq.push(top - 1); // Update the count of persons c++; } return profit;} // Driver codeint main(){ int seats[] = { 2, 3, 4, 5, 1 }; int k = sizeof(seats) / sizeof(int); int n = 6; cout << maxProfit(seats, k, n); return 0;}", "e": 2215, "s": 1114, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG { // Function to return the maximized profitstatic int maxProfit(int seats[], int k, int n){ // Push all the vacant seats // in a priority queue PriorityQueue<Integer> pq; pq = new PriorityQueue<>(Collections.reverseOrder()); for(int i = 0; i < k; i++) pq.add(seats[i]); // To store the maximized profit int profit = 0; // To count the people that // have been sold a ticket int c = 0; while (c < n) { // Get the maximum number of // vacant seats for any row int top = pq.remove(); // If there are no vacant seats if (top == 0) break; // Update the profit profit = profit + top; // Push the updated status of the // vacant seats in the current row pq.add(top - 1); // Update the count of persons c++; } return profit;} // Driver Codepublic static void main(String args[]){ int seats[] = { 2, 3, 4, 5, 1 }; int k = seats.length; int n = 6; System.out.println(maxProfit(seats, k ,n));}} // This code is contributed by rutvik_56", "e": 3391, "s": 2215, "text": null }, { "code": "# Python3 implementation of the approachimport heapq# Function to return the maximized profit def maxProfit(seats, k, n): # Push all the vacant seats # in a max heap pq = seats # for maintaining the property of max heap heapq._heapify_max(pq) # To store the maximized profit profit = 0 while n > 0: # updating the profit value # with maximum number of vacant seats profit += pq[0] pq[0] -= 1 # If there are no vacant seats if pq[0] == 0: break # for maintaining the property of max heap heapq._heapify_max(pq) # decrementing the ticket count n -= 1 return profit # Driver Codeseats = [2, 3, 4, 5, 1]k = len(seats)n = 6print(maxProfit(seats, k, n)) '''Code is written by Rajat Kumar (GLAU)'''", "e": 4194, "s": 3391, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the maximized profitstatic int maxProfit(int[] seats, int k, int n){ // Push all the vacant seats // in a priority queue List<int> pq = new List<int>(); for(int i = 0; i < k; i++) pq.Add(seats[i]); // To store the maximized profit int profit = 0; // To count the people that // have been sold a ticket int c = 0; while (c < n) { // Get the maximum number of // vacant seats for any row pq.Sort(); pq.Reverse(); int top = pq[0]; // Remove it from the queue pq.RemoveAt(0); // If there are no vacant seats if (top == 0) break; // Update the profit profit = profit + top; // Push the updated status of the // vacant seats in the current row pq.Add(top - 1); // Update the count of persons c++; } return profit;} // Driver Codestatic void Main(){ int[] seats = { 2, 3, 4, 5, 1 }; int k = seats.Length; int n = 6; Console.Write(maxProfit(seats, k, n));}} // This code is contributed by divyeshrabadiya07", "e": 5439, "s": 4194, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the maximized profit function maxProfit(seats, k, n) { // Push all the vacant seats // in a priority queue let priorityQueue = counter.map((item) => item); // To store the maximized profit let profit = 0; while (n != 0) { // Get the maximum number of // vacant seats for any row priorityQueue.sort((a,b) => b - a); let top = priorityQueue[0]; // Remove it from the queue priorityQueue.shift(); // If there are no vacant seats if (top == 0) break; // Update the profit profit = profit + top; // Push the updated status of the // vacant seats in the current row priorityQueue.push(top - 1); // Update the count of persons n--; } return profit; } let seats = [ 2, 3, 4, 5, 1 ]; let k = seats.length; let n = 6; document.write(maxProfit(seats, k, n)); </script>", "e": 6568, "s": 5439, "text": null }, { "code": null, "e": 6571, "s": 6568, "text": "22" }, { "code": null, "e": 6600, "s": 6571, "text": "Time complexity: O(n*log(n))" }, { "code": null, "e": 6623, "s": 6600, "text": "Auxiliary Space: O(n) " }, { "code": null, "e": 6648, "s": 6623, "text": "Sliding Window approach:" }, { "code": null, "e": 6715, "s": 6648, "text": "The problem can also be solved using the sliding window technique." }, { "code": null, "e": 6811, "s": 6715, "text": "For each person we need to sell ticket that has the maximum price and decrement its value by 1." }, { "code": null, "e": 6833, "s": 6811, "text": "Sort the array seats." }, { "code": null, "e": 6922, "s": 6833, "text": "Maintain two pointers pointing at the current maximum and next maximum number of seats ." }, { "code": null, "e": 6998, "s": 6922, "text": "We iterate till our n>0 and there is a second largest element in the array." }, { "code": null, "e": 7215, "s": 6998, "text": "In each iteration if seats[i] > seats[j] ,we add the value at seats[i] ,min(n, i-j) times to our answer and decrement the value at ith index else we find j such that seats[j]<seats[i]. If there is no such j we break." }, { "code": null, "e": 7308, "s": 7215, "text": "If at the end of iteration our n>0 and seats[i]!=0 we add seats[i] till n>0 and seats[i]!=0." }, { "code": null, "e": 7312, "s": 7308, "text": "C++" }, { "code": null, "e": 7317, "s": 7312, "text": "Java" }, { "code": null, "e": 7325, "s": 7317, "text": "Python3" }, { "code": null, "e": 7328, "s": 7325, "text": "C#" }, { "code": null, "e": 7339, "s": 7328, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;int maxProfit(int seats[],int k, int n){ sort(seats,seats+k); int ans = 0; int i = k - 1; int j = k - 2; while (n > 0 && j >= 0) { if (seats[i] > seats[j]) { ans = ans + min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } else { while (j >= 0 && seats[j] == seats[i]) j--; if (j < 0) break; ans = ans + min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } } while (n > 0 && seats[i] != 0) { ans = ans + min(n, k) * seats[i]; n -= k; seats[i]--; } return ans;}int main(){ int seats[] = { 2, 3, 4, 5, 1 }; int k = sizeof(seats) / sizeof(int); int n = 6; cout << maxProfit(seats, k, n); return 0;}", "e": 8202, "s": 7339, "text": null }, { "code": "// Java program for the above approach import java.util.Arrays; class GFG { static int maxProfit(int seats[], int k, int n) { Arrays.sort(seats, 0, k); int ans = 0; int i = k - 1; int j = k - 2; while (n > 0 && j >= 0) { if (seats[i] > seats[j]) { ans = ans + Math.min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } else { while (j >= 0 && seats[j] == seats[i]) j--; if (j < 0) break; ans = ans + Math.min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } } while (n > 0 && seats[i] != 0) { ans = ans + Math.min(n, k) * seats[i]; n -= k; seats[i]--; } return ans; } public static void main(String[] args) { int seats[] = { 2, 3, 4, 5, 1 }; int k = seats.length; int n = 6; System.out.println(maxProfit(seats, k, n)); }} // This code is contributed by rajsanghavi9.", "e": 9330, "s": 8202, "text": null }, { "code": "# Python3 program for the above approachdef maxProfit(seats,k, n): seats.sort() ans = 0 i = k - 1 j = k - 2 while (n > 0 and j >= 0): if (seats[i] > seats[j]): ans = ans + min(n, (i - j)) * seats[i] n = n - (i - j) seats[i] -= 1 else: while (j >= 0 and seats[j] == seats[i]): j -= 1 if (j < 0): break ans = ans + min(n, (i - j)) * seats[i] n = n - (i - j) seats[i] -= 1 while (n > 0 and seats[i] != 0): ans = ans + min(n, k) * seats[i] n -= k seats[i] -= 1 return ans seats = [2, 3, 4, 5, 1]k = len(seats)n = 6print(maxProfit(seats, k, n)) # This code is contributed by shinjanpatra", "e": 10121, "s": 9330, "text": null }, { "code": "// C# program for the above approach using System; class GFG { static int maxProfit(int []seats, int k, int n) { Array.Sort(seats, 0, k); int ans = 0; int i = k - 1; int j = k - 2; while (n > 0 && j >= 0) { if (seats[i] > seats[j]) { ans = ans + Math.Min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } else { while (j >= 0 && seats[j] == seats[i]) j--; if (j < 0) break; ans = ans + Math.Min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } } while (n > 0 && seats[i] != 0) { ans = ans + Math.Min(n, k) * seats[i]; n -= k; seats[i]--; } return ans; } public static void Main(String[] args) { int []seats = { 2, 3, 4, 5, 1 }; int k = seats.Length; int n = 6; Console.Write(maxProfit(seats, k, n)); }} // This code is contributed by shivanisinghss2110", "e": 11235, "s": 10121, "text": null }, { "code": "<script> function maxProfit(seats,k, n){ seats.sort(); var ans = 0; var i = k - 1; var j = k - 2; while (n > 0 && j >= 0) { if (seats[i] > seats[j]) { ans = ans + Math.min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } else { while (j >= 0 && seats[j] == seats[i]) j--; if (j < 0) break; ans = ans + Math.min(n, (i - j)) * seats[i]; n = n - (i - j); seats[i]--; } } while (n > 0 && seats[i] != 0) { ans = ans + Math.min(n, k) * seats[i]; n -= k; seats[i]--; } return ans;} var seats = [2, 3, 4, 5, 1];var k = seats.length;var n = 6;document.write(maxProfit(seats, k, n)); // This code is contributed by rrrtnx.</script>", "e": 12062, "s": 11235, "text": null }, { "code": null, "e": 12065, "s": 12062, "text": "22" }, { "code": null, "e": 12162, "s": 12065, "text": "Time Complexity: O(k logk), where k is the size of the given array of seatsAuxiliary Space: O(1)" }, { "code": null, "e": 12170, "s": 12162, "text": "ankthon" }, { "code": null, "e": 12180, "s": 12170, "text": "rutvik_56" }, { "code": null, "e": 12198, "s": 12180, "text": "divyeshrabadiya07" }, { "code": null, "e": 12209, "s": 12198, "text": "decode2207" }, { "code": null, "e": 12229, "s": 12209, "text": "parthagarwal1962000" }, { "code": null, "e": 12242, "s": 12229, "text": "rajsanghavi9" }, { "code": null, "e": 12261, "s": 12242, "text": "shivanisinghss2110" }, { "code": null, "e": 12268, "s": 12261, "text": "rrrtnx" }, { "code": null, "e": 12282, "s": 12268, "text": "sumitgumber28" }, { "code": null, "e": 12298, "s": 12282, "text": "rajatkumargla19" }, { "code": null, "e": 12305, "s": 12298, "text": "suryap" }, { "code": null, "e": 12318, "s": 12305, "text": "shinjanpatra" }, { "code": null, "e": 12329, "s": 12318, "text": "singhh3010" }, { "code": null, "e": 12339, "s": 12329, "text": "Microsoft" }, { "code": null, "e": 12354, "s": 12339, "text": "priority-queue" }, { "code": null, "e": 12361, "s": 12354, "text": "Arrays" }, { "code": null, "e": 12366, "s": 12361, "text": "Heap" }, { "code": null, "e": 12376, "s": 12366, "text": "Microsoft" }, { "code": null, "e": 12383, "s": 12376, "text": "Arrays" }, { "code": null, "e": 12388, "s": 12383, "text": "Heap" }, { "code": null, "e": 12403, "s": 12388, "text": "priority-queue" } ]
Check if a pair with given product exists in Linked list
04 Apr, 2022 Given a linked list, and a product K. The task is to check if there exist two numbers in the linked list whose product is equal to the given number K. If there exist two numbers, print them. If there are multiple answers, print any of them. Examples: Input : List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL K = 2 Output : Pair is (1, 2) Input : List = 10 -> 12 -> 31 -> 42 -> 53 -> NULL K = 15 Output : No Pair Exists Method 1 (Brute force): Run two nested loops to generate all possible pairs of the linked list and check if the product of any pair matches with the given product K.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP code to find the pair with given product#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Takes head pointer of the linked list and product*/int check_pair_product(struct Node* head, int prod){ struct Node *p = head, *q; while (p != NULL) { q = p->next; while (q != NULL) { // check if both product is equal to // given product if ((p->data) * (q->data) == prod) { cout << p->data << " " << q->data; return true; } q = q->next; } p = p->next; } return 0;} /* Driver program to test above function */int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list*/ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); /* function to print the result*/ bool res = check_pair_product(head, 26); if (res == false) cout << "NO PAIR EXIST"; return 0;} // A Java code to find the pair// with given productimport java.util.*;class GFG{ /* Link list node */static class Node{ int data; Node next;}static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} /* Takes head pointer of the linked listand product*/static boolean check_pair_product(Node head, int prod){ Node p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both product is equal to // given product if ((p.data) * (q.data) == prod) { System.out.print(p.data + " " + q.data); return true; } q = q.next; } p = p.next; } return false;} // Driver Codepublic static void main(String[] args){ /* Start with the empty list */ head = null; /* Use push() to construct linked list*/ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ boolean res = check_pair_product(head, 26); if (res == false) System.out.println("NO PAIR EXIST");}} // This code is contributed by Rajput-Ji # Python3 code to find the pair with# given product # Link list nodeclass Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Push a new node on the front of the list. def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Takes head pointer of the linked # list and product def check_pair_product(self, prod): p = self.head while p != None: q = p.next while q != None: # Check if both product is equal # to given product if p.data * q.data == prod: print(p.data, q.data) return True q = q.next p = p.next return False # Driver Codeif __name__ == "__main__": # Start with the empty list linkedlist = LinkedList() # Use push() to construct linked list linkedlist.push(1) linkedlist.push(4) linkedlist.push(1) linkedlist.push(12) linkedlist.push(1) linkedlist.push(18) linkedlist.push(47) linkedlist.push(16) linkedlist.push(12) linkedlist.push(14) # function to print the result res = linkedlist.check_pair_product(26) if res == False: print("NO PAIR EXIST") # This code is contributed by Rituraj Jain // A C# code to find the pair// with given productusing System; class GFG{ /* Link list node */public class Node{ public int data; public Node next;}static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} /* Takes head pointer of the linked listand product*/static Boolean check_pair_product(Node head, int prod){ Node p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both product is equal to // given product if ((p.data) * (q.data) == prod) { Console.Write(p.data + " " + q.data); return true; } q = q.next; } p = p.next; } return false;} // Driver Codepublic static void Main(String[] args){ /* Start with the empty list */ head = null; /* Use push() to construct linked list*/ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ Boolean res = check_pair_product(head, 26); if (res == false) Console.WriteLine("NO PAIR EXIST");}} // This code is contributed by Rajput-Ji <script>// A javascript code to find the pair// with given product /* Link list node */ class Node { constructor(val) { this.data = val; this.next = null; } } var head; /* * Given a reference (pointer to pointer) to the head of a list and an int, push * a new node on the front of the list. */ function push(head_ref , new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref; } /* * Takes head pointer of the linked list and product */ function check_pair_product(head , prod) { var p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both product is equal to // given product if ((p.data) * (q.data) == prod) { document.write(p.data + " " + q.data); return true; } q = q.next; } p = p.next; } return false; } // Driver Code /* Start with the empty list */ head = null; /* Use push() to construct linked list */ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result */ var res = check_pair_product(head, 26); if (res == false) document.write("NO PAIR EXIST"); // This code contributed by Rajput-Ji</script> NO PAIR EXIST Time complexity: O(N2), where N is the length of the linked list. Method 2 (using hashing): Take a hashtable.Now, start traversing the linked list and check if the given product is divisible by the current element of the linked list also check if (K/current_element) of the linked list is present in a hashtable or not.if yes, return “true” else insert the current element to the hashtable and make a transversing pointer point to the next element of linked list. Take a hashtable. Now, start traversing the linked list and check if the given product is divisible by the current element of the linked list also check if (K/current_element) of the linked list is present in a hashtable or not. if yes, return “true” else insert the current element to the hashtable and make a transversing pointer point to the next element of linked list. Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // CPP code to find the pair with given product#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to check if pair with the given product// exists in the list// Takes head pointer of the linked list and productbool check_pair_product(struct Node* head, int prod){ unordered_set<int> s; struct Node* p = head; while (p != NULL) { int curr = p->data; // Check if pair exits if ((prod % curr == 0) && (s.find(prod / curr) != s.end())) { cout << curr << " " << prod / curr; return true; } s.insert(p->data); p = p->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list */ push(&head, 1); push(&head, 2); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); /* function to print the result*/ bool res = check_pair_product(head, 24); if (res == false) cout << "NO PAIR EXIST"; return 0;} // Java code to find the pair with given productimport java.util.*; class Solution { static final int MAX = 100000; /* Link list node */ static class Node { int data; Node next; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Function to check if pair with given product // exists in the list // Takes head pointer of the linked list and product static boolean check_pair_product(Node head, int prod) { Vector<Integer> s = new Vector<Integer>(); Node p = head; while (p != null) { int curr = p.data; // Check if pair exits if ((prod % curr == 0) && (s.contains(prod / curr))) { System.out.print(curr + " " + (prod / curr)); return true; } s.add(p.data); p = p.next; } return false; } /* Driver program to test above function*/ public static void main(String args[]) { /* Start with the empty list */ Node head = null; /* Use push() to construct linked list */ head = push(head, 1); head = push(head, 2); head = push(head, 1); head = push(head, 12); head = push(head, 1); head = push(head, 18); head = push(head, 47); head = push(head, 16); head = push(head, 12); head = push(head, 14); /* function to print the result*/ boolean res = check_pair_product(head, 24); if (res == false) System.out.println("NO PAIR EXIST"); }} // This code is contributed// by Arnab Kundu # Python3 code to find the pair with# given product # Link list nodeclass Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Push a new node on the front of the list. def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Checks if pair with given product # exists in the list or not def check_pair_product(self, prod): p = self.head s = set() while p != None: curr = p.data # Check if pair exits if (prod % curr == 0 and (prod // curr) in s): print(curr, prod // curr) return True; s.add(p.data); p = p.next; return False # Driver Codeif __name__ == "__main__": # Start with the empty list linkedlist = LinkedList() # Use push() to construct linked list linkedlist.push(1) linkedlist.push(2) linkedlist.push(1) linkedlist.push(12) linkedlist.push(1) linkedlist.push(18) linkedlist.push(47) linkedlist.push(16) linkedlist.push(12) linkedlist.push(14) # function to print the result res = linkedlist.check_pair_product(24) if res == False: print("NO PAIR EXIST") # This code is contributed by Rituraj Jain // C# code to find the pair with given productusing System;using System.Collections.Generic; class GFG { static readonly int MAX = 100000; /* Link list node */ public class Node { public int data; public Node next; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Function to check if pair with given product // exists in the list // Takes head pointer of the linked list and product static bool check_pair_product(Node head, int prod) { List<int> s = new List<int>(); Node p = head; while (p != null) { int curr = p.data; // Check if pair exits if ((prod % curr == 0) && (s.Contains(prod / curr))) { Console.Write(curr + " " + (prod / curr)); return true; } s.Add(p.data); p = p.next; } return false; } /* Driver code*/ public static void Main(String[] args) { /* Start with the empty list */ Node head = null; /* Use push() to construct linked list */ head = push(head, 1); head = push(head, 2); head = push(head, 1); head = push(head, 12); head = push(head, 1); head = push(head, 18); head = push(head, 47); head = push(head, 16); head = push(head, 12); head = push(head, 14); /* function to print the result*/ bool res = check_pair_product(head, 24); if (res == false) Console.Write("NO PAIR EXIST"); }} // This code contributed by Rajput-Ji <script> // JavaScript code to find the pair with given product var MAX = 100000; /* Link list node */ class Node { constructor() { this.data = 0; this.next = null; } } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; } // Function to check if pair with given product // exists in the list // Takes head pointer of the linked list and product function check_pair_product(head, prod) { var s = []; var p = head; while (p != null) { var curr = p.data; // Check if pair exits if (prod % curr == 0 && s.includes(prod / curr)) { document.write(curr + " " + prod / curr); return true; } s.push(p.data); p = p.next; } return false; } /* Driver code*/ /* Start with the empty list */ var head = null; /* Use push() to construct linked list */ head = push(head, 1); head = push(head, 2); head = push(head, 1); head = push(head, 12); head = push(head, 1); head = push(head, 18); head = push(head, 47); head = push(head, 16); head = push(head, 12); head = push(head, 14); /* function to print the result*/ var res = check_pair_product(head, 24); if (res == false) document.write("NO PAIR EXIST"); </script> 2 12 Time complexity : O(N) Auxiliary Space : O(N) andrew1234 rituraj_jain Rajput-Ji ks94714 rdtank ankita_saini surinderdawra388 cpp-unordered_set Technical Scripter 2018 Hash Linked List Searching Technical Scripter Linked List Searching Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Apr, 2022" }, { "code": null, "e": 294, "s": 53, "text": "Given a linked list, and a product K. The task is to check if there exist two numbers in the linked list whose product is equal to the given number K. If there exist two numbers, print them. If there are multiple answers, print any of them." }, { "code": null, "e": 305, "s": 294, "text": "Examples: " }, { "code": null, "e": 482, "s": 305, "text": "Input : List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL \n K = 2\nOutput : Pair is (1, 2)\n\nInput : List = 10 -> 12 -> 31 -> 42 -> 53 -> NULL \n K = 15\nOutput : No Pair Exists " }, { "code": null, "e": 699, "s": 482, "text": "Method 1 (Brute force): Run two nested loops to generate all possible pairs of the linked list and check if the product of any pair matches with the given product K.Below is the implementation of the above approach: " }, { "code": null, "e": 703, "s": 699, "text": "C++" }, { "code": null, "e": 708, "s": 703, "text": "Java" }, { "code": null, "e": 716, "s": 708, "text": "Python3" }, { "code": null, "e": 719, "s": 716, "text": "C#" }, { "code": null, "e": 730, "s": 719, "text": "Javascript" }, { "code": "// CPP code to find the pair with given product#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Takes head pointer of the linked list and product*/int check_pair_product(struct Node* head, int prod){ struct Node *p = head, *q; while (p != NULL) { q = p->next; while (q != NULL) { // check if both product is equal to // given product if ((p->data) * (q->data) == prod) { cout << p->data << \" \" << q->data; return true; } q = q->next; } p = p->next; } return 0;} /* Driver program to test above function */int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list*/ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); /* function to print the result*/ bool res = check_pair_product(head, 26); if (res == false) cout << \"NO PAIR EXIST\"; return 0;}", "e": 2208, "s": 730, "text": null }, { "code": "// A Java code to find the pair// with given productimport java.util.*;class GFG{ /* Link list node */static class Node{ int data; Node next;}static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} /* Takes head pointer of the linked listand product*/static boolean check_pair_product(Node head, int prod){ Node p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both product is equal to // given product if ((p.data) * (q.data) == prod) { System.out.print(p.data + \" \" + q.data); return true; } q = q.next; } p = p.next; } return false;} // Driver Codepublic static void main(String[] args){ /* Start with the empty list */ head = null; /* Use push() to construct linked list*/ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ boolean res = check_pair_product(head, 26); if (res == false) System.out.println(\"NO PAIR EXIST\");}} // This code is contributed by Rajput-Ji", "e": 3809, "s": 2208, "text": null }, { "code": "# Python3 code to find the pair with# given product # Link list nodeclass Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Push a new node on the front of the list. def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Takes head pointer of the linked # list and product def check_pair_product(self, prod): p = self.head while p != None: q = p.next while q != None: # Check if both product is equal # to given product if p.data * q.data == prod: print(p.data, q.data) return True q = q.next p = p.next return False # Driver Codeif __name__ == \"__main__\": # Start with the empty list linkedlist = LinkedList() # Use push() to construct linked list linkedlist.push(1) linkedlist.push(4) linkedlist.push(1) linkedlist.push(12) linkedlist.push(1) linkedlist.push(18) linkedlist.push(47) linkedlist.push(16) linkedlist.push(12) linkedlist.push(14) # function to print the result res = linkedlist.check_pair_product(26) if res == False: print(\"NO PAIR EXIST\") # This code is contributed by Rituraj Jain", "e": 5262, "s": 3809, "text": null }, { "code": "// A C# code to find the pair// with given productusing System; class GFG{ /* Link list node */public class Node{ public int data; public Node next;}static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */static void push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref;} /* Takes head pointer of the linked listand product*/static Boolean check_pair_product(Node head, int prod){ Node p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both product is equal to // given product if ((p.data) * (q.data) == prod) { Console.Write(p.data + \" \" + q.data); return true; } q = q.next; } p = p.next; } return false;} // Driver Codepublic static void Main(String[] args){ /* Start with the empty list */ head = null; /* Use push() to construct linked list*/ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ Boolean res = check_pair_product(head, 26); if (res == false) Console.WriteLine(\"NO PAIR EXIST\");}} // This code is contributed by Rajput-Ji", "e": 6862, "s": 5262, "text": null }, { "code": "<script>// A javascript code to find the pair// with given product /* Link list node */ class Node { constructor(val) { this.data = val; this.next = null; } } var head; /* * Given a reference (pointer to pointer) to the head of a list and an int, push * a new node on the front of the list. */ function push(head_ref , new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; head = head_ref; } /* * Takes head pointer of the linked list and product */ function check_pair_product(head , prod) { var p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both product is equal to // given product if ((p.data) * (q.data) == prod) { document.write(p.data + \" \" + q.data); return true; } q = q.next; } p = p.next; } return false; } // Driver Code /* Start with the empty list */ head = null; /* Use push() to construct linked list */ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result */ var res = check_pair_product(head, 26); if (res == false) document.write(\"NO PAIR EXIST\"); // This code contributed by Rajput-Ji</script>", "e": 8545, "s": 6862, "text": null }, { "code": null, "e": 8559, "s": 8545, "text": "NO PAIR EXIST" }, { "code": null, "e": 8628, "s": 8561, "text": "Time complexity: O(N2), where N is the length of the linked list. " }, { "code": null, "e": 8655, "s": 8628, "text": "Method 2 (using hashing): " }, { "code": null, "e": 9027, "s": 8655, "text": "Take a hashtable.Now, start traversing the linked list and check if the given product is divisible by the current element of the linked list also check if (K/current_element) of the linked list is present in a hashtable or not.if yes, return “true” else insert the current element to the hashtable and make a transversing pointer point to the next element of linked list." }, { "code": null, "e": 9045, "s": 9027, "text": "Take a hashtable." }, { "code": null, "e": 9256, "s": 9045, "text": "Now, start traversing the linked list and check if the given product is divisible by the current element of the linked list also check if (K/current_element) of the linked list is present in a hashtable or not." }, { "code": null, "e": 9401, "s": 9256, "text": "if yes, return “true” else insert the current element to the hashtable and make a transversing pointer point to the next element of linked list." }, { "code": null, "e": 9453, "s": 9401, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 9459, "s": 9453, "text": "C++14" }, { "code": null, "e": 9464, "s": 9459, "text": "Java" }, { "code": null, "e": 9472, "s": 9464, "text": "Python3" }, { "code": null, "e": 9475, "s": 9472, "text": "C#" }, { "code": null, "e": 9486, "s": 9475, "text": "Javascript" }, { "code": "// CPP code to find the pair with given product#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to check if pair with the given product// exists in the list// Takes head pointer of the linked list and productbool check_pair_product(struct Node* head, int prod){ unordered_set<int> s; struct Node* p = head; while (p != NULL) { int curr = p->data; // Check if pair exits if ((prod % curr == 0) && (s.find(prod / curr) != s.end())) { cout << curr << \" \" << prod / curr; return true; } s.insert(p->data); p = p->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list */ push(&head, 1); push(&head, 2); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); /* function to print the result*/ bool res = check_pair_product(head, 24); if (res == false) cout << \"NO PAIR EXIST\"; return 0;}", "e": 10999, "s": 9486, "text": null }, { "code": "// Java code to find the pair with given productimport java.util.*; class Solution { static final int MAX = 100000; /* Link list node */ static class Node { int data; Node next; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Function to check if pair with given product // exists in the list // Takes head pointer of the linked list and product static boolean check_pair_product(Node head, int prod) { Vector<Integer> s = new Vector<Integer>(); Node p = head; while (p != null) { int curr = p.data; // Check if pair exits if ((prod % curr == 0) && (s.contains(prod / curr))) { System.out.print(curr + \" \" + (prod / curr)); return true; } s.add(p.data); p = p.next; } return false; } /* Driver program to test above function*/ public static void main(String args[]) { /* Start with the empty list */ Node head = null; /* Use push() to construct linked list */ head = push(head, 1); head = push(head, 2); head = push(head, 1); head = push(head, 12); head = push(head, 1); head = push(head, 18); head = push(head, 47); head = push(head, 16); head = push(head, 12); head = push(head, 14); /* function to print the result*/ boolean res = check_pair_product(head, 24); if (res == false) System.out.println(\"NO PAIR EXIST\"); }} // This code is contributed// by Arnab Kundu", "e": 12899, "s": 10999, "text": null }, { "code": "# Python3 code to find the pair with# given product # Link list nodeclass Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Push a new node on the front of the list. def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Checks if pair with given product # exists in the list or not def check_pair_product(self, prod): p = self.head s = set() while p != None: curr = p.data # Check if pair exits if (prod % curr == 0 and (prod // curr) in s): print(curr, prod // curr) return True; s.add(p.data); p = p.next; return False # Driver Codeif __name__ == \"__main__\": # Start with the empty list linkedlist = LinkedList() # Use push() to construct linked list linkedlist.push(1) linkedlist.push(2) linkedlist.push(1) linkedlist.push(12) linkedlist.push(1) linkedlist.push(18) linkedlist.push(47) linkedlist.push(16) linkedlist.push(12) linkedlist.push(14) # function to print the result res = linkedlist.check_pair_product(24) if res == False: print(\"NO PAIR EXIST\") # This code is contributed by Rituraj Jain", "e": 14311, "s": 12899, "text": null }, { "code": "// C# code to find the pair with given productusing System;using System.Collections.Generic; class GFG { static readonly int MAX = 100000; /* Link list node */ public class Node { public int data; public Node next; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static Node push(Node head_ref, int new_data) { Node new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref; } // Function to check if pair with given product // exists in the list // Takes head pointer of the linked list and product static bool check_pair_product(Node head, int prod) { List<int> s = new List<int>(); Node p = head; while (p != null) { int curr = p.data; // Check if pair exits if ((prod % curr == 0) && (s.Contains(prod / curr))) { Console.Write(curr + \" \" + (prod / curr)); return true; } s.Add(p.data); p = p.next; } return false; } /* Driver code*/ public static void Main(String[] args) { /* Start with the empty list */ Node head = null; /* Use push() to construct linked list */ head = push(head, 1); head = push(head, 2); head = push(head, 1); head = push(head, 12); head = push(head, 1); head = push(head, 18); head = push(head, 47); head = push(head, 16); head = push(head, 12); head = push(head, 14); /* function to print the result*/ bool res = check_pair_product(head, 24); if (res == false) Console.Write(\"NO PAIR EXIST\"); }} // This code contributed by Rajput-Ji", "e": 16185, "s": 14311, "text": null }, { "code": "<script> // JavaScript code to find the pair with given product var MAX = 100000; /* Link list node */ class Node { constructor() { this.data = 0; this.next = null; } } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(head_ref, new_data) { var new_node = new Node(); new_node.data = new_data; new_node.next = head_ref; head_ref = new_node; return head_ref; } // Function to check if pair with given product // exists in the list // Takes head pointer of the linked list and product function check_pair_product(head, prod) { var s = []; var p = head; while (p != null) { var curr = p.data; // Check if pair exits if (prod % curr == 0 && s.includes(prod / curr)) { document.write(curr + \" \" + prod / curr); return true; } s.push(p.data); p = p.next; } return false; } /* Driver code*/ /* Start with the empty list */ var head = null; /* Use push() to construct linked list */ head = push(head, 1); head = push(head, 2); head = push(head, 1); head = push(head, 12); head = push(head, 1); head = push(head, 18); head = push(head, 47); head = push(head, 16); head = push(head, 12); head = push(head, 14); /* function to print the result*/ var res = check_pair_product(head, 24); if (res == false) document.write(\"NO PAIR EXIST\"); </script>", "e": 17861, "s": 16185, "text": null }, { "code": null, "e": 17866, "s": 17861, "text": "2 12" }, { "code": null, "e": 17915, "s": 17868, "text": "Time complexity : O(N) Auxiliary Space : O(N) " }, { "code": null, "e": 17926, "s": 17915, "text": "andrew1234" }, { "code": null, "e": 17939, "s": 17926, "text": "rituraj_jain" }, { "code": null, "e": 17949, "s": 17939, "text": "Rajput-Ji" }, { "code": null, "e": 17957, "s": 17949, "text": "ks94714" }, { "code": null, "e": 17964, "s": 17957, "text": "rdtank" }, { "code": null, "e": 17977, "s": 17964, "text": "ankita_saini" }, { "code": null, "e": 17994, "s": 17977, "text": "surinderdawra388" }, { "code": null, "e": 18012, "s": 17994, "text": "cpp-unordered_set" }, { "code": null, "e": 18036, "s": 18012, "text": "Technical Scripter 2018" }, { "code": null, "e": 18041, "s": 18036, "text": "Hash" }, { "code": null, "e": 18053, "s": 18041, "text": "Linked List" }, { "code": null, "e": 18063, "s": 18053, "text": "Searching" }, { "code": null, "e": 18082, "s": 18063, "text": "Technical Scripter" }, { "code": null, "e": 18094, "s": 18082, "text": "Linked List" }, { "code": null, "e": 18104, "s": 18094, "text": "Searching" }, { "code": null, "e": 18109, "s": 18104, "text": "Hash" } ]
How to check an element is visible or not using jQuery?
11 Sep, 2019 Given a HTML document and the task is to check the element is visible or not using jQuery :visible selector. The :visible selector can be used with .toggle() function to toggle the visibility of an element. It will works with the elements visibility: hidden; or opacity: 0; Syntax: $(element).is(":visible"); Example 1: This example uses :visible selector to check an element is visible or not using jQuery. <!DOCTYPE html><html> <head> <title> How to check an element is visible or not using jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script></head> <body style="text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to check an element is visible or not using jQuery ? </h3> <p style="display: none;"> GEEKSFORGEEKS - A computer science portal for geeks. </p> <input onclick="change()" type="button" value="Click to Display" id="myButton1"> </input> <script type="text/javascript"> $(document).ready(function() { $("input").click(function() { // Display hide paragraph on button click if (this.value == "Click to Display") this.value = "Click to Hide"; else this.value = "Click to Display"; $("p").toggle("slow", function() { // Check paragraph once toggle // effect is completed if($("p").is(":visible")) { alert("Paragraph is visible."); } else { alert("Paragraph is hidden."); } }); }); }); </script></body> </html> Output: Example 2: This example uses :visible selector to check an element is visible or not using jQuery. <!DOCTYPE html><html> <head> <title> How to check an element is visible or not using jQuery? </title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <style> h1 { color: green; } table, th, td { border: 1px solid black; text-align: center; } </style></head> <body> <center> <h1 style = "color:green;" > GeeksForGeeks </h1> <h3> How to check an element is visible or not using jQuery? </h3> <input onclick="change()" type="button" value="Click to Display" id="myButton1"> </input> <table style="width:70% "> <tr> <th>Language Index</th> <th>Language Name</th> </tr> <tr> <td>1</td> <td>C</td> </tr> <tr> <td>2</td> <td>C++</td> </tr> <tr> <td>3</td> <td>Java</td> </tr> <tr> <td>4</td> <td>Python</td> </tr> <tr> <td>5</td> <td>HTML</td> </tr> </table> <h4></h4> <script type="text/javascript"> $(document).ready(function() { $("input").click(function() { // Display hide paragraph on // button click if (this.value=="Click to Display") this.value = "Click to Hide"; else this.value = "Click to Display"; $("table").toggle("slow", function() { // Check paragraph once toggle // effect is completed if($("table").is(":visible")) { $("h4").text("Paragraph is visible."); } else { $("h4").text("Paragraph is hidden."); } }); }); }); </script> <center></body> </html> Output: Before Click on the Button: After Click on the “Click to Display” button: After Click on the “Click to Hide” button: jQuery-Misc JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Sep, 2019" }, { "code": null, "e": 302, "s": 28, "text": "Given a HTML document and the task is to check the element is visible or not using jQuery :visible selector. The :visible selector can be used with .toggle() function to toggle the visibility of an element. It will works with the elements visibility: hidden; or opacity: 0;" }, { "code": null, "e": 310, "s": 302, "text": "Syntax:" }, { "code": null, "e": 337, "s": 310, "text": "$(element).is(\":visible\");" }, { "code": null, "e": 436, "s": 337, "text": "Example 1: This example uses :visible selector to check an element is visible or not using jQuery." }, { "code": "<!DOCTYPE html><html> <head> <title> How to check an element is visible or not using jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to check an element is visible or not using jQuery ? </h3> <p style=\"display: none;\"> GEEKSFORGEEKS - A computer science portal for geeks. </p> <input onclick=\"change()\" type=\"button\" value=\"Click to Display\" id=\"myButton1\"> </input> <script type=\"text/javascript\"> $(document).ready(function() { $(\"input\").click(function() { // Display hide paragraph on button click if (this.value == \"Click to Display\") this.value = \"Click to Hide\"; else this.value = \"Click to Display\"; $(\"p\").toggle(\"slow\", function() { // Check paragraph once toggle // effect is completed if($(\"p\").is(\":visible\")) { alert(\"Paragraph is visible.\"); } else { alert(\"Paragraph is hidden.\"); } }); }); }); </script></body> </html> ", "e": 1885, "s": 436, "text": null }, { "code": null, "e": 1893, "s": 1885, "text": "Output:" }, { "code": null, "e": 1992, "s": 1893, "text": "Example 2: This example uses :visible selector to check an element is visible or not using jQuery." }, { "code": "<!DOCTYPE html><html> <head> <title> How to check an element is visible or not using jQuery? </title> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <style> h1 { color: green; } table, th, td { border: 1px solid black; text-align: center; } </style></head> <body> <center> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <h3> How to check an element is visible or not using jQuery? </h3> <input onclick=\"change()\" type=\"button\" value=\"Click to Display\" id=\"myButton1\"> </input> <table style=\"width:70% \"> <tr> <th>Language Index</th> <th>Language Name</th> </tr> <tr> <td>1</td> <td>C</td> </tr> <tr> <td>2</td> <td>C++</td> </tr> <tr> <td>3</td> <td>Java</td> </tr> <tr> <td>4</td> <td>Python</td> </tr> <tr> <td>5</td> <td>HTML</td> </tr> </table> <h4></h4> <script type=\"text/javascript\"> $(document).ready(function() { $(\"input\").click(function() { // Display hide paragraph on // button click if (this.value==\"Click to Display\") this.value = \"Click to Hide\"; else this.value = \"Click to Display\"; $(\"table\").toggle(\"slow\", function() { // Check paragraph once toggle // effect is completed if($(\"table\").is(\":visible\")) { $(\"h4\").text(\"Paragraph is visible.\"); } else { $(\"h4\").text(\"Paragraph is hidden.\"); } }); }); }); </script> <center></body> </html> ", "e": 4129, "s": 1992, "text": null }, { "code": null, "e": 4137, "s": 4129, "text": "Output:" }, { "code": null, "e": 4165, "s": 4137, "text": "Before Click on the Button:" }, { "code": null, "e": 4211, "s": 4165, "text": "After Click on the “Click to Display” button:" }, { "code": null, "e": 4254, "s": 4211, "text": "After Click on the “Click to Hide” button:" }, { "code": null, "e": 4266, "s": 4254, "text": "jQuery-Misc" }, { "code": null, "e": 4273, "s": 4266, "text": "JQuery" }, { "code": null, "e": 4290, "s": 4273, "text": "Web Technologies" }, { "code": null, "e": 4317, "s": 4290, "text": "Web technologies Questions" } ]
Adapter Method - Python Design Patterns - GeeksforGeeks
30 Jun, 2020 Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to create a bridge between two incompatible interfaces. This method provides a different interface for a class. We can more easily understand the concept by thinking about the Cable Adapter that allows us to charge a phone somewhere that has outlets in different shapes.Using this idea, we can integrate the classes that couldn’t be integrated due to interface incompatibility. Imagine you are creating an application that shows the data about all different types of vehicles present. It takes the data from APIs of different vehicle organizations in XML format and then displays the information.But suppose at some time you want to upgrade your application with a Machine Learning algorithms that work beautifully on the data and fetch the important data only. But there is a problem, it takes data in JSON format only.It will be a really poor approach to make changes in Machine Learning Algorithm so that it will take data in XML format. Problem-Adapter-Method For solving the problem we defined above, We can use Adapter Method that helps by creating an Adapter object.To use an adapter in our code: Client should make a request to the adapter by calling a method on it using the target interface.Using the Adaptee interface, the Adapter should translate that request on the adaptee.Result of the call is received the client and he/she is unaware of the presence of the Adapter’s presence. Client should make a request to the adapter by calling a method on it using the target interface. Using the Adaptee interface, the Adapter should translate that request on the adaptee. Result of the call is received the client and he/she is unaware of the presence of the Adapter’s presence. # Dog - Cycle# human - Truck# car - Car class MotorCycle: """Class for MotorCycle""" def __init__(self): self.name = "MotorCycle" def TwoWheeler(self): return "TwoWheeler" class Truck: """Class for Truck""" def __init__(self): self.name = "Truck" def EightWheeler(self): return "EightWheeler" class Car: """Class for Car""" def __init__(self): self.name = "Car" def FourWheeler(self): return "FourWheeler" class Adapter: """ Adapts an object by replacing methods. Usage: motorCycle = MotorCycle() motorCycle = Adapter(motorCycle, wheels = motorCycle.TwoWheeler) """ def __init__(self, obj, **adapted_methods): """We set the adapted methods in the object's dict""" self.obj = obj self.__dict__.update(adapted_methods) def __getattr__(self, attr): """All non-adapted calls are passed to the object""" return getattr(self.obj, attr) def original_dict(self): """Print original object dict""" return self.obj.__dict__ """ main method """if __name__ == "__main__": """list to store objects""" objects = [] motorCycle = MotorCycle() objects.append(Adapter(motorCycle, wheels = motorCycle.TwoWheeler)) truck = Truck() objects.append(Adapter(truck, wheels = truck.EightWheeler)) car = Car() objects.append(Adapter(car, wheels = car.FourWheeler)) for obj in objects: print("A {0} is a {1} vehicle".format(obj.name, obj.wheels())) Class diagram for the Adapter method which is a type of Structural Design pattern: Adapter-class-diagram Principle of Single Responsibility: We can achieve the principle of Single responsibility with Adapter Method because here we can separate the concrete code from the primary logic of the client. Flexibility: Adapter Method helps in achieving the flexibility and reusability of the code. Less complicated class: Our client class is not complicated by having to use a different interface and can use polymorphism to swap between different implementations of adapters. Open/Closed principle: We can introduce the ne wadapter classes into the code without violating the Open/Closed principle. Complexity of the Code: As we have introduced the set of new classes, objects and interfaces, the complexity of or code definitely rises. Adaptability: Most of the times, we require many adaptations with the adaptee chain to reach the compatibility what we want. To make classes and interfaces compatible : Adapter method is always used when we are in need to make certain classes compatible to communicate. Relatable to Inheritance: When we want to reuse some piece of code i.e., classes and interfaces that lack some functionalities, it can be done using the Adapter Method. Further read: Adapter Pattern in Java nidhi_biet python-design-pattern 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? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n30 Jun, 2020" }, { "code": null, "e": 24964, "s": 24292, "text": "Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to create a bridge between two incompatible interfaces. This method provides a different interface for a class. We can more easily understand the concept by thinking about the Cable Adapter that allows us to charge a phone somewhere that has outlets in different shapes.Using this idea, we can integrate the classes that couldn’t be integrated due to interface incompatibility." }, { "code": null, "e": 25527, "s": 24964, "text": "Imagine you are creating an application that shows the data about all different types of vehicles present. It takes the data from APIs of different vehicle organizations in XML format and then displays the information.But suppose at some time you want to upgrade your application with a Machine Learning algorithms that work beautifully on the data and fetch the important data only. But there is a problem, it takes data in JSON format only.It will be a really poor approach to make changes in Machine Learning Algorithm so that it will take data in XML format." }, { "code": null, "e": 25550, "s": 25527, "text": "Problem-Adapter-Method" }, { "code": null, "e": 25690, "s": 25550, "text": "For solving the problem we defined above, We can use Adapter Method that helps by creating an Adapter object.To use an adapter in our code:" }, { "code": null, "e": 25980, "s": 25690, "text": "Client should make a request to the adapter by calling a method on it using the target interface.Using the Adaptee interface, the Adapter should translate that request on the adaptee.Result of the call is received the client and he/she is unaware of the presence of the Adapter’s presence." }, { "code": null, "e": 26078, "s": 25980, "text": "Client should make a request to the adapter by calling a method on it using the target interface." }, { "code": null, "e": 26165, "s": 26078, "text": "Using the Adaptee interface, the Adapter should translate that request on the adaptee." }, { "code": null, "e": 26272, "s": 26165, "text": "Result of the call is received the client and he/she is unaware of the presence of the Adapter’s presence." }, { "code": "# Dog - Cycle# human - Truck# car - Car class MotorCycle: \"\"\"Class for MotorCycle\"\"\" def __init__(self): self.name = \"MotorCycle\" def TwoWheeler(self): return \"TwoWheeler\" class Truck: \"\"\"Class for Truck\"\"\" def __init__(self): self.name = \"Truck\" def EightWheeler(self): return \"EightWheeler\" class Car: \"\"\"Class for Car\"\"\" def __init__(self): self.name = \"Car\" def FourWheeler(self): return \"FourWheeler\" class Adapter: \"\"\" Adapts an object by replacing methods. Usage: motorCycle = MotorCycle() motorCycle = Adapter(motorCycle, wheels = motorCycle.TwoWheeler) \"\"\" def __init__(self, obj, **adapted_methods): \"\"\"We set the adapted methods in the object's dict\"\"\" self.obj = obj self.__dict__.update(adapted_methods) def __getattr__(self, attr): \"\"\"All non-adapted calls are passed to the object\"\"\" return getattr(self.obj, attr) def original_dict(self): \"\"\"Print original object dict\"\"\" return self.obj.__dict__ \"\"\" main method \"\"\"if __name__ == \"__main__\": \"\"\"list to store objects\"\"\" objects = [] motorCycle = MotorCycle() objects.append(Adapter(motorCycle, wheels = motorCycle.TwoWheeler)) truck = Truck() objects.append(Adapter(truck, wheels = truck.EightWheeler)) car = Car() objects.append(Adapter(car, wheels = car.FourWheeler)) for obj in objects: print(\"A {0} is a {1} vehicle\".format(obj.name, obj.wheels()))", "e": 27815, "s": 26272, "text": null }, { "code": null, "e": 27898, "s": 27815, "text": "Class diagram for the Adapter method which is a type of Structural Design pattern:" }, { "code": null, "e": 27920, "s": 27898, "text": "Adapter-class-diagram" }, { "code": null, "e": 28115, "s": 27920, "text": "Principle of Single Responsibility: We can achieve the principle of Single responsibility with Adapter Method because here we can separate the concrete code from the primary logic of the client." }, { "code": null, "e": 28207, "s": 28115, "text": "Flexibility: Adapter Method helps in achieving the flexibility and reusability of the code." }, { "code": null, "e": 28386, "s": 28207, "text": "Less complicated class: Our client class is not complicated by having to use a different interface and can use polymorphism to swap between different implementations of adapters." }, { "code": null, "e": 28509, "s": 28386, "text": "Open/Closed principle: We can introduce the ne wadapter classes into the code without violating the Open/Closed principle." }, { "code": null, "e": 28647, "s": 28509, "text": "Complexity of the Code: As we have introduced the set of new classes, objects and interfaces, the complexity of or code definitely rises." }, { "code": null, "e": 28772, "s": 28647, "text": "Adaptability: Most of the times, we require many adaptations with the adaptee chain to reach the compatibility what we want." }, { "code": null, "e": 28917, "s": 28772, "text": "To make classes and interfaces compatible : Adapter method is always used when we are in need to make certain classes compatible to communicate." }, { "code": null, "e": 29086, "s": 28917, "text": "Relatable to Inheritance: When we want to reuse some piece of code i.e., classes and interfaces that lack some functionalities, it can be done using the Adapter Method." }, { "code": null, "e": 29124, "s": 29086, "text": "Further read: Adapter Pattern in Java" }, { "code": null, "e": 29135, "s": 29124, "text": "nidhi_biet" }, { "code": null, "e": 29157, "s": 29135, "text": "python-design-pattern" }, { "code": null, "e": 29164, "s": 29157, "text": "Python" }, { "code": null, "e": 29262, "s": 29164, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29294, "s": 29262, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29350, "s": 29294, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29392, "s": 29350, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29434, "s": 29392, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29456, "s": 29434, "text": "Defaultdict in Python" }, { "code": null, "e": 29495, "s": 29456, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29526, "s": 29495, "text": "Python | os.path.join() method" }, { "code": null, "e": 29581, "s": 29526, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29610, "s": 29581, "text": "Create a directory in Python" } ]
Count of subsets with sum equal to X - GeeksforGeeks
29 Mar, 2022 Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X. Examples: Input: arr[] = {1, 2, 3, 3}, X = 6 Output: 3 All the possible subsets are {1, 2, 3}, {1, 2, 3} and {3, 3} Input: arr[] = {1, 1, 1, 1}, X = 1 Output: 4 Approach: A simple approach is to solve this problem by generating all the possible subsets and then checking whether the subset has the required sum. This approach will have exponential time complexity. However, for smaller values of X and array elements, this problem can be solved using dynamic programming. Let’s look at the recurrence relation first. This method is valid for all the integers. dp[i][C] = dp[i – 1][C – arr[i]] + dp[i – 1][C] Let’s understand the states of the DP now. Here, dp[i][C] stores the number of subsets of the sub-array arr[i...N-1] such that their sum is equal to C. Thus, the recurrence is very trivial as there are only two choices i.e. either consider the ith element in the subset or don’t. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define maxN 20#define maxSum 50#define minSum 50#define base 50 // To store the states of DPint dp[maxN][maxSum + minSum];bool v[maxN][maxSum + minSum]; // Function to return the required countint findCnt(int* arr, int i, int required_sum, int n){ // Base case if (i == n) { if (required_sum == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][required_sum + base]) return dp[i][required_sum + base]; // Setting the state as solved v[i][required_sum + base] = 1; // Recurrence relation dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i][required_sum + base];} // Driver codeint main(){ int arr[] = { 3, 3, 3, 3 }; int n = sizeof(arr) / sizeof(int); int x = 6; cout << findCnt(arr, 0, x, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{static int maxN = 20;static int maxSum = 50;static int minSum = 50;static int base = 50; // To store the states of DPstatic int [][]dp = new int[maxN][maxSum + minSum];static boolean [][]v = new boolean[maxN][maxSum + minSum]; // Function to return the required countstatic int findCnt(int []arr, int i, int required_sum, int n){ // Base case if (i == n) { if (required_sum == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][required_sum + base]) return dp[i][required_sum + base]; // Setting the state as solved v[i][required_sum + base] = true; // Recurrence relation dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i][required_sum + base];} // Driver codepublic static void main(String []args){ int arr[] = { 3, 3, 3, 3 }; int n = arr.length; int x = 6; System.out.println(findCnt(arr, 0, x, n));}} // This code is contributed by 29AjayKumar # Python3 implementation of the approachimport numpy as np maxN = 20maxSum = 50minSum = 50base = 50 # To store the states of DPdp = np.zeros((maxN, maxSum + minSum));v = np.zeros((maxN, maxSum + minSum)); # Function to return the required countdef findCnt(arr, i, required_sum, n) : # Base case if (i == n) : if (required_sum == 0) : return 1; else : return 0; # If the state has been solved before # return the value of the state if (v[i][required_sum + base]) : return dp[i][required_sum + base]; # Setting the state as solved v[i][required_sum + base] = 1; # Recurrence relation dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + \ findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i][required_sum + base]; # Driver codeif __name__ == "__main__" : arr = [ 3, 3, 3, 3 ]; n = len(arr); x = 6; print(findCnt(arr, 0, x, n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ static int maxN = 20;static int maxSum = 50;static int minSum = 50;static int Base = 50; // To store the states of DPstatic int [,]dp = new int[maxN, maxSum + minSum];static Boolean [,]v = new Boolean[maxN, maxSum + minSum]; // Function to return the required countstatic int findCnt(int []arr, int i, int required_sum, int n){ // Base case if (i == n) { if (required_sum == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i, required_sum + Base]) return dp[i, required_sum + Base]; // Setting the state as solved v[i, required_sum + Base] = true; // Recurrence relation dp[i, required_sum + Base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i,required_sum + Base];} // Driver codepublic static void Main(String []args){ int []arr = { 3, 3, 3, 3 }; int n = arr.Length; int x = 6; Console.WriteLine(findCnt(arr, 0, x, n));}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the approach var maxN = 20var maxSum = 50var minSum = 50var base = 50 // To store the states of DPvar dp = Array.from(Array(maxN),()=>Array(maxSum+minSum));var v = Array.from(Array(maxN),()=>Array(maxSum+minSum)); // Function to return the required countfunction findCnt(arr, i, required_sum, n){ // Base case if (i == n) { if (required_sum == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][required_sum + base]) return dp[i][required_sum + base]; // Setting the state as solved v[i][required_sum + base] = 1; // Recurrence relation dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i][required_sum + base];} // Driver codevar arr = [3, 3, 3, 3];var n = arr.length;var x = 6;document.write( findCnt(arr, 0, x, n)); </script> 6 This method is valid only for those arrays which contains positive elements. In this method we use a 2D array of size (arr.size() + 1) * (target + 1) of type integer. Initialization of Matrix: mat[0][0] = 1 because If the size of sum is if (A[i] > j) DP[i][j] = DP[i-1][j] else DP[i][j] = DP[i-1][j] + DP[i-1][j-A[i]] This means that if the current element has a value greater than the ‘current sum value’ we will copy the answer for previous cases And if the current sum value is greater than the ‘ith’ element we will see if any of the previous states have already experienced the sum=’j’ and any previous states experienced a value ‘j – A[i]’ which will solve our purpose C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; int subsetSum(int a[], int n, int sum){ // Initializing the matrix int tab[n + 1][sum + 1]; // Initializing the first value of matrix tab[0][0] = 1; for (int i = 1; i <= sum; i++) tab[0][i] = 0; for (int i = 1; i <= n; i++) { for (int j = 0; j <= sum; j++) { // if the value is greater than the sum if (a[i - 1] > j) tab[i][j] = tab[i - 1][j]; else { tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]]; } } } return tab[n][sum];} int main(){ int n = 4; int a[] = {3,3,3,3}; int sum = 6; cout << (subsetSum(a, n, sum));} import java.io.*;import java.lang.*;import java.util.*; class GFG{ static int subsetSum(int a[], int n, int sum){ // Initializing the matrix int tab[][] = new int[n + 1][sum + 1]; // Initializing the first value of matrix tab[0][0] = 1; for(int i = 1; i <= sum; i++) tab[0][i] = 0; for(int i = 1; i <= n; i++) { for(int j = 0; j <= sum; j++) { // If the value is greater than the sum if (a[i - 1] > j) tab[i][j] = tab[i - 1][j]; else { tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]]; } } } return tab[n][sum];} // Driver Codepublic static void main(String[] args){ int n = 4; int a[] = { 3, 3, 3, 3 }; int sum = 6; System.out.print(subsetSum(a, n, sum));}} // This code is contributed by Kingash def subset_sum(a: list, n: int, sum: int): # Initializing the matrix tab = [[0] * (sum + 1) for i in range(n + 1)] tab[0][0] = 1 for i in range(1, sum + 1): tab[0][i] = 0 for i in range(1, n+1): for j in range(sum + 1): if a[i-1] <= j: tab[i][j] = tab[i-1][j] + tab[i-1][j-a[i-1]] else: tab[i][j] = tab[i-1][j] return tab[n][sum] if __name__ == '__main__': a = [3, 3, 3, 3] n = 4 sum = 6 print(subset_sum(a, n, sum)) # This code is contributed by Premansh2001. using System; class GFG{ static int subsetSum(int []a, int n, int sum){ // Initializing the matrix int [,]tab = new int[n + 1, sum + 1]; // Initializing the first value of matrix tab[0, 0] = 1; for(int i = 1; i <= sum; i++) tab[0, i] = 0; for(int i = 1; i <= n; i++) { for(int j = 0; j <= sum; j++) { // If the value is greater than the sum if (a[i - 1] > j) tab[i, j] = tab[i - 1, j]; else { tab[i, j] = tab[i - 1, j] + tab[i - 1, j - a[i - 1]]; } } } return tab[n, sum];} // Driver Codepublic static void Main(String[] args){ int n = 4; int []a = { 3, 3, 3, 3 }; int sum = 6; Console.Write(subsetSum(a, n, sum));}} // This code is contributed by shivanisinghss2110 <script> function subsetSum( a, n, sum){ // Initializing the matrix var tab = new Array(n + 1); for (let i = 0; i< n+1; i++) tab[i] = new Array(sum + 1); // Initializing the first value of matrix tab[0][0] = 1; for (let i = 1; i <= sum; i++) tab[0][i] = 0; for (let i = 1; i <= n; i++) { for (let j = 0; j <= sum; j++) { // if the value is greater than the sum if (a[i - 1] > j) tab[i][j] = tab[i - 1][j]; else { tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]]; } } } return tab[n][sum];} var n = 4;var a = new Array(3,3,3,3);var sum = 6; console.log(subsetSum(a, n, sum)); // This code is contributed by ukasp.</script> 6 Time Complexity: O(sum*n), where the sum is the ‘target sum’ and ‘n’ is the size of the array.Auxiliary Space: O(sum*n), as the size of the 2-D array, is sum*n. Method 3: Space Optimization:- We can solve this problem by just taking care of last state and current state so we can wrap up this problem in O(target+1) space complexiy. Example:- vector<int> arr = { 3, 3, 3, 3 }; with targetSum of 6; dp[0][arr[0]] — tells about what if at index 0 we need arr[0] to achieve the targetSum and fortunately we have that solve so mark them 1; =====dp[0][3]=1 target Index at dp[2][6] --- tells tell me is at index 2 can count some subsets with sum=6, How can we achieve this? so we can tell ok i have reached at index 2 by adding element of index 1 or not both case has been added ------ means dp[i-1] we need only bcoz we are need of last index decision only nothing more than that so this why we are using a huge 2D array just store our running state and last state that's it. 1.Time Complexity:- O(N*val) 2.Space Compexity:- O(Val) where val and n are targetSum and number of element. C++ #include <bits/stdc++.h>using namespace std; int CountSubsetSum(vector<int>& arr, int val, int n){ int count = 0; vector<int> PresentState(val + 1, 0), LastState(val + 1, 0); // consider only last and present state we dont need the // (present-2)th state and above and we know for val to // be 0 if we dont pick the current index element we can // achieve PresentState[0] = LastState[0] = 1; if (arr[0] <= val) LastState[arr[0]] = 1; for (int i = 1; i < n; i++) { for (int j = 0; j <= val; j++) PresentState[j] = ((j >= arr[i]) ? LastState[j - arr[i]] : 0) + LastState[j]; // this we will need in the next iteration so just // swap current and last state. LastState = PresentState; } // Note after exit from loop we will having a present // state which is nothing but the laststate itself; return PresentState[val]; // or return // CurrentState[val];}int main(){ vector<int> arr = { 3, 3, 3, 3 }; cout << CountSubsetSum(arr, 6, arr.size());} 6 ankthon 29AjayKumar ankitkumar774 architgwl2000 Kingash noob2000 lakshya1st premansh2001 shivanisinghss2110 ukasp niyam239 abhishek2007 subset Arrays Combinatorial Dynamic Programming Arrays Dynamic Programming subset Combinatorial 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 Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Factorial of a large number Program to calculate value of nCr
[ { "code": null, "e": 24443, "s": 24415, "text": "\n29 Mar, 2022" }, { "code": null, "e": 24559, "s": 24443, "text": "Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X." }, { "code": null, "e": 24570, "s": 24559, "text": "Examples: " }, { "code": null, "e": 24676, "s": 24570, "text": "Input: arr[] = {1, 2, 3, 3}, X = 6 Output: 3 All the possible subsets are {1, 2, 3}, {1, 2, 3} and {3, 3}" }, { "code": null, "e": 24722, "s": 24676, "text": "Input: arr[] = {1, 1, 1, 1}, X = 1 Output: 4 " }, { "code": null, "e": 25079, "s": 24722, "text": "Approach: A simple approach is to solve this problem by generating all the possible subsets and then checking whether the subset has the required sum. This approach will have exponential time complexity. However, for smaller values of X and array elements, this problem can be solved using dynamic programming. Let’s look at the recurrence relation first. " }, { "code": null, "e": 25122, "s": 25079, "text": "This method is valid for all the integers." }, { "code": null, "e": 25171, "s": 25122, "text": "dp[i][C] = dp[i – 1][C – arr[i]] + dp[i – 1][C] " }, { "code": null, "e": 25451, "s": 25171, "text": "Let’s understand the states of the DP now. Here, dp[i][C] stores the number of subsets of the sub-array arr[i...N-1] such that their sum is equal to C. Thus, the recurrence is very trivial as there are only two choices i.e. either consider the ith element in the subset or don’t." }, { "code": null, "e": 25503, "s": 25451, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25507, "s": 25503, "text": "C++" }, { "code": null, "e": 25512, "s": 25507, "text": "Java" }, { "code": null, "e": 25520, "s": 25512, "text": "Python3" }, { "code": null, "e": 25523, "s": 25520, "text": "C#" }, { "code": null, "e": 25534, "s": 25523, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; #define maxN 20#define maxSum 50#define minSum 50#define base 50 // To store the states of DPint dp[maxN][maxSum + minSum];bool v[maxN][maxSum + minSum]; // Function to return the required countint findCnt(int* arr, int i, int required_sum, int n){ // Base case if (i == n) { if (required_sum == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][required_sum + base]) return dp[i][required_sum + base]; // Setting the state as solved v[i][required_sum + base] = 1; // Recurrence relation dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i][required_sum + base];} // Driver codeint main(){ int arr[] = { 3, 3, 3, 3 }; int n = sizeof(arr) / sizeof(int); int x = 6; cout << findCnt(arr, 0, x, n); return 0;}", "e": 26570, "s": 25534, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{static int maxN = 20;static int maxSum = 50;static int minSum = 50;static int base = 50; // To store the states of DPstatic int [][]dp = new int[maxN][maxSum + minSum];static boolean [][]v = new boolean[maxN][maxSum + minSum]; // Function to return the required countstatic int findCnt(int []arr, int i, int required_sum, int n){ // Base case if (i == n) { if (required_sum == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][required_sum + base]) return dp[i][required_sum + base]; // Setting the state as solved v[i][required_sum + base] = true; // Recurrence relation dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i][required_sum + base];} // Driver codepublic static void main(String []args){ int arr[] = { 3, 3, 3, 3 }; int n = arr.length; int x = 6; System.out.println(findCnt(arr, 0, x, n));}} // This code is contributed by 29AjayKumar", "e": 27754, "s": 26570, "text": null }, { "code": "# Python3 implementation of the approachimport numpy as np maxN = 20maxSum = 50minSum = 50base = 50 # To store the states of DPdp = np.zeros((maxN, maxSum + minSum));v = np.zeros((maxN, maxSum + minSum)); # Function to return the required countdef findCnt(arr, i, required_sum, n) : # Base case if (i == n) : if (required_sum == 0) : return 1; else : return 0; # If the state has been solved before # return the value of the state if (v[i][required_sum + base]) : return dp[i][required_sum + base]; # Setting the state as solved v[i][required_sum + base] = 1; # Recurrence relation dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + \\ findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i][required_sum + base]; # Driver codeif __name__ == \"__main__\" : arr = [ 3, 3, 3, 3 ]; n = len(arr); x = 6; print(findCnt(arr, 0, x, n)); # This code is contributed by AnkitRai01", "e": 28851, "s": 27754, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int maxN = 20;static int maxSum = 50;static int minSum = 50;static int Base = 50; // To store the states of DPstatic int [,]dp = new int[maxN, maxSum + minSum];static Boolean [,]v = new Boolean[maxN, maxSum + minSum]; // Function to return the required countstatic int findCnt(int []arr, int i, int required_sum, int n){ // Base case if (i == n) { if (required_sum == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i, required_sum + Base]) return dp[i, required_sum + Base]; // Setting the state as solved v[i, required_sum + Base] = true; // Recurrence relation dp[i, required_sum + Base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i,required_sum + Base];} // Driver codepublic static void Main(String []args){ int []arr = { 3, 3, 3, 3 }; int n = arr.Length; int x = 6; Console.WriteLine(findCnt(arr, 0, x, n));}} // This code is contributed by 29AjayKumar", "e": 30028, "s": 28851, "text": null }, { "code": "<script> // Javascript implementation of the approach var maxN = 20var maxSum = 50var minSum = 50var base = 50 // To store the states of DPvar dp = Array.from(Array(maxN),()=>Array(maxSum+minSum));var v = Array.from(Array(maxN),()=>Array(maxSum+minSum)); // Function to return the required countfunction findCnt(arr, i, required_sum, n){ // Base case if (i == n) { if (required_sum == 0) return 1; else return 0; } // If the state has been solved before // return the value of the state if (v[i][required_sum + base]) return dp[i][required_sum + base]; // Setting the state as solved v[i][required_sum + base] = 1; // Recurrence relation dp[i][required_sum + base] = findCnt(arr, i + 1, required_sum, n) + findCnt(arr, i + 1, required_sum - arr[i], n); return dp[i][required_sum + base];} // Driver codevar arr = [3, 3, 3, 3];var n = arr.length;var x = 6;document.write( findCnt(arr, 0, x, n)); </script>", "e": 31046, "s": 30028, "text": null }, { "code": null, "e": 31048, "s": 31046, "text": "6" }, { "code": null, "e": 31286, "s": 31048, "text": "This method is valid only for those arrays which contains positive elements.\nIn this method we use a 2D array of size (arr.size() + 1) * (target + 1) of type integer.\nInitialization of Matrix:\nmat[0][0] = 1 because If the size of sum is " }, { "code": null, "e": 31368, "s": 31286, "text": "if (A[i] > j)\nDP[i][j] = DP[i-1][j]\nelse \nDP[i][j] = DP[i-1][j] + DP[i-1][j-A[i]]" }, { "code": null, "e": 31499, "s": 31368, "text": "This means that if the current element has a value greater than the ‘current sum value’ we will copy the answer for previous cases" }, { "code": null, "e": 31725, "s": 31499, "text": "And if the current sum value is greater than the ‘ith’ element we will see if any of the previous states have already experienced the sum=’j’ and any previous states experienced a value ‘j – A[i]’ which will solve our purpose" }, { "code": null, "e": 31729, "s": 31725, "text": "C++" }, { "code": null, "e": 31734, "s": 31729, "text": "Java" }, { "code": null, "e": 31742, "s": 31734, "text": "Python3" }, { "code": null, "e": 31745, "s": 31742, "text": "C#" }, { "code": null, "e": 31756, "s": 31745, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int subsetSum(int a[], int n, int sum){ // Initializing the matrix int tab[n + 1][sum + 1]; // Initializing the first value of matrix tab[0][0] = 1; for (int i = 1; i <= sum; i++) tab[0][i] = 0; for (int i = 1; i <= n; i++) { for (int j = 0; j <= sum; j++) { // if the value is greater than the sum if (a[i - 1] > j) tab[i][j] = tab[i - 1][j]; else { tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]]; } } } return tab[n][sum];} int main(){ int n = 4; int a[] = {3,3,3,3}; int sum = 6; cout << (subsetSum(a, n, sum));}", "e": 32482, "s": 31756, "text": null }, { "code": "import java.io.*;import java.lang.*;import java.util.*; class GFG{ static int subsetSum(int a[], int n, int sum){ // Initializing the matrix int tab[][] = new int[n + 1][sum + 1]; // Initializing the first value of matrix tab[0][0] = 1; for(int i = 1; i <= sum; i++) tab[0][i] = 0; for(int i = 1; i <= n; i++) { for(int j = 0; j <= sum; j++) { // If the value is greater than the sum if (a[i - 1] > j) tab[i][j] = tab[i - 1][j]; else { tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]]; } } } return tab[n][sum];} // Driver Codepublic static void main(String[] args){ int n = 4; int a[] = { 3, 3, 3, 3 }; int sum = 6; System.out.print(subsetSum(a, n, sum));}} // This code is contributed by Kingash", "e": 33388, "s": 32482, "text": null }, { "code": "def subset_sum(a: list, n: int, sum: int): # Initializing the matrix tab = [[0] * (sum + 1) for i in range(n + 1)] tab[0][0] = 1 for i in range(1, sum + 1): tab[0][i] = 0 for i in range(1, n+1): for j in range(sum + 1): if a[i-1] <= j: tab[i][j] = tab[i-1][j] + tab[i-1][j-a[i-1]] else: tab[i][j] = tab[i-1][j] return tab[n][sum] if __name__ == '__main__': a = [3, 3, 3, 3] n = 4 sum = 6 print(subset_sum(a, n, sum)) # This code is contributed by Premansh2001.", "e": 33957, "s": 33388, "text": null }, { "code": "using System; class GFG{ static int subsetSum(int []a, int n, int sum){ // Initializing the matrix int [,]tab = new int[n + 1, sum + 1]; // Initializing the first value of matrix tab[0, 0] = 1; for(int i = 1; i <= sum; i++) tab[0, i] = 0; for(int i = 1; i <= n; i++) { for(int j = 0; j <= sum; j++) { // If the value is greater than the sum if (a[i - 1] > j) tab[i, j] = tab[i - 1, j]; else { tab[i, j] = tab[i - 1, j] + tab[i - 1, j - a[i - 1]]; } } } return tab[n, sum];} // Driver Codepublic static void Main(String[] args){ int n = 4; int []a = { 3, 3, 3, 3 }; int sum = 6; Console.Write(subsetSum(a, n, sum));}} // This code is contributed by shivanisinghss2110", "e": 34826, "s": 33957, "text": null }, { "code": "<script> function subsetSum( a, n, sum){ // Initializing the matrix var tab = new Array(n + 1); for (let i = 0; i< n+1; i++) tab[i] = new Array(sum + 1); // Initializing the first value of matrix tab[0][0] = 1; for (let i = 1; i <= sum; i++) tab[0][i] = 0; for (let i = 1; i <= n; i++) { for (let j = 0; j <= sum; j++) { // if the value is greater than the sum if (a[i - 1] > j) tab[i][j] = tab[i - 1][j]; else { tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]]; } } } return tab[n][sum];} var n = 4;var a = new Array(3,3,3,3);var sum = 6; console.log(subsetSum(a, n, sum)); // This code is contributed by ukasp.</script>", "e": 35601, "s": 34826, "text": null }, { "code": null, "e": 35603, "s": 35601, "text": "6" }, { "code": null, "e": 35765, "s": 35603, "text": "Time Complexity: O(sum*n), where the sum is the ‘target sum’ and ‘n’ is the size of the array.Auxiliary Space: O(sum*n), as the size of the 2-D array, is sum*n. " }, { "code": null, "e": 35796, "s": 35765, "text": "Method 3: Space Optimization:-" }, { "code": null, "e": 35937, "s": 35796, "text": "We can solve this problem by just taking care of last state and current state so we can wrap up this problem in O(target+1) space complexiy." }, { "code": null, "e": 35947, "s": 35937, "text": "Example:-" }, { "code": null, "e": 36002, "s": 35947, "text": "vector<int> arr = { 3, 3, 3, 3 }; with targetSum of 6;" }, { "code": null, "e": 36140, "s": 36002, "text": "dp[0][arr[0]] — tells about what if at index 0 we need arr[0] to achieve the targetSum and fortunately we have that solve so mark them 1;" }, { "code": null, "e": 36156, "s": 36140, "text": "=====dp[0][3]=1" }, { "code": null, "e": 36163, "s": 36156, "text": "target" }, { "code": null, "e": 36169, "s": 36163, "text": "Index" }, { "code": null, "e": 36686, "s": 36169, "text": "at dp[2][6] --- tells tell me is at index 2 can count some subsets with sum=6, How can we achieve this?\nso we can tell ok i have reached at index 2 by adding element of index 1 or not both case has been added ------ means dp[i-1] we need only bcoz we are need of last index decision only nothing more than that so this why we are using a huge 2D array\njust store our running state and last state that's it.\n\n1.Time Complexity:- O(N*val)\n2.Space Compexity:- O(Val)\nwhere val and n are targetSum and number of element." }, { "code": null, "e": 36690, "s": 36686, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; int CountSubsetSum(vector<int>& arr, int val, int n){ int count = 0; vector<int> PresentState(val + 1, 0), LastState(val + 1, 0); // consider only last and present state we dont need the // (present-2)th state and above and we know for val to // be 0 if we dont pick the current index element we can // achieve PresentState[0] = LastState[0] = 1; if (arr[0] <= val) LastState[arr[0]] = 1; for (int i = 1; i < n; i++) { for (int j = 0; j <= val; j++) PresentState[j] = ((j >= arr[i]) ? LastState[j - arr[i]] : 0) + LastState[j]; // this we will need in the next iteration so just // swap current and last state. LastState = PresentState; } // Note after exit from loop we will having a present // state which is nothing but the laststate itself; return PresentState[val]; // or return // CurrentState[val];}int main(){ vector<int> arr = { 3, 3, 3, 3 }; cout << CountSubsetSum(arr, 6, arr.size());}", "e": 37823, "s": 36690, "text": null }, { "code": null, "e": 37825, "s": 37823, "text": "6" }, { "code": null, "e": 37833, "s": 37825, "text": "ankthon" }, { "code": null, "e": 37845, "s": 37833, "text": "29AjayKumar" }, { "code": null, "e": 37859, "s": 37845, "text": "ankitkumar774" }, { "code": null, "e": 37873, "s": 37859, "text": "architgwl2000" }, { "code": null, "e": 37881, "s": 37873, "text": "Kingash" }, { "code": null, "e": 37890, "s": 37881, "text": "noob2000" }, { "code": null, "e": 37901, "s": 37890, "text": "lakshya1st" }, { "code": null, "e": 37914, "s": 37901, "text": "premansh2001" }, { "code": null, "e": 37933, "s": 37914, "text": "shivanisinghss2110" }, { "code": null, "e": 37939, "s": 37933, "text": "ukasp" }, { "code": null, "e": 37948, "s": 37939, "text": "niyam239" }, { "code": null, "e": 37961, "s": 37948, "text": "abhishek2007" }, { "code": null, "e": 37968, "s": 37961, "text": "subset" }, { "code": null, "e": 37975, "s": 37968, "text": "Arrays" }, { "code": null, "e": 37989, "s": 37975, "text": "Combinatorial" }, { "code": null, "e": 38009, "s": 37989, "text": "Dynamic Programming" }, { "code": null, "e": 38016, "s": 38009, "text": "Arrays" }, { "code": null, "e": 38036, "s": 38016, "text": "Dynamic Programming" }, { "code": null, "e": 38043, "s": 38036, "text": "subset" }, { "code": null, "e": 38057, "s": 38043, "text": "Combinatorial" }, { "code": null, "e": 38155, "s": 38057, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38164, "s": 38155, "text": "Comments" }, { "code": null, "e": 38177, "s": 38164, "text": "Old Comments" }, { "code": null, "e": 38225, "s": 38177, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 38269, "s": 38225, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 38292, "s": 38269, "text": "Introduction to Arrays" }, { "code": null, "e": 38324, "s": 38292, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 38338, "s": 38324, "text": "Linear Search" }, { "code": null, "e": 38376, "s": 38338, "text": "Permutation and Combination in Python" }, { "code": null, "e": 38453, "s": 38376, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 38481, "s": 38453, "text": "Factorial of a large number" } ]
Feature Engineering Examples: Binning Numerical Features | by Max Steele (they/them) | Towards Data Science
Feature engineering focuses on using the variables already present in your dataset to create additional features that are (hopefully) better at representing the underlying structure of your data. For example, your model performance may benefit from binning numerical features. This essentially means dividing continuous or other numerical features into distinct groups. By applying domain knowledge, you may be able to engineer categories and features that better emphasize important trends in your data. In this post, we’ll walk through three different methods for binning numerical features with specific examples using NumPy and Pandas. We’ll engineer features from a dataset with information about voter demographics and participation. I’ve selected 2 numerical variables to work with: age: a registered voter’s age at the end of the election yearbirth_year: the year a registered voter was born age: a registered voter’s age at the end of the election year birth_year: the year a registered voter was born If you want to start applying these methods to your own projects, you’ll just need to make sure you have both NumPy and Pandas installed, then import both. It may be odd to think about, but indicating whether a certain threshold is met by each instance (in this case by each registered voter) is a type of binning. For example, imagine we’re trying to predict whether each registered voter turned out to vote in the election. Maybe we suspect that younger voters will be more likely to turn out if this is the first time they were eligible to vote in a presidential election. Since the legal voting age is 18, anyone less than 22 years of age during the current presidential election would not have been able to vote in the previous presidential election. We can create an indicator variable for this threshold using np.where() which takes 3 arguments: a conditionwhat to return if the condition is metwhat to return if the condition is not met a condition what to return if the condition is met what to return if the condition is not met The following code creates a new feature, first_pres_elec, based on an individual’s age: df['first_pres_elec'] = np.where(df['age']<22, 1, 0) The condition we’re checking is whether or not the individual is less than 22 years of age. If they are below that threshold, np.where() returns a 1 because this was the first presidential election in which they were eligible to vote. If not, then 0 is returned. From our continuous variable age, we have created a new binary categorical variable. Maybe we also have reason to suspect that senior citizens were more or less likely to turnout to vote. If so, we might want to draw our model’s attention to this threshold by creating another threshold indicator: df['senior'] = np.where(df['age']>=65, 1, 0) Now we’ve created two threshold indicators that split the distribution of voter age as shown below. Younger individual’s who are newly eligible to vote in a presidential election are highlighted in red and seniors are highlighted in yellow. It might make sense to divide our registered voters up into generations based on their year of birth since that often seems so wrapped up in a person’s politics. One way to do this is to write our own custom function delineating the cutoffs for each generation. Below is one way we could write such a custom function: And then use Pandas` apply() to create a new feature based on the original birth_year variable: Now our registered voters are broken up into 5 discrete and meaningful categories. I decided to combine the 2 oldest generations (Greatest and Silent generations) so as not to create 2 rare categories that each make up only a very small portion of the population. We can also create the same generation bins using pd.cut() instead of writing our own function and applying it. We’ll still need to define the appropriate labels for each group, as well as the bin edges (cut off birth years). In the last line, we create our new feature by providing pd.cut() with the column we want binned into categories, the bins we want, and how to label each binned category. Rather than grouping by generation, we could quickly create a range and supply those as our bin edges. For example, if we thought it would be meaningful to group age by decade, we could accomplish that with the following: The first line defines a range that starts at 10 and continues up to, but not including 110, increasing by 10 at each step. The second line uses that range as bin edges to discretize registered voters by age into the following groups: The first row shows that 33,349 or 19.84% of our voters are in their 40’s. The parenthesis indicates that the 40 is inclusive, whereas the square bracket indicates the 50 is excluded from the bin. To more easily keep track of what each bin means, we could feed in the following labels to pd.cut(): We covered: What it means to bin numerical features 1 method for creating a threshold indicator (np.where()) 2 methods for binning numerical features into groups (custom function with Pandas apply() and defining bin edges with pd.cut()) I hope you found this informative and are able to apply something you learned to your own work. Thanks for reading! More on feature engineering: What is Feature Engineering? Feature Engineering Examples: Binning Categorical Features
[ { "code": null, "e": 367, "s": 171, "text": "Feature engineering focuses on using the variables already present in your dataset to create additional features that are (hopefully) better at representing the underlying structure of your data." }, { "code": null, "e": 676, "s": 367, "text": "For example, your model performance may benefit from binning numerical features. This essentially means dividing continuous or other numerical features into distinct groups. By applying domain knowledge, you may be able to engineer categories and features that better emphasize important trends in your data." }, { "code": null, "e": 961, "s": 676, "text": "In this post, we’ll walk through three different methods for binning numerical features with specific examples using NumPy and Pandas. We’ll engineer features from a dataset with information about voter demographics and participation. I’ve selected 2 numerical variables to work with:" }, { "code": null, "e": 1071, "s": 961, "text": "age: a registered voter’s age at the end of the election yearbirth_year: the year a registered voter was born" }, { "code": null, "e": 1133, "s": 1071, "text": "age: a registered voter’s age at the end of the election year" }, { "code": null, "e": 1182, "s": 1133, "text": "birth_year: the year a registered voter was born" }, { "code": null, "e": 1338, "s": 1182, "text": "If you want to start applying these methods to your own projects, you’ll just need to make sure you have both NumPy and Pandas installed, then import both." }, { "code": null, "e": 1497, "s": 1338, "text": "It may be odd to think about, but indicating whether a certain threshold is met by each instance (in this case by each registered voter) is a type of binning." }, { "code": null, "e": 1938, "s": 1497, "text": "For example, imagine we’re trying to predict whether each registered voter turned out to vote in the election. Maybe we suspect that younger voters will be more likely to turn out if this is the first time they were eligible to vote in a presidential election. Since the legal voting age is 18, anyone less than 22 years of age during the current presidential election would not have been able to vote in the previous presidential election." }, { "code": null, "e": 2035, "s": 1938, "text": "We can create an indicator variable for this threshold using np.where() which takes 3 arguments:" }, { "code": null, "e": 2127, "s": 2035, "text": "a conditionwhat to return if the condition is metwhat to return if the condition is not met" }, { "code": null, "e": 2139, "s": 2127, "text": "a condition" }, { "code": null, "e": 2178, "s": 2139, "text": "what to return if the condition is met" }, { "code": null, "e": 2221, "s": 2178, "text": "what to return if the condition is not met" }, { "code": null, "e": 2310, "s": 2221, "text": "The following code creates a new feature, first_pres_elec, based on an individual’s age:" }, { "code": null, "e": 2363, "s": 2310, "text": "df['first_pres_elec'] = np.where(df['age']<22, 1, 0)" }, { "code": null, "e": 2711, "s": 2363, "text": "The condition we’re checking is whether or not the individual is less than 22 years of age. If they are below that threshold, np.where() returns a 1 because this was the first presidential election in which they were eligible to vote. If not, then 0 is returned. From our continuous variable age, we have created a new binary categorical variable." }, { "code": null, "e": 2924, "s": 2711, "text": "Maybe we also have reason to suspect that senior citizens were more or less likely to turnout to vote. If so, we might want to draw our model’s attention to this threshold by creating another threshold indicator:" }, { "code": null, "e": 2969, "s": 2924, "text": "df['senior'] = np.where(df['age']>=65, 1, 0)" }, { "code": null, "e": 3210, "s": 2969, "text": "Now we’ve created two threshold indicators that split the distribution of voter age as shown below. Younger individual’s who are newly eligible to vote in a presidential election are highlighted in red and seniors are highlighted in yellow." }, { "code": null, "e": 3472, "s": 3210, "text": "It might make sense to divide our registered voters up into generations based on their year of birth since that often seems so wrapped up in a person’s politics. One way to do this is to write our own custom function delineating the cutoffs for each generation." }, { "code": null, "e": 3528, "s": 3472, "text": "Below is one way we could write such a custom function:" }, { "code": null, "e": 3624, "s": 3528, "text": "And then use Pandas` apply() to create a new feature based on the original birth_year variable:" }, { "code": null, "e": 3888, "s": 3624, "text": "Now our registered voters are broken up into 5 discrete and meaningful categories. I decided to combine the 2 oldest generations (Greatest and Silent generations) so as not to create 2 rare categories that each make up only a very small portion of the population." }, { "code": null, "e": 4114, "s": 3888, "text": "We can also create the same generation bins using pd.cut() instead of writing our own function and applying it. We’ll still need to define the appropriate labels for each group, as well as the bin edges (cut off birth years)." }, { "code": null, "e": 4285, "s": 4114, "text": "In the last line, we create our new feature by providing pd.cut() with the column we want binned into categories, the bins we want, and how to label each binned category." }, { "code": null, "e": 4507, "s": 4285, "text": "Rather than grouping by generation, we could quickly create a range and supply those as our bin edges. For example, if we thought it would be meaningful to group age by decade, we could accomplish that with the following:" }, { "code": null, "e": 4742, "s": 4507, "text": "The first line defines a range that starts at 10 and continues up to, but not including 110, increasing by 10 at each step. The second line uses that range as bin edges to discretize registered voters by age into the following groups:" }, { "code": null, "e": 5040, "s": 4742, "text": "The first row shows that 33,349 or 19.84% of our voters are in their 40’s. The parenthesis indicates that the 40 is inclusive, whereas the square bracket indicates the 50 is excluded from the bin. To more easily keep track of what each bin means, we could feed in the following labels to pd.cut():" }, { "code": null, "e": 5052, "s": 5040, "text": "We covered:" }, { "code": null, "e": 5092, "s": 5052, "text": "What it means to bin numerical features" }, { "code": null, "e": 5149, "s": 5092, "text": "1 method for creating a threshold indicator (np.where())" }, { "code": null, "e": 5277, "s": 5149, "text": "2 methods for binning numerical features into groups (custom function with Pandas apply() and defining bin edges with pd.cut())" }, { "code": null, "e": 5393, "s": 5277, "text": "I hope you found this informative and are able to apply something you learned to your own work. Thanks for reading!" }, { "code": null, "e": 5422, "s": 5393, "text": "More on feature engineering:" }, { "code": null, "e": 5451, "s": 5422, "text": "What is Feature Engineering?" } ]
Construct a Turing Machine for L = {a^n b^n | n>=1}
The Turing machine (TM) is more powerful than both finite automata (FA) and pushdown automata (PDA). They are as powerful as any computer we have ever built. A Turing machine can be formally described as seven tuples (Q,X, Σ, δ,q0,B,F) Where, Q is a finite set of states Q is a finite set of states X is the tape alphabet X is the tape alphabet Σ is the input alphabet Σ is the input alphabet δ is a transition function: δ:QxX→QxXx{left shift, right shift} δ is a transition function: δ:QxX→QxXx{left shift, right shift} q0 is the initial state q0 is the initial state B is the blank symbol B is the blank symbol F is the final state. F is the final state. A Turing Machine (TM) is a mathematical model which consists of an infinite length tape divided into cells on which input is given. It consists of a head which reads the input tape. A state register stores the state of the Turing machine. After reading an input symbol, it is replaced with another symbol, its internal state is changed, and it moves from one cell to the right or left. If the TM reaches the final state, the input string is accepted, otherwise rejected. The Turing machine has a read/write head. So we can write on the tape. Now, let us construct a Turing machine which accepts equal number of a’s and b’s, The language it is generated is L ={ anbn | n>=1}, the strings that are accepted by the given language is − L= {ab, aabb, aaabbb, aaaabbbb,.........} Consider n=3 so, a3b3 , the tape looks like − B= blank We need to convert every ‘a’ as X and every ‘b’ as Y. If the Turing machine contains an equal number of X and Y then it reaches the final state. Step 1 − Consider the initial state as q0. This state replace ‘a’ as X and move to right, now state changes for q0 toq1, so the transition function is − δ(q0, a) = (q1,X,R) Step 2 − Move right until you see the blank symbol. δ(q1, a) = (q1,a,R) δ(q1, b) = (q1,b,R) After reaching the blank symbol B, move left and change the state to q2, because we need to change the last ‘b’ to Y. δ(q1, B) = (q2,B,L) //1st iteration δ(q1, Y) = (q2,Y,L) // remaining iterations Step 3 − When we see the symbol ‘b’, replace it as Y and change the state to q3 and move left. δ(q2, B) = (q3,Y,L) Step 4 − Move to left until reach the symbol X. δ(q3, a) = (q3,a,L) δ(q3, b) = (q3,b,L) When we reach X move right and change the state as q0, and the next iteration is started. After replacing every ‘a’ and ‘b’ as X and Y by changing the states to q0 to q4, we get the following − δ(q0, Y) = (q4,Y,N) N represents No movement. q4 is the final state and q0 is the initial state of the Turing Machine, the intermediate states are q1, q2, q3. The transition diagram for Turing Machine is as follows −
[ { "code": null, "e": 1220, "s": 1062, "text": "The Turing machine (TM) is more powerful than both finite automata (FA) and pushdown automata (PDA). They are as powerful as any computer we have ever built." }, { "code": null, "e": 1279, "s": 1220, "text": "A Turing machine can be formally described as seven tuples" }, { "code": null, "e": 1298, "s": 1279, "text": "(Q,X, Σ, δ,q0,B,F)" }, { "code": null, "e": 1305, "s": 1298, "text": "Where," }, { "code": null, "e": 1333, "s": 1305, "text": "Q is a finite set of states" }, { "code": null, "e": 1361, "s": 1333, "text": "Q is a finite set of states" }, { "code": null, "e": 1384, "s": 1361, "text": "X is the tape alphabet" }, { "code": null, "e": 1407, "s": 1384, "text": "X is the tape alphabet" }, { "code": null, "e": 1431, "s": 1407, "text": "Σ is the input alphabet" }, { "code": null, "e": 1455, "s": 1431, "text": "Σ is the input alphabet" }, { "code": null, "e": 1519, "s": 1455, "text": "δ is a transition function: δ:QxX→QxXx{left shift, right shift}" }, { "code": null, "e": 1583, "s": 1519, "text": "δ is a transition function: δ:QxX→QxXx{left shift, right shift}" }, { "code": null, "e": 1607, "s": 1583, "text": "q0 is the initial state" }, { "code": null, "e": 1631, "s": 1607, "text": "q0 is the initial state" }, { "code": null, "e": 1653, "s": 1631, "text": "B is the blank symbol" }, { "code": null, "e": 1675, "s": 1653, "text": "B is the blank symbol" }, { "code": null, "e": 1697, "s": 1675, "text": "F is the final state." }, { "code": null, "e": 1719, "s": 1697, "text": "F is the final state." }, { "code": null, "e": 1958, "s": 1719, "text": "A Turing Machine (TM) is a mathematical model which consists of an infinite length tape divided into cells on which input is given. It consists of a head which reads the input tape. A state register stores the state of the Turing machine." }, { "code": null, "e": 2190, "s": 1958, "text": "After reading an input symbol, it is replaced with another symbol, its internal state is changed, and it moves from one cell to the right or left. If the TM reaches the final state, the input string is accepted, otherwise rejected." }, { "code": null, "e": 2261, "s": 2190, "text": "The Turing machine has a read/write head. So we can write on the tape." }, { "code": null, "e": 2343, "s": 2261, "text": "Now, let us construct a Turing machine which accepts equal number of a’s and b’s," }, { "code": null, "e": 2451, "s": 2343, "text": "The language it is generated is L ={ anbn | n>=1}, the strings that are accepted by the given language is −" }, { "code": null, "e": 2493, "s": 2451, "text": "L= {ab, aabb, aaabbb, aaaabbbb,.........}" }, { "code": null, "e": 2539, "s": 2493, "text": "Consider n=3 so, a3b3 , the tape looks like −" }, { "code": null, "e": 2548, "s": 2539, "text": "B= blank" }, { "code": null, "e": 2693, "s": 2548, "text": "We need to convert every ‘a’ as X and every ‘b’ as Y. If the Turing machine contains an equal number of X and Y then it reaches the final state." }, { "code": null, "e": 2846, "s": 2693, "text": "Step 1 − Consider the initial state as q0. This state replace ‘a’ as X and move to right, now state changes for q0 toq1, so the transition function is −" }, { "code": null, "e": 2866, "s": 2846, "text": "δ(q0, a) = (q1,X,R)" }, { "code": null, "e": 2918, "s": 2866, "text": "Step 2 − Move right until you see the blank symbol." }, { "code": null, "e": 2958, "s": 2918, "text": "δ(q1, a) = (q1,a,R)\nδ(q1, b) = (q1,b,R)" }, { "code": null, "e": 3076, "s": 2958, "text": "After reaching the blank symbol B, move left and change the state to q2, because we need to change the last ‘b’ to Y." }, { "code": null, "e": 3156, "s": 3076, "text": "δ(q1, B) = (q2,B,L) //1st iteration\nδ(q1, Y) = (q2,Y,L) // remaining iterations" }, { "code": null, "e": 3251, "s": 3156, "text": "Step 3 − When we see the symbol ‘b’, replace it as Y and change the state to q3 and move left." }, { "code": null, "e": 3271, "s": 3251, "text": "δ(q2, B) = (q3,Y,L)" }, { "code": null, "e": 3319, "s": 3271, "text": "Step 4 − Move to left until reach the symbol X." }, { "code": null, "e": 3359, "s": 3319, "text": "δ(q3, a) = (q3,a,L)\nδ(q3, b) = (q3,b,L)" }, { "code": null, "e": 3449, "s": 3359, "text": "When we reach X move right and change the state as q0, and the next iteration is started." }, { "code": null, "e": 3553, "s": 3449, "text": "After replacing every ‘a’ and ‘b’ as X and Y by changing the states to q0 to q4, we get the following −" }, { "code": null, "e": 3573, "s": 3553, "text": "δ(q0, Y) = (q4,Y,N)" }, { "code": null, "e": 3599, "s": 3573, "text": "N represents No movement." }, { "code": null, "e": 3712, "s": 3599, "text": "q4 is the final state and q0 is the initial state of the Turing Machine, the intermediate states are q1, q2, q3." }, { "code": null, "e": 3770, "s": 3712, "text": "The transition diagram for Turing Machine is as follows −" } ]
C - nested switch statements
It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise. The syntax for a nested switch statement is as follows − switch(ch1) { case 'A': printf("This A is part of outer switch" ); switch(ch2) { case 'A': printf("This A is part of inner switch" ); break; case 'B': /* case code */ } break; case 'B': /* case code */ } #include <stdio.h> int main () { /* local variable definition */ int a = 100; int b = 200; switch(a) { case 100: printf("This is part of outer switch\n", a ); switch(b) { case 200: printf("This is part of inner switch\n", a ); } } printf("Exact value of a is : %d\n", a ); printf("Exact value of b is : %d\n", b ); return 0; } When the above code is compiled and executed, it produces the following result − This is part of outer switch This is part of inner switch Exact value of a is : 100 Exact value of b is : 200 Print Add Notes Bookmark this page
[ { "code": null, "e": 2277, "s": 2084, "text": "It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise." }, { "code": null, "e": 2334, "s": 2277, "text": "The syntax for a nested switch statement is as follows −" }, { "code": null, "e": 2620, "s": 2334, "text": "switch(ch1) {\n\n case 'A': \n printf(\"This A is part of outer switch\" );\n\t\t\n switch(ch2) {\n case 'A':\n printf(\"This A is part of inner switch\" );\n break;\n case 'B': /* case code */\n }\n\t \n break;\n case 'B': /* case code */\n}\n" }, { "code": null, "e": 3054, "s": 2620, "text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int a = 100;\n int b = 200;\n \n switch(a) {\n \n case 100: \n printf(\"This is part of outer switch\\n\", a );\n \n switch(b) {\n case 200:\n printf(\"This is part of inner switch\\n\", a );\n }\n }\n \n printf(\"Exact value of a is : %d\\n\", a );\n printf(\"Exact value of b is : %d\\n\", b );\n \n return 0;\n}" }, { "code": null, "e": 3135, "s": 3054, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3246, "s": 3135, "text": "This is part of outer switch\nThis is part of inner switch\nExact value of a is : 100\nExact value of b is : 200\n" }, { "code": null, "e": 3253, "s": 3246, "text": " Print" }, { "code": null, "e": 3264, "s": 3253, "text": " Add Notes" } ]
Machine Learning Pipeline End-to-End Solution | by Andrej Baranovskij | Towards Data Science
After implementing several ML systems and running them in production, I realized there is a significant maintenance overload for monolithic ML apps. ML app code complexity grows exponentially. Data processing and preparation, model training, model serving — these things could look straightforward, but they are not, especially after moving to production. Data structures are changing, this requires adjusting data processing code. New data types are appearing, this requires maintaining the model up to date and re-train it. These changes could lead to model serving updates. When all this runs as a monolith, it becomes so hard to fix one thing, without breaking something else. Performance is another important point. When the system is split into different services, it becomes possible to run these services on different hardware. For example, we could run training services on TensorFlow Cloud with GPU, while data processing service could run on local CPU VM. I did research and checked what options are available to implement ML microservices. There are various solutions, but most of them looked over complicated to me. I decided to implement my own open-source product, which would rely on Python, FastAPI, RabbitMQ, and Celery for communication between services. I called it Skipper, it is on GitHub. The product is under active development, nevertheless, it can be used already. The core idea of Skipper is to provide a simple and reliable workflow for ML microservices implementation, with Web API interface in the front. In the next phases, services will be wrapped into Docker containers. We will provide support to run services on top of Kubernetes. There are two main blocks — engine and microservices. The engine can be treated as a microservice on its own, but I don’t call it a microservice for a reason. The engine part is responsible to provide Web API access, which is called from the outside. It acts as a gateway to a group of microservices. Web API is implemented with FastAPI. Celery is used to handle long-running tasks submitted through Web API. We start a long-running async task with Celery, the result is retrieved through another endpoint, using task ID. Common logic is encapsulated into Python library, which is published on PyPI — skipper-lib. The idea of this library is to allow generic event publishing/receiving with RabbitMQ task broker. The same library is used in Web API engine and in microservices. Microservices block is more like an example. It implements a sample service for data processing, model training, and finally model serving. There is communication through RabbitMQ queue between data processing model training services. The idea is that you could plug your own services into the workflow. The core element — RabbitMQ broker. Skipper is using RabbitMQ RPC calls to send messages between the services. There is no orchestrator to manage communication. Communication runs based on events, which are sent and received by the services. Web API is implemented with FastAPI. There is a router.py script, where endpoints are implemented. Long-running tasks, such as model training are started in async mode, use the Celery distributed task queue. We call process_worflow task and get its ID: @router_tasks.post('/execute_async', response_model=WorkflowTask, status_code=202)def exec_workflow_task_async(workflow_task_data: WorkflowTaskData): payload = workflow_task_data.json() task_id = process_workflow.delay(payload) return {'task_id': str(task_id), 'task_status': 'Processing'} Task status is checked through another endpoint, where we send the task ID and query Celery API to get the status: @router_tasks.get('/workflow/{task_id}', response_model=WorkflowTaskResult, status_code=202, responses={202: {'model': WorkflowTask, 'description': 'Accepted: Not Ready'}})async def exec_workflow_task_result(task_id): task = AsyncResult(task_id) if not task.ready(): return JSONResponse(status_code=202, content={'task_id': str(task_id), 'task_status': 'Processing'}) result = task.get() return {'task_id': task_id, 'task_status': 'Success', 'outcome': str(result)} Tasks that are supposed to complete quickly—for example, predict task—are executed directly, without starting Celery task. The event is sent to RabbitMQ broker and the result is returned in synch mode: @router_tasks.post('/execute_sync', response_model=WorkflowTaskResult, status_code=202, responses={202: {'model': WorkflowTaskCancelled, 'description': 'Accepted: Not Ready'}})def exec_workflow_task_sync(workflow_task_data: WorkflowTaskData): payload = workflow_task_data.json() queue_name = None if workflow_task_data.task_type == 'serving': queue_name = 'skipper_serving' if queue_name is None: return JSONResponse(status_code=202, content={'task_id': '-', 'task_status': 'Wrong task type'}) event_producer = EventProducer(username='skipper', password='welcome1', host='localhost', port=5672) response = json.loads(event_producer.call(queue_name, payload)) return {'task_id': '-', 'task_status': 'Success', 'outcome': str(response)} The Celery task is implemented in tasks.py script. Its job is to submit a new event to RabbitMQ and wait for the response. The library helps to encapsulate common logic without repeating the same code. I have built and published a library on PyPI with a tool called Poetry. The library helps to simplify communication with RabbitMQ. It implements the event producer and receiver. The event producer submits the task to the queue using RPC and waits for the response: def call(self, queue_name, payload): self.response = None self.corr_id = str(uuid.uuid4()) self.channel.basic_publish( exchange='', routing_key=queue_name, properties=pika.BasicProperties( reply_to=self.callback_queue, correlation_id=self.corr_id ), body=payload ) while self.response is None: self.connection.process_data_events() return self.response The event receiver listens for the messages from the RabbitMQ queue, calls the service, and returns the response: def on_request(self, ch, method, props, body): service_instance = self.service_worker() response, task_type = service_instance.call(body) ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties( correlation_id=props.correlation_id ), body=response) ch.basic_ack(delivery_tag=method.delivery_tag) print('Processed request:', task_type) The main goal of the implemented services is to provide an example, how to use the workflow. You can plugin your own services if you are using skipper-lib for event communication. All services follow the same code structure. This service is responsible to run model training as its name suggests. Service logic is implemented in training_service.py script. There is a method named call. This method is automatically executed by the event receiver from skipper-lib. In this method you are supposed to read input data, call model training logic and return the result: def call(self, data): data_json = json.loads(data) self.run_training(data) payload = { 'result': 'TASK_COMPLETED' } response = json.dumps(payload) return response, data_json['task_type'] This service sends events to request the data. We are using skipper-lib for that too: def prepare_datasets(self, data): event_producer = EventProducer(username='skipper', password='welcome1', host='localhost', port=5672) response = event_producer.call('skipper_data', data) To start the service, run main.py script: from skipper_lib.events.event_receiver import EventReceiverfrom app.training_service import TrainingServiceevent_receiver = EventReceiver(username='skipper', password='welcome1', host='localhost', port=5672, queue_name='skipper_training', service=TrainingService) Training service is configured to listen for skipper_training queue. This service receives events to prepare data and returns it to the caller. Multiple datasets are returned at once, for example, training and validation data, target values. Numpy arrays are converted to lists and serialized with json.dump: data = [norm_train_x.tolist(), norm_test_x.tolist(), norm_val_x.tolist(), train_y, test_y, val_y]response = json.dumps(data) Training service will deserialize the data with json.loads function and then it will create Numpy arrays structure again. This way only a single call is made to the data service and all data structures are transferred in a single call. To start the service, run main.py script: event_receiver = EventReceiver(username='skipper', password='welcome1', host='localhost', port=5672, queue_name='skipper_data', service=DataService) Data service is configured to listen for skipper_data queue. This service loads the model, which was saved by the training service. It loads numbers for data normalization, saved by data service. We need to normalize data, based on the same stats as the ones used for model training. Service method implementation: def call(self, data): data_json = json.loads(data) payload = pd.DataFrame(data_json['data'], index=[0, ]) payload.columns = [x.upper() for x in payload.columns] train_stats = pd.read_csv( '../models/train_stats.csv', index_col=0) x = np.array(self.norm(payload, train_stats)) models = self.get_immediate_subdirectories('../models/') saved_model = tf.keras.models.load_model( '../models/' + max(models)) predictions = saved_model.predict(x) result = { 'price': str(predictions[0][0][0]), 'ptratio': str(predictions[1][0][0]) } response = json.dumps(result) return response, data_json['task_type'] To start the service, run main.py script: event_receiver = EventReceiver(username='skipper', password='welcome1', host='localhost', port=5672, queue_name='skipper_serving', service=ServingService) The serving service is configured to listen for skipper_serving queue. The main idea of this post is to explain how you could split ML implementation into different services. This will help to manage complexity and will improve solution scalability. Hopefully, you will find Skipper useful for your own implementations. Enjoy! GitHub repo. Follow readme for setup instructions
[ { "code": null, "e": 528, "s": 172, "text": "After implementing several ML systems and running them in production, I realized there is a significant maintenance overload for monolithic ML apps. ML app code complexity grows exponentially. Data processing and preparation, model training, model serving — these things could look straightforward, but they are not, especially after moving to production." }, { "code": null, "e": 853, "s": 528, "text": "Data structures are changing, this requires adjusting data processing code. New data types are appearing, this requires maintaining the model up to date and re-train it. These changes could lead to model serving updates. When all this runs as a monolith, it becomes so hard to fix one thing, without breaking something else." }, { "code": null, "e": 1139, "s": 853, "text": "Performance is another important point. When the system is split into different services, it becomes possible to run these services on different hardware. For example, we could run training services on TensorFlow Cloud with GPU, while data processing service could run on local CPU VM." }, { "code": null, "e": 1563, "s": 1139, "text": "I did research and checked what options are available to implement ML microservices. There are various solutions, but most of them looked over complicated to me. I decided to implement my own open-source product, which would rely on Python, FastAPI, RabbitMQ, and Celery for communication between services. I called it Skipper, it is on GitHub. The product is under active development, nevertheless, it can be used already." }, { "code": null, "e": 1838, "s": 1563, "text": "The core idea of Skipper is to provide a simple and reliable workflow for ML microservices implementation, with Web API interface in the front. In the next phases, services will be wrapped into Docker containers. We will provide support to run services on top of Kubernetes." }, { "code": null, "e": 2176, "s": 1838, "text": "There are two main blocks — engine and microservices. The engine can be treated as a microservice on its own, but I don’t call it a microservice for a reason. The engine part is responsible to provide Web API access, which is called from the outside. It acts as a gateway to a group of microservices. Web API is implemented with FastAPI." }, { "code": null, "e": 2360, "s": 2176, "text": "Celery is used to handle long-running tasks submitted through Web API. We start a long-running async task with Celery, the result is retrieved through another endpoint, using task ID." }, { "code": null, "e": 2616, "s": 2360, "text": "Common logic is encapsulated into Python library, which is published on PyPI — skipper-lib. The idea of this library is to allow generic event publishing/receiving with RabbitMQ task broker. The same library is used in Web API engine and in microservices." }, { "code": null, "e": 2920, "s": 2616, "text": "Microservices block is more like an example. It implements a sample service for data processing, model training, and finally model serving. There is communication through RabbitMQ queue between data processing model training services. The idea is that you could plug your own services into the workflow." }, { "code": null, "e": 3162, "s": 2920, "text": "The core element — RabbitMQ broker. Skipper is using RabbitMQ RPC calls to send messages between the services. There is no orchestrator to manage communication. Communication runs based on events, which are sent and received by the services." }, { "code": null, "e": 3261, "s": 3162, "text": "Web API is implemented with FastAPI. There is a router.py script, where endpoints are implemented." }, { "code": null, "e": 3415, "s": 3261, "text": "Long-running tasks, such as model training are started in async mode, use the Celery distributed task queue. We call process_worflow task and get its ID:" }, { "code": null, "e": 3763, "s": 3415, "text": "@router_tasks.post('/execute_async', response_model=WorkflowTask, status_code=202)def exec_workflow_task_async(workflow_task_data: WorkflowTaskData): payload = workflow_task_data.json() task_id = process_workflow.delay(payload) return {'task_id': str(task_id), 'task_status': 'Processing'}" }, { "code": null, "e": 3878, "s": 3763, "text": "Task status is checked through another endpoint, where we send the task ID and query Celery API to get the status:" }, { "code": null, "e": 4555, "s": 3878, "text": "@router_tasks.get('/workflow/{task_id}', response_model=WorkflowTaskResult, status_code=202, responses={202: {'model': WorkflowTask, 'description': 'Accepted: Not Ready'}})async def exec_workflow_task_result(task_id): task = AsyncResult(task_id) if not task.ready(): return JSONResponse(status_code=202, content={'task_id': str(task_id), 'task_status': 'Processing'}) result = task.get() return {'task_id': task_id, 'task_status': 'Success', 'outcome': str(result)}" }, { "code": null, "e": 4757, "s": 4555, "text": "Tasks that are supposed to complete quickly—for example, predict task—are executed directly, without starting Celery task. The event is sent to RabbitMQ broker and the result is returned in synch mode:" }, { "code": null, "e": 5822, "s": 4757, "text": "@router_tasks.post('/execute_sync', response_model=WorkflowTaskResult, status_code=202, responses={202: {'model': WorkflowTaskCancelled, 'description': 'Accepted: Not Ready'}})def exec_workflow_task_sync(workflow_task_data: WorkflowTaskData): payload = workflow_task_data.json() queue_name = None if workflow_task_data.task_type == 'serving': queue_name = 'skipper_serving' if queue_name is None: return JSONResponse(status_code=202, content={'task_id': '-', 'task_status': 'Wrong task type'}) event_producer = EventProducer(username='skipper', password='welcome1', host='localhost', port=5672) response = json.loads(event_producer.call(queue_name, payload)) return {'task_id': '-', 'task_status': 'Success', 'outcome': str(response)}" }, { "code": null, "e": 5945, "s": 5822, "text": "The Celery task is implemented in tasks.py script. Its job is to submit a new event to RabbitMQ and wait for the response." }, { "code": null, "e": 6096, "s": 5945, "text": "The library helps to encapsulate common logic without repeating the same code. I have built and published a library on PyPI with a tool called Poetry." }, { "code": null, "e": 6202, "s": 6096, "text": "The library helps to simplify communication with RabbitMQ. It implements the event producer and receiver." }, { "code": null, "e": 6289, "s": 6202, "text": "The event producer submits the task to the queue using RPC and waits for the response:" }, { "code": null, "e": 6724, "s": 6289, "text": "def call(self, queue_name, payload): self.response = None self.corr_id = str(uuid.uuid4()) self.channel.basic_publish( exchange='', routing_key=queue_name, properties=pika.BasicProperties( reply_to=self.callback_queue, correlation_id=self.corr_id ), body=payload ) while self.response is None: self.connection.process_data_events() return self.response" }, { "code": null, "e": 6838, "s": 6724, "text": "The event receiver listens for the messages from the RabbitMQ queue, calls the service, and returns the response:" }, { "code": null, "e": 7345, "s": 6838, "text": "def on_request(self, ch, method, props, body): service_instance = self.service_worker() response, task_type = service_instance.call(body) ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties( correlation_id=props.correlation_id ), body=response) ch.basic_ack(delivery_tag=method.delivery_tag) print('Processed request:', task_type)" }, { "code": null, "e": 7525, "s": 7345, "text": "The main goal of the implemented services is to provide an example, how to use the workflow. You can plugin your own services if you are using skipper-lib for event communication." }, { "code": null, "e": 7570, "s": 7525, "text": "All services follow the same code structure." }, { "code": null, "e": 7642, "s": 7570, "text": "This service is responsible to run model training as its name suggests." }, { "code": null, "e": 7911, "s": 7642, "text": "Service logic is implemented in training_service.py script. There is a method named call. This method is automatically executed by the event receiver from skipper-lib. In this method you are supposed to read input data, call model training logic and return the result:" }, { "code": null, "e": 8123, "s": 7911, "text": "def call(self, data): data_json = json.loads(data) self.run_training(data) payload = { 'result': 'TASK_COMPLETED' } response = json.dumps(payload) return response, data_json['task_type']" }, { "code": null, "e": 8209, "s": 8123, "text": "This service sends events to request the data. We are using skipper-lib for that too:" }, { "code": null, "e": 8506, "s": 8209, "text": "def prepare_datasets(self, data): event_producer = EventProducer(username='skipper', password='welcome1', host='localhost', port=5672) response = event_producer.call('skipper_data', data)" }, { "code": null, "e": 8548, "s": 8506, "text": "To start the service, run main.py script:" }, { "code": null, "e": 8962, "s": 8548, "text": "from skipper_lib.events.event_receiver import EventReceiverfrom app.training_service import TrainingServiceevent_receiver = EventReceiver(username='skipper', password='welcome1', host='localhost', port=5672, queue_name='skipper_training', service=TrainingService)" }, { "code": null, "e": 9031, "s": 8962, "text": "Training service is configured to listen for skipper_training queue." }, { "code": null, "e": 9271, "s": 9031, "text": "This service receives events to prepare data and returns it to the caller. Multiple datasets are returned at once, for example, training and validation data, target values. Numpy arrays are converted to lists and serialized with json.dump:" }, { "code": null, "e": 9431, "s": 9271, "text": "data = [norm_train_x.tolist(), norm_test_x.tolist(), norm_val_x.tolist(), train_y, test_y, val_y]response = json.dumps(data)" }, { "code": null, "e": 9667, "s": 9431, "text": "Training service will deserialize the data with json.loads function and then it will create Numpy arrays structure again. This way only a single call is made to the data service and all data structures are transferred in a single call." }, { "code": null, "e": 9709, "s": 9667, "text": "To start the service, run main.py script:" }, { "code": null, "e": 10008, "s": 9709, "text": "event_receiver = EventReceiver(username='skipper', password='welcome1', host='localhost', port=5672, queue_name='skipper_data', service=DataService)" }, { "code": null, "e": 10069, "s": 10008, "text": "Data service is configured to listen for skipper_data queue." }, { "code": null, "e": 10292, "s": 10069, "text": "This service loads the model, which was saved by the training service. It loads numbers for data normalization, saved by data service. We need to normalize data, based on the same stats as the ones used for model training." }, { "code": null, "e": 10323, "s": 10292, "text": "Service method implementation:" }, { "code": null, "e": 11022, "s": 10323, "text": "def call(self, data): data_json = json.loads(data) payload = pd.DataFrame(data_json['data'], index=[0, ]) payload.columns = [x.upper() for x in payload.columns] train_stats = pd.read_csv( '../models/train_stats.csv', index_col=0) x = np.array(self.norm(payload, train_stats)) models = self.get_immediate_subdirectories('../models/') saved_model = tf.keras.models.load_model( '../models/' + max(models)) predictions = saved_model.predict(x) result = { 'price': str(predictions[0][0][0]), 'ptratio': str(predictions[1][0][0]) } response = json.dumps(result) return response, data_json['task_type']" }, { "code": null, "e": 11064, "s": 11022, "text": "To start the service, run main.py script:" }, { "code": null, "e": 11369, "s": 11064, "text": "event_receiver = EventReceiver(username='skipper', password='welcome1', host='localhost', port=5672, queue_name='skipper_serving', service=ServingService)" }, { "code": null, "e": 11440, "s": 11369, "text": "The serving service is configured to listen for skipper_serving queue." }, { "code": null, "e": 11696, "s": 11440, "text": "The main idea of this post is to explain how you could split ML implementation into different services. This will help to manage complexity and will improve solution scalability. Hopefully, you will find Skipper useful for your own implementations. Enjoy!" } ]
MySQL query to generate row index (rank) in SELECT statement?
To generate a row index, use ROW_NUMBER(). Let us first create a table − mysql> create table DemoTable ( Name varchar(40) ); Query OK, 0 rows affected (0.49 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.08 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +--------+ | Name | +--------+ | Chris | | Chris | | Chris | | Robert | | Robert | | Adam | | Adam | | Adam | | Adam | +--------+ 9 rows in set (0.00 sec) Following is the query to generate a row index in MySQL SELECT statement. Here, we have set rank for duplicate names − mysql> select Name, row_number() over (partition by Name) as `Rank` from DemoTable; This will produce the following output − +--------+------+ | Name | Rank | +--------+------+ | Adam | 1 | | Adam | 2 | | Adam | 3 | | Adam | 4 | | Chris | 1 | | Chris | 2 | | Chris | 3 | | Robert | 1 | | Robert | 2 | +--------+------+ 9 rows in set (0.00 sec)
[ { "code": null, "e": 1135, "s": 1062, "text": "To generate a row index, use ROW_NUMBER(). Let us first create a table −" }, { "code": null, "e": 1227, "s": 1135, "text": "mysql> create table DemoTable\n(\n Name varchar(40)\n);\nQuery OK, 0 rows affected (0.49 sec)" }, { "code": null, "e": 1283, "s": 1227, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2019, "s": 1283, "text": "mysql> insert into DemoTable values('Chris');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Chris');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable values('Chris');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable values('Robert');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Robert');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Adam');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Adam');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable values('Adam');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable values('Adam');\nQuery OK, 1 row affected (0.08 sec)" }, { "code": null, "e": 2079, "s": 2019, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2110, "s": 2079, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2151, "s": 2110, "text": "This will produce the following output −" }, { "code": null, "e": 2319, "s": 2151, "text": "+--------+\n| Name |\n+--------+\n| Chris |\n| Chris |\n| Chris |\n| Robert |\n| Robert |\n| Adam |\n| Adam |\n| Adam |\n| Adam |\n+--------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2438, "s": 2319, "text": "Following is the query to generate a row index in MySQL SELECT statement. Here, we have set rank for duplicate names −" }, { "code": null, "e": 2522, "s": 2438, "text": "mysql> select Name,\nrow_number() over (partition by Name) as `Rank`\nfrom DemoTable;" }, { "code": null, "e": 2563, "s": 2522, "text": "This will produce the following output −" }, { "code": null, "e": 2822, "s": 2563, "text": "+--------+------+\n| Name | Rank |\n+--------+------+\n| Adam | 1 |\n| Adam | 2 |\n| Adam | 3 |\n| Adam | 4 |\n| Chris | 1 |\n| Chris | 2 |\n| Chris | 3 |\n| Robert | 1 |\n| Robert | 2 |\n+--------+------+\n9 rows in set (0.00 sec)" } ]
Difference between Servlet and JSP
In brief, it can be defined as Servlet are the java programs that run on a Web server and act as a middle layer between a request coming from HTTP client and databases or applications on the HTTP server.While JSP is simply a text document that contains two types of text: static text which is predefined and dynamic text which is rendered after server response is received. The following are the important differences between ArrayList and HashSet. JavaTester.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class JavaTester extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println(message); } } Hello World
[ { "code": null, "e": 1436, "s": 1062, "text": "In brief, it can be defined as Servlet are the java programs that run on a Web server and act as a middle layer between a request coming from HTTP client and databases or applications on the HTTP server.While JSP is simply a text document that contains two types of text: static text which is predefined and dynamic text which is rendered after server response is received." }, { "code": null, "e": 1511, "s": 1436, "text": "The following are the important differences between ArrayList and HashSet." }, { "code": null, "e": 1527, "s": 1511, "text": "JavaTester.java" }, { "code": null, "e": 2105, "s": 1527, "text": "import java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\npublic class JavaTester extends HttpServlet {\n private String message;\n public void init() throws ServletException {\n // Do required initialization\n message = \"Hello World\";\n }\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n // Set response content type\n response.setContentType(\"text/html\");\n // Actual logic goes here.\n PrintWriter out = response.getWriter();\n out.println(message);\n }\n}" }, { "code": null, "e": 2117, "s": 2105, "text": "Hello World" } ]
"delete this" in C++ - GeeksforGeeks
11 Nov, 2021 Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined. CPP class A{ public: void fun() { delete this; }}; int main(){ /* Following is Valid */ A *ptr = new A; ptr->fun(); ptr = NULL; // make ptr NULL to make sure that things are not accessed using ptr. /* And following is Invalid: Undefined Behavior */ A a; a.fun(); getchar(); return 0;} 2) Once delete this is done, any member of the deleted object should not be accessed after deletion. CPP #include<iostream>using namespace std; class A{ int x; public: A() { x = 0;} void fun() { delete this; /* Invalid: Undefined Behavior */ cout<<x; // this is working }}; int main(){ A* obj = new A; obj->fun(); return 0;} 0 The best thing is to not do delete this at all.Thanks to Shekhu for providing above details.References: https://www.securecoding.cert.org/confluence/display/cplusplus/OOP05-CPP.+Avoid+deleting+this http://en.wikipedia.org/wiki/This_%28computer_science%29This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. DeepakTiwari2 hail2m15 cpp-pointer secure-coding C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++
[ { "code": null, "e": 24129, "s": 24101, "text": "\n11 Nov, 2021" }, { "code": null, "e": 24435, "s": 24129, "text": "Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined. " }, { "code": null, "e": 24439, "s": 24435, "text": "CPP" }, { "code": "class A{ public: void fun() { delete this; }}; int main(){ /* Following is Valid */ A *ptr = new A; ptr->fun(); ptr = NULL; // make ptr NULL to make sure that things are not accessed using ptr. /* And following is Invalid: Undefined Behavior */ A a; a.fun(); getchar(); return 0;}", "e": 24749, "s": 24439, "text": null }, { "code": null, "e": 24851, "s": 24749, "text": "2) Once delete this is done, any member of the deleted object should not be accessed after deletion. " }, { "code": null, "e": 24855, "s": 24851, "text": "CPP" }, { "code": "#include<iostream>using namespace std; class A{ int x; public: A() { x = 0;} void fun() { delete this; /* Invalid: Undefined Behavior */ cout<<x; // this is working }}; int main(){ A* obj = new A; obj->fun(); return 0;}", "e": 25105, "s": 24855, "text": null }, { "code": null, "e": 25107, "s": 25105, "text": "0" }, { "code": null, "e": 25531, "s": 25107, "text": "The best thing is to not do delete this at all.Thanks to Shekhu for providing above details.References: https://www.securecoding.cert.org/confluence/display/cplusplus/OOP05-CPP.+Avoid+deleting+this http://en.wikipedia.org/wiki/This_%28computer_science%29This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 25545, "s": 25531, "text": "DeepakTiwari2" }, { "code": null, "e": 25554, "s": 25545, "text": "hail2m15" }, { "code": null, "e": 25566, "s": 25554, "text": "cpp-pointer" }, { "code": null, "e": 25580, "s": 25566, "text": "secure-coding" }, { "code": null, "e": 25591, "s": 25580, "text": "C Language" }, { "code": null, "e": 25595, "s": 25591, "text": "C++" }, { "code": null, "e": 25599, "s": 25595, "text": "CPP" }, { "code": null, "e": 25697, "s": 25599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25706, "s": 25697, "text": "Comments" }, { "code": null, "e": 25719, "s": 25706, "text": "Old Comments" }, { "code": null, "e": 25754, "s": 25719, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25782, "s": 25754, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25828, "s": 25782, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25840, "s": 25828, "text": "fork() in C" }, { "code": null, "e": 25872, "s": 25840, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25890, "s": 25872, "text": "Vector in C++ STL" }, { "code": null, "e": 25936, "s": 25890, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 25979, "s": 25936, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 25998, "s": 25979, "text": "Inheritance in C++" } ]
Statistical - FORECAST.ETS Function
The FORECAST.ETS function calculates or predicts a future value based on existing (historical) values by using the AAA version of the Exponential Smoothing (ETS) algorithm. The predicted value is a continuation of the historical values in the specified target date, which should be a continuation of the timeline. FORECAST.ETS (target_date, values, timeline, [seasonality], [data_completion], [aggregation]) However, FORECAST.ETS supports up to 30% missing data, and will automatically adjust for it. The timeline is not required to be sorted, as FORECAST.ETS will sort it implicitly for calculations. The data point for which you want to predict a value. Target date can be date/time or numeric. A numeric value. The default value of 1 means Excel detects seasonality automatically for the forecast and uses positive, whole numbers for the length of the seasonal pattern. 0 indicates no seasonality, meaning the prediction will be linear. Positive whole numbers will indicate to the algorithm to use patterns of this length as the seasonality. Maximum supported seasonality is 8,760 (number of hours in a year). FORECAST.ETS supports up to 30% missing data in the timeline and will automatically adjust for it based on Data_completion. The default value of 1 will account for missing points by completing them to be the average of the neighboring points. 0 will indicate the algorithm to account for missing points as zeros. Although the timeline requires a constant step between data points, FORECAST.ETS will aggregate multiple points which have the same time stamp. The aggregation parameter is a numeric value indicating which method will be used to aggregate several values with the same time stamp. The default value of 0 will use AVERAGE, while other options are SUM, COUNT, COUNTA, MIN, MAX, and MEDIAN. FORECAST.ETS Function is added in Excel 2016. FORECAST.ETS Function is added in Excel 2016. This Function uses advanced machine learning algorithms, such as Exponential Triple Smoothing (ETS). This Function uses advanced machine learning algorithms, such as Exponential Triple Smoothing (ETS). This Function uses advanced machine learning algorithms, such as Exponential Triple Smoothing (ETS). This Function uses advanced machine learning algorithms, such as Exponential Triple Smoothing (ETS). If a constant step cannot be identified in the provided timeline, FORECAST.ETS returns the #NUM! error. If a constant step cannot be identified in the provided timeline, FORECAST.ETS returns the #NUM! error. If timeline contains duplicate values, FORECAST.ETS returns the #VALUE! Error. If timeline contains duplicate values, FORECAST.ETS returns the #VALUE! Error. If the ranges of the timeline and values are not of same size, FORECAST.ETS returns the #N/A error. If the ranges of the timeline and values are not of same size, FORECAST.ETS returns the #N/A error. If the Seasonality is <0, or >8760, or a non-numeric value, FORECAST.ETS returns the #NUM! error. If the Seasonality is <0, or >8760, or a non-numeric value, FORECAST.ETS returns the #NUM! error. 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": 2169, "s": 1854, "text": "The FORECAST.ETS function calculates or predicts a future value based on existing (historical) values by using the AAA version of the Exponential Smoothing (ETS) algorithm. The predicted value is a continuation of the historical values in the specified target date, which should be a continuation of the timeline." }, { "code": null, "e": 2269, "s": 2169, "text": "FORECAST.ETS (target_date, values, timeline, \n [seasonality], [data_completion], [aggregation]) \n" }, { "code": null, "e": 2463, "s": 2269, "text": "However, FORECAST.ETS supports up to 30% missing data, and will automatically adjust for it. The timeline is not required to be sorted, as FORECAST.ETS will sort it implicitly for calculations." }, { "code": null, "e": 2517, "s": 2463, "text": "The data point for which you want to predict a value." }, { "code": null, "e": 2558, "s": 2517, "text": "Target date can be date/time or numeric." }, { "code": null, "e": 2575, "s": 2558, "text": "A numeric value." }, { "code": null, "e": 2734, "s": 2575, "text": "The default value of 1 means Excel detects seasonality automatically for the forecast and uses positive, whole numbers for the length of the seasonal pattern." }, { "code": null, "e": 2801, "s": 2734, "text": "0 indicates no seasonality, meaning the prediction will be linear." }, { "code": null, "e": 2906, "s": 2801, "text": "Positive whole numbers will indicate to the algorithm to use patterns of this length as the seasonality." }, { "code": null, "e": 2974, "s": 2906, "text": "Maximum supported seasonality is 8,760 (number of hours in a year)." }, { "code": null, "e": 3098, "s": 2974, "text": "FORECAST.ETS supports up to 30% missing data in the timeline and will automatically adjust for it based on Data_completion." }, { "code": null, "e": 3217, "s": 3098, "text": "The default value of 1 will account for missing points by completing them to be the average of the neighboring points." }, { "code": null, "e": 3287, "s": 3217, "text": "0 will indicate the algorithm to account for missing points as zeros." }, { "code": null, "e": 3431, "s": 3287, "text": "Although the timeline requires a constant step between data points, FORECAST.ETS will aggregate multiple points which have the same time stamp." }, { "code": null, "e": 3567, "s": 3431, "text": "The aggregation parameter is a numeric value indicating which method will be used to aggregate several values with the same time stamp." }, { "code": null, "e": 3674, "s": 3567, "text": "The default value of 0 will use AVERAGE, while other options are SUM, COUNT, COUNTA, MIN, MAX, and MEDIAN." }, { "code": null, "e": 3720, "s": 3674, "text": "FORECAST.ETS Function is added in Excel 2016." }, { "code": null, "e": 3766, "s": 3720, "text": "FORECAST.ETS Function is added in Excel 2016." }, { "code": null, "e": 3867, "s": 3766, "text": "This Function uses advanced machine learning algorithms, such as Exponential Triple Smoothing (ETS)." }, { "code": null, "e": 3968, "s": 3867, "text": "This Function uses advanced machine learning algorithms, such as Exponential Triple Smoothing (ETS)." }, { "code": null, "e": 4069, "s": 3968, "text": "This Function uses advanced machine learning algorithms, such as Exponential Triple Smoothing (ETS)." }, { "code": null, "e": 4170, "s": 4069, "text": "This Function uses advanced machine learning algorithms, such as Exponential Triple Smoothing (ETS)." }, { "code": null, "e": 4274, "s": 4170, "text": "If a constant step cannot be identified in the provided timeline, FORECAST.ETS returns the #NUM! error." }, { "code": null, "e": 4378, "s": 4274, "text": "If a constant step cannot be identified in the provided timeline, FORECAST.ETS returns the #NUM! error." }, { "code": null, "e": 4457, "s": 4378, "text": "If timeline contains duplicate values, FORECAST.ETS returns the #VALUE! Error." }, { "code": null, "e": 4536, "s": 4457, "text": "If timeline contains duplicate values, FORECAST.ETS returns the #VALUE! Error." }, { "code": null, "e": 4636, "s": 4536, "text": "If the ranges of the timeline and values are not of same size, FORECAST.ETS returns the #N/A error." }, { "code": null, "e": 4736, "s": 4636, "text": "If the ranges of the timeline and values are not of same size, FORECAST.ETS returns the #N/A error." }, { "code": null, "e": 4834, "s": 4736, "text": "If the Seasonality is <0, or >8760, or a non-numeric value, FORECAST.ETS returns the #NUM! error." }, { "code": null, "e": 4932, "s": 4834, "text": "If the Seasonality is <0, or >8760, or a non-numeric value, FORECAST.ETS returns the #NUM! error." }, { "code": null, "e": 4943, "s": 4932, "text": "Excel 2016" }, { "code": null, "e": 4979, "s": 4943, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 4993, "s": 4979, "text": " Arun Motoori" }, { "code": null, "e": 5028, "s": 4993, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5043, "s": 5028, "text": " Pavan Lalwani" }, { "code": null, "e": 5079, "s": 5043, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5088, "s": 5079, "text": " Inf Sid" }, { "code": null, "e": 5124, "s": 5088, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5139, "s": 5124, "text": " Yoda Learning" }, { "code": null, "e": 5174, "s": 5139, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5189, "s": 5174, "text": " William Fiset" }, { "code": null, "e": 5224, "s": 5189, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5238, "s": 5224, "text": " Sasha Miller" }, { "code": null, "e": 5245, "s": 5238, "text": " Print" }, { "code": null, "e": 5256, "s": 5245, "text": " Add Notes" } ]
Boxplot for anomaly detection. Bite-size data science | by Mahbubul Alam | Towards Data Science
In the previous article, I wrote about outlier detection using a simple statistical technique called Z-score. While that’s an easy way to create a filter for screening outliers, there’s even a better way to do it — using boxplots. Boxplots are an excellent statistical technique to understand the distribution, dispersion and variation of univariate and categorical data— all in a single plot. The purpose of this article is to introduce boxplot as a tool for outlier detection, and I’m doing so focusing on the following areas: the statistical intuition behind boxplots how they are used in outlier detection a tiny bit of programming The boxplot is an effective tool to visualize the spread of data with respect to central values. I really don’t think you need to learn a lot of details, but below is a brief description to give a bit of intuition of how it works under the hood. Don’t feel bad if you don’t get it 100%. A picture is worth a thousand words, so instead of describing the concept in words just take a look at the following figure top-to-bottom to build your own intuition. It all starts with a small dataset of seven observations: 1, 6, 5, 4, 4, 7, 8. If you re-arrange the data small to large, the mid-point is the median. The median splits data into two halves. The mid-points of each halve is called a “quartile”. So we get two quartiles — the 1st quartile is the mid-point of the first half and the 3rd quartile is the mid-point of the second half. As you walk through the steps from the top, in the final part of the figure you have a boxplot and the data it contains. Statistically speaking, a boxplot provides several pieces of information, two important ones are the quartiles, represented by both ends of the box. The distance between these two quartiles is called the Interquartile Range (IQR). In the boxplot below, the length of the box is IQR, and the minimum and maximum values are represented by the whiskers. The whiskers are generally extended into 1.5*IQR distance on either side of the box. Therefore, all data points outside these 1.5*IQR values are flagged as outliers. If you’ve got the intuition about right, understanding how an “outlier” comes into play isn’t that difficult. Check out the following figure. Generally, any data point outside the min and max values (represented by whiskers at both ends of the box) are treated as outliers. Again, if you didn’t understand the statistical concept 100%, no hard feelings. We can drive a car without understanding a lot of its mechanics. But we do have to know how to drive! Just like knowing how to drive, understanding how to implement an algorithm is the most important part of the business. Below is a small snippet to build that programming intuition in Python. # import librariesimport numpy as npimport seaborn as snssns.set_style("whitegrid")# datadata = [1, 4, 4, 5, 6, 7, 8, 13]# create boxplotsns.boxplot(y = data) As you can see, one outlier is pretty clearly visible in this boxplot and we can easily filter that. We don’t know the exact value of the outlier but we know that it’s greater than 12. So let’s filter that outlier value. # filter outliers outliers = [i for i in data if i > 12]print("Outliers are: ", outliers) There you have it, the boxplot detects 13 as an outlier in the dataset. Whether this outlier is an anomaly or not, that, of course, is a different question that can only be answered separately using domain knowledge and additional techniques. The purpose of this article was to give the statistical intuition behind boxplot and demonstrate how it works with a tiny bit of programming example. The power of boxplots lies in the fact that you can “see” the extreme values and make a decision on the threshold for outliers by visual interpretation. The demo here was based on univariate data but it would work in a similar fashion for a multivariate dataset and categorical values. If you liked the article feel free to follow me on Medium or Twitter.
[ { "code": null, "e": 403, "s": 172, "text": "In the previous article, I wrote about outlier detection using a simple statistical technique called Z-score. While that’s an easy way to create a filter for screening outliers, there’s even a better way to do it — using boxplots." }, { "code": null, "e": 566, "s": 403, "text": "Boxplots are an excellent statistical technique to understand the distribution, dispersion and variation of univariate and categorical data— all in a single plot." }, { "code": null, "e": 701, "s": 566, "text": "The purpose of this article is to introduce boxplot as a tool for outlier detection, and I’m doing so focusing on the following areas:" }, { "code": null, "e": 743, "s": 701, "text": "the statistical intuition behind boxplots" }, { "code": null, "e": 782, "s": 743, "text": "how they are used in outlier detection" }, { "code": null, "e": 808, "s": 782, "text": "a tiny bit of programming" }, { "code": null, "e": 1095, "s": 808, "text": "The boxplot is an effective tool to visualize the spread of data with respect to central values. I really don’t think you need to learn a lot of details, but below is a brief description to give a bit of intuition of how it works under the hood. Don’t feel bad if you don’t get it 100%." }, { "code": null, "e": 1341, "s": 1095, "text": "A picture is worth a thousand words, so instead of describing the concept in words just take a look at the following figure top-to-bottom to build your own intuition. It all starts with a small dataset of seven observations: 1, 6, 5, 4, 4, 7, 8." }, { "code": null, "e": 1763, "s": 1341, "text": "If you re-arrange the data small to large, the mid-point is the median. The median splits data into two halves. The mid-points of each halve is called a “quartile”. So we get two quartiles — the 1st quartile is the mid-point of the first half and the 3rd quartile is the mid-point of the second half. As you walk through the steps from the top, in the final part of the figure you have a boxplot and the data it contains." }, { "code": null, "e": 1994, "s": 1763, "text": "Statistically speaking, a boxplot provides several pieces of information, two important ones are the quartiles, represented by both ends of the box. The distance between these two quartiles is called the Interquartile Range (IQR)." }, { "code": null, "e": 2280, "s": 1994, "text": "In the boxplot below, the length of the box is IQR, and the minimum and maximum values are represented by the whiskers. The whiskers are generally extended into 1.5*IQR distance on either side of the box. Therefore, all data points outside these 1.5*IQR values are flagged as outliers." }, { "code": null, "e": 2422, "s": 2280, "text": "If you’ve got the intuition about right, understanding how an “outlier” comes into play isn’t that difficult. Check out the following figure." }, { "code": null, "e": 2554, "s": 2422, "text": "Generally, any data point outside the min and max values (represented by whiskers at both ends of the box) are treated as outliers." }, { "code": null, "e": 2736, "s": 2554, "text": "Again, if you didn’t understand the statistical concept 100%, no hard feelings. We can drive a car without understanding a lot of its mechanics. But we do have to know how to drive!" }, { "code": null, "e": 2928, "s": 2736, "text": "Just like knowing how to drive, understanding how to implement an algorithm is the most important part of the business. Below is a small snippet to build that programming intuition in Python." }, { "code": null, "e": 3087, "s": 2928, "text": "# import librariesimport numpy as npimport seaborn as snssns.set_style(\"whitegrid\")# datadata = [1, 4, 4, 5, 6, 7, 8, 13]# create boxplotsns.boxplot(y = data)" }, { "code": null, "e": 3308, "s": 3087, "text": "As you can see, one outlier is pretty clearly visible in this boxplot and we can easily filter that. We don’t know the exact value of the outlier but we know that it’s greater than 12. So let’s filter that outlier value." }, { "code": null, "e": 3398, "s": 3308, "text": "# filter outliers outliers = [i for i in data if i > 12]print(\"Outliers are: \", outliers)" }, { "code": null, "e": 3641, "s": 3398, "text": "There you have it, the boxplot detects 13 as an outlier in the dataset. Whether this outlier is an anomaly or not, that, of course, is a different question that can only be answered separately using domain knowledge and additional techniques." }, { "code": null, "e": 4077, "s": 3641, "text": "The purpose of this article was to give the statistical intuition behind boxplot and demonstrate how it works with a tiny bit of programming example. The power of boxplots lies in the fact that you can “see” the extreme values and make a decision on the threshold for outliers by visual interpretation. The demo here was based on univariate data but it would work in a similar fashion for a multivariate dataset and categorical values." } ]
Getting Started with Pytorch: How to Train a Deep Learning Model With Pytorch | by Anuj Syal | Towards Data Science
Exploring the deep world of machine learning and artificial intelligence, today I will introduce my fellow AI enthusiasts to Pytorch. Primarily developed by Facebook’s AI Research Lab, Pytorch is an open-source machine learning library that aids in the production deployment of models from research prototyping by accelerating the process. The library consists of Python programs that facilitate building deep learning projects. Pytorch is easier to read and understand, is flexible, and allows deep learning models to be expressed in idiomatic Python, making it a go-to tool for those looking to develop apps that leverage computer vision and natural language processing. The best way to get started with Pytorch is through Google Colaboratory. Using this, you can easily write and execute Python in your browser. Colab is ideal as it is not only a great tool to help improve your coding skills but also allows you to develop deep learning applications using libraries such as Pytorch, TensorFlow, Keras, and OpenCV. The best part? Colab supports free GPU. The flexibility of the tool lets you create, upload, store, or share notebooks, import from directories, or upload your personal Jupyter notebooks to get started. Recently, Colab added support for native Pytorch, enabling you to run Torch imports without the following code: # http://pytorch.org/from os.path import existsfrom wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tagplatform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())cuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\.\([0-9]*\)\.\([0-9]*\)$/cu\1\2/'accelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu'!pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.1-{platform}-linux_x86_64.whl torchvisionimport torch In any deep learning model, you have to deal with data that is to be classified first before any network can be trained on it. One has to deal with image, text, audio, or video data. While using Pytorch, you can use standard python packages that load data into a numpy array which can then be converted into a torch.*Tensor. When it comes to image data, packages such as Pillow, OpenCV are useful. For audio, scipy and librosa are recommended. For text, raw Python or Cython based loading, or NLTK and SpaCy are useful. For visual data, Pytorch has created a package called torchvision that includes data loaders for common datasets such as Imagenet, CIFAR10, MNIST, etc. and data transformers for images, viz., torchvision.datasets and torch.utils.data.DataLoader. We will look at this tutorial for training a classifier that uses the CIFAR10 dataset. It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size. To begin training an image classifier, you have to first load and normalize the CIFAR10 training and test datasets using torchvision. Once you do that, move forth by defining a convolutional neural network. The third step is to define a loss function. Next, train the network on the training data, and lastly, test the network on the test data. We will now look at each step in details: import torchimport torchvisionimport torchvision.transforms as transforms The output of torchvision datasets are PILImage images of range [0, 1]. We transform them to Tensors of normalized range [-1, 1]. .. note: If running on Windows and you get a BrokenPipeError, try setting the num_worker of torch.utils.data.DataLoader() to 0. transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,shuffle=True, num_workers=2)testset = torchvision.datasets.CIFAR10(root='./data', train=False,download=True, transform=transform)testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') Out: Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gzExtracting ./data/cifar-10-python.tar.gz to ./dataFiles already downloaded and verified Let’s check out the images. import matplotlib.pyplot as pltimport numpy as np# image showdef imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show()# select random imagesdataiter = iter(trainloader)images, labels = dataiter.next()# show imshow(torchvision.utils.make_grid(images))# show labelsprint(' '.join('%5s' % classes[labels[j]] for j in range(4))) Out:frog frog dog bird Now, you have to copy the neural network from the Neural Networks section before and modify it to take 3-channel images. import torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return xnet = Net() For this, you can use a classification cross-entropy loss and SGD with momentum. import torch.optim as optimcriterion = nn.CrossEntropyLoss()optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) A crucial and interesting step in training the classifier; you simply have to loop over the data iterator and feed the inputs to the network and optimize. for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data# zero the parameter gradients optimizer.zero_grad()# forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step()# print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0print('Finished Training')# print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0print('Finished Training') At this stage, don’t forget to save your trained model: PATH = './cifar_net.pth'torch.save(net.state_dict(), PATH) You can also follow this guide to learn more about saving Pytorch models correctly. Now that the training is complete, it is time to test the network. To check if the network has learnt anything, we will predict the class label that the neural network outputs, and check it against the ground-truth. If the prediction is correct, we add the sample to the list of correct predictions. The first step here will require you to display an image from the test set to get familiar. dataiter = iter(testloader)images, labels = dataiter.next()# print imagesimshow(torchvision.utils.make_grid(images))print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4))) Out:GroundTruth: cat ship ship plane Now, load back in the saved model. net = Net()net.load_state_dict(torch.load(PATH)) You can now check what this neural network thinks these examples above are: outputs = net(images) The outputs are energies for the 10 classes. The higher the energy for a class, the more the network thinks that the image is of the particular class. So, let’s get the index of the highest energy: _, predicted = torch.max(outputs, 1)print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))Out:Predicted: cat ship plane plane The results seem pretty good. Let us look at how the network performs on the whole dataset correct = 0total = 0with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total))Out:Accuracy of the network on the 10000 test images: 57 % That looks way better than chance, which is 10% accuracy (randomly picking a class out of 10 classes). This shows that the network has learnt something. Now, let’s look at the classes that performed well and the classes that did not perform well: class_correct = list(0. for i in range(10))class_total = list(0. for i in range(10))with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs, 1) c = (predicted == labels).squeeze() for i in range(4): label = labels[i] class_correct[label] += c[i].item() class_total[label] += 1for i in range(10): print('Accuracy of %5s : %2d %%' % ( classes[i], 100 * class_correct[i] / class_total[i]))Out:Accuracy of plane : 63 %Accuracy of car : 59 %Accuracy of bird : 37 %Accuracy of cat : 24 %Accuracy of deer : 53 %Accuracy of dog : 64 %Accuracy of frog : 73 %Accuracy of horse : 62 %Accuracy of ship : 65 %Accuracy of truck : 72 % Next, we can run these neural networks on the GPU. Similar to how you would transfer a Tensor onto the GPU, you will transfer the neural net onto the GPU. First, we need to define the device as the first visible cuda device if we have CUDA available: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")# Assuming that we are on a CUDA machine, this should print a CUDA device:print(device)Out:Cuda:0 The rest of this section assumes that the device is a CUDA device. Then these methods will recursively go over all modules and convert their parameters and buffers to CUDA tensors: net.to(device) Remember that you will have to send the inputs and targets at every step to the GPU too: inputs, labels = data[0].to(device), data[1].to(device) You may notice that there is no massive speedup compared to CPU, this is because your network is small. To address this, try increasing the width of your network (argument 2 of the first nn.Conv2d, and argument 1 of the second nn.Conv2d — they need to be the same number), and see what kind of speedup you get. By following the tutorial above, you have successfully managed to train a small neural network to classify images. Checkout this video on my YouTube Channel If you are interested in similar content do follow me on Twitter and Linkedin
[ { "code": null, "e": 387, "s": 47, "text": "Exploring the deep world of machine learning and artificial intelligence, today I will introduce my fellow AI enthusiasts to Pytorch. Primarily developed by Facebook’s AI Research Lab, Pytorch is an open-source machine learning library that aids in the production deployment of models from research prototyping by accelerating the process." }, { "code": null, "e": 720, "s": 387, "text": "The library consists of Python programs that facilitate building deep learning projects. Pytorch is easier to read and understand, is flexible, and allows deep learning models to be expressed in idiomatic Python, making it a go-to tool for those looking to develop apps that leverage computer vision and natural language processing." }, { "code": null, "e": 1065, "s": 720, "text": "The best way to get started with Pytorch is through Google Colaboratory. Using this, you can easily write and execute Python in your browser. Colab is ideal as it is not only a great tool to help improve your coding skills but also allows you to develop deep learning applications using libraries such as Pytorch, TensorFlow, Keras, and OpenCV." }, { "code": null, "e": 1380, "s": 1065, "text": "The best part? Colab supports free GPU. The flexibility of the tool lets you create, upload, store, or share notebooks, import from directories, or upload your personal Jupyter notebooks to get started. Recently, Colab added support for native Pytorch, enabling you to run Torch imports without the following code:" }, { "code": null, "e": 1850, "s": 1380, "text": "# http://pytorch.org/from os.path import existsfrom wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tagplatform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())cuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\\.\\([0-9]*\\)\\.\\([0-9]*\\)$/cu\\1\\2/'accelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu'!pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.1-{platform}-linux_x86_64.whl torchvisionimport torch" }, { "code": null, "e": 2175, "s": 1850, "text": "In any deep learning model, you have to deal with data that is to be classified first before any network can be trained on it. One has to deal with image, text, audio, or video data. While using Pytorch, you can use standard python packages that load data into a numpy array which can then be converted into a torch.*Tensor." }, { "code": null, "e": 2370, "s": 2175, "text": "When it comes to image data, packages such as Pillow, OpenCV are useful. For audio, scipy and librosa are recommended. For text, raw Python or Cython based loading, or NLTK and SpaCy are useful." }, { "code": null, "e": 2616, "s": 2370, "text": "For visual data, Pytorch has created a package called torchvision that includes data loaders for common datasets such as Imagenet, CIFAR10, MNIST, etc. and data transformers for images, viz., torchvision.datasets and torch.utils.data.DataLoader." }, { "code": null, "e": 2910, "s": 2616, "text": "We will look at this tutorial for training a classifier that uses the CIFAR10 dataset. It has the classes: ‘airplane’, ‘automobile’, ‘bird’, ‘cat’, ‘deer’, ‘dog’, ‘frog’, ‘horse’, ‘ship’, ‘truck’. The images in CIFAR-10 are of size 3x32x32, i.e. 3-channel color images of 32x32 pixels in size." }, { "code": null, "e": 3255, "s": 2910, "text": "To begin training an image classifier, you have to first load and normalize the CIFAR10 training and test datasets using torchvision. Once you do that, move forth by defining a convolutional neural network. The third step is to define a loss function. Next, train the network on the training data, and lastly, test the network on the test data." }, { "code": null, "e": 3297, "s": 3255, "text": "We will now look at each step in details:" }, { "code": null, "e": 3371, "s": 3297, "text": "import torchimport torchvisionimport torchvision.transforms as transforms" }, { "code": null, "e": 3510, "s": 3371, "text": "The output of torchvision datasets are PILImage images of range [0, 1]. We transform them to Tensors of normalized range [-1, 1]. .. note:" }, { "code": null, "e": 3629, "s": 3510, "text": "If running on Windows and you get a BrokenPipeError, try setting the num_worker of torch.utils.data.DataLoader() to 0." }, { "code": null, "e": 4219, "s": 3629, "text": "transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,shuffle=True, num_workers=2)testset = torchvision.datasets.CIFAR10(root='./data', train=False,download=True, transform=transform)testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')" }, { "code": null, "e": 4224, "s": 4219, "text": "Out:" }, { "code": null, "e": 4412, "s": 4224, "text": "Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gzExtracting ./data/cifar-10-python.tar.gz to ./dataFiles already downloaded and verified" }, { "code": null, "e": 4440, "s": 4412, "text": "Let’s check out the images." }, { "code": null, "e": 4844, "s": 4440, "text": "import matplotlib.pyplot as pltimport numpy as np# image showdef imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show()# select random imagesdataiter = iter(trainloader)images, labels = dataiter.next()# show imshow(torchvision.utils.make_grid(images))# show labelsprint(' '.join('%5s' % classes[labels[j]] for j in range(4)))" }, { "code": null, "e": 4867, "s": 4844, "text": "Out:frog frog dog bird" }, { "code": null, "e": 4988, "s": 4867, "text": "Now, you have to copy the neural network from the Neural Networks section before and modify it to take 3-channel images." }, { "code": null, "e": 5610, "s": 4988, "text": "import torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return xnet = Net()" }, { "code": null, "e": 5691, "s": 5610, "text": "For this, you can use a classification cross-entropy loss and SGD with momentum." }, { "code": null, "e": 5815, "s": 5691, "text": "import torch.optim as optimcriterion = nn.CrossEntropyLoss()optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)" }, { "code": null, "e": 5970, "s": 5815, "text": "A crucial and interesting step in training the classifier; you simply have to loop over the data iterator and feed the inputs to the network and optimize." }, { "code": null, "e": 6940, "s": 5970, "text": "for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data# zero the parameter gradients optimizer.zero_grad()# forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step()# print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0print('Finished Training')# print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0print('Finished Training')" }, { "code": null, "e": 6996, "s": 6940, "text": "At this stage, don’t forget to save your trained model:" }, { "code": null, "e": 7055, "s": 6996, "text": "PATH = './cifar_net.pth'torch.save(net.state_dict(), PATH)" }, { "code": null, "e": 7139, "s": 7055, "text": "You can also follow this guide to learn more about saving Pytorch models correctly." }, { "code": null, "e": 7355, "s": 7139, "text": "Now that the training is complete, it is time to test the network. To check if the network has learnt anything, we will predict the class label that the neural network outputs, and check it against the ground-truth." }, { "code": null, "e": 7439, "s": 7355, "text": "If the prediction is correct, we add the sample to the list of correct predictions." }, { "code": null, "e": 7531, "s": 7439, "text": "The first step here will require you to display an image from the test set to get familiar." }, { "code": null, "e": 7726, "s": 7531, "text": "dataiter = iter(testloader)images, labels = dataiter.next()# print imagesimshow(torchvision.utils.make_grid(images))print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))" }, { "code": null, "e": 7768, "s": 7726, "text": "Out:GroundTruth: cat ship ship plane" }, { "code": null, "e": 7803, "s": 7768, "text": "Now, load back in the saved model." }, { "code": null, "e": 7852, "s": 7803, "text": "net = Net()net.load_state_dict(torch.load(PATH))" }, { "code": null, "e": 7928, "s": 7852, "text": "You can now check what this neural network thinks these examples above are:" }, { "code": null, "e": 7950, "s": 7928, "text": "outputs = net(images)" }, { "code": null, "e": 8148, "s": 7950, "text": "The outputs are energies for the 10 classes. The higher the energy for a class, the more the network thinks that the image is of the particular class. So, let’s get the index of the highest energy:" }, { "code": null, "e": 8303, "s": 8148, "text": "_, predicted = torch.max(outputs, 1)print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))Out:Predicted: cat ship plane plane" }, { "code": null, "e": 8333, "s": 8303, "text": "The results seem pretty good." }, { "code": null, "e": 8394, "s": 8333, "text": "Let us look at how the network performs on the whole dataset" }, { "code": null, "e": 8806, "s": 8394, "text": "correct = 0total = 0with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total))Out:Accuracy of the network on the 10000 test images: 57 %" }, { "code": null, "e": 8959, "s": 8806, "text": "That looks way better than chance, which is 10% accuracy (randomly picking a class out of 10 classes). This shows that the network has learnt something." }, { "code": null, "e": 9053, "s": 8959, "text": "Now, let’s look at the classes that performed well and the classes that did not perform well:" }, { "code": null, "e": 9832, "s": 9053, "text": "class_correct = list(0. for i in range(10))class_total = list(0. for i in range(10))with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs, 1) c = (predicted == labels).squeeze() for i in range(4): label = labels[i] class_correct[label] += c[i].item() class_total[label] += 1for i in range(10): print('Accuracy of %5s : %2d %%' % ( classes[i], 100 * class_correct[i] / class_total[i]))Out:Accuracy of plane : 63 %Accuracy of car : 59 %Accuracy of bird : 37 %Accuracy of cat : 24 %Accuracy of deer : 53 %Accuracy of dog : 64 %Accuracy of frog : 73 %Accuracy of horse : 62 %Accuracy of ship : 65 %Accuracy of truck : 72 %" }, { "code": null, "e": 9883, "s": 9832, "text": "Next, we can run these neural networks on the GPU." }, { "code": null, "e": 10083, "s": 9883, "text": "Similar to how you would transfer a Tensor onto the GPU, you will transfer the neural net onto the GPU. First, we need to define the device as the first visible cuda device if we have CUDA available:" }, { "code": null, "e": 10252, "s": 10083, "text": "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")# Assuming that we are on a CUDA machine, this should print a CUDA device:print(device)Out:Cuda:0" }, { "code": null, "e": 10319, "s": 10252, "text": "The rest of this section assumes that the device is a CUDA device." }, { "code": null, "e": 10433, "s": 10319, "text": "Then these methods will recursively go over all modules and convert their parameters and buffers to CUDA tensors:" }, { "code": null, "e": 10448, "s": 10433, "text": "net.to(device)" }, { "code": null, "e": 10537, "s": 10448, "text": "Remember that you will have to send the inputs and targets at every step to the GPU too:" }, { "code": null, "e": 10593, "s": 10537, "text": "inputs, labels = data[0].to(device), data[1].to(device)" }, { "code": null, "e": 10904, "s": 10593, "text": "You may notice that there is no massive speedup compared to CPU, this is because your network is small. To address this, try increasing the width of your network (argument 2 of the first nn.Conv2d, and argument 1 of the second nn.Conv2d — they need to be the same number), and see what kind of speedup you get." }, { "code": null, "e": 11019, "s": 10904, "text": "By following the tutorial above, you have successfully managed to train a small neural network to classify images." }, { "code": null, "e": 11061, "s": 11019, "text": "Checkout this video on my YouTube Channel" } ]
Count of Palindromic substrings in an Index range - GeeksforGeeks
21 May, 2021 Given a string str of small alphabetic characters other than this we will be given many substrings of this string in form of index tuples. We need to find out the count of the palindromic substrings in given substring range. Examples: Input : String str = "xyaabax" Range1 = (3, 5) Range2 = (2, 3) Output : 4 3 For Range1, substring is "aba" Count of palindromic substring in "aba" is four : "a", "b", "aba", "a" For Range2, substring is "aa" Count of palindromic substring in "aa" is 3 : "a", "a", "aa" Prerequisite : Count All Palindrome Sub-Strings in a StringWe can solve this problem using dynamic programming. First we will make a 2D array isPalin, isPalin[i][j] will be 1 if string(i..j) is a palindrome otherwise it will be 0. After constructing isPalin we will construct another 2D array dp, dp[i][j] will tell the count of palindromic substring in string(i..j) Now we can write the relation among isPalin and dp values as shown below, // isPalin[i][j] will be 1 if ith and jth characters // are equal and mid substring str(i+1..j-1) is also // a palindrome isPalin[i][j] = (str[i] == str[j]) and (isPalin[i + 1][j – 1]) // Similar to set theory we can write the relation among // dp values as, // dp[i][j] will be addition of number of palindromes from // i to j-1 and i+1 to j subtracting palindromes from i+1 // to j-1 because they are counted twice once in dp[i][j-1] // and then in dp[i + 1][j] plus 1 if str(i..j) is also a // palindrome dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1] + isPalin[i][j]; Total time complexity of solution will be O(length ^ 2) for constructing dp array then O(1) per query. C++ Java Python3 C# PHP Javascript // C++ program to query number of palindromic// substrings of a string in a range#include <bits/stdc++.h>using namespace std;#define M 50 // Utility method to construct the dp arrayvoid constructDP(int dp[M][M], string str){ int l = str.length(); // declare 2D array isPalin, isPalin[i][j] will // be 1 if str(i..j) is palindrome int isPalin[l + 1][l + 1]; // initialize dp and isPalin array by zeros for (int i = 0; i <= l; i++) { for (int j = 0; j <= l; j++) { isPalin[i][j] = dp[i][j] = 0; } } // loop for starting index of range for (int i = l - 1; i >= 0; i--) { // initialize value for one character strings as 1 isPalin[i][i] = 1; dp[i][i] = 1; // loop for ending index of range for (int j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ isPalin[i][j] = (str[i] == str[j] && (i + 1 > j - 1 || isPalin[i + 1][j - 1])); /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]; } }} // method returns count of palindromic substring in range (l, r)int countOfPalindromeInRange(int dp[M][M], int l, int r){ return dp[l][r];} // Driver code to test above methodsint main(){ string str = "xyaabax"; int dp[M][M]; constructDP(dp, str); int l = 3; int r = 5; cout << countOfPalindromeInRange(dp, l, r); return 0;} // Java program to query number of palindromic// substrings of a string in a rangeimport java.io.*; class GFG { // Function to construct the dp array static void constructDp(int dp[][], String str) { int l = str.length(); // declare 2D array isPalin, isPalin[i][j] will // be 1 if str(i..j) is palindrome int[][] isPalin = new int[l + 1][l + 1]; // initialize dp and isPalin array by zeros for (int i = 0; i <= l; i++) { for (int j = 0; j <= l; j++) { isPalin[i][j] = dp[i][j] = 0; } } // loop for starting index of range for (int i = l - 1; i >= 0; i--) { // initialize value for one character strings as 1 isPalin[i][i] = 1; dp[i][i] = 1; // loop for ending index of range for (int j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ isPalin[i][j] = (str.charAt(i) == str.charAt(j) && (i + 1 > j - 1 || (isPalin[i + 1][j - 1]) != 0)) ? 1 : 0; /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]; } } } // method returns count of palindromic substring in range (l, r) static int countOfPalindromeInRange(int dp[][], int l, int r) { return dp[l][r]; } // driver program public static void main(String args[]) { int MAX = 50; String str = "xyaabax"; int[][] dp = new int[MAX][MAX]; constructDp(dp, str); int l = 3; int r = 5; System.out.println(countOfPalindromeInRange(dp, l, r)); }} // Contributed by Pramod Kumar # Python3 program to query the number of# palindromic substrings of a string in a rangeM = 50 # Utility method to construct the dp arraydef constructDP(dp, string): l = len(string) # declare 2D array isPalin, isPalin[i][j] # will be 1 if str(i..j) is palindrome # and initialize it with zero isPalin = [[0 for i in range(l + 1)] for j in range(l + 1)] # loop for starting index of range for i in range(l - 1, -1, -1): # initialize value for one # character strings as 1 isPalin[i][i], dp[i][i] = 1, 1 # loop for ending index of range for j in range(i + 1, l): # isPalin[i][j] will be 1 if ith and jth # characters are equal and mid substring # str(i+1..j-1) is also a palindrome isPalin[i][j] = (string[i] == string[j] and (i + 1 > j - 1 or isPalin[i + 1][j - 1])) # dp[i][j] will be addition of number # of palindromes from i to j-1 and i+1 # to j subtracting palindromes from i+1 # to j-1 (as counted twice) plus 1 if # str(i..j) is also a palindrome dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]) # Method returns count of palindromic# substring in range (l, r)def countOfPalindromeInRange(dp, l, r): return dp[l][r] # Driver codeif __name__ == "__main__": string = "xyaabax" dp = [[0 for i in range(M)] for j in range(M)] constructDP(dp, string) l, r = 3, 5 print(countOfPalindromeInRange(dp, l, r)) # This code is contributed by Rituraj Jain // C# program to query number of palindromic// substrings of a string in a rangeusing System; class GFG { // Function to construct the dp array static void constructDp(int[, ] dp, string str) { int l = str.Length; // declare 2D array isPalin, isPalin[i][j] // will be 1 if str(i..j) is palindrome int[, ] isPalin = new int[l + 1, l + 1]; // initialize dp and isPalin array by zeros for (int i = 0; i <= l; i++) { for (int j = 0; j <= l; j++) { isPalin[i, j] = dp[i, j] = 0; } } // loop for starting index of range for (int i = l - 1; i >= 0; i--) { // initialize value for one // character strings as 1 isPalin[i, i] = 1; dp[i, i] = 1; // loop for ending index of range for (int j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome*/ isPalin[i, j] = (str[i] == str[j] && (i + 1 > j - 1 || (isPalin[i + 1, j - 1]) != 0)) ? 1 : 0; /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i, j] = dp[i, j - 1] + dp[i + 1, j] - dp[i + 1, j - 1] + isPalin[i, j]; } } } // method returns count of palindromic // substring in range (l, r) static int countOfPalindromeInRange(int[, ] dp, int l, int r) { return dp[l, r]; } // driver program public static void Main() { int MAX = 50; string str = "xyaabax"; int[, ] dp = new int[MAX, MAX]; constructDp(dp, str); int l = 3; int r = 5; Console.WriteLine(countOfPalindromeInRange(dp, l, r)); }} // This code is contributed by vt_m. <?php// PHP program to query number of palindromic// substrings of a string in a range $GLOBALS['M'] = 50; // Utility method to construct the dp arrayfunction constructDP($dp, $str){ $l = strlen($str); // declare 2D array isPalin, isPalin[i][j] // will be 1 if str(i..j) is palindrome $isPalin = array(array()); // initialize dp and isPalin array by zeros for ($i = 0; $i <= $l; $i++) { for ($j = 0; $j <= $l; $j++) { $isPalin[$i][$j] = $dp[$i][$j] = 0; } } // loop for starting index of range for ($i = $l - 1; $i >= 0; $i--) { // initialize value for one character // strings as 1 $isPalin[$i][$i] = 1; $dp[$i][$i] = 1; // loop for ending index of range for ($j = $i + 1; $j < $l; $j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ $isPalin[$i][$j] = ($str[$i] == $str[$j] && ($i + 1 > $j - 1 || $isPalin[$i + 1][$j - 1])); /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ $dp[$i][$j] = $dp[$i][$j - 1] + $dp[$i + 1][$j] - $dp[$i + 1][$j - 1] + $isPalin[$i][$j]; } } return $dp ;} // method returns count of palindromic// substring in range (l, r)function countOfPalindromeInRange($dp, $l, $r){ return $dp[$l][$r];} // Driver code$str = "xyaabax"; $dp = array(array()); for($i = 0; $i < $GLOBALS['M']; $i++ ) for($j = 0; $j < $GLOBALS['M']; $j++) $dp[$i][$j] = 0; $dp = constructDP($dp, $str); $l = 3;$r = 5; echo countOfPalindromeInRange($dp, $l, $r); // This code is contributed by Ryuga?> <script> // Javascript program to query number of palindromic // substrings of a string in a range // Function to construct the dp array function constructDp(dp, str) { let l = str.length; // declare 2D array isPalin, isPalin[i][j] will // be 1 if str(i..j) is palindrome let isPalin = new Array(l + 1); // initialize dp and isPalin array by zeros for (let i = 0; i <= l; i++) { isPalin[i] = new Array(l + 1); for (let j = 0; j <= l; j++) { isPalin[i][j] = dp[i][j] = 0; } } // loop for starting index of range for (let i = l - 1; i >= 0; i--) { // initialize value for one character strings as 1 isPalin[i][i] = 1; dp[i][i] = 1; // loop for ending index of range for (let j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ isPalin[i][j] = (str[i] == str[j] && (i + 1 > j - 1 || (isPalin[i + 1][j - 1]) != 0)) ? 1 : 0; /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]; } } } // method returns count of palindromic substring in range (l, r) function countOfPalindromeInRange(dp, l, r) { return dp[l][r]; } let MAX = 50; let str = "xyaabax"; let dp = new Array(MAX); for (let i = 0; i < MAX; i++) { dp[i] = new Array(MAX); for (let j = 0; j < MAX; j++) { dp[i][j] = 0; } } constructDp(dp, str); let l = 3; let r = 5; document.write(countOfPalindromeInRange(dp, l, r)); </script> Output: 4 This article is contributed by Utkarsh Trivedi. 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. vt_m ankthon rituraj_jain divyesh072019 palindrome Dynamic Programming Strings Strings Dynamic Programming palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Subset Sum Problem | DP-25 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 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 24858, "s": 24830, "text": "\n21 May, 2021" }, { "code": null, "e": 25095, "s": 24858, "text": "Given a string str of small alphabetic characters other than this we will be given many substrings of this string in form of index tuples. We need to find out the count of the palindromic substrings in given substring range. Examples: " }, { "code": null, "e": 25403, "s": 25095, "text": "Input : String str = \"xyaabax\"\n Range1 = (3, 5) \n Range2 = (2, 3) \nOutput : 4\n 3\nFor Range1, substring is \"aba\"\nCount of palindromic substring in \"aba\" is \nfour : \"a\", \"b\", \"aba\", \"a\"\nFor Range2, substring is \"aa\"\nCount of palindromic substring in \"aa\" is \n3 : \"a\", \"a\", \"aa\"" }, { "code": null, "e": 25848, "s": 25405, "text": "Prerequisite : Count All Palindrome Sub-Strings in a StringWe can solve this problem using dynamic programming. First we will make a 2D array isPalin, isPalin[i][j] will be 1 if string(i..j) is a palindrome otherwise it will be 0. After constructing isPalin we will construct another 2D array dp, dp[i][j] will tell the count of palindromic substring in string(i..j) Now we can write the relation among isPalin and dp values as shown below, " }, { "code": null, "e": 26497, "s": 25848, "text": "// isPalin[i][j] will be 1 if ith and jth characters \n// are equal and mid substring str(i+1..j-1) is also\n// a palindrome\nisPalin[i][j] = (str[i] == str[j]) and \n (isPalin[i + 1][j – 1])\n \n// Similar to set theory we can write the relation among\n// dp values as,\n// dp[i][j] will be addition of number of palindromes from \n// i to j-1 and i+1 to j subtracting palindromes from i+1\n// to j-1 because they are counted twice once in dp[i][j-1] \n// and then in dp[i + 1][j] plus 1 if str(i..j) is also a\n// palindrome\ndp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1] + \n isPalin[i][j];" }, { "code": null, "e": 26602, "s": 26497, "text": "Total time complexity of solution will be O(length ^ 2) for constructing dp array then O(1) per query. " }, { "code": null, "e": 26606, "s": 26602, "text": "C++" }, { "code": null, "e": 26611, "s": 26606, "text": "Java" }, { "code": null, "e": 26619, "s": 26611, "text": "Python3" }, { "code": null, "e": 26622, "s": 26619, "text": "C#" }, { "code": null, "e": 26626, "s": 26622, "text": "PHP" }, { "code": null, "e": 26637, "s": 26626, "text": "Javascript" }, { "code": "// C++ program to query number of palindromic// substrings of a string in a range#include <bits/stdc++.h>using namespace std;#define M 50 // Utility method to construct the dp arrayvoid constructDP(int dp[M][M], string str){ int l = str.length(); // declare 2D array isPalin, isPalin[i][j] will // be 1 if str(i..j) is palindrome int isPalin[l + 1][l + 1]; // initialize dp and isPalin array by zeros for (int i = 0; i <= l; i++) { for (int j = 0; j <= l; j++) { isPalin[i][j] = dp[i][j] = 0; } } // loop for starting index of range for (int i = l - 1; i >= 0; i--) { // initialize value for one character strings as 1 isPalin[i][i] = 1; dp[i][i] = 1; // loop for ending index of range for (int j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ isPalin[i][j] = (str[i] == str[j] && (i + 1 > j - 1 || isPalin[i + 1][j - 1])); /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]; } }} // method returns count of palindromic substring in range (l, r)int countOfPalindromeInRange(int dp[M][M], int l, int r){ return dp[l][r];} // Driver code to test above methodsint main(){ string str = \"xyaabax\"; int dp[M][M]; constructDP(dp, str); int l = 3; int r = 5; cout << countOfPalindromeInRange(dp, l, r); return 0;}", "e": 28430, "s": 26637, "text": null }, { "code": "// Java program to query number of palindromic// substrings of a string in a rangeimport java.io.*; class GFG { // Function to construct the dp array static void constructDp(int dp[][], String str) { int l = str.length(); // declare 2D array isPalin, isPalin[i][j] will // be 1 if str(i..j) is palindrome int[][] isPalin = new int[l + 1][l + 1]; // initialize dp and isPalin array by zeros for (int i = 0; i <= l; i++) { for (int j = 0; j <= l; j++) { isPalin[i][j] = dp[i][j] = 0; } } // loop for starting index of range for (int i = l - 1; i >= 0; i--) { // initialize value for one character strings as 1 isPalin[i][i] = 1; dp[i][i] = 1; // loop for ending index of range for (int j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ isPalin[i][j] = (str.charAt(i) == str.charAt(j) && (i + 1 > j - 1 || (isPalin[i + 1][j - 1]) != 0)) ? 1 : 0; /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]; } } } // method returns count of palindromic substring in range (l, r) static int countOfPalindromeInRange(int dp[][], int l, int r) { return dp[l][r]; } // driver program public static void main(String args[]) { int MAX = 50; String str = \"xyaabax\"; int[][] dp = new int[MAX][MAX]; constructDp(dp, str); int l = 3; int r = 5; System.out.println(countOfPalindromeInRange(dp, l, r)); }} // Contributed by Pramod Kumar", "e": 30494, "s": 28430, "text": null }, { "code": "# Python3 program to query the number of# palindromic substrings of a string in a rangeM = 50 # Utility method to construct the dp arraydef constructDP(dp, string): l = len(string) # declare 2D array isPalin, isPalin[i][j] # will be 1 if str(i..j) is palindrome # and initialize it with zero isPalin = [[0 for i in range(l + 1)] for j in range(l + 1)] # loop for starting index of range for i in range(l - 1, -1, -1): # initialize value for one # character strings as 1 isPalin[i][i], dp[i][i] = 1, 1 # loop for ending index of range for j in range(i + 1, l): # isPalin[i][j] will be 1 if ith and jth # characters are equal and mid substring # str(i+1..j-1) is also a palindrome isPalin[i][j] = (string[i] == string[j] and (i + 1 > j - 1 or isPalin[i + 1][j - 1])) # dp[i][j] will be addition of number # of palindromes from i to j-1 and i+1 # to j subtracting palindromes from i+1 # to j-1 (as counted twice) plus 1 if # str(i..j) is also a palindrome dp[i][j] = (dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]) # Method returns count of palindromic# substring in range (l, r)def countOfPalindromeInRange(dp, l, r): return dp[l][r] # Driver codeif __name__ == \"__main__\": string = \"xyaabax\" dp = [[0 for i in range(M)] for j in range(M)] constructDP(dp, string) l, r = 3, 5 print(countOfPalindromeInRange(dp, l, r)) # This code is contributed by Rituraj Jain", "e": 32147, "s": 30494, "text": null }, { "code": "// C# program to query number of palindromic// substrings of a string in a rangeusing System; class GFG { // Function to construct the dp array static void constructDp(int[, ] dp, string str) { int l = str.Length; // declare 2D array isPalin, isPalin[i][j] // will be 1 if str(i..j) is palindrome int[, ] isPalin = new int[l + 1, l + 1]; // initialize dp and isPalin array by zeros for (int i = 0; i <= l; i++) { for (int j = 0; j <= l; j++) { isPalin[i, j] = dp[i, j] = 0; } } // loop for starting index of range for (int i = l - 1; i >= 0; i--) { // initialize value for one // character strings as 1 isPalin[i, i] = 1; dp[i, i] = 1; // loop for ending index of range for (int j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome*/ isPalin[i, j] = (str[i] == str[j] && (i + 1 > j - 1 || (isPalin[i + 1, j - 1]) != 0)) ? 1 : 0; /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i, j] = dp[i, j - 1] + dp[i + 1, j] - dp[i + 1, j - 1] + isPalin[i, j]; } } } // method returns count of palindromic // substring in range (l, r) static int countOfPalindromeInRange(int[, ] dp, int l, int r) { return dp[l, r]; } // driver program public static void Main() { int MAX = 50; string str = \"xyaabax\"; int[, ] dp = new int[MAX, MAX]; constructDp(dp, str); int l = 3; int r = 5; Console.WriteLine(countOfPalindromeInRange(dp, l, r)); }} // This code is contributed by vt_m.", "e": 34316, "s": 32147, "text": null }, { "code": "<?php// PHP program to query number of palindromic// substrings of a string in a range $GLOBALS['M'] = 50; // Utility method to construct the dp arrayfunction constructDP($dp, $str){ $l = strlen($str); // declare 2D array isPalin, isPalin[i][j] // will be 1 if str(i..j) is palindrome $isPalin = array(array()); // initialize dp and isPalin array by zeros for ($i = 0; $i <= $l; $i++) { for ($j = 0; $j <= $l; $j++) { $isPalin[$i][$j] = $dp[$i][$j] = 0; } } // loop for starting index of range for ($i = $l - 1; $i >= 0; $i--) { // initialize value for one character // strings as 1 $isPalin[$i][$i] = 1; $dp[$i][$i] = 1; // loop for ending index of range for ($j = $i + 1; $j < $l; $j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ $isPalin[$i][$j] = ($str[$i] == $str[$j] && ($i + 1 > $j - 1 || $isPalin[$i + 1][$j - 1])); /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ $dp[$i][$j] = $dp[$i][$j - 1] + $dp[$i + 1][$j] - $dp[$i + 1][$j - 1] + $isPalin[$i][$j]; } } return $dp ;} // method returns count of palindromic// substring in range (l, r)function countOfPalindromeInRange($dp, $l, $r){ return $dp[$l][$r];} // Driver code$str = \"xyaabax\"; $dp = array(array()); for($i = 0; $i < $GLOBALS['M']; $i++ ) for($j = 0; $j < $GLOBALS['M']; $j++) $dp[$i][$j] = 0; $dp = constructDP($dp, $str); $l = 3;$r = 5; echo countOfPalindromeInRange($dp, $l, $r); // This code is contributed by Ryuga?>", "e": 36291, "s": 34316, "text": null }, { "code": "<script> // Javascript program to query number of palindromic // substrings of a string in a range // Function to construct the dp array function constructDp(dp, str) { let l = str.length; // declare 2D array isPalin, isPalin[i][j] will // be 1 if str(i..j) is palindrome let isPalin = new Array(l + 1); // initialize dp and isPalin array by zeros for (let i = 0; i <= l; i++) { isPalin[i] = new Array(l + 1); for (let j = 0; j <= l; j++) { isPalin[i][j] = dp[i][j] = 0; } } // loop for starting index of range for (let i = l - 1; i >= 0; i--) { // initialize value for one character strings as 1 isPalin[i][i] = 1; dp[i][i] = 1; // loop for ending index of range for (let j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ isPalin[i][j] = (str[i] == str[j] && (i + 1 > j - 1 || (isPalin[i + 1][j - 1]) != 0)) ? 1 : 0; /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]; } } } // method returns count of palindromic substring in range (l, r) function countOfPalindromeInRange(dp, l, r) { return dp[l][r]; } let MAX = 50; let str = \"xyaabax\"; let dp = new Array(MAX); for (let i = 0; i < MAX; i++) { dp[i] = new Array(MAX); for (let j = 0; j < MAX; j++) { dp[i][j] = 0; } } constructDp(dp, str); let l = 3; let r = 5; document.write(countOfPalindromeInRange(dp, l, r)); </script>", "e": 38352, "s": 36291, "text": null }, { "code": null, "e": 38362, "s": 38352, "text": "Output: " }, { "code": null, "e": 38364, "s": 38362, "text": "4" }, { "code": null, "e": 38788, "s": 38364, "text": "This article is contributed by Utkarsh Trivedi. 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": 38793, "s": 38788, "text": "vt_m" }, { "code": null, "e": 38801, "s": 38793, "text": "ankthon" }, { "code": null, "e": 38814, "s": 38801, "text": "rituraj_jain" }, { "code": null, "e": 38828, "s": 38814, "text": "divyesh072019" }, { "code": null, "e": 38839, "s": 38828, "text": "palindrome" }, { "code": null, "e": 38859, "s": 38839, "text": "Dynamic Programming" }, { "code": null, "e": 38867, "s": 38859, "text": "Strings" }, { "code": null, "e": 38875, "s": 38867, "text": "Strings" }, { "code": null, "e": 38895, "s": 38875, "text": "Dynamic Programming" }, { "code": null, "e": 38906, "s": 38895, "text": "palindrome" }, { "code": null, "e": 39004, "s": 38906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39035, "s": 39004, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 39068, "s": 39035, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 39103, "s": 39068, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 39171, "s": 39103, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 39198, "s": 39171, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 39244, "s": 39198, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 39269, "s": 39244, "text": "Reverse a string in Java" }, { "code": null, "e": 39329, "s": 39269, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39344, "s": 39329, "text": "C++ Data Types" } ]
Final local variables in Java - GeeksforGeeks
25 Sep, 2017 Prerequisite : final keyword, Variables, Scope of Variables A local variable in Java is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists. If we are declaring a local variable then we should initialize it within the block before using it. In case of local variable, JVM won’t provide any default values. A final local variable serves as a warning when you “accidentally” try to modify a value and also provides information to the compiler that can lead to better optimization of the class file. Usability of using final local variables: Most importantly, We can use local variable as final in an anonymous inner class, we have to declare the local variable of anonymous inner class as final. This is to do with the individual accessor methods that get generated to implement the anonymous inner class. Non-final local variables can’t be used for inner classes It may allow Java compiler or Just In Time compiler to optimize code, knowing that the variable value will not change. This can improve the processing time of the program. Important points about local final variable : Initialization of the variable is not Mandatory: Even though local variable is final we have to perform initialization only if you want to use it i.e. if we are not using then it is not required to perform initialization even though it is final.// Java program to illustrate the behavior of// final local variableclass Test { public static void main(String[] args) { final int x; System.out.println("GEEKS"); }}Output:GEEKS Final is the only applicable modifier for local variables : The only applicable modifier for local variable is final. By mistake if we trying to apply any other modifier then we will get compile time error.// Java program to illustrate that final is// the only applicable modifier for local variableclass Test { public static void main(String[] args) { public int x; // static int x will also not work. System.out.println("GEEKS"); }}Output:error: illegal start of expression Initialization of the variable is not Mandatory: Even though local variable is final we have to perform initialization only if you want to use it i.e. if we are not using then it is not required to perform initialization even though it is final.// Java program to illustrate the behavior of// final local variableclass Test { public static void main(String[] args) { final int x; System.out.println("GEEKS"); }}Output:GEEKS // Java program to illustrate the behavior of// final local variableclass Test { public static void main(String[] args) { final int x; System.out.println("GEEKS"); }} Output: GEEKS Final is the only applicable modifier for local variables : The only applicable modifier for local variable is final. By mistake if we trying to apply any other modifier then we will get compile time error.// Java program to illustrate that final is// the only applicable modifier for local variableclass Test { public static void main(String[] args) { public int x; // static int x will also not work. System.out.println("GEEKS"); }}Output:error: illegal start of expression // Java program to illustrate that final is// the only applicable modifier for local variableclass Test { public static void main(String[] args) { public int x; // static int x will also not work. System.out.println("GEEKS"); }} Output: error: illegal start of expression This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-final keyword Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23582, "s": 23554, "text": "\n25 Sep, 2017" }, { "code": null, "e": 23642, "s": 23582, "text": "Prerequisite : final keyword, Variables, Scope of Variables" }, { "code": null, "e": 24017, "s": 23642, "text": "A local variable in Java is a variable that’s declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren’t even aware that the variable exists. If we are declaring a local variable then we should initialize it within the block before using it. In case of local variable, JVM won’t provide any default values." }, { "code": null, "e": 24208, "s": 24017, "text": "A final local variable serves as a warning when you “accidentally” try to modify a value and also provides information to the compiler that can lead to better optimization of the class file." }, { "code": null, "e": 24250, "s": 24208, "text": "Usability of using final local variables:" }, { "code": null, "e": 24573, "s": 24250, "text": "Most importantly, We can use local variable as final in an anonymous inner class, we have to declare the local variable of anonymous inner class as final. This is to do with the individual accessor methods that get generated to implement the anonymous inner class. Non-final local variables can’t be used for inner classes" }, { "code": null, "e": 24745, "s": 24573, "text": "It may allow Java compiler or Just In Time compiler to optimize code, knowing that the variable value will not change. This can improve the processing time of the program." }, { "code": null, "e": 24791, "s": 24745, "text": "Important points about local final variable :" }, { "code": null, "e": 25738, "s": 24791, "text": "Initialization of the variable is not Mandatory: Even though local variable is final we have to perform initialization only if you want to use it i.e. if we are not using then it is not required to perform initialization even though it is final.// Java program to illustrate the behavior of// final local variableclass Test { public static void main(String[] args) { final int x; System.out.println(\"GEEKS\"); }}Output:GEEKS\nFinal is the only applicable modifier for local variables : The only applicable modifier for local variable is final. By mistake if we trying to apply any other modifier then we will get compile time error.// Java program to illustrate that final is// the only applicable modifier for local variableclass Test { public static void main(String[] args) { public int x; // static int x will also not work. System.out.println(\"GEEKS\"); }}Output:error: illegal start of expression\n" }, { "code": null, "e": 26186, "s": 25738, "text": "Initialization of the variable is not Mandatory: Even though local variable is final we have to perform initialization only if you want to use it i.e. if we are not using then it is not required to perform initialization even though it is final.// Java program to illustrate the behavior of// final local variableclass Test { public static void main(String[] args) { final int x; System.out.println(\"GEEKS\"); }}Output:GEEKS\n" }, { "code": "// Java program to illustrate the behavior of// final local variableclass Test { public static void main(String[] args) { final int x; System.out.println(\"GEEKS\"); }}", "e": 26376, "s": 26186, "text": null }, { "code": null, "e": 26384, "s": 26376, "text": "Output:" }, { "code": null, "e": 26391, "s": 26384, "text": "GEEKS\n" }, { "code": null, "e": 26891, "s": 26391, "text": "Final is the only applicable modifier for local variables : The only applicable modifier for local variable is final. By mistake if we trying to apply any other modifier then we will get compile time error.// Java program to illustrate that final is// the only applicable modifier for local variableclass Test { public static void main(String[] args) { public int x; // static int x will also not work. System.out.println(\"GEEKS\"); }}Output:error: illegal start of expression\n" }, { "code": "// Java program to illustrate that final is// the only applicable modifier for local variableclass Test { public static void main(String[] args) { public int x; // static int x will also not work. System.out.println(\"GEEKS\"); }}", "e": 27143, "s": 26891, "text": null }, { "code": null, "e": 27151, "s": 27143, "text": "Output:" }, { "code": null, "e": 27187, "s": 27151, "text": "error: illegal start of expression\n" }, { "code": null, "e": 27493, "s": 27187, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27618, "s": 27493, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27637, "s": 27618, "text": "Java-final keyword" }, { "code": null, "e": 27642, "s": 27637, "text": "Java" }, { "code": null, "e": 27647, "s": 27642, "text": "Java" }, { "code": null, "e": 27745, "s": 27647, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27754, "s": 27745, "text": "Comments" }, { "code": null, "e": 27767, "s": 27754, "text": "Old Comments" }, { "code": null, "e": 27797, "s": 27767, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27812, "s": 27797, "text": "Stream In Java" }, { "code": null, "e": 27833, "s": 27812, "text": "Constructors in Java" }, { "code": null, "e": 27879, "s": 27833, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27898, "s": 27879, "text": "Exceptions in Java" }, { "code": null, "e": 27915, "s": 27898, "text": "Generics in Java" }, { "code": null, "e": 27958, "s": 27915, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27974, "s": 27958, "text": "Strings in Java" }, { "code": null, "e": 28023, "s": 27974, "text": "How to remove an element from ArrayList in Java?" } ]
bar3d() function in C graphics - GeeksforGeeks
30 Jan, 2018 The header file graphics.h contains bar3d() function which is used to draw a 2-dimensional, rectangular filled in bar . Coordinates of left top and right bottom corner of bar are required to draw the bar.Syntax : void bar3d(int left, int top, int right, int bottom, int depth, int topflag); where, left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifies the Y-coordinate of right bottom corner, depth specifies the depth of bar in pixels, topflag determines whether a 3 dimensional top is put on the bar or not ( if it is non-zero then it is put otherwise not ). Example : Input : left = 150, top = 250, right = 190, bottom = 350, depth = 20, topflag = 1 left = 220, top = 150, right = 260, bottom = 350, depth = 20, topflag = 0 left = 290, top = 200, right = 330, bottom = 350, depth = 20, topflag = 1 Output : Below is the implementation of bar3d() function : // C Implementation for bar3d() function#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // location of sides int left, top, right, bottom; // depth of the bar int depth; // top flag denotes top line. int topflag; // left, top, right, bottom, // depth, topflag location's bar3d(left = 150, top = 250, right = 190, bottom = 350, depth = 20, topflag = 1); bar3d(left = 220, top = 150, right = 260, bottom = 350, depth = 20, topflag = 0); bar3d(left = 290, top = 200, right = 330, bottom = 350, depth = 20, topflag = 1); // y axis line line(100, 50, 100, 350); // x axis line line(100, 350, 400, 350); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;} Output: c-graphics computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ 'this' pointer in C++ Arrow operator -> in C/C++ with Examples UDP Server-Client implementation in C Understanding "extern" keyword in C Smart Pointers in C++ and How to Use Them Multiple Inheritance in C++ Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
[ { "code": null, "e": 24208, "s": 24180, "text": "\n30 Jan, 2018" }, { "code": null, "e": 24421, "s": 24208, "text": "The header file graphics.h contains bar3d() function which is used to draw a 2-dimensional, rectangular filled in bar . Coordinates of left top and right bottom corner of bar are required to draw the bar.Syntax :" }, { "code": null, "e": 24904, "s": 24421, "text": "void bar3d(int left, int top, int right, \n int bottom, int depth, int topflag);\n\nwhere,\nleft specifies the X-coordinate of top left corner,\ntop specifies the Y-coordinate of top left corner, \nright specifies the X-coordinate of right bottom corner, \nbottom specifies the Y-coordinate of right bottom corner, \ndepth specifies the depth of bar in pixels, \ntopflag determines whether a 3 dimensional top is put on \nthe bar or not ( if it is non-zero then it is put otherwise not ).\n" }, { "code": null, "e": 24914, "s": 24904, "text": "Example :" }, { "code": null, "e": 25251, "s": 24914, "text": "Input : left = 150, top = 250,\n right = 190, bottom = 350,\n depth = 20, topflag = 1\n \n left = 220, top = 150,\n right = 260, bottom = 350, \n depth = 20, topflag = 0\n \n left = 290, top = 200, \n right = 330, bottom = 350, \n depth = 20, topflag = 1\nOutput : \n\n" }, { "code": null, "e": 25301, "s": 25251, "text": "Below is the implementation of bar3d() function :" }, { "code": "// C Implementation for bar3d() function#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // location of sides int left, top, right, bottom; // depth of the bar int depth; // top flag denotes top line. int topflag; // left, top, right, bottom, // depth, topflag location's bar3d(left = 150, top = 250, right = 190, bottom = 350, depth = 20, topflag = 1); bar3d(left = 220, top = 150, right = 260, bottom = 350, depth = 20, topflag = 0); bar3d(left = 290, top = 200, right = 330, bottom = 350, depth = 20, topflag = 1); // y axis line line(100, 50, 100, 350); // x axis line line(100, 350, 400, 350); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}", "e": 26480, "s": 25301, "text": null }, { "code": null, "e": 26488, "s": 26480, "text": "Output:" }, { "code": null, "e": 26501, "s": 26490, "text": "c-graphics" }, { "code": null, "e": 26519, "s": 26501, "text": "computer-graphics" }, { "code": null, "e": 26530, "s": 26519, "text": "C Language" }, { "code": null, "e": 26628, "s": 26530, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26666, "s": 26628, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26686, "s": 26666, "text": "Multithreading in C" }, { "code": null, "e": 26712, "s": 26686, "text": "Exception Handling in C++" }, { "code": null, "e": 26734, "s": 26712, "text": "'this' pointer in C++" }, { "code": null, "e": 26775, "s": 26734, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26813, "s": 26775, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 26849, "s": 26813, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 26891, "s": 26849, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26919, "s": 26891, "text": "Multiple Inheritance in C++" } ]
How to Create and Customize Venn Diagrams in Python? - GeeksforGeeks
15 Mar, 2021 Venn Diagrams are useful for illustrating relations between two or more groups. We can easily see commonalities and differences between different groups. In this article, we are going to discuss how to create and customize Venn diagrams in Python: Simple Venn Diagram: Installation: Install matplotlib-venn Library in your computer (Here we used the tool Pycharm) go to the terminal and use the following command. pip install matplotlib-venn After installing the library create a new python file and import the libraries as explained in the below program: Python3 # import modulesfrom matplotlib_venn import venn2 from matplotlib import pyplot as plt # depict venn diagramvenn2(subsets = (50, 10, 7), set_labels = ('Group A', 'Group B'))plt.show() Output: The statement venn2(subsets = (30, 10, 5), set_labels = (‘Group A’, ‘Group B’)) refers to the subset’s parameter is a 3 element list where the numbers 50, 10, 7 correspond to Ab, aB, AB. Ab = Contained in group A, but not B aB = Contained in group B, but not A AB = Contained in both group A and B The set_labels parameter allows you to label your two groups in the Venn diagram. The show() function in pyplot module of matplotlib library is used to display all figures. Below are various examples that depict how to create and customize Venn diagrams: Example 1: Venn Diagrams automatically size the circle depending upon the magnitude of items allotted. However, we can disable this by using an unweighted Venn Diagram, so the circles appear in the same size irrespective of the items allotted. The default colors of Venn Diagrams are red and green now we will customize the colors orange and blue using set_colors parameter. The alpha parameter is used to control the transparency. Python3 # import modulesfrom matplotlib_venn import venn2_unweighted from matplotlib import pyplot as plt # depict venn diagramvenn2_unweighted(subsets = (50, 10, 7), set_labels = ('Group A', 'Group B'), set_colors=("orange", "blue"),alpha=0.7)plt.show() Output: Example 2: We can customize the outline of the circle note it works on weighted Venn Diagrams which are shown in the below program. Python3 # import modulesfrom matplotlib_venn import venn2,venn2_circlesfrom matplotlib import pyplot as plt # depict venn diagramvenn2(subsets = (50, 10, 7), set_labels = ('Group A', 'Group B'), set_colors=("orange", "blue"),alpha=0.7) # add outlinevenn2_circles(subsets=(50,10,7)) plt.show() Output: Example 3: We can also customize the outline of the circle with dashed line style and line width: Python3 # import modulesfrom matplotlib_venn import venn2, venn2_circlesfrom matplotlib import pyplot as plt # depict venn diagramvenn2(subsets=(50, 10, 7), set_labels=('Group A', 'Group B'), set_colors=("orange", "blue"), alpha=0.7) # outline of the circle with defined # line style and line widthvenn2_circles(subsets=(50, 10, 7), linestyle="dashed", linewidth=2)plt.show() Output: Example 4: A title can be assigned to Venn diagrams using the title() method. Python3 # import modulesfrom matplotlib_venn import venn2, venn2_circlesfrom matplotlib import pyplot as plt # depict venn diagramvenn2(subsets=(50, 10, 7), set_labels=('Group A', 'Group B'), set_colors=("orange", "blue"), alpha=0.7) # add outlinevenn2_circles(subsets=(50, 10, 7), linestyle="dashed", linewidth=2) # assign title of the venn diagramplt.title("Venn Diagram in geeks for geeks") plt.show() Output: Example 6: Let us draw three Venn Diagrams use venn3, venn3_circles modules. Python3 # import modulefrom matplotlib_venn import venn3, venn3_circlesfrom matplotlib import pyplot as plt # depict venn diagramvenn3(subsets=(20, 10, 12, 10, 9, 4, 3), set_labels=('Group A', 'Group B', 'Group C'), set_colors=("orange", "blue", "red"), alpha=0.7) # outline of circle line style and widthvenn3_circles(subsets=(20, 10, 12, 10, 9, 4, 3), linestyle="dashed", linewidth=2) # title of the venn diagramplt.title("Venn Diagram in geeks for geeks")plt.show() Output: Example 7: Let us customize the colors of each area of the diagram with the get_patch_by_id() method. Python3 #import modulefrom matplotlib_venn import venn3, venn3_circlesfrom matplotlib import pyplot as plt # depict venn diagramv = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels=('A', 'B', 'C')) # set color to defined path idv.get_patch_by_id("100").set_color("white")# set text to defined label idv.get_label_by_id("100").set_text("unknown")# set text to defined label id "A"v.get_label_by_id('A').set_text('A new') # add outlinevenn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle="dashed", linewidth=2) # assign titleplt.title("Venn Diagram in geeks for geeks")plt.show() Output: Data Visualization Picked Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n15 Mar, 2021" }, { "code": null, "e": 24149, "s": 23901, "text": "Venn Diagrams are useful for illustrating relations between two or more groups. We can easily see commonalities and differences between different groups. In this article, we are going to discuss how to create and customize Venn diagrams in Python:" }, { "code": null, "e": 24170, "s": 24149, "text": "Simple Venn Diagram:" }, { "code": null, "e": 24184, "s": 24170, "text": "Installation:" }, { "code": null, "e": 24315, "s": 24184, "text": "Install matplotlib-venn Library in your computer (Here we used the tool Pycharm) go to the terminal and use the following command." }, { "code": null, "e": 24343, "s": 24315, "text": "pip install matplotlib-venn" }, { "code": null, "e": 24457, "s": 24343, "text": "After installing the library create a new python file and import the libraries as explained in the below program:" }, { "code": null, "e": 24465, "s": 24457, "text": "Python3" }, { "code": "# import modulesfrom matplotlib_venn import venn2 from matplotlib import pyplot as plt # depict venn diagramvenn2(subsets = (50, 10, 7), set_labels = ('Group A', 'Group B'))plt.show()", "e": 24650, "s": 24465, "text": null }, { "code": null, "e": 24658, "s": 24650, "text": "Output:" }, { "code": null, "e": 24845, "s": 24658, "text": "The statement venn2(subsets = (30, 10, 5), set_labels = (‘Group A’, ‘Group B’)) refers to the subset’s parameter is a 3 element list where the numbers 50, 10, 7 correspond to Ab, aB, AB." }, { "code": null, "e": 24882, "s": 24845, "text": "Ab = Contained in group A, but not B" }, { "code": null, "e": 24919, "s": 24882, "text": "aB = Contained in group B, but not A" }, { "code": null, "e": 24956, "s": 24919, "text": "AB = Contained in both group A and B" }, { "code": null, "e": 25129, "s": 24956, "text": "The set_labels parameter allows you to label your two groups in the Venn diagram. The show() function in pyplot module of matplotlib library is used to display all figures." }, { "code": null, "e": 25211, "s": 25129, "text": "Below are various examples that depict how to create and customize Venn diagrams:" }, { "code": null, "e": 25223, "s": 25211, "text": "Example 1: " }, { "code": null, "e": 25456, "s": 25223, "text": "Venn Diagrams automatically size the circle depending upon the magnitude of items allotted. However, we can disable this by using an unweighted Venn Diagram, so the circles appear in the same size irrespective of the items allotted." }, { "code": null, "e": 25644, "s": 25456, "text": "The default colors of Venn Diagrams are red and green now we will customize the colors orange and blue using set_colors parameter. The alpha parameter is used to control the transparency." }, { "code": null, "e": 25652, "s": 25644, "text": "Python3" }, { "code": "# import modulesfrom matplotlib_venn import venn2_unweighted from matplotlib import pyplot as plt # depict venn diagramvenn2_unweighted(subsets = (50, 10, 7), set_labels = ('Group A', 'Group B'), set_colors=(\"orange\", \"blue\"),alpha=0.7)plt.show()", "e": 25991, "s": 25652, "text": null }, { "code": null, "e": 25999, "s": 25991, "text": "Output:" }, { "code": null, "e": 26010, "s": 25999, "text": "Example 2:" }, { "code": null, "e": 26131, "s": 26010, "text": "We can customize the outline of the circle note it works on weighted Venn Diagrams which are shown in the below program." }, { "code": null, "e": 26139, "s": 26131, "text": "Python3" }, { "code": "# import modulesfrom matplotlib_venn import venn2,venn2_circlesfrom matplotlib import pyplot as plt # depict venn diagramvenn2(subsets = (50, 10, 7), set_labels = ('Group A', 'Group B'), set_colors=(\"orange\", \"blue\"),alpha=0.7) # add outlinevenn2_circles(subsets=(50,10,7)) plt.show()", "e": 26473, "s": 26139, "text": null }, { "code": null, "e": 26481, "s": 26473, "text": "Output:" }, { "code": null, "e": 26492, "s": 26481, "text": "Example 3:" }, { "code": null, "e": 26579, "s": 26492, "text": "We can also customize the outline of the circle with dashed line style and line width:" }, { "code": null, "e": 26587, "s": 26579, "text": "Python3" }, { "code": "# import modulesfrom matplotlib_venn import venn2, venn2_circlesfrom matplotlib import pyplot as plt # depict venn diagramvenn2(subsets=(50, 10, 7), set_labels=('Group A', 'Group B'), set_colors=(\"orange\", \"blue\"), alpha=0.7) # outline of the circle with defined # line style and line widthvenn2_circles(subsets=(50, 10, 7), linestyle=\"dashed\", linewidth=2)plt.show()", "e": 26982, "s": 26587, "text": null }, { "code": null, "e": 26990, "s": 26982, "text": "Output:" }, { "code": null, "e": 27001, "s": 26990, "text": "Example 4:" }, { "code": null, "e": 27068, "s": 27001, "text": "A title can be assigned to Venn diagrams using the title() method." }, { "code": null, "e": 27076, "s": 27068, "text": "Python3" }, { "code": "# import modulesfrom matplotlib_venn import venn2, venn2_circlesfrom matplotlib import pyplot as plt # depict venn diagramvenn2(subsets=(50, 10, 7), set_labels=('Group A', 'Group B'), set_colors=(\"orange\", \"blue\"), alpha=0.7) # add outlinevenn2_circles(subsets=(50, 10, 7), linestyle=\"dashed\", linewidth=2) # assign title of the venn diagramplt.title(\"Venn Diagram in geeks for geeks\") plt.show()", "e": 27516, "s": 27076, "text": null }, { "code": null, "e": 27524, "s": 27516, "text": "Output:" }, { "code": null, "e": 27535, "s": 27524, "text": "Example 6:" }, { "code": null, "e": 27601, "s": 27535, "text": "Let us draw three Venn Diagrams use venn3, venn3_circles modules." }, { "code": null, "e": 27609, "s": 27601, "text": "Python3" }, { "code": "# import modulefrom matplotlib_venn import venn3, venn3_circlesfrom matplotlib import pyplot as plt # depict venn diagramvenn3(subsets=(20, 10, 12, 10, 9, 4, 3), set_labels=('Group A', 'Group B', 'Group C'), set_colors=(\"orange\", \"blue\", \"red\"), alpha=0.7) # outline of circle line style and widthvenn3_circles(subsets=(20, 10, 12, 10, 9, 4, 3), linestyle=\"dashed\", linewidth=2) # title of the venn diagramplt.title(\"Venn Diagram in geeks for geeks\")plt.show()", "e": 28098, "s": 27609, "text": null }, { "code": null, "e": 28106, "s": 28098, "text": "Output:" }, { "code": null, "e": 28117, "s": 28106, "text": "Example 7:" }, { "code": null, "e": 28208, "s": 28117, "text": "Let us customize the colors of each area of the diagram with the get_patch_by_id() method." }, { "code": null, "e": 28216, "s": 28208, "text": "Python3" }, { "code": "#import modulefrom matplotlib_venn import venn3, venn3_circlesfrom matplotlib import pyplot as plt # depict venn diagramv = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels=('A', 'B', 'C')) # set color to defined path idv.get_patch_by_id(\"100\").set_color(\"white\")# set text to defined label idv.get_label_by_id(\"100\").set_text(\"unknown\")# set text to defined label id \"A\"v.get_label_by_id('A').set_text('A new') # add outlinevenn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle=\"dashed\", linewidth=2) # assign titleplt.title(\"Venn Diagram in geeks for geeks\")plt.show()", "e": 28815, "s": 28216, "text": null }, { "code": null, "e": 28823, "s": 28815, "text": "Output:" }, { "code": null, "e": 28842, "s": 28823, "text": "Data Visualization" }, { "code": null, "e": 28849, "s": 28842, "text": "Picked" }, { "code": null, "e": 28856, "s": 28849, "text": "Python" }, { "code": null, "e": 28954, "s": 28856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28963, "s": 28954, "text": "Comments" }, { "code": null, "e": 28976, "s": 28963, "text": "Old Comments" }, { "code": null, "e": 29008, "s": 28976, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29064, "s": 29008, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29106, "s": 29064, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29148, "s": 29106, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29184, "s": 29148, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 29206, "s": 29184, "text": "Defaultdict in Python" }, { "code": null, "e": 29245, "s": 29206, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29272, "s": 29245, "text": "Python Classes and Objects" }, { "code": null, "e": 29303, "s": 29272, "text": "Python | os.path.join() method" } ]
Groovy - random()
The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic. static double random() This is a default method and accepts no parameter. This method returns a double. Following is an example of the usage of this method − class Example { static void main(String[] args) { System.out.println( Math.random() ); System.out.println( Math.random() ); } } When we run the above program, we will get the following result − 0.0543333676591804 0.3223824169137166 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2400, "s": 2238, "text": "The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic." }, { "code": null, "e": 2425, "s": 2400, "text": "static double random() \n" }, { "code": null, "e": 2476, "s": 2425, "text": "This is a default method and accepts no parameter." }, { "code": null, "e": 2506, "s": 2476, "text": "This method returns a double." }, { "code": null, "e": 2560, "s": 2506, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2711, "s": 2560, "text": "class Example { \n static void main(String[] args) { \n System.out.println( Math.random() ); \n System.out.println( Math.random() ); \n } \n}" }, { "code": null, "e": 2777, "s": 2711, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 2817, "s": 2777, "text": "0.0543333676591804 \n0.3223824169137166\n" }, { "code": null, "e": 2850, "s": 2817, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 2868, "s": 2850, "text": " Krishna Sakinala" }, { "code": null, "e": 2903, "s": 2868, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2921, "s": 2903, "text": " Packt Publishing" }, { "code": null, "e": 2928, "s": 2921, "text": " Print" }, { "code": null, "e": 2939, "s": 2928, "text": " Add Notes" } ]
Demand forecast with different data science approaches | by Andrii Shchur | Towards Data Science
In this story, I would like to make an overview of common data science techniques and frameworks to create a demand forecast model. First of all, let's define what is demand forecasting and what impact it has got on business. Wiki said — “Demand forecasting is a field of predictive analytics which tries to understand and predict customer demand to optimize supply decisions by corporate supply chain and business management.” There are several types of demand forecast: Short-term (It is is carried out for a shorter-term period of 3 months to 12 months. In the short term, the seasonal pattern of demand and the effect of tactical decisions on customer demand are taken into consideration.) Medium to long-term (It is typically carried out for more than 12 months to 24 months in advance (36–48 months in certain businesses). Long-term Forecasting drives business strategy planning, sales and marketing planning, financial planning, capacity planning, capital expenditure, etc.) External macro-level (This type of Forecasting deals with the broader market movements which depend on the macroeconomic environment. External Forecasting is carried out for evaluating the strategic objectives of a business like product portfolio expansion, entering new customer segments, technological disruptions, a paradigm shift in consumer behavior, and risk mitigation strategies.) Internal business level (This type of Forecasting deals with internal operations of the business such as product category, sales division, financial division, and manufacturing group. This includes annual sales forecast, estimation of COGS, net profit margin, cash flow, etc.) Passive (It is carried out for stable businesses with very conservative growth plans. Simple extrapolations of historical data are carried out with minimal assumptions.) Active (It is carried out for scaling and diversifying businesses with aggressive growth plans in terms of marketing activities, product portfolio expansion, and consideration of competitor activities and external economic environment.) Why demand forecast is so important and what process it improve? Demand Forecasting is the pivotal business process around which strategic and operational plans of a company are devised. Based on the Demand Forecast, strategic and long-range plans of a business like budgeting, financial planning, sales and marketing plans, capacity planning, risk assessment, and mitigation plans are formulated. It also affects the following processes: Supplier relationship management. Customer relationship management. Order fulfillment and logistics. Marketing campaigns. Manufacturing flow management. Ok, let's solve this problem and try to use different data science techniques and frameworks to make an accurate demand forecast. For my experiment, I would like to use a dataset from Kaggle's competition. In every data science task, I use CRISP-DM to follow all the necessary processes during the work on the project. The first phase of CRISP-DM is — Business Understanding. The task is to forecast the total amount of products sold in every shop for the test set. What about the metrics or success criteria? The forecast is evaluated by the root mean squared error (RMSE). The second and the third phases, as for me, are one of the most important — Data understanding and preparation. The first task when initiating the demand forecasting project is to provide the client with meaningful insights. The process includes the following steps: Gather available data Gather available data In our case we have got the next datasets: sales_train.csv — the training set. Daily historical data from January 2013 to October 2015. test.csv — the test set. You need to forecast the sales for these shops and products for November 2015. sample_submission.csv — a sample submission file in the correct format. items.csv — supplemental information about the items/products. item_categories.csv — supplemental information about the items categories. shops.csv- supplemental information about the shops. Briefly review the data structure, accuracy, and consistency. Let’s make several tables and plots to analyze our dataset. This base analytics could help us to understand, the main input parameters of the dataset. For example, we could see, that in our dataset we have got a negative value for Price, which could be a mistake, and a negative value for Sales, which could be зurchase returns. The next table explains for us the distribution for numeric columns: Here we can see, that half of our sales have a value equal to 1. Let’s make a scatter plot to analyze the relationship between sales volume and price. This type of plot usually can show us, that we have got units with little price and big volume of sales and inits with an abnormally high price and very low volume of sales. Let’s analyze our data in dynamic — The first plot show for us decrease trend of unique items in the assortment: The second plot show for us decreases trend of quantity sales and two picks, which could be a seasonal or some promo. This is what we need to learn from business and through quantitative analysis. The next step is analytics of our category which we will use to aggregate our dataset, the first dimension is items/category names and the second is shops id. This analysis shows for us the sales volume distribution in item’s category and shops and would help for us to understand which categories and shops is the most important for us and which ones have got a short history for analytics and forecasting. EDA is an ongoing process that you can continue to do throughout the entire time of working with different experiments. Let’s stop at this point and start creat models. Before we start to create models, we need to split our dataset for training, validation, and testing. Keep in mind, that we need to use the date column to filter our dataset, don’t use random split for time-series. In this part, I would like to explain and create basic approach models. The first one is the Smoothed Moving Average. The smoothed moving average (SMMA) is a demand forecasting model that can be used to gauge trends based on a series of averages from consecutive periods. For example, the smoothed moving average from six months of sales could be calculated by taking the average of sales from January to June, then the average of sales between February to July, then March to August, and so on. This model is called ‘moving’ because averages are continually recalculated as more data becomes available. A moving average of order mm can be written as: where m=2k+1m=2k+1. That is, the estimate of the trend-cycle at time tt is obtained by averaging values of the time series within kk periods of tt. Observations that are nearby in time are also likely to be close in value. Smoothed Moving Average is useful for looking at overall sales trends over time and aiding long-term demand planning. Rapid changes as a result of seasonality or other fluctuations are smoothed out so you can analyze the bigger picture more accurately. The smoothed moving average model typically works well when you have a product that’s growing consistently or declining over time. Also, the important disadvantage of this approach, that we could make Items without history. To make it in Python we can use pandas.DataFrame.shift to create Lag value, full_df['sales_lag_n'] = full_df['sales'].shift(periods=n) then we can use pandas.DataFrame.rolling to create a rolling mean base on created Lag values. full_df['sma'] = full_df['sales_lag_n].rolling(n).mean() The next model is Holt Winter’s Exponential Smoothing. Holt (1957) and Winters (1960) extended Holt’s method to capture seasonality. The Holt-Winters seasonal method comprises the forecast equation and three smoothing equations — one for the level ltlt, one for the trend bt, and one for the seasonal component st, with corresponding smoothing parameters αα, β∗β∗ and γγ. We use mm to denote the frequency of the seasonality, i.e., the number of seasons in a year. For example, for quarterly data m=4m=4, and monthly data m=12m=12. There are two variations to this method that differ like the seasonal component. The additive method is preferred when the seasonal variations are roughly constant through the series, while the multiplicative method is preferred when the seasonal variations are changing proportionally to the level of the series. With the additive method, the seasonal component is expressed in absolute terms in the scale of the observed series, and in the level equation, the series is seasonally adjusted by subtracting the seasonal component. Within each year, the seasonal component will add up to approximately zero. With the multiplicative method, the seasonal component is expressed in relative terms (percentages), and the series is seasonally adjusted by dividing through by the seasonal component. Within each year, the seasonal component will sum up to approximately mm. This method is more efficient than the previous one because it handles the season components, but it has got the same disadvantage it doesn’t handle new items in the assortment. This method has an implementation in Python from statsmodels.tsa.holtwinters import ExponentialSmoothing as HWES This model applies to one pair shop-item, which means that we need to create a new model for every pair. for index, row in tqdm(df_test.iterrows()): tmp = df_train_aggr[(df_train_aggr['shop_id'] == row['shop_id']) & (df_train_aggr['item_id'] == row['item_id'])] model = ExponentialSmoothing(tmp.item_cnt_day) model_fit = model.fit() forecast = model_fit.forecast(steps=n) The last model in my basic approach is ARIMA. ARIMA, short for ‘Auto-Regressive Integrated Moving Average’ is actually a class of models that ‘explains’ a given time series based on its own past values, that is, its own lags and the lagged forecast errors, so that equation can be used to forecast future values. Any ‘non-seasonal time series that exhibits patterns and is not a random white noise can be modeled with ARIMA models. An ARIMA model is characterized by 3 terms: p, d, q where, p is the order of the AR term q is the order of the MA term d is the number of differences required to make the time series stationary If a time series, has seasonal patterns, then you need to add seasonal terms and it becomes SARIMA, short for ‘Seasonal ARIMA’. More on that once we finish ARIMA. As a previous model, I will build a separate model for each shop-item pairs. So the main idea is to find the right parameters for our models. I would not write a long description of how to calculate each one, but You can find it here. In my case, I would like to use something like auto.arima. I find an interesting implementation — pmdarima. “pmdarima” brings R’s beloved auto.arima to Python, making an even stronger case for why you don’t need R for data science. pmdarima is 100% Python + Cython and does not leverage any R code, but is implemented in a powerful, yet easy-to-use set of functions & classes that will be familiar to scikit-learn users. The code will be very similar to the previous one: import pmdarima as pmfor index, row in tqdm(df_test.iterrows()): model = pm.auto_arima(tmp.item_cnt_day, start_p=1, start_q=1, max_p=3, max_q=3, m=12,start_P=0, seasonal=False,d=1, D=1, trace=False,error_action='ignore', # don't want to know if an order does not worksuppress_warnings=True, # don't want convergence warningsstepwise=True)forecast = model_fit.predict(n_periods = n, return_conf_int=False) ARIMA is a quite strong model, which could give a good forecast. ARIMA can be limited in forecasting extreme values. While the model is adept at modeling seasonality and trends, outliers are difficult to forecast for ARIMA for the very reason that they lie outside of the general trend as captured by the model. So, classical time series forecasting methods may be focused on linear relationships, nevertheless, they are sophisticated and perform well on a wide range of problems, assuming that your data is suitably prepared and the method is well configured. A most common enterprise application of machine learning teamed with statistical methods is predictive analytics. It allows for not only estimating demand but also for understanding what drives sales and how customers are likely to behave under certain conditions. The main idea in using machine learning models for demand forecast is to generate a lot of useful features. Feature engineering is the use of domain knowledge data and the creation of features that make machine learning models predict more accurately. It enables a deeper understanding of data and more valuable insights. This feature could be: Product/Shop characteristics (information from items dictionaries) Internal information about promo activities and any price changes Different level target encoding of categorical variables Date features In my experiments, I will use the following Python libraries CatBoost, XGBoost, and H2O AML. Let’s start with XGBoost. from xgboost import XGBRegressor XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible, and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost cannot handle categorical features by itself, it only accepts numerical values similar to Random Forest. Therefore one has to perform various encodings like label encoding, mean encoding, or one-hot encoding before supplying categorical data to XGBoost. XGboost splits up to the specified max_depth hyperparameter and then starts pruning the tree backward and removes splits beyond which there is no positive gain. It uses this approach since sometimes a split of no loss reduction may be followed by a split with loss reduction. XGBoost can also perform leaf-wise tree growth. XGBoost missing values will be allocated to the side that reduces the loss in each split. # Trainmodel = XGBRegressor(max_depth=8,n_estimators=1000,min_child_weight=300,colsample_bytree=0.8,subsample=0.8,eta=0.3,seed=42)model.fit(X_train,Y_train,eval_metric="rmse",eval_set=[(X_train, Y_train), (X_valid, Y_valid)],verbose=True,early_stopping_rounds = 10) XGBoost is a good and fast implementation of gradient boosting algorithm for machine learning, but the main disadvantage, as for me, is that couldn't use categorical factors and in the results, a model may lose some information. The next library is CatBoost. from catboost import CatBoostRegressor Catboost grows a balanced tree. In each level of such a tree, the feature-split pair that brings to the lowest loss (according to a penalty function) is selected and is used for all the level’s nodes. It is possible to change its policy using the grow-policy parameter. Catboost has two modes for processing missing values, “Min” and “Max”. In “Min”, missing values are processed as the minimum value for a feature (they are given a value that is less than all existing values). This way, it is guaranteed that a split that separates missing values from all other values is considered when selecting splits. “Max” works the same as “Min”, only with maximum values. Catboost uses a combination of one-hot encoding and an advanced mean encoding. For features with a low number of categories, it uses one-hot encoding. The maximum number of categories for one-hot encoding can be controlled by the one_hot_max_size parameter. For the remaining categorical columns, CatBoost uses an efficient method of encoding, which is similar to mean encoding but with an additional mechanism aimed at reducing overfitting. Using CatBoost’s categorical encoding comes with a downside of a slower model. # Trainmodel=CatBoostRegressor(iterations=100, depth=10, learning_rate=0.03, loss_function='RMSE')model.fit(X_train, Y_train, cat_features = categorical, eval_set=(X_valid, Y_valid)) CatBoost provides useful tools for easy work with highly categorized data. It shows solid results training on unprocessed categorical features. The last one on H2O AML. import h2ofrom h2o.automl import H2OAutoMLh2o.init(nthreads = 7, max_mem_size = '45g') H2O’s AutoML can be used for automating the machine learning workflow, which includes automatic training and tuning of many models within a user-specified time-limit. Stacked Ensembles — one based on all previously trained models, another one on the best model of each family — will be automatically trained on collections of individual models to produce highly predictive ensemble models which, in most cases, will be the top-performing models in the AutoML Leaderboard. AutoML will iterate through different models and parameters trying to find the best. There are several parameters to specify, but in most cases, all you need to do is to set only the maximum runtime in seconds or a maximum number of models. You can think about AutoML as something similar to GridSearch but on the level of models rather than on the level of parameters. # Run AutoMLaml = H2OAutoML(max_models = 5, seed=1)aml.train(y=y, training_frame=x_train_hf,validation_frame = x_valid_hf) AutoML is to automate repetitive tasks like pipeline creation and hyperparameter tuning so that data scientists can spend more of their time on the business problem at hand. AutoML also aims to make the technology available to everybody rather than a select few. AutoML and data scientists can work in conjunction to accelerate the ML process so that the real effectiveness of machine learning can be utilized. In my case, I have the best result among the previous model. Powerful class of machine learning algorithms that use artificial neural networks to understand and leverage patterns in data. Deep learning algorithms use multiple layers to extract higher-level features from raw data progressively: this reduces the amount of feature extraction needed in other machine learning methods. The deep learning algorithm learns on its own by recognizing patterns using many layers of processing. That is why the “deep” in “deep learning” refers to the number of layers through which the data is transformed. Multiple transformations automatically extract important features from raw data. The main challenge in this task is to handle categorical variables. In deep learning, we can use Entity Embeddings. Embeddings are a solution to dealing with categorical variables while avoiding a lot of the pitfalls of one-hot encoding. An embedding is a mapping of a categorical variable into an n-dimensional vector. So, how our neural network’s architecture looks like? The first, Python framework for this task — Keras. The main challenge here is to write a code for embedding every categorical feature. import tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras.layers import Input, Dense, Activation, Reshape, BatchNormalization, Dropout, concatenate, Embeddingfrom tensorflow.keras.models import Modelfrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau Keras's implementation of this approach is rather bulky. model_inputs = []model_embeddings = []for input_dim, output_dim in emb_space: i = Input(shape=(1,)) emb = Embedding(input_dim=input_dim, output_dim=output_dim)(i) model_inputs.append(i) model_embeddings.append(emb)con_outputs = []for con in con_feature: elaps_input = Input(shape=(1,)) elaps_output = Dense(10)(elaps_input) elaps_output = Activation("relu")(elaps_output) elaps_output = Reshape(target_shape=(1,10))(elaps_output) model_inputs.append(elaps_input) con_outputs.append(elaps_output)merge_embeddings = concatenate(model_embeddings, axis=-1)if len(con_outputs) > 1:merge_con_output = concatenate(con_outputs)else:merge_con_output = con_outputs[0]merge_embedding_cont = concatenate([merge_embeddings, merge_con_output])merge_embedding_contoutput_tensor = Dense(1000, name="dense1024")(merge_embedding_cont)output_tensor = BatchNormalization()(output_tensor)output_tensor = Activation('relu')(output_tensor)output_tensor = Dropout(0.3)(output_tensor)output_tensor = Dense(500, name="dense512")(output_tensor)output_tensor = BatchNormalization()(output_tensor)output_tensor = Activation("relu")(output_tensor)output_tensor = Dropout(0.3)(output_tensor)output_tensor = Dense(1, activation='linear', name="output", kernel_constraint = NonNeg())(output_tensor)optimizer = Adam(lr=10e-3)nn_model = Model(inputs=model_inputs, outputs=output_tensor)nn_model.compile(loss='mse', optimizer=optimizer, metrics=['mean_squared_error'])reduceLr=ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=1, verbose=1)checkpoint = ModelCheckpoint("nn_model.hdf5", monitor='val_loss', verbose=1, save_best_only=True, mode='min')#val_mean_absolute_percentage_errorcallbacks_list = [checkpoint, reduceLr]history = nn_model.fit(x=x_fit_train, y=y_train.reshape(-1,1,1),validation_data=(x_fit_val, y_val.reshape(-1,1,1)),batch_size=1024, epochs=10, callbacks=callbacks_list) All machine learning features and entity embeddings approach showed slightly better results than previous models, but more training time was spent. The advantage of using embeddings is that they can be learned, representing each category better than what other models can approximate. So, we see that this approach is good, but the main disadvantage is a lot of code. Fastai is our solution. Fast.ai is popular deep learning that provides high-level components to obtain state-of-the-art results in standard deep learning domains. Fast.ai allows practitioners to experiment, mix and match to discover new approaches. In short, to facilitate hassle-free deep learning solutions. The libraries leverage the dynamism of the underlying Python language and the flexibility of the PyTorch library. from fastai.tabular import * Training a Deep Neural Network (DNN) is a difficult global optimization problem. Learning Rate (LR) is a crucial hyper-parameter to tune when training DNNs. A very small learning rate can lead to very slow training, while a very large learning rate can hinder convergence as the loss function fluctuates around the minimum, or even diverges. Fastai implemented in this framework one cycle policy. Super-convergence uses the CLR method, but with just one cycle — which contains two learning rate steps, one increasing and one decreasing — and a large maximum learning rate bound. The cycle’s size must be smaller than the total number of iterations/epochs. After the cycle is complete, the learning rate should decrease even further for the remaining iterations/epochs, several orders of magnitude less than its initial value. #TabularList for Validationval = (TabularList.from_df(X_train.iloc[start_indx:end_indx].copy(), path=path, cat_names=cat_feature, cont_names=con_feature))test = (TabularList.from_df(X_test, path=path, cat_names=cat_feature, cont_names=con_feature, procs=procs))#TabularList for trainingdata = (TabularList.from_df(X_train, path=path, cat_names=cat_feature, cont_names=con_feature, procs=procs).split_by_idx(list(range(start_indx,end_indx))).label_from_df(cols=dep_var).add_test(test).databunch())#Initializing the networklearn = tabular_learner(data, layers=[1024,512], metrics= [rmse,r2_score])#Exploring the learning rateslearn.lr_find()learn.recorder.plot()# Learn learn.fit_one_cycle(10, 1e-02) As a result, we have got less code and a faster way to find optimal learning rate. The result is very similar to the previous neural network architecture. This architecture works well, but what if we would like to get some information from previous periods of sales without adding Lag features. So we need to add LSTM or RNN layer to our architecture. In Keras, it will make the code even more cumbersome and there is no implementation for Fastai. I found the solution to this problem — PyTorch Forecasting. Pytorch Forecasting aims to ease state-of-the-art time series forecasting with neural networks for both real-world cases and research alike. The goal is to provide a high-level API with maximum flexibility for professionals and reasonable defaults for beginners. Specifically, the package provides A time-series dataset class that abstracts handling variable transformations, missing values, randomized subsampling, multiple history lengths, etc. A base model class which provides basic training of time series models along with logging in tensorboard and generic visualizations such as actual vs predictions and dependency plots Multiple neural network architectures for time series forecasting that have been enhanced for real-world deployment and come with in-built interpretation capabilities Multi-horizon time series metrics Ranger optimizer for faster model training Hyperparameter tuning with optuna The package is built on PyTorch Lightning to allow training on CPUs, single and multiple GPUs out-of-the-box. import torchimport pytorch_lightning as plfrom pytorch_lightning.callbacks import EarlyStopping, LearningRateMonitorfrom pytorch_lightning.loggers import TensorBoardLoggerfrom pytorch_forecasting import Baseline, TemporalFusionTransformer, TimeSeriesDataSetfrom pytorch_forecasting.data import GroupNormalizerfrom pytorch_forecasting.metrics import SMAPE, PoissonLoss, QuantileLoss, RMSEfrom pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparametersfrom pytorch_forecasting.data.encoders import NaNLabelEncoder In my example, I used Temporal Fusion Transformer [2]. This is an architecture developed by Oxford University and Google that has beaten Amazon’s DeepAR by 36–69% in benchmarks. The first step — we need to create a data loader and create a special data object for our model. max_prediction_length = 1max_encoder_length = 6training_cutoff = X_train["time_idx"].max() - max_prediction_lengthtraining = TimeSeriesDataSet(X_train[lambda x: x.time_idx <= training_cutoff],time_idx="time_idx",target="log_sales",group_ids=["shop_id", "item_id"],min_encoder_length=max_encoder_length // 2, # keep encoder length long (as it is in the validation set)max_encoder_length=max_encoder_length,min_prediction_length=1,max_prediction_length=max_prediction_length,static_categoricals=["shop_id", "item_id"],static_reals=['city_coord_1', 'city_coord_2'],time_varying_known_categoricals=["month"],time_varying_known_reals=["time_idx", "delta_price_lag"],time_varying_unknown_categoricals=["shop_category", "city_code", "item_category_id","type_code", "subtype_code", "country_part"],categorical_encoders = {"shop_id": NaNLabelEncoder(add_nan=True),"item_id": NaNLabelEncoder(add_nan=True),"shop_category": NaNLabelEncoder(add_nan=True),"city_code": NaNLabelEncoder(add_nan=True),"item_category_id": NaNLabelEncoder(add_nan=True),"type_code": NaNLabelEncoder(add_nan=True),"subtype_code": NaNLabelEncoder(add_nan=True),"country_part": NaNLabelEncoder(add_nan=True),},time_varying_unknown_reals=['date_cat_avg_item_cnt_lag_1','date_shop_cat_avg_item_cnt_lag_1', 'date_shop_type_avg_item_cnt_lag_1','date_shop_subtype_avg_item_cnt_lag_1','date_city_avg_item_cnt_lag_1','date_item_city_avg_item_cnt_lag_1','date_type_avg_item_cnt_lag_1','date_subtype_avg_item_cnt_lag_1', 'item_shop_last_sale', 'item_last_sale','item_shop_first_sale', 'item_first_sale'],add_relative_time_idx=True,add_encoder_length=True,allow_missings=True)validation = TimeSeriesDataSet.from_dataset(training,X_train, min_prediction_idx=training.index.time.max() + 1, stop_randomization=True)batch_size = 128train_dataloader = training.to_dataloader(train=True, batch_size=batch_size, num_workers=2)val_dataloader = validation.to_dataloader(train=False, batch_size=batch_size, num_workers=2) The next step is to find an optimal learning rate. pl.seed_everything(42)trainer = pl.Trainer(gpus=1,# clipping gradients is a hyperparameter and important to prevent divergance# of the gradient for recurrent neural networksgradient_clip_val=0.1,)tft = TemporalFusionTransformer.from_dataset(training,# not meaningful for finding the learning rate but otherwise very importantlearning_rate=0.03,hidden_size=16, # most important hyperparameter apart from learning rate# number of attention heads. Set to up to 4 for large datasetsattention_head_size=1,dropout=0.1, # between 0.1 and 0.3 are good valueshidden_continuous_size=8, # set to <= hidden_sizeoutput_size=1, # 7 quantiles by defaultloss=RMSE(),# reduce learning rate if no improvement in validation loss after x epochsreduce_on_plateau_patience=4,)print(f"Number of parameters in network: {tft.size()/1e3:.1f}k")# find optimal learning ratetorch.set_grad_enabled(False)res = trainer.tuner.lr_find(tft,train_dataloader=train_dataloader,val_dataloaders=val_dataloader,max_lr=10.0,min_lr=1e-6)print(f"suggested learning rate: {res.suggestion()}")fig = res.plot(show=True, suggest=True)fig.show() Now we can configure our neural network and train it. early_stop_callback = EarlyStopping(monitor="val_loss", min_delta=1e-4, patience=10, verbose=False, mode="min")lr_logger = LearningRateMonitor() # log the learning ratelogger = TensorBoardLogger("lightning_logs") # logging results to a tensorboardtrainer = pl.Trainer(max_epochs=30,gpus=1,weights_summary="top",gradient_clip_val=0.1,limit_train_batches=30, # coment in for training, running valiation every 30 batches# fast_dev_run=True, # comment in to check that networkor dataset has no serious bugscallbacks=[lr_logger, early_stop_callback],logger=logger,)tft = TemporalFusionTransformer.from_dataset(training,learning_rate=0.03,hidden_size=16,attention_head_size=4,dropout=0.1,hidden_continuous_size=8,output_size=1, # 7 quantiles by defaultloss=RMSE(),log_interval=10, # uncomment for learning rate finder and otherwise, e.g. to 10 for logging every 10 batchesreduce_on_plateau_patience=4)print(f"Number of parameters in network: {tft.size()/1e3:.1f}k")# fit networktrainer.fit(tft,train_dataloader=train_dataloader,val_dataloaders=val_dataloader) Also, we could tune our model and find optimal hyperparameters. from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters# create studystudy = optimize_hyperparameters(train_dataloader,val_dataloader,model_path="optuna_test",n_trials=200,max_epochs=50,gradient_clip_val_range=(0.01, 1.0),hidden_size_range=(8, 128),hidden_continuous_size_range=(8, 128),attention_head_size_range=(1, 4),learning_rate_range=(0.001, 0.1),dropout_range=(0.1, 0.3),trainer_kwargs=dict(limit_train_batches=30),reduce_on_plateau_patience=4,use_learning_rate_finder=False, # use Optuna to find ideal learning rate or use in-built learning rate finder)# save study results - also we can resume tuning at a later point in timewith open("test_study.pkl", "wb") as fout: pickle.dump(study, fout)# show best hyperparametersprint(study.best_trial.params) As a result, I have got a good performance model with all features and approaches, that could be used for time series forecasting. Stacking or Stacked Generalization is an ensemble machine learning algorithm. It uses a meta-learning algorithm to learn how to best combine the predictions from two or more base machine learning algorithms. We could use Stacking to combine the severals model and make new predictions. The architecture of a stacking model involves two or more base models, often referred to as level-0 models and a meta-model that combines the predictions of the base models referred to as a level-1 model. Level-0 Models (Base-Models): Models fit on the training data and whose predictions are compiled. Level-1 Model (Meta-Model): Model that learns how to best combine the predictions of the base models. The meta-model is trained on the predictions made by base models on out-of-sample data. That is, data not used to train the base models is fed to the base models, predictions are made, and these predictions, along with the expected outputs, provide the input and output pairs of the training dataset used to fit the meta-model. The outputs from the base models used as input to the meta-model may be real value in the case of regression, and probability values, probability like values, or class labels in the case of classification. For Stacking, we can use sklearn.ensemble.StackingRegressor. from mlxtend.regressor import StackingCVRegressorfrom sklearn.datasets import load_bostonfrom sklearn.svm import SVRfrom sklearn.linear_model import Lassofrom sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import cross_val_scorestack = StackingCVRegressor(regressors=(svr, lasso, rf), meta_regressor=lasso,random_state=RANDOM_SEED) Stacking regression is an ensemble learning technique to combine multiple regression models via a meta-regressor. The individual regression models are trained based on the complete training set; then, the meta-regressor is fitted based on the outputs — meta-features — of the individual regression models in the ensemble. As a result of this analysis, we can see that time series forecasting doesn't stay. Every day we could find new approaches and new frameworks. In this article, I tried to collect some of them and show how to implement them in the real case. From my experience combination strategies have potential application in demand forecasting problems, outperform other state-of-the-art models in trend and stationary series, and have comparable accuracy to other models. All depend on the input data and business goal, but I hope that those models help You to create your own state-of-the-art approach for your business. Thanks for reading. All code you can find in the Git repository — link.
[ { "code": null, "e": 304, "s": 172, "text": "In this story, I would like to make an overview of common data science techniques and frameworks to create a demand forecast model." }, { "code": null, "e": 600, "s": 304, "text": "First of all, let's define what is demand forecasting and what impact it has got on business. Wiki said — “Demand forecasting is a field of predictive analytics which tries to understand and predict customer demand to optimize supply decisions by corporate supply chain and business management.”" }, { "code": null, "e": 644, "s": 600, "text": "There are several types of demand forecast:" }, { "code": null, "e": 866, "s": 644, "text": "Short-term (It is is carried out for a shorter-term period of 3 months to 12 months. In the short term, the seasonal pattern of demand and the effect of tactical decisions on customer demand are taken into consideration.)" }, { "code": null, "e": 1154, "s": 866, "text": "Medium to long-term (It is typically carried out for more than 12 months to 24 months in advance (36–48 months in certain businesses). Long-term Forecasting drives business strategy planning, sales and marketing planning, financial planning, capacity planning, capital expenditure, etc.)" }, { "code": null, "e": 1543, "s": 1154, "text": "External macro-level (This type of Forecasting deals with the broader market movements which depend on the macroeconomic environment. External Forecasting is carried out for evaluating the strategic objectives of a business like product portfolio expansion, entering new customer segments, technological disruptions, a paradigm shift in consumer behavior, and risk mitigation strategies.)" }, { "code": null, "e": 1820, "s": 1543, "text": "Internal business level (This type of Forecasting deals with internal operations of the business such as product category, sales division, financial division, and manufacturing group. This includes annual sales forecast, estimation of COGS, net profit margin, cash flow, etc.)" }, { "code": null, "e": 1990, "s": 1820, "text": "Passive (It is carried out for stable businesses with very conservative growth plans. Simple extrapolations of historical data are carried out with minimal assumptions.)" }, { "code": null, "e": 2227, "s": 1990, "text": "Active (It is carried out for scaling and diversifying businesses with aggressive growth plans in terms of marketing activities, product portfolio expansion, and consideration of competitor activities and external economic environment.)" }, { "code": null, "e": 2666, "s": 2227, "text": "Why demand forecast is so important and what process it improve? Demand Forecasting is the pivotal business process around which strategic and operational plans of a company are devised. Based on the Demand Forecast, strategic and long-range plans of a business like budgeting, financial planning, sales and marketing plans, capacity planning, risk assessment, and mitigation plans are formulated. It also affects the following processes:" }, { "code": null, "e": 2700, "s": 2666, "text": "Supplier relationship management." }, { "code": null, "e": 2734, "s": 2700, "text": "Customer relationship management." }, { "code": null, "e": 2767, "s": 2734, "text": "Order fulfillment and logistics." }, { "code": null, "e": 2788, "s": 2767, "text": "Marketing campaigns." }, { "code": null, "e": 2819, "s": 2788, "text": "Manufacturing flow management." }, { "code": null, "e": 2949, "s": 2819, "text": "Ok, let's solve this problem and try to use different data science techniques and frameworks to make an accurate demand forecast." }, { "code": null, "e": 3138, "s": 2949, "text": "For my experiment, I would like to use a dataset from Kaggle's competition. In every data science task, I use CRISP-DM to follow all the necessary processes during the work on the project." }, { "code": null, "e": 3394, "s": 3138, "text": "The first phase of CRISP-DM is — Business Understanding. The task is to forecast the total amount of products sold in every shop for the test set. What about the metrics or success criteria? The forecast is evaluated by the root mean squared error (RMSE)." }, { "code": null, "e": 3661, "s": 3394, "text": "The second and the third phases, as for me, are one of the most important — Data understanding and preparation. The first task when initiating the demand forecasting project is to provide the client with meaningful insights. The process includes the following steps:" }, { "code": null, "e": 3683, "s": 3661, "text": "Gather available data" }, { "code": null, "e": 3705, "s": 3683, "text": "Gather available data" }, { "code": null, "e": 3748, "s": 3705, "text": "In our case we have got the next datasets:" }, { "code": null, "e": 3841, "s": 3748, "text": "sales_train.csv — the training set. Daily historical data from January 2013 to October 2015." }, { "code": null, "e": 3945, "s": 3841, "text": "test.csv — the test set. You need to forecast the sales for these shops and products for November 2015." }, { "code": null, "e": 4017, "s": 3945, "text": "sample_submission.csv — a sample submission file in the correct format." }, { "code": null, "e": 4080, "s": 4017, "text": "items.csv — supplemental information about the items/products." }, { "code": null, "e": 4155, "s": 4080, "text": "item_categories.csv — supplemental information about the items categories." }, { "code": null, "e": 4208, "s": 4155, "text": "shops.csv- supplemental information about the shops." }, { "code": null, "e": 4330, "s": 4208, "text": "Briefly review the data structure, accuracy, and consistency. Let’s make several tables and plots to analyze our dataset." }, { "code": null, "e": 4599, "s": 4330, "text": "This base analytics could help us to understand, the main input parameters of the dataset. For example, we could see, that in our dataset we have got a negative value for Price, which could be a mistake, and a negative value for Sales, which could be зurchase returns." }, { "code": null, "e": 4668, "s": 4599, "text": "The next table explains for us the distribution for numeric columns:" }, { "code": null, "e": 4733, "s": 4668, "text": "Here we can see, that half of our sales have a value equal to 1." }, { "code": null, "e": 4819, "s": 4733, "text": "Let’s make a scatter plot to analyze the relationship between sales volume and price." }, { "code": null, "e": 4993, "s": 4819, "text": "This type of plot usually can show us, that we have got units with little price and big volume of sales and inits with an abnormally high price and very low volume of sales." }, { "code": null, "e": 5029, "s": 4993, "text": "Let’s analyze our data in dynamic —" }, { "code": null, "e": 5106, "s": 5029, "text": "The first plot show for us decrease trend of unique items in the assortment:" }, { "code": null, "e": 5303, "s": 5106, "text": "The second plot show for us decreases trend of quantity sales and two picks, which could be a seasonal or some promo. This is what we need to learn from business and through quantitative analysis." }, { "code": null, "e": 5711, "s": 5303, "text": "The next step is analytics of our category which we will use to aggregate our dataset, the first dimension is items/category names and the second is shops id. This analysis shows for us the sales volume distribution in item’s category and shops and would help for us to understand which categories and shops is the most important for us and which ones have got a short history for analytics and forecasting." }, { "code": null, "e": 5880, "s": 5711, "text": "EDA is an ongoing process that you can continue to do throughout the entire time of working with different experiments. Let’s stop at this point and start creat models." }, { "code": null, "e": 6095, "s": 5880, "text": "Before we start to create models, we need to split our dataset for training, validation, and testing. Keep in mind, that we need to use the date column to filter our dataset, don’t use random split for time-series." }, { "code": null, "e": 6167, "s": 6095, "text": "In this part, I would like to explain and create basic approach models." }, { "code": null, "e": 6367, "s": 6167, "text": "The first one is the Smoothed Moving Average. The smoothed moving average (SMMA) is a demand forecasting model that can be used to gauge trends based on a series of averages from consecutive periods." }, { "code": null, "e": 6591, "s": 6367, "text": "For example, the smoothed moving average from six months of sales could be calculated by taking the average of sales from January to June, then the average of sales between February to July, then March to August, and so on." }, { "code": null, "e": 6699, "s": 6591, "text": "This model is called ‘moving’ because averages are continually recalculated as more data becomes available." }, { "code": null, "e": 6747, "s": 6699, "text": "A moving average of order mm can be written as:" }, { "code": null, "e": 6970, "s": 6747, "text": "where m=2k+1m=2k+1. That is, the estimate of the trend-cycle at time tt is obtained by averaging values of the time series within kk periods of tt. Observations that are nearby in time are also likely to be close in value." }, { "code": null, "e": 7447, "s": 6970, "text": "Smoothed Moving Average is useful for looking at overall sales trends over time and aiding long-term demand planning. Rapid changes as a result of seasonality or other fluctuations are smoothed out so you can analyze the bigger picture more accurately. The smoothed moving average model typically works well when you have a product that’s growing consistently or declining over time. Also, the important disadvantage of this approach, that we could make Items without history." }, { "code": null, "e": 7523, "s": 7447, "text": "To make it in Python we can use pandas.DataFrame.shift to create Lag value," }, { "code": null, "e": 7582, "s": 7523, "text": "full_df['sales_lag_n'] = full_df['sales'].shift(periods=n)" }, { "code": null, "e": 7676, "s": 7582, "text": "then we can use pandas.DataFrame.rolling to create a rolling mean base on created Lag values." }, { "code": null, "e": 7733, "s": 7676, "text": "full_df['sma'] = full_df['sales_lag_n].rolling(n).mean()" }, { "code": null, "e": 8265, "s": 7733, "text": "The next model is Holt Winter’s Exponential Smoothing. Holt (1957) and Winters (1960) extended Holt’s method to capture seasonality. The Holt-Winters seasonal method comprises the forecast equation and three smoothing equations — one for the level ltlt, one for the trend bt, and one for the seasonal component st, with corresponding smoothing parameters αα, β∗β∗ and γγ. We use mm to denote the frequency of the seasonality, i.e., the number of seasons in a year. For example, for quarterly data m=4m=4, and monthly data m=12m=12." }, { "code": null, "e": 9132, "s": 8265, "text": "There are two variations to this method that differ like the seasonal component. The additive method is preferred when the seasonal variations are roughly constant through the series, while the multiplicative method is preferred when the seasonal variations are changing proportionally to the level of the series. With the additive method, the seasonal component is expressed in absolute terms in the scale of the observed series, and in the level equation, the series is seasonally adjusted by subtracting the seasonal component. Within each year, the seasonal component will add up to approximately zero. With the multiplicative method, the seasonal component is expressed in relative terms (percentages), and the series is seasonally adjusted by dividing through by the seasonal component. Within each year, the seasonal component will sum up to approximately mm." }, { "code": null, "e": 9310, "s": 9132, "text": "This method is more efficient than the previous one because it handles the season components, but it has got the same disadvantage it doesn’t handle new items in the assortment." }, { "code": null, "e": 9354, "s": 9310, "text": "This method has an implementation in Python" }, { "code": null, "e": 9423, "s": 9354, "text": "from statsmodels.tsa.holtwinters import ExponentialSmoothing as HWES" }, { "code": null, "e": 9528, "s": 9423, "text": "This model applies to one pair shop-item, which means that we need to create a new model for every pair." }, { "code": null, "e": 9834, "s": 9528, "text": "for index, row in tqdm(df_test.iterrows()): tmp = df_train_aggr[(df_train_aggr['shop_id'] == row['shop_id']) & (df_train_aggr['item_id'] == row['item_id'])] model = ExponentialSmoothing(tmp.item_cnt_day) model_fit = model.fit() forecast = model_fit.forecast(steps=n)" }, { "code": null, "e": 10266, "s": 9834, "text": "The last model in my basic approach is ARIMA. ARIMA, short for ‘Auto-Regressive Integrated Moving Average’ is actually a class of models that ‘explains’ a given time series based on its own past values, that is, its own lags and the lagged forecast errors, so that equation can be used to forecast future values. Any ‘non-seasonal time series that exhibits patterns and is not a random white noise can be modeled with ARIMA models." }, { "code": null, "e": 10325, "s": 10266, "text": "An ARIMA model is characterized by 3 terms: p, d, q where," }, { "code": null, "e": 10355, "s": 10325, "text": "p is the order of the AR term" }, { "code": null, "e": 10385, "s": 10355, "text": "q is the order of the MA term" }, { "code": null, "e": 10460, "s": 10385, "text": "d is the number of differences required to make the time series stationary" }, { "code": null, "e": 10966, "s": 10460, "text": "If a time series, has seasonal patterns, then you need to add seasonal terms and it becomes SARIMA, short for ‘Seasonal ARIMA’. More on that once we finish ARIMA. As a previous model, I will build a separate model for each shop-item pairs. So the main idea is to find the right parameters for our models. I would not write a long description of how to calculate each one, but You can find it here. In my case, I would like to use something like auto.arima. I find an interesting implementation — pmdarima." }, { "code": null, "e": 11279, "s": 10966, "text": "“pmdarima” brings R’s beloved auto.arima to Python, making an even stronger case for why you don’t need R for data science. pmdarima is 100% Python + Cython and does not leverage any R code, but is implemented in a powerful, yet easy-to-use set of functions & classes that will be familiar to scikit-learn users." }, { "code": null, "e": 11330, "s": 11279, "text": "The code will be very similar to the previous one:" }, { "code": null, "e": 11750, "s": 11330, "text": "import pmdarima as pmfor index, row in tqdm(df_test.iterrows()): model = pm.auto_arima(tmp.item_cnt_day, start_p=1, start_q=1, max_p=3, max_q=3, m=12,start_P=0, seasonal=False,d=1, D=1, trace=False,error_action='ignore', # don't want to know if an order does not worksuppress_warnings=True, # don't want convergence warningsstepwise=True)forecast = model_fit.predict(n_periods = n, return_conf_int=False)" }, { "code": null, "e": 12062, "s": 11750, "text": "ARIMA is a quite strong model, which could give a good forecast. ARIMA can be limited in forecasting extreme values. While the model is adept at modeling seasonality and trends, outliers are difficult to forecast for ARIMA for the very reason that they lie outside of the general trend as captured by the model." }, { "code": null, "e": 12311, "s": 12062, "text": "So, classical time series forecasting methods may be focused on linear relationships, nevertheless, they are sophisticated and perform well on a wide range of problems, assuming that your data is suitably prepared and the method is well configured." }, { "code": null, "e": 12684, "s": 12311, "text": "A most common enterprise application of machine learning teamed with statistical methods is predictive analytics. It allows for not only estimating demand but also for understanding what drives sales and how customers are likely to behave under certain conditions. The main idea in using machine learning models for demand forecast is to generate a lot of useful features." }, { "code": null, "e": 12898, "s": 12684, "text": "Feature engineering is the use of domain knowledge data and the creation of features that make machine learning models predict more accurately. It enables a deeper understanding of data and more valuable insights." }, { "code": null, "e": 12921, "s": 12898, "text": "This feature could be:" }, { "code": null, "e": 12988, "s": 12921, "text": "Product/Shop characteristics (information from items dictionaries)" }, { "code": null, "e": 13054, "s": 12988, "text": "Internal information about promo activities and any price changes" }, { "code": null, "e": 13111, "s": 13054, "text": "Different level target encoding of categorical variables" }, { "code": null, "e": 13125, "s": 13111, "text": "Date features" }, { "code": null, "e": 13218, "s": 13125, "text": "In my experiments, I will use the following Python libraries CatBoost, XGBoost, and H2O AML." }, { "code": null, "e": 13244, "s": 13218, "text": "Let’s start with XGBoost." }, { "code": null, "e": 13277, "s": 13244, "text": "from xgboost import XGBRegressor" }, { "code": null, "e": 14153, "s": 13277, "text": "XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible, and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost cannot handle categorical features by itself, it only accepts numerical values similar to Random Forest. Therefore one has to perform various encodings like label encoding, mean encoding, or one-hot encoding before supplying categorical data to XGBoost. XGboost splits up to the specified max_depth hyperparameter and then starts pruning the tree backward and removes splits beyond which there is no positive gain. It uses this approach since sometimes a split of no loss reduction may be followed by a split with loss reduction. XGBoost can also perform leaf-wise tree growth. XGBoost missing values will be allocated to the side that reduces the loss in each split." }, { "code": null, "e": 14419, "s": 14153, "text": "# Trainmodel = XGBRegressor(max_depth=8,n_estimators=1000,min_child_weight=300,colsample_bytree=0.8,subsample=0.8,eta=0.3,seed=42)model.fit(X_train,Y_train,eval_metric=\"rmse\",eval_set=[(X_train, Y_train), (X_valid, Y_valid)],verbose=True,early_stopping_rounds = 10)" }, { "code": null, "e": 14648, "s": 14419, "text": "XGBoost is a good and fast implementation of gradient boosting algorithm for machine learning, but the main disadvantage, as for me, is that couldn't use categorical factors and in the results, a model may lose some information." }, { "code": null, "e": 14678, "s": 14648, "text": "The next library is CatBoost." }, { "code": null, "e": 14717, "s": 14678, "text": "from catboost import CatBoostRegressor" }, { "code": null, "e": 14987, "s": 14717, "text": "Catboost grows a balanced tree. In each level of such a tree, the feature-split pair that brings to the lowest loss (according to a penalty function) is selected and is used for all the level’s nodes. It is possible to change its policy using the grow-policy parameter." }, { "code": null, "e": 15382, "s": 14987, "text": "Catboost has two modes for processing missing values, “Min” and “Max”. In “Min”, missing values are processed as the minimum value for a feature (they are given a value that is less than all existing values). This way, it is guaranteed that a split that separates missing values from all other values is considered when selecting splits. “Max” works the same as “Min”, only with maximum values." }, { "code": null, "e": 15903, "s": 15382, "text": "Catboost uses a combination of one-hot encoding and an advanced mean encoding. For features with a low number of categories, it uses one-hot encoding. The maximum number of categories for one-hot encoding can be controlled by the one_hot_max_size parameter. For the remaining categorical columns, CatBoost uses an efficient method of encoding, which is similar to mean encoding but with an additional mechanism aimed at reducing overfitting. Using CatBoost’s categorical encoding comes with a downside of a slower model." }, { "code": null, "e": 16086, "s": 15903, "text": "# Trainmodel=CatBoostRegressor(iterations=100, depth=10, learning_rate=0.03, loss_function='RMSE')model.fit(X_train, Y_train, cat_features = categorical, eval_set=(X_valid, Y_valid))" }, { "code": null, "e": 16230, "s": 16086, "text": "CatBoost provides useful tools for easy work with highly categorized data. It shows solid results training on unprocessed categorical features." }, { "code": null, "e": 16255, "s": 16230, "text": "The last one on H2O AML." }, { "code": null, "e": 16342, "s": 16255, "text": "import h2ofrom h2o.automl import H2OAutoMLh2o.init(nthreads = 7, max_mem_size = '45g')" }, { "code": null, "e": 16814, "s": 16342, "text": "H2O’s AutoML can be used for automating the machine learning workflow, which includes automatic training and tuning of many models within a user-specified time-limit. Stacked Ensembles — one based on all previously trained models, another one on the best model of each family — will be automatically trained on collections of individual models to produce highly predictive ensemble models which, in most cases, will be the top-performing models in the AutoML Leaderboard." }, { "code": null, "e": 17184, "s": 16814, "text": "AutoML will iterate through different models and parameters trying to find the best. There are several parameters to specify, but in most cases, all you need to do is to set only the maximum runtime in seconds or a maximum number of models. You can think about AutoML as something similar to GridSearch but on the level of models rather than on the level of parameters." }, { "code": null, "e": 17307, "s": 17184, "text": "# Run AutoMLaml = H2OAutoML(max_models = 5, seed=1)aml.train(y=y, training_frame=x_train_hf,validation_frame = x_valid_hf)" }, { "code": null, "e": 17779, "s": 17307, "text": "AutoML is to automate repetitive tasks like pipeline creation and hyperparameter tuning so that data scientists can spend more of their time on the business problem at hand. AutoML also aims to make the technology available to everybody rather than a select few. AutoML and data scientists can work in conjunction to accelerate the ML process so that the real effectiveness of machine learning can be utilized. In my case, I have the best result among the previous model." }, { "code": null, "e": 18397, "s": 17779, "text": "Powerful class of machine learning algorithms that use artificial neural networks to understand and leverage patterns in data. Deep learning algorithms use multiple layers to extract higher-level features from raw data progressively: this reduces the amount of feature extraction needed in other machine learning methods. The deep learning algorithm learns on its own by recognizing patterns using many layers of processing. That is why the “deep” in “deep learning” refers to the number of layers through which the data is transformed. Multiple transformations automatically extract important features from raw data." }, { "code": null, "e": 18771, "s": 18397, "text": "The main challenge in this task is to handle categorical variables. In deep learning, we can use Entity Embeddings. Embeddings are a solution to dealing with categorical variables while avoiding a lot of the pitfalls of one-hot encoding. An embedding is a mapping of a categorical variable into an n-dimensional vector. So, how our neural network’s architecture looks like?" }, { "code": null, "e": 18906, "s": 18771, "text": "The first, Python framework for this task — Keras. The main challenge here is to write a code for embedding every categorical feature." }, { "code": null, "e": 19238, "s": 18906, "text": "import tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras.layers import Input, Dense, Activation, Reshape, BatchNormalization, Dropout, concatenate, Embeddingfrom tensorflow.keras.models import Modelfrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau" }, { "code": null, "e": 19295, "s": 19238, "text": "Keras's implementation of this approach is rather bulky." }, { "code": null, "e": 21242, "s": 19295, "text": "model_inputs = []model_embeddings = []for input_dim, output_dim in emb_space: i = Input(shape=(1,)) emb = Embedding(input_dim=input_dim, output_dim=output_dim)(i) model_inputs.append(i) model_embeddings.append(emb)con_outputs = []for con in con_feature: elaps_input = Input(shape=(1,)) elaps_output = Dense(10)(elaps_input) elaps_output = Activation(\"relu\")(elaps_output) elaps_output = Reshape(target_shape=(1,10))(elaps_output) model_inputs.append(elaps_input) con_outputs.append(elaps_output)merge_embeddings = concatenate(model_embeddings, axis=-1)if len(con_outputs) > 1:merge_con_output = concatenate(con_outputs)else:merge_con_output = con_outputs[0]merge_embedding_cont = concatenate([merge_embeddings, merge_con_output])merge_embedding_contoutput_tensor = Dense(1000, name=\"dense1024\")(merge_embedding_cont)output_tensor = BatchNormalization()(output_tensor)output_tensor = Activation('relu')(output_tensor)output_tensor = Dropout(0.3)(output_tensor)output_tensor = Dense(500, name=\"dense512\")(output_tensor)output_tensor = BatchNormalization()(output_tensor)output_tensor = Activation(\"relu\")(output_tensor)output_tensor = Dropout(0.3)(output_tensor)output_tensor = Dense(1, activation='linear', name=\"output\", kernel_constraint = NonNeg())(output_tensor)optimizer = Adam(lr=10e-3)nn_model = Model(inputs=model_inputs, outputs=output_tensor)nn_model.compile(loss='mse', optimizer=optimizer, metrics=['mean_squared_error'])reduceLr=ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=1, verbose=1)checkpoint = ModelCheckpoint(\"nn_model.hdf5\", monitor='val_loss', verbose=1, save_best_only=True, mode='min')#val_mean_absolute_percentage_errorcallbacks_list = [checkpoint, reduceLr]history = nn_model.fit(x=x_fit_train, y=y_train.reshape(-1,1,1),validation_data=(x_fit_val, y_val.reshape(-1,1,1)),batch_size=1024, epochs=10, callbacks=callbacks_list)" }, { "code": null, "e": 21527, "s": 21242, "text": "All machine learning features and entity embeddings approach showed slightly better results than previous models, but more training time was spent. The advantage of using embeddings is that they can be learned, representing each category better than what other models can approximate." }, { "code": null, "e": 21610, "s": 21527, "text": "So, we see that this approach is good, but the main disadvantage is a lot of code." }, { "code": null, "e": 22034, "s": 21610, "text": "Fastai is our solution. Fast.ai is popular deep learning that provides high-level components to obtain state-of-the-art results in standard deep learning domains. Fast.ai allows practitioners to experiment, mix and match to discover new approaches. In short, to facilitate hassle-free deep learning solutions. The libraries leverage the dynamism of the underlying Python language and the flexibility of the PyTorch library." }, { "code": null, "e": 22063, "s": 22034, "text": "from fastai.tabular import *" }, { "code": null, "e": 22405, "s": 22063, "text": "Training a Deep Neural Network (DNN) is a difficult global optimization problem. Learning Rate (LR) is a crucial hyper-parameter to tune when training DNNs. A very small learning rate can lead to very slow training, while a very large learning rate can hinder convergence as the loss function fluctuates around the minimum, or even diverges." }, { "code": null, "e": 22889, "s": 22405, "text": "Fastai implemented in this framework one cycle policy. Super-convergence uses the CLR method, but with just one cycle — which contains two learning rate steps, one increasing and one decreasing — and a large maximum learning rate bound. The cycle’s size must be smaller than the total number of iterations/epochs. After the cycle is complete, the learning rate should decrease even further for the remaining iterations/epochs, several orders of magnitude less than its initial value." }, { "code": null, "e": 23588, "s": 22889, "text": "#TabularList for Validationval = (TabularList.from_df(X_train.iloc[start_indx:end_indx].copy(), path=path, cat_names=cat_feature, cont_names=con_feature))test = (TabularList.from_df(X_test, path=path, cat_names=cat_feature, cont_names=con_feature, procs=procs))#TabularList for trainingdata = (TabularList.from_df(X_train, path=path, cat_names=cat_feature, cont_names=con_feature, procs=procs).split_by_idx(list(range(start_indx,end_indx))).label_from_df(cols=dep_var).add_test(test).databunch())#Initializing the networklearn = tabular_learner(data, layers=[1024,512], metrics= [rmse,r2_score])#Exploring the learning rateslearn.lr_find()learn.recorder.plot()# Learn learn.fit_one_cycle(10, 1e-02)" }, { "code": null, "e": 23743, "s": 23588, "text": "As a result, we have got less code and a faster way to find optimal learning rate. The result is very similar to the previous neural network architecture." }, { "code": null, "e": 24036, "s": 23743, "text": "This architecture works well, but what if we would like to get some information from previous periods of sales without adding Lag features. So we need to add LSTM or RNN layer to our architecture. In Keras, it will make the code even more cumbersome and there is no implementation for Fastai." }, { "code": null, "e": 24096, "s": 24036, "text": "I found the solution to this problem — PyTorch Forecasting." }, { "code": null, "e": 24394, "s": 24096, "text": "Pytorch Forecasting aims to ease state-of-the-art time series forecasting with neural networks for both real-world cases and research alike. The goal is to provide a high-level API with maximum flexibility for professionals and reasonable defaults for beginners. Specifically, the package provides" }, { "code": null, "e": 24543, "s": 24394, "text": "A time-series dataset class that abstracts handling variable transformations, missing values, randomized subsampling, multiple history lengths, etc." }, { "code": null, "e": 24726, "s": 24543, "text": "A base model class which provides basic training of time series models along with logging in tensorboard and generic visualizations such as actual vs predictions and dependency plots" }, { "code": null, "e": 24893, "s": 24726, "text": "Multiple neural network architectures for time series forecasting that have been enhanced for real-world deployment and come with in-built interpretation capabilities" }, { "code": null, "e": 24927, "s": 24893, "text": "Multi-horizon time series metrics" }, { "code": null, "e": 24970, "s": 24927, "text": "Ranger optimizer for faster model training" }, { "code": null, "e": 25004, "s": 24970, "text": "Hyperparameter tuning with optuna" }, { "code": null, "e": 25114, "s": 25004, "text": "The package is built on PyTorch Lightning to allow training on CPUs, single and multiple GPUs out-of-the-box." }, { "code": null, "e": 25661, "s": 25114, "text": "import torchimport pytorch_lightning as plfrom pytorch_lightning.callbacks import EarlyStopping, LearningRateMonitorfrom pytorch_lightning.loggers import TensorBoardLoggerfrom pytorch_forecasting import Baseline, TemporalFusionTransformer, TimeSeriesDataSetfrom pytorch_forecasting.data import GroupNormalizerfrom pytorch_forecasting.metrics import SMAPE, PoissonLoss, QuantileLoss, RMSEfrom pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparametersfrom pytorch_forecasting.data.encoders import NaNLabelEncoder" }, { "code": null, "e": 25839, "s": 25661, "text": "In my example, I used Temporal Fusion Transformer [2]. This is an architecture developed by Oxford University and Google that has beaten Amazon’s DeepAR by 36–69% in benchmarks." }, { "code": null, "e": 25936, "s": 25839, "text": "The first step — we need to create a data loader and create a special data object for our model." }, { "code": null, "e": 27902, "s": 25936, "text": "max_prediction_length = 1max_encoder_length = 6training_cutoff = X_train[\"time_idx\"].max() - max_prediction_lengthtraining = TimeSeriesDataSet(X_train[lambda x: x.time_idx <= training_cutoff],time_idx=\"time_idx\",target=\"log_sales\",group_ids=[\"shop_id\", \"item_id\"],min_encoder_length=max_encoder_length // 2, # keep encoder length long (as it is in the validation set)max_encoder_length=max_encoder_length,min_prediction_length=1,max_prediction_length=max_prediction_length,static_categoricals=[\"shop_id\", \"item_id\"],static_reals=['city_coord_1', 'city_coord_2'],time_varying_known_categoricals=[\"month\"],time_varying_known_reals=[\"time_idx\", \"delta_price_lag\"],time_varying_unknown_categoricals=[\"shop_category\", \"city_code\", \"item_category_id\",\"type_code\", \"subtype_code\", \"country_part\"],categorical_encoders = {\"shop_id\": NaNLabelEncoder(add_nan=True),\"item_id\": NaNLabelEncoder(add_nan=True),\"shop_category\": NaNLabelEncoder(add_nan=True),\"city_code\": NaNLabelEncoder(add_nan=True),\"item_category_id\": NaNLabelEncoder(add_nan=True),\"type_code\": NaNLabelEncoder(add_nan=True),\"subtype_code\": NaNLabelEncoder(add_nan=True),\"country_part\": NaNLabelEncoder(add_nan=True),},time_varying_unknown_reals=['date_cat_avg_item_cnt_lag_1','date_shop_cat_avg_item_cnt_lag_1', 'date_shop_type_avg_item_cnt_lag_1','date_shop_subtype_avg_item_cnt_lag_1','date_city_avg_item_cnt_lag_1','date_item_city_avg_item_cnt_lag_1','date_type_avg_item_cnt_lag_1','date_subtype_avg_item_cnt_lag_1', 'item_shop_last_sale', 'item_last_sale','item_shop_first_sale', 'item_first_sale'],add_relative_time_idx=True,add_encoder_length=True,allow_missings=True)validation = TimeSeriesDataSet.from_dataset(training,X_train, min_prediction_idx=training.index.time.max() + 1, stop_randomization=True)batch_size = 128train_dataloader = training.to_dataloader(train=True, batch_size=batch_size, num_workers=2)val_dataloader = validation.to_dataloader(train=False, batch_size=batch_size, num_workers=2)" }, { "code": null, "e": 27953, "s": 27902, "text": "The next step is to find an optimal learning rate." }, { "code": null, "e": 29056, "s": 27953, "text": "pl.seed_everything(42)trainer = pl.Trainer(gpus=1,# clipping gradients is a hyperparameter and important to prevent divergance# of the gradient for recurrent neural networksgradient_clip_val=0.1,)tft = TemporalFusionTransformer.from_dataset(training,# not meaningful for finding the learning rate but otherwise very importantlearning_rate=0.03,hidden_size=16, # most important hyperparameter apart from learning rate# number of attention heads. Set to up to 4 for large datasetsattention_head_size=1,dropout=0.1, # between 0.1 and 0.3 are good valueshidden_continuous_size=8, # set to <= hidden_sizeoutput_size=1, # 7 quantiles by defaultloss=RMSE(),# reduce learning rate if no improvement in validation loss after x epochsreduce_on_plateau_patience=4,)print(f\"Number of parameters in network: {tft.size()/1e3:.1f}k\")# find optimal learning ratetorch.set_grad_enabled(False)res = trainer.tuner.lr_find(tft,train_dataloader=train_dataloader,val_dataloaders=val_dataloader,max_lr=10.0,min_lr=1e-6)print(f\"suggested learning rate: {res.suggestion()}\")fig = res.plot(show=True, suggest=True)fig.show()" }, { "code": null, "e": 29110, "s": 29056, "text": "Now we can configure our neural network and train it." }, { "code": null, "e": 30170, "s": 29110, "text": "early_stop_callback = EarlyStopping(monitor=\"val_loss\", min_delta=1e-4, patience=10, verbose=False, mode=\"min\")lr_logger = LearningRateMonitor() # log the learning ratelogger = TensorBoardLogger(\"lightning_logs\") # logging results to a tensorboardtrainer = pl.Trainer(max_epochs=30,gpus=1,weights_summary=\"top\",gradient_clip_val=0.1,limit_train_batches=30, # coment in for training, running valiation every 30 batches# fast_dev_run=True, # comment in to check that networkor dataset has no serious bugscallbacks=[lr_logger, early_stop_callback],logger=logger,)tft = TemporalFusionTransformer.from_dataset(training,learning_rate=0.03,hidden_size=16,attention_head_size=4,dropout=0.1,hidden_continuous_size=8,output_size=1, # 7 quantiles by defaultloss=RMSE(),log_interval=10, # uncomment for learning rate finder and otherwise, e.g. to 10 for logging every 10 batchesreduce_on_plateau_patience=4)print(f\"Number of parameters in network: {tft.size()/1e3:.1f}k\")# fit networktrainer.fit(tft,train_dataloader=train_dataloader,val_dataloaders=val_dataloader)" }, { "code": null, "e": 30234, "s": 30170, "text": "Also, we could tune our model and find optimal hyperparameters." }, { "code": null, "e": 31041, "s": 30234, "text": "from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters# create studystudy = optimize_hyperparameters(train_dataloader,val_dataloader,model_path=\"optuna_test\",n_trials=200,max_epochs=50,gradient_clip_val_range=(0.01, 1.0),hidden_size_range=(8, 128),hidden_continuous_size_range=(8, 128),attention_head_size_range=(1, 4),learning_rate_range=(0.001, 0.1),dropout_range=(0.1, 0.3),trainer_kwargs=dict(limit_train_batches=30),reduce_on_plateau_patience=4,use_learning_rate_finder=False, # use Optuna to find ideal learning rate or use in-built learning rate finder)# save study results - also we can resume tuning at a later point in timewith open(\"test_study.pkl\", \"wb\") as fout: pickle.dump(study, fout)# show best hyperparametersprint(study.best_trial.params)" }, { "code": null, "e": 31172, "s": 31041, "text": "As a result, I have got a good performance model with all features and approaches, that could be used for time series forecasting." }, { "code": null, "e": 31380, "s": 31172, "text": "Stacking or Stacked Generalization is an ensemble machine learning algorithm. It uses a meta-learning algorithm to learn how to best combine the predictions from two or more base machine learning algorithms." }, { "code": null, "e": 31458, "s": 31380, "text": "We could use Stacking to combine the severals model and make new predictions." }, { "code": null, "e": 31663, "s": 31458, "text": "The architecture of a stacking model involves two or more base models, often referred to as level-0 models and a meta-model that combines the predictions of the base models referred to as a level-1 model." }, { "code": null, "e": 31761, "s": 31663, "text": "Level-0 Models (Base-Models): Models fit on the training data and whose predictions are compiled." }, { "code": null, "e": 31863, "s": 31761, "text": "Level-1 Model (Meta-Model): Model that learns how to best combine the predictions of the base models." }, { "code": null, "e": 32397, "s": 31863, "text": "The meta-model is trained on the predictions made by base models on out-of-sample data. That is, data not used to train the base models is fed to the base models, predictions are made, and these predictions, along with the expected outputs, provide the input and output pairs of the training dataset used to fit the meta-model. The outputs from the base models used as input to the meta-model may be real value in the case of regression, and probability values, probability like values, or class labels in the case of classification." }, { "code": null, "e": 32458, "s": 32397, "text": "For Stacking, we can use sklearn.ensemble.StackingRegressor." }, { "code": null, "e": 32820, "s": 32458, "text": "from mlxtend.regressor import StackingCVRegressorfrom sklearn.datasets import load_bostonfrom sklearn.svm import SVRfrom sklearn.linear_model import Lassofrom sklearn.ensemble import RandomForestRegressorfrom sklearn.model_selection import cross_val_scorestack = StackingCVRegressor(regressors=(svr, lasso, rf), meta_regressor=lasso,random_state=RANDOM_SEED)" }, { "code": null, "e": 33142, "s": 32820, "text": "Stacking regression is an ensemble learning technique to combine multiple regression models via a meta-regressor. The individual regression models are trained based on the complete training set; then, the meta-regressor is fitted based on the outputs — meta-features — of the individual regression models in the ensemble." }, { "code": null, "e": 33753, "s": 33142, "text": "As a result of this analysis, we can see that time series forecasting doesn't stay. Every day we could find new approaches and new frameworks. In this article, I tried to collect some of them and show how to implement them in the real case. From my experience combination strategies have potential application in demand forecasting problems, outperform other state-of-the-art models in trend and stationary series, and have comparable accuracy to other models. All depend on the input data and business goal, but I hope that those models help You to create your own state-of-the-art approach for your business." }, { "code": null, "e": 33773, "s": 33753, "text": "Thanks for reading." } ]
TypeScript - String toLowerCase()
This method returns the calling string value converted to lowercase. string.toLowerCase( ) Returns the calling string value converted to lowercase. var str = "Apples are round, and Apples are Juicy."; console.log(str.toLowerCase( )) On compiling, it will generate the same code in JavaScript. Its output is as follows − apples are round, and apples are juicy. 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2117, "s": 2048, "text": "This method returns the calling string value converted to lowercase." }, { "code": null, "e": 2140, "s": 2117, "text": "string.toLowerCase( )\n" }, { "code": null, "e": 2197, "s": 2140, "text": "Returns the calling string value converted to lowercase." }, { "code": null, "e": 2284, "s": 2197, "text": "var str = \"Apples are round, and Apples are Juicy.\"; \nconsole.log(str.toLowerCase( ))\n" }, { "code": null, "e": 2344, "s": 2284, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2371, "s": 2344, "text": "Its output is as follows −" }, { "code": null, "e": 2412, "s": 2371, "text": "apples are round, and apples are juicy.\n" }, { "code": null, "e": 2445, "s": 2412, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 2459, "s": 2445, "text": " Antonio Papa" }, { "code": null, "e": 2492, "s": 2459, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 2506, "s": 2492, "text": " Haider Malik" }, { "code": null, "e": 2541, "s": 2506, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2561, "s": 2541, "text": " Skillbakerystudios" }, { "code": null, "e": 2594, "s": 2561, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 2608, "s": 2594, "text": " Sean Bradley" }, { "code": null, "e": 2643, "s": 2608, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2659, "s": 2643, "text": " TELCOMA Global" }, { "code": null, "e": 2692, "s": 2659, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 2712, "s": 2692, "text": " Christopher Frewin" }, { "code": null, "e": 2719, "s": 2712, "text": " Print" }, { "code": null, "e": 2730, "s": 2719, "text": " Add Notes" } ]
MySQL UPDATE query where id is highest AND field is equal to variable?
The syntax is as follows update yourTableName set yourColumnName1=yourValue where yourColumnName2=yourValue order by yourIdColumnName DESC LIMIT 1; To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table UpdateWithHighestDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserStatus tinyint, -> UserRank int -> ); Query OK, 0 rows affected (0.61 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,78); Query OK, 1 row affected (0.12 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,118); Query OK, 1 row affected (0.18 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,223); Query OK, 1 row affected (0.62 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,225); Query OK, 1 row affected (0.12 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,227); Query OK, 1 row affected (0.14 sec) mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,230); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement. The query is as follows mysql> select *from UpdateWithHighestDemo; The following is the output +--------+------------+----------+ | UserId | UserStatus | UserRank | +--------+------------+----------+ | 1 | 1 | 78 | | 2 | 0 | 118 | | 3 | 1 | 223 | | 4 | 1 | 225 | | 5 | 0 | 227 | | 6 | 0 | 230 | +--------+------------+----------+ 6 rows in set (0.00 sec) Here is the query to update column mysql> update UpdateWithHighestDemo -> set UserStatus=1 where UserRank=230 order by UserId DESC LIMIT 1; Query OK, 1 row affected (0.19 sec) Rows matched: 1 Changed: 1 Warnings: 0 Let us check and display records from the table using select statement. The query is as follows mysql> select *from UpdateWithHighestDemo; The following is the output +--------+------------+----------+ | UserId | UserStatus | UserRank | +--------+------------+----------+ | 1 | 1 | 78 | | 2 | 0 | 118 | | 3 | 1 | 223 | | 4 | 1 | 225 | | 5 | 0 | 227 | | 6 | 1 | 230 | +--------+------------+----------+ 6 rows in set (0.00 sec) Now if you want to update with highest id then ORDER BY clause is useful. In the above sample output the highest ‘UserId’=6 and UserStatus is 1. Let us update UserStatus to 0. The query is as follows mysql> update UpdateWithHighestDemo -> set UserStatus=0 order by UserId DESC LIMIT 1; Query OK, 1 row affected (0.18 sec) Rows matched: 1 Changed: 1 Warnings: 0 Check the records from the table using select statement. The query is as follows mysql> select *from UpdateWithHighestDemo; +--------+------------+----------+ | UserId | UserStatus | UserRank | +--------+------------+----------+ | 1 | 1 | 78 | | 2 | 0 | 118 | | 3 | 1 | 223 | | 4 | 1 | 225 | | 5 | 0 | 227 | | 6 | 0 | 230 | +--------+------------+----------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1087, "s": 1062, "text": "The syntax is as follows" }, { "code": null, "e": 1210, "s": 1087, "text": "update yourTableName\nset yourColumnName1=yourValue where yourColumnName2=yourValue order by yourIdColumnName DESC LIMIT 1;" }, { "code": null, "e": 1307, "s": 1210, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1502, "s": 1307, "text": "mysql> create table UpdateWithHighestDemo\n -> (\n -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserStatus tinyint,\n -> UserRank int\n -> );\nQuery OK, 0 rows affected (0.61 sec)" }, { "code": null, "e": 1557, "s": 1502, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1581, "s": 1557, "text": "The query is as follows" }, { "code": null, "e": 2258, "s": 1581, "text": "mysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,78);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,118);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,223);\nQuery OK, 1 row affected (0.62 sec)\nmysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(1,225);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,227);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into UpdateWithHighestDemo(UserStatus,UserRank) values(0,230);\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2317, "s": 2258, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2341, "s": 2317, "text": "The query is as follows" }, { "code": null, "e": 2384, "s": 2341, "text": "mysql> select *from UpdateWithHighestDemo;" }, { "code": null, "e": 2412, "s": 2384, "text": "The following is the output" }, { "code": null, "e": 2787, "s": 2412, "text": "+--------+------------+----------+\n| UserId | UserStatus | UserRank |\n+--------+------------+----------+\n| 1 | 1 | 78 |\n| 2 | 0 | 118 |\n| 3 | 1 | 223 |\n| 4 | 1 | 225 |\n| 5 | 0 | 227 |\n| 6 | 0 | 230 |\n+--------+------------+----------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2822, "s": 2787, "text": "Here is the query to update column" }, { "code": null, "e": 3002, "s": 2822, "text": "mysql> update UpdateWithHighestDemo\n-> set UserStatus=1 where UserRank=230 order by UserId DESC LIMIT 1;\nQuery OK, 1 row affected (0.19 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 3074, "s": 3002, "text": "Let us check and display records from the table using select statement." }, { "code": null, "e": 3098, "s": 3074, "text": "The query is as follows" }, { "code": null, "e": 3141, "s": 3098, "text": "mysql> select *from UpdateWithHighestDemo;" }, { "code": null, "e": 3169, "s": 3141, "text": "The following is the output" }, { "code": null, "e": 3544, "s": 3169, "text": "+--------+------------+----------+\n| UserId | UserStatus | UserRank |\n+--------+------------+----------+\n| 1 | 1 | 78 |\n| 2 | 0 | 118 |\n| 3 | 1 | 223 |\n| 4 | 1 | 225 |\n| 5 | 0 | 227 |\n| 6 | 1 | 230 |\n+--------+------------+----------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 3689, "s": 3544, "text": "Now if you want to update with highest id then ORDER BY clause is useful. In the above sample output the highest ‘UserId’=6 and UserStatus is 1." }, { "code": null, "e": 3720, "s": 3689, "text": "Let us update UserStatus to 0." }, { "code": null, "e": 3744, "s": 3720, "text": "The query is as follows" }, { "code": null, "e": 3908, "s": 3744, "text": "mysql> update UpdateWithHighestDemo\n -> set UserStatus=0 order by UserId DESC LIMIT 1;\nQuery OK, 1 row affected (0.18 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 3965, "s": 3908, "text": "Check the records from the table using select statement." }, { "code": null, "e": 3989, "s": 3965, "text": "The query is as follows" }, { "code": null, "e": 4407, "s": 3989, "text": "mysql> select *from UpdateWithHighestDemo;\n+--------+------------+----------+\n| UserId | UserStatus | UserRank |\n+--------+------------+----------+\n| 1 | 1 | 78 |\n| 2 | 0 | 118 |\n| 3 | 1 | 223 |\n| 4 | 1 | 225 |\n| 5 | 0 | 227 |\n| 6 | 0 | 230 |\n+--------+------------+----------+\n6 rows in set (0.00 sec)" } ]
Lucene - Quick Guide
Lucene is a simple yet powerful Java-based Search library. It can be used in any application to add search capability to it. Lucene is an open-source project. It is scalable. This high-performance library is used to index and search virtually any kind of text. Lucene library provides the core operations which are required by any search application. Indexing and Searching. A Search application performs all or a few of the following operations − Acquire Raw Content The first step of any search application is to collect the target contents on which search application is to be conducted. Build the document The next step is to build the document(s) from the raw content, which the search application can understand and interpret easily. Analyze the document Before the indexing process starts, the document is to be analyzed as to which part of the text is a candidate to be indexed. This process is where the document is analyzed. Indexing the document Once documents are built and analyzed, the next step is to index them so that this document can be retrieved based on certain keys instead of the entire content of the document. Indexing process is similar to indexes at the end of a book where common words are shown with their page numbers so that these words can be tracked quickly instead of searching the complete book. User Interface for Search Once a database of indexes is ready then the application can make any search. To facilitate a user to make a search, the application must provide a user a mean or a user interface where a user can enter text and start the search process. Build Query Once a user makes a request to search a text, the application should prepare a Query object using that text which can be used to inquire index database to get the relevant details. Search Query Using a query object, the index database is then checked to get the relevant details and the content documents. Render Results Once the result is received, the application should decide on how to show the results to the user using User Interface. How much information is to be shown at first look and so on. Apart from these basic operations, a search application can also provide administration user interface and help administrators of the application to control the level of search based on the user profiles. Analytics of search results is another important and advanced aspect of any search application. Lucene plays role in steps 2 to step 7 mentioned above and provides classes to do the required operations. In a nutshell, Lucene is the heart of any search application and provides vital operations pertaining to indexing and searching. Acquiring contents and displaying the results is left for the application part to handle. In the next chapter, we will perform a simple Search application using Lucene Search library. This tutorial will guide you on how to prepare a development environment to start your work with the Spring Framework. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you set up the Spring Framework − You can download the latest version of SDK from Oracle's Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files; follow the given instructions to install and configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to the directory that contains Java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the JDK in C:\jdk1.6.0_15, you would have to put the following line in your C:\autoexec.bat file. set PATH = C:\jdk1.6.0_15\bin;%PATH% set JAVA_HOME = C:\jdk1.6.0_15 Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you would put the following into your .cshrc file. setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.6.0_15 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given in the document of the IDE. All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe %C:\eclipse\eclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, it should display the following result − If the startup is successful, then you can proceed to set up your Lucene framework. Following are the simple steps to download and install the framework on your machine. https://archive.apache.org/dist/lucene/java/3.6.2/ Make a choice whether you want to install Lucene on Windows, or Unix and then proceed to the next step to download the .zip file for windows and .tz file for Unix. Make a choice whether you want to install Lucene on Windows, or Unix and then proceed to the next step to download the .zip file for windows and .tz file for Unix. Download the suitable version of Lucene framework binaries from https://archive.apache.org/dist/lucene/java/. Download the suitable version of Lucene framework binaries from https://archive.apache.org/dist/lucene/java/. At the time of writing this tutorial, I downloaded lucene-3.6.2.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside C:\lucene-3.6.2 as follows. At the time of writing this tutorial, I downloaded lucene-3.6.2.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside C:\lucene-3.6.2 as follows. You will find all the Lucene libraries in the directory C:\lucene-3.6.2. Make sure you set your CLASSPATH variable on this directory properly otherwise, you will face problem while running your application. If you are using Eclipse, then it is not required to set CLASSPATH because all the setting will be done through Eclipse. Once you are done with this last step, you are ready to proceed for your first Lucene Example which you will see in the next chapter. In this chapter, we will learn the actual programming with Lucene Framework. Before you start writing your first example using Lucene framework, you have to make sure that you have set up your Lucene environment properly as explained in Lucene - Environment Setup tutorial. It is recommended you have the working knowledge of Eclipse IDE. Let us now proceed by writing a simple Search Application which will print the number of search results found. We'll also see the list of indexes created during this process. The first step is to create a simple Java Project using Eclipse IDE. Follow the option File > New -> Project and finally select Java Project wizard from the wizard list. Now name your project as LuceneFirstApplication using the wizard window as follows − Once your project is created successfully, you will have following content in your Project Explorer − Let us now add Lucene core Framework library in our project. To do this, right click on your project name LuceneFirstApplication and then follow the following option available in context menu: Build Path -> Configure Build Path to display the Java Build Path window as follows − Now use Add External JARs button available under Libraries tab to add the following core JAR from the Lucene installation directory − lucene-core-3.6.2 Let us now create actual source files under the LuceneFirstApplication project. First we need to create a package called com.tutorialspoint.lucene. To do this, right-click on src in package explorer section and follow the option : New -> Package. Next we will create LuceneTester.java and other java classes under the com.tutorialspoint.lucene package. This class is used to provide various constants to be used across the sample application. package com.tutorialspoint.lucene; public class LuceneConstants { public static final String CONTENTS = "contents"; public static final String FILE_NAME = "filename"; public static final String FILE_PATH = "filepath"; public static final int MAX_SEARCH = 10; } This class is used as a .txt file filter. package com.tutorialspoint.lucene; import java.io.File; import java.io.FileFilter; public class TextFileFilter implements FileFilter { @Override public boolean accept(File pathname) { return pathname.getName().toLowerCase().endsWith(".txt"); } } This class is used to index the raw data so that we can make it searchable using the Lucene library. package com.tutorialspoint.lucene; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Indexer { private IndexWriter writer; public Indexer(String indexDirectoryPath) throws IOException { //this directory will contain the indexes Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); //create the indexer writer = new IndexWriter(indexDirectory, new StandardAnalyzer(Version.LUCENE_36),true, IndexWriter.MaxFieldLength.UNLIMITED); } public void close() throws CorruptIndexException, IOException { writer.close(); } private Document getDocument(File file) throws IOException { Document document = new Document(); //index file contents Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file)); //index file name Field fileNameField = new Field(LuceneConstants.FILE_NAME, file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED); //index file path Field filePathField = new Field(LuceneConstants.FILE_PATH, file.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED); document.add(contentField); document.add(fileNameField); document.add(filePathField); return document; } private void indexFile(File file) throws IOException { System.out.println("Indexing "+file.getCanonicalPath()); Document document = getDocument(file); writer.addDocument(document); } public int createIndex(String dataDirPath, FileFilter filter) throws IOException { //get all files in the data directory File[] files = new File(dataDirPath).listFiles(); for (File file : files) { if(!file.isDirectory() && !file.isHidden() && file.exists() && file.canRead() && filter.accept(file) ){ indexFile(file); } } return writer.numDocs(); } } This class is used to search the indexes created by the Indexer to search the requested content. package com.tutorialspoint.lucene; import java.io.File; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Searcher { IndexSearcher indexSearcher; QueryParser queryParser; Query query; public Searcher(String indexDirectoryPath) throws IOException { Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); indexSearcher = new IndexSearcher(indexDirectory); queryParser = new QueryParser(Version.LUCENE_36, LuceneConstants.CONTENTS, new StandardAnalyzer(Version.LUCENE_36)); } public TopDocs search( String searchQuery) throws IOException, ParseException { query = queryParser.parse(searchQuery); return indexSearcher.search(query, LuceneConstants.MAX_SEARCH); } public Document getDocument(ScoreDoc scoreDoc) throws CorruptIndexException, IOException { return indexSearcher.doc(scoreDoc.doc); } public void close() throws IOException { indexSearcher.close(); } } This class is used to test the indexing and search capability of lucene library. package com.tutorialspoint.lucene; import java.io.IOException; import org.apache.lucene.document.Document; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; public class LuceneTester { String indexDir = "E:\\Lucene\\Index"; String dataDir = "E:\\Lucene\\Data"; Indexer indexer; Searcher searcher; public static void main(String[] args) { LuceneTester tester; try { tester = new LuceneTester(); tester.createIndex(); tester.search("Mohan"); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } private void createIndex() throws IOException { indexer = new Indexer(indexDir); int numIndexed; long startTime = System.currentTimeMillis(); numIndexed = indexer.createIndex(dataDir, new TextFileFilter()); long endTime = System.currentTimeMillis(); indexer.close(); System.out.println(numIndexed+" File indexed, time taken: " +(endTime-startTime)+" ms"); } private void search(String searchQuery) throws IOException, ParseException { searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); TopDocs hits = searcher.search(searchQuery); long endTime = System.currentTimeMillis(); System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime)); for(ScoreDoc scoreDoc : hits.scoreDocs) { Document doc = searcher.getDocument(scoreDoc); System.out.println("File: " + doc.get(LuceneConstants.FILE_PATH)); } searcher.close(); } } We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\Lucene\Data. Test Data. An index directory path should be created as E:\Lucene\Index. After running this program, you can see the list of index files created in that folder. Once you are done with the creation of the source, the raw data, the data directory and the index directory, you are ready for compiling and running of your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If the application runs successfully, it will print the following message in Eclipse IDE's console − Indexing E:\Lucene\Data\record1.txt Indexing E:\Lucene\Data\record10.txt Indexing E:\Lucene\Data\record2.txt Indexing E:\Lucene\Data\record3.txt Indexing E:\Lucene\Data\record4.txt Indexing E:\Lucene\Data\record5.txt Indexing E:\Lucene\Data\record6.txt Indexing E:\Lucene\Data\record7.txt Indexing E:\Lucene\Data\record8.txt Indexing E:\Lucene\Data\record9.txt 10 File indexed, time taken: 109 ms 1 documents found. Time :0 File: E:\Lucene\Data\record4.txt Once you've run the program successfully, you will have the following content in your index directory − Indexing process is one of the core functionalities provided by Lucene. The following diagram illustrates the indexing process and the use of classes. IndexWriter is the most important and the core component of the indexing process. We add Document(s) containing Field(s) to IndexWriter which analyzes the Document(s) using the Analyzer and then creates/open/edit indexes as required and store/update them in a Directory. IndexWriter is used to update or create indexes. It is not used to read indexes. Following is a list of commonly-used classes during the indexing process. This class acts as a core component which creates/updates indexes during the indexing process. This class represents the storage location of the indexes. This class is responsible to analyze a document and get the tokens/words from the text which is to be indexed. Without analysis done, IndexWriter cannot create index. This class represents a virtual document with Fields where the Field is an object which can contain the physical document's contents, its meta data and so on. The Analyzer can understand a Document only. This is the lowest unit or the starting point of the indexing process. It represents the key value pair relationship where a key is used to identify the value to be indexed. Let us assume a field used to represent contents of a document will have key as "contents" and the value may contain the part or all of the text or numeric content of the document. Lucene can index only text or numeric content only. The process of Searching is again one of the core functionalities provided by Lucene. Its flow is similar to that of the indexing process. Basic search of Lucene can be made using the following classes which can also be termed as foundation classes for all search related operations. Following is a list of commonly-used classes during searching process. This class act as a core component which reads/searches indexes created after the indexing process. It takes directory instance pointing to the location containing the indexes. This class is the lowest unit of searching. It is similar to Field in indexing process. Query is an abstract class and contains various utility methods and is the parent of all types of queries that Lucene uses during search process. TermQuery is the most commonly-used query object and is the foundation of many complex queries that Lucene can make use of. TopDocs points to the top N search results which matches the search criteria. It is a simple container of pointers to point to documents which are the output of a search result. Indexing process is one of the core functionality provided by Lucene. Following diagram illustrates the indexing process and use of classes. IndexWriter is the most important and core component of the indexing process. We add Document(s) containing Field(s) to IndexWriter which analyzes the Document(s) using the Analyzer and then creates/open/edit indexes as required and store/update them in a Directory. IndexWriter is used to update or create indexes. It is not used to read indexes. Now we'll show you a step by step process to get a kick start in understanding of indexing process using a basic example. Create a method to get a lucene document from a text file. Create a method to get a lucene document from a text file. Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed. Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed. Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations. Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations. Add the newly created fields to the document object and return it to the caller method. Add the newly created fields to the document object and return it to the caller method. private Document getDocument(File file) throws IOException { Document document = new Document(); //index file contents Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file)); //index file name Field fileNameField = new Field(LuceneConstants.FILE_NAME, file.getName(), Field.Store.YES,Field.Index.NOT_ANALYZED); //index file path Field filePathField = new Field(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Field.Store.YES,Field.Index.NOT_ANALYZED); document.add(contentField); document.add(fileNameField); document.add(filePathField); return document; } IndexWriter class acts as a core component which creates/updates indexes during indexing process. Follow these steps to create a IndexWriter − Step 1 − Create object of IndexWriter. Step 2 − Create a Lucene directory which should point to location where indexes are to be stored. Step 3 − Initialize the IndexWriter object created with the index directory, a standard analyzer having version information and other required/optional parameters. private IndexWriter writer; public Indexer(String indexDirectoryPath) throws IOException { //this directory will contain the indexes Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); //create the indexer writer = new IndexWriter(indexDirectory, new StandardAnalyzer(Version.LUCENE_36),true, IndexWriter.MaxFieldLength.UNLIMITED); } The following program shows how to start an indexing process − private void indexFile(File file) throws IOException { System.out.println("Indexing "+file.getCanonicalPath()); Document document = getDocument(file); writer.addDocument(document); } To test the indexing process, we need to create a Lucene application test. Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in Lucene - First Application chapter as such for this chapter to understand the indexing process. Create LuceneConstants.java,TextFileFilter.java and Indexer.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged. Create LuceneTester.java as mentioned below. Clean and build the application to make sure the business logic is working as per the requirements. This class is used to provide various constants to be used across the sample application. package com.tutorialspoint.lucene; public class LuceneConstants { public static final String CONTENTS = "contents"; public static final String FILE_NAME = "filename"; public static final String FILE_PATH = "filepath"; public static final int MAX_SEARCH = 10; } This class is used as a .txt file filter. package com.tutorialspoint.lucene; import java.io.File; import java.io.FileFilter; public class TextFileFilter implements FileFilter { @Override public boolean accept(File pathname) { return pathname.getName().toLowerCase().endsWith(".txt"); } } This class is used to index the raw data so that we can make it searchable using the Lucene library. package com.tutorialspoint.lucene; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Indexer { private IndexWriter writer; public Indexer(String indexDirectoryPath) throws IOException { //this directory will contain the indexes Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); //create the indexer writer = new IndexWriter(indexDirectory, new StandardAnalyzer(Version.LUCENE_36),true, IndexWriter.MaxFieldLength.UNLIMITED); } public void close() throws CorruptIndexException, IOException { writer.close(); } private Document getDocument(File file) throws IOException { Document document = new Document(); //index file contents Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file)); //index file name Field fileNameField = new Field(LuceneConstants.FILE_NAME, file.getName(), Field.Store.YES,Field.Index.NOT_ANALYZED); //index file path Field filePathField = new Field(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Field.Store.YES,Field.Index.NOT_ANALYZED); document.add(contentField); document.add(fileNameField); document.add(filePathField); return document; } private void indexFile(File file) throws IOException { System.out.println("Indexing "+file.getCanonicalPath()); Document document = getDocument(file); writer.addDocument(document); } public int createIndex(String dataDirPath, FileFilter filter) throws IOException { //get all files in the data directory File[] files = new File(dataDirPath).listFiles(); for (File file : files) { if(!file.isDirectory() && !file.isHidden() && file.exists() && file.canRead() && filter.accept(file) ){ indexFile(file); } } return writer.numDocs(); } } This class is used to test the indexing capability of the Lucene library. package com.tutorialspoint.lucene; import java.io.IOException; public class LuceneTester { String indexDir = "E:\\Lucene\\Index"; String dataDir = "E:\\Lucene\\Data"; Indexer indexer; public static void main(String[] args) { LuceneTester tester; try { tester = new LuceneTester(); tester.createIndex(); } catch (IOException e) { e.printStackTrace(); } } private void createIndex() throws IOException { indexer = new Indexer(indexDir); int numIndexed; long startTime = System.currentTimeMillis(); numIndexed = indexer.createIndex(dataDir, new TextFileFilter()); long endTime = System.currentTimeMillis(); indexer.close(); System.out.println(numIndexed+" File indexed, time taken: " +(endTime-startTime)+" ms"); } } We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\Lucene\Data. Test Data. An index directory path should be created as E:\Lucene\Index. After running this program, you can see the list of index files created in that folder. Once you are done with the creation of the source, the raw data, the data directory and the index directory, you can proceed by compiling and running your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console − Indexing E:\Lucene\Data\record1.txt Indexing E:\Lucene\Data\record10.txt Indexing E:\Lucene\Data\record2.txt Indexing E:\Lucene\Data\record3.txt Indexing E:\Lucene\Data\record4.txt Indexing E:\Lucene\Data\record5.txt Indexing E:\Lucene\Data\record6.txt Indexing E:\Lucene\Data\record7.txt Indexing E:\Lucene\Data\record8.txt Indexing E:\Lucene\Data\record9.txt 10 File indexed, time taken: 109 ms Once you've run the program successfully, you will have the following content in your index directory − In this chapter, we'll discuss the four major operations of indexing. These operations are useful at various times and are used throughout of a software search application. Following is a list of commonly-used operations during indexing process. This operation is used in the initial stage of the indexing process to create the indexes on the newly available content. This operation is used to update indexes to reflect the changes in the updated contents. It is similar to recreating the index. This operation is used to update indexes to exclude the documents which are not required to be indexed/searched. Field options specify a way or control the ways in which the contents of a field are to be made searchable. The process of searching is one of the core functionalities provided by Lucene. Following diagram illustrates the process and its use. IndexSearcher is one of the core components of the searching process. We first create Directory(s) containing indexes and then pass it to IndexSearcher which opens the Directory using IndexReader. Then we create a Query with a Term and make a search using IndexSearcher by passing the Query to the searcher. IndexSearcher returns a TopDocs object which contains the search details along with document ID(s) of the Document which is the result of the search operation. We will now show you a step-wise approach and help you understand the indexing process using a basic example. QueryParser class parses the user entered input into Lucene understandable format query. Follow these steps to create a QueryParser − Step 1 − Create object of QueryParser. Step 2 − Initialize the QueryParser object created with a standard analyzer having version information and index name on which this query is to be run. QueryParser queryParser; public Searcher(String indexDirectoryPath) throws IOException { queryParser = new QueryParser(Version.LUCENE_36, LuceneConstants.CONTENTS, new StandardAnalyzer(Version.LUCENE_36)); } IndexSearcher class acts as a core component which searcher indexes created during indexing process. Follow these steps to create a IndexSearcher − Step 1 − Create object of IndexSearcher. Step 2 − Create a Lucene directory which should point to location where indexes are to be stored. Step 3 − Initialize the IndexSearcher object created with the index directory. IndexSearcher indexSearcher; public Searcher(String indexDirectoryPath) throws IOException { Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); indexSearcher = new IndexSearcher(indexDirectory); } Follow these steps to make search − Step 1 − Create a Query object by parsing the search expression through QueryParser. Step 2 − Make search by calling the IndexSearcher.search() method. Query query; public TopDocs search( String searchQuery) throws IOException, ParseException { query = queryParser.parse(searchQuery); return indexSearcher.search(query, LuceneConstants.MAX_SEARCH); } The following program shows how to get the document. public Document getDocument(ScoreDoc scoreDoc) throws CorruptIndexException, IOException { return indexSearcher.doc(scoreDoc.doc); } The following program shows how to close the IndexSearcher. public void close() throws IOException { indexSearcher.close(); } Let us create a test Lucene application to test searching process. Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in Lucene - First Application chapter as such for this chapter to understand the searching process. Create LuceneConstants.java,TextFileFilter.java and Searcher.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged. Create LuceneTester.java as mentioned below. Clean and Build the application to make sure business logic is working as per the requirements. This class is used to provide various constants to be used across the sample application. package com.tutorialspoint.lucene; public class LuceneConstants { public static final String CONTENTS = "contents"; public static final String FILE_NAME = "filename"; public static final String FILE_PATH = "filepath"; public static final int MAX_SEARCH = 10; } This class is used as a .txt file filter. package com.tutorialspoint.lucene; import java.io.File; import java.io.FileFilter; public class TextFileFilter implements FileFilter { @Override public boolean accept(File pathname) { return pathname.getName().toLowerCase().endsWith(".txt"); } } This class is used to read the indexes made on raw data and searches data using the Lucene library. package com.tutorialspoint.lucene; import java.io.File; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Searcher { IndexSearcher indexSearcher; QueryParser queryParser; Query query; public Searcher(String indexDirectoryPath) throws IOException { Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); indexSearcher = new IndexSearcher(indexDirectory); queryParser = new QueryParser(Version.LUCENE_36, LuceneConstants.CONTENTS, new StandardAnalyzer(Version.LUCENE_36)); } public TopDocs search( String searchQuery) throws IOException, ParseException { query = queryParser.parse(searchQuery); return indexSearcher.search(query, LuceneConstants.MAX_SEARCH); } public Document getDocument(ScoreDoc scoreDoc) throws CorruptIndexException, IOException { return indexSearcher.doc(scoreDoc.doc); } public void close() throws IOException { indexSearcher.close(); } } This class is used to test the searching capability of the Lucene library. package com.tutorialspoint.lucene; import java.io.IOException; import org.apache.lucene.document.Document; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; public class LuceneTester { String indexDir = "E:\\Lucene\\Index"; String dataDir = "E:\\Lucene\\Data"; Searcher searcher; public static void main(String[] args) { LuceneTester tester; try { tester = new LuceneTester(); tester.search("Mohan"); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } private void search(String searchQuery) throws IOException, ParseException { searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); TopDocs hits = searcher.search(searchQuery); long endTime = System.currentTimeMillis(); System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime) +" ms"); for(ScoreDoc scoreDoc : hits.scoreDocs) { Document doc = searcher.getDocument(scoreDoc); System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH)); } searcher.close(); } } We have used 10 text files named record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\Lucene\Data. Test Data. An index directory path should be created as E:\Lucene\Index. After running the indexing program in the chapter Lucene - Indexing Process, you can see the list of index files created in that folder. Once you are done with the creation of the source, the raw data, the data directory, the index directory and the indexes, you can proceed by compiling and running your program. To do this, keep LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTesterapplication. If your application runs successfully, it will print the following message in Eclipse IDE's console − 1 documents found. Time :29 ms File: E:\Lucene\Data\record4.txt We have seen in previous chapter Lucene - Search Operation, Lucene uses IndexSearcher to make searches and it uses the Query object created by QueryParser as the input. In this chapter, we are going to discuss various types of Query objects and the different ways to create them programmatically. Creating different types of Query object gives control on the kind of search to be made. Consider a case of Advanced Search, provided by many applications where users are given multiple options to confine the search results. By Query programming, we can achieve the same very easily. Following is the list of Query types that we'll discuss in due course. This class acts as a core component which creates/updates indexes during the indexing process. TermRangeQuery is used when a range of textual terms are to be searched. PrefixQuery is used to match documents whose index starts with a specified string. BooleanQuery is used to search documents which are result of multiple queries using AND, OR or NOT operators. Phrase query is used to search documents which contain a particular sequence of terms. WildcardQuery is used to search documents using wildcards like '*' for any character sequence,? matching a single character. FuzzyQuery is used to search documents using fuzzy implementation that is an approximate search based on the edit distance algorithm. MatchAllDocsQuery as the name suggests matches all the documents. In one of our previous chapters, we have seen that Lucene uses IndexWriter to analyze the Document(s) using the Analyzer and then creates/open/edit indexes as required. In this chapter, we are going to discuss the various types of Analyzer objects and other relevant objects which are used during the analysis process. Understanding the Analysis process and how analyzers work will give you great insight over how Lucene indexes the documents. Following is the list of objects that we'll discuss in due course. Token represents text or word in a document with relevant details like its metadata (position, start offset, end offset, token type and its position increment). TokenStream is an output of the analysis process and it comprises of a series of tokens. It is an abstract class. This is an abstract base class for each and every type of Analyzer. This analyzer splits the text in a document based on whitespace. This analyzer splits the text in a document based on non-letter characters and puts the text in lowercase. This analyzer works just as the SimpleAnalyzer and removes the common words like 'a', 'an', 'the', etc. This is the most sophisticated analyzer and is capable of handling names, email addresses, etc. It lowercases each token and removes common words and punctuations, if any. In this chapter, we will look into the sorting orders in which Lucene gives the search results by default or can be manipulated as required. This is the default sorting mode used by Lucene. Lucene provides results by the most relevant hit at the top. private void sortUsingRelevance(String searchQuery) throws IOException, ParseException { searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); //create a term to search file name Term term = new Term(LuceneConstants.FILE_NAME, searchQuery); //create the term query object Query query = new FuzzyQuery(term); searcher.setDefaultFieldSortScoring(true, false); //do the search TopDocs hits = searcher.search(query,Sort.RELEVANCE); long endTime = System.currentTimeMillis(); System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime) + "ms"); for(ScoreDoc scoreDoc : hits.scoreDocs) { Document doc = searcher.getDocument(scoreDoc); System.out.print("Score: "+ scoreDoc.score + " "); System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH)); } searcher.close(); } This sorting mode is used by Lucene. Here, the first document indexed is shown first in the search results. private void sortUsingIndex(String searchQuery) throws IOException, ParseException { searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); //create a term to search file name Term term = new Term(LuceneConstants.FILE_NAME, searchQuery); //create the term query object Query query = new FuzzyQuery(term); searcher.setDefaultFieldSortScoring(true, false); //do the search TopDocs hits = searcher.search(query,Sort.INDEXORDER); long endTime = System.currentTimeMillis(); System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime) + "ms"); for(ScoreDoc scoreDoc : hits.scoreDocs) { Document doc = searcher.getDocument(scoreDoc); System.out.print("Score: "+ scoreDoc.score + " "); System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH)); } searcher.close(); } Let us create a test Lucene application to test the sorting process. Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in Lucene - First Application chapter as such for this chapter to understand the searching process. Create LuceneConstants.java and Searcher.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged. Create LuceneTester.java as mentioned below. Clean and Build the application to make sure the business logic is working as per the requirements. This class is used to provide various constants to be used across the sample application. package com.tutorialspoint.lucene; public class LuceneConstants { public static final String CONTENTS = "contents"; public static final String FILE_NAME = "filename"; public static final String FILE_PATH = "filepath"; public static final int MAX_SEARCH = 10; } This class is used to read the indexes made on raw data and searches data using the Lucene library. package com.tutorialspoint.lucene; import java.io.File; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class Searcher { IndexSearcher indexSearcher; QueryParser queryParser; Query query; public Searcher(String indexDirectoryPath) throws IOException { Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); indexSearcher = new IndexSearcher(indexDirectory); queryParser = new QueryParser(Version.LUCENE_36, LuceneConstants.CONTENTS, new StandardAnalyzer(Version.LUCENE_36)); } public TopDocs search( String searchQuery) throws IOException, ParseException { query = queryParser.parse(searchQuery); return indexSearcher.search(query, LuceneConstants.MAX_SEARCH); } public TopDocs search(Query query) throws IOException, ParseException { return indexSearcher.search(query, LuceneConstants.MAX_SEARCH); } public TopDocs search(Query query,Sort sort) throws IOException, ParseException { return indexSearcher.search(query, LuceneConstants.MAX_SEARCH,sort); } public void setDefaultFieldSortScoring(boolean doTrackScores, boolean doMaxScores) { indexSearcher.setDefaultFieldSortScoring( doTrackScores,doMaxScores); } public Document getDocument(ScoreDoc scoreDoc) throws CorruptIndexException, IOException { return indexSearcher.doc(scoreDoc.doc); } public void close() throws IOException { indexSearcher.close(); } } This class is used to test the searching capability of the Lucene library. package com.tutorialspoint.lucene; import java.io.IOException; import org.apache.lucene.document.Document; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.search.FuzzyQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TopDocs; public class LuceneTester { String indexDir = "E:\\Lucene\\Index"; String dataDir = "E:\\Lucene\\Data"; Indexer indexer; Searcher searcher; public static void main(String[] args) { LuceneTester tester; try { tester = new LuceneTester(); tester.sortUsingRelevance("cord3.txt"); tester.sortUsingIndex("cord3.txt"); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } private void sortUsingRelevance(String searchQuery) throws IOException, ParseException { searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); //create a term to search file name Term term = new Term(LuceneConstants.FILE_NAME, searchQuery); //create the term query object Query query = new FuzzyQuery(term); searcher.setDefaultFieldSortScoring(true, false); //do the search TopDocs hits = searcher.search(query,Sort.RELEVANCE); long endTime = System.currentTimeMillis(); System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime) + "ms"); for(ScoreDoc scoreDoc : hits.scoreDocs) { Document doc = searcher.getDocument(scoreDoc); System.out.print("Score: "+ scoreDoc.score + " "); System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH)); } searcher.close(); } private void sortUsingIndex(String searchQuery) throws IOException, ParseException { searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); //create a term to search file name Term term = new Term(LuceneConstants.FILE_NAME, searchQuery); //create the term query object Query query = new FuzzyQuery(term); searcher.setDefaultFieldSortScoring(true, false); //do the search TopDocs hits = searcher.search(query,Sort.INDEXORDER); long endTime = System.currentTimeMillis(); System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime) + "ms"); for(ScoreDoc scoreDoc : hits.scoreDocs) { Document doc = searcher.getDocument(scoreDoc); System.out.print("Score: "+ scoreDoc.score + " "); System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH)); } searcher.close(); } } We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\Lucene\Data. Test Data. An index directory path should be created as E:\Lucene\Index. After running the indexing program in the chapter Lucene - Indexing Process, you can see the list of index files created in that folder. Once you are done with the creation of the source, the raw data, the data directory, the index directory and the indexes, you can compile and run your program. To do this, Keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console − 10 documents found. Time :31ms Score: 1.3179655 File: E:\Lucene\Data\record3.txt Score: 0.790779 File: E:\Lucene\Data\record1.txt Score: 0.790779 File: E:\Lucene\Data\record2.txt Score: 0.790779 File: E:\Lucene\Data\record4.txt Score: 0.790779 File: E:\Lucene\Data\record5.txt Score: 0.790779 File: E:\Lucene\Data\record6.txt Score: 0.790779 File: E:\Lucene\Data\record7.txt Score: 0.790779 File: E:\Lucene\Data\record8.txt Score: 0.790779 File: E:\Lucene\Data\record9.txt Score: 0.2635932 File: E:\Lucene\Data\record10.txt 10 documents found. Time :0ms Score: 0.790779 File: E:\Lucene\Data\record1.txt Score: 0.2635932 File: E:\Lucene\Data\record10.txt Score: 0.790779 File: E:\Lucene\Data\record2.txt Score: 1.3179655 File: E:\Lucene\Data\record3.txt Score: 0.790779 File: E:\Lucene\Data\record4.txt Score: 0.790779 File: E:\Lucene\Data\record5.txt Score: 0.790779 File: E:\Lucene\Data\record6.txt Score: 0.790779 File: E:\Lucene\Data\record7.txt Score: 0.790779 File: E:\Lucene\Data\record8.txt Score: 0.790779 File: E:\Lucene\Data\record9.txt Print Add Notes Bookmark this page
[ { "code": null, "e": 2218, "s": 1843, "text": "Lucene is a simple yet powerful Java-based Search library. It can be used in any application to add search capability to it. Lucene is an open-source project. It is scalable. This high-performance library is used to index and search virtually any kind of text. Lucene library provides the core operations which are required by any search application. Indexing and Searching." }, { "code": null, "e": 2291, "s": 2218, "text": "A Search application performs all or a few of the following operations −" }, { "code": null, "e": 2311, "s": 2291, "text": "Acquire Raw Content" }, { "code": null, "e": 2434, "s": 2311, "text": "The first step of any search application is to collect the target contents on which search application is to be conducted." }, { "code": null, "e": 2453, "s": 2434, "text": "Build the document" }, { "code": null, "e": 2583, "s": 2453, "text": "The next step is to build the document(s) from the raw content, which the search application can understand and interpret easily." }, { "code": null, "e": 2604, "s": 2583, "text": "Analyze the document" }, { "code": null, "e": 2778, "s": 2604, "text": "Before the indexing process starts, the document is to be analyzed as to which part of the text is a candidate to be indexed. This process is where the document is analyzed." }, { "code": null, "e": 2800, "s": 2778, "text": "Indexing the document" }, { "code": null, "e": 3174, "s": 2800, "text": "Once documents are built and analyzed, the next step is to index them so that this document can be retrieved based on certain keys instead of the entire content of the document. Indexing process is similar to indexes at the end of a book where common words are shown with their page numbers so that these words can be tracked quickly instead of searching the complete book." }, { "code": null, "e": 3200, "s": 3174, "text": "User Interface for Search" }, { "code": null, "e": 3438, "s": 3200, "text": "Once a database of indexes is ready then the application can make any search. To facilitate a user to make a search, the application must provide a user a mean or a user interface where a user can enter text and start the search process." }, { "code": null, "e": 3450, "s": 3438, "text": "Build Query" }, { "code": null, "e": 3631, "s": 3450, "text": "Once a user makes a request to search a text, the application should prepare a Query object using that text which can be used to inquire index database to get the relevant details." }, { "code": null, "e": 3644, "s": 3631, "text": "Search Query" }, { "code": null, "e": 3756, "s": 3644, "text": "Using a query object, the index database is then checked to get the relevant details and the content documents." }, { "code": null, "e": 3771, "s": 3756, "text": "Render Results" }, { "code": null, "e": 3952, "s": 3771, "text": "Once the result is received, the application should decide on how to show the results to the user using User Interface. How much information is to be shown at first look and so on." }, { "code": null, "e": 4253, "s": 3952, "text": "Apart from these basic operations, a search application can also provide administration user interface and help administrators of the application to control the level of search based on the user profiles. Analytics of search results is another important and advanced aspect of any search application." }, { "code": null, "e": 4579, "s": 4253, "text": "Lucene plays role in steps 2 to step 7 mentioned above and provides classes to do the required operations. In a nutshell, Lucene is the heart of any search application and provides vital operations pertaining to indexing and searching. Acquiring contents and displaying the results is left for the application part to handle." }, { "code": null, "e": 4673, "s": 4579, "text": "In the next chapter, we will perform a simple Search application using Lucene Search library." }, { "code": null, "e": 4920, "s": 4673, "text": "This tutorial will guide you on how to prepare a development environment to start your work with the Spring Framework. This tutorial will also teach you how to setup JDK, Tomcat and Eclipse on your machine before you set up the Spring Framework −" }, { "code": null, "e": 5319, "s": 4920, "text": "You can download the latest version of SDK from Oracle's Java site: Java SE Downloads. You will find instructions for installing JDK in downloaded files; follow the given instructions to install and configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to the directory that contains Java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 5458, "s": 5319, "text": "If you are running Windows and installed the JDK in C:\\jdk1.6.0_15, you would have to put the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 5527, "s": 5458, "text": "set PATH = C:\\jdk1.6.0_15\\bin;%PATH%\nset JAVA_HOME = C:\\jdk1.6.0_15\n" }, { "code": null, "e": 5733, "s": 5527, "text": "Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button." }, { "code": null, "e": 5891, "s": 5733, "text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 and you use the C shell, you would put the following into your .cshrc file." }, { "code": null, "e": 5977, "s": 5891, "text": "setenv PATH /usr/local/jdk1.6.0_15/bin:$PATH\nsetenv JAVA_HOME /usr/local/jdk1.6.0_15\n" }, { "code": null, "e": 6265, "s": 5977, "text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given in the document of the IDE." }, { "code": null, "e": 6428, "s": 6265, "text": "All the examples in this tutorial have been written using Eclipse IDE. So I would suggest you should have the latest version of Eclipse installed on your machine." }, { "code": null, "e": 6747, "s": 6428, "text": "To install Eclipse IDE, download the latest Eclipse binaries from https://www.eclipse.org/downloads/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example, in C:\\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately." }, { "code": null, "e": 6872, "s": 6747, "text": "Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe" }, { "code": null, "e": 6898, "s": 6872, "text": " %C:\\eclipse\\eclipse.exe\n" }, { "code": null, "e": 6998, "s": 6898, "text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −" }, { "code": null, "e": 7027, "s": 6998, "text": "$/usr/local/eclipse/eclipse\n" }, { "code": null, "e": 7096, "s": 7027, "text": "After a successful startup, it should display the following result −" }, { "code": null, "e": 7266, "s": 7096, "text": "If the startup is successful, then you can proceed to set up your Lucene framework. Following are the simple steps to download and install the framework on your machine." }, { "code": null, "e": 7317, "s": 7266, "text": "https://archive.apache.org/dist/lucene/java/3.6.2/" }, { "code": null, "e": 7481, "s": 7317, "text": "Make a choice whether you want to install Lucene on Windows, or Unix and then proceed to the next step to download the .zip file for windows and .tz file for Unix." }, { "code": null, "e": 7645, "s": 7481, "text": "Make a choice whether you want to install Lucene on Windows, or Unix and then proceed to the next step to download the .zip file for windows and .tz file for Unix." }, { "code": null, "e": 7755, "s": 7645, "text": "Download the suitable version of Lucene framework binaries from https://archive.apache.org/dist/lucene/java/." }, { "code": null, "e": 7865, "s": 7755, "text": "Download the suitable version of Lucene framework binaries from https://archive.apache.org/dist/lucene/java/." }, { "code": null, "e": 8070, "s": 7865, "text": "At the time of writing this tutorial, I downloaded lucene-3.6.2.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside C:\\lucene-3.6.2 as follows." }, { "code": null, "e": 8275, "s": 8070, "text": "At the time of writing this tutorial, I downloaded lucene-3.6.2.zip on my Windows machine and when you unzip the downloaded file it will give you the directory structure inside C:\\lucene-3.6.2 as follows." }, { "code": null, "e": 8603, "s": 8275, "text": "You will find all the Lucene libraries in the directory C:\\lucene-3.6.2. Make sure you set your CLASSPATH variable on this directory properly otherwise, you will face problem while running your application. If you are using Eclipse, then it is not required to set CLASSPATH because all the setting will be done through Eclipse." }, { "code": null, "e": 8737, "s": 8603, "text": "Once you are done with this last step, you are ready to proceed for your first Lucene Example which you will see in the next chapter." }, { "code": null, "e": 9076, "s": 8737, "text": "In this chapter, we will learn the actual programming with Lucene Framework. Before you start writing your first example using Lucene framework, you have to make sure that you have set up your Lucene environment properly as explained in Lucene - Environment Setup tutorial. It is recommended you have the working knowledge of Eclipse IDE." }, { "code": null, "e": 9251, "s": 9076, "text": "Let us now proceed by writing a simple Search Application which will print the number of search results found. We'll also see the list of indexes created during this process." }, { "code": null, "e": 9506, "s": 9251, "text": "The first step is to create a simple Java Project using Eclipse IDE. Follow the option File > New -> Project and finally select Java Project wizard from the wizard list. Now name your project as LuceneFirstApplication using the wizard window as follows −" }, { "code": null, "e": 9608, "s": 9506, "text": "Once your project is created successfully, you will have following content in your Project Explorer −" }, { "code": null, "e": 9887, "s": 9608, "text": "Let us now add Lucene core Framework library in our project. To do this, right click on your project name LuceneFirstApplication and then follow the following option available in context menu: Build Path -> Configure Build Path to display the Java Build Path window as follows −" }, { "code": null, "e": 10021, "s": 9887, "text": "Now use Add External JARs button available under Libraries tab to add the following core JAR from the Lucene installation directory −" }, { "code": null, "e": 10039, "s": 10021, "text": "lucene-core-3.6.2" }, { "code": null, "e": 10286, "s": 10039, "text": "Let us now create actual source files under the LuceneFirstApplication project. First we need to create a package called com.tutorialspoint.lucene. To do this, right-click on src in package explorer section and follow the option : New -> Package." }, { "code": null, "e": 10392, "s": 10286, "text": "Next we will create LuceneTester.java and other java classes under the com.tutorialspoint.lucene package." }, { "code": null, "e": 10482, "s": 10392, "text": "This class is used to provide various constants to be used across the sample application." }, { "code": null, "e": 10756, "s": 10482, "text": "package com.tutorialspoint.lucene;\n\npublic class LuceneConstants {\n public static final String CONTENTS = \"contents\";\n public static final String FILE_NAME = \"filename\";\n public static final String FILE_PATH = \"filepath\";\n public static final int MAX_SEARCH = 10;\n}" }, { "code": null, "e": 10798, "s": 10756, "text": "This class is used as a .txt file filter." }, { "code": null, "e": 11062, "s": 10798, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\n\npublic class TextFileFilter implements FileFilter {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().toLowerCase().endsWith(\".txt\");\n }\n}" }, { "code": null, "e": 11163, "s": 11062, "text": "This class is used to index the raw data so that we can make it searchable using the Lucene library." }, { "code": null, "e": 13585, "s": 11163, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\nimport java.io.FileReader;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Indexer {\n\n private IndexWriter writer;\n\n public Indexer(String indexDirectoryPath) throws IOException {\n //this directory will contain the indexes\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n\n //create the indexer\n writer = new IndexWriter(indexDirectory, \n new StandardAnalyzer(Version.LUCENE_36),true, \n IndexWriter.MaxFieldLength.UNLIMITED);\n }\n\n public void close() throws CorruptIndexException, IOException {\n writer.close();\n }\n\n private Document getDocument(File file) throws IOException {\n Document document = new Document();\n\n //index file contents\n Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file));\n //index file name\n Field fileNameField = new Field(LuceneConstants.FILE_NAME,\n file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED);\n //index file path\n Field filePathField = new Field(LuceneConstants.FILE_PATH,\n file.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED);\n\n document.add(contentField);\n document.add(fileNameField);\n document.add(filePathField);\n\n return document;\n } \n\n private void indexFile(File file) throws IOException {\n System.out.println(\"Indexing \"+file.getCanonicalPath());\n Document document = getDocument(file);\n writer.addDocument(document);\n }\n\n public int createIndex(String dataDirPath, FileFilter filter) \n throws IOException {\n //get all files in the data directory\n File[] files = new File(dataDirPath).listFiles();\n\n for (File file : files) {\n if(!file.isDirectory()\n && !file.isHidden()\n && file.exists()\n && file.canRead()\n && filter.accept(file)\n ){\n indexFile(file);\n }\n }\n return writer.numDocs();\n }\n}" }, { "code": null, "e": 13682, "s": 13585, "text": "This class is used to search the indexes created by the Indexer to search the requested content." }, { "code": null, "e": 15249, "s": 13682, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.queryParser.ParseException;\nimport org.apache.lucene.queryParser.QueryParser;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.TopDocs;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Searcher {\n\t\n IndexSearcher indexSearcher;\n QueryParser queryParser;\n Query query;\n \n public Searcher(String indexDirectoryPath) \n throws IOException {\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n indexSearcher = new IndexSearcher(indexDirectory);\n queryParser = new QueryParser(Version.LUCENE_36,\n LuceneConstants.CONTENTS,\n new StandardAnalyzer(Version.LUCENE_36));\n }\n \n public TopDocs search( String searchQuery) \n throws IOException, ParseException {\n query = queryParser.parse(searchQuery);\n return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);\n }\n\n public Document getDocument(ScoreDoc scoreDoc) \n throws CorruptIndexException, IOException {\n return indexSearcher.doc(scoreDoc.doc);\t\n }\n\n public void close() throws IOException {\n indexSearcher.close();\n }\n}" }, { "code": null, "e": 15330, "s": 15249, "text": "This class is used to test the indexing and search capability of lucene library." }, { "code": null, "e": 17090, "s": 15330, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.IOException;\n\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.queryParser.ParseException;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.TopDocs;\n\npublic class LuceneTester {\n\t\n String indexDir = \"E:\\\\Lucene\\\\Index\";\n String dataDir = \"E:\\\\Lucene\\\\Data\";\n Indexer indexer;\n Searcher searcher;\n\n public static void main(String[] args) {\n LuceneTester tester;\n try {\n tester = new LuceneTester();\n tester.createIndex();\n tester.search(\"Mohan\");\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n\n private void createIndex() throws IOException {\n indexer = new Indexer(indexDir);\n int numIndexed;\n long startTime = System.currentTimeMillis();\t\n numIndexed = indexer.createIndex(dataDir, new TextFileFilter());\n long endTime = System.currentTimeMillis();\n indexer.close();\n System.out.println(numIndexed+\" File indexed, time taken: \"\n +(endTime-startTime)+\" ms\");\t\t\n }\n\n private void search(String searchQuery) throws IOException, ParseException {\n searcher = new Searcher(indexDir);\n long startTime = System.currentTimeMillis();\n TopDocs hits = searcher.search(searchQuery);\n long endTime = System.currentTimeMillis();\n \n System.out.println(hits.totalHits +\n \" documents found. Time :\" + (endTime - startTime));\n for(ScoreDoc scoreDoc : hits.scoreDocs) {\n Document doc = searcher.getDocument(scoreDoc);\n System.out.println(\"File: \"\n + doc.get(LuceneConstants.FILE_PATH));\n }\n searcher.close();\n }\n}" }, { "code": null, "e": 17408, "s": 17090, "text": "We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\\Lucene\\Data. Test Data. An index directory path should be created as E:\\Lucene\\Index. After running this program, you can see the list of index files created in that folder." }, { "code": null, "e": 17857, "s": 17408, "text": "Once you are done with the creation of the source, the raw data, the data directory and the index directory, you are ready for compiling and running of your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If the application runs successfully, it will print the following message in Eclipse IDE's console −" }, { "code": null, "e": 18315, "s": 17857, "text": "Indexing E:\\Lucene\\Data\\record1.txt\nIndexing E:\\Lucene\\Data\\record10.txt\nIndexing E:\\Lucene\\Data\\record2.txt\nIndexing E:\\Lucene\\Data\\record3.txt\nIndexing E:\\Lucene\\Data\\record4.txt\nIndexing E:\\Lucene\\Data\\record5.txt\nIndexing E:\\Lucene\\Data\\record6.txt\nIndexing E:\\Lucene\\Data\\record7.txt\nIndexing E:\\Lucene\\Data\\record8.txt\nIndexing E:\\Lucene\\Data\\record9.txt\n10 File indexed, time taken: 109 ms\n1 documents found. Time :0\nFile: E:\\Lucene\\Data\\record4.txt\n" }, { "code": null, "e": 18419, "s": 18315, "text": "Once you've run the program successfully, you will have the following content in your index directory −" }, { "code": null, "e": 18652, "s": 18419, "text": "Indexing process is one of the core functionalities provided by Lucene. The following diagram illustrates the indexing process and the use of classes. IndexWriter is the most important and the core component of the indexing process." }, { "code": null, "e": 18922, "s": 18652, "text": "We add Document(s) containing Field(s) to IndexWriter which analyzes the Document(s) using the Analyzer and then creates/open/edit indexes as required and store/update them in a Directory. IndexWriter is used to update or create indexes. It is not used to read indexes." }, { "code": null, "e": 18996, "s": 18922, "text": "Following is a list of commonly-used classes during the indexing process." }, { "code": null, "e": 19091, "s": 18996, "text": "This class acts as a core component which creates/updates indexes during the indexing process." }, { "code": null, "e": 19150, "s": 19091, "text": "This class represents the storage location of the indexes." }, { "code": null, "e": 19317, "s": 19150, "text": "This class is responsible to analyze a document and get the tokens/words from the text which is to be indexed. Without analysis done, IndexWriter cannot create index." }, { "code": null, "e": 19521, "s": 19317, "text": "This class represents a virtual document with Fields where the Field is an object which can contain the physical document's contents, its meta data and so on. The Analyzer can understand a Document only." }, { "code": null, "e": 19928, "s": 19521, "text": "This is the lowest unit or the starting point of the indexing process. It represents the key value pair relationship where a key is used to identify the value to be indexed. Let us assume a field used to represent contents of a document will have key as \"contents\" and the value may contain the part or all of the text or numeric content of the document. Lucene can index only text or numeric content only." }, { "code": null, "e": 20212, "s": 19928, "text": "The process of Searching is again one of the core functionalities provided by Lucene. Its flow is similar to that of the indexing process. Basic search of Lucene can be made using the following classes which can also be termed as foundation classes for all search related operations." }, { "code": null, "e": 20283, "s": 20212, "text": "Following is a list of commonly-used classes during searching process." }, { "code": null, "e": 20460, "s": 20283, "text": "This class act as a core component which reads/searches indexes created after the indexing process. It takes directory instance pointing to the location containing the indexes." }, { "code": null, "e": 20548, "s": 20460, "text": "This class is the lowest unit of searching. It is similar to Field in indexing process." }, { "code": null, "e": 20694, "s": 20548, "text": "Query is an abstract class and contains various utility methods and is the parent of all types of queries that Lucene uses during search process." }, { "code": null, "e": 20818, "s": 20694, "text": "TermQuery is the most commonly-used query object and is the foundation of many complex queries that Lucene can make use of." }, { "code": null, "e": 20996, "s": 20818, "text": "TopDocs points to the top N search results which matches the search criteria. It is a simple container of pointers to point to documents which are the output of a search result." }, { "code": null, "e": 21215, "s": 20996, "text": "Indexing process is one of the core functionality provided by Lucene. Following diagram illustrates the indexing process and use of classes. IndexWriter is the most important and core component of the indexing process." }, { "code": null, "e": 21485, "s": 21215, "text": "We add Document(s) containing Field(s) to IndexWriter which analyzes the Document(s) using the Analyzer and then creates/open/edit indexes as required and store/update them in a Directory. IndexWriter is used to update or create indexes. It is not used to read indexes." }, { "code": null, "e": 21607, "s": 21485, "text": "Now we'll show you a step by step process to get a kick start in understanding of indexing process using a basic example." }, { "code": null, "e": 21666, "s": 21607, "text": "Create a method to get a lucene document from a text file." }, { "code": null, "e": 21725, "s": 21666, "text": "Create a method to get a lucene document from a text file." }, { "code": null, "e": 21845, "s": 21725, "text": "Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed." }, { "code": null, "e": 21965, "s": 21845, "text": "Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed." }, { "code": null, "e": 22141, "s": 21967, "text": "Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations." }, { "code": null, "e": 22315, "s": 22141, "text": "Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations." }, { "code": null, "e": 22405, "s": 22317, "text": "Add the newly created fields to the document object and return it to the caller method." }, { "code": null, "e": 22493, "s": 22405, "text": "Add the newly created fields to the document object and return it to the caller method." }, { "code": null, "e": 23159, "s": 22493, "text": "private Document getDocument(File file) throws IOException {\n Document document = new Document();\n \n //index file contents\n Field contentField = new Field(LuceneConstants.CONTENTS, \n new FileReader(file));\n \n //index file name\n Field fileNameField = new Field(LuceneConstants.FILE_NAME,\n file.getName(),\n Field.Store.YES,Field.Index.NOT_ANALYZED);\n \n //index file path\n Field filePathField = new Field(LuceneConstants.FILE_PATH,\n file.getCanonicalPath(),\n Field.Store.YES,Field.Index.NOT_ANALYZED);\n\n document.add(contentField);\n document.add(fileNameField);\n document.add(filePathField);\n\n return document;\n} " }, { "code": null, "e": 23302, "s": 23159, "text": "IndexWriter class acts as a core component which creates/updates indexes during indexing process. Follow these steps to create a IndexWriter −" }, { "code": null, "e": 23341, "s": 23302, "text": "Step 1 − Create object of IndexWriter." }, { "code": null, "e": 23439, "s": 23341, "text": "Step 2 − Create a Lucene directory which should point to location where indexes are to be stored." }, { "code": null, "e": 23603, "s": 23439, "text": "Step 3 − Initialize the IndexWriter object created with the index directory, a standard analyzer having version information and other required/optional parameters." }, { "code": null, "e": 23997, "s": 23603, "text": "private IndexWriter writer;\n\npublic Indexer(String indexDirectoryPath) throws IOException {\n //this directory will contain the indexes\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n \n //create the indexer\n writer = new IndexWriter(indexDirectory, \n new StandardAnalyzer(Version.LUCENE_36),true,\n IndexWriter.MaxFieldLength.UNLIMITED);\n}" }, { "code": null, "e": 24060, "s": 23997, "text": "The following program shows how to start an indexing process −" }, { "code": null, "e": 24252, "s": 24060, "text": "private void indexFile(File file) throws IOException {\n System.out.println(\"Indexing \"+file.getCanonicalPath());\n Document document = getDocument(file);\n writer.addDocument(document);\n}" }, { "code": null, "e": 24327, "s": 24252, "text": "To test the indexing process, we need to create a Lucene application test." }, { "code": null, "e": 24613, "s": 24327, "text": "Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in Lucene - First Application chapter as such for this chapter to understand the indexing process." }, { "code": null, "e": 24772, "s": 24613, "text": "Create LuceneConstants.java,TextFileFilter.java and Indexer.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged." }, { "code": null, "e": 24817, "s": 24772, "text": "Create LuceneTester.java as mentioned below." }, { "code": null, "e": 24917, "s": 24817, "text": "Clean and build the application to make sure the business logic is working as per the requirements." }, { "code": null, "e": 25007, "s": 24917, "text": "This class is used to provide various constants to be used across the sample application." }, { "code": null, "e": 25281, "s": 25007, "text": "package com.tutorialspoint.lucene;\n\npublic class LuceneConstants {\n public static final String CONTENTS = \"contents\";\n public static final String FILE_NAME = \"filename\";\n public static final String FILE_PATH = \"filepath\";\n public static final int MAX_SEARCH = 10;\n}" }, { "code": null, "e": 25323, "s": 25281, "text": "This class is used as a .txt file filter." }, { "code": null, "e": 25587, "s": 25323, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\n\npublic class TextFileFilter implements FileFilter {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().toLowerCase().endsWith(\".txt\");\n }\n}" }, { "code": null, "e": 25688, "s": 25587, "text": "This class is used to index the raw data so that we can make it searchable using the Lucene library." }, { "code": null, "e": 28153, "s": 25688, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\nimport java.io.FileReader;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Indexer {\n\n private IndexWriter writer;\n\n public Indexer(String indexDirectoryPath) throws IOException {\n //this directory will contain the indexes\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n\n //create the indexer\n writer = new IndexWriter(indexDirectory, \n new StandardAnalyzer(Version.LUCENE_36),true,\n IndexWriter.MaxFieldLength.UNLIMITED);\n }\n\n public void close() throws CorruptIndexException, IOException {\n writer.close();\n }\n\n private Document getDocument(File file) throws IOException {\n Document document = new Document();\n\n //index file contents\n Field contentField = new Field(LuceneConstants.CONTENTS, \n new FileReader(file));\n \n //index file name\n Field fileNameField = new Field(LuceneConstants.FILE_NAME,\n file.getName(),\n Field.Store.YES,Field.Index.NOT_ANALYZED);\n \n //index file path\n Field filePathField = new Field(LuceneConstants.FILE_PATH,\n file.getCanonicalPath(),\n Field.Store.YES,Field.Index.NOT_ANALYZED);\n\n document.add(contentField);\n document.add(fileNameField);\n document.add(filePathField);\n\n return document;\n } \n\n private void indexFile(File file) throws IOException {\n System.out.println(\"Indexing \"+file.getCanonicalPath());\n Document document = getDocument(file);\n writer.addDocument(document);\n }\n\n public int createIndex(String dataDirPath, FileFilter filter) \n throws IOException {\n //get all files in the data directory\n File[] files = new File(dataDirPath).listFiles();\n\n for (File file : files) {\n if(!file.isDirectory()\n && !file.isHidden()\n && file.exists()\n && file.canRead()\n && filter.accept(file)\n ){\n indexFile(file);\n }\n }\n return writer.numDocs();\n }\n}" }, { "code": null, "e": 28227, "s": 28153, "text": "This class is used to test the indexing capability of the Lucene library." }, { "code": null, "e": 29077, "s": 28227, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.IOException;\n\npublic class LuceneTester {\n\t\n String indexDir = \"E:\\\\Lucene\\\\Index\";\n String dataDir = \"E:\\\\Lucene\\\\Data\";\n Indexer indexer;\n \n public static void main(String[] args) {\n LuceneTester tester;\n try {\n tester = new LuceneTester();\n tester.createIndex();\n } catch (IOException e) {\n e.printStackTrace();\n } \n }\n\n private void createIndex() throws IOException {\n indexer = new Indexer(indexDir);\n int numIndexed;\n long startTime = System.currentTimeMillis();\t\n numIndexed = indexer.createIndex(dataDir, new TextFileFilter());\n long endTime = System.currentTimeMillis();\n indexer.close();\n System.out.println(numIndexed+\" File indexed, time taken: \"\n +(endTime-startTime)+\" ms\");\t\t\n }\n}" }, { "code": null, "e": 29395, "s": 29077, "text": "We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\\Lucene\\Data. Test Data. An index directory path should be created as E:\\Lucene\\Index. After running this program, you can see the list of index files created in that folder." }, { "code": null, "e": 29843, "s": 29395, "text": "Once you are done with the creation of the source, the raw data, the data directory and the index directory, you can proceed by compiling and running your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console −" }, { "code": null, "e": 30241, "s": 29843, "text": "Indexing E:\\Lucene\\Data\\record1.txt\nIndexing E:\\Lucene\\Data\\record10.txt\nIndexing E:\\Lucene\\Data\\record2.txt\nIndexing E:\\Lucene\\Data\\record3.txt\nIndexing E:\\Lucene\\Data\\record4.txt\nIndexing E:\\Lucene\\Data\\record5.txt\nIndexing E:\\Lucene\\Data\\record6.txt\nIndexing E:\\Lucene\\Data\\record7.txt\nIndexing E:\\Lucene\\Data\\record8.txt\nIndexing E:\\Lucene\\Data\\record9.txt\n10 File indexed, time taken: 109 ms\n" }, { "code": null, "e": 30345, "s": 30241, "text": "Once you've run the program successfully, you will have the following content in your index directory −" }, { "code": null, "e": 30518, "s": 30345, "text": "In this chapter, we'll discuss the four major operations of indexing. These operations are useful at various times and are used throughout of a software search application." }, { "code": null, "e": 30591, "s": 30518, "text": "Following is a list of commonly-used operations during indexing process." }, { "code": null, "e": 30713, "s": 30591, "text": "This operation is used in the initial stage of the indexing process to create the indexes on the newly available content." }, { "code": null, "e": 30841, "s": 30713, "text": "This operation is used to update indexes to reflect the changes in the updated contents. It is similar to recreating the index." }, { "code": null, "e": 30954, "s": 30841, "text": "This operation is used to update indexes to exclude the documents which are not required to be indexed/searched." }, { "code": null, "e": 31062, "s": 30954, "text": "Field options specify a way or control the ways in which the contents of a field are to be made searchable." }, { "code": null, "e": 31267, "s": 31062, "text": "The process of searching is one of the core functionalities provided by Lucene. Following diagram illustrates the process and its use. IndexSearcher is one of the core components of the searching process." }, { "code": null, "e": 31665, "s": 31267, "text": "We first create Directory(s) containing indexes and then pass it to IndexSearcher which opens the Directory using IndexReader. Then we create a Query with a Term and make a search using IndexSearcher by passing the Query to the searcher. IndexSearcher returns a TopDocs object which contains the search details along with document ID(s) of the Document which is the result of the search operation." }, { "code": null, "e": 31775, "s": 31665, "text": "We will now show you a step-wise approach and help you understand the indexing process using a basic example." }, { "code": null, "e": 31909, "s": 31775, "text": "QueryParser class parses the user entered input into Lucene understandable format query. Follow these steps to create a QueryParser −" }, { "code": null, "e": 31948, "s": 31909, "text": "Step 1 − Create object of QueryParser." }, { "code": null, "e": 32100, "s": 31948, "text": "Step 2 − Initialize the QueryParser object created with a standard analyzer having version information and index name on which this query is to be run." }, { "code": null, "e": 32325, "s": 32100, "text": "QueryParser queryParser;\n\npublic Searcher(String indexDirectoryPath) throws IOException {\n\n queryParser = new QueryParser(Version.LUCENE_36,\n LuceneConstants.CONTENTS,\n new StandardAnalyzer(Version.LUCENE_36));\n}" }, { "code": null, "e": 32473, "s": 32325, "text": "IndexSearcher class acts as a core component which searcher indexes created during indexing process. Follow these steps to create a IndexSearcher −" }, { "code": null, "e": 32514, "s": 32473, "text": "Step 1 − Create object of IndexSearcher." }, { "code": null, "e": 32612, "s": 32514, "text": "Step 2 − Create a Lucene directory which should point to location where indexes are to be stored." }, { "code": null, "e": 32691, "s": 32612, "text": "Step 3 − Initialize the IndexSearcher object created with the index directory." }, { "code": null, "e": 32926, "s": 32691, "text": "IndexSearcher indexSearcher;\n\npublic Searcher(String indexDirectoryPath) throws IOException {\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n indexSearcher = new IndexSearcher(indexDirectory);\n}" }, { "code": null, "e": 32962, "s": 32926, "text": "Follow these steps to make search −" }, { "code": null, "e": 33047, "s": 32962, "text": "Step 1 − Create a Query object by parsing the search expression through QueryParser." }, { "code": null, "e": 33114, "s": 33047, "text": "Step 2 − Make search by calling the IndexSearcher.search() method." }, { "code": null, "e": 33320, "s": 33114, "text": "Query query;\n\npublic TopDocs search( String searchQuery) throws IOException, ParseException {\n query = queryParser.parse(searchQuery);\n return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);\n}" }, { "code": null, "e": 33373, "s": 33320, "text": "The following program shows how to get the document." }, { "code": null, "e": 33514, "s": 33373, "text": "public Document getDocument(ScoreDoc scoreDoc) \n throws CorruptIndexException, IOException {\n return indexSearcher.doc(scoreDoc.doc);\t\n}" }, { "code": null, "e": 33574, "s": 33514, "text": "The following program shows how to close the IndexSearcher." }, { "code": null, "e": 33643, "s": 33574, "text": "public void close() throws IOException {\n indexSearcher.close();\n}" }, { "code": null, "e": 33710, "s": 33643, "text": "Let us create a test Lucene application to test searching process." }, { "code": null, "e": 33997, "s": 33710, "text": "Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in Lucene - First Application chapter as such for this chapter to understand the searching process." }, { "code": null, "e": 34157, "s": 33997, "text": "Create LuceneConstants.java,TextFileFilter.java and Searcher.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged." }, { "code": null, "e": 34202, "s": 34157, "text": "Create LuceneTester.java as mentioned below." }, { "code": null, "e": 34298, "s": 34202, "text": "Clean and Build the application to make sure business logic is working as per the requirements." }, { "code": null, "e": 34388, "s": 34298, "text": "This class is used to provide various constants to be used across the sample application." }, { "code": null, "e": 34662, "s": 34388, "text": "package com.tutorialspoint.lucene;\n\npublic class LuceneConstants {\n public static final String CONTENTS = \"contents\";\n public static final String FILE_NAME = \"filename\";\n public static final String FILE_PATH = \"filepath\";\n public static final int MAX_SEARCH = 10;\n}" }, { "code": null, "e": 34704, "s": 34662, "text": "This class is used as a .txt file filter." }, { "code": null, "e": 34968, "s": 34704, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.FileFilter;\n\npublic class TextFileFilter implements FileFilter {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().toLowerCase().endsWith(\".txt\");\n }\n}" }, { "code": null, "e": 35068, "s": 34968, "text": "This class is used to read the indexes made on raw data and searches data using the Lucene library." }, { "code": null, "e": 36622, "s": 35068, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.queryParser.ParseException;\nimport org.apache.lucene.queryParser.QueryParser;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.TopDocs;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Searcher {\n\t\n IndexSearcher indexSearcher;\n QueryParser queryParser;\n Query query;\n\n public Searcher(String indexDirectoryPath) throws IOException {\n Directory indexDirectory = \n FSDirectory.open(new File(indexDirectoryPath));\n indexSearcher = new IndexSearcher(indexDirectory);\n queryParser = new QueryParser(Version.LUCENE_36,\n LuceneConstants.CONTENTS,\n new StandardAnalyzer(Version.LUCENE_36));\n }\n\n public TopDocs search( String searchQuery) \n throws IOException, ParseException {\n query = queryParser.parse(searchQuery);\n return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);\n }\n\n public Document getDocument(ScoreDoc scoreDoc) \n throws CorruptIndexException, IOException {\n return indexSearcher.doc(scoreDoc.doc);\t\n }\n\n public void close() throws IOException {\n indexSearcher.close();\n }\n}" }, { "code": null, "e": 36697, "s": 36622, "text": "This class is used to test the searching capability of the Lucene library." }, { "code": null, "e": 37976, "s": 36697, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.IOException;\n\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.queryParser.ParseException;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.TopDocs;\n\npublic class LuceneTester {\n\t\n String indexDir = \"E:\\\\Lucene\\\\Index\";\n String dataDir = \"E:\\\\Lucene\\\\Data\";\n Searcher searcher;\n\n public static void main(String[] args) {\n LuceneTester tester;\n try {\n tester = new LuceneTester();\n tester.search(\"Mohan\");\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n\n private void search(String searchQuery) throws IOException, ParseException {\n searcher = new Searcher(indexDir);\n long startTime = System.currentTimeMillis();\n TopDocs hits = searcher.search(searchQuery);\n long endTime = System.currentTimeMillis();\n\n System.out.println(hits.totalHits +\n \" documents found. Time :\" + (endTime - startTime) +\" ms\");\n for(ScoreDoc scoreDoc : hits.scoreDocs) {\n Document doc = searcher.getDocument(scoreDoc);\n System.out.println(\"File: \"+ doc.get(LuceneConstants.FILE_PATH));\n }\n searcher.close();\n }\t\n}" }, { "code": null, "e": 38345, "s": 37976, "text": "We have used 10 text files named record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\\Lucene\\Data. Test Data. An index directory path should be created as E:\\Lucene\\Index. After running the indexing program in the chapter Lucene - Indexing Process, you can see the list of index files created in that folder." }, { "code": null, "e": 38801, "s": 38345, "text": "Once you are done with the creation of the source, the raw data, the data directory, the index directory and the indexes, you can proceed by compiling and running your program. To do this, keep LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTesterapplication. If your application runs successfully, it will print the following message in Eclipse IDE's console −" }, { "code": null, "e": 38866, "s": 38801, "text": "1 documents found. Time :29 ms\nFile: E:\\Lucene\\Data\\record4.txt\n" }, { "code": null, "e": 39252, "s": 38866, "text": "We have seen in previous chapter Lucene - Search Operation, Lucene uses IndexSearcher to make searches and it uses the Query object created by QueryParser as the input. In this chapter, we are going to discuss various types of Query objects and the different ways to create them programmatically. Creating different types of Query object gives control on the kind of search to be made." }, { "code": null, "e": 39447, "s": 39252, "text": "Consider a case of Advanced Search, provided by many applications where users are given multiple options to confine the search results. By Query programming, we can achieve the same very easily." }, { "code": null, "e": 39518, "s": 39447, "text": "Following is the list of Query types that we'll discuss in due course." }, { "code": null, "e": 39613, "s": 39518, "text": "This class acts as a core component which creates/updates indexes during the indexing process." }, { "code": null, "e": 39686, "s": 39613, "text": "TermRangeQuery is used when a range of textual terms are to be searched." }, { "code": null, "e": 39769, "s": 39686, "text": "PrefixQuery is used to match documents whose index starts with a specified string." }, { "code": null, "e": 39879, "s": 39769, "text": "BooleanQuery is used to search documents which are result of multiple queries using AND, OR or NOT operators." }, { "code": null, "e": 39966, "s": 39879, "text": "Phrase query is used to search documents which contain a particular sequence of terms." }, { "code": null, "e": 40091, "s": 39966, "text": "WildcardQuery is used to search documents using wildcards like '*' for any character sequence,? matching a single character." }, { "code": null, "e": 40225, "s": 40091, "text": "FuzzyQuery is used to search documents using fuzzy implementation that is an approximate search based on the edit distance algorithm." }, { "code": null, "e": 40291, "s": 40225, "text": "MatchAllDocsQuery as the name suggests matches all the documents." }, { "code": null, "e": 40735, "s": 40291, "text": "In one of our previous chapters, we have seen that Lucene uses IndexWriter to analyze the Document(s) using the Analyzer and then creates/open/edit indexes as required. In this chapter, we are going to discuss the various types of Analyzer objects and other relevant objects which are used during the analysis process. Understanding the Analysis process and how analyzers work will give you great insight over how Lucene indexes the documents." }, { "code": null, "e": 40802, "s": 40735, "text": "Following is the list of objects that we'll discuss in due course." }, { "code": null, "e": 40963, "s": 40802, "text": "Token represents text or word in a document with relevant details like its metadata (position, start offset, end offset, token type and its position increment)." }, { "code": null, "e": 41077, "s": 40963, "text": "TokenStream is an output of the analysis process and it comprises of a series of tokens. It is an abstract class." }, { "code": null, "e": 41145, "s": 41077, "text": "This is an abstract base class for each and every type of Analyzer." }, { "code": null, "e": 41210, "s": 41145, "text": "This analyzer splits the text in a document based on whitespace." }, { "code": null, "e": 41317, "s": 41210, "text": "This analyzer splits the text in a document based on non-letter characters and puts the text in lowercase." }, { "code": null, "e": 41421, "s": 41317, "text": "This analyzer works just as the SimpleAnalyzer and removes the common words like 'a', 'an', 'the', etc." }, { "code": null, "e": 41593, "s": 41421, "text": "This is the most sophisticated analyzer and is capable of handling names, email addresses, etc. It lowercases each token and removes common words and punctuations, if any." }, { "code": null, "e": 41734, "s": 41593, "text": "In this chapter, we will look into the sorting orders in which Lucene gives the search results by default or can be manipulated as required." }, { "code": null, "e": 41844, "s": 41734, "text": "This is the default sorting mode used by Lucene. Lucene provides results by the most relevant hit at the top." }, { "code": null, "e": 42739, "s": 41844, "text": "private void sortUsingRelevance(String searchQuery)\n throws IOException, ParseException {\n searcher = new Searcher(indexDir);\n long startTime = System.currentTimeMillis();\n \n //create a term to search file name\n Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);\n //create the term query object\n Query query = new FuzzyQuery(term);\n searcher.setDefaultFieldSortScoring(true, false);\n //do the search\n TopDocs hits = searcher.search(query,Sort.RELEVANCE);\n long endTime = System.currentTimeMillis();\n\n System.out.println(hits.totalHits +\n \" documents found. Time :\" + (endTime - startTime) + \"ms\");\n for(ScoreDoc scoreDoc : hits.scoreDocs) {\n Document doc = searcher.getDocument(scoreDoc);\n System.out.print(\"Score: \"+ scoreDoc.score + \" \");\n System.out.println(\"File: \"+ doc.get(LuceneConstants.FILE_PATH));\n }\n searcher.close();\n}" }, { "code": null, "e": 42847, "s": 42739, "text": "This sorting mode is used by Lucene. Here, the first document indexed is shown first in the search results." }, { "code": null, "e": 43739, "s": 42847, "text": "private void sortUsingIndex(String searchQuery)\n throws IOException, ParseException {\n searcher = new Searcher(indexDir);\n long startTime = System.currentTimeMillis();\n \n //create a term to search file name\n Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);\n //create the term query object\n Query query = new FuzzyQuery(term);\n searcher.setDefaultFieldSortScoring(true, false);\n //do the search\n TopDocs hits = searcher.search(query,Sort.INDEXORDER);\n long endTime = System.currentTimeMillis();\n\n System.out.println(hits.totalHits +\n \" documents found. Time :\" + (endTime - startTime) + \"ms\");\n for(ScoreDoc scoreDoc : hits.scoreDocs) {\n Document doc = searcher.getDocument(scoreDoc);\n System.out.print(\"Score: \"+ scoreDoc.score + \" \");\n System.out.println(\"File: \"+ doc.get(LuceneConstants.FILE_PATH));\n }\n searcher.close();\n}" }, { "code": null, "e": 43808, "s": 43739, "text": "Let us create a test Lucene application to test the sorting process." }, { "code": null, "e": 44095, "s": 43808, "text": "Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.lucene as explained in the Lucene - First Application chapter. You can also use the project created in Lucene - First Application chapter as such for this chapter to understand the searching process." }, { "code": null, "e": 44235, "s": 44095, "text": "Create LuceneConstants.java and Searcher.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged." }, { "code": null, "e": 44280, "s": 44235, "text": "Create LuceneTester.java as mentioned below." }, { "code": null, "e": 44380, "s": 44280, "text": "Clean and Build the application to make sure the business logic is working as per the requirements." }, { "code": null, "e": 44470, "s": 44380, "text": "This class is used to provide various constants to be used across the sample application." }, { "code": null, "e": 44744, "s": 44470, "text": "package com.tutorialspoint.lucene;\n\npublic class LuceneConstants {\n public static final String CONTENTS = \"contents\";\n public static final String FILE_NAME = \"filename\";\n public static final String FILE_PATH = \"filepath\";\n public static final int MAX_SEARCH = 10;\n}" }, { "code": null, "e": 44844, "s": 44744, "text": "This class is used to read the indexes made on raw data and searches data using the Lucene library." }, { "code": null, "e": 46960, "s": 44844, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.index.CorruptIndexException;\nimport org.apache.lucene.queryParser.ParseException;\nimport org.apache.lucene.queryParser.QueryParser;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.Sort;\nimport org.apache.lucene.search.TopDocs;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.util.Version;\n\npublic class Searcher {\n\t\nIndexSearcher indexSearcher;\n QueryParser queryParser;\n Query query;\n\n public Searcher(String indexDirectoryPath) throws IOException {\n Directory indexDirectory \n = FSDirectory.open(new File(indexDirectoryPath));\n indexSearcher = new IndexSearcher(indexDirectory);\n queryParser = new QueryParser(Version.LUCENE_36,\n LuceneConstants.CONTENTS,\n new StandardAnalyzer(Version.LUCENE_36));\n }\n\n public TopDocs search( String searchQuery) \n throws IOException, ParseException {\n query = queryParser.parse(searchQuery);\n return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);\n }\n\n public TopDocs search(Query query) \n throws IOException, ParseException {\n return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);\n }\n\n public TopDocs search(Query query,Sort sort) \n throws IOException, ParseException {\n return indexSearcher.search(query, \n LuceneConstants.MAX_SEARCH,sort);\n }\n\n public void setDefaultFieldSortScoring(boolean doTrackScores, \n boolean doMaxScores) {\n indexSearcher.setDefaultFieldSortScoring(\n doTrackScores,doMaxScores);\n }\n\n public Document getDocument(ScoreDoc scoreDoc) \n throws CorruptIndexException, IOException {\n return indexSearcher.doc(scoreDoc.doc);\t\n }\n\n public void close() throws IOException {\n indexSearcher.close();\n }\n}" }, { "code": null, "e": 47035, "s": 46960, "text": "This class is used to test the searching capability of the Lucene library." }, { "code": null, "e": 49869, "s": 47035, "text": "package com.tutorialspoint.lucene;\n\nimport java.io.IOException;\n\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.index.Term;\nimport org.apache.lucene.queryParser.ParseException;\nimport org.apache.lucene.search.FuzzyQuery;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.Sort;\nimport org.apache.lucene.search.TopDocs;\n\npublic class LuceneTester {\n\t\n String indexDir = \"E:\\\\Lucene\\\\Index\";\n String dataDir = \"E:\\\\Lucene\\\\Data\";\n Indexer indexer;\n Searcher searcher;\n\n public static void main(String[] args) {\n LuceneTester tester;\n try {\n tester = new LuceneTester();\n tester.sortUsingRelevance(\"cord3.txt\");\n tester.sortUsingIndex(\"cord3.txt\");\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\t\t\n }\n\n private void sortUsingRelevance(String searchQuery)\n throws IOException, ParseException {\n searcher = new Searcher(indexDir);\n long startTime = System.currentTimeMillis();\n \n //create a term to search file name\n Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);\n //create the term query object\n Query query = new FuzzyQuery(term);\n searcher.setDefaultFieldSortScoring(true, false);\n //do the search\n TopDocs hits = searcher.search(query,Sort.RELEVANCE);\n long endTime = System.currentTimeMillis();\n\n System.out.println(hits.totalHits +\n \" documents found. Time :\" + (endTime - startTime) + \"ms\");\n for(ScoreDoc scoreDoc : hits.scoreDocs) {\n Document doc = searcher.getDocument(scoreDoc);\n System.out.print(\"Score: \"+ scoreDoc.score + \" \");\n System.out.println(\"File: \"+ doc.get(LuceneConstants.FILE_PATH));\n }\n searcher.close();\n }\n\n private void sortUsingIndex(String searchQuery)\n throws IOException, ParseException {\n searcher = new Searcher(indexDir);\n long startTime = System.currentTimeMillis();\n //create a term to search file name\n Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);\n //create the term query object\n Query query = new FuzzyQuery(term);\n searcher.setDefaultFieldSortScoring(true, false);\n //do the search\n TopDocs hits = searcher.search(query,Sort.INDEXORDER);\n long endTime = System.currentTimeMillis();\n\n System.out.println(hits.totalHits +\n \" documents found. Time :\" + (endTime - startTime) + \"ms\");\n for(ScoreDoc scoreDoc : hits.scoreDocs) {\n Document doc = searcher.getDocument(scoreDoc);\n System.out.print(\"Score: \"+ scoreDoc.score + \" \");\n System.out.println(\"File: \"+ doc.get(LuceneConstants.FILE_PATH));\n }\n searcher.close();\n }\n}" }, { "code": null, "e": 50236, "s": 49869, "text": "We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:\\Lucene\\Data. Test Data. An index directory path should be created as E:\\Lucene\\Index. After running the indexing program in the chapter Lucene - Indexing Process, you can see the list of index files created in that folder." }, { "code": null, "e": 50680, "s": 50236, "text": "Once you are done with the creation of the source, the raw data, the data directory, the index directory and the indexes, you can compile and run your program. To do this, Keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console −" }, { "code": null, "e": 51728, "s": 50680, "text": "10 documents found. Time :31ms\nScore: 1.3179655 File: E:\\Lucene\\Data\\record3.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record1.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record2.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record4.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record5.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record6.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record7.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record8.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record9.txt\nScore: 0.2635932 File: E:\\Lucene\\Data\\record10.txt\n10 documents found. Time :0ms\nScore: 0.790779 File: E:\\Lucene\\Data\\record1.txt\nScore: 0.2635932 File: E:\\Lucene\\Data\\record10.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record2.txt\nScore: 1.3179655 File: E:\\Lucene\\Data\\record3.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record4.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record5.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record6.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record7.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record8.txt\nScore: 0.790779 File: E:\\Lucene\\Data\\record9.txt\n" }, { "code": null, "e": 51735, "s": 51728, "text": " Print" }, { "code": null, "e": 51746, "s": 51735, "text": " Add Notes" } ]
C++ Program to Reverse a Number
Reversing a number means storing its digits in reverse order. For example: If the number is 6529, then 9256 is displayed in the output. A program to reverse a number is given as follows − Live Demo #include <iostream> using namespace std; int main() { int num = 63972, rev = 0; while(num > 0) { rev = rev*10 + num%10; num = num/10; } cout<<"Reverse of number is "<<rev; return 0; } Reverse of number is 27936 In the above program, the number that needs to be reversed is 63972. It is stored in the variable num. The reversed number will be stored in the variable rev. The main logic of the program is in the while loop. The while loop will run till the number is greater than 0. For each iteration of the while loop, rev is multiplied with 10 and added to num modulus 10. Then this is stored in rev. Also num is divided by 10 in each loop iteration. This is demonstrated by the following code snippet. while(num > 0) { rev = rev*10 + num%10; num = num/10; } Eventually, rev stores the reverse number of that in num and the value of num is zero. After that rev is displayed. This can be seen in the following code snippet − cout<<"Reverse of number is "<<rev;
[ { "code": null, "e": 1124, "s": 1062, "text": "Reversing a number means storing its digits in reverse order." }, { "code": null, "e": 1198, "s": 1124, "text": "For example: If the number is 6529, then 9256 is displayed in the output." }, { "code": null, "e": 1250, "s": 1198, "text": "A program to reverse a number is given as follows −" }, { "code": null, "e": 1261, "s": 1250, "text": " Live Demo" }, { "code": null, "e": 1472, "s": 1261, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int num = 63972, rev = 0;\n while(num > 0) {\n rev = rev*10 + num%10;\n num = num/10;\n }\n cout<<\"Reverse of number is \"<<rev;\n return 0;\n}" }, { "code": null, "e": 1499, "s": 1472, "text": "Reverse of number is 27936" }, { "code": null, "e": 1769, "s": 1499, "text": "In the above program, the number that needs to be reversed is 63972. It is stored in the variable num. The reversed number will be stored in the variable rev. The main logic of the program is in the while loop. The while loop will run till the number is greater than 0." }, { "code": null, "e": 1940, "s": 1769, "text": "For each iteration of the while loop, rev is multiplied with 10 and added to num modulus 10. Then this is stored in rev. Also num is divided by 10 in each loop iteration." }, { "code": null, "e": 1992, "s": 1940, "text": "This is demonstrated by the following code snippet." }, { "code": null, "e": 2054, "s": 1992, "text": "while(num > 0) {\n rev = rev*10 + num%10;\n num = num/10;\n}" }, { "code": null, "e": 2170, "s": 2054, "text": "Eventually, rev stores the reverse number of that in num and the value of num is zero. After that rev is displayed." }, { "code": null, "e": 2219, "s": 2170, "text": "This can be seen in the following code snippet −" }, { "code": null, "e": 2255, "s": 2219, "text": "cout<<\"Reverse of number is \"<<rev;" } ]
Travelling Salesman Problem | Practice | GeeksforGeeks
Given a matrix cost of size n where cost[i][j] denotes the cost of moving from city i to city j. Your task is to complete a tour from the city 0 (0 based index) to all other cities such that you visit each city atmost once and then at the end come back to city 0 in min cost. Example 1: Input: cost = {{0,111},{112,0}} Output: 223 Explanation: We can visit 0->1->0 and cost = 111 + 112. Example 2: Input: cost = {{0,1000,5000},{5000,0,1000}, {1000,5000,0}} Output: 3000 Explanation: We can visit 0->1->2->0 and cost = 1000+1000+1000 = 3000 Your Task: You don't need to read or print anyhting. Your task is to complete the function total_cost() which takes cost as input parameter and returns the total cost to visit each city exactly once starting from city 0 and again comback to city 0. Expected Time Complexity: O(2n * n2) Expected Space Compelxity: O(2n * n) Constraints: 1 <= n <= 10 1 <= cost[i][j] <= 103 0 dattatraygujar772 weeks ago public int min=Integer.MAX_VALUE; public void solve(int cost[][], HashSet<Integer> set,int ans,int i) { if(ans>min) return ; if(set.size()==cost.length) { min=Math.min(min,ans+cost[i][0]); return; } for(int j=1;j<cost.length;j++) { if(!set.contains(j)) { set.add(j); ans+=cost[i][j]; solve(cost,set,ans,j); set.remove(j); ans=ans-cost[i][j]; } } } public int total_cost(int[][] cost) { HashSet<Integer> set=new HashSet<>(); set.add(0); int ans=0; solve(cost,set,ans,0); return min; } +1 avinashdhn19042 weeks ago // solution using dp with bitmasking int dp[1<<11][11]; class Solution { public: int tsp(int mask,int pos,vector<vector<int>>cost,int n){ if(mask==((1<<n)-1))return cost[pos][0]; if(dp[mask][pos]!=-1)return dp[mask][pos]; int ans=INT_MAX; for(int city=0;city<n;city++){ if(!(mask&(1<<city))){ int tmp=cost[pos][city]+tsp((mask|(1<<city)),city,cost,n); ans=min(ans,tmp); } } return dp[mask][pos]=ans; } int total_cost(vector<vector<int>>cost){ memset(dp,-1,sizeof(dp)); int n=cost.size(); return tsp(1,0,cost,n); } }; +1 rohitshinde1803011 month ago class Solution {public:int solve(vector<vector<int>>&cost, int i, int no_of_cities, vector<bool>& visited){ const int n = cost.size(); //when we reach all cities, then its time to return to the city from where we started if(no_of_cities==n) return cost[i][0]; int ans=INT_MAX; visited[i] = true; for(int j=0;j<n;j++){ if(!visited[j]){ visited[j] = true; ans = min(ans, cost[i][j] + solve(cost, j, no_of_cities+1, visited)); visited[j] = false; } } visited[i] = false; return ans;}int total_cost(vector<vector<int>>cost){ // Code here vector<bool> visited(cost.size(), false); //we are starting from city 0 //"i" represent current city in above solve() function return solve(cost, 0, 1, visited);}}; 0 anshul gupta 61 month ago public int solve(int[][] cost, int sum, List<Integer> list, int index) { if (list.size() == cost.length - 1) return sum + cost[list.get(list.size() - 1)][0]; int min = Integer.MAX_VALUE; for (int i = 1; i < cost.length; i++) { if (i != index && !list.contains(i)) { list.add(i); min = Math.min(min, solve(cost, sum + cost[index][i], list, i)); list.remove(list.size() - 1); } } return min; } public int total_cost(int[][] cost) { if(cost.length==1) return 0; return solve(cost, 0, new ArrayList<>(), 0); } +1 aloksinghbais022 months ago C++ solution using Hamiltonian Cycle using bit masking, backtracking is as follows :- Execution Time :- 0.2 / 3.4 sec int minCost; int vis; void dfs(int node,int cost,int val,vector<pair<int,int>> adj[],vector<vector<int>> &ct){ vis = vis | (1 << (node)); for(auto choice: adj[node]){ int n = choice.first; int c = choice.second; if((vis & (1<<n)) == 0){ dfs(n,cost+c,val,adj,ct); vis = vis ^ (1<<n); } else{ if(vis == val && n == 0){ minCost = min(minCost,cost + ct[node][n]); } } } } int total_cost(vector<vector<int>>cost){ int n = cost.size(); if(n == 1) return (0); vector<pair<int,int>> adj[n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(cost[i][j] != 0){ adj[i].push_back({j,cost[i][j]}); } } } vis = 0; minCost = INT_MAX; dfs(0,0,(1<<n)-1,adj,cost); return (minCost); } 0 guptaravi32173 months ago // JAVA Solution // HashSet , backtracking Solution int min = Integer.MAX_VALUE; public int total_cost(int[][] cost) { HashSet<Integer> set = new HashSet<>(); int n = cost.length - 1; for (int i = 1; i <= n; i++) { set.add(i); } for (int i = 1; i <= n; i++) { findMinimumCost(i, cost, cost[0][i], set); } return min == Integer.MAX_VALUE? 0 : min; } public void findMinimumCost(int i, int[][] matrix, int cost, HashSet<Integer> set) {// System.out.println(i + " " + set + " " + cost); if (set.size() == 1) { for (int val : set) { min = Math.min(min, matrix[i][0] + cost); }// System.out.println(min); return; } set.remove(i); HashSet<Integer> cloned_set = new HashSet<>(); cloned_set = (HashSet) set.clone(); for (int key : cloned_set) { findMinimumCost(key, matrix, cost + matrix[i][key], set); } set.add(i); } 0 utkarshrdce3 months ago DP with bitmask class Solution { public: int dp[11][1<<11]; int f(int i, int mask, vector<vector<int>> &cost) { if(mask == 0) return cost[i][0]; if(dp[i][mask] != -1) return dp[i][mask]; int curAns = INT_MAX; for(int j = 31; j >= 0; j--) { if((mask & (1 << j))) { curAns = min(curAns, cost[i][j] + f(j, mask ^ (1 << j), cost)); } } return dp[i][mask] = curAns; } int total_cost(vector<vector<int>>cost){ // Code here memset(dp, -1, sizeof(dp)); int n = cost.size(); int current_mask = (1 << n) - 1; current_mask = current_mask ^ (1 << 0); return f(0, current_mask, cost); } }; -3 kunal04033 months ago Any iterative dp+bitmask solution ? +1 imansaboori5 months ago class Solution { public: int solve(vector<vector<int>>&cost, int i, int depth, vector<bool>& visited) { const int n = cost.size(); if(depth==n) return cost[i][0]; int ans=INT_MAX; visited[i] = true; for(int j=0;j<n;j++) { if(!visited[j]) { visited[j] = true; ans = min(ans, cost[i][j] + solve(cost, j, depth+1, visited)); visited[j] = false; } } visited[i] = false; return ans; } int total_cost(vector<vector<int>>cost){ // Code here vector<bool> visited(cost.size(), false); return solve(cost, 0, 1, visited); } }; +2 amanshakya0076 months ago Dynamic Programming , Graph and BackTracking We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 504, "s": 226, "text": "Given a matrix cost of size n where cost[i][j] denotes the cost of moving from city i to city j. Your task is to complete a tour from the city 0 (0 based index) to all other cities such that you visit each city atmost once and then at the end come back to city 0 in min cost.\n " }, { "code": null, "e": 515, "s": 504, "text": "Example 1:" }, { "code": null, "e": 617, "s": 515, "text": "Input: cost = {{0,111},{112,0}}\nOutput: 223\nExplanation: We can visit 0->1->0 and \ncost = 111 + 112.\n" }, { "code": null, "e": 628, "s": 617, "text": "Example 2:" }, { "code": null, "e": 772, "s": 628, "text": "Input: cost = {{0,1000,5000},{5000,0,1000},\n{1000,5000,0}}\nOutput: 3000\nExplanation: We can visit 0->1->2->0 and cost \n= 1000+1000+1000 = 3000\n" }, { "code": null, "e": 1025, "s": 774, "text": "Your Task:\nYou don't need to read or print anyhting. Your task is to complete the function total_cost() which takes cost as input parameter and returns the total cost to visit each city exactly once starting from city 0 and again comback to city 0.\n " }, { "code": null, "e": 1101, "s": 1025, "text": "Expected Time Complexity: O(2n * n2)\nExpected Space Compelxity: O(2n * n)\n " }, { "code": null, "e": 1150, "s": 1101, "text": "Constraints:\n1 <= n <= 10\n1 <= cost[i][j] <= 103" }, { "code": null, "e": 1152, "s": 1150, "text": "0" }, { "code": null, "e": 1180, "s": 1152, "text": "dattatraygujar772 weeks ago" }, { "code": null, "e": 1924, "s": 1180, "text": "public int min=Integer.MAX_VALUE;\n public void solve(int cost[][], HashSet<Integer> set,int ans,int i)\n {\n if(ans>min) return ;\n if(set.size()==cost.length)\n {\n min=Math.min(min,ans+cost[i][0]);\n return;\n }\n for(int j=1;j<cost.length;j++)\n {\n if(!set.contains(j))\n {\n set.add(j);\n ans+=cost[i][j];\n solve(cost,set,ans,j);\n set.remove(j);\n ans=ans-cost[i][j];\n }\n }\n \n }\n public int total_cost(int[][] cost)\n {\n HashSet<Integer> set=new HashSet<>();\n set.add(0);\n int ans=0;\n solve(cost,set,ans,0);\n return min;\n }" }, { "code": null, "e": 1929, "s": 1926, "text": "+1" }, { "code": null, "e": 1955, "s": 1929, "text": "avinashdhn19042 weeks ago" }, { "code": null, "e": 2550, "s": 1955, "text": "// solution using dp with bitmasking\n\n\nint dp[1<<11][11];\nclass Solution {\npublic:\nint tsp(int mask,int pos,vector<vector<int>>cost,int n){\n if(mask==((1<<n)-1))return cost[pos][0];\n if(dp[mask][pos]!=-1)return dp[mask][pos];\n int ans=INT_MAX;\n for(int city=0;city<n;city++){\n if(!(mask&(1<<city))){\n int tmp=cost[pos][city]+tsp((mask|(1<<city)),city,cost,n);\n ans=min(ans,tmp);\n }\n }\n return dp[mask][pos]=ans;\n}\nint total_cost(vector<vector<int>>cost){\n memset(dp,-1,sizeof(dp));\n int n=cost.size();\n return tsp(1,0,cost,n);\n}\n};" }, { "code": null, "e": 2555, "s": 2552, "text": "+1" }, { "code": null, "e": 2584, "s": 2555, "text": "rohitshinde1803011 month ago" }, { "code": null, "e": 2857, "s": 2584, "text": "class Solution {public:int solve(vector<vector<int>>&cost, int i, int no_of_cities, vector<bool>& visited){ const int n = cost.size(); //when we reach all cities, then its time to return to the city from where we started if(no_of_cities==n) return cost[i][0];" }, { "code": null, "e": 3361, "s": 2857, "text": " int ans=INT_MAX; visited[i] = true; for(int j=0;j<n;j++){ if(!visited[j]){ visited[j] = true; ans = min(ans, cost[i][j] + solve(cost, j, no_of_cities+1, visited)); visited[j] = false; } } visited[i] = false; return ans;}int total_cost(vector<vector<int>>cost){ // Code here vector<bool> visited(cost.size(), false); //we are starting from city 0 //\"i\" represent current city in above solve() function return solve(cost, 0, 1, visited);}};" }, { "code": null, "e": 3363, "s": 3361, "text": "0" }, { "code": null, "e": 3389, "s": 3363, "text": "anshul gupta 61 month ago" }, { "code": null, "e": 4064, "s": 3389, "text": " public int solve(int[][] cost, int sum, List<Integer> list, int index) {\n if (list.size() == cost.length - 1)\n return sum + cost[list.get(list.size() - 1)][0];\n int min = Integer.MAX_VALUE;\n for (int i = 1; i < cost.length; i++) {\n if (i != index && !list.contains(i)) {\n list.add(i);\n min = Math.min(min, solve(cost, sum + cost[index][i], list, i));\n list.remove(list.size() - 1);\n }\n }\n return min;\n }\n public int total_cost(int[][] cost)\n {\n if(cost.length==1)\n return 0;\n return solve(cost, 0, new ArrayList<>(), 0);\n }" }, { "code": null, "e": 4067, "s": 4064, "text": "+1" }, { "code": null, "e": 4095, "s": 4067, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 4182, "s": 4095, "text": "C++ solution using Hamiltonian Cycle using bit masking, backtracking is as follows :- " }, { "code": null, "e": 4216, "s": 4184, "text": "Execution Time :- 0.2 / 3.4 sec" }, { "code": null, "e": 5202, "s": 4218, "text": "int minCost; int vis; void dfs(int node,int cost,int val,vector<pair<int,int>> adj[],vector<vector<int>> &ct){ vis = vis | (1 << (node)); for(auto choice: adj[node]){ int n = choice.first; int c = choice.second; if((vis & (1<<n)) == 0){ dfs(n,cost+c,val,adj,ct); vis = vis ^ (1<<n); } else{ if(vis == val && n == 0){ minCost = min(minCost,cost + ct[node][n]); } } } } int total_cost(vector<vector<int>>cost){ int n = cost.size(); if(n == 1) return (0); vector<pair<int,int>> adj[n]; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(cost[i][j] != 0){ adj[i].push_back({j,cost[i][j]}); } } } vis = 0; minCost = INT_MAX; dfs(0,0,(1<<n)-1,adj,cost); return (minCost); }" }, { "code": null, "e": 5204, "s": 5202, "text": "0" }, { "code": null, "e": 5230, "s": 5204, "text": "guptaravi32173 months ago" }, { "code": null, "e": 5253, "s": 5230, "text": " // JAVA Solution " }, { "code": null, "e": 5292, "s": 5253, "text": " // HashSet , backtracking Solution" }, { "code": null, "e": 5661, "s": 5292, "text": " int min = Integer.MAX_VALUE; public int total_cost(int[][] cost) { HashSet<Integer> set = new HashSet<>(); int n = cost.length - 1; for (int i = 1; i <= n; i++) { set.add(i); } for (int i = 1; i <= n; i++) { findMinimumCost(i, cost, cost[0][i], set); } return min == Integer.MAX_VALUE? 0 : min; }" }, { "code": null, "e": 6252, "s": 5661, "text": " public void findMinimumCost(int i, int[][] matrix, int cost, HashSet<Integer> set) {// System.out.println(i + \" \" + set + \" \" + cost); if (set.size() == 1) { for (int val : set) { min = Math.min(min, matrix[i][0] + cost); }// System.out.println(min); return; } set.remove(i); HashSet<Integer> cloned_set = new HashSet<>(); cloned_set = (HashSet) set.clone(); for (int key : cloned_set) { findMinimumCost(key, matrix, cost + matrix[i][key], set); } set.add(i); }" }, { "code": null, "e": 6254, "s": 6252, "text": "0" }, { "code": null, "e": 6278, "s": 6254, "text": "utkarshrdce3 months ago" }, { "code": null, "e": 6294, "s": 6278, "text": "DP with bitmask" }, { "code": null, "e": 6955, "s": 6296, "text": "class Solution {\npublic:\nint dp[11][1<<11];\n\nint f(int i, int mask, vector<vector<int>> &cost) {\n if(mask == 0) return cost[i][0];\n if(dp[i][mask] != -1) return dp[i][mask];\n \n int curAns = INT_MAX;\n for(int j = 31; j >= 0; j--) {\n if((mask & (1 << j))) {\n curAns = min(curAns, cost[i][j] + f(j, mask ^ (1 << j), cost));\n }\n }\n return dp[i][mask] = curAns;\n \n}\nint total_cost(vector<vector<int>>cost){\n // Code here\n memset(dp, -1, sizeof(dp));\n int n = cost.size();\n int current_mask = (1 << n) - 1;\n current_mask = current_mask ^ (1 << 0);\n return f(0, current_mask, cost);\n \n \n}\n};" }, { "code": null, "e": 6958, "s": 6955, "text": "-3" }, { "code": null, "e": 6980, "s": 6958, "text": "kunal04033 months ago" }, { "code": null, "e": 7016, "s": 6980, "text": "Any iterative dp+bitmask solution ?" }, { "code": null, "e": 7019, "s": 7016, "text": "+1" }, { "code": null, "e": 7043, "s": 7019, "text": "imansaboori5 months ago" }, { "code": null, "e": 7676, "s": 7043, "text": "class Solution {\npublic:\nint solve(vector<vector<int>>&cost, int i, int depth, vector<bool>& visited)\n{\n const int n = cost.size();\n if(depth==n)\n return cost[i][0];\n\n int ans=INT_MAX;\n visited[i] = true;\n for(int j=0;j<n;j++)\n {\n if(!visited[j])\n {\n visited[j] = true;\n ans = min(ans, cost[i][j] + solve(cost, j, depth+1, visited));\n visited[j] = false;\n }\n }\n visited[i] = false;\n return ans;\n}\nint total_cost(vector<vector<int>>cost){\n // Code here\n vector<bool> visited(cost.size(), false);\n return solve(cost, 0, 1, visited);\n}\n};" }, { "code": null, "e": 7679, "s": 7676, "text": "+2" }, { "code": null, "e": 7705, "s": 7679, "text": "amanshakya0076 months ago" }, { "code": null, "e": 7751, "s": 7705, "text": "Dynamic Programming , Graph and BackTracking " }, { "code": null, "e": 7897, "s": 7751, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7933, "s": 7897, "text": " Login to access your submissions. " }, { "code": null, "e": 7943, "s": 7933, "text": "\nProblem\n" }, { "code": null, "e": 7953, "s": 7943, "text": "\nContest\n" }, { "code": null, "e": 8016, "s": 7953, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8164, "s": 8016, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8372, "s": 8164, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8478, "s": 8372, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
ML - Clustering K-Means Algorithm
K-means clustering algorithm computes the centroids and iterates until we it finds optimal centroid. It assumes that the number of clusters are already known. It is also called flat clustering algorithm. The number of clusters identified from data by algorithm is represented by ‘K’ in K-means. In this algorithm, the data points are assigned to a cluster in such a manner that the sum of the squared distance between the data points and centroid would be minimum. It is to be understood that less variation within the clusters will lead to more similar data points within same cluster. We can understand the working of K-Means clustering algorithm with the help of following steps − Step 1 − First, we need to specify the number of clusters, K, need to be generated by this algorithm. Step 2 − Next, randomly select K data points and assign each data point to a cluster. In simple words, classify the data based on the number of data points. Step 3 − Now it will compute the cluster centroids. Step 4 − Next, keep iterating the following until we find optimal centroid which is the assignment of data points to the clusters that are not changing any more 4.1 − First, the sum of squared distance between data points and centroids would be computed. 4.1 − First, the sum of squared distance between data points and centroids would be computed. 4.2 − Now, we have to assign each data point to the cluster that is closer than other cluster (centroid). 4.2 − Now, we have to assign each data point to the cluster that is closer than other cluster (centroid). 4.3 − At last compute the centroids for the clusters by taking the average of all data points of that cluster. 4.3 − At last compute the centroids for the clusters by taking the average of all data points of that cluster. K-means follows Expectation-Maximization approach to solve the problem. The Expectation-step is used for assigning the data points to the closest cluster and the Maximization-step is used for computing the centroid of each cluster. While working with K-means algorithm we need to take care of the following things − While working with clustering algorithms including K-Means, it is recommended to standardize the data because such algorithms use distance-based measurement to determine the similarity between data points. While working with clustering algorithms including K-Means, it is recommended to standardize the data because such algorithms use distance-based measurement to determine the similarity between data points. Due to the iterative nature of K-Means and random initialization of centroids, K-Means may stick in a local optimum and may not converge to global optimum. That is why it is recommended to use different initializations of centroids. Due to the iterative nature of K-Means and random initialization of centroids, K-Means may stick in a local optimum and may not converge to global optimum. That is why it is recommended to use different initializations of centroids. The following two examples of implementing K-Means clustering algorithm will help us in its better understanding − It is a simple example to understand how k-means works. In this example, we are going to first generate 2D dataset containing 4 different blobs and after that will apply k-means algorithm to see the result. First, we will start by importing the necessary packages − %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np from sklearn.cluster import KMeans The following code will generate the 2D, containing four blobs − from sklearn.datasets.samples_generator import make_blobs X, y_true = make_blobs(n_samples = 400, centers = 4, cluster_std = 0.60, random_state = 0) Next, the following code will help us to visualize the dataset − plt.scatter(X[:, 0], X[:, 1], s = 20); plt.show() Next, make an object of KMeans along with providing number of clusters, train the model and do the prediction as follows − kmeans = KMeans(n_clusters = 4) kmeans.fit(X) y_kmeans = kmeans.predict(X) Now, with the help of following code we can plot and visualize the cluster’s centers picked by k-means Python estimator − from sklearn.datasets.samples_generator import make_blobs X, y_true = make_blobs(n_samples = 400, centers = 4, cluster_std = 0.60, random_state = 0) Next, the following code will help us to visualize the dataset − plt.scatter(X[:, 0], X[:, 1], c = y_kmeans, s = 20, cmap = 'summer') centers = kmeans.cluster_centers_ plt.scatter(centers[:, 0], centers[:, 1], c = 'blue', s = 100, alpha = 0.9); plt.show() Let us move to another example in which we are going to apply K-means clustering on simple digits dataset. K-means will try to identify similar digits without using the original label information. First, we will start by importing the necessary packages − %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np from sklearn.cluster import KMeans Next, load the digit dataset from sklearn and make an object of it. We can also find number of rows and columns in this dataset as follows − from sklearn.datasets import load_digits digits = load_digits() digits.data.shape (1797, 64) The above output shows that this dataset is having 1797 samples with 64 features. We can perform the clustering as we did in Example 1 above − kmeans = KMeans(n_clusters = 10, random_state = 0) clusters = kmeans.fit_predict(digits.data) kmeans.cluster_centers_.shape (10, 64) The above output shows that K-means created 10 clusters with 64 features. fig, ax = plt.subplots(2, 5, figsize=(8, 3)) centers = kmeans.cluster_centers_.reshape(10, 8, 8) for axi, center in zip(ax.flat, centers): axi.set(xticks=[], yticks=[]) axi.imshow(center, interpolation='nearest', cmap=plt.cm.binary) As output, we will get following image showing clusters centers learned by k-means. The following lines of code will match the learned cluster labels with the true labels found in them − from scipy.stats import mode labels = np.zeros_like(clusters) for i in range(10): mask = (clusters == i) labels[mask] = mode(digits.target[mask])[0] Next, we can check the accuracy as follows − from sklearn.metrics import accuracy_score accuracy_score(digits.target, labels) 0.7935447968836951 The above output shows that the accuracy is around 80%. The following are some advantages of K-Means clustering algorithms − It is very easy to understand and implement. It is very easy to understand and implement. If we have large number of variables then, K-means would be faster than Hierarchical clustering. If we have large number of variables then, K-means would be faster than Hierarchical clustering. On re-computation of centroids, an instance can change the cluster. On re-computation of centroids, an instance can change the cluster. Tighter clusters are formed with K-means as compared to Hierarchical clustering. Tighter clusters are formed with K-means as compared to Hierarchical clustering. The following are some disadvantages of K-Means clustering algorithms − It is a bit difficult to predict the number of clusters i.e. the value of k. It is a bit difficult to predict the number of clusters i.e. the value of k. Output is strongly impacted by initial inputs like number of clusters (value of k) Output is strongly impacted by initial inputs like number of clusters (value of k) Order of data will have strong impact on the final output. Order of data will have strong impact on the final output. It is very sensitive to rescaling. If we will rescale our data by means of normalization or standardization, then the output will completely change. It is very sensitive to rescaling. If we will rescale our data by means of normalization or standardization, then the output will completely change. It is not good in doing clustering job if the clusters have a complicated geometric shape. It is not good in doing clustering job if the clusters have a complicated geometric shape. The main goals of cluster analysis are − To get a meaningful intuition from the data we are working with. To get a meaningful intuition from the data we are working with. Cluster-then-predict where different models will be built for different subgroups. Cluster-then-predict where different models will be built for different subgroups. To fulfill the above-mentioned goals, K-means clustering is performing well enough. It can be used in following applications − Market segmentation Document Clustering Image segmentation Image compression Customer segmentation Analyzing the trend on dynamic data 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2599, "s": 2304, "text": "K-means clustering algorithm computes the centroids and iterates until we it finds optimal centroid. It assumes that the number of clusters are already known. It is also called flat clustering algorithm. The number of clusters identified from data by algorithm is represented by ‘K’ in K-means." }, { "code": null, "e": 2891, "s": 2599, "text": "In this algorithm, the data points are assigned to a cluster in such a manner that the sum of the squared distance between the data points and centroid would be minimum. It is to be understood that less variation within the clusters will lead to more similar data points within same cluster." }, { "code": null, "e": 2988, "s": 2891, "text": "We can understand the working of K-Means clustering algorithm with the help of following steps −" }, { "code": null, "e": 3090, "s": 2988, "text": "Step 1 − First, we need to specify the number of clusters, K, need to be generated by this algorithm." }, { "code": null, "e": 3247, "s": 3090, "text": "Step 2 − Next, randomly select K data points and assign each data point to a cluster. In simple words, classify the data based on the number of data points." }, { "code": null, "e": 3299, "s": 3247, "text": "Step 3 − Now it will compute the cluster centroids." }, { "code": null, "e": 3460, "s": 3299, "text": "Step 4 − Next, keep iterating the following until we find optimal centroid which is the assignment of data points to the clusters that are not changing any more" }, { "code": null, "e": 3554, "s": 3460, "text": "4.1 − First, the sum of squared distance between data points and centroids would be computed." }, { "code": null, "e": 3648, "s": 3554, "text": "4.1 − First, the sum of squared distance between data points and centroids would be computed." }, { "code": null, "e": 3754, "s": 3648, "text": "4.2 − Now, we have to assign each data point to the cluster that is closer than other cluster (centroid)." }, { "code": null, "e": 3860, "s": 3754, "text": "4.2 − Now, we have to assign each data point to the cluster that is closer than other cluster (centroid)." }, { "code": null, "e": 3971, "s": 3860, "text": "4.3 − At last compute the centroids for the clusters by taking the average of all data points of that cluster." }, { "code": null, "e": 4082, "s": 3971, "text": "4.3 − At last compute the centroids for the clusters by taking the average of all data points of that cluster." }, { "code": null, "e": 4314, "s": 4082, "text": "K-means follows Expectation-Maximization approach to solve the problem. The Expectation-step is used for assigning the data points to the closest cluster and the Maximization-step is used for computing the centroid of each cluster." }, { "code": null, "e": 4398, "s": 4314, "text": "While working with K-means algorithm we need to take care of the following things −" }, { "code": null, "e": 4604, "s": 4398, "text": "While working with clustering algorithms including K-Means, it is recommended to standardize the data because such algorithms use distance-based measurement to determine the similarity between data points." }, { "code": null, "e": 4810, "s": 4604, "text": "While working with clustering algorithms including K-Means, it is recommended to standardize the data because such algorithms use distance-based measurement to determine the similarity between data points." }, { "code": null, "e": 5043, "s": 4810, "text": "Due to the iterative nature of K-Means and random initialization of centroids, K-Means may stick in a local optimum and may not converge to global optimum. That is why it is recommended to use different initializations of centroids." }, { "code": null, "e": 5276, "s": 5043, "text": "Due to the iterative nature of K-Means and random initialization of centroids, K-Means may stick in a local optimum and may not converge to global optimum. That is why it is recommended to use different initializations of centroids." }, { "code": null, "e": 5391, "s": 5276, "text": "The following two examples of implementing K-Means clustering algorithm will help us in its better understanding −" }, { "code": null, "e": 5598, "s": 5391, "text": "It is a simple example to understand how k-means works. In this example, we are going to first generate 2D dataset containing 4 different blobs and after that will apply k-means algorithm to see the result." }, { "code": null, "e": 5657, "s": 5598, "text": "First, we will start by importing the necessary packages −" }, { "code": null, "e": 5796, "s": 5657, "text": "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport numpy as np\nfrom sklearn.cluster import KMeans\n" }, { "code": null, "e": 5861, "s": 5796, "text": "The following code will generate the 2D, containing four blobs −" }, { "code": null, "e": 6011, "s": 5861, "text": "from sklearn.datasets.samples_generator import make_blobs\nX, y_true = make_blobs(n_samples = 400, centers = 4, cluster_std = 0.60, random_state = 0)\n" }, { "code": null, "e": 6076, "s": 6011, "text": "Next, the following code will help us to visualize the dataset −" }, { "code": null, "e": 6127, "s": 6076, "text": "plt.scatter(X[:, 0], X[:, 1], s = 20);\nplt.show()\n" }, { "code": null, "e": 6250, "s": 6127, "text": "Next, make an object of KMeans along with providing number of clusters, train the model and do the prediction as follows −" }, { "code": null, "e": 6326, "s": 6250, "text": "kmeans = KMeans(n_clusters = 4)\nkmeans.fit(X)\ny_kmeans = kmeans.predict(X)\n" }, { "code": null, "e": 6448, "s": 6326, "text": "Now, with the help of following code we can plot and visualize the cluster’s centers picked by k-means Python estimator −" }, { "code": null, "e": 6598, "s": 6448, "text": "from sklearn.datasets.samples_generator import make_blobs\nX, y_true = make_blobs(n_samples = 400, centers = 4, cluster_std = 0.60, random_state = 0)\n" }, { "code": null, "e": 6663, "s": 6598, "text": "Next, the following code will help us to visualize the dataset −" }, { "code": null, "e": 6855, "s": 6663, "text": "plt.scatter(X[:, 0], X[:, 1], c = y_kmeans, s = 20, cmap = 'summer')\ncenters = kmeans.cluster_centers_\nplt.scatter(centers[:, 0], centers[:, 1], c = 'blue', s = 100, alpha = 0.9);\nplt.show()\n" }, { "code": null, "e": 7052, "s": 6855, "text": "Let us move to another example in which we are going to apply K-means clustering on simple digits dataset. K-means will try to identify similar digits without using the original label information." }, { "code": null, "e": 7111, "s": 7052, "text": "First, we will start by importing the necessary packages −" }, { "code": null, "e": 7250, "s": 7111, "text": "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport numpy as np\nfrom sklearn.cluster import KMeans\n" }, { "code": null, "e": 7391, "s": 7250, "text": "Next, load the digit dataset from sklearn and make an object of it. We can also find number of rows and columns in this dataset as follows −" }, { "code": null, "e": 7474, "s": 7391, "text": "from sklearn.datasets import load_digits\ndigits = load_digits()\ndigits.data.shape\n" }, { "code": null, "e": 7486, "s": 7474, "text": "(1797, 64)\n" }, { "code": null, "e": 7568, "s": 7486, "text": "The above output shows that this dataset is having 1797 samples with 64 features." }, { "code": null, "e": 7629, "s": 7568, "text": "We can perform the clustering as we did in Example 1 above −" }, { "code": null, "e": 7754, "s": 7629, "text": "kmeans = KMeans(n_clusters = 10, random_state = 0)\nclusters = kmeans.fit_predict(digits.data)\nkmeans.cluster_centers_.shape\n" }, { "code": null, "e": 7764, "s": 7754, "text": "(10, 64)\n" }, { "code": null, "e": 7838, "s": 7764, "text": "The above output shows that K-means created 10 clusters with 64 features." }, { "code": null, "e": 8072, "s": 7838, "text": "fig, ax = plt.subplots(2, 5, figsize=(8, 3))\ncenters = kmeans.cluster_centers_.reshape(10, 8, 8)\nfor axi, center in zip(ax.flat, centers):\naxi.set(xticks=[], yticks=[])\naxi.imshow(center, interpolation='nearest', cmap=plt.cm.binary)\n" }, { "code": null, "e": 8156, "s": 8072, "text": "As output, we will get following image showing clusters centers learned by k-means." }, { "code": null, "e": 8259, "s": 8156, "text": "The following lines of code will match the learned cluster labels with the true labels found in them −" }, { "code": null, "e": 8414, "s": 8259, "text": "from scipy.stats import mode\nlabels = np.zeros_like(clusters)\nfor i in range(10):\n mask = (clusters == i)\n labels[mask] = mode(digits.target[mask])[0]" }, { "code": null, "e": 8459, "s": 8414, "text": "Next, we can check the accuracy as follows −" }, { "code": null, "e": 8541, "s": 8459, "text": "from sklearn.metrics import accuracy_score\naccuracy_score(digits.target, labels)\n" }, { "code": null, "e": 8561, "s": 8541, "text": "0.7935447968836951\n" }, { "code": null, "e": 8617, "s": 8561, "text": "The above output shows that the accuracy is around 80%." }, { "code": null, "e": 8686, "s": 8617, "text": "The following are some advantages of K-Means clustering algorithms −" }, { "code": null, "e": 8731, "s": 8686, "text": "It is very easy to understand and implement." }, { "code": null, "e": 8776, "s": 8731, "text": "It is very easy to understand and implement." }, { "code": null, "e": 8873, "s": 8776, "text": "If we have large number of variables then, K-means would be faster than Hierarchical clustering." }, { "code": null, "e": 8970, "s": 8873, "text": "If we have large number of variables then, K-means would be faster than Hierarchical clustering." }, { "code": null, "e": 9038, "s": 8970, "text": "On re-computation of centroids, an instance can change the cluster." }, { "code": null, "e": 9106, "s": 9038, "text": "On re-computation of centroids, an instance can change the cluster." }, { "code": null, "e": 9187, "s": 9106, "text": "Tighter clusters are formed with K-means as compared to Hierarchical clustering." }, { "code": null, "e": 9268, "s": 9187, "text": "Tighter clusters are formed with K-means as compared to Hierarchical clustering." }, { "code": null, "e": 9340, "s": 9268, "text": "The following are some disadvantages of K-Means clustering algorithms −" }, { "code": null, "e": 9417, "s": 9340, "text": "It is a bit difficult to predict the number of clusters i.e. the value of k." }, { "code": null, "e": 9494, "s": 9417, "text": "It is a bit difficult to predict the number of clusters i.e. the value of k." }, { "code": null, "e": 9577, "s": 9494, "text": "Output is strongly impacted by initial inputs like number of clusters (value of k)" }, { "code": null, "e": 9660, "s": 9577, "text": "Output is strongly impacted by initial inputs like number of clusters (value of k)" }, { "code": null, "e": 9719, "s": 9660, "text": "Order of data will have strong impact on the final output." }, { "code": null, "e": 9778, "s": 9719, "text": "Order of data will have strong impact on the final output." }, { "code": null, "e": 9927, "s": 9778, "text": "It is very sensitive to rescaling. If we will rescale our data by means of normalization or standardization, then the output will completely change." }, { "code": null, "e": 10076, "s": 9927, "text": "It is very sensitive to rescaling. If we will rescale our data by means of normalization or standardization, then the output will completely change." }, { "code": null, "e": 10167, "s": 10076, "text": "It is not good in doing clustering job if the clusters have a complicated geometric shape." }, { "code": null, "e": 10258, "s": 10167, "text": "It is not good in doing clustering job if the clusters have a complicated geometric shape." }, { "code": null, "e": 10299, "s": 10258, "text": "The main goals of cluster analysis are −" }, { "code": null, "e": 10364, "s": 10299, "text": "To get a meaningful intuition from the data we are working with." }, { "code": null, "e": 10429, "s": 10364, "text": "To get a meaningful intuition from the data we are working with." }, { "code": null, "e": 10512, "s": 10429, "text": "Cluster-then-predict where different models will be built for different subgroups." }, { "code": null, "e": 10595, "s": 10512, "text": "Cluster-then-predict where different models will be built for different subgroups." }, { "code": null, "e": 10722, "s": 10595, "text": "To fulfill the above-mentioned goals, K-means clustering is performing well enough. It can be used in following applications −" }, { "code": null, "e": 10742, "s": 10722, "text": "Market segmentation" }, { "code": null, "e": 10762, "s": 10742, "text": "Document Clustering" }, { "code": null, "e": 10781, "s": 10762, "text": "Image segmentation" }, { "code": null, "e": 10799, "s": 10781, "text": "Image compression" }, { "code": null, "e": 10821, "s": 10799, "text": "Customer segmentation" }, { "code": null, "e": 10857, "s": 10821, "text": "Analyzing the trend on dynamic data" }, { "code": null, "e": 10894, "s": 10857, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 10917, "s": 10894, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 10953, "s": 10917, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 10981, "s": 10953, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11015, "s": 10981, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 11032, "s": 11015, "text": " Abhilash Nelson" }, { "code": null, "e": 11065, "s": 11032, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 11087, "s": 11065, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 11120, "s": 11087, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 11142, "s": 11120, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 11175, "s": 11142, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 11197, "s": 11175, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 11204, "s": 11197, "text": " Print" }, { "code": null, "e": 11215, "s": 11204, "text": " Add Notes" } ]
Longest subsequence having maximum sum - GeeksforGeeks
21 Apr, 2021 Given an array arr[] of size N, the task is to find the longest non-empty subsequence from the given array whose sum is maximum. Examples: Input: arr[] = { 1, 2, -4, -2, 3, 0 } Output: 1 2 3 0 Explanation: Sum of elements of the subsequence {1, 2, 3, 0} is 6 which is the maximum possible sum. Therefore, the required output is 1 2 3 0 Input: arr[] = { -10, -6, -2, -3, -4 } Output: -2 Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible subsequence of the given array and calculate their sums. Print the longest of all subsequences with maximum sum. Time Complexity: O(N * 2N) Auxiliary Space: O(N) Efficient Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem: Initialize a variable, say maxm, to store the largest element of the given array. If maxm < 0, then print the value of maxm. Otherwise, traverse the array and print all positive array elements. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the longest subsequence// from the given array with maximum sumvoid longestSubWithMaxSum(int arr[], int N){ // Stores the largest element // of the array int Max = *max_element(arr, arr + N); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array cout << Max; return; } // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence cout << arr[i] << " "; } }} // Driver Codeint main(){ int arr[] = { 1, 2, -4, -2, 3, 0 }; int N = sizeof(arr) / sizeof(arr[0]); longestSubWithMaxSum(arr, N); return 0;} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the longest subsequence// from the given array with maximum sumstatic void longestSubWithMaxSum(int arr[], int N){ // Stores the largest element // of the array int Max = Arrays.stream(arr).max().getAsInt(); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array System.out.print(Max); return; } // Traverse the array for(int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence System.out.print(arr[i] + " "); } }} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, -4, -2, 3, 0 }; int N = arr.length; longestSubWithMaxSum(arr, N);}} // This code is contributed by code_hunt # Python3 program to implement# the above approach # Function to find the longest subsequence# from the given array with maximum sumdef longestSubWithMaxSum(arr, N): # Stores the largest element # of the array Max = max(arr) # If Max is less than 0 if (Max < 0) : # Print the largest element # of the array print(Max) return # Traverse the array for i in range(N): # If arr[i] is greater # than or equal to 0 if (arr[i] >= 0) : # Print elements of # the subsequence print(arr[i], end = " ") # Driver codearr = [ 1, 2, -4, -2, 3, 0 ] N = len(arr) longestSubWithMaxSum(arr, N) # This code is contributed divyeshrabadiya07 // C# program to implement// the above approachusing System; class GFG{ // Function to find the longest subsequence// from the given array with maximum sumstatic void longestSubWithMaxSum(int []arr, int N){ // Stores the largest element // of the array int Max = arr[0]; for(int i = 1; i < N; i++) { if (Max < arr[i]) Max = arr[i]; } // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array Console.Write(Max); return; } // Traverse the array for(int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence Console.Write(arr[i] + " "); } }} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, -4, -2, 3, 0 }; int N = arr.Length; longestSubWithMaxSum(arr, N);}} // This code is contributed by aashish1995 <script> // JavaScript program to implement// the above approach // Function to find the longest subsequence// from the given array with maximum sumfunction longestSubWithMaxSum(arr, N){ // Stores the largest element // of the array let Max = Math.max(...arr); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array document.write(Max); return; } // Traverse the array for(let i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print the elements of // the subsequence document.write(arr[i] + " "); } }} // Driver codelet arr = [ 1, 2, -4, -2, 3, 0 ];let N = arr.length; longestSubWithMaxSum(arr, N); // This code is contributed by avijitmondal1998 </script> 1 2 3 0 Time Complexity: O(N) Auxiliary Space: O(1) code_hunt divyeshrabadiya07 aashish1995 avijitmondal1998 interview-preparation subsequence Arrays Greedy Mathematical Searching Arrays Searching Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 24431, "s": 24403, "text": "\n21 Apr, 2021" }, { "code": null, "e": 24560, "s": 24431, "text": "Given an array arr[] of size N, the task is to find the longest non-empty subsequence from the given array whose sum is maximum." }, { "code": null, "e": 24570, "s": 24560, "text": "Examples:" }, { "code": null, "e": 24767, "s": 24570, "text": "Input: arr[] = { 1, 2, -4, -2, 3, 0 } Output: 1 2 3 0 Explanation: Sum of elements of the subsequence {1, 2, 3, 0} is 6 which is the maximum possible sum. Therefore, the required output is 1 2 3 0" }, { "code": null, "e": 24817, "s": 24767, "text": "Input: arr[] = { -10, -6, -2, -3, -4 } Output: -2" }, { "code": null, "e": 25042, "s": 24817, "text": "Naive Approach: The simplest approach to solve this problem is to traverse the array and generate all possible subsequence of the given array and calculate their sums. Print the longest of all subsequences with maximum sum. " }, { "code": null, "e": 25091, "s": 25042, "text": "Time Complexity: O(N * 2N) Auxiliary Space: O(N)" }, { "code": null, "e": 25206, "s": 25091, "text": "Efficient Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:" }, { "code": null, "e": 25288, "s": 25206, "text": "Initialize a variable, say maxm, to store the largest element of the given array." }, { "code": null, "e": 25331, "s": 25288, "text": "If maxm < 0, then print the value of maxm." }, { "code": null, "e": 25400, "s": 25331, "text": "Otherwise, traverse the array and print all positive array elements." }, { "code": null, "e": 25451, "s": 25400, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25455, "s": 25451, "text": "C++" }, { "code": null, "e": 25460, "s": 25455, "text": "Java" }, { "code": null, "e": 25468, "s": 25460, "text": "Python3" }, { "code": null, "e": 25471, "s": 25468, "text": "C#" }, { "code": null, "e": 25482, "s": 25471, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the longest subsequence// from the given array with maximum sumvoid longestSubWithMaxSum(int arr[], int N){ // Stores the largest element // of the array int Max = *max_element(arr, arr + N); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array cout << Max; return; } // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence cout << arr[i] << \" \"; } }} // Driver Codeint main(){ int arr[] = { 1, 2, -4, -2, 3, 0 }; int N = sizeof(arr) / sizeof(arr[0]); longestSubWithMaxSum(arr, N); return 0;}", "e": 26383, "s": 25482, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the longest subsequence// from the given array with maximum sumstatic void longestSubWithMaxSum(int arr[], int N){ // Stores the largest element // of the array int Max = Arrays.stream(arr).max().getAsInt(); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array System.out.print(Max); return; } // Traverse the array for(int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence System.out.print(arr[i] + \" \"); } }} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, -4, -2, 3, 0 }; int N = arr.length; longestSubWithMaxSum(arr, N);}} // This code is contributed by code_hunt", "e": 27368, "s": 26383, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find the longest subsequence# from the given array with maximum sumdef longestSubWithMaxSum(arr, N): # Stores the largest element # of the array Max = max(arr) # If Max is less than 0 if (Max < 0) : # Print the largest element # of the array print(Max) return # Traverse the array for i in range(N): # If arr[i] is greater # than or equal to 0 if (arr[i] >= 0) : # Print elements of # the subsequence print(arr[i], end = \" \") # Driver codearr = [ 1, 2, -4, -2, 3, 0 ] N = len(arr) longestSubWithMaxSum(arr, N) # This code is contributed divyeshrabadiya07", "e": 28097, "s": 27368, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to find the longest subsequence// from the given array with maximum sumstatic void longestSubWithMaxSum(int []arr, int N){ // Stores the largest element // of the array int Max = arr[0]; for(int i = 1; i < N; i++) { if (Max < arr[i]) Max = arr[i]; } // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array Console.Write(Max); return; } // Traverse the array for(int i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print elements of // the subsequence Console.Write(arr[i] + \" \"); } }} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, -4, -2, 3, 0 }; int N = arr.Length; longestSubWithMaxSum(arr, N);}} // This code is contributed by aashish1995", "e": 29173, "s": 28097, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to find the longest subsequence// from the given array with maximum sumfunction longestSubWithMaxSum(arr, N){ // Stores the largest element // of the array let Max = Math.max(...arr); // If Max is less than 0 if (Max < 0) { // Print the largest element // of the array document.write(Max); return; } // Traverse the array for(let i = 0; i < N; i++) { // If arr[i] is greater // than or equal to 0 if (arr[i] >= 0) { // Print the elements of // the subsequence document.write(arr[i] + \" \"); } }} // Driver codelet arr = [ 1, 2, -4, -2, 3, 0 ];let N = arr.length; longestSubWithMaxSum(arr, N); // This code is contributed by avijitmondal1998 </script>", "e": 30079, "s": 29173, "text": null }, { "code": null, "e": 30087, "s": 30079, "text": "1 2 3 0" }, { "code": null, "e": 30133, "s": 30089, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 30143, "s": 30133, "text": "code_hunt" }, { "code": null, "e": 30161, "s": 30143, "text": "divyeshrabadiya07" }, { "code": null, "e": 30173, "s": 30161, "text": "aashish1995" }, { "code": null, "e": 30190, "s": 30173, "text": "avijitmondal1998" }, { "code": null, "e": 30212, "s": 30190, "text": "interview-preparation" }, { "code": null, "e": 30224, "s": 30212, "text": "subsequence" }, { "code": null, "e": 30231, "s": 30224, "text": "Arrays" }, { "code": null, "e": 30238, "s": 30231, "text": "Greedy" }, { "code": null, "e": 30251, "s": 30238, "text": "Mathematical" }, { "code": null, "e": 30261, "s": 30251, "text": "Searching" }, { "code": null, "e": 30268, "s": 30261, "text": "Arrays" }, { "code": null, "e": 30278, "s": 30268, "text": "Searching" }, { "code": null, "e": 30285, "s": 30278, "text": "Greedy" }, { "code": null, "e": 30298, "s": 30285, "text": "Mathematical" }, { "code": null, "e": 30396, "s": 30298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30405, "s": 30396, "text": "Comments" }, { "code": null, "e": 30418, "s": 30405, "text": "Old Comments" }, { "code": null, "e": 30439, "s": 30418, "text": "Next Greater Element" }, { "code": null, "e": 30464, "s": 30439, "text": "Window Sliding Technique" }, { "code": null, "e": 30491, "s": 30464, "text": "Count pairs with given sum" }, { "code": null, "e": 30540, "s": 30491, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30578, "s": 30540, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30629, "s": 30578, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 30680, "s": 30629, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 30738, "s": 30680, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 30769, "s": 30738, "text": "Huffman Coding | Greedy Algo-3" } ]
Passing unknown number of arguments to a function in Javascript
When you call a function in JavaScript you can pass in any number of arguments. There is no function parameter limit. This also means that functions can't be overloaded in traditional ways in js. The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0. For example, if a function is passed 3 arguments, you can access them as follows − arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument Note − arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have Array's built-in methods like forEach() and map(). For example, to accept a arbitrary number of args, you can create a function as follows − function printAllArguments(a, b) { console.log("First arg: " + a) console.log("Second arg: " + b) console.log("All args: " + arguments) } printAllArguments(1) printAllArguments(1, "hello") printAllArguments(1, "hello", 1, "hello") First arg: 1 Second arg: undefined All args: {"0":1} First arg: 1 Second arg: hello All args: {"0":1,"1":"hello"} First arg: 1 Second arg: hello All args: {"0":1,"1":"hello","2":1,"3":"hello"}
[ { "code": null, "e": 1258, "s": 1062, "text": "When you call a function in JavaScript you can pass in any number of arguments. There is no function parameter limit. This also means that functions can't be overloaded in traditional ways in js." }, { "code": null, "e": 1531, "s": 1258, "text": "The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0." }, { "code": null, "e": 1614, "s": 1531, "text": "For example, if a function is passed 3 arguments, you can access them as follows −" }, { "code": null, "e": 1708, "s": 1614, "text": "arguments[0] // first argument\narguments[1] // second argument\narguments[2] // third argument" }, { "code": null, "e": 2005, "s": 1708, "text": "Note − arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have Array's built-in methods like forEach() and map()." }, { "code": null, "e": 2095, "s": 2005, "text": "For example, to accept a arbitrary number of args, you can create a function as follows −" }, { "code": null, "e": 2335, "s": 2095, "text": "function printAllArguments(a, b) {\n console.log(\"First arg: \" + a)\n console.log(\"Second arg: \" + b)\n console.log(\"All args: \" + arguments)\n}\nprintAllArguments(1)\nprintAllArguments(1, \"hello\")\nprintAllArguments(1, \"hello\", 1, \"hello\")" }, { "code": null, "e": 2534, "s": 2335, "text": "First arg: 1 \nSecond arg: undefined \nAll args: {\"0\":1}\nFirst arg: 1\nSecond arg: hello \nAll args: {\"0\":1,\"1\":\"hello\"} \nFirst arg: 1\nSecond arg: hello \nAll args: {\"0\":1,\"1\":\"hello\",\"2\":1,\"3\":\"hello\"} " } ]
PHP - Function move_uploaded_file()
The move_uploaded_file() function can move an uploaded file to new location. If the filename is not a valid upload file, then no action can occur and return false. If the filename is a valid upload file but can't be moved for some reason, then no action can occur and return false. Additionally, a warning can be issued. bool move_uploaded_file ( string $filename , string $destination ) This function can check to ensure that the file designated by filename is a valid upload file, which means that it has uploaded via PHP's HTTP POST upload mechanism. If the file is valid, it can be moved to the filename given by the destination. This sort of check is especially used if there is any chance that anything done with uploaded files can reveal their contents to the user, or even to other users on the same system. <?php $uploads_dir = "/PhpProject/uploads"; foreach($_FILES["pictures"]["error"] as $key => $error) { if($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; $name = basename($_FILES["pictures"]["name"][$key]); move_uploaded_file($tmp_name, "$uploads_dir/$name"); } } ?> 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 3080, "s": 2757, "text": " The move_uploaded_file() function can move an uploaded file to new location. If the filename is not a valid upload file, then no action can occur and return false. If the filename is a valid upload file but can't be moved for some reason, then no action can occur and return false. Additionally, a warning can be issued. " }, { "code": null, "e": 3148, "s": 3080, "text": "bool move_uploaded_file ( string $filename , string $destination )\n" }, { "code": null, "e": 3396, "s": 3148, "text": " This function can check to ensure that the file designated by filename is a valid upload file, which means that it has uploaded via PHP's HTTP POST upload mechanism. If the file is valid, it can be moved to the filename given by the destination. " }, { "code": null, "e": 3580, "s": 3396, "text": " This sort of check is especially used if there is any chance that anything done with uploaded files can reveal their contents to the user, or even to other users on the same system. " }, { "code": null, "e": 3924, "s": 3580, "text": "<?php\n $uploads_dir = \"/PhpProject/uploads\";\n foreach($_FILES[\"pictures\"][\"error\"] as $key => $error) {\n if($error == UPLOAD_ERR_OK) {\n $tmp_name = $_FILES[\"pictures\"][\"tmp_name\"][$key];\n $name = basename($_FILES[\"pictures\"][\"name\"][$key]);\n move_uploaded_file($tmp_name, \"$uploads_dir/$name\");\n }\n }\n?>" }, { "code": null, "e": 3957, "s": 3924, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 3973, "s": 3957, "text": " Malhar Lathkar" }, { "code": null, "e": 4006, "s": 3973, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4017, "s": 4006, "text": " Syed Raza" }, { "code": null, "e": 4052, "s": 4017, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4069, "s": 4052, "text": " Frahaan Hussain" }, { "code": null, "e": 4102, "s": 4069, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4117, "s": 4102, "text": " Nivedita Jain" }, { "code": null, "e": 4152, "s": 4117, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 4164, "s": 4152, "text": " Azaz Patel" }, { "code": null, "e": 4199, "s": 4164, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4227, "s": 4199, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4234, "s": 4227, "text": " Print" }, { "code": null, "e": 4245, "s": 4234, "text": " Add Notes" } ]
JavaFX - 2D Shapes Quad Curve
Mathematically a quadratic curve is one that is described by a quadratic function like − y = ax2 + bx + c. In computer graphics Bezier curves are used. These are parametric curves which appear reasonably smooth at all scales. These Bezier curves are drawn based on points on an XY plane. A quadratic curve is a Bezier parametric curve in the XY plane which is a curve of degree 2. It is drawn using three points: start point, end point and control point as shown in the following diagram In JavaFX, a QuadCurve is represented by a class named QuadCurve. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a QuadCurve node in JavaFX. This class has 6 properties of the double datatype namely − startX − The x coordinate of the starting point of the curve. startX − The x coordinate of the starting point of the curve. startY − The y coordinate of the starting point of the curve. startY − The y coordinate of the starting point of the curve. controlX − The x coordinate of the control point of the curve. controlX − The x coordinate of the control point of the curve. controlY − The y coordinate of the control point of the curve. controlY − The y coordinate of the control point of the curve. endX − The x coordinate of the end point of the curve. endX − The x coordinate of the end point of the curve. endY − The y coordinate of the end point of the curve. endY − The y coordinate of the end point of the curve. To draw a QuadCurve, you need to pass values to these properties. This can be done either by passing them to the constructor of this class, in the same order, at the time of instantiation, as follows − QuadCurve quadcurve = new QuadCurve(startX, startY, controlX, controlY, endX, endY); Or, by using their respective setter methods as follow − setStartX(value); setStartY(value); setControlX(value); setControlY(value); setEndX(value); setEndY(value); To Draw a Bezier Quadrilateral Curve in JavaFX, follow the steps given below. Create a Java class and inherit the Application class of the package javafx.application. Then you can implement the start() method of this class as follows. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { } } You can create a QuadCurve in JavaFX by instantiating the class named QuadCurve which belongs to a package javafx.scene.shape. You can then instantiate this class as shown in the following code block. //Creating an object of the class QuadCurve QuadCurve quadcurve = new QuadCurve(); Specify the x, y coordinates of the three points: start point, end point and control points, of the required curve, using their respective setter methods as shown in the following code block. //Adding properties to the Quad Curve quadCurve.setStartX(100.0); quadCurve.setStartY(220.0f); quadCurve.setEndX(500.0f); quadCurve.setEndY(220.0f); quadCurve.setControlX(250.0f); quadCurve.setControlY(0.0f); In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the QuadCurve (node) object created in the previous step as a parameter to the constructor of the Group class, in order to add it to the group as follows − Group root = new Group(quadcurve); Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root) created in the previous step. In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows. Scene scene = new Scene(group ,600, 300); You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as follows. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows. primaryStage.setScene(scene); Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows. public static void main(String args[]){ launch(args); } Following is a program which generates a quadrilateral curve using JavaFX. Save this code in a file with the name QuadCurveExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.QuadCurve; public class QuadCurveExample extends Application { @Override public void start(Stage stage) { //Creating a QuadCurve QuadCurve quadCurve = new QuadCurve(); //Adding properties to the Quad Curve quadCurve.setStartX(100.0); quadCurve.setStartY(220.0f); quadCurve.setEndX(500.0f); quadCurve.setEndY(220.0f); quadCurve.setControlX(250.0f); quadCurve.setControlY(0.0f); //Creating a Group object Group root = new Group(quadCurve); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Quad curve"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac QuadCurveExample.java java QuadCurveExample On executing, the above program generates a JavaFX window displaying a Bezier quadrilateral curve as shown in the following screenshot. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2007, "s": 1900, "text": "Mathematically a quadratic curve is one that is described by a quadratic function like − y = ax2 + bx + c." }, { "code": null, "e": 2188, "s": 2007, "text": "In computer graphics Bezier curves are used. These are parametric curves which appear reasonably smooth at all scales. These Bezier curves are drawn based on points on an XY plane." }, { "code": null, "e": 2388, "s": 2188, "text": "A quadratic curve is a Bezier parametric curve in the XY plane which is a curve of degree 2. It is drawn using three points: start point, end point and control point as shown in the following diagram" }, { "code": null, "e": 2508, "s": 2388, "text": "In JavaFX, a QuadCurve is represented by a class named QuadCurve. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 2580, "s": 2508, "text": "By instantiating this class, you can create a QuadCurve node in JavaFX." }, { "code": null, "e": 2640, "s": 2580, "text": "This class has 6 properties of the double datatype namely −" }, { "code": null, "e": 2702, "s": 2640, "text": "startX − The x coordinate of the starting point of the curve." }, { "code": null, "e": 2764, "s": 2702, "text": "startX − The x coordinate of the starting point of the curve." }, { "code": null, "e": 2826, "s": 2764, "text": "startY − The y coordinate of the starting point of the curve." }, { "code": null, "e": 2888, "s": 2826, "text": "startY − The y coordinate of the starting point of the curve." }, { "code": null, "e": 2951, "s": 2888, "text": "controlX − The x coordinate of the control point of the curve." }, { "code": null, "e": 3014, "s": 2951, "text": "controlX − The x coordinate of the control point of the curve." }, { "code": null, "e": 3077, "s": 3014, "text": "controlY − The y coordinate of the control point of the curve." }, { "code": null, "e": 3140, "s": 3077, "text": "controlY − The y coordinate of the control point of the curve." }, { "code": null, "e": 3195, "s": 3140, "text": "endX − The x coordinate of the end point of the curve." }, { "code": null, "e": 3250, "s": 3195, "text": "endX − The x coordinate of the end point of the curve." }, { "code": null, "e": 3305, "s": 3250, "text": "endY − The y coordinate of the end point of the curve." }, { "code": null, "e": 3360, "s": 3305, "text": "endY − The y coordinate of the end point of the curve." }, { "code": null, "e": 3562, "s": 3360, "text": "To draw a QuadCurve, you need to pass values to these properties. This can be done either by passing them to the constructor of this class, in the same order, at the time of instantiation, as follows −" }, { "code": null, "e": 3648, "s": 3562, "text": "QuadCurve quadcurve = new QuadCurve(startX, startY, controlX, controlY, endX, endY);\n" }, { "code": null, "e": 3705, "s": 3648, "text": "Or, by using their respective setter methods as follow −" }, { "code": null, "e": 3820, "s": 3705, "text": "setStartX(value); \nsetStartY(value); \nsetControlX(value); \nsetControlY(value); \nsetEndX(value); \nsetEndY(value); \n" }, { "code": null, "e": 3898, "s": 3820, "text": "To Draw a Bezier Quadrilateral Curve in JavaFX, follow the steps given below." }, { "code": null, "e": 4055, "s": 3898, "text": "Create a Java class and inherit the Application class of the package javafx.application. Then you can implement the start() method of this class as follows." }, { "code": null, "e": 4195, "s": 4055, "text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n}" }, { "code": null, "e": 4396, "s": 4195, "text": "You can create a QuadCurve in JavaFX by instantiating the class named QuadCurve which belongs to a package javafx.scene.shape. You can then instantiate this class as shown in the following code block." }, { "code": null, "e": 4481, "s": 4396, "text": "//Creating an object of the class QuadCurve \nQuadCurve quadcurve = new QuadCurve();\n" }, { "code": null, "e": 4673, "s": 4481, "text": "Specify the x, y coordinates of the three points: start point, end point and control points, of the required curve, using their respective setter methods as shown in the following code block." }, { "code": null, "e": 4888, "s": 4673, "text": "//Adding properties to the Quad Curve \nquadCurve.setStartX(100.0); \nquadCurve.setStartY(220.0f); \nquadCurve.setEndX(500.0f); \nquadCurve.setEndY(220.0f);\nquadCurve.setControlX(250.0f); \nquadCurve.setControlY(0.0f);\n" }, { "code": null, "e": 5016, "s": 4888, "text": "In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene." }, { "code": null, "e": 5177, "s": 5016, "text": "Pass the QuadCurve (node) object created in the previous step as a parameter to the constructor of the Group class, in order to add it to the group as follows −" }, { "code": null, "e": 5213, "s": 5177, "text": "Group root = new Group(quadcurve);\n" }, { "code": null, "e": 5383, "s": 5213, "text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root) created in the previous step." }, { "code": null, "e": 5552, "s": 5383, "text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows." }, { "code": null, "e": 5595, "s": 5552, "text": "Scene scene = new Scene(group ,600, 300);\n" }, { "code": null, "e": 5785, "s": 5595, "text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter." }, { "code": null, "e": 5877, "s": 5785, "text": "Using the primaryStage object, set the title of the scene as Sample Application as follows." }, { "code": null, "e": 5923, "s": 5877, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 6099, "s": 5923, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows." }, { "code": null, "e": 6130, "s": 6099, "text": "primaryStage.setScene(scene);\n" }, { "code": null, "e": 6225, "s": 6130, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 6247, "s": 6225, "text": "primaryStage.show();\n" }, { "code": null, "e": 6373, "s": 6247, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows." }, { "code": null, "e": 6442, "s": 6373, "text": "public static void main(String args[]){ \n launch(args); \n} " }, { "code": null, "e": 6579, "s": 6442, "text": "Following is a program which generates a quadrilateral curve using JavaFX. Save this code in a file with the name QuadCurveExample.java." }, { "code": null, "e": 7716, "s": 6579, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.shape.QuadCurve; \n\npublic class QuadCurveExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a QuadCurve \n QuadCurve quadCurve = new QuadCurve(); \n \n //Adding properties to the Quad Curve \n quadCurve.setStartX(100.0); \n quadCurve.setStartY(220.0f); \n quadCurve.setEndX(500.0f); \n quadCurve.setEndY(220.0f); \n quadCurve.setControlX(250.0f); \n quadCurve.setControlY(0.0f); \n \n //Creating a Group object \n Group root = new Group(quadCurve);\n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a Quad curve\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 7810, "s": 7716, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 7862, "s": 7810, "text": "javac QuadCurveExample.java \njava QuadCurveExample\n" }, { "code": null, "e": 7998, "s": 7862, "text": "On executing, the above program generates a JavaFX window displaying a Bezier quadrilateral curve as shown in the following screenshot." }, { "code": null, "e": 8033, "s": 7998, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8044, "s": 8033, "text": " Syed Raza" }, { "code": null, "e": 8080, "s": 8044, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 8116, "s": 8080, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8149, "s": 8116, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 8185, "s": 8149, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8192, "s": 8185, "text": " Print" }, { "code": null, "e": 8203, "s": 8192, "text": " Add Notes" } ]
GATE | GATE-CS-2017 (Set 1) | Question 63 - GeeksforGeeks
28 Jun, 2021 Recall that Belady’s anomaly is that the pages-fault rate may increase as the number of allocated frames increases. Now consider the following statements: S1: Random page replacement algorithm (where a page chosen at random is replaced) suffers from Belady’s anomaly. S2: LRU page replacement algorithm suffers from Belady’s anomaly . Which of the following is CORRECT?(A) S1 is true, S2 is true(B) S1 is true, S2 is false(C) S1 is false , S2 is true(D) S1 is false, S2 is falseAnswer: (B)Explanation: Belady’s anomaly proves that it is possible to have more page faults when increasing the number of page frames while using the First in First Out (FIFO) page replacement algorithm. For example, if we consider reference string 3 2 1 0 3 2 4 3 2 1 0 4 and 3 slots, we get 9 total page faults, but if we increase slots to 4, we get 10 page faults. S1: Random page replacement algorithm (where a page chosen at random is replaced) suffers from Belady’s anomaly.-> Random page replacement algorithm can be any including FIFO so its true S2: LRU page replacement algorithm suffers from Belady’s anomaly .-> LRU does’nt suffer from Belady’s anomaly . Therefore, option B is correctQuiz of this Question GATE-CS-2017 (Set 1) GATE-GATE-CS-2017 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE CS 2012 | Question 40
[ { "code": null, "e": 24043, "s": 24015, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24198, "s": 24043, "text": "Recall that Belady’s anomaly is that the pages-fault rate may increase as the number of allocated frames increases. Now consider the following statements:" }, { "code": null, "e": 24393, "s": 24198, "text": "S1: Random page replacement algorithm (where\n a page chosen at random is replaced) \n suffers from Belady’s anomaly.\n\nS2: LRU page replacement algorithm suffers\n from Belady’s anomaly .\n" }, { "code": null, "e": 24905, "s": 24393, "text": "Which of the following is CORRECT?(A) S1 is true, S2 is true(B) S1 is true, S2 is false(C) S1 is false , S2 is true(D) S1 is false, S2 is falseAnswer: (B)Explanation: Belady’s anomaly proves that it is possible to have more page faults when increasing the number of page frames while using the First in First Out (FIFO) page replacement algorithm. For example, if we consider reference string 3 2 1 0 3 2 4 3 2 1 0 4 and 3 slots, we get 9 total page faults, but if we increase slots to 4, we get 10 page faults." }, { "code": null, "e": 25092, "s": 24905, "text": "S1: Random page replacement algorithm (where a page chosen at random is replaced) suffers from Belady’s anomaly.-> Random page replacement algorithm can be any including FIFO so its true" }, { "code": null, "e": 25204, "s": 25092, "text": "S2: LRU page replacement algorithm suffers from Belady’s anomaly .-> LRU does’nt suffer from Belady’s anomaly ." }, { "code": null, "e": 25256, "s": 25204, "text": "Therefore, option B is correctQuiz of this Question" }, { "code": null, "e": 25277, "s": 25256, "text": "GATE-CS-2017 (Set 1)" }, { "code": null, "e": 25303, "s": 25277, "text": "GATE-GATE-CS-2017 (Set 1)" }, { "code": null, "e": 25308, "s": 25303, "text": "GATE" }, { "code": null, "e": 25406, "s": 25308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25415, "s": 25406, "text": "Comments" }, { "code": null, "e": 25428, "s": 25415, "text": "Old Comments" }, { "code": null, "e": 25470, "s": 25428, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25512, "s": 25470, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25546, "s": 25512, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25588, "s": 25546, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25622, "s": 25588, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25664, "s": 25622, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25697, "s": 25664, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25739, "s": 25697, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25793, "s": 25739, "text": "C++ Program to count Vowels in a string using Pointer" } ]
traceroute command in Linux with Examples
27 May, 2019 traceroute command in Linux prints the route that a packet takes to reach the host. This command is useful when you want to know about the route and about all the hops that a packet takes. Below image depicts how traceroute command is used to reach the Google(172.217.26.206) host from the local machine and it also prints detail about all the hops that it visits in between. The first column corresponds to the hop count. The second column represents the address of that hop and after that, you see three space-separated time in milliseconds. traceroute command sends three packets to the hop and each of the time refers to the time taken by the packet to reach the hop. Syntax: traceroute [options] host_Address [pathlength] Options: -4 Option: Use ip version 4 i.e. use IPv4Syntax:$ traceroute -4 10 google.com Syntax: $ traceroute -4 10 google.com -6 Option: Use ip version 6 i.e. use IPv6Syntax:$ traceroute -6 10 google.com Syntax: $ traceroute -6 10 google.com -F Option: Do not fragment packet.Syntax:$ traceroute -F google.com Syntax: $ traceroute -F google.com -f first_ttl Option: Start from the first_ttl hop (instead from 1).Syntax:$ traceroute -f 10 google.com Syntax: $ traceroute -f 10 google.com -g gate Option: Route the packet through gate.Syntax:$ traceroute -g 192.168.43.45 google.com Syntax: $ traceroute -g 192.168.43.45 google.com -m max_ttl Option: Set the max number of hops for the packet to reach the destination.Default value is 30.Syntax:$traceroute -m 5 google.com Syntax: $traceroute -m 5 google.com -n Option: Do not resolve IP addresses to their domain names.Syntax:$traceroute -n google.com Syntax: $traceroute -n google.com -p port Option: Set the destination port to use. Default is 33434.Syntax:$traceroute -p 20292 google.com Syntax: $traceroute -p 20292 google.com -q nqueries Option: Set the number of probes per each hop. Default is 3.Syntax:$traceroute -q 1 google.com Syntax: $traceroute -q 1 google.com packetlen Option: The full packet length. Default len is 60 byte packets.Syntax:$traceroute google.com 100 Syntax: $traceroute google.com 100 –help: Display help messages and exit.Syntax:$traceroute --help Syntax: $traceroute --help linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2019" }, { "code": null, "e": 428, "s": 52, "text": "traceroute command in Linux prints the route that a packet takes to reach the host. This command is useful when you want to know about the route and about all the hops that a packet takes. Below image depicts how traceroute command is used to reach the Google(172.217.26.206) host from the local machine and it also prints detail about all the hops that it visits in between." }, { "code": null, "e": 724, "s": 428, "text": "The first column corresponds to the hop count. The second column represents the address of that hop and after that, you see three space-separated time in milliseconds. traceroute command sends three packets to the hop and each of the time refers to the time taken by the packet to reach the hop." }, { "code": null, "e": 732, "s": 724, "text": "Syntax:" }, { "code": null, "e": 781, "s": 732, "text": "traceroute [options] host_Address [pathlength]\n" }, { "code": null, "e": 790, "s": 781, "text": "Options:" }, { "code": null, "e": 868, "s": 790, "text": "-4 Option: Use ip version 4 i.e. use IPv4Syntax:$ traceroute -4 10 google.com" }, { "code": null, "e": 876, "s": 868, "text": "Syntax:" }, { "code": null, "e": 906, "s": 876, "text": "$ traceroute -4 10 google.com" }, { "code": null, "e": 984, "s": 906, "text": "-6 Option: Use ip version 6 i.e. use IPv6Syntax:$ traceroute -6 10 google.com" }, { "code": null, "e": 992, "s": 984, "text": "Syntax:" }, { "code": null, "e": 1022, "s": 992, "text": "$ traceroute -6 10 google.com" }, { "code": null, "e": 1090, "s": 1022, "text": "-F Option: Do not fragment packet.Syntax:$ traceroute -F google.com" }, { "code": null, "e": 1098, "s": 1090, "text": "Syntax:" }, { "code": null, "e": 1125, "s": 1098, "text": "$ traceroute -F google.com" }, { "code": null, "e": 1229, "s": 1125, "text": "-f first_ttl Option: Start from the first_ttl hop (instead from 1).Syntax:$ traceroute -f 10 google.com" }, { "code": null, "e": 1237, "s": 1229, "text": "Syntax:" }, { "code": null, "e": 1267, "s": 1237, "text": "$ traceroute -f 10 google.com" }, { "code": null, "e": 1361, "s": 1267, "text": "-g gate Option: Route the packet through gate.Syntax:$ traceroute -g 192.168.43.45 google.com" }, { "code": null, "e": 1369, "s": 1361, "text": "Syntax:" }, { "code": null, "e": 1410, "s": 1369, "text": "$ traceroute -g 192.168.43.45 google.com" }, { "code": null, "e": 1552, "s": 1410, "text": "-m max_ttl Option: Set the max number of hops for the packet to reach the destination.Default value is 30.Syntax:$traceroute -m 5 google.com" }, { "code": null, "e": 1560, "s": 1552, "text": "Syntax:" }, { "code": null, "e": 1589, "s": 1560, "text": "$traceroute -m 5 google.com" }, { "code": null, "e": 1683, "s": 1589, "text": "-n Option: Do not resolve IP addresses to their domain names.Syntax:$traceroute -n google.com" }, { "code": null, "e": 1691, "s": 1683, "text": "Syntax:" }, { "code": null, "e": 1717, "s": 1691, "text": "$traceroute -n google.com" }, { "code": null, "e": 1823, "s": 1717, "text": "-p port Option: Set the destination port to use. Default is 33434.Syntax:$traceroute -p 20292 google.com" }, { "code": null, "e": 1831, "s": 1823, "text": "Syntax:" }, { "code": null, "e": 1864, "s": 1831, "text": "$traceroute -p 20292 google.com" }, { "code": null, "e": 1971, "s": 1864, "text": "-q nqueries Option: Set the number of probes per each hop. Default is 3.Syntax:$traceroute -q 1 google.com" }, { "code": null, "e": 1979, "s": 1971, "text": "Syntax:" }, { "code": null, "e": 2007, "s": 1979, "text": "$traceroute -q 1 google.com" }, { "code": null, "e": 2115, "s": 2007, "text": "packetlen Option: The full packet length. Default len is 60 byte packets.Syntax:$traceroute google.com 100" }, { "code": null, "e": 2123, "s": 2115, "text": "Syntax:" }, { "code": null, "e": 2151, "s": 2123, "text": "$traceroute google.com 100" }, { "code": null, "e": 2215, "s": 2151, "text": "–help: Display help messages and exit.Syntax:$traceroute --help" }, { "code": null, "e": 2223, "s": 2215, "text": "Syntax:" }, { "code": null, "e": 2242, "s": 2223, "text": "$traceroute --help" }, { "code": null, "e": 2256, "s": 2242, "text": "linux-command" }, { "code": null, "e": 2276, "s": 2256, "text": "Linux-misc-commands" }, { "code": null, "e": 2283, "s": 2276, "text": "Picked" }, { "code": null, "e": 2294, "s": 2283, "text": "Linux-Unix" } ]
Java Program to Illustrate a Method with 2 Parameters and without Return Type
07 Feb, 2022 Function without return type stands for a void function. The void function may take multiple or zero parameters and returns nothing. Here, we are going to define a method which takes 2 parameters and doesn’t return anything. Syntax: public static void function(int a, int b) Example: public static void fun1(String 1, String 2){ // method execution code }; Approach: Take 2 inputs into two variables.Pass these inputs as an argument to the function.Display the sum from this defined function. Take 2 inputs into two variables. Pass these inputs as an argument to the function. Display the sum from this defined function. Code: Java // Java Program to Illustrate a Method// with 2 Parameters and without Return Typeimport java.util.*;public class Main { public static void main(String args[]) { int a = 4; int b = 5; // Calling the function with 2 parameters calc(a, b); } public static void calc(int x, int y) { int sum = x + y; // Displaying the sum System.out.print("Sum of two numbers is :" + sum); }} Sum of two numbers is :9 sumitgumber28 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Feb, 2022" }, { "code": null, "e": 253, "s": 28, "text": "Function without return type stands for a void function. The void function may take multiple or zero parameters and returns nothing. Here, we are going to define a method which takes 2 parameters and doesn’t return anything." }, { "code": null, "e": 261, "s": 253, "text": "Syntax:" }, { "code": null, "e": 303, "s": 261, "text": "public static void function(int a, int b)" }, { "code": null, "e": 313, "s": 303, "text": "Example: " }, { "code": null, "e": 390, "s": 313, "text": "public static void fun1(String 1, String 2){\n // method execution code\n};" }, { "code": null, "e": 400, "s": 390, "text": "Approach:" }, { "code": null, "e": 526, "s": 400, "text": "Take 2 inputs into two variables.Pass these inputs as an argument to the function.Display the sum from this defined function." }, { "code": null, "e": 560, "s": 526, "text": "Take 2 inputs into two variables." }, { "code": null, "e": 610, "s": 560, "text": "Pass these inputs as an argument to the function." }, { "code": null, "e": 654, "s": 610, "text": "Display the sum from this defined function." }, { "code": null, "e": 660, "s": 654, "text": "Code:" }, { "code": null, "e": 665, "s": 660, "text": "Java" }, { "code": "// Java Program to Illustrate a Method// with 2 Parameters and without Return Typeimport java.util.*;public class Main { public static void main(String args[]) { int a = 4; int b = 5; // Calling the function with 2 parameters calc(a, b); } public static void calc(int x, int y) { int sum = x + y; // Displaying the sum System.out.print(\"Sum of two numbers is :\" + sum); }}", "e": 1106, "s": 665, "text": null }, { "code": null, "e": 1134, "s": 1109, "text": "Sum of two numbers is :9" }, { "code": null, "e": 1150, "s": 1136, "text": "sumitgumber28" }, { "code": null, "e": 1157, "s": 1150, "text": "Picked" }, { "code": null, "e": 1162, "s": 1157, "text": "Java" }, { "code": null, "e": 1176, "s": 1162, "text": "Java Programs" }, { "code": null, "e": 1181, "s": 1176, "text": "Java" } ]
Ways to color a 3*N board using 4 colors
23 May, 2022 Given a 3 X n board, find the number of ways to color it using at most 4 colors such that no two adjacent boxes have the same color. Diagonal neighbors are not treated as adjacent boxes. Output the ways%1000000007 as the answer grows quickly.Constraints: 1<= n < 100000Examples : Input : 1 Output : 36 We can use either a combination of 3 colors or 2 colors. Now, choosing 3 colors out of 4 is and arranging them in 3! ways, similarly choosing 2 colors out of 4 is and while arrangingwe can only choose which of them could be at centre, that would be 2 ways. Answer = *3! + *2! = 36Input : 2Output : 588 We are going to solve this using dynamic approach because when a new column is added to the board, the ways in which colors are going to be filled depends just upon the color pattern in the current column. We can only have a combination of two colors and three colors in a column. All possible new columns that can be generated is given in the image. Please consider A, B, C and D as 4 colors. All possible color combinations that can be generated from current column. From now, we will refer 3 colors combination for a Nth column of the 3*N board as W(n) and two colors as Y(n). We can see that each W can generate 5Y and 11W, and each Y can generate 7Y and 10W. We get two equation from here We have two equations now, W(n+1) = 10*Y(n)+11*W(n); Y(n+1) = 7*Y(n)+5*W(n); C++ Java Python3 C# PHP Javascript // C++ program to find number of ways// to color a 3 x n grid using 4 colors// such that no two adjacent have same// color#include <iostream>using namespace std; int solve(int A){ // When we to fill single column long int color3 = 24; long int color2 = 12; long int temp = 0; for (int i = 2; i <= A; i++) { temp = color3; color3 = (11 * color3 + 10 * color2 ) % 1000000007; color2 = ( 5 * temp + 7 * color2 ) % 1000000007; } long num = (color3 + color2) % 1000000007; return (int)num;} // Driver codeint main(){ int num1 = 1; cout << solve(num1) << endl; int num2 = 2; cout << solve(num2) << endl; int num3 = 500; cout << solve(num3) << endl; int num4 = 10000; cout << solve(num4); return 0;} // This code is contributed by vt_m. // Java program to find number of ways to color// a 3 x n grid using 4 colors such that no two// adjacent have same color.public class Solution { public static int solve(int A) { long color3 = 24; // When we to fill single column long color2 = 12; long temp = 0; for (int i = 2; i <= A; i++) { long temp = color3; color3 = (11 * color3 + 10 * color2 ) % 1000000007; color2 = ( 5 * temp + 7 * color2 ) % 1000000007; } long num = (color3 + color2) % 1000000007; return (int)num; } // Driver code public static void main(String[] args) { int num1 = 1; System.out.println(solve(num1)); int num2 = 2; System.out.println(solve(num2)); int num3 = 500; System.out.println(solve(num3)); int num4 = 10000; System.out.println(solve(num4)); }} # Python 3 program to find number of ways# to color a 3 x n grid using 4 colors# such that no two adjacent have same# color def solve(A): # When we to fill single column color3 = 24 color2 = 12 temp = 0 for i in range(2, A + 1, 1): temp = color3 color3 = (11 * color3 + 10 * color2 ) % 1000000007 color2 = ( 5 * temp + 7 * color2 ) % 1000000007 num = (color3 + color2) % 1000000007 return num # Driver codeif __name__ == '__main__': num1 = 1 print(solve(num1)) num2 = 2 print(solve(num2)) num3 = 500 print(solve(num3)) num4 = 10000 print(solve(num4)) # This code is contributed by# Shashank_Sharma // C# program to find number of ways// to color a 3 x n grid using 4// colors such that no two adjacent// have same color.using System; public class GFG { public static int solve(int A) { // When we to fill single column long color3 = 24; long color2 = 12; long temp = 0; for (int i = 2; i <= A; i++) { temp = color3; color3 = (11 * color3 + 10 * color2 ) % 1000000007; color2 = ( 5 * temp + 7 * color2 ) % 1000000007; } long num = (color3 + color2) % 1000000007; return (int)num; } // Driver code public static void Main() { int num1 = 1; Console.WriteLine(solve(num1)); int num2 = 2; Console.WriteLine(solve(num2)); int num3 = 500; Console.WriteLine(solve(num3)); int num4 = 10000; Console.WriteLine(solve(num4)); }} // This code is contributed by vt_m. <?php// PHP program to find number of ways// to color a 3 x n grid using 4 colors// such that no two adjacent have same// colorfunction solve($A){ // When we to fill single column $color3 = 24; $color2 = 12; $temp = 0; for ($i = 2; $i <= $A; $i++) { $temp = $color3; $color3 = (11 * $color3 + 10 * $color2 ) % 1000000007; $color2 = ( 5 * $temp + 7 * $color2 ) % 1000000007; } $num = ($color3 + $color2) % 1000000007; return (int)$num;} // Driver code$num1 = 1;echo solve($num1) ,"\n"; $num2 = 2;echo solve($num2) ,"\n"; $num3 = 500;echo solve($num3),"\n"; $num4 = 10000;echo solve($num4); // This code is contributed by m_kit.?> <script>// JavaScript program to find number of ways to color// a 3 x n grid using 4 colors such that no two// adjacent have same color. function solve(A) { let color3 = 24; // When we to fill single column let color2 = 12; let temp = 0; for (let i = 2; i <= A; i++) { let temp = color3; color3 = (11 * color3 + 10 * color2 ) % 1000000007; color2 = ( 5 * temp + 7 * color2 ) % 1000000007; } let num = (color3 + color2) % 1000000007; return num; } // Driver Code let num1 = 1; document.write(solve(num1) + "<br/>"); let num2 = 2; document.write(solve(num2) + "<br/>"); let num3 = 500; document.write(solve(num3) + "<br/>"); let num4 = 10000; document.write(solve(num4)); </script> Output : 36 588 178599516 540460643 Time Complexity: O(N), where number of rows = 3 and number of columns = N of the board. Auxiliary Space: O(1), no extra space required so it is a constant.This article is contributed by Panshul Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jit_t Shashank_Sharma code_hunt samim2000 Combinatorial Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 May, 2022" }, { "code": null, "e": 334, "s": 52, "text": "Given a 3 X n board, find the number of ways to color it using at most 4 colors such that no two adjacent boxes have the same color. Diagonal neighbors are not treated as adjacent boxes. Output the ways%1000000007 as the answer grows quickly.Constraints: 1<= n < 100000Examples : " }, { "code": null, "e": 661, "s": 334, "text": "Input : 1\nOutput : 36\nWe can use either a combination of 3 colors\nor 2 colors. Now, choosing 3 colors out of \n4 is and arranging them in 3! ways, similarly choosing 2 colors out of 4 is and while arrangingwe can only choose which of them could be at centre, that would be 2 ways. Answer = *3! + *2! = 36Input : 2Output : 588" }, { "code": null, "e": 1059, "s": 663, "text": "We are going to solve this using dynamic approach because when a new column is added to the board, the ways in which colors are going to be filled depends just upon the color pattern in the current column. We can only have a combination of two colors and three colors in a column. All possible new columns that can be generated is given in the image. Please consider A, B, C and D as 4 colors. " }, { "code": null, "e": 1134, "s": 1059, "text": "All possible color combinations that can be generated from current column." }, { "code": null, "e": 1388, "s": 1134, "text": "From now, we will refer 3 colors combination for a Nth column of the 3*N board as W(n) and two colors as Y(n). We can see that each W can generate 5Y and 11W, and each Y can generate 7Y and 10W. We get two equation from here We have two equations now, " }, { "code": null, "e": 1438, "s": 1388, "text": "W(n+1) = 10*Y(n)+11*W(n);\nY(n+1) = 7*Y(n)+5*W(n);" }, { "code": null, "e": 1444, "s": 1440, "text": "C++" }, { "code": null, "e": 1449, "s": 1444, "text": "Java" }, { "code": null, "e": 1457, "s": 1449, "text": "Python3" }, { "code": null, "e": 1460, "s": 1457, "text": "C#" }, { "code": null, "e": 1464, "s": 1460, "text": "PHP" }, { "code": null, "e": 1475, "s": 1464, "text": "Javascript" }, { "code": "// C++ program to find number of ways// to color a 3 x n grid using 4 colors// such that no two adjacent have same// color#include <iostream>using namespace std; int solve(int A){ // When we to fill single column long int color3 = 24; long int color2 = 12; long int temp = 0; for (int i = 2; i <= A; i++) { temp = color3; color3 = (11 * color3 + 10 * color2 ) % 1000000007; color2 = ( 5 * temp + 7 * color2 ) % 1000000007; } long num = (color3 + color2) % 1000000007; return (int)num;} // Driver codeint main(){ int num1 = 1; cout << solve(num1) << endl; int num2 = 2; cout << solve(num2) << endl; int num3 = 500; cout << solve(num3) << endl; int num4 = 10000; cout << solve(num4); return 0;} // This code is contributed by vt_m.", "e": 2394, "s": 1475, "text": null }, { "code": "// Java program to find number of ways to color// a 3 x n grid using 4 colors such that no two// adjacent have same color.public class Solution { public static int solve(int A) { long color3 = 24; // When we to fill single column long color2 = 12; long temp = 0; for (int i = 2; i <= A; i++) { long temp = color3; color3 = (11 * color3 + 10 * color2 ) % 1000000007; color2 = ( 5 * temp + 7 * color2 ) % 1000000007; } long num = (color3 + color2) % 1000000007; return (int)num; } // Driver code public static void main(String[] args) { int num1 = 1; System.out.println(solve(num1)); int num2 = 2; System.out.println(solve(num2)); int num3 = 500; System.out.println(solve(num3)); int num4 = 10000; System.out.println(solve(num4)); }}", "e": 3300, "s": 2394, "text": null }, { "code": "# Python 3 program to find number of ways# to color a 3 x n grid using 4 colors# such that no two adjacent have same# color def solve(A): # When we to fill single column color3 = 24 color2 = 12 temp = 0 for i in range(2, A + 1, 1): temp = color3 color3 = (11 * color3 + 10 * color2 ) % 1000000007 color2 = ( 5 * temp + 7 * color2 ) % 1000000007 num = (color3 + color2) % 1000000007 return num # Driver codeif __name__ == '__main__': num1 = 1 print(solve(num1)) num2 = 2 print(solve(num2)) num3 = 500 print(solve(num3)) num4 = 10000 print(solve(num4)) # This code is contributed by# Shashank_Sharma", "e": 4032, "s": 3300, "text": null }, { "code": "// C# program to find number of ways// to color a 3 x n grid using 4// colors such that no two adjacent// have same color.using System; public class GFG { public static int solve(int A) { // When we to fill single column long color3 = 24; long color2 = 12; long temp = 0; for (int i = 2; i <= A; i++) { temp = color3; color3 = (11 * color3 + 10 * color2 ) % 1000000007; color2 = ( 5 * temp + 7 * color2 ) % 1000000007; } long num = (color3 + color2) % 1000000007; return (int)num; } // Driver code public static void Main() { int num1 = 1; Console.WriteLine(solve(num1)); int num2 = 2; Console.WriteLine(solve(num2)); int num3 = 500; Console.WriteLine(solve(num3)); int num4 = 10000; Console.WriteLine(solve(num4)); }} // This code is contributed by vt_m.", "e": 5065, "s": 4032, "text": null }, { "code": "<?php// PHP program to find number of ways// to color a 3 x n grid using 4 colors// such that no two adjacent have same// colorfunction solve($A){ // When we to fill single column $color3 = 24; $color2 = 12; $temp = 0; for ($i = 2; $i <= $A; $i++) { $temp = $color3; $color3 = (11 * $color3 + 10 * $color2 ) % 1000000007; $color2 = ( 5 * $temp + 7 * $color2 ) % 1000000007; } $num = ($color3 + $color2) % 1000000007; return (int)$num;} // Driver code$num1 = 1;echo solve($num1) ,\"\\n\"; $num2 = 2;echo solve($num2) ,\"\\n\"; $num3 = 500;echo solve($num3),\"\\n\"; $num4 = 10000;echo solve($num4); // This code is contributed by m_kit.?>", "e": 5889, "s": 5065, "text": null }, { "code": "<script>// JavaScript program to find number of ways to color// a 3 x n grid using 4 colors such that no two// adjacent have same color. function solve(A) { let color3 = 24; // When we to fill single column let color2 = 12; let temp = 0; for (let i = 2; i <= A; i++) { let temp = color3; color3 = (11 * color3 + 10 * color2 ) % 1000000007; color2 = ( 5 * temp + 7 * color2 ) % 1000000007; } let num = (color3 + color2) % 1000000007; return num; } // Driver Code let num1 = 1; document.write(solve(num1) + \"<br/>\"); let num2 = 2; document.write(solve(num2) + \"<br/>\"); let num3 = 500; document.write(solve(num3) + \"<br/>\"); let num4 = 10000; document.write(solve(num4)); </script>", "e": 6755, "s": 5889, "text": null }, { "code": null, "e": 6766, "s": 6755, "text": "Output : " }, { "code": null, "e": 6793, "s": 6766, "text": "36\n588\n178599516\n540460643" }, { "code": null, "e": 6881, "s": 6793, "text": "Time Complexity: O(N), where number of rows = 3 and number of columns = N of the board." }, { "code": null, "e": 7374, "s": 6881, "text": "Auxiliary Space: O(1), no extra space required so it is a constant.This article is contributed by Panshul Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7379, "s": 7374, "text": "vt_m" }, { "code": null, "e": 7385, "s": 7379, "text": "jit_t" }, { "code": null, "e": 7401, "s": 7385, "text": "Shashank_Sharma" }, { "code": null, "e": 7411, "s": 7401, "text": "code_hunt" }, { "code": null, "e": 7421, "s": 7411, "text": "samim2000" }, { "code": null, "e": 7435, "s": 7421, "text": "Combinatorial" }, { "code": null, "e": 7449, "s": 7435, "text": "Combinatorial" } ]
Version Control in Project
16 Apr, 2020 The procedures and tools are combined by the version control to manage different versions of configuration items that are created during the software engineering process. A version of the software is a collection of software configuration items (source code, documents, data). Each version may be consist of different variants. Version control activity is divided in four sub-activities- Identifying New Versions :A software configuration item (SCI) will receive a new version number when its baseline has changed. Each previous version will be stored in a compatible directory like version 0, version 1, version 2 etc.Numbering Scheme :The numbering scheme will have the following format-version X.Y.Z .... The first letter (X) denotes the entire SCI. Therefore, changes made to the entire configuration item, or changes large enough to warrant a completely new release of the item, will cause the first digit to increase.The second letter (Y) Denotes a component of the SCI. This digit will sequentially increase if a change is made to a component or small changes to multiple components.The third letter (Z) denotes a section of the component of a SCI. This number will only be visible if a component of an be divided into individual sections. Changes made at this level of detail will need a sequential change of the third digit.Visibility :The version number can be viewed in a frame, or below the title. The decision for this depends on the decision of the group to code all documents for a frame enabled browser or allow for a non-frame enabled browser.In either case, the number will always be made available.Tracking :The best way to keep track of the different versions list is with the version development graph shown in figure.For example, if we required to keep track of every updated project schedule then we could assign a version number each time a change was made. Identifying New Versions :A software configuration item (SCI) will receive a new version number when its baseline has changed. Each previous version will be stored in a compatible directory like version 0, version 1, version 2 etc. Numbering Scheme :The numbering scheme will have the following format-version X.Y.Z .... The first letter (X) denotes the entire SCI. Therefore, changes made to the entire configuration item, or changes large enough to warrant a completely new release of the item, will cause the first digit to increase.The second letter (Y) Denotes a component of the SCI. This digit will sequentially increase if a change is made to a component or small changes to multiple components.The third letter (Z) denotes a section of the component of a SCI. This number will only be visible if a component of an be divided into individual sections. Changes made at this level of detail will need a sequential change of the third digit. version X.Y.Z .... The first letter (X) denotes the entire SCI. Therefore, changes made to the entire configuration item, or changes large enough to warrant a completely new release of the item, will cause the first digit to increase. The second letter (Y) Denotes a component of the SCI. This digit will sequentially increase if a change is made to a component or small changes to multiple components. The third letter (Z) denotes a section of the component of a SCI. This number will only be visible if a component of an be divided into individual sections. Changes made at this level of detail will need a sequential change of the third digit. Visibility :The version number can be viewed in a frame, or below the title. The decision for this depends on the decision of the group to code all documents for a frame enabled browser or allow for a non-frame enabled browser.In either case, the number will always be made available. Tracking :The best way to keep track of the different versions list is with the version development graph shown in figure.For example, if we required to keep track of every updated project schedule then we could assign a version number each time a change was made. For example, if we required to keep track of every updated project schedule then we could assign a version number each time a change was made. Software Engineering Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Apr, 2020" }, { "code": null, "e": 199, "s": 28, "text": "The procedures and tools are combined by the version control to manage different versions of configuration items that are created during the software engineering process." }, { "code": null, "e": 416, "s": 199, "text": "A version of the software is a collection of software configuration items (source code, documents, data). Each version may be consist of different variants. Version control activity is divided in four sub-activities-" }, { "code": null, "e": 1910, "s": 416, "text": "Identifying New Versions :A software configuration item (SCI) will receive a new version number when its baseline has changed. Each previous version will be stored in a compatible directory like version 0, version 1, version 2 etc.Numbering Scheme :The numbering scheme will have the following format-version X.Y.Z .... The first letter (X) denotes the entire SCI. Therefore, changes made to the entire configuration item, or changes large enough to warrant a completely new release of the item, will cause the first digit to increase.The second letter (Y) Denotes a component of the SCI. This digit will sequentially increase if a change is made to a component or small changes to multiple components.The third letter (Z) denotes a section of the component of a SCI. This number will only be visible if a component of an be divided into individual sections. Changes made at this level of detail will need a sequential change of the third digit.Visibility :The version number can be viewed in a frame, or below the title. The decision for this depends on the decision of the group to code all documents for a frame enabled browser or allow for a non-frame enabled browser.In either case, the number will always be made available.Tracking :The best way to keep track of the different versions list is with the version development graph shown in figure.For example, if we required to keep track of every updated project schedule then we could assign a version number each time a change was made." }, { "code": null, "e": 2142, "s": 1910, "text": "Identifying New Versions :A software configuration item (SCI) will receive a new version number when its baseline has changed. Each previous version will be stored in a compatible directory like version 0, version 1, version 2 etc." }, { "code": null, "e": 2857, "s": 2142, "text": "Numbering Scheme :The numbering scheme will have the following format-version X.Y.Z .... The first letter (X) denotes the entire SCI. Therefore, changes made to the entire configuration item, or changes large enough to warrant a completely new release of the item, will cause the first digit to increase.The second letter (Y) Denotes a component of the SCI. This digit will sequentially increase if a change is made to a component or small changes to multiple components.The third letter (Z) denotes a section of the component of a SCI. This number will only be visible if a component of an be divided into individual sections. Changes made at this level of detail will need a sequential change of the third digit." }, { "code": null, "e": 2877, "s": 2857, "text": "version X.Y.Z .... " }, { "code": null, "e": 3093, "s": 2877, "text": "The first letter (X) denotes the entire SCI. Therefore, changes made to the entire configuration item, or changes large enough to warrant a completely new release of the item, will cause the first digit to increase." }, { "code": null, "e": 3261, "s": 3093, "text": "The second letter (Y) Denotes a component of the SCI. This digit will sequentially increase if a change is made to a component or small changes to multiple components." }, { "code": null, "e": 3505, "s": 3261, "text": "The third letter (Z) denotes a section of the component of a SCI. This number will only be visible if a component of an be divided into individual sections. Changes made at this level of detail will need a sequential change of the third digit." }, { "code": null, "e": 3790, "s": 3505, "text": "Visibility :The version number can be viewed in a frame, or below the title. The decision for this depends on the decision of the group to code all documents for a frame enabled browser or allow for a non-frame enabled browser.In either case, the number will always be made available." }, { "code": null, "e": 4055, "s": 3790, "text": "Tracking :The best way to keep track of the different versions list is with the version development graph shown in figure.For example, if we required to keep track of every updated project schedule then we could assign a version number each time a change was made." }, { "code": null, "e": 4198, "s": 4055, "text": "For example, if we required to keep track of every updated project schedule then we could assign a version number each time a change was made." }, { "code": null, "e": 4219, "s": 4198, "text": "Software Engineering" }, { "code": null, "e": 4235, "s": 4219, "text": "Write From Home" } ]
du command in Linux with examples
17 Oct, 2019 du command, short for disk usage, is used to estimate file space usage.The du command can be used to track the files and directories which are consuming excessive amount of space on hard disk drive. Syntax : du [OPTION]... [FILE]... du [OPTION]... --files0-from=F Examples : du /home/mandeep/test Output: 44 /home/mandeep/test/data 2012 /home/mandeep/test/system design 24 /home/mandeep/test/table/sample_table/tree 28 /home/mandeep/test/table/sample_table 32 /home/mandeep/test/table 100104 /home/mandeep/test Options : -0, –null : end each output line with NULL-a, –all : write count of all files, not just directories–apparent-size : print apparent sizes, rather than disk usage.-B, –block-size=SIZE : scale sizes to SIZE before printing on console-c, –total : produce grand total-d, –max-depth=N : print total for directory only if it is N or fewer levels below command line argument-h, –human-readable : print sizes in human readable format-S, -separate-dirs : for directories, don’t include size of subdirectories-s, –summarize : display only total for each directory–time : show time of last modification of any file or directory.–exclude=PATTERN : exclude files that match PATTERN Command usage examples with options : If we want to print sizes in human readable format(K, M, G), use -h optiondu -h /home/mandeep/test Output: 44K /home/mandeep/test/data 2.0M /home/mandeep/test/system design 24K /home/mandeep/test/table/sample_table/tree 28K /home/mandeep/test/table/sample_table 32K /home/mandeep/test/table 98M /home/mandeep/test Use -a option for printing all files including directories.du -a -h /home/mandeep/test Output:This is partial output of above command.4.0K /home/mandeep/test/blah1-new 4.0K /home/mandeep/test/fbtest.py 8.0K /home/mandeep/test/data/4.txt 4.0K /home/mandeep/test/data/7.txt 4.0K /home/mandeep/test/data/1.txt 4.0K /home/mandeep/test/data/3.txt 4.0K /home/mandeep/test/data/6.txt 4.0K /home/mandeep/test/data/2.txt 4.0K /home/mandeep/test/data/8.txt 8.0K /home/mandeep/test/data/5.txt 44K /home/mandeep/test/data 4.0K /home/mandeep/test/notifier.py Use -c option to print total sizedu -c -h /home/mandeep/test Output:44K /home/mandeep/test/data 2.0M /home/mandeep/test/system design 24K /home/mandeep/test/table/sample_table/tree 28K /home/mandeep/test/table/sample_table 32K /home/mandeep/test/table 98M /home/mandeep/test 98M total To print sizes till particular level, use -d option with level no.du -d 1 /home/mandeep/test Output:44 /home/mandeep/test/data 2012 /home/mandeep/test/system design 32 /home/mandeep/test/table 100104 /home/mandeep/test Now try with level 2, you will get some extra directoriesdu -d 2 /home/mandeep/test Output:44 /home/mandeep/test/data 2012 /home/mandeep/test/system design 28 /home/mandeep/test/table/sample_table 32 /home/mandeep/test/table 100104 /home/mandeep/test Get summary of file system using -s optiondu -s /home/mandeep/test Output:100104 /home/mandeep/test Get the timestamp of last modified using --time optiondu --time -h /home/mandeep/test Output:44K 2018-01-14 22:22 /home/mandeep/test/data 2.0M 2017-12-24 23:06 /home/mandeep/test/system design 24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree 28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table 32K 2017-12-30 10:20 /home/mandeep/test/table 98M 2018-02-02 17:32 /home/mandeep/test If we want to print sizes in human readable format(K, M, G), use -h optiondu -h /home/mandeep/test Output: 44K /home/mandeep/test/data 2.0M /home/mandeep/test/system design 24K /home/mandeep/test/table/sample_table/tree 28K /home/mandeep/test/table/sample_table 32K /home/mandeep/test/table 98M /home/mandeep/test du -h /home/mandeep/test Output: 44K /home/mandeep/test/data 2.0M /home/mandeep/test/system design 24K /home/mandeep/test/table/sample_table/tree 28K /home/mandeep/test/table/sample_table 32K /home/mandeep/test/table 98M /home/mandeep/test 44K /home/mandeep/test/data 2.0M /home/mandeep/test/system design 24K /home/mandeep/test/table/sample_table/tree 28K /home/mandeep/test/table/sample_table 32K /home/mandeep/test/table 98M /home/mandeep/test Use -a option for printing all files including directories.du -a -h /home/mandeep/test Output:This is partial output of above command.4.0K /home/mandeep/test/blah1-new 4.0K /home/mandeep/test/fbtest.py 8.0K /home/mandeep/test/data/4.txt 4.0K /home/mandeep/test/data/7.txt 4.0K /home/mandeep/test/data/1.txt 4.0K /home/mandeep/test/data/3.txt 4.0K /home/mandeep/test/data/6.txt 4.0K /home/mandeep/test/data/2.txt 4.0K /home/mandeep/test/data/8.txt 8.0K /home/mandeep/test/data/5.txt 44K /home/mandeep/test/data 4.0K /home/mandeep/test/notifier.py du -a -h /home/mandeep/test Output:This is partial output of above command. 4.0K /home/mandeep/test/blah1-new 4.0K /home/mandeep/test/fbtest.py 8.0K /home/mandeep/test/data/4.txt 4.0K /home/mandeep/test/data/7.txt 4.0K /home/mandeep/test/data/1.txt 4.0K /home/mandeep/test/data/3.txt 4.0K /home/mandeep/test/data/6.txt 4.0K /home/mandeep/test/data/2.txt 4.0K /home/mandeep/test/data/8.txt 8.0K /home/mandeep/test/data/5.txt 44K /home/mandeep/test/data 4.0K /home/mandeep/test/notifier.py Use -c option to print total sizedu -c -h /home/mandeep/test Output:44K /home/mandeep/test/data 2.0M /home/mandeep/test/system design 24K /home/mandeep/test/table/sample_table/tree 28K /home/mandeep/test/table/sample_table 32K /home/mandeep/test/table 98M /home/mandeep/test 98M total du -c -h /home/mandeep/test Output: 44K /home/mandeep/test/data 2.0M /home/mandeep/test/system design 24K /home/mandeep/test/table/sample_table/tree 28K /home/mandeep/test/table/sample_table 32K /home/mandeep/test/table 98M /home/mandeep/test 98M total To print sizes till particular level, use -d option with level no.du -d 1 /home/mandeep/test Output:44 /home/mandeep/test/data 2012 /home/mandeep/test/system design 32 /home/mandeep/test/table 100104 /home/mandeep/test Now try with level 2, you will get some extra directoriesdu -d 2 /home/mandeep/test Output:44 /home/mandeep/test/data 2012 /home/mandeep/test/system design 28 /home/mandeep/test/table/sample_table 32 /home/mandeep/test/table 100104 /home/mandeep/test du -d 1 /home/mandeep/test Output: 44 /home/mandeep/test/data 2012 /home/mandeep/test/system design 32 /home/mandeep/test/table 100104 /home/mandeep/test Now try with level 2, you will get some extra directories du -d 2 /home/mandeep/test Output: 44 /home/mandeep/test/data 2012 /home/mandeep/test/system design 28 /home/mandeep/test/table/sample_table 32 /home/mandeep/test/table 100104 /home/mandeep/test Get summary of file system using -s optiondu -s /home/mandeep/test Output:100104 /home/mandeep/test du -s /home/mandeep/test Output: 100104 /home/mandeep/test Get the timestamp of last modified using --time optiondu --time -h /home/mandeep/test Output:44K 2018-01-14 22:22 /home/mandeep/test/data 2.0M 2017-12-24 23:06 /home/mandeep/test/system design 24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree 28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table 32K 2017-12-30 10:20 /home/mandeep/test/table 98M 2018-02-02 17:32 /home/mandeep/test du --time -h /home/mandeep/test Output: 44K 2018-01-14 22:22 /home/mandeep/test/data 2.0M 2017-12-24 23:06 /home/mandeep/test/system design 24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree 28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table 32K 2017-12-30 10:20 /home/mandeep/test/table 98M 2018-02-02 17:32 /home/mandeep/test - Mandeep Singh References :1) du wikipedia2) du man entry Akanksha_Rai linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Oct, 2019" }, { "code": null, "e": 251, "s": 52, "text": "du command, short for disk usage, is used to estimate file space usage.The du command can be used to track the files and directories which are consuming excessive amount of space on hard disk drive." }, { "code": null, "e": 260, "s": 251, "text": "Syntax :" }, { "code": null, "e": 317, "s": 260, "text": "du [OPTION]... [FILE]...\ndu [OPTION]... --files0-from=F\n" }, { "code": null, "e": 328, "s": 317, "text": "Examples :" }, { "code": null, "e": 351, "s": 328, "text": "du /home/mandeep/test\n" }, { "code": null, "e": 359, "s": 351, "text": "Output:" }, { "code": null, "e": 584, "s": 359, "text": "44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n24 /home/mandeep/test/table/sample_table/tree\n28 /home/mandeep/test/table/sample_table\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n" }, { "code": null, "e": 594, "s": 584, "text": "Options :" }, { "code": null, "e": 1262, "s": 594, "text": "-0, –null : end each output line with NULL-a, –all : write count of all files, not just directories–apparent-size : print apparent sizes, rather than disk usage.-B, –block-size=SIZE : scale sizes to SIZE before printing on console-c, –total : produce grand total-d, –max-depth=N : print total for directory only if it is N or fewer levels below command line argument-h, –human-readable : print sizes in human readable format-S, -separate-dirs : for directories, don’t include size of subdirectories-s, –summarize : display only total for each directory–time : show time of last modification of any file or directory.–exclude=PATTERN : exclude files that match PATTERN" }, { "code": null, "e": 1300, "s": 1262, "text": "Command usage examples with options :" }, { "code": null, "e": 3561, "s": 1300, "text": "If we want to print sizes in human readable format(K, M, G), use -h optiondu -h /home/mandeep/test \n\nOutput:\n44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\nUse -a option for printing all files including directories.du -a -h /home/mandeep/test\nOutput:This is partial output of above command.4.0K /home/mandeep/test/blah1-new\n4.0K /home/mandeep/test/fbtest.py\n8.0K /home/mandeep/test/data/4.txt\n4.0K /home/mandeep/test/data/7.txt\n4.0K /home/mandeep/test/data/1.txt\n4.0K /home/mandeep/test/data/3.txt\n4.0K /home/mandeep/test/data/6.txt\n4.0K /home/mandeep/test/data/2.txt\n4.0K /home/mandeep/test/data/8.txt\n8.0K /home/mandeep/test/data/5.txt\n44K /home/mandeep/test/data\n4.0K /home/mandeep/test/notifier.py\nUse -c option to print total sizedu -c -h /home/mandeep/test\nOutput:44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n98M total\nTo print sizes till particular level, use -d option with level no.du -d 1 /home/mandeep/test\nOutput:44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\nNow try with level 2, you will get some extra directoriesdu -d 2 /home/mandeep/test\nOutput:44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n28 /home/mandeep/test/table/sample_table\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\nGet summary of file system using -s optiondu -s /home/mandeep/test\nOutput:100104 /home/mandeep/test\nGet the timestamp of last modified using --time optiondu --time -h /home/mandeep/test\nOutput:44K 2018-01-14 22:22 /home/mandeep/test/data\n2.0M 2017-12-24 23:06 /home/mandeep/test/system design\n24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree\n28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table\n32K 2017-12-30 10:20 /home/mandeep/test/table\n98M 2018-02-02 17:32 /home/mandeep/test\n" }, { "code": null, "e": 3896, "s": 3561, "text": "If we want to print sizes in human readable format(K, M, G), use -h optiondu -h /home/mandeep/test \n\nOutput:\n44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n" }, { "code": null, "e": 4157, "s": 3896, "text": "du -h /home/mandeep/test \n\nOutput:\n44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n" }, { "code": null, "e": 4383, "s": 4157, "text": "44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n" }, { "code": null, "e": 4966, "s": 4383, "text": "Use -a option for printing all files including directories.du -a -h /home/mandeep/test\nOutput:This is partial output of above command.4.0K /home/mandeep/test/blah1-new\n4.0K /home/mandeep/test/fbtest.py\n8.0K /home/mandeep/test/data/4.txt\n4.0K /home/mandeep/test/data/7.txt\n4.0K /home/mandeep/test/data/1.txt\n4.0K /home/mandeep/test/data/3.txt\n4.0K /home/mandeep/test/data/6.txt\n4.0K /home/mandeep/test/data/2.txt\n4.0K /home/mandeep/test/data/8.txt\n8.0K /home/mandeep/test/data/5.txt\n44K /home/mandeep/test/data\n4.0K /home/mandeep/test/notifier.py\n" }, { "code": null, "e": 4995, "s": 4966, "text": "du -a -h /home/mandeep/test\n" }, { "code": null, "e": 5043, "s": 4995, "text": "Output:This is partial output of above command." }, { "code": null, "e": 5492, "s": 5043, "text": "4.0K /home/mandeep/test/blah1-new\n4.0K /home/mandeep/test/fbtest.py\n8.0K /home/mandeep/test/data/4.txt\n4.0K /home/mandeep/test/data/7.txt\n4.0K /home/mandeep/test/data/1.txt\n4.0K /home/mandeep/test/data/3.txt\n4.0K /home/mandeep/test/data/6.txt\n4.0K /home/mandeep/test/data/2.txt\n4.0K /home/mandeep/test/data/8.txt\n8.0K /home/mandeep/test/data/5.txt\n44K /home/mandeep/test/data\n4.0K /home/mandeep/test/notifier.py\n" }, { "code": null, "e": 5799, "s": 5492, "text": "Use -c option to print total sizedu -c -h /home/mandeep/test\nOutput:44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n98M total\n" }, { "code": null, "e": 5828, "s": 5799, "text": "du -c -h /home/mandeep/test\n" }, { "code": null, "e": 5836, "s": 5828, "text": "Output:" }, { "code": null, "e": 6075, "s": 5836, "text": "44K /home/mandeep/test/data\n2.0M /home/mandeep/test/system design\n24K /home/mandeep/test/table/sample_table/tree\n28K /home/mandeep/test/table/sample_table\n32K /home/mandeep/test/table\n98M /home/mandeep/test\n98M total\n" }, { "code": null, "e": 6573, "s": 6075, "text": "To print sizes till particular level, use -d option with level no.du -d 1 /home/mandeep/test\nOutput:44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\nNow try with level 2, you will get some extra directoriesdu -d 2 /home/mandeep/test\nOutput:44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n28 /home/mandeep/test/table/sample_table\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n" }, { "code": null, "e": 6601, "s": 6573, "text": "du -d 1 /home/mandeep/test\n" }, { "code": null, "e": 6609, "s": 6601, "text": "Output:" }, { "code": null, "e": 6741, "s": 6609, "text": "44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n" }, { "code": null, "e": 6799, "s": 6741, "text": "Now try with level 2, you will get some extra directories" }, { "code": null, "e": 6827, "s": 6799, "text": "du -d 2 /home/mandeep/test\n" }, { "code": null, "e": 6835, "s": 6827, "text": "Output:" }, { "code": null, "e": 7011, "s": 6835, "text": "44 /home/mandeep/test/data\n2012 /home/mandeep/test/system design\n28 /home/mandeep/test/table/sample_table\n32 /home/mandeep/test/table\n100104 /home/mandeep/test\n" }, { "code": null, "e": 7115, "s": 7011, "text": "Get summary of file system using -s optiondu -s /home/mandeep/test\nOutput:100104 /home/mandeep/test\n" }, { "code": null, "e": 7141, "s": 7115, "text": "du -s /home/mandeep/test\n" }, { "code": null, "e": 7149, "s": 7141, "text": "Output:" }, { "code": null, "e": 7179, "s": 7149, "text": "100104 /home/mandeep/test\n" }, { "code": null, "e": 7618, "s": 7179, "text": "Get the timestamp of last modified using --time optiondu --time -h /home/mandeep/test\nOutput:44K 2018-01-14 22:22 /home/mandeep/test/data\n2.0M 2017-12-24 23:06 /home/mandeep/test/system design\n24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree\n28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table\n32K 2017-12-30 10:20 /home/mandeep/test/table\n98M 2018-02-02 17:32 /home/mandeep/test\n" }, { "code": null, "e": 7651, "s": 7618, "text": "du --time -h /home/mandeep/test\n" }, { "code": null, "e": 7659, "s": 7651, "text": "Output:" }, { "code": null, "e": 8005, "s": 7659, "text": "44K 2018-01-14 22:22 /home/mandeep/test/data\n2.0M 2017-12-24 23:06 /home/mandeep/test/system design\n24K 2017-12-30 10:20 /home/mandeep/test/table/sample_table/tree\n28K 2017-12-30 10:20 /home/mandeep/test/table/sample_table\n32K 2017-12-30 10:20 /home/mandeep/test/table\n98M 2018-02-02 17:32 /home/mandeep/test\n" }, { "code": null, "e": 8021, "s": 8005, "text": "- Mandeep Singh" }, { "code": null, "e": 8064, "s": 8021, "text": "References :1) du wikipedia2) du man entry" }, { "code": null, "e": 8077, "s": 8064, "text": "Akanksha_Rai" }, { "code": null, "e": 8091, "s": 8077, "text": "linux-command" }, { "code": null, "e": 8102, "s": 8091, "text": "Linux-Unix" } ]
Program for Gauss-Jordan Elimination Method
25 Nov, 2021 Prerequisite : Gaussian Elimination to Solve Linear EquationsIntroduction : The Gauss-Jordan method, also known as Gauss-Jordan elimination method is used to solve a system of linear equations and is a modified version of Gauss Elimination Method.It is similar and simpler than Gauss Elimination Method as we have to perform 2 different process in Gauss Elimination Method i.e. 1) Formation of upper triangular matrix, and 2) Back substitutionBut in case of Gauss-Jordan Elimination Method, we only have to form a reduced row echelon form (diagonal matrix). Below given is the flow-chart of Gauss-Jordan Elimination Method. Flow Chart of Gauss-Jordan Elimination Method : Examples : Input : 2y + z = 4 x + y + 2z = 6 2x + y + z = 7 Output : Final Augmented Matrix is : 1 0 0 2.2 0 2 0 2.8 0 0 -2.5 -3 Result is : 2.2 1.4 1.2 Explanation : Below given is the explanation of the above example. Input Augmented Matrix is : Interchanging R1 and R2, we get Performing the row operation R3 <- R3 – (2*R1) Performing the row operations R1 <- R1 – ((1/2)* R2) and R3 <- R3 + ((1/2)*R2) Performing R1 <- R1 + ((3/5)*R3) and R2 <- R2 + ((2/5)*R3) Unique Solutions are : C++ Java C# Javascript // C++ Implementation for Gauss-Jordan// Elimination Method#include <bits/stdc++.h>using namespace std; #define M 10 // Function to print the matrixvoid PrintMatrix(float a[][M], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) cout << a[i][j] << " "; cout << endl; }} // function to reduce matrix to reduced// row echelon form.int PerformOperation(float a[][M], int n){ int i, j, k = 0, c, flag = 0, m = 0; float pro = 0; // Performing elementary operations for (i = 0; i < n; i++) { if (a[i][i] == 0) { c = 1; while ((i + c) < n && a[i + c][i] == 0) c++; if ((i + c) == n) { flag = 1; break; } for (j = i, k = 0; k <= n; k++) swap(a[j][k], a[j+c][k]); } for (j = 0; j < n; j++) { // Excluding all i == j if (i != j) { // Converting Matrix to reduced row // echelon form(diagonal matrix) float pro = a[j][i] / a[i][i]; for (k = 0; k <= n; k++) a[j][k] = a[j][k] - (a[i][k]) * pro; } } } return flag;} // Function to print the desired result// if unique solutions exists, otherwise// prints no solution or infinite solutions// depending upon the input given.void PrintResult(float a[][M], int n, int flag){ cout << "Result is : "; if (flag == 2) cout << "Infinite Solutions Exists" << endl; else if (flag == 3) cout << "No Solution Exists" << endl; // Printing the solution by dividing constants by // their respective diagonal elements else { for (int i = 0; i < n; i++) cout << a[i][n] / a[i][i] << " "; }} // To check whether infinite solutions// exists or no solution existsint CheckConsistency(float a[][M], int n, int flag){ int i, j; float sum; // flag == 2 for infinite solution // flag == 3 for No solution flag = 3; for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < n; j++) sum = sum + a[i][j]; if (sum == a[i][j]) flag = 2; } return flag;} // Driver codeint main(){ float a[M][M] = {{ 0, 2, 1, 4 }, { 1, 1, 2, 6 }, { 2, 1, 1, 7 }}; // Order of Matrix(n) int n = 3, flag = 0; // Performing Matrix transformation flag = PerformOperation(a, n); if (flag == 1) flag = CheckConsistency(a, n, flag); // Printing Final Matrix cout << "Final Augmented Matrix is : " << endl; PrintMatrix(a, n); cout << endl; // Printing Solutions(if exist) PrintResult(a, n, flag); return 0;} // Java Implementation for Gauss-Jordan// Elimination Methodclass GFG { static int M = 10; // Function to print the matrixstatic void PrintMatrix(float a[][], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) System.out.print(a[i][j] + " "); System.out.println(); }} // function to reduce matrix to reduced// row echelon form.static int PerformOperation(float a[][], int n){ int i, j, k = 0, c, flag = 0, m = 0; float pro = 0; // Performing elementary operations for (i = 0; i < n; i++) { if (a[i][i] == 0) { c = 1; while ((i + c) < n && a[i + c][i] == 0) c++; if ((i + c) == n) { flag = 1; break; } for (j = i, k = 0; k <= n; k++) { float temp =a[j][k]; a[j][k] = a[j+c][k]; a[j+c][k] = temp; } } for (j = 0; j < n; j++) { // Excluding all i == j if (i != j) { // Converting Matrix to reduced row // echelon form(diagonal matrix) float p = a[j][i] / a[i][i]; for (k = 0; k <= n; k++) a[j][k] = a[j][k] - (a[i][k]) * p; } } } return flag;} // Function to print the desired result// if unique solutions exists, otherwise// prints no solution or infinite solutions// depending upon the input given.static void PrintResult(float a[][], int n, int flag){ System.out.print("Result is : "); if (flag == 2) System.out.println("Infinite Solutions Exists"); else if (flag == 3) System.out.println("No Solution Exists"); // Printing the solution by dividing constants by // their respective diagonal elements else { for (int i = 0; i < n; i++) System.out.print(a[i][n] / a[i][i] +" "); }} // To check whether infinite solutions// exists or no solution existsstatic int CheckConsistency(float a[][], int n, int flag){ int i, j; float sum; // flag == 2 for infinite solution // flag == 3 for No solution flag = 3; for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < n; j++) sum = sum + a[i][j]; if (sum == a[i][j]) flag = 2; } return flag;} // Driver codepublic static void main(String[] args){ float a[][] = {{ 0, 2, 1, 4 }, { 1, 1, 2, 6 }, { 2, 1, 1, 7 }}; // Order of Matrix(n) int n = 3, flag = 0; // Performing Matrix transformation flag = PerformOperation(a, n); if (flag == 1) flag = CheckConsistency(a, n, flag); // Printing Final Matrix System.out.println("Final Augmented Matrix is : "); PrintMatrix(a, n); System.out.println(""); // Printing Solutions(if exist) PrintResult(a, n, flag);}} /* This code contributed by PrinciRaj1992 */ // C# Implementation for Gauss-Jordan// Elimination Methodusing System;using System.Collections.Generic; class GFG{static int M = 10; // Function to print the matrixstatic void PrintMatrix(float [,]a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) Console.Write(a[i, j] + " "); Console.WriteLine(); }} // function to reduce matrix to reduced// row echelon form.static int PerformOperation(float [,]a, int n){ int i, j, k = 0, c, flag = 0; // Performing elementary operations for (i = 0; i < n; i++) { if (a[i, i] == 0) { c = 1; while ((i + c) < n && a[i + c, i] == 0) c++; if ((i + c) == n) { flag = 1; break; } for (j = i, k = 0; k <= n; k++) { float temp = a[j, k]; a[j, k] = a[j + c, k]; a[j + c, k] = temp; } } for (j = 0; j < n; j++) { // Excluding all i == j if (i != j) { // Converting Matrix to reduced row // echelon form(diagonal matrix) float p = a[j, i] / a[i, i]; for (k = 0; k <= n; k++) a[j, k] = a[j, k] - (a[i, k]) * p; } } } return flag;} // Function to print the desired result// if unique solutions exists, otherwise// prints no solution or infinite solutions// depending upon the input given.static void PrintResult(float [,]a, int n, int flag){ Console.Write("Result is : "); if (flag == 2) Console.WriteLine("Infinite Solutions Exists"); else if (flag == 3) Console.WriteLine("No Solution Exists"); // Printing the solution by dividing // constants by their respective // diagonal elements else { for (int i = 0; i < n; i++) Console.Write(a[i, n] / a[i, i] + " "); }} // To check whether infinite solutions// exists or no solution existsstatic int CheckConsistency(float [,]a, int n, int flag){ int i, j; float sum; // flag == 2 for infinite solution // flag == 3 for No solution flag = 3; for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < n; j++) sum = sum + a[i, j]; if (sum == a[i, j]) flag = 2; } return flag;} // Driver codepublic static void Main(String[] args){ float [,]a = {{ 0, 2, 1, 4 }, { 1, 1, 2, 6 }, { 2, 1, 1, 7 }}; // Order of Matrix(n) int n = 3, flag = 0; // Performing Matrix transformation flag = PerformOperation(a, n); if (flag == 1) flag = CheckConsistency(a, n, flag); // Printing Final Matrix Console.WriteLine("Final Augmented Matrix is : "); PrintMatrix(a, n); Console.WriteLine(""); // Printing Solutions(if exist) PrintResult(a, n, flag);}} // This code is contributed by 29AjayKumar <script> // JavaScript Implementation for Gauss-Jordan// Elimination Method let M = 10; // Function to print the matrixfunction PrintMatrix(a,n){ for (let i = 0; i < n; i++) { for (let j = 0; j <= n; j++) document.write(a[i][j] + " "); document.write("<br>"); }} // function to reduce matrix to reduced// row echelon form.function PerformOperation(a,n){ let i, j, k = 0, c, flag = 0, m = 0; let pro = 0; // Performing elementary operations for (i = 0; i < n; i++) { if (a[i][i] == 0) { c = 1; while ((i + c) < n && a[i + c][i] == 0) c++; if ((i + c) == n) { flag = 1; break; } for (j = i, k = 0; k <= n; k++) { let temp =a[j][k]; a[j][k] = a[j+c][k]; a[j+c][k] = temp; } } for (j = 0; j < n; j++) { // Excluding all i == j if (i != j) { // Converting Matrix to reduced row // echelon form(diagonal matrix) let p = a[j][i] / a[i][i]; for (k = 0; k <= n; k++) a[j][k] = a[j][k] - (a[i][k]) * p; } } } return flag;} // Function to print the desired result// if unique solutions exists, otherwise// prints no solution or infinite solutions// depending upon the input given.function PrintResult(a,n,flag){ document.write("Result is : "); if (flag == 2) document.write("Infinite Solutions Exists<br>"); else if (flag == 3) document.write("No Solution Exists<br>"); // Printing the solution by dividing constants by // their respective diagonal elements else { for (let i = 0; i < n; i++) document.write(a[i][n] / a[i][i] +" "); }} // To check whether infinite solutions// exists or no solution existsfunction CheckConsistency(a,n,flag){ let i, j; let sum; // flag == 2 for infinite solution // flag == 3 for No solution flag = 3; for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < n; j++) sum = sum + a[i][j]; if (sum == a[i][j]) flag = 2; } return flag;} // Driver codelet a=[[ 0, 2, 1, 4 ], [ 1, 1, 2, 6 ], [ 2, 1, 1, 7 ]];// Order of Matrix(n)let n = 3, flag = 0; // Performing Matrix transformationflag = PerformOperation(a, n); if (flag == 1) flag = CheckConsistency(a, n, flag); // Printing Final Matrixdocument.write("Final Augmented Matrix is : <br>");PrintMatrix(a, n);document.write("<br>"); // Printing Solutions(if exist)PrintResult(a, n, flag); // This code is contributed by rag2127 </script> Final Augmented Matrix is : 1 0 0 2.2 0 2 0 2.8 0 0 -2.5 -3 Result is : 2.2 1.4 1.2 Applications : Solving System of Linear Equations: Gauss-Jordan Elimination Method can be used for finding the solution of a systems of linear equations which is applied throughout the mathematics. Finding Determinant: The Gaussian Elimination can be applied to a square matrix in order to find determinant of the matrix. Finding Inverse of Matrix: The Gauss-Jordan Elimination method can be used in determining the inverse of a square matrix. Finding Ranks and Bases: Using reduced row echelon form, the ranks as well as bases of square matrices can be computed by Gaussian elimination method. princiraj1992 29AjayKumar jeroenoorschot rag2127 sumitgumber28 Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Nov, 2021" }, { "code": null, "e": 728, "s": 54, "text": "Prerequisite : Gaussian Elimination to Solve Linear EquationsIntroduction : The Gauss-Jordan method, also known as Gauss-Jordan elimination method is used to solve a system of linear equations and is a modified version of Gauss Elimination Method.It is similar and simpler than Gauss Elimination Method as we have to perform 2 different process in Gauss Elimination Method i.e. 1) Formation of upper triangular matrix, and 2) Back substitutionBut in case of Gauss-Jordan Elimination Method, we only have to form a reduced row echelon form (diagonal matrix). Below given is the flow-chart of Gauss-Jordan Elimination Method. Flow Chart of Gauss-Jordan Elimination Method : " }, { "code": null, "e": 741, "s": 728, "text": "Examples : " }, { "code": null, "e": 909, "s": 741, "text": "Input : 2y + z = 4\n x + y + 2z = 6\n 2x + y + z = 7\n\nOutput :\nFinal Augmented Matrix is : \n1 0 0 2.2 \n0 2 0 2.8 \n0 0 -2.5 -3 \n\nResult is : 2.2 1.4 1.2 " }, { "code": null, "e": 977, "s": 909, "text": "Explanation : Below given is the explanation of the above example. " }, { "code": null, "e": 1005, "s": 977, "text": "Input Augmented Matrix is :" }, { "code": null, "e": 1041, "s": 1009, "text": "Interchanging R1 and R2, we get" }, { "code": null, "e": 1092, "s": 1045, "text": "Performing the row operation R3 <- R3 – (2*R1)" }, { "code": null, "e": 1175, "s": 1096, "text": "Performing the row operations R1 <- R1 – ((1/2)* R2) and R3 <- R3 + ((1/2)*R2)" }, { "code": null, "e": 1238, "s": 1179, "text": "Performing R1 <- R1 + ((3/5)*R3) and R2 <- R2 + ((2/5)*R3)" }, { "code": null, "e": 1265, "s": 1242, "text": "Unique Solutions are :" }, { "code": null, "e": 1273, "s": 1269, "text": "C++" }, { "code": null, "e": 1278, "s": 1273, "text": "Java" }, { "code": null, "e": 1281, "s": 1278, "text": "C#" }, { "code": null, "e": 1292, "s": 1281, "text": "Javascript" }, { "code": "// C++ Implementation for Gauss-Jordan// Elimination Method#include <bits/stdc++.h>using namespace std; #define M 10 // Function to print the matrixvoid PrintMatrix(float a[][M], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) cout << a[i][j] << \" \"; cout << endl; }} // function to reduce matrix to reduced// row echelon form.int PerformOperation(float a[][M], int n){ int i, j, k = 0, c, flag = 0, m = 0; float pro = 0; // Performing elementary operations for (i = 0; i < n; i++) { if (a[i][i] == 0) { c = 1; while ((i + c) < n && a[i + c][i] == 0) c++; if ((i + c) == n) { flag = 1; break; } for (j = i, k = 0; k <= n; k++) swap(a[j][k], a[j+c][k]); } for (j = 0; j < n; j++) { // Excluding all i == j if (i != j) { // Converting Matrix to reduced row // echelon form(diagonal matrix) float pro = a[j][i] / a[i][i]; for (k = 0; k <= n; k++) a[j][k] = a[j][k] - (a[i][k]) * pro; } } } return flag;} // Function to print the desired result// if unique solutions exists, otherwise// prints no solution or infinite solutions// depending upon the input given.void PrintResult(float a[][M], int n, int flag){ cout << \"Result is : \"; if (flag == 2) cout << \"Infinite Solutions Exists\" << endl; else if (flag == 3) cout << \"No Solution Exists\" << endl; // Printing the solution by dividing constants by // their respective diagonal elements else { for (int i = 0; i < n; i++) cout << a[i][n] / a[i][i] << \" \"; }} // To check whether infinite solutions// exists or no solution existsint CheckConsistency(float a[][M], int n, int flag){ int i, j; float sum; // flag == 2 for infinite solution // flag == 3 for No solution flag = 3; for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < n; j++) sum = sum + a[i][j]; if (sum == a[i][j]) flag = 2; } return flag;} // Driver codeint main(){ float a[M][M] = {{ 0, 2, 1, 4 }, { 1, 1, 2, 6 }, { 2, 1, 1, 7 }}; // Order of Matrix(n) int n = 3, flag = 0; // Performing Matrix transformation flag = PerformOperation(a, n); if (flag == 1) flag = CheckConsistency(a, n, flag); // Printing Final Matrix cout << \"Final Augmented Matrix is : \" << endl; PrintMatrix(a, n); cout << endl; // Printing Solutions(if exist) PrintResult(a, n, flag); return 0;}", "e": 4188, "s": 1292, "text": null }, { "code": "// Java Implementation for Gauss-Jordan// Elimination Methodclass GFG { static int M = 10; // Function to print the matrixstatic void PrintMatrix(float a[][], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) System.out.print(a[i][j] + \" \"); System.out.println(); }} // function to reduce matrix to reduced// row echelon form.static int PerformOperation(float a[][], int n){ int i, j, k = 0, c, flag = 0, m = 0; float pro = 0; // Performing elementary operations for (i = 0; i < n; i++) { if (a[i][i] == 0) { c = 1; while ((i + c) < n && a[i + c][i] == 0) c++; if ((i + c) == n) { flag = 1; break; } for (j = i, k = 0; k <= n; k++) { float temp =a[j][k]; a[j][k] = a[j+c][k]; a[j+c][k] = temp; } } for (j = 0; j < n; j++) { // Excluding all i == j if (i != j) { // Converting Matrix to reduced row // echelon form(diagonal matrix) float p = a[j][i] / a[i][i]; for (k = 0; k <= n; k++) a[j][k] = a[j][k] - (a[i][k]) * p; } } } return flag;} // Function to print the desired result// if unique solutions exists, otherwise// prints no solution or infinite solutions// depending upon the input given.static void PrintResult(float a[][], int n, int flag){ System.out.print(\"Result is : \"); if (flag == 2) System.out.println(\"Infinite Solutions Exists\"); else if (flag == 3) System.out.println(\"No Solution Exists\"); // Printing the solution by dividing constants by // their respective diagonal elements else { for (int i = 0; i < n; i++) System.out.print(a[i][n] / a[i][i] +\" \"); }} // To check whether infinite solutions// exists or no solution existsstatic int CheckConsistency(float a[][], int n, int flag){ int i, j; float sum; // flag == 2 for infinite solution // flag == 3 for No solution flag = 3; for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < n; j++) sum = sum + a[i][j]; if (sum == a[i][j]) flag = 2; } return flag;} // Driver codepublic static void main(String[] args){ float a[][] = {{ 0, 2, 1, 4 }, { 1, 1, 2, 6 }, { 2, 1, 1, 7 }}; // Order of Matrix(n) int n = 3, flag = 0; // Performing Matrix transformation flag = PerformOperation(a, n); if (flag == 1) flag = CheckConsistency(a, n, flag); // Printing Final Matrix System.out.println(\"Final Augmented Matrix is : \"); PrintMatrix(a, n); System.out.println(\"\"); // Printing Solutions(if exist) PrintResult(a, n, flag);}} /* This code contributed by PrinciRaj1992 */", "e": 7293, "s": 4188, "text": null }, { "code": "// C# Implementation for Gauss-Jordan// Elimination Methodusing System;using System.Collections.Generic; class GFG{static int M = 10; // Function to print the matrixstatic void PrintMatrix(float [,]a, int n){ for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) Console.Write(a[i, j] + \" \"); Console.WriteLine(); }} // function to reduce matrix to reduced// row echelon form.static int PerformOperation(float [,]a, int n){ int i, j, k = 0, c, flag = 0; // Performing elementary operations for (i = 0; i < n; i++) { if (a[i, i] == 0) { c = 1; while ((i + c) < n && a[i + c, i] == 0) c++; if ((i + c) == n) { flag = 1; break; } for (j = i, k = 0; k <= n; k++) { float temp = a[j, k]; a[j, k] = a[j + c, k]; a[j + c, k] = temp; } } for (j = 0; j < n; j++) { // Excluding all i == j if (i != j) { // Converting Matrix to reduced row // echelon form(diagonal matrix) float p = a[j, i] / a[i, i]; for (k = 0; k <= n; k++) a[j, k] = a[j, k] - (a[i, k]) * p; } } } return flag;} // Function to print the desired result// if unique solutions exists, otherwise// prints no solution or infinite solutions// depending upon the input given.static void PrintResult(float [,]a, int n, int flag){ Console.Write(\"Result is : \"); if (flag == 2) Console.WriteLine(\"Infinite Solutions Exists\"); else if (flag == 3) Console.WriteLine(\"No Solution Exists\"); // Printing the solution by dividing // constants by their respective // diagonal elements else { for (int i = 0; i < n; i++) Console.Write(a[i, n] / a[i, i] + \" \"); }} // To check whether infinite solutions// exists or no solution existsstatic int CheckConsistency(float [,]a, int n, int flag){ int i, j; float sum; // flag == 2 for infinite solution // flag == 3 for No solution flag = 3; for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < n; j++) sum = sum + a[i, j]; if (sum == a[i, j]) flag = 2; } return flag;} // Driver codepublic static void Main(String[] args){ float [,]a = {{ 0, 2, 1, 4 }, { 1, 1, 2, 6 }, { 2, 1, 1, 7 }}; // Order of Matrix(n) int n = 3, flag = 0; // Performing Matrix transformation flag = PerformOperation(a, n); if (flag == 1) flag = CheckConsistency(a, n, flag); // Printing Final Matrix Console.WriteLine(\"Final Augmented Matrix is : \"); PrintMatrix(a, n); Console.WriteLine(\"\"); // Printing Solutions(if exist) PrintResult(a, n, flag);}} // This code is contributed by 29AjayKumar", "e": 10447, "s": 7293, "text": null }, { "code": "<script> // JavaScript Implementation for Gauss-Jordan// Elimination Method let M = 10; // Function to print the matrixfunction PrintMatrix(a,n){ for (let i = 0; i < n; i++) { for (let j = 0; j <= n; j++) document.write(a[i][j] + \" \"); document.write(\"<br>\"); }} // function to reduce matrix to reduced// row echelon form.function PerformOperation(a,n){ let i, j, k = 0, c, flag = 0, m = 0; let pro = 0; // Performing elementary operations for (i = 0; i < n; i++) { if (a[i][i] == 0) { c = 1; while ((i + c) < n && a[i + c][i] == 0) c++; if ((i + c) == n) { flag = 1; break; } for (j = i, k = 0; k <= n; k++) { let temp =a[j][k]; a[j][k] = a[j+c][k]; a[j+c][k] = temp; } } for (j = 0; j < n; j++) { // Excluding all i == j if (i != j) { // Converting Matrix to reduced row // echelon form(diagonal matrix) let p = a[j][i] / a[i][i]; for (k = 0; k <= n; k++) a[j][k] = a[j][k] - (a[i][k]) * p; } } } return flag;} // Function to print the desired result// if unique solutions exists, otherwise// prints no solution or infinite solutions// depending upon the input given.function PrintResult(a,n,flag){ document.write(\"Result is : \"); if (flag == 2) document.write(\"Infinite Solutions Exists<br>\"); else if (flag == 3) document.write(\"No Solution Exists<br>\"); // Printing the solution by dividing constants by // their respective diagonal elements else { for (let i = 0; i < n; i++) document.write(a[i][n] / a[i][i] +\" \"); }} // To check whether infinite solutions// exists or no solution existsfunction CheckConsistency(a,n,flag){ let i, j; let sum; // flag == 2 for infinite solution // flag == 3 for No solution flag = 3; for (i = 0; i < n; i++) { sum = 0; for (j = 0; j < n; j++) sum = sum + a[i][j]; if (sum == a[i][j]) flag = 2; } return flag;} // Driver codelet a=[[ 0, 2, 1, 4 ], [ 1, 1, 2, 6 ], [ 2, 1, 1, 7 ]];// Order of Matrix(n)let n = 3, flag = 0; // Performing Matrix transformationflag = PerformOperation(a, n); if (flag == 1) flag = CheckConsistency(a, n, flag); // Printing Final Matrixdocument.write(\"Final Augmented Matrix is : <br>\");PrintMatrix(a, n);document.write(\"<br>\"); // Printing Solutions(if exist)PrintResult(a, n, flag); // This code is contributed by rag2127 </script>", "e": 13351, "s": 10447, "text": null }, { "code": null, "e": 13441, "s": 13351, "text": "Final Augmented Matrix is : \n1 0 0 2.2 \n0 2 0 2.8 \n0 0 -2.5 -3 \n\nResult is : 2.2 1.4 1.2 " }, { "code": null, "e": 13458, "s": 13441, "text": "Applications : " }, { "code": null, "e": 13641, "s": 13458, "text": "Solving System of Linear Equations: Gauss-Jordan Elimination Method can be used for finding the solution of a systems of linear equations which is applied throughout the mathematics." }, { "code": null, "e": 13765, "s": 13641, "text": "Finding Determinant: The Gaussian Elimination can be applied to a square matrix in order to find determinant of the matrix." }, { "code": null, "e": 13887, "s": 13765, "text": "Finding Inverse of Matrix: The Gauss-Jordan Elimination method can be used in determining the inverse of a square matrix." }, { "code": null, "e": 14038, "s": 13887, "text": "Finding Ranks and Bases: Using reduced row echelon form, the ranks as well as bases of square matrices can be computed by Gaussian elimination method." }, { "code": null, "e": 14054, "s": 14040, "text": "princiraj1992" }, { "code": null, "e": 14066, "s": 14054, "text": "29AjayKumar" }, { "code": null, "e": 14081, "s": 14066, "text": "jeroenoorschot" }, { "code": null, "e": 14089, "s": 14081, "text": "rag2127" }, { "code": null, "e": 14103, "s": 14089, "text": "sumitgumber28" }, { "code": null, "e": 14116, "s": 14103, "text": "Mathematical" }, { "code": null, "e": 14123, "s": 14116, "text": "Matrix" }, { "code": null, "e": 14136, "s": 14123, "text": "Mathematical" }, { "code": null, "e": 14143, "s": 14136, "text": "Matrix" }, { "code": null, "e": 14241, "s": 14143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14265, "s": 14241, "text": "Merge two sorted arrays" }, { "code": null, "e": 14286, "s": 14265, "text": "Operators in C / C++" }, { "code": null, "e": 14300, "s": 14286, "text": "Prime Numbers" }, { "code": null, "e": 14342, "s": 14300, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 14364, "s": 14342, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 14399, "s": 14364, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 14443, "s": 14399, "text": "Program to find largest element in an array" }, { "code": null, "e": 14474, "s": 14443, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 14498, "s": 14474, "text": "Sudoku | Backtracking-7" } ]
How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
30 Jun, 2021 In some android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On another side, it provides a different look to that app. It is also possible to provide different feel like left and right swipe by using ViewPager. And to implement this topic, few terms are required such as ViewPager, Fragments, and TabLayout. For practice purposes, Kotlin programming language is used in this article. TabLayout: This view allows us to make use of multiple tabs in the android app. This Layout holds different tabs. In this article, tabs are used to navigate from one Fragment to another Fragment. ViewPager: This view allows us to make use of the left and right swipe feature to show another fragment. Fragments: This is a part of the Activity. This view is necessary, to do multiple tasks on a single activity. The Fragment also makes use of layout file which contains view/s as per need. A sample GIF is given below to get an idea about what we are going to do in this article. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Create Fragments Go to app > res > layout > right-click > New > Layout Resource File and after that, it asks for the file name then gives “layout_login” as the name of that layout file. Use the same method to create another layout file “layout_signup”. After that, use the following code for the “layout_login.xml” file. Here one TextView is shown. XML <?xml version="1.0" encoding="utf-8"?><!-- This linear layout is used to show elements in vertical or in horizontal linear manner --><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <!-- This TextView indicates new fragment is open --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Login Fragment" android:textColor="#0F9D58" android:textSize="25sp" android:textStyle="bold" /> </LinearLayout> Below is the code for the layout_signup.xml file. XML <?xml version="1.0" encoding="utf-8"?><!-- This linear layout is used to show elements in vertical or in horizontal linear manner --><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <!-- This TextView indicates new fragment is open --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Signup Fragment" android:textColor="#0F9D58" android:textSize="25sp" android:textStyle="bold" /> </LinearLayout> To create Fragment class, right-click on the first package of java directory which is located at app > java > “com.example.gfgtabdemo”, where “gfgtabdemo” is the project name in a small case. Move cursor on “New” and select “Kotlin file/class”. Give “LoginFragment” as a name to that file and select the “class” option as shown in the below screenshot. To create a Fragment, it is necessary to make this class as a child of the Fragment class by using the “:” symbol. And override the “onCreateView” method to set the layout resource file to that fragment file as shown in the following code snippet. Use the above procedure to create the “SignupFragment” file. After that, use the following code in the “LoginFragment.kt” file. Kotlin import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.fragment.app.Fragment // Here ":" symbol is indicate that LoginFragment// is child class of Fragment Classclass LoginFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate( R.layout.layout_login, container, false ) } // Here "layout_login" is a name of layout file // created for LoginFragment} Use the following code in the “SignupFragment.kt” file. Kotlin import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.fragment.app.Fragment // Here ":" symbol is indicate that SignupFragment// is child class of Fragment Classclass SignupFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate( R.layout.layout_signup, container, false ) } // Here "layout_signup" is a name of layout file // created for SignFragment} Step 3: Theme Configuration Open “styles.xml” which is placed inside of folder “app > res > values > styles.xml” as shown in the image below. Add the following code inside of <resources> tag in styles.xml. XML <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item></style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> Below is the complete code for the complete styles.xml file. XML <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> </resources> After that open, the “AndroidManifest.xml” file placed inside of folders ”app > manifest > AndroidManifest.xml”. We need to set the theme “@style/AppTheme.NoActionBar” inside of <activity> tag. To do the same type the highlighted line in the following screenshot, inside of that activity tag, in which you want to use tab layout. Step 4: Adding Required Views For the implementation of this topic, it is important to add some views. To do the same first, open build.gradle (Module: app) file, located at “Gradle Script > build.gradle (Module: app)”, and add the following dependency inside of dependencies block. And don’t forget to click on “sync now”. This dependency is required, to make use of “appbar layout”. implementation ‘com.google.android.material:material:1.2.0’ Note: Type this dependency line rather than copy and paste. Because due to copy and paste formatting or text style may be unaccepted if it is not matched with the required format. Step 5: Working with the activity_main.xml file After that, it is necessary to add the following views in a layout file of activity so open it. Here we use “activity_main.xml”. AppBarLayout ToolBar TabLayout ViewPager Add the following code to the “activity_main.xml” file. Comments are added inside the code to understand the code in more detail. XML <?xml version="1.0" encoding="utf-8"?> <!-- In order to use tabs, coordinator layout is useful--><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <!--This appbarlayout covers the toolbar and tablayout--> <com.google.android.material.appbar.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#0F9D58" android:theme="@style/AppTheme.AppBarOverlay"> <!--toolbar is one component which is necessary because if we not use this then title is not shown when project executed--> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/AppTheme.PopupOverlay" /> <!-- tablayout which contains which is important to show tabs --> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_tablayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIndicatorColor="#FFF" app:tabIndicatorHeight="3dp" app:tabMode="fixed" /> </com.google.android.material.appbar.AppBarLayout> <!-- view pager is used to open other fragment by using left or right swip--> <androidx.viewpager.widget.ViewPager android:id="@+id/tab_viewpager" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="5dp" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> Step 6: Working with the MainActivity.kt file After that, open “MainActivity.kt”. In this file, it is important to create the object of Toolbar, ViewPager, and TabLayout and use the “findViewById()” method to identify the view. Its syntax is shown below. var object_name = findViewById<ViewName>(unique_id_assigned_to_view) Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport androidx.annotation.Nullableimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbarimport androidx.fragment.app.Fragmentimport androidx.fragment.app.FragmentManagerimport androidx.fragment.app.FragmentPagerAdapterimport androidx.viewpager.widget.ViewPagerimport com.google.android.material.tabs.TabLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Create the object of Toolbar, ViewPager and // TabLayout and use “findViewById()” method*/ var tab_toolbar = findViewById<Toolbar>(R.id.toolbar) var tab_viewpager = findViewById<ViewPager>(R.id.tab_viewpager) var tab_tablayout = findViewById<TabLayout>(R.id.tab_tablayout) // As we set NoActionBar as theme to this activity // so when we run this project then this activity doesn't // show title. And for this reason, we need to run // setSupportActionBar method setSupportActionBar(tab_toolbar) setupViewPager(tab_viewpager) // If we dont use setupWithViewPager() method then // tabs are not used or shown when activity opened tab_tablayout.setupWithViewPager(tab_viewpager) } // This function is used to add items in arraylist and assign // the adapter to view pager private fun setupViewPager(viewpager: ViewPager) { var adapter: ViewPagerAdapter = ViewPagerAdapter(supportFragmentManager) // LoginFragment is the name of Fragment and the Login // is a title of tab adapter.addFragment(LoginFragment(), "Login") adapter.addFragment(SignupFragment(), "Signup") // setting adapter to view pager. viewpager.setAdapter(adapter) } // This "ViewPagerAdapter" class overrides functions which are // necessary to get information about which item is selected // by user, what is title for selected item and so on.*/ class ViewPagerAdapter : FragmentPagerAdapter { // objects of arraylist. One is of Fragment type and // another one is of String type.*/ private final var fragmentList1: ArrayList<Fragment> = ArrayList() private final var fragmentTitleList1: ArrayList<String> = ArrayList() // this is a secondary constructor of ViewPagerAdapter class. public constructor(supportFragmentManager: FragmentManager) : super(supportFragmentManager) // returns which item is selected from arraylist of fragments. override fun getItem(position: Int): Fragment { return fragmentList1.get(position) } // returns which item is selected from arraylist of titles. @Nullable override fun getPageTitle(position: Int): CharSequence { return fragmentTitleList1.get(position) } // returns the number of items present in arraylist. override fun getCount(): Int { return fragmentList1.size } // this function adds the fragment and title in 2 separate arraylist. fun addFragment(fragment: Fragment, title: String) { fragmentList1.add(fragment) fragmentTitleList1.add(title) } }} arorakashish0911 android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 474, "s": 28, "text": "In some android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On another side, it provides a different look to that app. It is also possible to provide different feel like left and right swipe by using ViewPager. And to implement this topic, few terms are required such as ViewPager, Fragments, and TabLayout. For practice purposes, Kotlin programming language is used in this article." }, { "code": null, "e": 670, "s": 474, "text": "TabLayout: This view allows us to make use of multiple tabs in the android app. This Layout holds different tabs. In this article, tabs are used to navigate from one Fragment to another Fragment." }, { "code": null, "e": 775, "s": 670, "text": "ViewPager: This view allows us to make use of the left and right swipe feature to show another fragment." }, { "code": null, "e": 963, "s": 775, "text": "Fragments: This is a part of the Activity. This view is necessary, to do multiple tasks on a single activity. The Fragment also makes use of layout file which contains view/s as per need." }, { "code": null, "e": 1053, "s": 963, "text": "A sample GIF is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 1082, "s": 1053, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1246, "s": 1082, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 1271, "s": 1246, "text": "Step 2: Create Fragments" }, { "code": null, "e": 1440, "s": 1271, "text": "Go to app > res > layout > right-click > New > Layout Resource File and after that, it asks for the file name then gives “layout_login” as the name of that layout file." }, { "code": null, "e": 1507, "s": 1440, "text": "Use the same method to create another layout file “layout_signup”." }, { "code": null, "e": 1603, "s": 1507, "text": "After that, use the following code for the “layout_login.xml” file. Here one TextView is shown." }, { "code": null, "e": 1607, "s": 1603, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- This linear layout is used to show elements in vertical or in horizontal linear manner --><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\"> <!-- This TextView indicates new fragment is open --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:text=\"Login Fragment\" android:textColor=\"#0F9D58\" android:textSize=\"25sp\" android:textStyle=\"bold\" /> </LinearLayout>", "e": 2276, "s": 1607, "text": null }, { "code": null, "e": 2329, "s": 2279, "text": "Below is the code for the layout_signup.xml file." }, { "code": null, "e": 2335, "s": 2331, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- This linear layout is used to show elements in vertical or in horizontal linear manner --><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\"> <!-- This TextView indicates new fragment is open --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:text=\"Signup Fragment\" android:textColor=\"#0F9D58\" android:textSize=\"25sp\" android:textStyle=\"bold\" /> </LinearLayout>", "e": 3005, "s": 2335, "text": null }, { "code": null, "e": 3256, "s": 3011, "text": "To create Fragment class, right-click on the first package of java directory which is located at app > java > “com.example.gfgtabdemo”, where “gfgtabdemo” is the project name in a small case. Move cursor on “New” and select “Kotlin file/class”." }, { "code": null, "e": 3364, "s": 3256, "text": "Give “LoginFragment” as a name to that file and select the “class” option as shown in the below screenshot." }, { "code": null, "e": 3612, "s": 3364, "text": "To create a Fragment, it is necessary to make this class as a child of the Fragment class by using the “:” symbol. And override the “onCreateView” method to set the layout resource file to that fragment file as shown in the following code snippet." }, { "code": null, "e": 3673, "s": 3612, "text": "Use the above procedure to create the “SignupFragment” file." }, { "code": null, "e": 3740, "s": 3673, "text": "After that, use the following code in the “LoginFragment.kt” file." }, { "code": null, "e": 3749, "s": 3742, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.fragment.app.Fragment // Here \":\" symbol is indicate that LoginFragment// is child class of Fragment Classclass LoginFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate( R.layout.layout_login, container, false ) } // Here \"layout_login\" is a name of layout file // created for LoginFragment}", "e": 4326, "s": 3749, "text": null }, { "code": null, "e": 4390, "s": 4334, "text": "Use the following code in the “SignupFragment.kt” file." }, { "code": null, "e": 4399, "s": 4392, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.fragment.app.Fragment // Here \":\" symbol is indicate that SignupFragment// is child class of Fragment Classclass SignupFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate( R.layout.layout_signup, container, false ) } // Here \"layout_signup\" is a name of layout file // created for SignFragment}", "e": 4979, "s": 4399, "text": null }, { "code": null, "e": 5015, "s": 4987, "text": "Step 3: Theme Configuration" }, { "code": null, "e": 5131, "s": 5017, "text": "Open “styles.xml” which is placed inside of folder “app > res > values > styles.xml” as shown in the image below." }, { "code": null, "e": 5195, "s": 5131, "text": "Add the following code inside of <resources> tag in styles.xml." }, { "code": null, "e": 5201, "s": 5197, "text": "XML" }, { "code": "<style name=\"AppTheme.NoActionBar\"> <item name=\"windowActionBar\">false</item> <item name=\"windowNoTitle\">true</item></style> <style name=\"AppTheme.AppBarOverlay\" parent=\"ThemeOverlay.AppCompat.Dark.ActionBar\" /> <style name=\"AppTheme.PopupOverlay\" parent=\"ThemeOverlay.AppCompat.Light\" />", "e": 5516, "s": 5201, "text": null }, { "code": null, "e": 5580, "s": 5519, "text": "Below is the complete code for the complete styles.xml file." }, { "code": null, "e": 5588, "s": 5584, "text": "XML" }, { "code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> <style name=\"AppTheme.NoActionBar\"> <item name=\"windowActionBar\">false</item> <item name=\"windowNoTitle\">true</item> </style> <style name=\"AppTheme.AppBarOverlay\" parent=\"ThemeOverlay.AppCompat.Dark.ActionBar\" /> <style name=\"AppTheme.PopupOverlay\" parent=\"ThemeOverlay.AppCompat.Light\" /> </resources>", "e": 6300, "s": 5588, "text": null }, { "code": null, "e": 6633, "s": 6303, "text": "After that open, the “AndroidManifest.xml” file placed inside of folders ”app > manifest > AndroidManifest.xml”. We need to set the theme “@style/AppTheme.NoActionBar” inside of <activity> tag. To do the same type the highlighted line in the following screenshot, inside of that activity tag, in which you want to use tab layout." }, { "code": null, "e": 6665, "s": 6635, "text": "Step 4: Adding Required Views" }, { "code": null, "e": 7022, "s": 6667, "text": "For the implementation of this topic, it is important to add some views. To do the same first, open build.gradle (Module: app) file, located at “Gradle Script > build.gradle (Module: app)”, and add the following dependency inside of dependencies block. And don’t forget to click on “sync now”. This dependency is required, to make use of “appbar layout”." }, { "code": null, "e": 7084, "s": 7024, "text": "implementation ‘com.google.android.material:material:1.2.0’" }, { "code": null, "e": 7268, "s": 7088, "text": "Note: Type this dependency line rather than copy and paste. Because due to copy and paste formatting or text style may be unaccepted if it is not matched with the required format." }, { "code": null, "e": 7318, "s": 7270, "text": "Step 5: Working with the activity_main.xml file" }, { "code": null, "e": 7449, "s": 7320, "text": "After that, it is necessary to add the following views in a layout file of activity so open it. Here we use “activity_main.xml”." }, { "code": null, "e": 7464, "s": 7451, "text": "AppBarLayout" }, { "code": null, "e": 7472, "s": 7464, "text": "ToolBar" }, { "code": null, "e": 7482, "s": 7472, "text": "TabLayout" }, { "code": null, "e": 7492, "s": 7482, "text": "ViewPager" }, { "code": null, "e": 7624, "s": 7494, "text": "Add the following code to the “activity_main.xml” file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 7630, "s": 7626, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!-- In order to use tabs, coordinator layout is useful--><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--This appbarlayout covers the toolbar and tablayout--> <com.google.android.material.appbar.AppBarLayout android:id=\"@+id/appbar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"#0F9D58\" android:theme=\"@style/AppTheme.AppBarOverlay\"> <!--toolbar is one component which is necessary because if we not use this then title is not shown when project executed--> <androidx.appcompat.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:layout_scrollFlags=\"scroll|enterAlways\" app:popupTheme=\"@style/AppTheme.PopupOverlay\" /> <!-- tablayout which contains which is important to show tabs --> <com.google.android.material.tabs.TabLayout android:id=\"@+id/tab_tablayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" app:tabIndicatorColor=\"#FFF\" app:tabIndicatorHeight=\"3dp\" app:tabMode=\"fixed\" /> </com.google.android.material.appbar.AppBarLayout> <!-- view pager is used to open other fragment by using left or right swip--> <androidx.viewpager.widget.ViewPager android:id=\"@+id/tab_viewpager\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginTop=\"5dp\" app:layout_behavior=\"@string/appbar_scrolling_view_behavior\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>", "e": 9610, "s": 7630, "text": null }, { "code": null, "e": 9660, "s": 9614, "text": "Step 6: Working with the MainActivity.kt file" }, { "code": null, "e": 9873, "s": 9664, "text": "After that, open “MainActivity.kt”. In this file, it is important to create the object of Toolbar, ViewPager, and TabLayout and use the “findViewById()” method to identify the view. Its syntax is shown below." }, { "code": null, "e": 9945, "s": 9875, "text": "var object_name = findViewById<ViewName>(unique_id_assigned_to_view) " }, { "code": null, "e": 10136, "s": 9949, "text": "Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 10145, "s": 10138, "text": "Kotlin" }, { "code": "import android.os.Bundleimport androidx.annotation.Nullableimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbarimport androidx.fragment.app.Fragmentimport androidx.fragment.app.FragmentManagerimport androidx.fragment.app.FragmentPagerAdapterimport androidx.viewpager.widget.ViewPagerimport com.google.android.material.tabs.TabLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Create the object of Toolbar, ViewPager and // TabLayout and use “findViewById()” method*/ var tab_toolbar = findViewById<Toolbar>(R.id.toolbar) var tab_viewpager = findViewById<ViewPager>(R.id.tab_viewpager) var tab_tablayout = findViewById<TabLayout>(R.id.tab_tablayout) // As we set NoActionBar as theme to this activity // so when we run this project then this activity doesn't // show title. And for this reason, we need to run // setSupportActionBar method setSupportActionBar(tab_toolbar) setupViewPager(tab_viewpager) // If we dont use setupWithViewPager() method then // tabs are not used or shown when activity opened tab_tablayout.setupWithViewPager(tab_viewpager) } // This function is used to add items in arraylist and assign // the adapter to view pager private fun setupViewPager(viewpager: ViewPager) { var adapter: ViewPagerAdapter = ViewPagerAdapter(supportFragmentManager) // LoginFragment is the name of Fragment and the Login // is a title of tab adapter.addFragment(LoginFragment(), \"Login\") adapter.addFragment(SignupFragment(), \"Signup\") // setting adapter to view pager. viewpager.setAdapter(adapter) } // This \"ViewPagerAdapter\" class overrides functions which are // necessary to get information about which item is selected // by user, what is title for selected item and so on.*/ class ViewPagerAdapter : FragmentPagerAdapter { // objects of arraylist. One is of Fragment type and // another one is of String type.*/ private final var fragmentList1: ArrayList<Fragment> = ArrayList() private final var fragmentTitleList1: ArrayList<String> = ArrayList() // this is a secondary constructor of ViewPagerAdapter class. public constructor(supportFragmentManager: FragmentManager) : super(supportFragmentManager) // returns which item is selected from arraylist of fragments. override fun getItem(position: Int): Fragment { return fragmentList1.get(position) } // returns which item is selected from arraylist of titles. @Nullable override fun getPageTitle(position: Int): CharSequence { return fragmentTitleList1.get(position) } // returns the number of items present in arraylist. override fun getCount(): Int { return fragmentList1.size } // this function adds the fragment and title in 2 separate arraylist. fun addFragment(fragment: Fragment, title: String) { fragmentList1.add(fragment) fragmentTitleList1.add(title) } }}", "e": 13451, "s": 10145, "text": null }, { "code": null, "e": 13474, "s": 13457, "text": "arorakashish0911" }, { "code": null, "e": 13482, "s": 13474, "text": "android" }, { "code": null, "e": 13490, "s": 13482, "text": "Android" }, { "code": null, "e": 13497, "s": 13490, "text": "Kotlin" }, { "code": null, "e": 13505, "s": 13497, "text": "Android" } ]
Difference between <i> and <em> tag of HTML
04 Dec, 2020 1. <i> tag :It is one of the element of HTML which is used in formatting HTML texts. It is used to define a text in technical term, alternative mood or voice, a thought, etc. Syntax : <i> Content... </i> 2. <em> tag :It is also one of the element of HTML used in formatting texts. It is used to define emphasized text or statements. Syntax : <em> Content... </em> By default, the visual result is the same. The main difference between these two tag is that the <em> tag semantically emphasizes on the important word or section of words while <i> tag is just offset text conventionally styled in italic to show alternative mood or voice. Below is the code to show this difference between the two : Example-1 : HTML <!DOCTYPE html><html> <head> <title>b Tag</title> <style> body { text-align:center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <p><i>Iron Man</i> is a hero.</p> <p>Gfg is the <em>best</em> educational site.</p> </body></html> Output : Here, there is no added emphasis or importance on the word “Iron Man”. It just indicates here iron isn’t a mineral or metal but it refers to a character. But in the next sentence the reader will use verbal stress on the word “best”. Example-2 : HTML <!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Difference between <i> and <em> tag of HTML</title></head> <body> <h1><i>This senetence is in Italic</i></h1> <h1> <em>This sentence has emphasized meaning.</em></h1></body> </html> Output : Though they appears to be same but semantic meaning is different.Supported Browser : The browser supported by <i> and <em> tag are listed below. Chrome Android Firefox (Gecko) Firefox Mobile (Gecko) Internet Explorer (IE) Edge Mobile Opera Opera Mobile Safari (WebKit) Safari Mobile CSS Difference Between HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Dec, 2020" }, { "code": null, "e": 227, "s": 52, "text": "1. <i> tag :It is one of the element of HTML which is used in formatting HTML texts. It is used to define a text in technical term, alternative mood or voice, a thought, etc." }, { "code": null, "e": 236, "s": 227, "text": "Syntax :" }, { "code": null, "e": 256, "s": 236, "text": "<i> Content... </i>" }, { "code": null, "e": 385, "s": 256, "text": "2. <em> tag :It is also one of the element of HTML used in formatting texts. It is used to define emphasized text or statements." }, { "code": null, "e": 394, "s": 385, "text": "Syntax :" }, { "code": null, "e": 416, "s": 394, "text": "<em> Content... </em>" }, { "code": null, "e": 749, "s": 416, "text": "By default, the visual result is the same. The main difference between these two tag is that the <em> tag semantically emphasizes on the important word or section of words while <i> tag is just offset text conventionally styled in italic to show alternative mood or voice. Below is the code to show this difference between the two :" }, { "code": null, "e": 761, "s": 749, "text": "Example-1 :" }, { "code": null, "e": 766, "s": 761, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>b Tag</title> <style> body { text-align:center; } h1 { color: green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <p><i>Iron Man</i> is a hero.</p> <p>Gfg is the <em>best</em> educational site.</p> </body></html> ", "e": 1177, "s": 766, "text": null }, { "code": null, "e": 1186, "s": 1177, "text": "Output :" }, { "code": null, "e": 1419, "s": 1186, "text": "Here, there is no added emphasis or importance on the word “Iron Man”. It just indicates here iron isn’t a mineral or metal but it refers to a character. But in the next sentence the reader will use verbal stress on the word “best”." }, { "code": null, "e": 1431, "s": 1419, "text": "Example-2 :" }, { "code": null, "e": 1436, "s": 1431, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>Difference between <i> and <em> tag of HTML</title></head> <body> <h1><i>This senetence is in Italic</i></h1> <h1> <em>This sentence has emphasized meaning.</em></h1></body> </html>", "e": 1711, "s": 1436, "text": null }, { "code": null, "e": 1720, "s": 1711, "text": "Output :" }, { "code": null, "e": 1865, "s": 1720, "text": "Though they appears to be same but semantic meaning is different.Supported Browser : The browser supported by <i> and <em> tag are listed below." }, { "code": null, "e": 1872, "s": 1865, "text": "Chrome" }, { "code": null, "e": 1880, "s": 1872, "text": "Android" }, { "code": null, "e": 1896, "s": 1880, "text": "Firefox (Gecko)" }, { "code": null, "e": 1919, "s": 1896, "text": "Firefox Mobile (Gecko)" }, { "code": null, "e": 1942, "s": 1919, "text": "Internet Explorer (IE)" }, { "code": null, "e": 1954, "s": 1942, "text": "Edge Mobile" }, { "code": null, "e": 1960, "s": 1954, "text": "Opera" }, { "code": null, "e": 1973, "s": 1960, "text": "Opera Mobile" }, { "code": null, "e": 1989, "s": 1973, "text": "Safari (WebKit)" }, { "code": null, "e": 2003, "s": 1989, "text": "Safari Mobile" }, { "code": null, "e": 2007, "s": 2003, "text": "CSS" }, { "code": null, "e": 2026, "s": 2007, "text": "Difference Between" }, { "code": null, "e": 2031, "s": 2026, "text": "HTML" }, { "code": null, "e": 2036, "s": 2031, "text": "HTML" } ]
Ways to extract all dictionary values | Python
24 Oct, 2019 While working with Python dictionaries, there can be cases in which we are just concerned about getting the values list and don’t care about keys. This is yet another essential utility and solution to it should be known and discussed. Let’s perform this task through certain methods. Method #1 : Using loop + keys()The first method that comes to mind to achieve this task is the use of loop to access each key’s value and append it into a list and return it. This can be one of method to perform this task. # Python3 code to demonstrate working of# Ways to extract all dictionary values# Using loop + keys() # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Extracting all dictionary values# Using loop + keys()res = []for key in test_dict.keys() : res.append(test_dict[key]) # printing resultprint("The list of values is : " + str(res)) The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3} The list of values is : [1, 2, 3] Method #2 : Using values()This task can also be performed using the inbuilt function of values(). This is the best and most Pythonic way to perform this particular task and returns the exact desired result. # Python3 code to demonstrate working of# Ways to extract all dictionary values# Using values() # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Extracting all dictionary values# Using values()res = list(test_dict.values()) # printing resultprint("The list of values is : " + str(res)) The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3} The list of values is : [1, 2, 3] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? Python String | replace() Defaultdict in Python Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Oct, 2019" }, { "code": null, "e": 336, "s": 52, "text": "While working with Python dictionaries, there can be cases in which we are just concerned about getting the values list and don’t care about keys. This is yet another essential utility and solution to it should be known and discussed. Let’s perform this task through certain methods." }, { "code": null, "e": 559, "s": 336, "text": "Method #1 : Using loop + keys()The first method that comes to mind to achieve this task is the use of loop to access each key’s value and append it into a list and return it. This can be one of method to perform this task." }, { "code": "# Python3 code to demonstrate working of# Ways to extract all dictionary values# Using loop + keys() # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Extracting all dictionary values# Using loop + keys()res = []for key in test_dict.keys() : res.append(test_dict[key]) # printing resultprint(\"The list of values is : \" + str(res))", "e": 1007, "s": 559, "text": null }, { "code": null, "e": 1102, "s": 1007, "text": "The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3}\nThe list of values is : [1, 2, 3]\n" }, { "code": null, "e": 1311, "s": 1104, "text": "Method #2 : Using values()This task can also be performed using the inbuilt function of values(). This is the best and most Pythonic way to perform this particular task and returns the exact desired result." }, { "code": "# Python3 code to demonstrate working of# Ways to extract all dictionary values# Using values() # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Extracting all dictionary values# Using values()res = list(test_dict.values()) # printing resultprint(\"The list of values is : \" + str(res))", "e": 1712, "s": 1311, "text": null }, { "code": null, "e": 1807, "s": 1712, "text": "The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3}\nThe list of values is : [1, 2, 3]\n" }, { "code": null, "e": 1834, "s": 1807, "text": "Python dictionary-programs" }, { "code": null, "e": 1841, "s": 1834, "text": "Python" }, { "code": null, "e": 1857, "s": 1841, "text": "Python Programs" }, { "code": null, "e": 1955, "s": 1857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1973, "s": 1955, "text": "Python Dictionary" }, { "code": null, "e": 2015, "s": 1973, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2037, "s": 2015, "text": "Enumerate() in Python" }, { "code": null, "e": 2069, "s": 2037, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2095, "s": 2069, "text": "Python String | replace()" }, { "code": null, "e": 2117, "s": 2095, "text": "Defaultdict in Python" }, { "code": null, "e": 2155, "s": 2117, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2192, "s": 2155, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 2241, "s": 2192, "text": "Python | Convert string dictionary to dictionary" } ]
JavaScript match() Function - GeeksforGeeks
06 Oct, 2021 The string.match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Syntax: string.match(regExp) Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string. Return Value: It will return an array that contains the matches one item for each match or if the match will not found then it will return Null. JavaScript code to show the working of match() function: Example 1: Input: var string = Welcome to geeks for geeks! document.write(string.match(/eek/g); Output: eek, eek In the above example, substring “eek” will match with the given string, and when a match is found, it will return an array of string objects. Here “g” flag indicates that the regular expression should be tested against all possible matches in a string. code #1: javascript <script> // initializing function to demonstrate match() // method with "g" para function matchString() { var string = "Welcome to geeks for geeks"; var result = string.match(/eek/g); document.write("Output : " + result); } matchString(); </script> Output: eek,eek Example 2: Input: var string = "Welcome to GEEKS for geeks!"; document.write(string.match(/eek/i); Output: EEK In the above example, the substring “eek” will match with the given string, and it will return instantly if it found the match. Here “i” parameter helps to find the case-insensitive match in the given string. Code #2: javascript <script> // initializing function to demonstrate match() // method with "i" para function matchString() { var string = "Welcome to GEEKS for geeks!"; var result = string.match(/eek/i); document.write("Output : " + result); } matchString(); </script> Output: EEK Example 3: Input: var string = "Welcome to GEEKS for geeks!"; document.write(string.match(/eek/gi); Output: EEK, eek In the above example, the substring “eek” will match with the given string, and it will return instantly if it found the match. Here “gi” parameter helps to find the case-insensitive match AND all possible combinations in the given string. Code #3: javascript <script> // initializing function to demonstrate match() // method with "gi" para function matchString() { var string = "Welcome to GEEKS for geeks!"; var result = string.match(/eek/gi); document.write("Output : " + result); } matchString(); </script> Output: EEK,eek Supported Browser: chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 4 and above Opera 4 and above Safari 1 and above JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. ManasChhabra2 impress ysachin2314 javascript-functions JavaScript 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 ? How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request JavaScript | console.log() with Examples How to read a local text file using JavaScript? Node.js | fs.writeFileSync() Method
[ { "code": null, "e": 24768, "s": 24740, "text": "\n06 Oct, 2021" }, { "code": null, "e": 24970, "s": 24768, "text": "The string.match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Syntax: " }, { "code": null, "e": 24991, "s": 24970, "text": "string.match(regExp)" }, { "code": null, "e": 25317, "s": 24991, "text": "Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string. Return Value: It will return an array that contains the matches one item for each match or if the match will not found then it will return Null. JavaScript code to show the working of match() function: Example 1: " }, { "code": null, "e": 25420, "s": 25317, "text": "Input: \nvar string = Welcome to geeks for geeks!\ndocument.write(string.match(/eek/g);\nOutput:\neek, eek" }, { "code": null, "e": 25684, "s": 25420, "text": "In the above example, substring “eek” will match with the given string, and when a match is found, it will return an array of string objects. Here “g” flag indicates that the regular expression should be tested against all possible matches in a string. code #1: " }, { "code": null, "e": 25695, "s": 25684, "text": "javascript" }, { "code": "<script> // initializing function to demonstrate match() // method with \"g\" para function matchString() { var string = \"Welcome to geeks for geeks\"; var result = string.match(/eek/g); document.write(\"Output : \" + result); } matchString(); </script> ", "e": 26001, "s": 25695, "text": null }, { "code": null, "e": 26011, "s": 26001, "text": "Output: " }, { "code": null, "e": 26019, "s": 26011, "text": "eek,eek" }, { "code": null, "e": 26032, "s": 26019, "text": "Example 2: " }, { "code": null, "e": 26132, "s": 26032, "text": "Input:\nvar string = \"Welcome to GEEKS for geeks!\";\ndocument.write(string.match(/eek/i);\nOutput:\nEEK" }, { "code": null, "e": 26352, "s": 26132, "text": "In the above example, the substring “eek” will match with the given string, and it will return instantly if it found the match. Here “i” parameter helps to find the case-insensitive match in the given string. Code #2: " }, { "code": null, "e": 26363, "s": 26352, "text": "javascript" }, { "code": "<script> // initializing function to demonstrate match() // method with \"i\" para function matchString() { var string = \"Welcome to GEEKS for geeks!\"; var result = string.match(/eek/i); document.write(\"Output : \" + result); } matchString(); </script> ", "e": 26670, "s": 26363, "text": null }, { "code": null, "e": 26680, "s": 26670, "text": "Output: " }, { "code": null, "e": 26684, "s": 26680, "text": "EEK" }, { "code": null, "e": 26697, "s": 26684, "text": "Example 3: " }, { "code": null, "e": 26803, "s": 26697, "text": "Input:\nvar string = \"Welcome to GEEKS for geeks!\";\ndocument.write(string.match(/eek/gi);\nOutput:\nEEK, eek" }, { "code": null, "e": 27054, "s": 26803, "text": "In the above example, the substring “eek” will match with the given string, and it will return instantly if it found the match. Here “gi” parameter helps to find the case-insensitive match AND all possible combinations in the given string. Code #3: " }, { "code": null, "e": 27065, "s": 27054, "text": "javascript" }, { "code": "<script> // initializing function to demonstrate match() // method with \"gi\" para function matchString() { var string = \"Welcome to GEEKS for geeks!\"; var result = string.match(/eek/gi); document.write(\"Output : \" + result); } matchString(); </script> ", "e": 27374, "s": 27065, "text": null }, { "code": null, "e": 27384, "s": 27374, "text": "Output: " }, { "code": null, "e": 27392, "s": 27384, "text": "EEK,eek" }, { "code": null, "e": 27411, "s": 27392, "text": "Supported Browser:" }, { "code": null, "e": 27430, "s": 27411, "text": "chrome 1 and above" }, { "code": null, "e": 27448, "s": 27430, "text": "Edge 12 and above" }, { "code": null, "e": 27468, "s": 27448, "text": "Firefox 1 and above" }, { "code": null, "e": 27498, "s": 27468, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 27516, "s": 27498, "text": "Opera 4 and above" }, { "code": null, "e": 27536, "s": 27516, "text": "Safari 1 and above " }, { "code": null, "e": 27755, "s": 27536, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 27769, "s": 27755, "text": "ManasChhabra2" }, { "code": null, "e": 27777, "s": 27769, "text": "impress" }, { "code": null, "e": 27789, "s": 27777, "text": "ysachin2314" }, { "code": null, "e": 27810, "s": 27789, "text": "javascript-functions" }, { "code": null, "e": 27821, "s": 27810, "text": "JavaScript" }, { "code": null, "e": 27919, "s": 27821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27959, "s": 27919, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28004, "s": 27959, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28065, "s": 28004, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28137, "s": 28065, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28189, "s": 28137, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28235, "s": 28189, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28276, "s": 28235, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28317, "s": 28276, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 28365, "s": 28317, "text": "How to read a local text file using JavaScript?" } ]
Find if there is a path between two vertices in a directed graph - GeeksforGeeks
29 Mar, 2022 Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: Consider the following Graph: Input : (u, v) = (1, 3) Output: Yes Explanation: There is a path from 1 to 3, 1 -> 2 -> 3 Input : (u, v) = (3, 6) Output: No Explanation: There is no path from 3 to 6 Approach: Either Breadth First Search (BFS) or Depth First Search (DFS) can be used to find path between two vertices. Take the first vertex as source in BFS (or DFS), follow the standard BFS (or DFS). If the second vertex is found in our traversal, then return true else return false. BFS Algorithm: The implementation below is using BFS.Create a queue and a visited array initially filled with 0, of size V where V is number of vertices.Insert the starting node in the queue, i.e. push u in the queue and mark u as visited.Run a loop until the queue is not empty.Dequeue the front element of the queue. Iterate all its adjacent elements. If any of the adjacent element is the destination return true. Push all the adjacent and unvisited vertices in the queue and mark them as visited.Return false as the destination is not reached in BFS. The implementation below is using BFS. Create a queue and a visited array initially filled with 0, of size V where V is number of vertices. Insert the starting node in the queue, i.e. push u in the queue and mark u as visited. Run a loop until the queue is not empty. Dequeue the front element of the queue. Iterate all its adjacent elements. If any of the adjacent element is the destination return true. Push all the adjacent and unvisited vertices in the queue and mark them as visited. Return false as the destination is not reached in BFS. Implementation: C++, Java and Python codes that use BFS for finding reachability of the second vertex from the first vertex. C++ Java Python3 C# Javascript // C++ program to check if there is exist a path between two vertices// of a graph.#include<iostream>#include <list>using namespace std; // This class represents a directed graph using adjacency list// representationclass Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph bool isReachable(int s, int d); }; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // A BFS based function to check whether d is reachable from s.bool Graph::isReachable(int s, int d){ // Base case if (s == d) return true; // Mark all the vertices as not visited bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); // it will be used to get all adjacent vertices of a vertex list<int>::iterator i; while (!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); queue.pop_front(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it visited // and enqueue it for (i = adj[s].begin(); i != adj[s].end(); ++i) { // If this adjacent node is the destination node, then // return true if (*i == d) return true; // Else, continue to do BFS if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } // If BFS is complete without visiting d return false;} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); int u = 1, v = 3; if(g.isReachable(u, v)) cout<< "\n There is a path from " << u << " to " << v; else cout<< "\n There is no path from " << u << " to " << v; u = 3, v = 1; if(g.isReachable(u, v)) cout<< "\n There is a path from " << u << " to " << v; else cout<< "\n There is no path from " << u << " to " << v; return 0;} // Java program to check if there is exist a path between two vertices// of a graph.import java.io.*;import java.util.*;import java.util.LinkedList; // This class represents a directed graph using adjacency list// representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } //prints BFS traversal from a given source s Boolean isReachable(int s, int d) { LinkedList<Integer>temp; // Mark all the vertices as not visited(By default set // as false) boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<Integer>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); // 'i' will be used to get all adjacent vertices of a vertex Iterator<Integer> i; while (queue.size()!=0) { // Dequeue a vertex from queue and print it s = queue.poll(); int n; i = adj[s].listIterator(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it while (i.hasNext()) { n = i.next(); // If this adjacent node is the destination node, // then return true if (n==d) return true; // Else, continue to do BFS if (!visited[n]) { visited[n] = true; queue.add(n); } } } // If BFS is complete without visited d return false; } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); int u = 1; int v = 3; if (g.isReachable(u, v)) System.out.println("There is a path from " + u +" to " + v); else System.out.println("There is no path from " + u +" to " + v);; u = 3; v = 1; if (g.isReachable(u, v)) System.out.println("There is a path from " + u +" to " + v); else System.out.println("There is no path from " + u +" to " + v);; }}// This code is contributed by Aakash Hasija # program to check if there is exist a path between two vertices# of a graph from collections import defaultdict #This class represents a directed graph using adjacency list representationclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Use BFS to check path between s and d def isReachable(self, s, d): # Mark all the vertices as not visited visited =[False]*(self.V) # Create a queue for BFS queue=[] # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True while queue: #Dequeue a vertex from queue n = queue.pop(0) # If this adjacent node is the destination node, # then return true if n == d: return True # Else, continue to do BFS for i in self.graph[n]: if visited[i] == False: queue.append(i) visited[i] = True # If BFS is complete without visited d return False # Create a graph given in the above diagramg = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) u =1; v = 3 if g.isReachable(u, v): print("There is a path from %d to %d" % (u,v))else : print("There is no path from %d to %d" % (u,v)) u = 3; v = 1if g.isReachable(u, v) : print("There is a path from %d to %d" % (u,v))else : print("There is no path from %d to %d" % (u,v)) #This code is contributed by Neelam Yadav // C# program to check if there is// exist a path between two vertices// of a graph.using System;using System.Collections;using System.Collections.Generic; // This class represents a directed// graph using adjacency list// representationclass Graph{ private int V; // No. of vertices private LinkedList<int>[] adj; //Adjacency List // Constructor Graph(int v) { V = v; adj = new LinkedList<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].AddLast(w); } // prints BFS traversal from a given source s bool isReachable(int s, int d) { // LinkedList<int> temp = new LinkedList<int>(); // Mark all the vertices as not visited(By default set // as false) bool[] visited = new bool[V]; // Create a queue for BFS LinkedList<int> queue = new LinkedList<int>(); // Mark the current node as visited and enqueue it visited[s] = true; queue.AddLast(s); // 'i' will be used to get all adjacent vertices of a vertex IEnumerator i; while (queue.Count != 0) { // Dequeue a vertex from queue and print it s = queue.First.Value; queue.RemoveFirst(); int n; i = adj[s].GetEnumerator(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it while (i.MoveNext()) { n = (int)i.Current; // If this adjacent node is the destination node, // then return true if (n == d) return true; // Else, continue to do BFS if (!visited[n]) { visited[n] = true; queue.AddLast(n); } } } // If BFS is complete without visited d return false; } // Driver method public static void Main(string[] args) { // Create a graph given in the above diagram Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); int u = 1; int v = 3; if (g.isReachable(u, v)) Console.WriteLine("There is a path from " + u + " to " + v); else Console.WriteLine("There is no path from " + u + " to " + v); u = 3; v = 1; if (g.isReachable(u, v)) Console.WriteLine("There is a path from " + u + " to " + v); else Console.WriteLine("There is no path from " + u + " to " + v); }} // This code is contributed by sanjeev2552 <script>// Javascript program to check if there is exist a path between two vertices// of a graph.let V;let adj; function Graph( v){ V = v; adj = new Array(v); for (let i = 0; i < v; ++i) adj[i] = [];} // Function to add an edge into the graphfunction addEdge(v,w){ adj[v].push(w);} // prints BFS traversal from a given source sfunction isReachable(s,d){ let temp; // Mark all the vertices as not visited(By default set // as false) let visited = new Array(V); for(let i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS let queue = []; // Mark the current node as visited and enqueue it visited[s] = true; queue.push(s); while (queue.length != 0) { // Dequeue a vertex from queue and print it n = queue.shift(); if(n == d) return true; for(let i = 0; i < adj[n].length; i++) { if (visited[adj[n][i]] == false) { queue.push(adj[n][i]); visited[adj[n][i]] = true; } } } // If BFS is complete without visited d return false;} // Driver methodGraph(4);addEdge(0, 1);addEdge(0, 2);addEdge(1, 2);addEdge(2, 0);addEdge(2, 3);addEdge(3, 3); let u = 1;let v = 3;if (isReachable(u, v)) document.write("There is a path from " + u +" to " + v+"<br>");else document.write("There is no path from " + u +" to " + v+"<br>"); u = 3;v = 1;if (isReachable(u, v)) document.write("There is a path from " + u +" to " + v+"<br>");else document.write("There is no path from " + u +" to " + v+"<br>"); // This code is contributed by avanitrachhadiya2155</script> There is a path from 1 to 3 There is no path from 3 to 1 Complexity Analysis: Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph. Space Complexity: O(V). There can be atmost V elements in the queue. So the space needed is O(V). DFS Algorithm: 1. if start==end return 1 since we have to reached our destination. 2. Mark start as visited. 3. Traverse directly connected vertices of start and recur the function dfs for every such unexplored vertex. 4. return 0 if we do not reach our destination. Implementation: C++14 #include <bits/stdc++.h>using namespace std;typedef long long ll; vector<ll> adj[100000];bool visited[100000]; bool dfs(int start, int end){ if (start == end) return true; visited[start] = 1; for (auto x : adj[start]) { if (!visited[x]) if (dfs(x, end)) return true; } return false;} int main(){ int V = 4; vector<ll> members = { 2, 5, 7, 9 }; int E = 4; vector<pair<ll, ll> > connections = { { 2, 9 }, { 7, 2 }, { 7, 9 }, { 9, 5 } }; for (int i = 0; i < E; i++) adj[connections[i].first].push_back( connections[i].second); int sender = 7, receiver = 9; if (dfs(sender, receiver)) cout << "1"; else cout << "0"; return 0;}// this code is contributed by prophet1999 1 Complexity Analysis: Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.Space Complexity: O(V). There can be atmost V elements in the stack. So the space needed is O(V). Trade-offs between BFS and DFS: Breadth-First search can be useful to find the shortest path between nodes, and depth-first search may traverse one adjacent node very deeply before ever going into immediate neighbours. As an exercise, try an extended version of the problem where the complete path between two vertices is also needed.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Shaik Suraz andrew1234 sanjeev2552 avanitrachhadiya2155 adnanirshad158 amartyaghoshgfg prophet1999 BFS Graph Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Traveling Salesman Problem (TSP) Implementation Detect cycle in an undirected graph Hamiltonian Cycle | Backtracking-6 m Coloring Problem | Backtracking-5 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 26585, "s": 26557, "text": "\n29 Mar, 2022" }, { "code": null, "e": 26711, "s": 26585, "text": "Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. Example: " }, { "code": null, "e": 26911, "s": 26711, "text": "Consider the following Graph:\n\n\nInput : (u, v) = (1, 3)\nOutput: Yes\nExplanation: There is a path from 1 to 3, 1 -> 2 -> 3\n\nInput : (u, v) = (3, 6)\nOutput: No\nExplanation: There is no path from 3 to 6" }, { "code": null, "e": 27199, "s": 26913, "text": "Approach: Either Breadth First Search (BFS) or Depth First Search (DFS) can be used to find path between two vertices. Take the first vertex as source in BFS (or DFS), follow the standard BFS (or DFS). If the second vertex is found in our traversal, then return true else return false." }, { "code": null, "e": 27215, "s": 27199, "text": "BFS Algorithm: " }, { "code": null, "e": 27755, "s": 27215, "text": "The implementation below is using BFS.Create a queue and a visited array initially filled with 0, of size V where V is number of vertices.Insert the starting node in the queue, i.e. push u in the queue and mark u as visited.Run a loop until the queue is not empty.Dequeue the front element of the queue. Iterate all its adjacent elements. If any of the adjacent element is the destination return true. Push all the adjacent and unvisited vertices in the queue and mark them as visited.Return false as the destination is not reached in BFS." }, { "code": null, "e": 27794, "s": 27755, "text": "The implementation below is using BFS." }, { "code": null, "e": 27895, "s": 27794, "text": "Create a queue and a visited array initially filled with 0, of size V where V is number of vertices." }, { "code": null, "e": 27982, "s": 27895, "text": "Insert the starting node in the queue, i.e. push u in the queue and mark u as visited." }, { "code": null, "e": 28023, "s": 27982, "text": "Run a loop until the queue is not empty." }, { "code": null, "e": 28245, "s": 28023, "text": "Dequeue the front element of the queue. Iterate all its adjacent elements. If any of the adjacent element is the destination return true. Push all the adjacent and unvisited vertices in the queue and mark them as visited." }, { "code": null, "e": 28300, "s": 28245, "text": "Return false as the destination is not reached in BFS." }, { "code": null, "e": 28426, "s": 28300, "text": "Implementation: C++, Java and Python codes that use BFS for finding reachability of the second vertex from the first vertex. " }, { "code": null, "e": 28430, "s": 28426, "text": "C++" }, { "code": null, "e": 28435, "s": 28430, "text": "Java" }, { "code": null, "e": 28443, "s": 28435, "text": "Python3" }, { "code": null, "e": 28446, "s": 28443, "text": "C#" }, { "code": null, "e": 28457, "s": 28446, "text": "Javascript" }, { "code": "// C++ program to check if there is exist a path between two vertices// of a graph.#include<iostream>#include <list>using namespace std; // This class represents a directed graph using adjacency list// representationclass Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph bool isReachable(int s, int d); }; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // A BFS based function to check whether d is reachable from s.bool Graph::isReachable(int s, int d){ // Base case if (s == d) return true; // Mark all the vertices as not visited bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); // it will be used to get all adjacent vertices of a vertex list<int>::iterator i; while (!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); queue.pop_front(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it visited // and enqueue it for (i = adj[s].begin(); i != adj[s].end(); ++i) { // If this adjacent node is the destination node, then // return true if (*i == d) return true; // Else, continue to do BFS if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } } // If BFS is complete without visiting d return false;} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); int u = 1, v = 3; if(g.isReachable(u, v)) cout<< \"\\n There is a path from \" << u << \" to \" << v; else cout<< \"\\n There is no path from \" << u << \" to \" << v; u = 3, v = 1; if(g.isReachable(u, v)) cout<< \"\\n There is a path from \" << u << \" to \" << v; else cout<< \"\\n There is no path from \" << u << \" to \" << v; return 0;}", "e": 30970, "s": 28457, "text": null }, { "code": "// Java program to check if there is exist a path between two vertices// of a graph.import java.io.*;import java.util.*;import java.util.LinkedList; // This class represents a directed graph using adjacency list// representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); } //prints BFS traversal from a given source s Boolean isReachable(int s, int d) { LinkedList<Integer>temp; // Mark all the vertices as not visited(By default set // as false) boolean visited[] = new boolean[V]; // Create a queue for BFS LinkedList<Integer> queue = new LinkedList<Integer>(); // Mark the current node as visited and enqueue it visited[s]=true; queue.add(s); // 'i' will be used to get all adjacent vertices of a vertex Iterator<Integer> i; while (queue.size()!=0) { // Dequeue a vertex from queue and print it s = queue.poll(); int n; i = adj[s].listIterator(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it while (i.hasNext()) { n = i.next(); // If this adjacent node is the destination node, // then return true if (n==d) return true; // Else, continue to do BFS if (!visited[n]) { visited[n] = true; queue.add(n); } } } // If BFS is complete without visited d return false; } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); int u = 1; int v = 3; if (g.isReachable(u, v)) System.out.println(\"There is a path from \" + u +\" to \" + v); else System.out.println(\"There is no path from \" + u +\" to \" + v);; u = 3; v = 1; if (g.isReachable(u, v)) System.out.println(\"There is a path from \" + u +\" to \" + v); else System.out.println(\"There is no path from \" + u +\" to \" + v);; }}// This code is contributed by Aakash Hasija", "e": 33754, "s": 30970, "text": null }, { "code": "# program to check if there is exist a path between two vertices# of a graph from collections import defaultdict #This class represents a directed graph using adjacency list representationclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # Use BFS to check path between s and d def isReachable(self, s, d): # Mark all the vertices as not visited visited =[False]*(self.V) # Create a queue for BFS queue=[] # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True while queue: #Dequeue a vertex from queue n = queue.pop(0) # If this adjacent node is the destination node, # then return true if n == d: return True # Else, continue to do BFS for i in self.graph[n]: if visited[i] == False: queue.append(i) visited[i] = True # If BFS is complete without visited d return False # Create a graph given in the above diagramg = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) u =1; v = 3 if g.isReachable(u, v): print(\"There is a path from %d to %d\" % (u,v))else : print(\"There is no path from %d to %d\" % (u,v)) u = 3; v = 1if g.isReachable(u, v) : print(\"There is a path from %d to %d\" % (u,v))else : print(\"There is no path from %d to %d\" % (u,v)) #This code is contributed by Neelam Yadav", "e": 35494, "s": 33754, "text": null }, { "code": "// C# program to check if there is// exist a path between two vertices// of a graph.using System;using System.Collections;using System.Collections.Generic; // This class represents a directed// graph using adjacency list// representationclass Graph{ private int V; // No. of vertices private LinkedList<int>[] adj; //Adjacency List // Constructor Graph(int v) { V = v; adj = new LinkedList<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].AddLast(w); } // prints BFS traversal from a given source s bool isReachable(int s, int d) { // LinkedList<int> temp = new LinkedList<int>(); // Mark all the vertices as not visited(By default set // as false) bool[] visited = new bool[V]; // Create a queue for BFS LinkedList<int> queue = new LinkedList<int>(); // Mark the current node as visited and enqueue it visited[s] = true; queue.AddLast(s); // 'i' will be used to get all adjacent vertices of a vertex IEnumerator i; while (queue.Count != 0) { // Dequeue a vertex from queue and print it s = queue.First.Value; queue.RemoveFirst(); int n; i = adj[s].GetEnumerator(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it while (i.MoveNext()) { n = (int)i.Current; // If this adjacent node is the destination node, // then return true if (n == d) return true; // Else, continue to do BFS if (!visited[n]) { visited[n] = true; queue.AddLast(n); } } } // If BFS is complete without visited d return false; } // Driver method public static void Main(string[] args) { // Create a graph given in the above diagram Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); int u = 1; int v = 3; if (g.isReachable(u, v)) Console.WriteLine(\"There is a path from \" + u + \" to \" + v); else Console.WriteLine(\"There is no path from \" + u + \" to \" + v); u = 3; v = 1; if (g.isReachable(u, v)) Console.WriteLine(\"There is a path from \" + u + \" to \" + v); else Console.WriteLine(\"There is no path from \" + u + \" to \" + v); }} // This code is contributed by sanjeev2552", "e": 38001, "s": 35494, "text": null }, { "code": "<script>// Javascript program to check if there is exist a path between two vertices// of a graph.let V;let adj; function Graph( v){ V = v; adj = new Array(v); for (let i = 0; i < v; ++i) adj[i] = [];} // Function to add an edge into the graphfunction addEdge(v,w){ adj[v].push(w);} // prints BFS traversal from a given source sfunction isReachable(s,d){ let temp; // Mark all the vertices as not visited(By default set // as false) let visited = new Array(V); for(let i = 0; i < V; i++) visited[i] = false; // Create a queue for BFS let queue = []; // Mark the current node as visited and enqueue it visited[s] = true; queue.push(s); while (queue.length != 0) { // Dequeue a vertex from queue and print it n = queue.shift(); if(n == d) return true; for(let i = 0; i < adj[n].length; i++) { if (visited[adj[n][i]] == false) { queue.push(adj[n][i]); visited[adj[n][i]] = true; } } } // If BFS is complete without visited d return false;} // Driver methodGraph(4);addEdge(0, 1);addEdge(0, 2);addEdge(1, 2);addEdge(2, 0);addEdge(2, 3);addEdge(3, 3); let u = 1;let v = 3;if (isReachable(u, v)) document.write(\"There is a path from \" + u +\" to \" + v+\"<br>\");else document.write(\"There is no path from \" + u +\" to \" + v+\"<br>\"); u = 3;v = 1;if (isReachable(u, v)) document.write(\"There is a path from \" + u +\" to \" + v+\"<br>\");else document.write(\"There is no path from \" + u +\" to \" + v+\"<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 39826, "s": 38001, "text": null }, { "code": null, "e": 39885, "s": 39826, "text": " There is a path from 1 to 3\n There is no path from 3 to 1" }, { "code": null, "e": 39908, "s": 39885, "text": "Complexity Analysis: " }, { "code": null, "e": 40014, "s": 39908, "text": "Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph." }, { "code": null, "e": 40112, "s": 40014, "text": "Space Complexity: O(V). There can be atmost V elements in the queue. So the space needed is O(V)." }, { "code": null, "e": 40127, "s": 40112, "text": "DFS Algorithm:" }, { "code": null, "e": 40195, "s": 40127, "text": "1. if start==end return 1 since we have to reached our destination." }, { "code": null, "e": 40221, "s": 40195, "text": "2. Mark start as visited." }, { "code": null, "e": 40331, "s": 40221, "text": "3. Traverse directly connected vertices of start and recur the function dfs for every such unexplored vertex." }, { "code": null, "e": 40379, "s": 40331, "text": "4. return 0 if we do not reach our destination." }, { "code": null, "e": 40395, "s": 40379, "text": "Implementation:" }, { "code": null, "e": 40401, "s": 40395, "text": "C++14" }, { "code": "#include <bits/stdc++.h>using namespace std;typedef long long ll; vector<ll> adj[100000];bool visited[100000]; bool dfs(int start, int end){ if (start == end) return true; visited[start] = 1; for (auto x : adj[start]) { if (!visited[x]) if (dfs(x, end)) return true; } return false;} int main(){ int V = 4; vector<ll> members = { 2, 5, 7, 9 }; int E = 4; vector<pair<ll, ll> > connections = { { 2, 9 }, { 7, 2 }, { 7, 9 }, { 9, 5 } }; for (int i = 0; i < E; i++) adj[connections[i].first].push_back( connections[i].second); int sender = 7, receiver = 9; if (dfs(sender, receiver)) cout << \"1\"; else cout << \"0\"; return 0;}// this code is contributed by prophet1999", "e": 41193, "s": 40401, "text": null }, { "code": null, "e": 41195, "s": 41193, "text": "1" }, { "code": null, "e": 41218, "s": 41195, "text": "Complexity Analysis: " }, { "code": null, "e": 41421, "s": 41218, "text": "Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.Space Complexity: O(V). There can be atmost V elements in the stack. So the space needed is O(V)." }, { "code": null, "e": 41880, "s": 41421, "text": "Trade-offs between BFS and DFS: Breadth-First search can be useful to find the shortest path between nodes, and depth-first search may traverse one adjacent node very deeply before ever going into immediate neighbours. As an exercise, try an extended version of the problem where the complete path between two vertices is also needed.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 41892, "s": 41880, "text": "Shaik Suraz" }, { "code": null, "e": 41903, "s": 41892, "text": "andrew1234" }, { "code": null, "e": 41915, "s": 41903, "text": "sanjeev2552" }, { "code": null, "e": 41936, "s": 41915, "text": "avanitrachhadiya2155" }, { "code": null, "e": 41951, "s": 41936, "text": "adnanirshad158" }, { "code": null, "e": 41967, "s": 41951, "text": "amartyaghoshgfg" }, { "code": null, "e": 41979, "s": 41967, "text": "prophet1999" }, { "code": null, "e": 41983, "s": 41979, "text": "BFS" }, { "code": null, "e": 41989, "s": 41983, "text": "Graph" }, { "code": null, "e": 41995, "s": 41989, "text": "Graph" }, { "code": null, "e": 41999, "s": 41995, "text": "BFS" }, { "code": null, "e": 42097, "s": 41999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42117, "s": 42097, "text": "Topological Sorting" }, { "code": null, "e": 42150, "s": 42117, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 42218, "s": 42150, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 42268, "s": 42218, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 42343, "s": 42268, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 42391, "s": 42343, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 42427, "s": 42391, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 42462, "s": 42427, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 42498, "s": 42462, "text": "m Coloring Problem | Backtracking-5" } ]
How to handle events in dynamically created elements in jQuery ? - GeeksforGeeks
30 Jun, 2020 When we want to bind any event to an element, normally we could directly bind to any event of each element using the on() method. Example 1: This example using jQuery on() method to add paragraph element dynamically. <!DOCTYPE html><html> <head> <title> How to handle events in dynamically created elements in jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("#list li").on("click", function (event) { $('#list').append('<li>New Paragraph</li>'); }); }); </script> <style> li { font-size: 30px; width: 400px; padding: 20px; color: green; } </style></head> <body> <!-- Click on this paragraph --> <ul id="list"> <li>Click here to append !!!</li> </ul></body> </html> Output: This works really well, but when we add a new list item and click it, nothing happens. This is because of the event handler attached before which is executed when the document is loaded. At that time only the first list item existed and not the new ones. Hence the .on() method was applied only for the first list item and not the rest. Example 2: The following example is implemented using on() method. <!DOCTYPE html><html> <head> <title> How to handle events in dynamically created elements in jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("#list").on("click", "li", function (event) { $('#list').append( '<li>New Paragraph</li>'); }); }); </script> <style> li { font-size: 30px; width: 400px; padding: 20px; color: green; } </style></head> <body> <ul id="list"> <!-- Click on this item --> <li>Click here to check on()!!!</li> </ul></body> </html> Output: Example 3: The following example is implemented using delegate() function. To bind the event handler to dynamically created elements, we will be using Event Delegation. On clicking the new list items, the same action is performed. Event delegation is the process that allows us to attach a single event listener, to the parent element and it will fire for all the children elements that exist now or will be added in the future. Both on() and delegate() functions allow us to do event delegation. <!DOCTYPE html><html> <head> <title> How to handle events in dynamically created elements in jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("#list").delegate("li", "click", function (event) { $('#list').append( '<li>New Paragraph</li>'); }); }); </script> <style> li { font-size: 30px; width: 400px; padding: 20px; color: green; } </style></head> <body> <ul id="list"> <!-- Click on this item --> <li>Click to check delegate !!!</li> </ul></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc Picked 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. How to apply style to parent if it has child with CSS? How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26174, "s": 26146, "text": "\n30 Jun, 2020" }, { "code": null, "e": 26304, "s": 26174, "text": "When we want to bind any event to an element, normally we could directly bind to any event of each element using the on() method." }, { "code": null, "e": 26391, "s": 26304, "text": "Example 1: This example using jQuery on() method to add paragraph element dynamically." }, { "code": "<!DOCTYPE html><html> <head> <title> How to handle events in dynamically created elements in jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"#list li\").on(\"click\", function (event) { $('#list').append('<li>New Paragraph</li>'); }); }); </script> <style> li { font-size: 30px; width: 400px; padding: 20px; color: green; } </style></head> <body> <!-- Click on this paragraph --> <ul id=\"list\"> <li>Click here to append !!!</li> </ul></body> </html>", "e": 27115, "s": 26391, "text": null }, { "code": null, "e": 27123, "s": 27115, "text": "Output:" }, { "code": null, "e": 27460, "s": 27123, "text": "This works really well, but when we add a new list item and click it, nothing happens. This is because of the event handler attached before which is executed when the document is loaded. At that time only the first list item existed and not the new ones. Hence the .on() method was applied only for the first list item and not the rest." }, { "code": null, "e": 27527, "s": 27460, "text": "Example 2: The following example is implemented using on() method." }, { "code": "<!DOCTYPE html><html> <head> <title> How to handle events in dynamically created elements in jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"#list\").on(\"click\", \"li\", function (event) { $('#list').append( '<li>New Paragraph</li>'); }); }); </script> <style> li { font-size: 30px; width: 400px; padding: 20px; color: green; } </style></head> <body> <ul id=\"list\"> <!-- Click on this item --> <li>Click here to check on()!!!</li> </ul></body> </html>", "e": 28302, "s": 27527, "text": null }, { "code": null, "e": 28310, "s": 28302, "text": "Output:" }, { "code": null, "e": 28541, "s": 28310, "text": "Example 3: The following example is implemented using delegate() function. To bind the event handler to dynamically created elements, we will be using Event Delegation. On clicking the new list items, the same action is performed." }, { "code": null, "e": 28807, "s": 28541, "text": "Event delegation is the process that allows us to attach a single event listener, to the parent element and it will fire for all the children elements that exist now or will be added in the future. Both on() and delegate() functions allow us to do event delegation." }, { "code": "<!DOCTYPE html><html> <head> <title> How to handle events in dynamically created elements in jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"#list\").delegate(\"li\", \"click\", function (event) { $('#list').append( '<li>New Paragraph</li>'); }); }); </script> <style> li { font-size: 30px; width: 400px; padding: 20px; color: green; } </style></head> <body> <ul id=\"list\"> <!-- Click on this item --> <li>Click to check delegate !!!</li> </ul></body> </html>", "e": 29581, "s": 28807, "text": null }, { "code": null, "e": 29589, "s": 29581, "text": "Output:" }, { "code": null, "e": 29726, "s": 29589, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29735, "s": 29726, "text": "CSS-Misc" }, { "code": null, "e": 29745, "s": 29735, "text": "HTML-Misc" }, { "code": null, "e": 29757, "s": 29745, "text": "jQuery-Misc" }, { "code": null, "e": 29764, "s": 29757, "text": "Picked" }, { "code": null, "e": 29768, "s": 29764, "text": "CSS" }, { "code": null, "e": 29773, "s": 29768, "text": "HTML" }, { "code": null, "e": 29780, "s": 29773, "text": "JQuery" }, { "code": null, "e": 29797, "s": 29780, "text": "Web Technologies" }, { "code": null, "e": 29824, "s": 29797, "text": "Web technologies Questions" }, { "code": null, "e": 29829, "s": 29824, "text": "HTML" }, { "code": null, "e": 29927, "s": 29829, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29982, "s": 29927, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 30021, "s": 29982, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30082, "s": 30021, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 30119, "s": 30082, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30160, "s": 30119, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 30220, "s": 30160, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30273, "s": 30220, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30334, "s": 30273, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30358, "s": 30334, "text": "REST API (Introduction)" } ]
Display Command Output or File Contents in Column Format in Linux
Sometimes there may be too many columns crammed into a single file. That makes it difficult to read the content of the file and point out which data belongs to which column. In order to have a better view, we ca use certain commands that will allocate space between the columns and also mark some separation characters that will make it clear to see the beginning and end of the column. Lets’ look at the below sample file which we will use to demonstrate the column command. We can get the file from kaggle.here. $ cat iris.data Running the above code gives us the following result − Id,SepalLengthCm,SepalWidthCm,PetalLengthCm,PetalWidthCm,Species 1,5.1,3.5,1.4,0.2,Iris-setosa 2,4.9,3.0,1.4,0.2,Iris-setosa 3,4.7,3.2,1.3,0.2,Iris-setosa 4,4.6,3.1,1.5,0.2,Iris-setosa 5,5.0,3.6,1.4,0.2,Iris-setosa 6,5.4,3.9,1.7,0.4,Iris-setosa 7,4.6,3.4,1.4,0.3,Iris-setosa ............... ............. The column command makes the layout of the column very clear. It uses the –t and –s switches. The -t helps to determine the number of columns the input contains and creates a table and the -s specifies a delimiter character. $ cat iris.data | column -t -s "," Running the above code gives us the following result − SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species 5.1 3.5 1.4 0.2 Iris-setosa 4.9 3.0 1.4 0.2 Iris-setosa 4.7 3.2 1.3 0.2 Iris-setosa 4.6 3.1 1.5 0.2 Iris-setosa 5.0 3.6 1.4 0.2 Iris-setosa 5.4 3.9 1.7 0.4 Iris-setosa 4.6 3.4 1.4 0.3 Iris-setosa 5.0 3.4 1.5 0.2 Iris-setosa 4.4 2.9 1.4 0.2 Iris-setosa 4.9 3.1 1.5 0.1 Iris-setosa 5.4 3.7 1.5 0.2 Iris-setosa 4.8 3.4 1.6 0.2 Iris-setosa 4.8 3.0 1.4 0.1 Iris-setosa Another example is the mount command which is most often used by unix admins. The original result is not clearly legible, but we can make it columnar and nicely formatted. $ mount Running the above code gives us the following result − sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime) proc on /proc type proc (rw,nosuid,nodev,noexec,relatime) udev on /dev type devtmpfs (rw,nosuid,relatime,size=1977472k,nr_inodes=494368,mode=755) devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000) tmpfs on /run type tmpfs (rw,nosuid,noexec,relatime,size=401592k,mode=755) /dev/sda1 on / type ext4 (rw,relatime,errors=remount-ro,data=ordered) securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime) tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev) tmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k) tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755) cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd) Then we runt he below command which gives us a formatted output. $ mount | column –t Next we run it with the mount command. sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime) proc on /proc type proc (rw,nosuid,nodev,noexec,relatime) udev on /dev type devtmpfs (rw,nosuid,relatime,size=1977472k,nr_inodes=494368,mode=755) devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000) tmpfs on /run type tmpfs (rw,nosuid,noexec,relatime,size=401592k,mode=755) /dev/sda1 on / type ext4 (rw,relatime,errors=remount-ro,data=ordered)
[ { "code": null, "e": 1449, "s": 1062, "text": "Sometimes there may be too many columns crammed into a single file. That makes it difficult to read the content of the file and point out which data belongs to which column. In order to have a better view, we ca use certain commands that will allocate space between the columns and also mark some separation characters that will make it clear to see the beginning and end of the column." }, { "code": null, "e": 1576, "s": 1449, "text": "Lets’ look at the below sample file which we will use to demonstrate the column command. We can get the file from kaggle.here." }, { "code": null, "e": 1592, "s": 1576, "text": "$ cat iris.data" }, { "code": null, "e": 1647, "s": 1592, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1952, "s": 1647, "text": "Id,SepalLengthCm,SepalWidthCm,PetalLengthCm,PetalWidthCm,Species\n1,5.1,3.5,1.4,0.2,Iris-setosa\n2,4.9,3.0,1.4,0.2,Iris-setosa\n3,4.7,3.2,1.3,0.2,Iris-setosa\n4,4.6,3.1,1.5,0.2,Iris-setosa\n5,5.0,3.6,1.4,0.2,Iris-setosa\n6,5.4,3.9,1.7,0.4,Iris-setosa\n7,4.6,3.4,1.4,0.3,Iris-setosa\n...............\n............." }, { "code": null, "e": 2177, "s": 1952, "text": "The column command makes the layout of the column very clear. It uses the –t and –s switches. The -t helps to determine the number of columns the input contains and creates a table and the -s specifies a delimiter character." }, { "code": null, "e": 2212, "s": 2177, "text": "$ cat iris.data | column -t -s \",\"" }, { "code": null, "e": 2267, "s": 2212, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3497, "s": 2267, "text": "SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm Species\n5.1 3.5 1.4 0.2 Iris-setosa\n4.9 3.0 1.4 0.2 Iris-setosa\n4.7 3.2 1.3 0.2 Iris-setosa\n4.6 3.1 1.5 0.2 Iris-setosa\n5.0 3.6 1.4 0.2 Iris-setosa\n5.4 3.9 1.7 0.4 Iris-setosa\n4.6 3.4 1.4 0.3 Iris-setosa\n5.0 3.4 1.5 0.2 Iris-setosa\n4.4 2.9 1.4 0.2 Iris-setosa\n4.9 3.1 1.5 0.1 Iris-setosa\n5.4 3.7 1.5 0.2 Iris-setosa\n4.8 3.4 1.6 0.2 Iris-setosa\n4.8 3.0 1.4 0.1 Iris-setosa" }, { "code": null, "e": 3669, "s": 3497, "text": "Another example is the mount command which is most often used by unix admins. The original result is not clearly legible, but we can make it columnar and nicely formatted." }, { "code": null, "e": 3677, "s": 3669, "text": "$ mount" }, { "code": null, "e": 3732, "s": 3677, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 4592, "s": 3732, "text": "sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)\nproc on /proc type proc (rw,nosuid,nodev,noexec,relatime)\nudev on /dev type devtmpfs (rw,nosuid,relatime,size=1977472k,nr_inodes=494368,mode=755)\ndevpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)\ntmpfs on /run type tmpfs (rw,nosuid,noexec,relatime,size=401592k,mode=755)\n/dev/sda1 on / type ext4 (rw,relatime,errors=remount-ro,data=ordered)\nsecurityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)\ntmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)\ntmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k)\ntmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755)\ncgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd)" }, { "code": null, "e": 4657, "s": 4592, "text": "Then we runt he below command which gives us a formatted output." }, { "code": null, "e": 4677, "s": 4657, "text": "$ mount | column –t" }, { "code": null, "e": 4716, "s": 4677, "text": "Next we run it with the mount command." }, { "code": null, "e": 5274, "s": 4716, "text": "sysfs on /sys type sysfs\n(rw,nosuid,nodev,noexec,relatime)\nproc on /proc type proc\n(rw,nosuid,nodev,noexec,relatime)\nudev on /dev type devtmpfs\n(rw,nosuid,relatime,size=1977472k,nr_inodes=494368,mode=755)\ndevpts on /dev/pts type devpts\n(rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)\ntmpfs on /run type tmpfs\n(rw,nosuid,noexec,relatime,size=401592k,mode=755)\n/dev/sda1 on / type ext4 \n(rw,relatime,errors=remount-ro,data=ordered)" } ]
Binary Tree | Set 2 (Properties)
27 Jun, 2022 We have discussed Introduction to Binary Tree in set 1. In this post, the properties of a binary tree are discussed. 1) The maximum number of nodes at level ‘l’ of a binary tree is 2l. Here level is the number of nodes on the path from the root to the node (including root and node). Level of the root is 0. This can be proved by induction. For root, l = 0, number of nodes = 20 = 1 Assume that the maximum number of nodes on level ‘l’ is 2l Since in Binary tree every node has at most 2 children, next level would have twice nodes, i.e. 2 * 2l 2) The Maximum number of nodes in a binary tree of height ‘h’ is 2h – 1. Here the height of a tree is the maximum number of nodes on the root to leaf path. Height of a tree with a single node is considered as 1. This result can be derived from point 2 above. A tree has maximum nodes if all levels have maximum nodes. So maximum number of nodes in a binary tree of height h is 1 + 2 + 4 + .. + 2h-1. This is a simple geometric series with h terms and sum of this series is 2h– 1. In some books, the height of the root is considered as 0. In this convention, the above formula becomes 2h+1 – 1 3) In a Binary Tree with N nodes, minimum possible height or the minimum number of levels is Log2(N+1).There should be at least one element on each level, so the height cannot be more than N. A binary tree of height ‘h’ can have maximum 2h – 1 nodes (previous property). So the number of nodes will be less than or equal to this maximum value. N <= 2h - 1 2h >= N+1 log2(2h) >= log2(N+1) (Taking log both sides) hlog22 >= log2(N+1) (h is an integer) h >= | log2(N+1) | So the minimum height possible is | log2(N+1) | 4) A Binary Tree with L leaves has at least | Log2L |+ 1 levels. A Binary tree has the maximum number of leaves (and a minimum number of levels) when all levels are fully filled. Let all leaves be at level l, then below is true for the number of leaves L. L <= 2l-1 [From Point 1] l = | Log2L | + 1 where l is the minimum number of levels. 5) In Binary tree where every node has 0 or 2 children, the number of leaf nodes is always one more than nodes with two children. L = T + 1 Where L = Number of leaf nodes T = Number of internal nodes with two children Proof: No. of leaf nodes (L) i.e. total elements present at the bottom of tree = 2h-1 (h is height of tree) No. of internal nodes = {total no. of nodes} - {leaf nodes} = { 2h - 1 } - {2h-1} = 2h-1 (2-1) - 1 = 2h-1 - 1 So , L = 2h-1 T = 2h-1 - 1 Therefore L = T + 1 Hence proved 6) In a non empty binary tree, if n is the total number of nodes and e is the total number of edges, then e = n-1 Every node in a binary tree has exactly one parent with the exception of root node. So if n is the totalnumber of nodes then n-1 nodes have exactly one parent. There is only one edge between any child and itsparent. So the total number of edges is n-1. See Handshaking Lemma and Tree for proof.In the next article on tree series, we will be discussing different types of Binary Trees and their properties. ArjunAshok keon saipavanbhanu code4anshu vaibhavjadhav mo99 scisaif shreyasgosavi2016 namanyadav982 madhavchitlangia divyanshmishra101010 alisha88ouf thenitu dassnehashish7 abhijeet19403 hardikkoriintern Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jun, 2022" }, { "code": null, "e": 170, "s": 52, "text": "We have discussed Introduction to Binary Tree in set 1. In this post, the properties of a binary tree are discussed. " }, { "code": null, "e": 599, "s": 170, "text": "1) The maximum number of nodes at level ‘l’ of a binary tree is 2l. Here level is the number of nodes on the path from the root to the node (including root and node). Level of the root is 0. This can be proved by induction. For root, l = 0, number of nodes = 20 = 1 Assume that the maximum number of nodes on level ‘l’ is 2l Since in Binary tree every node has at most 2 children, next level would have twice nodes, i.e. 2 * 2l " }, { "code": null, "e": 1193, "s": 599, "text": "2) The Maximum number of nodes in a binary tree of height ‘h’ is 2h – 1. Here the height of a tree is the maximum number of nodes on the root to leaf path. Height of a tree with a single node is considered as 1. This result can be derived from point 2 above. A tree has maximum nodes if all levels have maximum nodes. So maximum number of nodes in a binary tree of height h is 1 + 2 + 4 + .. + 2h-1. This is a simple geometric series with h terms and sum of this series is 2h– 1. In some books, the height of the root is considered as 0. In this convention, the above formula becomes 2h+1 – 1 " }, { "code": null, "e": 1537, "s": 1193, "text": "3) In a Binary Tree with N nodes, minimum possible height or the minimum number of levels is Log2(N+1).There should be at least one element on each level, so the height cannot be more than N. A binary tree of height ‘h’ can have maximum 2h – 1 nodes (previous property). So the number of nodes will be less than or equal to this maximum value." }, { "code": null, "e": 1680, "s": 1537, "text": "N <= 2h - 1\n2h >= N+1\nlog2(2h) >= log2(N+1) (Taking log both sides)\nhlog22 >= log2(N+1) (h is an integer)\nh >= | log2(N+1) |" }, { "code": null, "e": 1728, "s": 1680, "text": "So the minimum height possible is | log2(N+1) |" }, { "code": null, "e": 1987, "s": 1728, "text": "4) A Binary Tree with L leaves has at least | Log2L |+ 1 levels. A Binary tree has the maximum number of leaves (and a minimum number of levels) when all levels are fully filled. Let all leaves be at level l, then below is true for the number of leaves L. " }, { "code": null, "e": 2078, "s": 1987, "text": "L <= 2l-1 [From Point 1]\nl = | Log2L | + 1 \nwhere l is the minimum number of levels." }, { "code": null, "e": 2208, "s": 2078, "text": "5) In Binary tree where every node has 0 or 2 children, the number of leaf nodes is always one more than nodes with two children." }, { "code": null, "e": 2581, "s": 2208, "text": "L = T + 1\nWhere L = Number of leaf nodes\nT = Number of internal nodes with two children\nProof:\nNo. of leaf nodes (L) i.e. total elements present at the bottom of tree = \n2h-1 (h is height of tree)\nNo. of internal nodes = {total no. of nodes} - {leaf nodes} = \n{ 2h - 1 } - {2h-1} = 2h-1 (2-1) - 1 = 2h-1 - 1\nSo , L = 2h-1\n T = 2h-1 - 1\nTherefore L = T + 1\nHence proved" }, { "code": null, "e": 2696, "s": 2581, "text": "6) In a non empty binary tree, if n is the total number of nodes and e is the total number of edges, then e = n-1 " }, { "code": null, "e": 2950, "s": 2696, "text": "Every node in a binary tree has exactly one parent with the exception of root node. So if n is the totalnumber of nodes then n-1 nodes have exactly one parent. There is only one edge between any child and itsparent. So the total number of edges is n-1. " }, { "code": null, "e": 3104, "s": 2950, "text": "See Handshaking Lemma and Tree for proof.In the next article on tree series, we will be discussing different types of Binary Trees and their properties. " }, { "code": null, "e": 3115, "s": 3104, "text": "ArjunAshok" }, { "code": null, "e": 3120, "s": 3115, "text": "keon" }, { "code": null, "e": 3134, "s": 3120, "text": "saipavanbhanu" }, { "code": null, "e": 3145, "s": 3134, "text": "code4anshu" }, { "code": null, "e": 3159, "s": 3145, "text": "vaibhavjadhav" }, { "code": null, "e": 3164, "s": 3159, "text": "mo99" }, { "code": null, "e": 3172, "s": 3164, "text": "scisaif" }, { "code": null, "e": 3190, "s": 3172, "text": "shreyasgosavi2016" }, { "code": null, "e": 3204, "s": 3190, "text": "namanyadav982" }, { "code": null, "e": 3221, "s": 3204, "text": "madhavchitlangia" }, { "code": null, "e": 3242, "s": 3221, "text": "divyanshmishra101010" }, { "code": null, "e": 3254, "s": 3242, "text": "alisha88ouf" }, { "code": null, "e": 3262, "s": 3254, "text": "thenitu" }, { "code": null, "e": 3277, "s": 3262, "text": "dassnehashish7" }, { "code": null, "e": 3291, "s": 3277, "text": "abhijeet19403" }, { "code": null, "e": 3308, "s": 3291, "text": "hardikkoriintern" }, { "code": null, "e": 3313, "s": 3308, "text": "Tree" }, { "code": null, "e": 3318, "s": 3313, "text": "Tree" } ]
Python PIL | ImageGrab.grabclipboard() method
29 Jul, 2019 PIL.ImageGrab.grabclipboard() method takes a snapshot of the clipboard image, if any. Syntax: PIL.ImageGrab.grabclipboard() Parameters: no arguments Returns: On Windows, an image, a list of filenames, or None if the clipboard does not contain image data or filenames. Note: This Module only work for Windows and Mac OS. # Importing Image and ImageGrab module from PIL package from PIL import Image, ImageGrab # using the grabclipboard methodim = ImageGrab.grabclipboard() im.show() Output: After changing the image on the clipboard # Importing Image and ImageGrab module from PIL package from PIL import Image, ImageGrab # using the grabclipboard methodim = ImageGrab.grabclipboard() im.show() Output: nidhi_biet Image-Processing python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2019" }, { "code": null, "e": 114, "s": 28, "text": "PIL.ImageGrab.grabclipboard() method takes a snapshot of the clipboard image, if any." }, { "code": null, "e": 152, "s": 114, "text": "Syntax: PIL.ImageGrab.grabclipboard()" }, { "code": null, "e": 177, "s": 152, "text": "Parameters: no arguments" }, { "code": null, "e": 296, "s": 177, "text": "Returns: On Windows, an image, a list of filenames, or None if the clipboard does not contain image data or filenames." }, { "code": null, "e": 348, "s": 296, "text": "Note: This Module only work for Windows and Mac OS." }, { "code": "# Importing Image and ImageGrab module from PIL package from PIL import Image, ImageGrab # using the grabclipboard methodim = ImageGrab.grabclipboard() im.show()", "e": 521, "s": 348, "text": null }, { "code": null, "e": 529, "s": 521, "text": "Output:" }, { "code": null, "e": 571, "s": 529, "text": "After changing the image on the clipboard" }, { "code": "# Importing Image and ImageGrab module from PIL package from PIL import Image, ImageGrab # using the grabclipboard methodim = ImageGrab.grabclipboard() im.show()", "e": 744, "s": 571, "text": null }, { "code": null, "e": 752, "s": 744, "text": "Output:" }, { "code": null, "e": 763, "s": 752, "text": "nidhi_biet" }, { "code": null, "e": 780, "s": 763, "text": "Image-Processing" }, { "code": null, "e": 795, "s": 780, "text": "python-utility" }, { "code": null, "e": 802, "s": 795, "text": "Python" }, { "code": null, "e": 900, "s": 802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 932, "s": 900, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 959, "s": 932, "text": "Python Classes and Objects" }, { "code": null, "e": 980, "s": 959, "text": "Python OOPs Concepts" }, { "code": null, "e": 1003, "s": 980, "text": "Introduction To PYTHON" }, { "code": null, "e": 1034, "s": 1003, "text": "Python | os.path.join() method" }, { "code": null, "e": 1090, "s": 1034, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1132, "s": 1090, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1174, "s": 1132, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1213, "s": 1174, "text": "Python | Get unique values from a list" } ]
Redux - Quick Guide
Redux is a predictable state container for JavaScript apps. As the application grows, it becomes difficult to keep it organized and maintain data flow. Redux solves this problem by managing application’s state with a single global object called Store. Redux fundamental principles help in maintaining consistency throughout your application, which makes debugging and testing easier. More importantly, it gives you live code editing combined with a time-travelling debugger. It is flexible to go with any view layer such as React, Angular, Vue, etc. Predictability of Redux is determined by three most important principles as given below − The state of your whole application is stored in an object tree within a single store. As whole application state is stored in a single tree, it makes debugging easy, and development faster. The only way to change the state is to emit an action, an object describing what happened. This means nobody can directly change the state of your application. To specify how the state tree is transformed by actions, you write pure reducers. A reducer is a central place where state modification takes place. Reducer is a function which takes state and action as arguments, and returns a newly updated state. Before installing Redux, we have to install Nodejs and NPM. Below are the instructions that will help you install it. You can skip these steps if you already have Nodejs and NPM installed in your device. Visit https://nodejs.org/ and install the package file. Visit https://nodejs.org/ and install the package file. Run the installer, follow the instructions and accept the license agreement. Run the installer, follow the instructions and accept the license agreement. Restart your device to run it. Restart your device to run it. You can check successful installation by opening the command prompt and type node -v. This will show you the latest version of Node in your system. You can check successful installation by opening the command prompt and type node -v. This will show you the latest version of Node in your system. To check if npm is installed successfully, you can type npm –v which returns you the latest npm version. To check if npm is installed successfully, you can type npm –v which returns you the latest npm version. To install redux, you can follow the below steps − Run the following command in your command prompt to install Redux. npm install --save redux To use Redux with react application, you need to install an additional dependency as follows − npm install --save react-redux To install developer tools for Redux, you need to install the following as dependency − Run the below command in your command prompt to install Redux dev-tools. npm install --save-dev redux-devtools If you do not want to install Redux dev tools and integrate it into your project, you can install Redux DevTools Extension for Chrome and Firefox. Let us assume our application’s state is described by a plain object called initialState which is as follows − const initialState = { isLoading: false, items: [], hasError: false }; Every piece of code in your application cannot change this state. To change the state, you need to dispatch an action. An action is a plain object that describes the intention to cause change with a type property. It must have a type property which tells what type of action is being performed. The command for action is as follows − return { type: 'ITEMS_REQUEST', //action type isLoading: true //payload information } Actions and states are held together by a function called Reducer. An action is dispatched with an intention to cause change. This change is performed by the reducer. Reducer is the only way to change states in Redux, making it more predictable, centralised and debuggable. A reducer function that handles the ‘ITEMS_REQUEST’ action is as follows − const reducer = (state = initialState, action) => { //es6 arrow function switch (action.type) { case 'ITEMS_REQUEST': return Object.assign({}, state, { isLoading: action.isLoading }) default: return state; } } Redux has a single store which holds the application state. If you want to split your code on the basis of data handling logic, you should start splitting your reducers instead of stores in Redux. We will discuss how we can split reducers and combine it with store later in this tutorial. Redux components are as follows − Redux follows the unidirectional data flow. It means that your application data will follow in one-way binding data flow. As the application grows & becomes complex, it is hard to reproduce issues and add new features if you have no control over the state of your application. Redux reduces the complexity of the code, by enforcing the restriction on how and when state update can happen. This way, managing updated states is easy. We already know about the restrictions as the three principles of Redux. Following diagram will help you understand Redux data flow better − An action is dispatched when a user interacts with the application. An action is dispatched when a user interacts with the application. The root reducer function is called with the current state and the dispatched action. The root reducer may divide the task among smaller reducer functions, which ultimately returns a new state. The root reducer function is called with the current state and the dispatched action. The root reducer may divide the task among smaller reducer functions, which ultimately returns a new state. The store notifies the view by executing their callback functions. The store notifies the view by executing their callback functions. The view can retrieve updated state and re-render again. The view can retrieve updated state and re-render again. A store is an immutable object tree in Redux. A store is a state container which holds the application’s state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer. Let us see how we can create a store using the createStore method from Redux. One need to import the createStore package from the Redux library that supports the store creation process as shown below − import { createStore } from 'redux'; import reducer from './reducers/reducer' const store = createStore(reducer); A createStore function can have three arguments. The following is the syntax − createStore(reducer, [preloadedState], [enhancer]) A reducer is a function that returns the next state of app. A preloadedState is an optional argument and is the initial state of your app. An enhancer is also an optional argument. It will help you enhance store with third-party capabilities. A store has three important methods as given below − It helps you retrieve the current state of your Redux store. The syntax for getState is as follows − store.getState() It allows you to dispatch an action to change a state in your application. The syntax for dispatch is as follows − store.dispatch({type:'ITEMS_REQUEST'}) It helps you register a callback that Redux store will call when an action has been dispatched. As soon as the Redux state has been updated, the view will re-render automatically. The syntax for dispatch is as follows − store.subscribe(()=>{ console.log(store.getState());}) Note that subscribe function returns a function for unsubscribing the listener. To unsubscribe the listener, we can use the below code − const unsubscribe = store.subscribe(()=>{console.log(store.getState());}); unsubscribe(); Actions are the only source of information for the store as per Redux official documentation. It carries a payload of information from your application to store. As discussed earlier, actions are plain JavaScript object that must have a type attribute to indicate the type of action performed. It tells us what had happened. Types should be defined as string constants in your application as given below − const ITEMS_REQUEST = 'ITEMS_REQUEST'; Apart from this type attribute, the structure of an action object is totally up to the developer. It is recommended to keep your action object as light as possible and pass only the necessary information. To cause any change in the store, you need to dispatch an action first by using store.dispatch() function. The action object is as follows − { type: GET_ORDER_STATUS , payload: {orderId,userId } } { type: GET_WISHLIST_ITEMS, payload: userId } Action creators are the functions that encapsulate the process of creation of an action object. These functions simply return a plain Js object which is an action. It promotes writing clean code and helps to achieve reusability. Let us learn about action creator which lets you dispatch an action, ‘ITEMS_REQUEST’ that requests for the product items list data from the server. Meanwhile, the isLoading state is made true in the reducer in ‘ITEMS_REQUEST’ action type to indicate that items are loading, and data is still not received from the server. Initially, the isLoading state was false in the initialState object assuming nothing is loading. When data is received at browser, isLoading state will be returned as false in ‘ITEMS_REQUEST_SUCCESS’ action type in the corresponding reducer. This state can be used as a prop in react components to display loader/message on your page while the request for data is on. The action creator is as follows − const ITEMS_REQUEST = ‘ITEMS_REQUEST’ ; const ITEMS_REQUEST_SUCCESS = ‘ITEMS_REQUEST_SUCCESS’ ; export function itemsRequest(bool,startIndex,endIndex) { let payload = { isLoading: bool, startIndex, endIndex } return { type: ITEMS_REQUEST, payload } } export function itemsRequestSuccess(bool) { return { type: ITEMS_REQUEST_SUCCESS, isLoading: bool, } } To invoke a dispatch function, you need to pass action as an argument to dispatch function. dispatch(itemsRequest(true,1, 20)); dispatch(itemsRequestSuccess(false)); You can dispatch an action by directly using store.dispatch(). However, it is more likely that you access it with react-Redux helper method called connect(). You can also use bindActionCreators() method to bind many action creators with dispatch function. A function is a process which takes inputs called arguments, and produces some output known as return value. A function is called pure if it abides by the following rules − A function returns the same result for same arguments. A function returns the same result for same arguments. Its evaluation has no side effects, i.e., it does not alter input data. Its evaluation has no side effects, i.e., it does not alter input data. No mutation of local & global variables. No mutation of local & global variables. It does not depend on the external state like a global variable. It does not depend on the external state like a global variable. Let us take the example of a function which returns two times of the value passed as an input to the function. In general, it is written as, f(x) => x*2. If a function is called with an argument value 2, then the output would be 4, f(2) => 4. Let us write the definition of the function in JavaScript as shown below − const double = x => x*2; // es6 arrow function console.log(double(2)); // 4 Here, double is a pure function. As per the three principles in Redux, changes must be made by a pure function, i.e., reducer in Redux. Now, a question arises as to why a reducer must be a pure function. Suppose, you want to dispatch an action whose type is 'ADD_TO_CART_SUCCESS' to add an item to your shopping cart application by clicking add to cart button. Let us assume the reducer is adding an item to your cart as given below − const initialState = { isAddedToCart: false; } const addToCartReducer = (state = initialState, action) => { //es6 arrow function switch (action.type) { case 'ADD_TO_CART_SUCCESS' : state.isAddedToCart = !state.isAddedToCart; //original object altered return state; default: return state; } } export default addToCartReducer ; Let us suppose, isAddedToCart is a property on state object that allows you to decide when to disable ‘add to cart’ button for the item by returning a Boolean value ‘true or false’. This prevents user to add same product multiple times. Now, instead of returning a new object, we are mutating isAddedToCart prop on the state like above. Now if we try to add an item to cart, nothing happens. Add to cart button will not get disabled. The reason for this behaviour is as follows − Redux compares old and new objects by the memory location of both the objects. It expects a new object from reducer if any change has happened. And it also expects to get the old object back if no change occurs. In this case, it is the same. Due to this reason, Redux assumes that nothing has happened. So, it is necessary for a reducer to be a pure function in Redux. The following is a way to write it without mutation − const initialState = { isAddedToCart: false; } const addToCartReducer = (state = initialState, action) => { //es6 arrow function switch (action.type) { case 'ADD_TO_CART_SUCCESS' : return { ...state, isAddedToCart: !state.isAddedToCart } default: return state; } } export default addToCartReducer; Reducers are a pure function in Redux. Pure functions are predictable. Reducers are the only way to change states in Redux. It is the only place where you can write logic and calculations. Reducer function will accept the previous state of app and action being dispatched, calculate the next state and returns the new object. The following few things should never be performed inside the reducer − Mutation of functions arguments API calls & routing logic Calling non-pure function e.g. Math.random() The following is the syntax of a reducer − (state,action) => newState Let us continue the example of showing the list of product items on a web page, discussed in the action creators module. Let us see below how to write its reducer. const initialState = { isLoading: false, items: [] }; const reducer = (state = initialState, action) => { switch (action.type) { case 'ITEMS_REQUEST': return Object.assign({}, state, { isLoading: action.payload.isLoading }) case ‘ITEMS_REQUEST_SUCCESS': return Object.assign({}, state, { items: state.items.concat(action.items), isLoading: action.isLoading }) default: return state; } } export default reducer; Firstly, if you do not set state to ‘initialState’, Redux calls reducer with the undefined state. In this code example, concat() function of JavaScript is used in ‘ITEMS_REQUEST_SUCCESS', which does not change the existing array; instead returns a new array. In this way, you can avoid mutation of the state. Never write directly to the state. In 'ITEMS_REQUEST', we have to set the state value from the action received. It is already discussed that we can write our logic in reducer and can split it on the logical data basis. Let us see how we can split reducers and combine them together as root reducer when dealing with a large application. Suppose, we want to design a web page where a user can access product order status and see wishlist information. We can separate the logic in different reducers files, and make them work independently. Let us assume that GET_ORDER_STATUS action is dispatched to get the status of order corresponding to some order id and user id. /reducer/orderStatusReducer.js import { GET_ORDER_STATUS } from ‘../constants/appConstant’; export default function (state = {} , action) { switch(action.type) { case GET_ORDER_STATUS: return { ...state, orderStatusData: action.payload.orderStatus }; default: return state; } } Similarly, assume GET_WISHLIST_ITEMS action is dispatched to get the user’s wishlist information respective of a user. /reducer/getWishlistDataReducer.js import { GET_WISHLIST_ITEMS } from ‘../constants/appConstant’; export default function (state = {}, action) { switch(action.type) { case GET_WISHLIST_ITEMS: return { ...state, wishlistData: action.payload.wishlistData }; default: return state; } } Now, we can combine both reducers by using Redux combineReducers utility. The combineReducers generate a function which returns an object whose values are different reducer functions. You can import all the reducers in index reducer file and combine them together as an object with their respective names. /reducer/index.js import { combineReducers } from ‘redux’; import OrderStatusReducer from ‘./orderStatusReducer’; import GetWishlistDataReducer from ‘./getWishlistDataReducer’; const rootReducer = combineReducers ({ orderStatusReducer: OrderStatusReducer, getWishlistDataReducer: GetWishlistDataReducer }); export default rootReducer; Now, you can pass this rootReducer to the createStore method as follows − const store = createStore(rootReducer); Redux itself is synchronous, so how the async operations like network request work with Redux? Here middlewares come handy. As discussed earlier, reducers are the place where all the execution logic is written. Reducer has nothing to do with who performs it, how much time it is taking or logging the state of the app before and after the action is dispatched. In this case, Redux middleware function provides a medium to interact with dispatched action before they reach the reducer. Customized middleware functions can be created by writing high order functions (a function that returns another function), which wraps around some logic. Multiple middlewares can be combined together to add new functionality, and each middleware requires no knowledge of what came before and after. You can imagine middlewares somewhere between action dispatched and reducer. Commonly, middlewares are used to deal with asynchronous actions in your app. Redux provides with API called applyMiddleware which allows us to use custom middleware as well as Redux middlewares like redux-thunk and redux-promise. It applies middlewares to store. The syntax of using applyMiddleware API is − applyMiddleware(...middleware) And this can be applied to store as follows − import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers/index'; const store = createStore(rootReducer, applyMiddleware(thunk)); Middlewares will let you write an action dispatcher which returns a function instead of an action object. Example for the same is shown below − function getUser() { return function() { return axios.get('/get_user_details'); }; } Conditional dispatch can be written inside middleware. Each middleware receives store’s dispatch so that they can dispatch new action, and getState functions as arguments so that they can access the current state and return a function. Any return value from an inner function will be available as the value of dispatch function itself. The following is the syntax of a middleware − ({ getState, dispatch }) => next => action The getState function is useful to decide whether new data is to be fetched or cache result should get returned, depending upon the current state. Let us see an example of a custom middleware logger function. It simply logs the action and new state. import { createStore, applyMiddleware } from 'redux' import userLogin from './reducers' function logger({ getState }) { return next => action => { console.log(‘action’, action); const returnVal = next(action); console.log('state when action is dispatched', getState()); return returnVal; } } Now apply the logger middleware to the store by writing the following line of code − const store = createStore(userLogin , initialState=[ ] , applyMiddleware(logger)); Dispatch an action to check the action dispatched and new state using the below code − store.dispatch({ type: 'ITEMS_REQUEST', isLoading: true }) Another example of middleware where you can handle when to show or hide the loader is given below. This middleware shows the loader when you are requesting any resource and hides it when resource request has been completed. import isPromise from 'is-promise'; function loaderHandler({ dispatch }) { return next => action => { if (isPromise(action)) { dispatch({ type: 'SHOW_LOADER' }); action .then(() => dispatch({ type: 'HIDE_LOADER' })) .catch(() => dispatch({ type: 'HIDE_LOADER' })); } return next(action); }; } const store = createStore( userLogin , initialState = [ ] , applyMiddleware(loaderHandler) ); Redux-Devtools provide us debugging platform for Redux apps. It allows us to perform time-travel debugging and live editing. Some of the features in official documentation are as follows − It lets you inspect every state and action payload. It lets you inspect every state and action payload. It lets you go back in time by “cancelling” actions. It lets you go back in time by “cancelling” actions. If you change the reducer code, each “staged” action will be re-evaluated. If you change the reducer code, each “staged” action will be re-evaluated. If the reducers throw, we can identify the error and also during which action this happened. If the reducers throw, we can identify the error and also during which action this happened. With persistState() store enhancer, you can persist debug sessions across page reloads. With persistState() store enhancer, you can persist debug sessions across page reloads. There are two variants of Redux dev-tools as given below − Redux DevTools − It can be installed as a package and integrated into your application as given below − https://github.com/reduxjs/redux-devtools/blob/master/docs/Walkthrough.md#manual-integration Redux DevTools Extension − A browser extension that implements the same developer tools for Redux is as follows − https://github.com/zalmoxisus/redux-devtools-extension Now let us check how we can skip actions and go back in time with the help of Redux dev tool. Following screenshots explain about the actions we have dispatched earlier to get the listing of items. Here we can see the actions dispatched in the inspector tab. On the right, you can see the Demo tab which shows you the difference in the state tree. You will get familiar with this tool when you start using it. You can dispatch an action without writing the actual code just from this Redux plugin tool. A Dispatcher option in the last row will help you with this. Let us check the last action where items are fetched successfully. We received an array of objects as a response from the server. All the data is available to display listing on our page. You can also track the store’s state at the same time by clicking on the state tab on the upper right side. In the previous sections, we have learnt about time travel debugging. Let us now check how to skip one action and go back in time to analyze the state of our app. As you click on any action type, two options: ‘Jump’ and ‘Skip’ will appear. By clicking on the skip button on a certain action type, you can skip particular action. It acts as if the action never happened. When you click on jump button on certain action type, it will take you to the state when that action occurred and skip all the remaining actions in sequence. This way you will be able to retain the state when a particular action happened. This feature is useful in debugging and finding errors in the application. We skipped the last action, and all the listing data from background got vanished. It takes back to the time when data of the items has not arrived, and our app has no data to render on the page. It actually makes coding easy and debugging easier. Testing Redux code is easy as we mostly write functions, and most of them are pure. So we can test it without even mocking them. Here, we are using JEST as a testing engine. It works in the node environment and does not access DOM. We can install JEST with the code given below − npm install --save-dev jest With babel, you need to install babel-jest as follows − npm install --save-dev babel-jest And configure it to use babel-preset-env features in the .babelrc file as follows − { "presets": ["@babel/preset-env"] } And add the following script in your package.json: { //Some other code "scripts": { //code "test": "jest", "test:watch": "npm test -- --watch" }, //code } Finally, run npm test or npm run test. Let us check how we can write test cases for action creators and reducers. Let us assume you have action creator as shown below − export function itemsRequestSuccess(bool) { return { type: ITEMS_REQUEST_SUCCESS, isLoading: bool, } } This action creator can be tested as given below − import * as action from '../actions/actions'; import * as types from '../../constants/ActionTypes'; describe('actions', () => { it('should create an action to check if item is loading', () => { const isLoading = true, const expectedAction = { type: types.ITEMS_REQUEST_SUCCESS, isLoading } expect(actions.itemsRequestSuccess(isLoading)).toEqual(expectedAction) }) }) We have learnt that reducer should return a new state when action is applied. So reducer is tested on this behaviour. Consider a reducer as given below − const initialState = { isLoading: false }; const reducer = (state = initialState, action) => { switch (action.type) { case 'ITEMS_REQUEST': return Object.assign({}, state, { isLoading: action.payload.isLoading }) default: return state; } } export default reducer; To test above reducer, we need to pass state and action to the reducer, and return a new state as shown below − import reducer from '../../reducer/reducer' import * as types from '../../constants/ActionTypes' describe('reducer initial state', () => { it('should return the initial state', () => { expect(reducer(undefined, {})).toEqual([ { isLoading: false, } ]) }) it('should handle ITEMS_REQUEST', () => { expect( reducer( { isLoading: false, }, { type: types.ITEMS_REQUEST, payload: { isLoading: true } } ) ).toEqual({ isLoading: true }) }) }) If you are not familiar with writing test case, you can check the basics of JEST. In the previous chapters, we have learnt what is Redux and how it works. Let us now check the integration of view part with Redux. You can add any view layer to Redux. We will also discuss react library and Redux. Let us say if various react components need to display the same data in different ways without passing it as a prop to all the components from top-level component to the way down. It would be ideal to store it outside the react components. Because it helps in faster data retrieval as you need not pass data all the way down to different components. Let us discuss how it is possible with Redux. Redux provides the react-redux package to bind react components with two utilities as given below − Provider Connect Provider makes the store available to rest of the application. Connect function helps react component to connect to the store, responding to each change occurring in the store’s state. Let us have a look at the root index.js file which creates store and uses a provider that enables the store to the rest of the app in a react-redux app. import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore, applyMiddleware } from 'redux'; import reducer from './reducers/reducer' import thunk from 'redux-thunk'; import App from './components/app' import './index.css'; const store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), applyMiddleware(thunk) ) render( <Provider store = {store}> <App /> </Provider>, document.getElementById('root') ) Whenever a change occurs in a react-redux app, mapStateToProps() is called. In this function, we exactly specify which state we need to provide to our react component. With the help of connect() function explained below, we are connecting these app’s state to react component. Connect() is a high order function which takes component as a parameter. It performs certain operations and returns a new component with correct data which we finally exported. With the help of mapStateToProps(), we provide these store states as prop to our react component. This code can be wrapped in a container component. The motive is to separate concerns like data fetching, rendering concern and reusability. import { connect } from 'react-redux' import Listing from '../components/listing/Listing' //react component import makeApiCall from '../services/services' //component to make api call const mapStateToProps = (state) => { return { items: state.items, isLoading: state.isLoading }; }; const mapDispatchToProps = (dispatch) => { return { fetchData: () => dispatch(makeApiCall()) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Listing); The definition of a component to make an api call in services.js file is as follows − import axios from 'axios' import { itemsLoading, itemsFetchDataSuccess } from '../actions/actions' export default function makeApiCall() { return (dispatch) => { dispatch(itemsLoading(true)); axios.get('http://api.tvmaze.com/shows') .then((response) => { if (response.status !== 200) { throw Error(response.statusText); } dispatch(itemsLoading(false)); return response; }) .then((response) => dispatch(itemsFetchDataSuccess(response.data))) }; } mapDispatchToProps() function receives dispatch function as a parameter and returns you callback props as plain object that you pass to your react component. Here, you can access fetchData as a prop in your react listing component, which dispatches an action to make an API call. mapDispatchToProps() is used to dispatch an action to store. In react-redux, components cannot access the store directly. The only way is to use connect(). Let us understand how the react-redux works through the below diagram − STORE − Stores all your application state as a JavaScript object PROVIDER − Makes stores available CONTAINER − Get apps state & provide it as a prop to components COMPONENT − User interacts through view component ACTIONS − Causes a change in store, it may or may not change the state of your app REDUCER − Only way to change app state, accept state and action, and returns updated state. However, Redux is an independent library and can be used with any UI layer. React-redux is the official Redux, UI binding with the react. Moreover, it encourages a good react Redux app structure. React-redux internally implements performance optimization, so that component re-render occurs only when it is needed. To sum up, Redux is not designed to write shortest and the fastest code. It is intended to provide a predictable state management container. It helps us understand when a certain state changed, or where the data came from. Here is a small example of react and Redux application. You can also try developing small apps. Sample code for increase or decrease counter is given below − This is the root file which is responsible for the creation of store and rendering our react app component. /src/index.js import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore } from 'redux'; import reducer from '../src/reducer/index' import App from '../src/App' import './index.css'; const store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ) render( <Provider store = {store}> <App /> </Provider>, document.getElementById('root') ) This is our root component of react. It is responsible for rendering counter container component as a child. /src/app.js import React, { Component } from 'react'; import './App.css'; import Counter from '../src/container/appContainer'; class App extends Component { render() { return ( <div className = "App"> <header className = "App-header"> <Counter/> </header> </div> ); } } export default App; The following is the container component which is responsible for providing Redux’s state to react component − /container/counterContainer.js import { connect } from 'react-redux' import Counter from '../component/counter' import { increment, decrement, reset } from '../actions'; const mapStateToProps = (state) => { return { counter: state }; }; const mapDispatchToProps = (dispatch) => { return { increment: () => dispatch(increment()), decrement: () => dispatch(decrement()), reset: () => dispatch(reset()) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Counter); Given below is the react component responsible for view part − /component/counter.js import React, { Component } from 'react'; class Counter extends Component { render() { const {counter,increment,decrement,reset} = this.props; return ( <div className = "App"> <div>{counter}</div> <div> <button onClick = {increment}>INCREMENT BY 1</button> </div> <div> <button onClick = {decrement}>DECREMENT BY 1</button> </div> <button onClick = {reset}>RESET</button> </div> ); } } export default Counter; The following are the action creators responsible for creating an action − /actions/index.js export function increment() { return { type: 'INCREMENT' } } export function decrement() { return { type: 'DECREMENT' } } export function reset() { return { type: 'RESET' } } Below, we have shown line of code for reducer file which is responsible for updating the state in Redux. reducer/index.js const reducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 case 'RESET' : return 0 default: return state } } export default reducer; Initially, the app looks as follows − When I click increment two times, the output screen will be as shown below − When we decrement it once, it shows the following screen − And reset will take the app back to initial state which is counter value 0. This is shown below − Let us understand what happens with Redux dev tools when the first increment action takes place − State of the app will be moved to the time when only increment action is dispatched and rest of the actions are skipped. We encourage to develop a small Todo App as an assignment by yourself and understand the Redux tool better.
[ { "code": null, "e": 2333, "s": 1949, "text": "Redux is a predictable state container for JavaScript apps. As the application grows, it becomes difficult to keep it organized and maintain data flow. Redux solves this problem by managing application’s state with a single global object called Store. Redux fundamental principles help in maintaining consistency throughout your application, which makes debugging and testing easier." }, { "code": null, "e": 2499, "s": 2333, "text": "More importantly, it gives you live code editing combined with a time-travelling debugger. It is flexible to go with any view layer such as React, Angular, Vue, etc." }, { "code": null, "e": 2589, "s": 2499, "text": "Predictability of Redux is determined by three most important principles as given below −" }, { "code": null, "e": 2780, "s": 2589, "text": "The state of your whole application is stored in an object tree within a single store. As whole application state is stored in a single tree, it makes debugging easy, and development faster." }, { "code": null, "e": 2940, "s": 2780, "text": "The only way to change the state is to emit an action, an object describing what happened. This means nobody can directly change the state of your application." }, { "code": null, "e": 3189, "s": 2940, "text": "To specify how the state tree is transformed by actions, you write pure reducers. A reducer is a central place where state modification takes place. Reducer is a function which takes state and action as arguments, and returns a newly updated state." }, { "code": null, "e": 3393, "s": 3189, "text": "Before installing Redux, we have to install Nodejs and NPM. Below are the instructions that will help you install it. You can skip these steps if you already have Nodejs and NPM installed in your device." }, { "code": null, "e": 3449, "s": 3393, "text": "Visit https://nodejs.org/ and install the package file." }, { "code": null, "e": 3505, "s": 3449, "text": "Visit https://nodejs.org/ and install the package file." }, { "code": null, "e": 3582, "s": 3505, "text": "Run the installer, follow the instructions and accept the license agreement." }, { "code": null, "e": 3659, "s": 3582, "text": "Run the installer, follow the instructions and accept the license agreement." }, { "code": null, "e": 3690, "s": 3659, "text": "Restart your device to run it." }, { "code": null, "e": 3721, "s": 3690, "text": "Restart your device to run it." }, { "code": null, "e": 3869, "s": 3721, "text": "You can check successful installation by opening the command prompt and type node -v. This will show you the latest version of Node in your system." }, { "code": null, "e": 4017, "s": 3869, "text": "You can check successful installation by opening the command prompt and type node -v. This will show you the latest version of Node in your system." }, { "code": null, "e": 4122, "s": 4017, "text": "To check if npm is installed successfully, you can type npm –v which returns you the latest npm version." }, { "code": null, "e": 4227, "s": 4122, "text": "To check if npm is installed successfully, you can type npm –v which returns you the latest npm version." }, { "code": null, "e": 4278, "s": 4227, "text": "To install redux, you can follow the below steps −" }, { "code": null, "e": 4345, "s": 4278, "text": "Run the following command in your command prompt to install Redux." }, { "code": null, "e": 4371, "s": 4345, "text": "npm install --save redux\n" }, { "code": null, "e": 4466, "s": 4371, "text": "To use Redux with react application, you need to install an additional dependency as follows −" }, { "code": null, "e": 4498, "s": 4466, "text": "npm install --save react-redux\n" }, { "code": null, "e": 4586, "s": 4498, "text": "To install developer tools for Redux, you need to install the following as dependency −" }, { "code": null, "e": 4659, "s": 4586, "text": "Run the below command in your command prompt to install Redux dev-tools." }, { "code": null, "e": 4698, "s": 4659, "text": "npm install --save-dev redux-devtools\n" }, { "code": null, "e": 4845, "s": 4698, "text": "If you do not want to install Redux dev tools and integrate it into your project, you can install Redux DevTools Extension for Chrome and Firefox." }, { "code": null, "e": 4956, "s": 4845, "text": "Let us assume our application’s state is described by a plain object called initialState which is as follows −" }, { "code": null, "e": 5037, "s": 4956, "text": "const initialState = {\n isLoading: false,\n items: [],\n hasError: false\n};\n" }, { "code": null, "e": 5156, "s": 5037, "text": "Every piece of code in your application cannot change this state. To change the state, you need to dispatch an action." }, { "code": null, "e": 5371, "s": 5156, "text": "An action is a plain object that describes the intention to cause change with a type property. It must have a type property which tells what type of action is being performed. The command for action is as follows −" }, { "code": null, "e": 5464, "s": 5371, "text": "return {\n type: 'ITEMS_REQUEST', //action type\n isLoading: true //payload information\n}\n" }, { "code": null, "e": 5813, "s": 5464, "text": "Actions and states are held together by a function called Reducer. An action is dispatched with an intention to cause change. This change is performed by the reducer. Reducer is the only way to change states in Redux, making it more predictable, centralised and debuggable. A reducer function that handles the ‘ITEMS_REQUEST’ action is as follows −" }, { "code": null, "e": 6080, "s": 5813, "text": "const reducer = (state = initialState, action) => { //es6 arrow function\n switch (action.type) {\n case 'ITEMS_REQUEST':\n return Object.assign({}, state, {\n isLoading: action.isLoading\n })\n default:\n return state;\n }\n}" }, { "code": null, "e": 6277, "s": 6080, "text": "Redux has a single store which holds the application state. If you want to split your code on the basis of data handling logic, you should start splitting your reducers instead of stores in Redux." }, { "code": null, "e": 6369, "s": 6277, "text": "We will discuss how we can split reducers and combine it with store later in this tutorial." }, { "code": null, "e": 6403, "s": 6369, "text": "Redux components are as follows −" }, { "code": null, "e": 6680, "s": 6403, "text": "Redux follows the unidirectional data flow. It means that your application data will follow in one-way binding data flow. As the application grows & becomes complex, it is hard to reproduce issues and add new features if you have no control over the state of your application." }, { "code": null, "e": 6976, "s": 6680, "text": "Redux reduces the complexity of the code, by enforcing the restriction on how and when state update can happen. This way, managing updated states is easy. We already know about the restrictions as the three principles of Redux. Following diagram will help you understand Redux data flow better −" }, { "code": null, "e": 7044, "s": 6976, "text": "An action is dispatched when a user interacts with the application." }, { "code": null, "e": 7112, "s": 7044, "text": "An action is dispatched when a user interacts with the application." }, { "code": null, "e": 7306, "s": 7112, "text": "The root reducer function is called with the current state and the dispatched action. The root reducer may divide the task among smaller reducer functions, which ultimately returns a new state." }, { "code": null, "e": 7500, "s": 7306, "text": "The root reducer function is called with the current state and the dispatched action. The root reducer may divide the task among smaller reducer functions, which ultimately returns a new state." }, { "code": null, "e": 7567, "s": 7500, "text": "The store notifies the view by executing their callback functions." }, { "code": null, "e": 7634, "s": 7567, "text": "The store notifies the view by executing their callback functions." }, { "code": null, "e": 7691, "s": 7634, "text": "The view can retrieve updated state and re-render again." }, { "code": null, "e": 7748, "s": 7691, "text": "The view can retrieve updated state and re-render again." }, { "code": null, "e": 7987, "s": 7748, "text": "A store is an immutable object tree in Redux. A store is a state container which holds the application’s state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer." }, { "code": null, "e": 8189, "s": 7987, "text": "Let us see how we can create a store using the createStore method from Redux. One need to import the createStore package from the Redux library that supports the store creation process as shown below −" }, { "code": null, "e": 8304, "s": 8189, "text": "import { createStore } from 'redux';\nimport reducer from './reducers/reducer'\nconst store = createStore(reducer);\n" }, { "code": null, "e": 8383, "s": 8304, "text": "A createStore function can have three arguments. The following is the syntax −" }, { "code": null, "e": 8435, "s": 8383, "text": "createStore(reducer, [preloadedState], [enhancer])\n" }, { "code": null, "e": 8678, "s": 8435, "text": "A reducer is a function that returns the next state of app. A preloadedState is an optional argument and is the initial state of your app. An enhancer is also an optional argument. It will help you enhance store with third-party capabilities." }, { "code": null, "e": 8731, "s": 8678, "text": "A store has three important methods as given below −" }, { "code": null, "e": 8792, "s": 8731, "text": "It helps you retrieve the current state of your Redux store." }, { "code": null, "e": 8832, "s": 8792, "text": "The syntax for getState is as follows −" }, { "code": null, "e": 8850, "s": 8832, "text": "store.getState()\n" }, { "code": null, "e": 8925, "s": 8850, "text": "It allows you to dispatch an action to change a state in your application." }, { "code": null, "e": 8965, "s": 8925, "text": "The syntax for dispatch is as follows −" }, { "code": null, "e": 9005, "s": 8965, "text": "store.dispatch({type:'ITEMS_REQUEST'})\n" }, { "code": null, "e": 9185, "s": 9005, "text": "It helps you register a callback that Redux store will call when an action has been dispatched. As soon as the Redux state has been updated, the view will re-render automatically." }, { "code": null, "e": 9225, "s": 9185, "text": "The syntax for dispatch is as follows −" }, { "code": null, "e": 9281, "s": 9225, "text": "store.subscribe(()=>{ console.log(store.getState());})\n" }, { "code": null, "e": 9418, "s": 9281, "text": "Note that subscribe function returns a function for unsubscribing the listener. To unsubscribe the listener, we can use the below code −" }, { "code": null, "e": 9509, "s": 9418, "text": "const unsubscribe = store.subscribe(()=>{console.log(store.getState());});\nunsubscribe();\n" }, { "code": null, "e": 9671, "s": 9509, "text": "Actions are the only source of information for the store as per Redux official documentation. It carries a payload of information from your application to store." }, { "code": null, "e": 9915, "s": 9671, "text": "As discussed earlier, actions are plain JavaScript object that must have a type attribute to indicate the type of action performed. It tells us what had happened. Types should be defined as string constants in your application as given below −" }, { "code": null, "e": 9955, "s": 9915, "text": "const ITEMS_REQUEST = 'ITEMS_REQUEST';\n" }, { "code": null, "e": 10160, "s": 9955, "text": "Apart from this type attribute, the structure of an action object is totally up to the developer. It is recommended to keep your action object as light as possible and pass only the necessary information." }, { "code": null, "e": 10301, "s": 10160, "text": "To cause any change in the store, you need to dispatch an action first by using store.dispatch() function. The action object is as follows −" }, { "code": null, "e": 10404, "s": 10301, "text": "{ type: GET_ORDER_STATUS , payload: {orderId,userId } }\n{ type: GET_WISHLIST_ITEMS, payload: userId }\n" }, { "code": null, "e": 10633, "s": 10404, "text": "Action creators are the functions that encapsulate the process of creation of an action object. These functions simply return a plain Js object which is an action. It promotes writing clean code and helps to achieve reusability." }, { "code": null, "e": 10955, "s": 10633, "text": "Let us learn about action creator which lets you dispatch an action, ‘ITEMS_REQUEST’ that requests for the product items list data from the server. Meanwhile, the isLoading state is made true in the reducer in ‘ITEMS_REQUEST’ action type to indicate that items are loading, and data is still not received from the server." }, { "code": null, "e": 11358, "s": 10955, "text": "Initially, the isLoading state was false in the initialState object assuming nothing is loading. When data is received at browser, isLoading state will be returned as false in ‘ITEMS_REQUEST_SUCCESS’ action type in the corresponding reducer. This state can be used as a prop in react components to display loader/message on your page while the request for data is on. The action creator is as follows −" }, { "code": null, "e": 11772, "s": 11358, "text": "const ITEMS_REQUEST = ‘ITEMS_REQUEST’ ;\nconst ITEMS_REQUEST_SUCCESS = ‘ITEMS_REQUEST_SUCCESS’ ;\nexport function itemsRequest(bool,startIndex,endIndex) {\n let payload = {\n isLoading: bool,\n startIndex,\n endIndex\n }\n return {\n type: ITEMS_REQUEST,\n payload\n }\n}\nexport function itemsRequestSuccess(bool) {\n return {\n type: ITEMS_REQUEST_SUCCESS,\n isLoading: bool,\n }\n}" }, { "code": null, "e": 11864, "s": 11772, "text": "To invoke a dispatch function, you need to pass action as an argument to dispatch function." }, { "code": null, "e": 11939, "s": 11864, "text": "dispatch(itemsRequest(true,1, 20));\ndispatch(itemsRequestSuccess(false));\n" }, { "code": null, "e": 12195, "s": 11939, "text": "You can dispatch an action by directly using store.dispatch(). However, it is more likely that you access it with react-Redux helper method called connect(). You can also use bindActionCreators() method to bind many action creators with dispatch function." }, { "code": null, "e": 12368, "s": 12195, "text": "A function is a process which takes inputs called arguments, and produces some output known as return value. A function is called pure if it abides by the following rules −" }, { "code": null, "e": 12423, "s": 12368, "text": "A function returns the same result for same arguments." }, { "code": null, "e": 12478, "s": 12423, "text": "A function returns the same result for same arguments." }, { "code": null, "e": 12550, "s": 12478, "text": "Its evaluation has no side effects, i.e., it does not alter input data." }, { "code": null, "e": 12622, "s": 12550, "text": "Its evaluation has no side effects, i.e., it does not alter input data." }, { "code": null, "e": 12663, "s": 12622, "text": "No mutation of local & global variables." }, { "code": null, "e": 12704, "s": 12663, "text": "No mutation of local & global variables." }, { "code": null, "e": 12769, "s": 12704, "text": "It does not depend on the external state like a global variable." }, { "code": null, "e": 12834, "s": 12769, "text": "It does not depend on the external state like a global variable." }, { "code": null, "e": 13077, "s": 12834, "text": "Let us take the example of a function which returns two times of the value passed as an input to the function. In general, it is written as, f(x) => x*2. If a function is called with an argument value 2, then the output would be 4, f(2) => 4." }, { "code": null, "e": 13152, "s": 13077, "text": "Let us write the definition of the function in JavaScript as shown below −" }, { "code": null, "e": 13230, "s": 13152, "text": "const double = x => x*2; // es6 arrow function\nconsole.log(double(2)); // 4\n" }, { "code": null, "e": 13263, "s": 13230, "text": "Here, double is a pure function." }, { "code": null, "e": 13434, "s": 13263, "text": "As per the three principles in Redux, changes must be made by a pure function, i.e., reducer in Redux. Now, a question arises as to why a reducer must be a pure function." }, { "code": null, "e": 13591, "s": 13434, "text": "Suppose, you want to dispatch an action whose type is 'ADD_TO_CART_SUCCESS' to add an item to your shopping cart application by clicking add to cart button." }, { "code": null, "e": 13665, "s": 13591, "text": "Let us assume the reducer is adding an item to your cart as given below −" }, { "code": null, "e": 14039, "s": 13665, "text": "const initialState = {\n isAddedToCart: false;\n}\nconst addToCartReducer = (state = initialState, action) => { //es6 arrow function\n switch (action.type) {\n case 'ADD_TO_CART_SUCCESS' :\n state.isAddedToCart = !state.isAddedToCart; //original object altered\n return state;\n default:\n return state;\n }\n}\nexport default addToCartReducer ;" }, { "code": null, "e": 14473, "s": 14039, "text": "Let us suppose, isAddedToCart is a property on state object that allows you to decide when to disable ‘add to cart’ button for the item by returning a Boolean value ‘true or false’. This prevents user to add same product multiple times. Now, instead of returning a new object, we are mutating isAddedToCart prop on the state like above. Now if we try to add an item to cart, nothing happens. Add to cart button will not get disabled." }, { "code": null, "e": 14519, "s": 14473, "text": "The reason for this behaviour is as follows −" }, { "code": null, "e": 14822, "s": 14519, "text": "Redux compares old and new objects by the memory location of both the objects. It expects a new object from reducer if any change has happened. And it also expects to get the old object back if no change occurs. In this case, it is the same. Due to this reason, Redux assumes that nothing has happened." }, { "code": null, "e": 14942, "s": 14822, "text": "So, it is necessary for a reducer to be a pure function in Redux. The following is a way to write it without mutation −" }, { "code": null, "e": 15312, "s": 14942, "text": "const initialState = {\n isAddedToCart: false;\n}\nconst addToCartReducer = (state = initialState, action) => { //es6 arrow function\n switch (action.type) {\n case 'ADD_TO_CART_SUCCESS' :\n return {\n ...state,\n isAddedToCart: !state.isAddedToCart\n }\n default:\n return state;\n }\n}\nexport default addToCartReducer;" }, { "code": null, "e": 15638, "s": 15312, "text": "Reducers are a pure function in Redux. Pure functions are predictable. Reducers are the only way to change states in Redux. It is the only place where you can write logic and calculations. Reducer function will accept the previous state of app and action being dispatched, calculate the next state and returns the new object." }, { "code": null, "e": 15710, "s": 15638, "text": "The following few things should never be performed inside the reducer −" }, { "code": null, "e": 15742, "s": 15710, "text": "Mutation of functions arguments" }, { "code": null, "e": 15768, "s": 15742, "text": "API calls & routing logic" }, { "code": null, "e": 15813, "s": 15768, "text": "Calling non-pure function e.g. Math.random()" }, { "code": null, "e": 15856, "s": 15813, "text": "The following is the syntax of a reducer −" }, { "code": null, "e": 15884, "s": 15856, "text": "(state,action) => newState\n" }, { "code": null, "e": 16048, "s": 15884, "text": "Let us continue the example of showing the list of product items on a web page, discussed in the action creators module. Let us see below how to write its reducer." }, { "code": null, "e": 16570, "s": 16048, "text": "const initialState = {\n isLoading: false,\n items: []\n};\nconst reducer = (state = initialState, action) => {\n switch (action.type) {\n case 'ITEMS_REQUEST':\n return Object.assign({}, state, {\n isLoading: action.payload.isLoading\n })\n case ‘ITEMS_REQUEST_SUCCESS':\n return Object.assign({}, state, {\n items: state.items.concat(action.items),\n isLoading: action.isLoading\n })\n default:\n return state;\n }\n}\nexport default reducer;" }, { "code": null, "e": 16829, "s": 16570, "text": "Firstly, if you do not set state to ‘initialState’, Redux calls reducer with the undefined state. In this code example, concat() function of JavaScript is used in ‘ITEMS_REQUEST_SUCCESS', which does not change the existing array; instead returns a new array." }, { "code": null, "e": 16991, "s": 16829, "text": "In this way, you can avoid mutation of the state. Never write directly to the state. In 'ITEMS_REQUEST', we have to set the state value from the action received." }, { "code": null, "e": 17216, "s": 16991, "text": "It is already discussed that we can write our logic in reducer and can split it on the logical data basis. Let us see how we can split reducers and combine them together as root reducer when dealing with a large application." }, { "code": null, "e": 17546, "s": 17216, "text": "Suppose, we want to design a web page where a user can access product order status and see wishlist information. We can separate the logic in different reducers files, and make them work independently. Let us assume that GET_ORDER_STATUS action is dispatched to get the status of order corresponding to some order id and user id." }, { "code": null, "e": 17860, "s": 17546, "text": "/reducer/orderStatusReducer.js\nimport { GET_ORDER_STATUS } from ‘../constants/appConstant’;\nexport default function (state = {} , action) {\n switch(action.type) {\n case GET_ORDER_STATUS:\n return { ...state, orderStatusData: action.payload.orderStatus };\n default:\n return state;\n }\n}" }, { "code": null, "e": 17979, "s": 17860, "text": "Similarly, assume GET_WISHLIST_ITEMS action is dispatched to get the user’s wishlist information respective of a user." }, { "code": null, "e": 18298, "s": 17979, "text": "/reducer/getWishlistDataReducer.js\nimport { GET_WISHLIST_ITEMS } from ‘../constants/appConstant’;\nexport default function (state = {}, action) {\n switch(action.type) {\n case GET_WISHLIST_ITEMS:\n return { ...state, wishlistData: action.payload.wishlistData };\n default:\n return state;\n }\n}" }, { "code": null, "e": 18604, "s": 18298, "text": "Now, we can combine both reducers by using Redux combineReducers utility. The combineReducers generate a function which returns an object whose values are different reducer functions. You can import all the reducers in index reducer file and combine them together as an object with their respective names." }, { "code": null, "e": 18946, "s": 18604, "text": "/reducer/index.js\nimport { combineReducers } from ‘redux’;\nimport OrderStatusReducer from ‘./orderStatusReducer’;\nimport GetWishlistDataReducer from ‘./getWishlistDataReducer’;\n\nconst rootReducer = combineReducers ({\n orderStatusReducer: OrderStatusReducer,\n getWishlistDataReducer: GetWishlistDataReducer\n});\nexport default rootReducer;" }, { "code": null, "e": 19020, "s": 18946, "text": "Now, you can pass this rootReducer to the createStore method as follows −" }, { "code": null, "e": 19061, "s": 19020, "text": "const store = createStore(rootReducer);\n" }, { "code": null, "e": 19422, "s": 19061, "text": "Redux itself is synchronous, so how the async operations like network request work with Redux? Here middlewares come handy. As discussed earlier, reducers are the place where all the execution logic is written. Reducer has nothing to do with who performs it, how much time it is taking or logging the state of the app before and after the action is dispatched." }, { "code": null, "e": 19922, "s": 19422, "text": "In this case, Redux middleware function provides a medium to interact with dispatched action before they reach the reducer. Customized middleware functions can be created by writing high order functions (a function that returns another function), which wraps around some logic. Multiple middlewares can be combined together to add new functionality, and each middleware requires no knowledge of what came before and after. You can imagine middlewares somewhere between action dispatched and reducer." }, { "code": null, "e": 20231, "s": 19922, "text": "Commonly, middlewares are used to deal with asynchronous actions in your app. Redux provides with API called applyMiddleware which allows us to use custom middleware as well as Redux middlewares like redux-thunk and redux-promise. It applies middlewares to store. The syntax of using applyMiddleware API is −" }, { "code": null, "e": 20263, "s": 20231, "text": "applyMiddleware(...middleware)\n" }, { "code": null, "e": 20309, "s": 20263, "text": "And this can be applied to store as follows −" }, { "code": null, "e": 20504, "s": 20309, "text": "import { createStore, applyMiddleware } from 'redux';\nimport thunk from 'redux-thunk';\nimport rootReducer from './reducers/index';\nconst store = createStore(rootReducer, applyMiddleware(thunk));" }, { "code": null, "e": 20648, "s": 20504, "text": "Middlewares will let you write an action dispatcher which returns a function instead of an action object. Example for the same is shown below −" }, { "code": null, "e": 20746, "s": 20648, "text": "function getUser() {\n return function() {\n return axios.get('/get_user_details');\n };\n}\n" }, { "code": null, "e": 21082, "s": 20746, "text": "Conditional dispatch can be written inside middleware. Each middleware receives store’s dispatch so that they can dispatch new action, and getState functions as arguments so that they can access the current state and return a function. Any return value from an inner function will be available as the value of dispatch function itself." }, { "code": null, "e": 21128, "s": 21082, "text": "The following is the syntax of a middleware −" }, { "code": null, "e": 21172, "s": 21128, "text": "({ getState, dispatch }) => next => action\n" }, { "code": null, "e": 21319, "s": 21172, "text": "The getState function is useful to decide whether new data is to be fetched or cache result should get returned, depending upon the current state." }, { "code": null, "e": 21422, "s": 21319, "text": "Let us see an example of a custom middleware logger function. It simply logs the action and new state." }, { "code": null, "e": 21746, "s": 21422, "text": "import { createStore, applyMiddleware } from 'redux'\nimport userLogin from './reducers'\n\nfunction logger({ getState }) {\n return next => action => {\n console.log(‘action’, action);\n const returnVal = next(action);\n console.log('state when action is dispatched', getState()); \n return returnVal;\n }\n}" }, { "code": null, "e": 21831, "s": 21746, "text": "Now apply the logger middleware to the store by writing the following line of code −" }, { "code": null, "e": 21915, "s": 21831, "text": "const store = createStore(userLogin , initialState=[ ] , applyMiddleware(logger));\n" }, { "code": null, "e": 22002, "s": 21915, "text": "Dispatch an action to check the action dispatched and new state using the below code −" }, { "code": null, "e": 22067, "s": 22002, "text": "store.dispatch({\n type: 'ITEMS_REQUEST', \n\tisLoading: true\n})\n" }, { "code": null, "e": 22291, "s": 22067, "text": "Another example of middleware where you can handle when to show or hide the loader is given below. This middleware shows the loader when you are requesting any resource and hides it when resource request has been completed." }, { "code": null, "e": 22752, "s": 22291, "text": "import isPromise from 'is-promise';\n\nfunction loaderHandler({ dispatch }) {\n return next => action => {\n if (isPromise(action)) {\n dispatch({ type: 'SHOW_LOADER' });\n action\n .then(() => dispatch({ type: 'HIDE_LOADER' }))\n .catch(() => dispatch({ type: 'HIDE_LOADER' }));\n }\n return next(action);\n };\n}\nconst store = createStore(\n userLogin , initialState = [ ] , \n applyMiddleware(loaderHandler)\n);" }, { "code": null, "e": 22941, "s": 22752, "text": "Redux-Devtools provide us debugging platform for Redux apps. It allows us to perform time-travel debugging and live editing. Some of the features in official documentation are as follows −" }, { "code": null, "e": 22993, "s": 22941, "text": "It lets you inspect every state and action payload." }, { "code": null, "e": 23045, "s": 22993, "text": "It lets you inspect every state and action payload." }, { "code": null, "e": 23098, "s": 23045, "text": "It lets you go back in time by “cancelling” actions." }, { "code": null, "e": 23151, "s": 23098, "text": "It lets you go back in time by “cancelling” actions." }, { "code": null, "e": 23226, "s": 23151, "text": "If you change the reducer code, each “staged” action will be re-evaluated." }, { "code": null, "e": 23301, "s": 23226, "text": "If you change the reducer code, each “staged” action will be re-evaluated." }, { "code": null, "e": 23394, "s": 23301, "text": "If the reducers throw, we can identify the error and also during which action this happened." }, { "code": null, "e": 23487, "s": 23394, "text": "If the reducers throw, we can identify the error and also during which action this happened." }, { "code": null, "e": 23575, "s": 23487, "text": "With persistState() store enhancer, you can persist debug sessions across page reloads." }, { "code": null, "e": 23663, "s": 23575, "text": "With persistState() store enhancer, you can persist debug sessions across page reloads." }, { "code": null, "e": 23722, "s": 23663, "text": "There are two variants of Redux dev-tools as given below −" }, { "code": null, "e": 23826, "s": 23722, "text": "Redux DevTools − It can be installed as a package and integrated into your application as given below −" }, { "code": null, "e": 23919, "s": 23826, "text": "https://github.com/reduxjs/redux-devtools/blob/master/docs/Walkthrough.md#manual-integration" }, { "code": null, "e": 24033, "s": 23919, "text": "Redux DevTools Extension − A browser extension that implements the same developer tools for Redux is as follows −" }, { "code": null, "e": 24088, "s": 24033, "text": "https://github.com/zalmoxisus/redux-devtools-extension" }, { "code": null, "e": 24436, "s": 24088, "text": "Now let us check how we can skip actions and go back in time with the help of Redux dev tool. Following screenshots explain about the actions we have dispatched earlier to get the listing of items. Here we can see the actions dispatched in the inspector tab. On the right, you can see the Demo tab which shows you the difference in the state tree." }, { "code": null, "e": 24719, "s": 24436, "text": "You will get familiar with this tool when you start using it. You can dispatch an action without writing the actual code just from this Redux plugin tool. A Dispatcher option in the last row will help you with this. Let us check the last action where items are fetched successfully." }, { "code": null, "e": 24948, "s": 24719, "text": "We received an array of objects as a response from the server. All the data is available to display listing on our page. You can also track the store’s state at the same time by clicking on the state tab on the upper right side." }, { "code": null, "e": 25188, "s": 24948, "text": "In the previous sections, we have learnt about time travel debugging. Let us now check how to skip one action and go back in time to analyze the state of our app. As you click on any action type, two options: ‘Jump’ and ‘Skip’ will appear." }, { "code": null, "e": 25632, "s": 25188, "text": "By clicking on the skip button on a certain action type, you can skip particular action. It acts as if the action never happened. When you click on jump button on certain action type, it will take you to the state when that action occurred and skip all the remaining actions in sequence. This way you will be able to retain the state when a particular action happened. This feature is useful in debugging and finding errors in the application." }, { "code": null, "e": 25880, "s": 25632, "text": "We skipped the last action, and all the listing data from background got vanished. It takes back to the time when data of the items has not arrived, and our app has no data to render on the page. It actually makes coding easy and debugging easier." }, { "code": null, "e": 26112, "s": 25880, "text": "Testing Redux code is easy as we mostly write functions, and most of them are pure. So we can test it without even mocking them. Here, we are using JEST as a testing engine. It works in the node environment and does not access DOM." }, { "code": null, "e": 26160, "s": 26112, "text": "We can install JEST with the code given below −" }, { "code": null, "e": 26189, "s": 26160, "text": "npm install --save-dev jest\n" }, { "code": null, "e": 26245, "s": 26189, "text": "With babel, you need to install babel-jest as follows −" }, { "code": null, "e": 26280, "s": 26245, "text": "npm install --save-dev babel-jest\n" }, { "code": null, "e": 26364, "s": 26280, "text": "And configure it to use babel-preset-env features in the .babelrc file as follows −" }, { "code": null, "e": 26597, "s": 26364, "text": "{ \n \"presets\": [\"@babel/preset-env\"] \n}\nAnd add the following script in your package.json:\n{ \n //Some other code \n \"scripts\": {\n //code\n \"test\": \"jest\", \n \"test:watch\": \"npm test -- --watch\" \n }, \n //code \n}" }, { "code": null, "e": 26711, "s": 26597, "text": "Finally, run npm test or npm run test. Let us check how we can write test cases for action creators and reducers." }, { "code": null, "e": 26766, "s": 26711, "text": "Let us assume you have action creator as shown below −" }, { "code": null, "e": 26887, "s": 26766, "text": "export function itemsRequestSuccess(bool) {\n return {\n type: ITEMS_REQUEST_SUCCESS,\n isLoading: bool,\n }\n}" }, { "code": null, "e": 26938, "s": 26887, "text": "This action creator can be tested as given below −" }, { "code": null, "e": 27351, "s": 26938, "text": "import * as action from '../actions/actions';\nimport * as types from '../../constants/ActionTypes';\n\ndescribe('actions', () => {\n it('should create an action to check if item is loading', () => { \n const isLoading = true, \n const expectedAction = { \n type: types.ITEMS_REQUEST_SUCCESS, isLoading \n } \n expect(actions.itemsRequestSuccess(isLoading)).toEqual(expectedAction) \n })\n})" }, { "code": null, "e": 27469, "s": 27351, "text": "We have learnt that reducer should return a new state when action is applied. So reducer is tested on this behaviour." }, { "code": null, "e": 27505, "s": 27469, "text": "Consider a reducer as given below −" }, { "code": null, "e": 27829, "s": 27505, "text": "const initialState = {\n isLoading: false\n};\nconst reducer = (state = initialState, action) => {\n switch (action.type) {\n case 'ITEMS_REQUEST':\n return Object.assign({}, state, {\n isLoading: action.payload.isLoading\n })\n default:\n return state;\n }\n}\nexport default reducer;" }, { "code": null, "e": 27941, "s": 27829, "text": "To test above reducer, we need to pass state and action to the reducer, and return a new state as shown below −" }, { "code": null, "e": 28570, "s": 27941, "text": "import reducer from '../../reducer/reducer' \nimport * as types from '../../constants/ActionTypes'\n\ndescribe('reducer initial state', () => {\n it('should return the initial state', () => {\n expect(reducer(undefined, {})).toEqual([\n {\n isLoading: false,\n }\n ])\n })\n it('should handle ITEMS_REQUEST', () => {\n expect(\n reducer(\n {\n isLoading: false,\n },\n {\n type: types.ITEMS_REQUEST,\n payload: { isLoading: true }\n }\n )\n ).toEqual({\n isLoading: true\n })\n })\n})" }, { "code": null, "e": 28652, "s": 28570, "text": "If you are not familiar with writing test case, you can check the basics of JEST." }, { "code": null, "e": 28866, "s": 28652, "text": "In the previous chapters, we have learnt what is Redux and how it works. Let us now check the integration of view part with Redux. You can add any view layer to Redux. We will also discuss react library and Redux." }, { "code": null, "e": 29216, "s": 28866, "text": "Let us say if various react components need to display the same data in different ways without passing it as a prop to all the components from top-level component to the way down. It would be ideal to store it outside the react components. Because it helps in faster data retrieval as you need not pass data all the way down to different components." }, { "code": null, "e": 29362, "s": 29216, "text": "Let us discuss how it is possible with Redux. Redux provides the react-redux package to bind react components with two utilities as given below −" }, { "code": null, "e": 29371, "s": 29362, "text": "Provider" }, { "code": null, "e": 29379, "s": 29371, "text": "Connect" }, { "code": null, "e": 29564, "s": 29379, "text": "Provider makes the store available to rest of the application. Connect function helps react component to connect to the store, responding to each change occurring in the store’s state." }, { "code": null, "e": 29717, "s": 29564, "text": "Let us have a look at the root index.js file which creates store and uses a provider that enables the store to the rest of the app in a react-redux app." }, { "code": null, "e": 30256, "s": 29717, "text": "import React from 'react'\nimport { render } from 'react-dom'\nimport { Provider } from 'react-redux'\nimport { createStore, applyMiddleware } from 'redux';\nimport reducer from './reducers/reducer'\nimport thunk from 'redux-thunk';\nimport App from './components/app'\nimport './index.css';\n\nconst store = createStore(\n reducer,\n window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),\n applyMiddleware(thunk)\n)\nrender(\n <Provider store = {store}>\n <App />\n </Provider>,\n document.getElementById('root')\n)" }, { "code": null, "e": 30424, "s": 30256, "text": "Whenever a change occurs in a react-redux app, mapStateToProps() is called. In this function, we exactly specify which state we need to provide to our react component." }, { "code": null, "e": 30710, "s": 30424, "text": "With the help of connect() function explained below, we are connecting these app’s state to react component. Connect() is a high order function which takes component as a parameter. It performs certain operations and returns a new component with correct data which we finally exported." }, { "code": null, "e": 30949, "s": 30710, "text": "With the help of mapStateToProps(), we provide these store states as prop to our react component. This code can be wrapped in a container component. The motive is to separate concerns like data fetching, rendering concern and reusability." }, { "code": null, "e": 31432, "s": 30949, "text": "import { connect } from 'react-redux'\nimport Listing from '../components/listing/Listing' //react component\nimport makeApiCall from '../services/services' //component to make api call\n\nconst mapStateToProps = (state) => {\n return {\n items: state.items,\n isLoading: state.isLoading\n };\n};\nconst mapDispatchToProps = (dispatch) => {\n return {\n fetchData: () => dispatch(makeApiCall())\n };\n};\nexport default connect(mapStateToProps, mapDispatchToProps)(Listing);" }, { "code": null, "e": 31518, "s": 31432, "text": "The definition of a component to make an api call in services.js file is as follows −" }, { "code": null, "e": 32049, "s": 31518, "text": "import axios from 'axios'\nimport { itemsLoading, itemsFetchDataSuccess } from '../actions/actions'\n\nexport default function makeApiCall() {\n return (dispatch) => {\n dispatch(itemsLoading(true));\n axios.get('http://api.tvmaze.com/shows')\n .then((response) => {\n if (response.status !== 200) {\n throw Error(response.statusText);\n }\n dispatch(itemsLoading(false));\n return response;\n })\n .then((response) => dispatch(itemsFetchDataSuccess(response.data)))\n };\n}" }, { "code": null, "e": 32207, "s": 32049, "text": "mapDispatchToProps() function receives dispatch function as a parameter and returns you callback props as plain object that you pass to your react component." }, { "code": null, "e": 32485, "s": 32207, "text": "Here, you can access fetchData as a prop in your react listing component, which dispatches an action to make an API call. mapDispatchToProps() is used to dispatch an action to store. In react-redux, components cannot access the store directly. The only way is to use connect()." }, { "code": null, "e": 32557, "s": 32485, "text": "Let us understand how the react-redux works through the below diagram −" }, { "code": null, "e": 32622, "s": 32557, "text": "STORE − Stores all your application state as a JavaScript object" }, { "code": null, "e": 32656, "s": 32622, "text": "PROVIDER − Makes stores available" }, { "code": null, "e": 32720, "s": 32656, "text": "CONTAINER − Get apps state & provide it as a prop to components" }, { "code": null, "e": 32770, "s": 32720, "text": "COMPONENT − User interacts through view component" }, { "code": null, "e": 32853, "s": 32770, "text": "ACTIONS − Causes a change in store, it may or may not change the state of your app" }, { "code": null, "e": 32945, "s": 32853, "text": "REDUCER − Only way to change app state, accept state and action, and returns updated state." }, { "code": null, "e": 33260, "s": 32945, "text": "However, Redux is an independent library and can be used with any UI layer. React-redux is the official Redux, UI binding with the react. Moreover, it encourages a good react Redux app structure. React-redux internally implements performance optimization, so that component re-render occurs only when it is needed." }, { "code": null, "e": 33483, "s": 33260, "text": "To sum up, Redux is not designed to write shortest and the fastest code. It is intended to provide a predictable state management container. It helps us understand when a certain state changed, or where the data came from." }, { "code": null, "e": 33641, "s": 33483, "text": "Here is a small example of react and Redux application. You can also try developing small apps. Sample code for increase or decrease counter is given below −" }, { "code": null, "e": 33749, "s": 33641, "text": "This is the root file which is responsible for the creation of store and rendering our react app component." }, { "code": null, "e": 34223, "s": 33749, "text": "/src/index.js\n\nimport React from 'react'\nimport { render } from 'react-dom'\nimport { Provider } from 'react-redux'\nimport { createStore } from 'redux';\nimport reducer from '../src/reducer/index'\nimport App from '../src/App'\nimport './index.css';\n\nconst store = createStore(\n reducer,\n window.__REDUX_DEVTOOLS_EXTENSION__ && \n window.__REDUX_DEVTOOLS_EXTENSION__()\n)\nrender(\n <Provider store = {store}>\n <App />\n </Provider>, document.getElementById('root')\n)" }, { "code": null, "e": 34332, "s": 34223, "text": "This is our root component of react. It is responsible for rendering counter container component as a child." }, { "code": null, "e": 34699, "s": 34332, "text": "/src/app.js\n\nimport React, { Component } from 'react';\nimport './App.css';\nimport Counter from '../src/container/appContainer';\n\nclass App extends Component {\n render() {\n return (\n <div className = \"App\">\n <header className = \"App-header\">\n <Counter/>\n </header>\n </div>\n );\n }\n}\nexport default App;" }, { "code": null, "e": 34810, "s": 34699, "text": "The following is the container component which is responsible for providing Redux’s state to react component −" }, { "code": null, "e": 35324, "s": 34810, "text": "/container/counterContainer.js\n\nimport { connect } from 'react-redux'\nimport Counter from '../component/counter'\nimport { increment, decrement, reset } from '../actions';\n\nconst mapStateToProps = (state) => {\n return {\n counter: state\n };\n};\nconst mapDispatchToProps = (dispatch) => {\n return {\n increment: () => dispatch(increment()),\n decrement: () => dispatch(decrement()),\n reset: () => dispatch(reset())\n };\n};\nexport default connect(mapStateToProps, mapDispatchToProps)(Counter);" }, { "code": null, "e": 35387, "s": 35324, "text": "Given below is the react component responsible for view part −" }, { "code": null, "e": 35963, "s": 35387, "text": "/component/counter.js\nimport React, { Component } from 'react';\nclass Counter extends Component {\n render() {\n const {counter,increment,decrement,reset} = this.props;\n return (\n <div className = \"App\">\n <div>{counter}</div>\n <div>\n <button onClick = {increment}>INCREMENT BY 1</button>\n </div>\n <div>\n <button onClick = {decrement}>DECREMENT BY 1</button>\n </div>\n <button onClick = {reset}>RESET</button>\n </div>\n );\n }\n}\nexport default Counter;" }, { "code": null, "e": 36038, "s": 35963, "text": "The following are the action creators responsible for creating an action −" }, { "code": null, "e": 36258, "s": 36038, "text": "/actions/index.js\nexport function increment() {\n return {\n type: 'INCREMENT'\n }\n}\nexport function decrement() {\n return {\n type: 'DECREMENT'\n }\n}\nexport function reset() {\n return { type: 'RESET' }\n}" }, { "code": null, "e": 36363, "s": 36258, "text": "Below, we have shown line of code for reducer file which is responsible for updating the state in Redux." }, { "code": null, "e": 36612, "s": 36363, "text": "reducer/index.js\nconst reducer = (state = 0, action) => {\n switch (action.type) {\n case 'INCREMENT': return state + 1\n case 'DECREMENT': return state - 1\n case 'RESET' : return 0 default: return state\n }\n}\nexport default reducer;" }, { "code": null, "e": 36650, "s": 36612, "text": "Initially, the app looks as follows −" }, { "code": null, "e": 36727, "s": 36650, "text": "When I click increment two times, the output screen will be as shown below −" }, { "code": null, "e": 36786, "s": 36727, "text": "When we decrement it once, it shows the following screen −" }, { "code": null, "e": 36884, "s": 36786, "text": "And reset will take the app back to initial state which is counter value 0. This is shown below −" }, { "code": null, "e": 36982, "s": 36884, "text": "Let us understand what happens with Redux dev tools when the first increment action takes place −" }, { "code": null, "e": 37103, "s": 36982, "text": "State of the app will be moved to the time when only increment action is dispatched and rest of the actions are skipped." } ]
Priority queue of pairs in C++ (Ordered by first)
04 Oct, 2018 In C++, priority_queue implements heap. Below are some examples of creating priority queue of pair type. Max Priority queue (Or Max heap) ordered by first element // C++ program to create a priority queue of pairs.// By default a max heap is created ordered// by first element of pair.#include <bits/stdc++.h> using namespace std; // Driver program to test methods of graph classint main(){ // By default a max heap is created ordered // by first element of pair. priority_queue<pair<int, int> > 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;} Output : 20 100 Min Priority queue (Or Min heap) ordered by first element // C++ program to create a priority queue of pairs.// We can create a min heap by passing adding two // parameters, vector and greater().#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pi; // Driver program to test methods of graph classint main(){ // By default a min heap is created ordered // by first element of pair. 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;} Output : 10 200 addiegupta cpp-pair cpp-priority-queue STL Heap Heap STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Sliding Window Maximum (Maximum of all subarrays of size k) Building Heap from Array Max Heap in Java Priority Queue in Python Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Insertion and Deletion in Heaps Sort a nearly sorted (or K sorted) array Merge k sorted arrays | Set 1 Find k numbers with most occurrences in the given array
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Oct, 2018" }, { "code": null, "e": 157, "s": 52, "text": "In C++, priority_queue implements heap. Below are some examples of creating priority queue of pair type." }, { "code": null, "e": 215, "s": 157, "text": "Max Priority queue (Or Max heap) ordered by first element" }, { "code": "// C++ program to create a priority queue of pairs.// By default a max heap is created ordered// by first element of pair.#include <bits/stdc++.h> using namespace std; // Driver program to test methods of graph classint main(){ // By default a max heap is created ordered // by first element of pair. priority_queue<pair<int, int> > 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;}", "e": 754, "s": 215, "text": null }, { "code": null, "e": 763, "s": 754, "text": "Output :" }, { "code": null, "e": 770, "s": 763, "text": "20 100" }, { "code": null, "e": 828, "s": 770, "text": "Min Priority queue (Or Min heap) ordered by first element" }, { "code": "// C++ program to create a priority queue of pairs.// We can create a min heap by passing adding two // parameters, vector and greater().#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pi; // Driver program to test methods of graph classint main(){ // By default a min heap is created ordered // by first element of pair. 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;}", "e": 1423, "s": 828, "text": null }, { "code": null, "e": 1432, "s": 1423, "text": "Output :" }, { "code": null, "e": 1439, "s": 1432, "text": "10 200" }, { "code": null, "e": 1450, "s": 1439, "text": "addiegupta" }, { "code": null, "e": 1459, "s": 1450, "text": "cpp-pair" }, { "code": null, "e": 1478, "s": 1459, "text": "cpp-priority-queue" }, { "code": null, "e": 1482, "s": 1478, "text": "STL" }, { "code": null, "e": 1487, "s": 1482, "text": "Heap" }, { "code": null, "e": 1492, "s": 1487, "text": "Heap" }, { "code": null, "e": 1496, "s": 1492, "text": "STL" }, { "code": null, "e": 1594, "s": 1496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1626, "s": 1594, "text": "Introduction to Data Structures" }, { "code": null, "e": 1686, "s": 1626, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 1711, "s": 1686, "text": "Building Heap from Array" }, { "code": null, "e": 1728, "s": 1711, "text": "Max Heap in Java" }, { "code": null, "e": 1753, "s": 1728, "text": "Priority Queue in Python" }, { "code": null, "e": 1823, "s": 1753, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 1855, "s": 1823, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 1896, "s": 1855, "text": "Sort a nearly sorted (or K sorted) array" }, { "code": null, "e": 1926, "s": 1896, "text": "Merge k sorted arrays | Set 1" } ]
Difference Between Sequential, Indexed, and Relative Files in COBOL
07 Sep, 2021 Files are the collection of records related to a particular entity. Through file handling, we can store these records in an organized order. These records are stored either on magnetic tape or on a hard disk. The files are further classified into 3 types: Sequential file organization.Relative file organization.Indexed file organization. Sequential file organization. Relative file organization. Indexed file organization. It has unlimited storage and thus stores a large volume of data.It stores the data permanently on the device.It reduces the re-editing of data. It has unlimited storage and thus stores a large volume of data. It stores the data permanently on the device. It reduces the re-editing of data. It provides slow access.Cannot perform operations efficiently. It provides slow access. Cannot perform operations efficiently. Entries for declaring a file: Python3 ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT RFILE ASSIGN TO Storage Device. [RESERVE INT-1{AREA/AREAS}] [ORGANIZATION IS {SEQUENTIAL/RELATIVE/INDEXED}] [ACCESS MODE IS {SEQUENTIAL/RANDOM/DYNAMIC}] [RELATIVE KEY Variable] [FILE STATUS IS DATA-NAME]. DATA-DIVISION. FILE-SECTION. FD File Name. The Sequential file organization stores the data in sequence order. We can access the data sequentially and the data can be stored only at the end of the file. There are 2 types of sequential files: A line sequential file is also known as a text file or ASCII file. It is a simple text file that can be edited by almost all PC editors. It separates each record from the other by adding a delimiter at the end of the record. In the case of windows and DOS, the carriage return (x”OD”) and line feed (x”OA”) is added at the end of the record, whereas in UNIX only the line feed(x”OA”)is added at the end of the record. Example: Python3 IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT FILE1 ASSIGN TO DISK ORGANIZATION IS LINE SEQUENTIAL.DATA DIVISION.FILE SECTION.FD FILE1. 01 STUDENT. 02 RNO PIC 99. 02 NAME PIC A(7). 02 PERC PIC 99.99. Record sequential file is default sequential file. These records are based either on the size(bytes) which is defined by the programmer or on the size of the record.If the size of the record is defined by the programmer then it is known as Fixed length.If the records are stored on the basis of the size of the records then it is known as Variable length. If the size of the record is defined by the programmer then it is known as Fixed length. If the records are stored on the basis of the size of the records then it is known as Variable length. Variable-length records save the space of the hard disk as compared to fixed-length records. Example: Python3 IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT FILE1 ASSIGN TO DISK ORGANIZATION IS RECORD SEQUENTIAL.DATA DIVISION.FILE SECTION.FD LENGTH RECORDING MODE IS V RECORD CONTAINS 0 TO 99 CHARACTERS.FD FILE1. 01 STUDENT. 02 RNO PIC 99. 02 NAME PIC A(7). 02 PERC PIC 99.99. Indexed file organization stores the record sequentially depending on the value of the RECORD-KEY(generally in ascending order). A RECORD-KEY in an Indexed file is a variable that must be part of the record/data. In the case of Indexed files two types of files are created: Data file: It consists of the records in sequential order.Index file: It consists of the RECORD-KEY and the address of the RECORD-KEY in the data file. Data file: It consists of the records in sequential order. Index file: It consists of the RECORD-KEY and the address of the RECORD-KEY in the data file. The Indexed file can be accessed sequentially same as Sequential file organization as well as randomly only if the RECORD-KEY is known. Example: Python3 IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT IFILE ASSIGN TO DISK ORGANIZATION IS INDEXED ACCESS MODE RANDOM RECORD KEY RNO.DATA DIVISION.FILE SECTION.FD IFILE. 01 STUDENT. 02 RNO PIC 99. 02 NAME PIC A(7). 02 PERC PIC 99.99. Relative file organization stores the record on the basis of their relative address. Each record is identified by its Relative Record Number, a Relative Record Number is the position of the record from the beginning of the file. These records can be accessed sequentially same as Sequential file organization as well as randomly, to access files randomly the user must specify the relative record number. Example: Python3 IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT RFILE ASSIGN TO DISK ORGANIZATION IS RELATIVE ACCESS MODE RANDOM RELATIVE KEY POS.DATA DIVISION.FILE SECTION.FD RFILE. 01 STUDENT. 02 RNO PIC 99. 02 NAME PIC A(7). 02 PERC PIC 99.99. Difference between Sequential, Indexed, Relative files: Picked COBOL Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Sep, 2021" }, { "code": null, "e": 284, "s": 28, "text": "Files are the collection of records related to a particular entity. Through file handling, we can store these records in an organized order. These records are stored either on magnetic tape or on a hard disk. The files are further classified into 3 types:" }, { "code": null, "e": 367, "s": 284, "text": "Sequential file organization.Relative file organization.Indexed file organization." }, { "code": null, "e": 397, "s": 367, "text": "Sequential file organization." }, { "code": null, "e": 425, "s": 397, "text": "Relative file organization." }, { "code": null, "e": 452, "s": 425, "text": "Indexed file organization." }, { "code": null, "e": 596, "s": 452, "text": "It has unlimited storage and thus stores a large volume of data.It stores the data permanently on the device.It reduces the re-editing of data." }, { "code": null, "e": 661, "s": 596, "text": "It has unlimited storage and thus stores a large volume of data." }, { "code": null, "e": 707, "s": 661, "text": "It stores the data permanently on the device." }, { "code": null, "e": 742, "s": 707, "text": "It reduces the re-editing of data." }, { "code": null, "e": 805, "s": 742, "text": "It provides slow access.Cannot perform operations efficiently." }, { "code": null, "e": 830, "s": 805, "text": "It provides slow access." }, { "code": null, "e": 869, "s": 830, "text": "Cannot perform operations efficiently." }, { "code": null, "e": 899, "s": 869, "text": "Entries for declaring a file:" }, { "code": null, "e": 907, "s": 899, "text": "Python3" }, { "code": "ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT RFILE ASSIGN TO Storage Device. [RESERVE INT-1{AREA/AREAS}] [ORGANIZATION IS {SEQUENTIAL/RELATIVE/INDEXED}] [ACCESS MODE IS {SEQUENTIAL/RANDOM/DYNAMIC}] [RELATIVE KEY Variable] [FILE STATUS IS DATA-NAME]. DATA-DIVISION. FILE-SECTION. FD File Name.", "e": 1224, "s": 907, "text": null }, { "code": null, "e": 1424, "s": 1224, "text": "The Sequential file organization stores the data in sequence order. We can access the data sequentially and the data can be stored only at the end of the file. There are 2 types of sequential files:" }, { "code": null, "e": 1843, "s": 1424, "text": "A line sequential file is also known as a text file or ASCII file. It is a simple text file that can be edited by almost all PC editors. It separates each record from the other by adding a delimiter at the end of the record. In the case of windows and DOS, the carriage return (x”OD”) and line feed (x”OA”) is added at the end of the record, whereas in UNIX only the line feed(x”OA”)is added at the end of the record." }, { "code": null, "e": 1852, "s": 1843, "text": "Example:" }, { "code": null, "e": 1860, "s": 1852, "text": "Python3" }, { "code": "IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT FILE1 ASSIGN TO DISK ORGANIZATION IS LINE SEQUENTIAL.DATA DIVISION.FILE SECTION.FD FILE1. 01 STUDENT. 02 RNO PIC 99. 02 NAME PIC A(7). 02 PERC PIC 99.99.", "e": 2119, "s": 1860, "text": null }, { "code": null, "e": 2475, "s": 2119, "text": "Record sequential file is default sequential file. These records are based either on the size(bytes) which is defined by the programmer or on the size of the record.If the size of the record is defined by the programmer then it is known as Fixed length.If the records are stored on the basis of the size of the records then it is known as Variable length." }, { "code": null, "e": 2564, "s": 2475, "text": "If the size of the record is defined by the programmer then it is known as Fixed length." }, { "code": null, "e": 2667, "s": 2564, "text": "If the records are stored on the basis of the size of the records then it is known as Variable length." }, { "code": null, "e": 2760, "s": 2667, "text": "Variable-length records save the space of the hard disk as compared to fixed-length records." }, { "code": null, "e": 2769, "s": 2760, "text": "Example:" }, { "code": null, "e": 2777, "s": 2769, "text": "Python3" }, { "code": "IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT FILE1 ASSIGN TO DISK ORGANIZATION IS RECORD SEQUENTIAL.DATA DIVISION.FILE SECTION.FD LENGTH RECORDING MODE IS V RECORD CONTAINS 0 TO 99 CHARACTERS.FD FILE1. 01 STUDENT. 02 RNO PIC 99. 02 NAME PIC A(7). 02 PERC PIC 99.99.", "e": 3093, "s": 2777, "text": null }, { "code": null, "e": 3367, "s": 3093, "text": "Indexed file organization stores the record sequentially depending on the value of the RECORD-KEY(generally in ascending order). A RECORD-KEY in an Indexed file is a variable that must be part of the record/data. In the case of Indexed files two types of files are created:" }, { "code": null, "e": 3519, "s": 3367, "text": "Data file: It consists of the records in sequential order.Index file: It consists of the RECORD-KEY and the address of the RECORD-KEY in the data file." }, { "code": null, "e": 3578, "s": 3519, "text": "Data file: It consists of the records in sequential order." }, { "code": null, "e": 3672, "s": 3578, "text": "Index file: It consists of the RECORD-KEY and the address of the RECORD-KEY in the data file." }, { "code": null, "e": 3809, "s": 3672, "text": "The Indexed file can be accessed sequentially same as Sequential file organization as well as randomly only if the RECORD-KEY is known. " }, { "code": null, "e": 3818, "s": 3809, "text": "Example:" }, { "code": null, "e": 3826, "s": 3818, "text": "Python3" }, { "code": "IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT IFILE ASSIGN TO DISK ORGANIZATION IS INDEXED ACCESS MODE RANDOM RECORD KEY RNO.DATA DIVISION.FILE SECTION.FD IFILE. 01 STUDENT. 02 RNO PIC 99. 02 NAME PIC A(7). 02 PERC PIC 99.99.", "e": 4101, "s": 3826, "text": null }, { "code": null, "e": 4506, "s": 4101, "text": "Relative file organization stores the record on the basis of their relative address. Each record is identified by its Relative Record Number, a Relative Record Number is the position of the record from the beginning of the file. These records can be accessed sequentially same as Sequential file organization as well as randomly, to access files randomly the user must specify the relative record number." }, { "code": null, "e": 4515, "s": 4506, "text": "Example:" }, { "code": null, "e": 4523, "s": 4515, "text": "Python3" }, { "code": "IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT RFILE ASSIGN TO DISK ORGANIZATION IS RELATIVE ACCESS MODE RANDOM RELATIVE KEY POS.DATA DIVISION.FILE SECTION.FD RFILE. 01 STUDENT. 02 RNO PIC 99. 02 NAME PIC A(7). 02 PERC PIC 99.99.", "e": 4801, "s": 4523, "text": null }, { "code": null, "e": 4857, "s": 4801, "text": "Difference between Sequential, Indexed, Relative files:" }, { "code": null, "e": 4864, "s": 4857, "text": "Picked" }, { "code": null, "e": 4870, "s": 4864, "text": "COBOL" }, { "code": null, "e": 4889, "s": 4870, "text": "Difference Between" } ]
Largest sum Zigzag sequence in a matrix
16 Dec, 2021 Given a matrix of size n x n, find the sum of the Zigzag sequence with the largest sum. A zigzag sequence starts from the top and ends at the bottom. Two consecutive elements of sequence cannot belong to the same column. Examples: Input : mat[][] = 3 1 2 4 8 5 6 9 7 Output : 18 Zigzag sequence is: 3->8->7 Another such sequence is 2->4->7 Input : mat[][] = 4 2 1 3 9 6 11 3 15 Output : 28 This problem has an Optimal Substructure. Maximum Zigzag sum starting from arr[i][j] to a bottom cell can be written as : zzs(i, j) = arr[i][j] + max(zzs(i+1, k)), where k = 0, 1, 2 and k != j zzs(i, j) = arr[i][j], if i = n-1 We have to find the largest among all as Result = zzs(0, j) where 0 <= j < n C++ Java Python 3 C# PHP Javascript // C++ program to find the largest sum zigzag sequence#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell.int largestZigZagSumRec(int mat[][MAX], int i, int j, int n){ // If we have reached bottom if (i == n-1) return mat[i][j]; // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k=0; k<n; k++) if (k != j) zzs = max(zzs, largestZigZagSumRec(mat, i+1, k, n)); return zzs + mat[i][j];} // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom.int largestZigZag(int mat[][MAX], int n){ // Consider all cells of top row as starting point int res = 0; for (int j=0; j<n; j++) res = max(res, largestZigZagSumRec(mat, 0, j, n)); return res;} // Driver program to test aboveint main(){ int n = 3; int mat[][MAX] = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; cout << "Largest zigzag sum: " << largestZigZag(mat, n); return 0;} // Java program to find the largest sum// zigzag sequenceimport java.io.*; class GFG { static int MAX = 100; // Returns largest sum of a Zigzag // sequence starting from (i, j) // and ending at a bottom cell. static int largestZigZagSumRec(int mat[][], int i, int j, int n) { // If we have reached bottom if (i == n-1) return mat[i][j]; // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k=0; k<n; k++) if (k != j) zzs = Math.max(zzs, largestZigZagSumRec(mat, i+1, k, n)); return zzs + mat[i][j]; } // Returns largest possible sum of a Zigzag // sequence starting from top and ending // at bottom. static int largestZigZag(int mat[][], int n) { // Consider all cells of top row as starting // point int res = 0; for (int j=0; j<n; j++) res = Math.max(res, largestZigZagSumRec(mat, 0, j, n)); return res; } // Driver program to test above public static void main (String[] args) { int n = 3; int mat[][] = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15} }; System.out.println( "Largest zigzag sum: " + largestZigZag(mat, n)); }} // This code is contributed by anuj_67. # Python3 program to find the largest# sum zigzag sequenceMAX = 100 # Returns largest sum of a Zigzag# sequence starting from (i, j) and# ending at a bottom cell.def largestZigZagSumRec( mat, i, j, n): # If we have reached bottom if (i == n-1): return mat[i][j] # Find the largest sum by considering all # possible next elements in sequence. zzs = 0 for k in range(n): if (k != j): zzs = max(zzs, largestZigZagSumRec(mat, i + 1, k, n)) return zzs + mat[i][j] # Returns largest possible sum of a# Zigzag sequence starting from top# and ending at bottom.def largestZigZag(mat, n): # Consider all cells of top row as # starting point res = 0 for j in range(n): res = max(res, largestZigZagSumRec(mat, 0, j, n)) return res # Driver Codeif __name__ == "__main__": n = 3 mat = [ [4, 2, 1], [3, 9, 6], [11, 3, 15]] print("Largest zigzag sum: " , largestZigZag(mat, n)) # This code is contributed by ChitraNayal // C# program to find the largest sum// zigzag sequenceusing System;class GFG { // static int MAX = 100; // Returns largest sum of a Zigzag // sequence starting from (i, j) // and ending at a bottom cell. static int largestZigZagSumRec(int [,]mat, int i, int j, int n) { // If we have reached bottom if (i == n-1) return mat[i,j]; // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k = 0; k < n; k++) if (k != j) zzs = Math.Max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); return zzs + mat[i,j]; } // Returns largest possible // sum of a Zigzag sequence // starting from top and ending // at bottom. static int largestZigZag(int [,]mat, int n) { // Consider all cells of // top row as starting // point int res = 0; for (int j = 0; j < n; j++) res = Math.Max(res, largestZigZagSumRec(mat, 0, j, n)); return res; } // Driver Code public static void Main () { int n = 3; int [,]mat = {{4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; Console.WriteLine("Largest zigzag sum: " + largestZigZag(mat, n)); }} // This code is contributed by anuj_67. <?php// PHP program to find the// largest sum zigzag sequence $MAX = 100; // Returns largest sum of a// Zigzag sequence starting// from (i, j) and ending at// a bottom cell.function largestZigZagSumRec($mat, $i, $j, $n){ // If we have reached bottom if ($i == $n - 1) return $mat[$i][$j]; // Find the largest sum // by considering all // possible next elements // in sequence. $zzs = 0; for ($k = 0; $k < $n; $k++) if ($k != $j) $zzs = max($zzs, largestZigZagSumRec($mat, $i + 1, $k, $n)); return $zzs + $mat[$i][$j];} // Returns largest possible// sum of a Zigzag sequence// starting from top and// ending at bottom.function largestZigZag( $mat, $n){ // Consider all cells of top // row as starting point $res = 0; for ($j = 0; $j < $n; $j++) $res = max($res, largestZigZagSumRec( $mat, 0, $j, $n)); return $res;} // Driver Code $n = 3; $mat = array(array(4, 2, 1), array(3, 9, 6), array(11, 3, 15)); echo "Largest zigzag sum: " , largestZigZag($mat, $n); // This code is contributed by anuj_67.?> <script> // Javascript program to find the largest sum// zigzag sequence let MAX = 100; // Returns largest sum of a Zigzag // sequence starting from (i, j) // and ending at a bottom cell. function largestZigZagSumRec(mat,i,j,n) { // If we have reached bottom if (i == n-1) return mat[i][j]; // Find the largest sum by considering all // possible next elements in sequence. let zzs = 0; for (let k=0; k<n; k++) if (k != j) zzs = Math.max(zzs, largestZigZagSumRec(mat, i+1, k, n)); return zzs + mat[i][j]; } // Returns largest possible sum of a Zigzag // sequence starting from top and ending // at bottom. function largestZigZag(mat,n) { // Consider all cells of top row as starting // point let res = 0; for (let j=0; j<n; j++) res = Math.max(res, largestZigZagSumRec(mat, 0, j, n)); return res; } // Driver program to test above let n = 3; let mat = [ [4, 2, 1], [3, 9, 6], [11, 3, 15]]; document.write("Largest zigzag sum: " + largestZigZag(mat, n)) // This code is contributed by rag2127 </script> Output: Largest zigzag sum: 28 Overlapping Subproblems Considering the above implementation, for a matrix mat[][] of size 3 x 3, to find the zigzag sum(zzs) for an element mat(i,j), the following recursion tree is formed. Recursion tree for cell (0, 0) zzs(0,0) / \ zzs(1,1) zzs(1,2) / \ / \ zzs(2,0) zzs(2,2) zzs(2,0) zzs(2,1) Recursion tree for cell (0, 1) zzs(0,1) / \ zzs(1,0) zzs(1,2) / \ / \ zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,1) Recursion tree for cell (0, 2) zzs(0,2) / \ zzs(1,0) zzs(1,1) / \ / \ zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,2) We can see that there are many subproblems that are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabulated implementation for the LIS problem. C++ Java Python3 C# Javascript // Memoization based C++ program to find the largest// sum zigzag sequence#include <bits/stdc++.h>using namespace std; const int MAX = 100;int dp[MAX][MAX]; // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell.int largestZigZagSumRec(int mat[][MAX], int i, int j, int n){ if (dp[i][j] != -1) return dp[i][j]; // If we have reached bottom if (i == n-1) return (dp[i][j] = mat[i][j]); // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k=0; k<n; k++) if (k != j) zzs = max(zzs, largestZigZagSumRec(mat, i+1, k, n)); return (dp[i][j] = (zzs + mat[i][j]));} // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom.int largestZigZag(int mat[][MAX], int n){ memset(dp, -1, sizeof(dp)); // Consider all cells of top row as starting point int res = 0; for (int j=0; j<n; j++) res = max(res, largestZigZagSumRec(mat, 0, j, n)); return res;} // Driver program to test aboveint main(){ int n = 3; int mat[][MAX] = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; cout << "Largest zigzag sum: " << largestZigZag(mat, n); return 0;} // Memoization based Java program to find the largest// sum zigzag sequenceclass GFG{ static int MAX = 100;static int [][]dp = new int[MAX][MAX]; // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell.static int largestZigZagSumRec(int mat[][], int i, int j, int n){ if (dp[i][j] != -1) return dp[i][j]; // If we have reached bottom if (i == n - 1) return (dp[i][j] = mat[i][j]); // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k = 0; k < n; k++) if (k != j) zzs = Math.max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); return (dp[i][j] = (zzs + mat[i][j]));} // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom.static int largestZigZag(int mat[][], int n){ for (int i = 0; i < MAX; i++) for (int k = 0; k < MAX; k++) dp[i][k] = -1; // Consider all cells of top row as starting point int res = 0; for (int j = 0; j < n; j++) res = Math.max(res, largestZigZagSumRec(mat, 0, j, n)); return res;} // Driver codepublic static void main(String[] args){ int n = 3; int mat[][] = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; System.out.print("Largest zigzag sum: " + largestZigZag(mat, n));}} // This code is contributed by PrinciRaj1992 # Memoization based Python3 program to find the largest# sum zigzag sequenceMAX = 100; dp = [[0 for i in range(MAX)] for j in range(MAX)] # Returns largest sum of a Zigzag sequence starting# from (i, j) and ending at a bottom cell.def largestZigZagSumRec(mat, i, j, n): if (dp[i][j] != -1): return dp[i][j]; # If we have reached bottom if (i == n - 1): dp[i][j] = mat[i][j]; return (dp[i][j]); # Find the largest sum by considering all # possible next elements in sequence. zzs = 0; for k in range(n): if (k != j): zzs = max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); dp[i][j] = (zzs + mat[i][j]); return (dp[i][j]); # Returns largest possible sum of a Zigzag sequence# starting from top and ending at bottom.def largestZigZag(mat, n): for i in range(MAX): for k in range(MAX): dp[i][k] = -1; # Consider all cells of top row as starting point res = 0; for j in range(n): res = max(res, largestZigZagSumRec(mat, 0, j, n)); return res; # Driver codeif __name__ == '__main__': n = 3; mat = [[4, 2, 1], [3, 9, 6], [11, 3, 15]]; print("Largest zigzag sum: ", largestZigZag(mat, n)); # This code is contributed by Rajput-Ji // Memoization based C# program to find the largest// sum zigzag sequenceusing System; class GFG{ static int MAX = 100;static int [,]dp = new int[MAX, MAX]; // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell.static int largestZigZagSumRec(int [,]mat, int i, int j, int n){ if (dp[i, j] != -1) return dp[i, j]; // If we have reached bottom if (i == n - 1) return (dp[i, j] = mat[i, j]); // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k = 0; k < n; k++) if (k != j) zzs = Math.Max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); return (dp[i, j] = (zzs + mat[i, j]));} // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom.static int largestZigZag(int [,]mat, int n){ for (int i = 0; i < MAX; i++) for (int k = 0; k < MAX; k++) dp[i, k] = -1; // Consider all cells of top row as starting point int res = 0; for (int j = 0; j < n; j++) res = Math.Max(res, largestZigZagSumRec(mat, 0, j, n)); return res;} // Driver codepublic static void Main(String[] args){ int n = 3; int [,]mat = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; Console.Write("Largest zigzag sum: " + largestZigZag(mat, n));}} // This code is contributed by 29AjayKumar <script>// Memoization based Javascript program to find the largest// sum zigzag sequence let MAX = 100; let dp=new Array(MAX); // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell. function largestZigZagSumRec(mat,i,j,n) { if (dp[i][j] != -1) return dp[i][j]; // If we have reached bottom if (i == n - 1) return (dp[i][j] = mat[i][j]); // Find the largest sum by considering all // possible next elements in sequence. let zzs = 0; for (let k = 0; k < n; k++) if (k != j) zzs = Math.max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); return (dp[i][j] = (zzs + mat[i][j])); } // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom. function largestZigZag(mat,n) { for (let i = 0; i < MAX; i++) { dp[i]=new Array(MAX); for (let k = 0; k < MAX; k++) dp[i][k] = -1; } // Consider all cells of top row as starting point let res = 0; for (let j = 0; j < n; j++) res = Math.max(res, largestZigZagSumRec(mat, 0, j, n)); return res; } // Driver code let n = 3; let mat=[[4, 2, 1],[3, 9, 6],[11, 3, 15]]; document.write("Largest zigzag sum: " + largestZigZag(mat, n)); // This code is contributed by avanitrachhadiya2155</script> Output: Largest zigzag sum: 28 vt_m ukasp princiraj1992 29AjayKumar Rajput-Ji rag2127 avanitrachhadiya2155 sumitgumber28 sweetyty Directi Dynamic Programming Matrix Directi Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 Sieve of Eratosthenes Matrix Chain Multiplication | DP-8 Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Dec, 2021" }, { "code": null, "e": 277, "s": 54, "text": "Given a matrix of size n x n, find the sum of the Zigzag sequence with the largest sum. A zigzag sequence starts from the top and ends at the bottom. Two consecutive elements of sequence cannot belong to the same column. " }, { "code": null, "e": 288, "s": 277, "text": "Examples: " }, { "code": null, "e": 533, "s": 288, "text": "Input : mat[][] = 3 1 2\n 4 8 5\n 6 9 7\nOutput : 18\nZigzag sequence is: 3->8->7\nAnother such sequence is 2->4->7\n\nInput : mat[][] = 4 2 1\n 3 9 6\n 11 3 15\nOutput : 28" }, { "code": null, "e": 577, "s": 533, "text": "This problem has an Optimal Substructure. " }, { "code": null, "e": 858, "s": 577, "text": "Maximum Zigzag sum starting from arr[i][j] to a \nbottom cell can be written as :\nzzs(i, j) = arr[i][j] + max(zzs(i+1, k)), \n where k = 0, 1, 2 and k != j\nzzs(i, j) = arr[i][j], if i = n-1 \n\nWe have to find the largest among all as\nResult = zzs(0, j) where 0 <= j < n" }, { "code": null, "e": 862, "s": 858, "text": "C++" }, { "code": null, "e": 867, "s": 862, "text": "Java" }, { "code": null, "e": 876, "s": 867, "text": "Python 3" }, { "code": null, "e": 879, "s": 876, "text": "C#" }, { "code": null, "e": 883, "s": 879, "text": "PHP" }, { "code": null, "e": 894, "s": 883, "text": "Javascript" }, { "code": "// C++ program to find the largest sum zigzag sequence#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell.int largestZigZagSumRec(int mat[][MAX], int i, int j, int n){ // If we have reached bottom if (i == n-1) return mat[i][j]; // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k=0; k<n; k++) if (k != j) zzs = max(zzs, largestZigZagSumRec(mat, i+1, k, n)); return zzs + mat[i][j];} // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom.int largestZigZag(int mat[][MAX], int n){ // Consider all cells of top row as starting point int res = 0; for (int j=0; j<n; j++) res = max(res, largestZigZagSumRec(mat, 0, j, n)); return res;} // Driver program to test aboveint main(){ int n = 3; int mat[][MAX] = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; cout << \"Largest zigzag sum: \" << largestZigZag(mat, n); return 0;}", "e": 2039, "s": 894, "text": null }, { "code": "// Java program to find the largest sum// zigzag sequenceimport java.io.*; class GFG { static int MAX = 100; // Returns largest sum of a Zigzag // sequence starting from (i, j) // and ending at a bottom cell. static int largestZigZagSumRec(int mat[][], int i, int j, int n) { // If we have reached bottom if (i == n-1) return mat[i][j]; // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k=0; k<n; k++) if (k != j) zzs = Math.max(zzs, largestZigZagSumRec(mat, i+1, k, n)); return zzs + mat[i][j]; } // Returns largest possible sum of a Zigzag // sequence starting from top and ending // at bottom. static int largestZigZag(int mat[][], int n) { // Consider all cells of top row as starting // point int res = 0; for (int j=0; j<n; j++) res = Math.max(res, largestZigZagSumRec(mat, 0, j, n)); return res; } // Driver program to test above public static void main (String[] args) { int n = 3; int mat[][] = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15} }; System.out.println( \"Largest zigzag sum: \" + largestZigZag(mat, n)); }} // This code is contributed by anuj_67.", "e": 3545, "s": 2039, "text": null }, { "code": "# Python3 program to find the largest# sum zigzag sequenceMAX = 100 # Returns largest sum of a Zigzag# sequence starting from (i, j) and# ending at a bottom cell.def largestZigZagSumRec( mat, i, j, n): # If we have reached bottom if (i == n-1): return mat[i][j] # Find the largest sum by considering all # possible next elements in sequence. zzs = 0 for k in range(n): if (k != j): zzs = max(zzs, largestZigZagSumRec(mat, i + 1, k, n)) return zzs + mat[i][j] # Returns largest possible sum of a# Zigzag sequence starting from top# and ending at bottom.def largestZigZag(mat, n): # Consider all cells of top row as # starting point res = 0 for j in range(n): res = max(res, largestZigZagSumRec(mat, 0, j, n)) return res # Driver Codeif __name__ == \"__main__\": n = 3 mat = [ [4, 2, 1], [3, 9, 6], [11, 3, 15]] print(\"Largest zigzag sum: \" , largestZigZag(mat, n)) # This code is contributed by ChitraNayal", "e": 4587, "s": 3545, "text": null }, { "code": "// C# program to find the largest sum// zigzag sequenceusing System;class GFG { // static int MAX = 100; // Returns largest sum of a Zigzag // sequence starting from (i, j) // and ending at a bottom cell. static int largestZigZagSumRec(int [,]mat, int i, int j, int n) { // If we have reached bottom if (i == n-1) return mat[i,j]; // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k = 0; k < n; k++) if (k != j) zzs = Math.Max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); return zzs + mat[i,j]; } // Returns largest possible // sum of a Zigzag sequence // starting from top and ending // at bottom. static int largestZigZag(int [,]mat, int n) { // Consider all cells of // top row as starting // point int res = 0; for (int j = 0; j < n; j++) res = Math.Max(res, largestZigZagSumRec(mat, 0, j, n)); return res; } // Driver Code public static void Main () { int n = 3; int [,]mat = {{4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; Console.WriteLine(\"Largest zigzag sum: \" + largestZigZag(mat, n)); }} // This code is contributed by anuj_67.", "e": 6099, "s": 4587, "text": null }, { "code": "<?php// PHP program to find the// largest sum zigzag sequence $MAX = 100; // Returns largest sum of a// Zigzag sequence starting// from (i, j) and ending at// a bottom cell.function largestZigZagSumRec($mat, $i, $j, $n){ // If we have reached bottom if ($i == $n - 1) return $mat[$i][$j]; // Find the largest sum // by considering all // possible next elements // in sequence. $zzs = 0; for ($k = 0; $k < $n; $k++) if ($k != $j) $zzs = max($zzs, largestZigZagSumRec($mat, $i + 1, $k, $n)); return $zzs + $mat[$i][$j];} // Returns largest possible// sum of a Zigzag sequence// starting from top and// ending at bottom.function largestZigZag( $mat, $n){ // Consider all cells of top // row as starting point $res = 0; for ($j = 0; $j < $n; $j++) $res = max($res, largestZigZagSumRec( $mat, 0, $j, $n)); return $res;} // Driver Code $n = 3; $mat = array(array(4, 2, 1), array(3, 9, 6), array(11, 3, 15)); echo \"Largest zigzag sum: \" , largestZigZag($mat, $n); // This code is contributed by anuj_67.?>", "e": 7324, "s": 6099, "text": null }, { "code": "<script> // Javascript program to find the largest sum// zigzag sequence let MAX = 100; // Returns largest sum of a Zigzag // sequence starting from (i, j) // and ending at a bottom cell. function largestZigZagSumRec(mat,i,j,n) { // If we have reached bottom if (i == n-1) return mat[i][j]; // Find the largest sum by considering all // possible next elements in sequence. let zzs = 0; for (let k=0; k<n; k++) if (k != j) zzs = Math.max(zzs, largestZigZagSumRec(mat, i+1, k, n)); return zzs + mat[i][j]; } // Returns largest possible sum of a Zigzag // sequence starting from top and ending // at bottom. function largestZigZag(mat,n) { // Consider all cells of top row as starting // point let res = 0; for (let j=0; j<n; j++) res = Math.max(res, largestZigZagSumRec(mat, 0, j, n)); return res; } // Driver program to test above let n = 3; let mat = [ [4, 2, 1], [3, 9, 6], [11, 3, 15]]; document.write(\"Largest zigzag sum: \" + largestZigZag(mat, n)) // This code is contributed by rag2127 </script>", "e": 8654, "s": 7324, "text": null }, { "code": null, "e": 8662, "s": 8654, "text": "Output:" }, { "code": null, "e": 8685, "s": 8662, "text": "Largest zigzag sum: 28" }, { "code": null, "e": 8877, "s": 8685, "text": "Overlapping Subproblems Considering the above implementation, for a matrix mat[][] of size 3 x 3, to find the zigzag sum(zzs) for an element mat(i,j), the following recursion tree is formed. " }, { "code": null, "e": 9659, "s": 8877, "text": "Recursion tree for cell (0, 0)\n zzs(0,0) \n / \\ \n zzs(1,1) zzs(1,2) \n / \\ / \\ \nzzs(2,0) zzs(2,2) zzs(2,0) zzs(2,1) \n\n\nRecursion tree for cell (0, 1)\n zzs(0,1)\n / \\ \n zzs(1,0) zzs(1,2)\n / \\ / \\ \nzzs(2,1) zzs(2,2) zzs(2,0) zzs(2,1)\n\nRecursion tree for cell (0, 2)\n zzs(0,2)\n / \\ \n zzs(1,0) zzs(1,1) \n / \\ / \\ \n zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,2)" }, { "code": null, "e": 9947, "s": 9659, "text": "We can see that there are many subproblems that are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. Following is a tabulated implementation for the LIS problem. " }, { "code": null, "e": 9951, "s": 9947, "text": "C++" }, { "code": null, "e": 9956, "s": 9951, "text": "Java" }, { "code": null, "e": 9964, "s": 9956, "text": "Python3" }, { "code": null, "e": 9967, "s": 9964, "text": "C#" }, { "code": null, "e": 9978, "s": 9967, "text": "Javascript" }, { "code": "// Memoization based C++ program to find the largest// sum zigzag sequence#include <bits/stdc++.h>using namespace std; const int MAX = 100;int dp[MAX][MAX]; // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell.int largestZigZagSumRec(int mat[][MAX], int i, int j, int n){ if (dp[i][j] != -1) return dp[i][j]; // If we have reached bottom if (i == n-1) return (dp[i][j] = mat[i][j]); // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k=0; k<n; k++) if (k != j) zzs = max(zzs, largestZigZagSumRec(mat, i+1, k, n)); return (dp[i][j] = (zzs + mat[i][j]));} // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom.int largestZigZag(int mat[][MAX], int n){ memset(dp, -1, sizeof(dp)); // Consider all cells of top row as starting point int res = 0; for (int j=0; j<n; j++) res = max(res, largestZigZagSumRec(mat, 0, j, n)); return res;} // Driver program to test aboveint main(){ int n = 3; int mat[][MAX] = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; cout << \"Largest zigzag sum: \" << largestZigZag(mat, n); return 0;}", "e": 11264, "s": 9978, "text": null }, { "code": "// Memoization based Java program to find the largest// sum zigzag sequenceclass GFG{ static int MAX = 100;static int [][]dp = new int[MAX][MAX]; // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell.static int largestZigZagSumRec(int mat[][], int i, int j, int n){ if (dp[i][j] != -1) return dp[i][j]; // If we have reached bottom if (i == n - 1) return (dp[i][j] = mat[i][j]); // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k = 0; k < n; k++) if (k != j) zzs = Math.max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); return (dp[i][j] = (zzs + mat[i][j]));} // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom.static int largestZigZag(int mat[][], int n){ for (int i = 0; i < MAX; i++) for (int k = 0; k < MAX; k++) dp[i][k] = -1; // Consider all cells of top row as starting point int res = 0; for (int j = 0; j < n; j++) res = Math.max(res, largestZigZagSumRec(mat, 0, j, n)); return res;} // Driver codepublic static void main(String[] args){ int n = 3; int mat[][] = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; System.out.print(\"Largest zigzag sum: \" + largestZigZag(mat, n));}} // This code is contributed by PrinciRaj1992", "e": 12828, "s": 11264, "text": null }, { "code": "# Memoization based Python3 program to find the largest# sum zigzag sequenceMAX = 100; dp = [[0 for i in range(MAX)] for j in range(MAX)] # Returns largest sum of a Zigzag sequence starting# from (i, j) and ending at a bottom cell.def largestZigZagSumRec(mat, i, j, n): if (dp[i][j] != -1): return dp[i][j]; # If we have reached bottom if (i == n - 1): dp[i][j] = mat[i][j]; return (dp[i][j]); # Find the largest sum by considering all # possible next elements in sequence. zzs = 0; for k in range(n): if (k != j): zzs = max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); dp[i][j] = (zzs + mat[i][j]); return (dp[i][j]); # Returns largest possible sum of a Zigzag sequence# starting from top and ending at bottom.def largestZigZag(mat, n): for i in range(MAX): for k in range(MAX): dp[i][k] = -1; # Consider all cells of top row as starting point res = 0; for j in range(n): res = max(res, largestZigZagSumRec(mat, 0, j, n)); return res; # Driver codeif __name__ == '__main__': n = 3; mat = [[4, 2, 1], [3, 9, 6], [11, 3, 15]]; print(\"Largest zigzag sum: \", largestZigZag(mat, n)); # This code is contributed by Rajput-Ji", "e": 14087, "s": 12828, "text": null }, { "code": "// Memoization based C# program to find the largest// sum zigzag sequenceusing System; class GFG{ static int MAX = 100;static int [,]dp = new int[MAX, MAX]; // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell.static int largestZigZagSumRec(int [,]mat, int i, int j, int n){ if (dp[i, j] != -1) return dp[i, j]; // If we have reached bottom if (i == n - 1) return (dp[i, j] = mat[i, j]); // Find the largest sum by considering all // possible next elements in sequence. int zzs = 0; for (int k = 0; k < n; k++) if (k != j) zzs = Math.Max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); return (dp[i, j] = (zzs + mat[i, j]));} // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom.static int largestZigZag(int [,]mat, int n){ for (int i = 0; i < MAX; i++) for (int k = 0; k < MAX; k++) dp[i, k] = -1; // Consider all cells of top row as starting point int res = 0; for (int j = 0; j < n; j++) res = Math.Max(res, largestZigZagSumRec(mat, 0, j, n)); return res;} // Driver codepublic static void Main(String[] args){ int n = 3; int [,]mat = { {4, 2, 1}, {3, 9, 6}, {11, 3, 15}}; Console.Write(\"Largest zigzag sum: \" + largestZigZag(mat, n));}} // This code is contributed by 29AjayKumar", "e": 15646, "s": 14087, "text": null }, { "code": "<script>// Memoization based Javascript program to find the largest// sum zigzag sequence let MAX = 100; let dp=new Array(MAX); // Returns largest sum of a Zigzag sequence starting// from (i, j) and ending at a bottom cell. function largestZigZagSumRec(mat,i,j,n) { if (dp[i][j] != -1) return dp[i][j]; // If we have reached bottom if (i == n - 1) return (dp[i][j] = mat[i][j]); // Find the largest sum by considering all // possible next elements in sequence. let zzs = 0; for (let k = 0; k < n; k++) if (k != j) zzs = Math.max(zzs, largestZigZagSumRec(mat, i + 1, k, n)); return (dp[i][j] = (zzs + mat[i][j])); } // Returns largest possible sum of a Zigzag sequence// starting from top and ending at bottom. function largestZigZag(mat,n) { for (let i = 0; i < MAX; i++) { dp[i]=new Array(MAX); for (let k = 0; k < MAX; k++) dp[i][k] = -1; } // Consider all cells of top row as starting point let res = 0; for (let j = 0; j < n; j++) res = Math.max(res, largestZigZagSumRec(mat, 0, j, n)); return res; } // Driver code let n = 3; let mat=[[4, 2, 1],[3, 9, 6],[11, 3, 15]]; document.write(\"Largest zigzag sum: \" + largestZigZag(mat, n)); // This code is contributed by avanitrachhadiya2155</script>", "e": 17182, "s": 15646, "text": null }, { "code": null, "e": 17191, "s": 17182, "text": "Output: " }, { "code": null, "e": 17214, "s": 17191, "text": "Largest zigzag sum: 28" }, { "code": null, "e": 17221, "s": 17216, "text": "vt_m" }, { "code": null, "e": 17227, "s": 17221, "text": "ukasp" }, { "code": null, "e": 17241, "s": 17227, "text": "princiraj1992" }, { "code": null, "e": 17253, "s": 17241, "text": "29AjayKumar" }, { "code": null, "e": 17263, "s": 17253, "text": "Rajput-Ji" }, { "code": null, "e": 17271, "s": 17263, "text": "rag2127" }, { "code": null, "e": 17292, "s": 17271, "text": "avanitrachhadiya2155" }, { "code": null, "e": 17306, "s": 17292, "text": "sumitgumber28" }, { "code": null, "e": 17315, "s": 17306, "text": "sweetyty" }, { "code": null, "e": 17323, "s": 17315, "text": "Directi" }, { "code": null, "e": 17343, "s": 17323, "text": "Dynamic Programming" }, { "code": null, "e": 17350, "s": 17343, "text": "Matrix" }, { "code": null, "e": 17358, "s": 17350, "text": "Directi" }, { "code": null, "e": 17378, "s": 17358, "text": "Dynamic Programming" }, { "code": null, "e": 17385, "s": 17378, "text": "Matrix" }, { "code": null, "e": 17483, "s": 17385, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17521, "s": 17483, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 17554, "s": 17521, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 17573, "s": 17554, "text": "Coin Change | DP-7" }, { "code": null, "e": 17608, "s": 17573, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 17630, "s": 17608, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 17665, "s": 17630, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 17701, "s": 17665, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 17745, "s": 17701, "text": "Program to find largest element in an array" }, { "code": null, "e": 17776, "s": 17745, "text": "Rat in a Maze | Backtracking-2" } ]
jQuery Mouse Events
13 Jun, 2022 This article will explain different mouse events occurring based on mouse positions on a particular HTML element. Mouse Events in jQuery: mouseenter and mouseleave mouseup and mousedown mouseover and mouseout mouseenter and mouseleave: The mouseenter event occurs when the mouse is placed over the HTML element and mouseleave event occurs when the mouse is removed from the element. Javascript <!DOCTYPE html><html> <head> <script src="jquery.js"></script></head> <body bgcolor="cyan"> <p id="key">Original Text</p> <script> $("document").ready(function () { $("#key").mouseenter(enter); $("#key").mouseleave(leave); function enter() { $("#key").text( "mouseenter event has occurred"); } function leave() { $("#key").text( "mouseleave event has occurred"); } }); </script></body> </html> Output: On loading the webpage: MouseEnter and MouseLeave events: MouseUp and MouseDown events:mouseup and mousedown requires a mouse-click to occur.JavascriptJavascript<html> <body bgcolor="#ff00ff"> <p id="key">Original Text</p> </body> <script src = "jquery.js"></script> <script> $("document").ready(function() { $("#key").mouseup(up); $("#key").mousedown(down); function up() { $("#key").text("mouseup event has occurred"); } function down() { $("#key").text("mousedown event has occurred"); } }); </script></html>Output:On landing web page:MouseUp and MouseDown events: mouseup and mousedown requires a mouse-click to occur. Javascript <html> <body bgcolor="#ff00ff"> <p id="key">Original Text</p> </body> <script src = "jquery.js"></script> <script> $("document").ready(function() { $("#key").mouseup(up); $("#key").mousedown(down); function up() { $("#key").text("mouseup event has occurred"); } function down() { $("#key").text("mousedown event has occurred"); } }); </script></html> Output: On landing web page: MouseUp and MouseDown events: Mouseover and Mouseout:These events occur when the mouse is placed over some specific HTML element.JavascriptJavascript<html> <body bgcolor="#87FF2A"> <p id="key">Original Text</p> </body> <script src = "jquery.js"></script> <script> $("document").ready(function() { $("#key").mouseover(over); $("#key").mouseout(out); function over() { $("#key").text("mouseover event has occurred"); } function out() { $("#key").text("mouseout event has occurred"); } }); </script> </html>Output:Onloading web page:MouseOver and MouseOut events: Mouseover and Mouseout: These events occur when the mouse is placed over some specific HTML element. Javascript <html> <body bgcolor="#87FF2A"> <p id="key">Original Text</p> </body> <script src = "jquery.js"></script> <script> $("document").ready(function() { $("#key").mouseover(over); $("#key").mouseout(out); function over() { $("#key").text("mouseover event has occurred"); } function out() { $("#key").text("mouseout event has occurred"); } }); </script> </html> Output: Onloading web page: MouseOver and MouseOut events: MouseOver and MouseOut events: nikhatkhan11 jQuery-Events JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to get the value in an input text box using jQuery ? jQuery | ajax() Method How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | removeAttr() with Examples jQuery | parent() & parents() with Examples 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": "\n13 Jun, 2022" }, { "code": null, "e": 142, "s": 28, "text": "This article will explain different mouse events occurring based on mouse positions on a particular HTML element." }, { "code": null, "e": 166, "s": 142, "text": "Mouse Events in jQuery:" }, { "code": null, "e": 192, "s": 166, "text": "mouseenter and mouseleave" }, { "code": null, "e": 214, "s": 192, "text": "mouseup and mousedown" }, { "code": null, "e": 237, "s": 214, "text": "mouseover and mouseout" }, { "code": null, "e": 411, "s": 237, "text": "mouseenter and mouseleave: The mouseenter event occurs when the mouse is placed over the HTML element and mouseleave event occurs when the mouse is removed from the element." }, { "code": null, "e": 422, "s": 411, "text": "Javascript" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"jquery.js\"></script></head> <body bgcolor=\"cyan\"> <p id=\"key\">Original Text</p> <script> $(\"document\").ready(function () { $(\"#key\").mouseenter(enter); $(\"#key\").mouseleave(leave); function enter() { $(\"#key\").text( \"mouseenter event has occurred\"); } function leave() { $(\"#key\").text( \"mouseleave event has occurred\"); } }); </script></body> </html>", "e": 983, "s": 422, "text": null }, { "code": null, "e": 991, "s": 983, "text": "Output:" }, { "code": null, "e": 1015, "s": 991, "text": "On loading the webpage:" }, { "code": null, "e": 1049, "s": 1015, "text": "MouseEnter and MouseLeave events:" }, { "code": null, "e": 1762, "s": 1049, "text": "MouseUp and MouseDown events:mouseup and mousedown requires a mouse-click to occur.JavascriptJavascript<html> <body bgcolor=\"#ff00ff\"> <p id=\"key\">Original Text</p> </body> <script src = \"jquery.js\"></script> <script> $(\"document\").ready(function() { $(\"#key\").mouseup(up); $(\"#key\").mousedown(down); function up() { $(\"#key\").text(\"mouseup event has occurred\"); } function down() { $(\"#key\").text(\"mousedown event has occurred\"); } }); </script></html>Output:On landing web page:MouseUp and MouseDown events:" }, { "code": null, "e": 1817, "s": 1762, "text": "mouseup and mousedown requires a mouse-click to occur." }, { "code": null, "e": 1828, "s": 1817, "text": "Javascript" }, { "code": "<html> <body bgcolor=\"#ff00ff\"> <p id=\"key\">Original Text</p> </body> <script src = \"jquery.js\"></script> <script> $(\"document\").ready(function() { $(\"#key\").mouseup(up); $(\"#key\").mousedown(down); function up() { $(\"#key\").text(\"mouseup event has occurred\"); } function down() { $(\"#key\").text(\"mousedown event has occurred\"); } }); </script></html>", "e": 2382, "s": 1828, "text": null }, { "code": null, "e": 2390, "s": 2382, "text": "Output:" }, { "code": null, "e": 2411, "s": 2390, "text": "On landing web page:" }, { "code": null, "e": 2441, "s": 2411, "text": "MouseUp and MouseDown events:" }, { "code": null, "e": 3186, "s": 2441, "text": "Mouseover and Mouseout:These events occur when the mouse is placed over some specific HTML element.JavascriptJavascript<html> <body bgcolor=\"#87FF2A\"> <p id=\"key\">Original Text</p> </body> <script src = \"jquery.js\"></script> <script> $(\"document\").ready(function() { $(\"#key\").mouseover(over); $(\"#key\").mouseout(out); function over() { $(\"#key\").text(\"mouseover event has occurred\"); } function out() { $(\"#key\").text(\"mouseout event has occurred\"); } }); </script> </html>Output:Onloading web page:MouseOver and MouseOut events:" }, { "code": null, "e": 3210, "s": 3186, "text": "Mouseover and Mouseout:" }, { "code": null, "e": 3287, "s": 3210, "text": "These events occur when the mouse is placed over some specific HTML element." }, { "code": null, "e": 3298, "s": 3287, "text": "Javascript" }, { "code": "<html> <body bgcolor=\"#87FF2A\"> <p id=\"key\">Original Text</p> </body> <script src = \"jquery.js\"></script> <script> $(\"document\").ready(function() { $(\"#key\").mouseover(over); $(\"#key\").mouseout(out); function over() { $(\"#key\").text(\"mouseover event has occurred\"); } function out() { $(\"#key\").text(\"mouseout event has occurred\"); } }); </script> </html>", "e": 3868, "s": 3298, "text": null }, { "code": null, "e": 3876, "s": 3868, "text": "Output:" }, { "code": null, "e": 3896, "s": 3876, "text": "Onloading web page:" }, { "code": null, "e": 3927, "s": 3896, "text": "MouseOver and MouseOut events:" }, { "code": null, "e": 3958, "s": 3927, "text": "MouseOver and MouseOut events:" }, { "code": null, "e": 3971, "s": 3958, "text": "nikhatkhan11" }, { "code": null, "e": 3985, "s": 3971, "text": "jQuery-Events" }, { "code": null, "e": 3992, "s": 3985, "text": "JQuery" }, { "code": null, "e": 4009, "s": 3992, "text": "Web Technologies" }, { "code": null, "e": 4107, "s": 4009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4164, "s": 4107, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 4187, "s": 4164, "text": "jQuery | ajax() Method" }, { "code": null, "e": 4260, "s": 4187, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 4296, "s": 4260, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 4340, "s": 4296, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 4373, "s": 4340, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4435, "s": 4373, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4496, "s": 4435, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4546, "s": 4496, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to make a HTML link that forces refresh ?
23 Apr, 2021 In this article, we will learn to make an HTML link that forces refresh. HTML <meta> http-equiv attribute with refresh value specified in meta element is used to refresh website pages. Refresh instruction specifies time interval for the page to reload itself, with its value mentioned in content attribute as a positive integer. Positive integer is the number of seconds after which the page will refresh itself. Syntax: <meta http-equiv="refresh" content="5"> HTML <!DOCTYPE html><html> <head> <meta http-equiv="refresh" content="5" /> </head> <body> <h2 style="color: green"> Welcome To GFG </h2> <p> This page automatically refreshes after every 5 seconds </p> </body></html> Output: HTML-Attributes HTML-Questions HTML-Tags 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": "\n23 Apr, 2021" }, { "code": null, "e": 237, "s": 52, "text": "In this article, we will learn to make an HTML link that forces refresh. HTML <meta> http-equiv attribute with refresh value specified in meta element is used to refresh website pages." }, { "code": null, "e": 466, "s": 237, "text": "Refresh instruction specifies time interval for the page to reload itself, with its value mentioned in content attribute as a positive integer. Positive integer is the number of seconds after which the page will refresh itself. " }, { "code": null, "e": 474, "s": 466, "text": "Syntax:" }, { "code": null, "e": 514, "s": 474, "text": "<meta http-equiv=\"refresh\" content=\"5\">" }, { "code": null, "e": 519, "s": 514, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta http-equiv=\"refresh\" content=\"5\" /> </head> <body> <h2 style=\"color: green\"> Welcome To GFG </h2> <p> This page automatically refreshes after every 5 seconds </p> </body></html>", "e": 766, "s": 519, "text": null }, { "code": null, "e": 774, "s": 766, "text": "Output:" }, { "code": null, "e": 790, "s": 774, "text": "HTML-Attributes" }, { "code": null, "e": 805, "s": 790, "text": "HTML-Questions" }, { "code": null, "e": 815, "s": 805, "text": "HTML-Tags" }, { "code": null, "e": 822, "s": 815, "text": "Picked" }, { "code": null, "e": 827, "s": 822, "text": "HTML" }, { "code": null, "e": 844, "s": 827, "text": "Web Technologies" }, { "code": null, "e": 849, "s": 844, "text": "HTML" } ]
Java Math abs() method with Examples
09 Nov, 2021 Absolute value refers to the positive value corresponding to the number passed as in arguments. Now geek you must be wondering what exactly it means so by this it is referred no matter what be it positive or negative number been passed for computation, the computation will occur over the positive corresponding number in both cases. So in order to compute the absolute value for any number we do have a specified method in Java referred to as abs() present inside Math class present inside java.lang package. The java.lang.Math.abs() returns the absolute value of a given argument. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned. Syntax : public static DataType abs(DataType a) Parameters: Int, long, float, or double value whose absolute value is to be determined Returns Type: This method returns the absolute value of the argument. Exceptions Thrown: ArithmeticException Tip: One must be aware of generic return type as follows: If the argument is of double or float type: If the argument is positive zero or negative zero, the result is positive zero.If the argument is infinite, the result is positive infinity.If the argument is NaN, the result is NaN. If the argument is positive zero or negative zero, the result is positive zero. If the argument is infinite, the result is positive infinity. If the argument is NaN, the result is NaN. If the argument is of int or long type: If the argument is equal to the value of Integer.MIN_VALUE or Long.MIN_VALUE, the most negative representable int or long value, the result is that same value, which is negative. Example 1: Java // Java Program to Illustrate Absolute Method// of Math Class // Importing all Math classes// from java.lang packageimport java.lang.Math; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom integer input received from user int n = -7; // Printing value before applying absolute function System.out.println( "Without applying Math.abs() method : " + n); // Applying absolute math function and // storing it in integer variable int value = Math.abs(n); // Printing value after applying absolute function System.out.println( "With applying Math.abs() method : " + value); }} Without applying Math.abs() method : -7 With applying Math.abs() method : 7 Example 2: Java // Java Program to Demonstrate Working of abs() method// of Math class inside java.lang package // Importing Math class// from java.lang packageimport java.lang.Math; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Customly declaring and initializing all // arguments that ans() function takes // Float float a = 123.0f; float b = -34.2323f; // Double double c = -0.0; double d = -999.3456; // Integer int e = -123; int f = -0; // Long long g = -12345678; long h = 98765433; // abs() method taking float type as input System.out.println(Math.abs(a)); System.out.println(Math.abs(b)); // abs() method taking double type as input System.out.println(Math.abs(1.0 / 0)); System.out.println(Math.abs(c)); System.out.println(Math.abs(d)); // abs() method taking int type as input System.out.println(Math.abs(e)); System.out.println(Math.abs(f)); System.out.println(Math.abs(Integer.MIN_VALUE)); // abs() method taking long type as input System.out.println(Math.abs(g)); System.out.println(Math.abs(h)); System.out.println(Math.abs(Long.MIN_VALUE)); }} 123.0 34.2323 Infinity 0.0 999.3456 123 0 -2147483648 12345678 98765433 -9223372036854775808 gopikrishnasa1 solankimayank Java-lang package java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Nov, 2021" }, { "code": null, "e": 565, "s": 53, "text": "Absolute value refers to the positive value corresponding to the number passed as in arguments. Now geek you must be wondering what exactly it means so by this it is referred no matter what be it positive or negative number been passed for computation, the computation will occur over the positive corresponding number in both cases. So in order to compute the absolute value for any number we do have a specified method in Java referred to as abs() present inside Math class present inside java.lang package. " }, { "code": null, "e": 639, "s": 565, "text": "The java.lang.Math.abs() returns the absolute value of a given argument. " }, { "code": null, "e": 698, "s": 639, "text": "If the argument is not negative, the argument is returned." }, { "code": null, "e": 769, "s": 698, "text": "If the argument is negative, the negation of the argument is returned." }, { "code": null, "e": 779, "s": 769, "text": "Syntax : " }, { "code": null, "e": 818, "s": 779, "text": "public static DataType abs(DataType a)" }, { "code": null, "e": 905, "s": 818, "text": "Parameters: Int, long, float, or double value whose absolute value is to be determined" }, { "code": null, "e": 975, "s": 905, "text": "Returns Type: This method returns the absolute value of the argument." }, { "code": null, "e": 1015, "s": 975, "text": "Exceptions Thrown: ArithmeticException " }, { "code": null, "e": 1073, "s": 1015, "text": "Tip: One must be aware of generic return type as follows:" }, { "code": null, "e": 1300, "s": 1073, "text": "If the argument is of double or float type: If the argument is positive zero or negative zero, the result is positive zero.If the argument is infinite, the result is positive infinity.If the argument is NaN, the result is NaN." }, { "code": null, "e": 1380, "s": 1300, "text": "If the argument is positive zero or negative zero, the result is positive zero." }, { "code": null, "e": 1442, "s": 1380, "text": "If the argument is infinite, the result is positive infinity." }, { "code": null, "e": 1485, "s": 1442, "text": "If the argument is NaN, the result is NaN." }, { "code": null, "e": 1704, "s": 1485, "text": "If the argument is of int or long type: If the argument is equal to the value of Integer.MIN_VALUE or Long.MIN_VALUE, the most negative representable int or long value, the result is that same value, which is negative." }, { "code": null, "e": 1715, "s": 1704, "text": "Example 1:" }, { "code": null, "e": 1720, "s": 1715, "text": "Java" }, { "code": "// Java Program to Illustrate Absolute Method// of Math Class // Importing all Math classes// from java.lang packageimport java.lang.Math; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom integer input received from user int n = -7; // Printing value before applying absolute function System.out.println( \"Without applying Math.abs() method : \" + n); // Applying absolute math function and // storing it in integer variable int value = Math.abs(n); // Printing value after applying absolute function System.out.println( \"With applying Math.abs() method : \" + value); }}", "e": 2443, "s": 1720, "text": null }, { "code": null, "e": 2519, "s": 2443, "text": "Without applying Math.abs() method : -7\nWith applying Math.abs() method : 7" }, { "code": null, "e": 2530, "s": 2519, "text": "Example 2:" }, { "code": null, "e": 2535, "s": 2530, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of abs() method// of Math class inside java.lang package // Importing Math class// from java.lang packageimport java.lang.Math; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Customly declaring and initializing all // arguments that ans() function takes // Float float a = 123.0f; float b = -34.2323f; // Double double c = -0.0; double d = -999.3456; // Integer int e = -123; int f = -0; // Long long g = -12345678; long h = 98765433; // abs() method taking float type as input System.out.println(Math.abs(a)); System.out.println(Math.abs(b)); // abs() method taking double type as input System.out.println(Math.abs(1.0 / 0)); System.out.println(Math.abs(c)); System.out.println(Math.abs(d)); // abs() method taking int type as input System.out.println(Math.abs(e)); System.out.println(Math.abs(f)); System.out.println(Math.abs(Integer.MIN_VALUE)); // abs() method taking long type as input System.out.println(Math.abs(g)); System.out.println(Math.abs(h)); System.out.println(Math.abs(Long.MIN_VALUE)); }}", "e": 3848, "s": 2535, "text": null }, { "code": null, "e": 3941, "s": 3848, "text": "123.0\n34.2323\nInfinity\n0.0\n999.3456\n123\n0\n-2147483648\n12345678\n98765433\n-9223372036854775808" }, { "code": null, "e": 3956, "s": 3941, "text": "gopikrishnasa1" }, { "code": null, "e": 3970, "s": 3956, "text": "solankimayank" }, { "code": null, "e": 3988, "s": 3970, "text": "Java-lang package" }, { "code": null, "e": 3998, "s": 3988, "text": "java-math" }, { "code": null, "e": 4003, "s": 3998, "text": "Java" }, { "code": null, "e": 4008, "s": 4003, "text": "Java" }, { "code": null, "e": 4106, "s": 4008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4157, "s": 4106, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4188, "s": 4157, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4207, "s": 4188, "text": "Interfaces in Java" }, { "code": null, "e": 4237, "s": 4207, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4252, "s": 4237, "text": "Stream In Java" }, { "code": null, "e": 4270, "s": 4252, "text": "ArrayList in Java" }, { "code": null, "e": 4290, "s": 4270, "text": "Collections in Java" }, { "code": null, "e": 4314, "s": 4290, "text": "Singleton Class in Java" }, { "code": null, "e": 4346, "s": 4314, "text": "Multidimensional Arrays in Java" } ]
Minimum jumps required to make a group of persons sit together
26 Mar, 2021 Given a string S of length N consisting of ‘x’ and ‘.’. The given string represents a row of seats where ‘x’ and ‘.’ represent occupied and unoccupied seats respectively. The task is to minimize the total number of hops or jumps to make all the occupants sit together i.e., next to each other, without having any vacant seat between them. Note: Since the count of jumps can be very large, print the answer modulo 109 + 7. Examples: Input: S = “. . . . x . . x x . . . x . .”Output: 5Explanation: Below are the required shuffling of occupants:Step 1: Make the person at 5th seat jump 2 places to the 7th seat.Step 2: Make the person at 13th seat jump 3 places to the 10th seat.Therefore, total number of jumps required = 2 + 3 = 5. Input: S = “x x x . . . . . . . . x x x x x x”Output: 24Explanation: Move the occupants from 1st, 2nd and 3rd position to the 9th, 10th, 11th positions respectively. Therefore, the total number of jumps required = (11 – 3) + (10 – 2) + (9 – 3) = 24. Approach: The idea is to use a Greedy Approach to solve this problem. Observe that it is always optimal to shift the elements towards the median element among the persons or the center person among all the persons present. The number of jumps will always be minimum when we shift points to the median. Below are the steps: Initialize a vector position to store the indexes of the persons present. Find the median of the vector position[]. All the other persons will now be made to sit around this person as this will give the minimum number of jumps that are required to be made. Initialize a variable ans that stores the minimum jumps required. Now, traverse the vector position[] and for every index i find the median element and update ans as: ans= ans+ abs(position[i] – medianElement) After the above steps, print the value of ans as the result. 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; long long int MOD = 1e9 + 7; // Function to find the minimum jumps// required to make the whole group// sit adjacentlyint minJumps(string seats){ // Store the indexes vector<int> position; // Stores the count of occupants int count = 0; // Length of the string int len = seats.length(); // Traverse the seats for (int i = 0; i < len; i++) { // If current place is occupied if (seats[i] == 'x') { // Push the current position // in the vector position.push_back(i - count); count++; } } // Base Case: if (count == len || count == 0) return 0; // The index of the median element int med_index = (count - 1) / 2; // The value of the median element int med_val = position[med_index]; int ans = 0; // Traverse the position[] for (int i = 0; i < position.size(); i++) { // Update the ans ans = (ans % MOD + abs(position[i] - med_val) % MOD) % MOD; } // Return the final count return ans % MOD;} // Driver Codeint main(){ // Given arrange of seats string S = "....x..xx...x.."; // Function Call cout << minJumps(S); return 0;} // Java program for the// above approachimport java.util.*;class GFG{ static int MOD = (int)1e9 + 7; // Function to find the minimum// jumps required to make the// whole group sit adjacentlystatic int minJumps(String seats){ // Store the indexes Vector<Integer> position = new Vector<>(); // Stores the count of // occupants int count = 0; // Length of the String int len = seats.length(); // Traverse the seats for (int i = 0; i < len; i++) { // If current place is occupied if (seats.charAt(i) == 'x') { // Push the current position // in the vector position.add(i - count); count++; } } // Base Case: if (count == len || count == 0) return 0; // The index of the median // element int med_index = (count - 1) / 2; // The value of the median // element int med_val = position.get(med_index); int ans = 0; // Traverse the position[] for (int i = 0; i < position.size(); i++) { // Update the ans ans = (ans % MOD + Math.abs(position.get(i) - med_val) % MOD) % MOD; } // Return the final count return ans % MOD;} // Driver Codepublic static void main(String[] args){ // Given arrange of seats String S = "....x..xx...x.."; // Function Call System.out.print(minJumps(S));}} // This code is contributed by gauravrajput1 # Python3 program for the above approachMOD = 10**9 + 7 # Function to find the minimum jumps# required to make the whole group# sit adjacentlydef minJumps(seats): # Store the indexes position = [] # Stores the count of occupants count = 0 # Length of the string lenn = len(seats) # Traverse the seats for i in range(lenn): # If current place is occupied if (seats[i] == 'x'): # Push the current position # in the vector position.append(i - count) count += 1 # Base Case: if (count == lenn or count == 0): return 0 # The index of the median element med_index = (count - 1) // 2 # The value of the median element med_val = position[med_index] ans = 0 # Traverse the position[] for i in range(len(position)): # Update the ans ans = (ans % MOD + abs(position[i] - med_val) % MOD) % MOD # Return the final count return ans % MOD # Driver Codeif __name__ == '__main__': # Given arrange of seats S = "....x..xx...x.." # Function Call print(minJumps(S)) # This code is contributed by mohit kumar 29 // C# program for the// above approachusing System;using System.Collections.Generic;class GFG{ static int MOD = (int)1e9 + 7; // Function to find the minimum// jumps required to make the// whole group sit adjacentlystatic int minJumps(String seats){ // Store the indexes List<int> position = new List<int>(); // Stores the count of // occupants int count = 0; // Length of the String int len = seats.Length; // Traverse the seats for (int i = 0; i < len; i++) { // If current place is // occupied if (seats[i] == 'x') { // Push the current // position in the // vector position.Add(i - count); count++; } } // Base Case: if (count == len || count == 0) return 0; // The index of the median // element int med_index = (count - 1) / 2; // The value of the median // element int med_val = position[med_index]; int ans = 0; // Traverse the position[] for (int i = 0; i < position.Count; i++) { // Update the ans ans = (ans % MOD + Math.Abs(position[i] - med_val) % MOD) % MOD; } // Return the readonly // count return ans % MOD;} // Driver Codepublic static void Main(String[] args){ // Given arrange of seats String S = "....x..xx...x.."; // Function Call Console.Write(minJumps(S));}} // This code is contributed by Amit Katiyar <script> // Javascript program for the above approachlet MOD = 1e9 + 7; // Function to find the minimum jumps// required to make the whole group// sit adjacentlyfunction minJumps(seats){ // Store the indexes let position = []; // Stores the count of occupants let count = 0; // Length of the string let len = seats.length; // Traverse the seats for(let i = 0; i < len; i++) { // If current place is occupied if (seats[i] == 'x') { // Push the current position // in the vector position.push(i - count); count++; } } // Base Case: if (count == len || count == 0) return 0; // The index of the median element let med_index = parseInt((count - 1) / 2, 10); // The value of the median element let med_val = position[med_index]; let ans = 0; // Traverse the position[] for(let i = 0; i < position.length; i++) { // Update the ans ans = (ans % MOD + Math.abs(position[i] - med_val) % MOD) % MOD; } // Return the final count return ans % MOD;} // Driver code // Given arrange of seatslet S = "....x..xx...x.."; // Function Calldocument.write(minJumps(S)); // This code is contributed by suresh07 </script> 5 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 GauravRajput1 amit143katiyar suresh07 interview-preparation median-finding Walmart Greedy Mathematical Searching Strings Walmart Searching Strings Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Mar, 2021" }, { "code": null, "e": 394, "s": 54, "text": "Given a string S of length N consisting of ‘x’ and ‘.’. The given string represents a row of seats where ‘x’ and ‘.’ represent occupied and unoccupied seats respectively. The task is to minimize the total number of hops or jumps to make all the occupants sit together i.e., next to each other, without having any vacant seat between them. " }, { "code": null, "e": 477, "s": 394, "text": "Note: Since the count of jumps can be very large, print the answer modulo 109 + 7." }, { "code": null, "e": 487, "s": 477, "text": "Examples:" }, { "code": null, "e": 786, "s": 487, "text": "Input: S = “. . . . x . . x x . . . x . .”Output: 5Explanation: Below are the required shuffling of occupants:Step 1: Make the person at 5th seat jump 2 places to the 7th seat.Step 2: Make the person at 13th seat jump 3 places to the 10th seat.Therefore, total number of jumps required = 2 + 3 = 5." }, { "code": null, "e": 1036, "s": 786, "text": "Input: S = “x x x . . . . . . . . x x x x x x”Output: 24Explanation: Move the occupants from 1st, 2nd and 3rd position to the 9th, 10th, 11th positions respectively. Therefore, the total number of jumps required = (11 – 3) + (10 – 2) + (9 – 3) = 24." }, { "code": null, "e": 1359, "s": 1036, "text": "Approach: The idea is to use a Greedy Approach to solve this problem. Observe that it is always optimal to shift the elements towards the median element among the persons or the center person among all the persons present. The number of jumps will always be minimum when we shift points to the median. Below are the steps:" }, { "code": null, "e": 1433, "s": 1359, "text": "Initialize a vector position to store the indexes of the persons present." }, { "code": null, "e": 1616, "s": 1433, "text": "Find the median of the vector position[]. All the other persons will now be made to sit around this person as this will give the minimum number of jumps that are required to be made." }, { "code": null, "e": 1682, "s": 1616, "text": "Initialize a variable ans that stores the minimum jumps required." }, { "code": null, "e": 1783, "s": 1682, "text": "Now, traverse the vector position[] and for every index i find the median element and update ans as:" }, { "code": null, "e": 1826, "s": 1783, "text": "ans= ans+ abs(position[i] – medianElement)" }, { "code": null, "e": 1887, "s": 1826, "text": "After the above steps, print the value of ans as the result." }, { "code": null, "e": 1938, "s": 1887, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1942, "s": 1938, "text": "C++" }, { "code": null, "e": 1947, "s": 1942, "text": "Java" }, { "code": null, "e": 1955, "s": 1947, "text": "Python3" }, { "code": null, "e": 1958, "s": 1955, "text": "C#" }, { "code": null, "e": 1969, "s": 1958, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; long long int MOD = 1e9 + 7; // Function to find the minimum jumps// required to make the whole group// sit adjacentlyint minJumps(string seats){ // Store the indexes vector<int> position; // Stores the count of occupants int count = 0; // Length of the string int len = seats.length(); // Traverse the seats for (int i = 0; i < len; i++) { // If current place is occupied if (seats[i] == 'x') { // Push the current position // in the vector position.push_back(i - count); count++; } } // Base Case: if (count == len || count == 0) return 0; // The index of the median element int med_index = (count - 1) / 2; // The value of the median element int med_val = position[med_index]; int ans = 0; // Traverse the position[] for (int i = 0; i < position.size(); i++) { // Update the ans ans = (ans % MOD + abs(position[i] - med_val) % MOD) % MOD; } // Return the final count return ans % MOD;} // Driver Codeint main(){ // Given arrange of seats string S = \"....x..xx...x..\"; // Function Call cout << minJumps(S); return 0;}", "e": 3325, "s": 1969, "text": null }, { "code": "// Java program for the// above approachimport java.util.*;class GFG{ static int MOD = (int)1e9 + 7; // Function to find the minimum// jumps required to make the// whole group sit adjacentlystatic int minJumps(String seats){ // Store the indexes Vector<Integer> position = new Vector<>(); // Stores the count of // occupants int count = 0; // Length of the String int len = seats.length(); // Traverse the seats for (int i = 0; i < len; i++) { // If current place is occupied if (seats.charAt(i) == 'x') { // Push the current position // in the vector position.add(i - count); count++; } } // Base Case: if (count == len || count == 0) return 0; // The index of the median // element int med_index = (count - 1) / 2; // The value of the median // element int med_val = position.get(med_index); int ans = 0; // Traverse the position[] for (int i = 0; i < position.size(); i++) { // Update the ans ans = (ans % MOD + Math.abs(position.get(i) - med_val) % MOD) % MOD; } // Return the final count return ans % MOD;} // Driver Codepublic static void main(String[] args){ // Given arrange of seats String S = \"....x..xx...x..\"; // Function Call System.out.print(minJumps(S));}} // This code is contributed by gauravrajput1", "e": 4684, "s": 3325, "text": null }, { "code": "# Python3 program for the above approachMOD = 10**9 + 7 # Function to find the minimum jumps# required to make the whole group# sit adjacentlydef minJumps(seats): # Store the indexes position = [] # Stores the count of occupants count = 0 # Length of the string lenn = len(seats) # Traverse the seats for i in range(lenn): # If current place is occupied if (seats[i] == 'x'): # Push the current position # in the vector position.append(i - count) count += 1 # Base Case: if (count == lenn or count == 0): return 0 # The index of the median element med_index = (count - 1) // 2 # The value of the median element med_val = position[med_index] ans = 0 # Traverse the position[] for i in range(len(position)): # Update the ans ans = (ans % MOD + abs(position[i] - med_val) % MOD) % MOD # Return the final count return ans % MOD # Driver Codeif __name__ == '__main__': # Given arrange of seats S = \"....x..xx...x..\" # Function Call print(minJumps(S)) # This code is contributed by mohit kumar 29", "e": 5882, "s": 4684, "text": null }, { "code": "// C# program for the// above approachusing System;using System.Collections.Generic;class GFG{ static int MOD = (int)1e9 + 7; // Function to find the minimum// jumps required to make the// whole group sit adjacentlystatic int minJumps(String seats){ // Store the indexes List<int> position = new List<int>(); // Stores the count of // occupants int count = 0; // Length of the String int len = seats.Length; // Traverse the seats for (int i = 0; i < len; i++) { // If current place is // occupied if (seats[i] == 'x') { // Push the current // position in the // vector position.Add(i - count); count++; } } // Base Case: if (count == len || count == 0) return 0; // The index of the median // element int med_index = (count - 1) / 2; // The value of the median // element int med_val = position[med_index]; int ans = 0; // Traverse the position[] for (int i = 0; i < position.Count; i++) { // Update the ans ans = (ans % MOD + Math.Abs(position[i] - med_val) % MOD) % MOD; } // Return the readonly // count return ans % MOD;} // Driver Codepublic static void Main(String[] args){ // Given arrange of seats String S = \"....x..xx...x..\"; // Function Call Console.Write(minJumps(S));}} // This code is contributed by Amit Katiyar", "e": 7240, "s": 5882, "text": null }, { "code": "<script> // Javascript program for the above approachlet MOD = 1e9 + 7; // Function to find the minimum jumps// required to make the whole group// sit adjacentlyfunction minJumps(seats){ // Store the indexes let position = []; // Stores the count of occupants let count = 0; // Length of the string let len = seats.length; // Traverse the seats for(let i = 0; i < len; i++) { // If current place is occupied if (seats[i] == 'x') { // Push the current position // in the vector position.push(i - count); count++; } } // Base Case: if (count == len || count == 0) return 0; // The index of the median element let med_index = parseInt((count - 1) / 2, 10); // The value of the median element let med_val = position[med_index]; let ans = 0; // Traverse the position[] for(let i = 0; i < position.length; i++) { // Update the ans ans = (ans % MOD + Math.abs(position[i] - med_val) % MOD) % MOD; } // Return the final count return ans % MOD;} // Driver code // Given arrange of seatslet S = \"....x..xx...x..\"; // Function Calldocument.write(minJumps(S)); // This code is contributed by suresh07 </script>", "e": 8584, "s": 7240, "text": null }, { "code": null, "e": 8586, "s": 8584, "text": "5" }, { "code": null, "e": 8631, "s": 8588, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 8646, "s": 8631, "text": "mohit kumar 29" }, { "code": null, "e": 8660, "s": 8646, "text": "GauravRajput1" }, { "code": null, "e": 8675, "s": 8660, "text": "amit143katiyar" }, { "code": null, "e": 8684, "s": 8675, "text": "suresh07" }, { "code": null, "e": 8706, "s": 8684, "text": "interview-preparation" }, { "code": null, "e": 8721, "s": 8706, "text": "median-finding" }, { "code": null, "e": 8729, "s": 8721, "text": "Walmart" }, { "code": null, "e": 8736, "s": 8729, "text": "Greedy" }, { "code": null, "e": 8749, "s": 8736, "text": "Mathematical" }, { "code": null, "e": 8759, "s": 8749, "text": "Searching" }, { "code": null, "e": 8767, "s": 8759, "text": "Strings" }, { "code": null, "e": 8775, "s": 8767, "text": "Walmart" }, { "code": null, "e": 8785, "s": 8775, "text": "Searching" }, { "code": null, "e": 8793, "s": 8785, "text": "Strings" }, { "code": null, "e": 8800, "s": 8793, "text": "Greedy" }, { "code": null, "e": 8813, "s": 8800, "text": "Mathematical" } ]
What is Thread cancellation?
Terminating a thread before it has completed is called Thread cancellation. For an example, if multiple threads are concurrently searching through a database and one thread returns the result, the remaining threads might be canceled. Another situation might be occurred when a user presses a button on a web browser that stops a web page from loading any further. Often, using several threads a web page loads — each image is loaded in a separate thread. When the stop button is pressed by a user on the browser, all threads loading the page are canceled. A thread which is to be cancelled is often referred to as the target thread. Cancellation of a target thread may occur in two different cases − Asynchronous cancellation − One thread terminates immediately the target thread. Asynchronous cancellation − One thread terminates immediately the target thread. Deferred cancellation − The target thread checks periodically whether it should terminate, allowing it an opportunity to terminate itself in an orderly fashion. Deferred cancellation − The target thread checks periodically whether it should terminate, allowing it an opportunity to terminate itself in an orderly fashion. The difficulty with cancellation occurs in situations where resources have been allocated to a cancelled thread or where a thread is canceled while in the midst of updating data it is sharing with other threads. This becomes especially troublesome with asynchronous cancellation. Many times, the operating system will reclaim system resources from a cancelled thread but will not reclaim all resources. So, canceling a thread asynchronously may not free a necessary system-wide resource. In contrast, with deferred cancellation, one thread indicates that a target thread is to be canceled, but cancellation occurs only after the target thread has checked a flag to determine whether or not it should be canceled. This check can be performed by the thread at a point at which it can be canceled safely. In Pthreads, thread cancellation is initiated using the pthread cancel() function. The identifier of the target thread is passed as a parameter to the function. The following code illustrates creating—and then canceling— a thread − pthread t tid; /* create the thread */ pthread create(&tid, 0, worker, NULL); ... /* cancel the thread */ pthread cancel(tid); Invoking pthread cancel() indicates only a request to cancel the target thread, however; actual cancellation depends on how the target thread is set up to handle the request. Pthreads supports three cancellation modes. Each mode is defined as a state and a type, as illustrated in the table below. Its cancellation state and type may be set by a thread using an API. As the table illustrates, Pthreads allows threads to disable or enable cancellation. Obviously, a thread cannot be canceled if cancellation is disabled. However, cancellation requests remain pending, so the thread can later enable cancellation and respond to the request. The default cancellation type is deferred cancellation. Here, cancellation occurs only when a thread reaches a cancellation point. One technique for establishing a cancellation point is to invoke the pthread testcancel() function. A function known as a cleanup handler is invoked, if a cancellation request is found to be pending. Any resources a thread may have acquired is allowed by this function to be released before the thread is terminated. The following code illustrates how a thread may respond to a cancellation request using deferred cancellation − while (1){ /* do some work for a while */ /* ... */ /* check if there is a cancellation request */ pthread testcancel(); }
[ { "code": null, "e": 1887, "s": 1187, "text": "Terminating a thread before it has completed is called Thread cancellation. For an example, if multiple threads are concurrently searching through a database and one thread returns the result, the remaining threads might be canceled. Another situation might be occurred when a user presses a button on a web browser that stops a web page from loading any further. Often, using several threads a web page loads — each image is loaded in a separate thread. When the stop button is pressed by a user on the browser, all threads loading the page are canceled. A thread which is to be cancelled is often referred to as the target thread. Cancellation of a target thread may occur in two different cases −" }, { "code": null, "e": 1968, "s": 1887, "text": "Asynchronous cancellation − One thread terminates immediately the target thread." }, { "code": null, "e": 2049, "s": 1968, "text": "Asynchronous cancellation − One thread terminates immediately the target thread." }, { "code": null, "e": 2210, "s": 2049, "text": "Deferred cancellation − The target thread checks periodically whether it should terminate, allowing it an opportunity to terminate itself in an orderly fashion." }, { "code": null, "e": 2371, "s": 2210, "text": "Deferred cancellation − The target thread checks periodically whether it should terminate, allowing it an opportunity to terminate itself in an orderly fashion." }, { "code": null, "e": 3405, "s": 2371, "text": "The difficulty with cancellation occurs in situations where resources have been allocated to a cancelled thread or where a thread is canceled while in the midst of updating data it is sharing with other threads. This becomes especially troublesome with asynchronous cancellation. Many times, the operating system will reclaim system resources from a cancelled thread but will not reclaim all resources. So, canceling a thread asynchronously may not free a necessary system-wide resource. In contrast, with deferred cancellation, one thread indicates that a target thread is to be canceled, but cancellation occurs only after the target thread has checked a flag to determine whether or not it should be canceled. This check can be performed by the thread at a point at which it can be canceled safely. In Pthreads, thread cancellation is initiated using the pthread cancel() function. The identifier of the target thread is passed as a parameter to the function. The following code illustrates creating—and then canceling— a thread −" }, { "code": null, "e": 3532, "s": 3405, "text": "pthread t tid;\n/* create the thread */\npthread create(&tid, 0, worker, NULL);\n...\n/* cancel the thread */\npthread cancel(tid);" }, { "code": null, "e": 3899, "s": 3532, "text": "Invoking pthread cancel() indicates only a request to cancel the target thread, however; actual cancellation depends on how the target thread is set up to handle the request. Pthreads supports three cancellation modes. Each mode is defined as a state and a type, as illustrated in the table below. Its cancellation state and type may be set by a thread using an API." }, { "code": null, "e": 4731, "s": 3899, "text": "As the table illustrates, Pthreads allows threads to disable or enable cancellation. Obviously, a thread cannot be canceled if cancellation is disabled. However, cancellation requests remain pending, so the thread can later enable cancellation and respond to the request. The default cancellation type is deferred cancellation. Here, cancellation occurs only when a thread reaches a cancellation point. One technique for establishing a cancellation point is to invoke the pthread testcancel() function. A function known as a cleanup handler is invoked, if a cancellation request is found to be pending. Any resources a thread may have acquired is allowed by this function to be released before the thread is terminated. The following code illustrates how a thread may respond to a cancellation request using deferred cancellation −" }, { "code": null, "e": 4866, "s": 4731, "text": "while (1){\n /* do some work for a while */\n /* ... */\n /* check if there is a cancellation request */\n pthread testcancel();\n}" } ]
Polynomial Division using Linked List
18 Jan, 2022 Given two polynomials P1 and P2 in the form of a singly linked list respectively, the task is to print the quotient and remainder expressions in the form of a singly linked list, obtained by dividing the polynomials P1 by P2. Note: Assume the polynomial is expressed as the higher power of x to the lower power of x(i.e., 0). Examples: Input: P1 = 5 -> 4 -> 2, P2 = 5 -> 5Output:Quotient = 1 -> 0.2Remainder = 3 Input: P1 = 3 -> 5 -> 2, P2 = 2 -> 1Output:Quotient = 1.5 -> 1.75Remainder = 0.25 Approach: Follow the steps below to solve the problem: Create two singly linked lists, quotient, and the remainder, where each node will consist of the coefficient of power of x, and a pointer to the next node. While the degree of the remainder is less than the degree of the divisor do the following:Subtract the power of the leading term of the dividend by that of the divisor and store in power.Divide the coefficient of the leading term of the dividend by the divisor and store in the variable coefficient.Create a new node N from the terms formed in step 1 and step 2 and insert N in the quotient list.Multiply N with the divisor and subtract the dividend from the obtained result. Subtract the power of the leading term of the dividend by that of the divisor and store in power. Divide the coefficient of the leading term of the dividend by the divisor and store in the variable coefficient. Create a new node N from the terms formed in step 1 and step 2 and insert N in the quotient list. Multiply N with the divisor and subtract the dividend from the obtained result. After the above steps, print the quotient and the remainder list. Below is the implementation of the above approach: C++ // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Node structure containing power and// coefficient of variablestruct Node { float coeff; int pow; struct Node* next;}; // Function to create new nodevoid create_node(float x, int y, struct Node** temp){ struct Node *r, *z; z = *temp; // If temp is NULL if (z == NULL) { r = (struct Node*)malloc( sizeof(struct Node)); // Update coefficient and // power in the LL z r->coeff = x; r->pow = y; *temp = r; r->next = (struct Node*)malloc( sizeof(struct Node)); r = r->next; r->next = NULL; } // Otherwise else { r->coeff = x; r->pow = y; r->next = (struct Node*)malloc( sizeof(struct Node)); r = r->next; r->next = NULL; }} // Function to create a LL that stores// the value of the quotient while// performing polynomial divisionvoid store_quotient(float mul_c, int diff, struct Node* quo){ // Till quo is non-empty while (quo->next != NULL) { quo = quo->next; } // Update powers and coefficient quo->pow = diff; quo->coeff = mul_c; quo->next = (struct Node*)malloc( sizeof(struct Node)); quo = quo->next; quo->next = NULL;} // Function to create a new polynomial// whenever subtraction is performed// in polynomial divisionvoid formNewPoly(int diff, float mul_c, struct Node* poly){ // Till poly is not empty while (poly->next != NULL) { poly->pow += diff; poly->coeff *= mul_c; poly = poly->next; }} // Function to copy one polynomial// into another linkedlistvoid copyList(struct Node* r, struct Node** copy){ // Copy the values of r in the // polynomial copy while (r != NULL) { struct Node* z = (struct Node*)malloc( sizeof(struct Node)); // Store coefficient and power z->coeff = r->coeff; z->pow = r->pow; z->next = NULL; struct Node* dis = *copy; if (dis == NULL) { *copy = z; } else { while (dis->next != NULL) { dis = dis->next; } dis->next = z; } r = r->next; }} // Function to subtract two polynomialvoid polySub(struct Node* poly1, struct Node* poly2, struct Node* poly){ // Compute until poly1 and poly2 is empty while (poly1->next && poly2->next) { // If power of 1st polynomial // > 2nd, then store 1st as // it is and move its pointer if (poly1->pow > poly2->pow) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; poly->next = (struct Node*)malloc( sizeof(struct Node)); poly = poly->next; poly->next = NULL; } // If power of 2nd polynomial > // 1st then store 2nd as it is // and move its pointer else if (poly1->pow < poly2->pow) { poly->pow = poly2->pow; poly->coeff = -1 * poly2->coeff; poly2 = poly2->next; poly->next = (struct Node*)malloc( sizeof(struct Node)); poly = poly->next; poly->next = NULL; } // If power of both polynomial // is same then subtract their // coefficients else { if ((poly1->coeff - poly2->coeff) != 0) { poly->pow = poly1->pow; poly->coeff = (poly1->coeff - poly2->coeff); poly->next = (struct Node*)malloc( sizeof(struct Node)); poly = poly->next; poly->next = NULL; } // Update the pointers // poly1 and poly2 poly1 = poly1->next; poly2 = poly2->next; } } // Add the remaining value of polynomials while (poly1->next || poly2->next) { // If poly1 exists if (poly1->next) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; } // If poly2 exists if (poly2->next) { poly->pow = poly2->pow; poly->coeff = -1 * poly2->coeff; poly2 = poly2->next; } // Add the new node to poly poly->next = (struct Node*)malloc( sizeof(struct Node)); poly = poly->next; poly->next = NULL; }} // Function to display linked listvoid show(struct Node* node){ int count = 0; while (node->next != NULL && node->coeff != 0) { // If count is non-zero, then // print the positive value if (count == 0) cout << node->coeff; // Otherwise else cout << abs(node->coeff); count++; // Print polynomial power if (node->pow != 0) cout << "x^" << node->pow; node = node->next; if (node->next != NULL) // If coeff of next term // > 0 then next sign will // be positive else negative if (node->coeff > 0) cout << " + "; else cout << " - "; } cout << "\n";} // Function to divide two polynomialsvoid divide_poly(struct Node* poly1, struct Node* poly2){ // Initialize Remainder and Quotient struct Node *rem = NULL, *quo = NULL; quo = (struct Node*)malloc( sizeof(struct Node)); quo->next = NULL; struct Node *q = NULL, *r = NULL; // Copy poly1, i.e., dividend to q copyList(poly1, &q); // Copy poly, i.e., divisor to r copyList(poly2, &r); // Perform polynomial subtraction till // highest power of q > highest power of divisor while (q != NULL && (q->pow >= poly2->pow)) { // difference of power int diff = q->pow - poly2->pow; float mul_c = (q->coeff / poly2->coeff); // Stores the quotient node store_quotient(mul_c, diff, quo); struct Node* q2 = NULL; // Copy one LL in another LL copyList(r, &q2); // formNewPoly forms next value // of q after performing the // polynomial subtraction formNewPoly(diff, mul_c, q2); struct Node* store = NULL; store = (struct Node*)malloc( sizeof(struct Node)); // Perform polynomial subtraction polySub(q, q2, store); // Now change value of q to the // subtracted value i.e., store q = store; free(q2); } // Print the quotient cout << "Quotient: "; show(quo); // Print the remainder cout << "Remainder: "; rem = q; show(rem);} // Driver Codeint main(){ struct Node* poly1 = NULL; struct Node *poly2 = NULL, *poly = NULL; // Create 1st Polynomial (Dividend): // 5x^2 + 4x^1 + 2 create_node(5.0, 2, &poly1); create_node(4.0, 1, &poly1); create_node(2.0, 0, &poly1); // Create 2nd Polynomial (Divisor): // 5x^1 + 5 create_node(5.0, 1, &poly2); create_node(5.0, 0, &poly2); // Function Call divide_poly(poly1, poly2); return 0;} Quotient: 1x^1 - 0.2 Remainder: 3 Time Complexity: O(M + N)Auxiliary Space: O(M + N) simmytarika5 surindertarika1234 germanshephered48 Linked Lists Linked-List-Polynomial maths-polynomial Linked List Mathematical Linked List Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Circular Singly Linked List | Insertion Add two numbers represented by linked lists | Set 2 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
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2022" }, { "code": null, "e": 255, "s": 28, "text": "Given two polynomials P1 and P2 in the form of a singly linked list respectively, the task is to print the quotient and remainder expressions in the form of a singly linked list, obtained by dividing the polynomials P1 by P2. " }, { "code": null, "e": 355, "s": 255, "text": "Note: Assume the polynomial is expressed as the higher power of x to the lower power of x(i.e., 0)." }, { "code": null, "e": 365, "s": 355, "text": "Examples:" }, { "code": null, "e": 441, "s": 365, "text": "Input: P1 = 5 -> 4 -> 2, P2 = 5 -> 5Output:Quotient = 1 -> 0.2Remainder = 3" }, { "code": null, "e": 523, "s": 441, "text": "Input: P1 = 3 -> 5 -> 2, P2 = 2 -> 1Output:Quotient = 1.5 -> 1.75Remainder = 0.25" }, { "code": null, "e": 578, "s": 523, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 734, "s": 578, "text": "Create two singly linked lists, quotient, and the remainder, where each node will consist of the coefficient of power of x, and a pointer to the next node." }, { "code": null, "e": 1210, "s": 734, "text": "While the degree of the remainder is less than the degree of the divisor do the following:Subtract the power of the leading term of the dividend by that of the divisor and store in power.Divide the coefficient of the leading term of the dividend by the divisor and store in the variable coefficient.Create a new node N from the terms formed in step 1 and step 2 and insert N in the quotient list.Multiply N with the divisor and subtract the dividend from the obtained result." }, { "code": null, "e": 1308, "s": 1210, "text": "Subtract the power of the leading term of the dividend by that of the divisor and store in power." }, { "code": null, "e": 1421, "s": 1308, "text": "Divide the coefficient of the leading term of the dividend by the divisor and store in the variable coefficient." }, { "code": null, "e": 1519, "s": 1421, "text": "Create a new node N from the terms formed in step 1 and step 2 and insert N in the quotient list." }, { "code": null, "e": 1599, "s": 1519, "text": "Multiply N with the divisor and subtract the dividend from the obtained result." }, { "code": null, "e": 1665, "s": 1599, "text": "After the above steps, print the quotient and the remainder list." }, { "code": null, "e": 1716, "s": 1665, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1720, "s": 1716, "text": "C++" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Node structure containing power and// coefficient of variablestruct Node { float coeff; int pow; struct Node* next;}; // Function to create new nodevoid create_node(float x, int y, struct Node** temp){ struct Node *r, *z; z = *temp; // If temp is NULL if (z == NULL) { r = (struct Node*)malloc( sizeof(struct Node)); // Update coefficient and // power in the LL z r->coeff = x; r->pow = y; *temp = r; r->next = (struct Node*)malloc( sizeof(struct Node)); r = r->next; r->next = NULL; } // Otherwise else { r->coeff = x; r->pow = y; r->next = (struct Node*)malloc( sizeof(struct Node)); r = r->next; r->next = NULL; }} // Function to create a LL that stores// the value of the quotient while// performing polynomial divisionvoid store_quotient(float mul_c, int diff, struct Node* quo){ // Till quo is non-empty while (quo->next != NULL) { quo = quo->next; } // Update powers and coefficient quo->pow = diff; quo->coeff = mul_c; quo->next = (struct Node*)malloc( sizeof(struct Node)); quo = quo->next; quo->next = NULL;} // Function to create a new polynomial// whenever subtraction is performed// in polynomial divisionvoid formNewPoly(int diff, float mul_c, struct Node* poly){ // Till poly is not empty while (poly->next != NULL) { poly->pow += diff; poly->coeff *= mul_c; poly = poly->next; }} // Function to copy one polynomial// into another linkedlistvoid copyList(struct Node* r, struct Node** copy){ // Copy the values of r in the // polynomial copy while (r != NULL) { struct Node* z = (struct Node*)malloc( sizeof(struct Node)); // Store coefficient and power z->coeff = r->coeff; z->pow = r->pow; z->next = NULL; struct Node* dis = *copy; if (dis == NULL) { *copy = z; } else { while (dis->next != NULL) { dis = dis->next; } dis->next = z; } r = r->next; }} // Function to subtract two polynomialvoid polySub(struct Node* poly1, struct Node* poly2, struct Node* poly){ // Compute until poly1 and poly2 is empty while (poly1->next && poly2->next) { // If power of 1st polynomial // > 2nd, then store 1st as // it is and move its pointer if (poly1->pow > poly2->pow) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; poly->next = (struct Node*)malloc( sizeof(struct Node)); poly = poly->next; poly->next = NULL; } // If power of 2nd polynomial > // 1st then store 2nd as it is // and move its pointer else if (poly1->pow < poly2->pow) { poly->pow = poly2->pow; poly->coeff = -1 * poly2->coeff; poly2 = poly2->next; poly->next = (struct Node*)malloc( sizeof(struct Node)); poly = poly->next; poly->next = NULL; } // If power of both polynomial // is same then subtract their // coefficients else { if ((poly1->coeff - poly2->coeff) != 0) { poly->pow = poly1->pow; poly->coeff = (poly1->coeff - poly2->coeff); poly->next = (struct Node*)malloc( sizeof(struct Node)); poly = poly->next; poly->next = NULL; } // Update the pointers // poly1 and poly2 poly1 = poly1->next; poly2 = poly2->next; } } // Add the remaining value of polynomials while (poly1->next || poly2->next) { // If poly1 exists if (poly1->next) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; } // If poly2 exists if (poly2->next) { poly->pow = poly2->pow; poly->coeff = -1 * poly2->coeff; poly2 = poly2->next; } // Add the new node to poly poly->next = (struct Node*)malloc( sizeof(struct Node)); poly = poly->next; poly->next = NULL; }} // Function to display linked listvoid show(struct Node* node){ int count = 0; while (node->next != NULL && node->coeff != 0) { // If count is non-zero, then // print the positive value if (count == 0) cout << node->coeff; // Otherwise else cout << abs(node->coeff); count++; // Print polynomial power if (node->pow != 0) cout << \"x^\" << node->pow; node = node->next; if (node->next != NULL) // If coeff of next term // > 0 then next sign will // be positive else negative if (node->coeff > 0) cout << \" + \"; else cout << \" - \"; } cout << \"\\n\";} // Function to divide two polynomialsvoid divide_poly(struct Node* poly1, struct Node* poly2){ // Initialize Remainder and Quotient struct Node *rem = NULL, *quo = NULL; quo = (struct Node*)malloc( sizeof(struct Node)); quo->next = NULL; struct Node *q = NULL, *r = NULL; // Copy poly1, i.e., dividend to q copyList(poly1, &q); // Copy poly, i.e., divisor to r copyList(poly2, &r); // Perform polynomial subtraction till // highest power of q > highest power of divisor while (q != NULL && (q->pow >= poly2->pow)) { // difference of power int diff = q->pow - poly2->pow; float mul_c = (q->coeff / poly2->coeff); // Stores the quotient node store_quotient(mul_c, diff, quo); struct Node* q2 = NULL; // Copy one LL in another LL copyList(r, &q2); // formNewPoly forms next value // of q after performing the // polynomial subtraction formNewPoly(diff, mul_c, q2); struct Node* store = NULL; store = (struct Node*)malloc( sizeof(struct Node)); // Perform polynomial subtraction polySub(q, q2, store); // Now change value of q to the // subtracted value i.e., store q = store; free(q2); } // Print the quotient cout << \"Quotient: \"; show(quo); // Print the remainder cout << \"Remainder: \"; rem = q; show(rem);} // Driver Codeint main(){ struct Node* poly1 = NULL; struct Node *poly2 = NULL, *poly = NULL; // Create 1st Polynomial (Dividend): // 5x^2 + 4x^1 + 2 create_node(5.0, 2, &poly1); create_node(4.0, 1, &poly1); create_node(2.0, 0, &poly1); // Create 2nd Polynomial (Divisor): // 5x^1 + 5 create_node(5.0, 1, &poly2); create_node(5.0, 0, &poly2); // Function Call divide_poly(poly1, poly2); return 0;}", "e": 9110, "s": 1720, "text": null }, { "code": null, "e": 9144, "s": 9110, "text": "Quotient: 1x^1 - 0.2\nRemainder: 3" }, { "code": null, "e": 9197, "s": 9146, "text": "Time Complexity: O(M + N)Auxiliary Space: O(M + N)" }, { "code": null, "e": 9210, "s": 9197, "text": "simmytarika5" }, { "code": null, "e": 9229, "s": 9210, "text": "surindertarika1234" }, { "code": null, "e": 9247, "s": 9229, "text": "germanshephered48" }, { "code": null, "e": 9260, "s": 9247, "text": "Linked Lists" }, { "code": null, "e": 9283, "s": 9260, "text": "Linked-List-Polynomial" }, { "code": null, "e": 9300, "s": 9283, "text": "maths-polynomial" }, { "code": null, "e": 9312, "s": 9300, "text": "Linked List" }, { "code": null, "e": 9325, "s": 9312, "text": "Mathematical" }, { "code": null, "e": 9337, "s": 9325, "text": "Linked List" }, { "code": null, "e": 9350, "s": 9337, "text": "Mathematical" }, { "code": null, "e": 9448, "s": 9350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9480, "s": 9448, "text": "Introduction to Data Structures" }, { "code": null, "e": 9544, "s": 9480, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 9565, "s": 9544, "text": "Types of Linked List" }, { "code": null, "e": 9605, "s": 9565, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 9657, "s": 9605, "text": "Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 9687, "s": 9657, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9730, "s": 9687, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9790, "s": 9730, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9805, "s": 9790, "text": "C++ Data Types" } ]
MySQL - USE Statement
The USE statement of MySQL helps you to select/use a database. You can also change to another database with this statement. Once you set the current database it will be same until the end of the session unless you change the it. Following is the syntax of the MySQL USE statement − USE db_name Following example demonstrates the usage of the MySQL USE statement − mysql> use test; mysql> CREATE TABLE SAMPLE(NAME VARCHAR(10)); Query OK, 0 rows affected (1.65 sec) mysql> INSERT INTO SAMPLE VALUES ('Raj'); Query OK, 1 row affected (0.19 sec) mysql> use sample Database changed mysql> SELECT * FROM SAMPLE; ERROR 1146 (42S02): Table 'sample.sample' doesn't exist Here we are creating a new database and changing the current database to it. mysql> CREATE DATABASE myDatabase; Query OK, 1 row affected (0.23 sec) mysql> use myDatabase
[ { "code": null, "e": 2670, "s": 2441, "text": "The USE statement of MySQL helps you to select/use a database. You can also change to another database with this statement. Once you set the current database it will be same until the end of the session unless you change the it." }, { "code": null, "e": 2723, "s": 2670, "text": "Following is the syntax of the MySQL USE statement −" }, { "code": null, "e": 2736, "s": 2723, "text": "USE db_name\n" }, { "code": null, "e": 2806, "s": 2736, "text": "Following example demonstrates the usage of the MySQL USE statement −" }, { "code": null, "e": 3104, "s": 2806, "text": "mysql> use test;\nmysql> CREATE TABLE SAMPLE(NAME VARCHAR(10));\nQuery OK, 0 rows affected (1.65 sec)\nmysql> INSERT INTO SAMPLE VALUES ('Raj');\nQuery OK, 1 row affected (0.19 sec)\nmysql> use sample\nDatabase changed\nmysql> SELECT * FROM SAMPLE;\nERROR 1146 (42S02): Table 'sample.sample' doesn't exist" }, { "code": null, "e": 3181, "s": 3104, "text": "Here we are creating a new database and changing the current database to it." } ]
C program to read a range of bytes from file and print it to console
28 Jun, 2021 Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console. Functions Used: fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.fgetc(): Reading the characters from the file.fclose(): For closing a file. fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”. fgetc(): Reading the characters from the file. fclose(): For closing a file. Approach: Initialize a file pointer, say File *fptr1. Initialize an array to store the bytes that will be read from the file. Open the file using the function fopen() as fptr1 = fopen(argv[1], “r”). Iterate a loop until the given file is read and stored, the characters are scanned in the variable, say C using the fgetc() function. Store each character C extracted in the above step, to a new string S and print that string using the printf() function. After completing the above steps, close the file using the fclose() function. Below is the implementation of the above approach: C // C program to read particular bytes// from the existing file#include <stdio.h>#include <stdlib.h> // Maximum range of bytes#define MAX 1000 // Filename given as the command// line argumentint main(int argc, char* argv[]){ // Pointer to the file to be // read from FILE* fptr1; char c; // Stores the bytes to read char str[MAX]; int i = 0, j, from, to; // If the file exists and has // read permission fptr1 = fopen(argv[1], "r"); if (fptr1 == NULL) { return 1; } // Input from the user range of // bytes inclusive of from and to printf("Read bytes from: "); scanf("%d", &from); printf("Read bytes upto: "); scanf("%d", &to); // Loop to read required byte // of file for (i = 0, j = 0; i <= to && c != EOF; i++) { // Skip the bytes not required if (i >= from) { str[j] = c; j++; } // Get the characters c = fgetc(fptr1); } // Print the bytes as string printf("%s", str); // Close the file fclose(fptr1); return 0;} Output: C-File Handling File Handling C Language C Programs File Handling 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 Strings in C Arrow operator -> in C/C++ with Examples Basics of File Handling in C UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 174, "s": 52, "text": "Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console." }, { "code": null, "e": 190, "s": 174, "text": "Functions Used:" }, { "code": null, "e": 365, "s": 190, "text": "fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.fgetc(): Reading the characters from the file.fclose(): For closing a file." }, { "code": null, "e": 465, "s": 365, "text": "fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”." }, { "code": null, "e": 512, "s": 465, "text": "fgetc(): Reading the characters from the file." }, { "code": null, "e": 542, "s": 512, "text": "fclose(): For closing a file." }, { "code": null, "e": 552, "s": 542, "text": "Approach:" }, { "code": null, "e": 596, "s": 552, "text": "Initialize a file pointer, say File *fptr1." }, { "code": null, "e": 668, "s": 596, "text": "Initialize an array to store the bytes that will be read from the file." }, { "code": null, "e": 741, "s": 668, "text": "Open the file using the function fopen() as fptr1 = fopen(argv[1], “r”)." }, { "code": null, "e": 875, "s": 741, "text": "Iterate a loop until the given file is read and stored, the characters are scanned in the variable, say C using the fgetc() function." }, { "code": null, "e": 996, "s": 875, "text": "Store each character C extracted in the above step, to a new string S and print that string using the printf() function." }, { "code": null, "e": 1074, "s": 996, "text": "After completing the above steps, close the file using the fclose() function." }, { "code": null, "e": 1125, "s": 1074, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1127, "s": 1125, "text": "C" }, { "code": "// C program to read particular bytes// from the existing file#include <stdio.h>#include <stdlib.h> // Maximum range of bytes#define MAX 1000 // Filename given as the command// line argumentint main(int argc, char* argv[]){ // Pointer to the file to be // read from FILE* fptr1; char c; // Stores the bytes to read char str[MAX]; int i = 0, j, from, to; // If the file exists and has // read permission fptr1 = fopen(argv[1], \"r\"); if (fptr1 == NULL) { return 1; } // Input from the user range of // bytes inclusive of from and to printf(\"Read bytes from: \"); scanf(\"%d\", &from); printf(\"Read bytes upto: \"); scanf(\"%d\", &to); // Loop to read required byte // of file for (i = 0, j = 0; i <= to && c != EOF; i++) { // Skip the bytes not required if (i >= from) { str[j] = c; j++; } // Get the characters c = fgetc(fptr1); } // Print the bytes as string printf(\"%s\", str); // Close the file fclose(fptr1); return 0;}", "e": 2240, "s": 1127, "text": null }, { "code": null, "e": 2248, "s": 2240, "text": "Output:" }, { "code": null, "e": 2264, "s": 2248, "text": "C-File Handling" }, { "code": null, "e": 2278, "s": 2264, "text": "File Handling" }, { "code": null, "e": 2289, "s": 2278, "text": "C Language" }, { "code": null, "e": 2300, "s": 2289, "text": "C Programs" }, { "code": null, "e": 2314, "s": 2300, "text": "File Handling" }, { "code": null, "e": 2412, "s": 2314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2460, "s": 2412, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2505, "s": 2460, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 2526, "s": 2505, "text": "Operators in C / C++" }, { "code": null, "e": 2552, "s": 2526, "text": "Exception Handling in C++" }, { "code": null, "e": 2590, "s": 2552, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2603, "s": 2590, "text": "Strings in C" }, { "code": null, "e": 2644, "s": 2603, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 2673, "s": 2644, "text": "Basics of File Handling in C" }, { "code": null, "e": 2711, "s": 2673, "text": "UDP Server-Client implementation in C" } ]
Youtube video downloader using Django
25 May, 2022 In this article, we will see how to make a YouTube video downloader tool in Django. We will be using pytube module for that. Prerequisite: pytube: It is python’s lightweight and dependency-free module, which is used to download YouTube Videos. Django: It is python’s framework to make web-applications. Here, we will be using Django as a backend along with pytube module to create this tool. We can install pytube module by typing the below command in the terminal. pip install pytube So, let’s dive in to make our YouTube video downloader tool. First, we will create an HTML design (form) where the user can come and enter the URL of a video which he/she wants to download. We will use Django’s POST method to get that URL (because it is secure). We also need to use csrf token if we are using the POST method. Syntax for csrf token is: {% csrf_token %} HTML <!DOCTYPE html><html><body> <h1>Youtube video downloader</h1> <form action="" method="post"> {% csrf_token %} <label for="link">Enter URL:</label> <input type="text" id="link" name="link"><br><br> <input type="submit" value="Submit"></form> </body></html> Now, it’s time to create a function that receives the video link and downloads that video. You need to import function YouTube from module pytube in views.py file. Now we can define the function to download video. views.py Python3 # importing all the required modulesfrom django.shortcuts import render, redirectfrom pytube import * # defining functiondef youtube(request): # checking whether request.method is post or not if request.method == 'POST': # getting link from frontend link = request.POST['link'] video = YouTube(link) # setting video resolution stream = video.streams.get_lowest_resolution() # downloads video stream.download() # returning HTML page return render(request, 'youtube.html') return render(request, 'youtube.html') Now, we have to define the URL (path) for this function inside urls.py. Python3 from django.contrib import adminfrom django.urls import pathfrom . import views urlpatterns = [ path('admin/', admin.site.urls), path('youtube', views.youtube, name='youtube'),] That is it for the coding part, now you can run the project by python manage.py runserver and head over to http://localhost:8000/youtube to see the output. Output: When you click on submit a video will be downloaded in your Django project’s directory. akshaysingh98088 Django-Projects Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n25 May, 2022" }, { "code": null, "e": 178, "s": 53, "text": "In this article, we will see how to make a YouTube video downloader tool in Django. We will be using pytube module for that." }, { "code": null, "e": 192, "s": 178, "text": "Prerequisite:" }, { "code": null, "e": 297, "s": 192, "text": "pytube: It is python’s lightweight and dependency-free module, which is used to download YouTube Videos." }, { "code": null, "e": 356, "s": 297, "text": "Django: It is python’s framework to make web-applications." }, { "code": null, "e": 519, "s": 356, "text": "Here, we will be using Django as a backend along with pytube module to create this tool. We can install pytube module by typing the below command in the terminal." }, { "code": null, "e": 538, "s": 519, "text": "pip install pytube" }, { "code": null, "e": 599, "s": 538, "text": "So, let’s dive in to make our YouTube video downloader tool." }, { "code": null, "e": 892, "s": 599, "text": "First, we will create an HTML design (form) where the user can come and enter the URL of a video which he/she wants to download. We will use Django’s POST method to get that URL (because it is secure). We also need to use csrf token if we are using the POST method. Syntax for csrf token is: " }, { "code": null, "e": 909, "s": 892, "text": "{% csrf_token %}" }, { "code": null, "e": 914, "s": 909, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h1>Youtube video downloader</h1> <form action=\"\" method=\"post\"> {% csrf_token %} <label for=\"link\">Enter URL:</label> <input type=\"text\" id=\"link\" name=\"link\"><br><br> <input type=\"submit\" value=\"Submit\"></form> </body></html>", "e": 1181, "s": 914, "text": null }, { "code": null, "e": 1400, "s": 1185, "text": "Now, it’s time to create a function that receives the video link and downloads that video. You need to import function YouTube from module pytube in views.py file. Now we can define the function to download video." }, { "code": null, "e": 1411, "s": 1402, "text": "views.py" }, { "code": null, "e": 1421, "s": 1413, "text": "Python3" }, { "code": "# importing all the required modulesfrom django.shortcuts import render, redirectfrom pytube import * # defining functiondef youtube(request): # checking whether request.method is post or not if request.method == 'POST': # getting link from frontend link = request.POST['link'] video = YouTube(link) # setting video resolution stream = video.streams.get_lowest_resolution() # downloads video stream.download() # returning HTML page return render(request, 'youtube.html') return render(request, 'youtube.html')", "e": 2030, "s": 1421, "text": null }, { "code": null, "e": 2106, "s": 2034, "text": "Now, we have to define the URL (path) for this function inside urls.py." }, { "code": null, "e": 2116, "s": 2108, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import pathfrom . import views urlpatterns = [ path('admin/', admin.site.urls), path('youtube', views.youtube, name='youtube'),]", "e": 2301, "s": 2116, "text": null }, { "code": null, "e": 2461, "s": 2305, "text": "That is it for the coding part, now you can run the project by python manage.py runserver and head over to http://localhost:8000/youtube to see the output." }, { "code": null, "e": 2471, "s": 2463, "text": "Output:" }, { "code": null, "e": 2563, "s": 2475, "text": "When you click on submit a video will be downloaded in your Django project’s directory." }, { "code": null, "e": 2584, "s": 2567, "text": "akshaysingh98088" }, { "code": null, "e": 2600, "s": 2584, "text": "Django-Projects" }, { "code": null, "e": 2614, "s": 2600, "text": "Python Django" }, { "code": null, "e": 2621, "s": 2614, "text": "Python" } ]
Minimum Cost using Dijkstra by Modifying Cost of an Edge
30 Jun, 2022 Given an undirected weighted graph of N nodes and M edges in the form of a tuple lets say {X, Y, Z} such that there is an edge with cost Z between X and Y. We are supposed to compute the minimum cost of traversal from node 1 to N. However, we can perform one operation before the traversal such that we can reduce the cost of any edge lets say, C to C / 2 (integer division). Examples: Input: N = 3, M = 4, Edges = {{1, 2, 3}, {2, 3, 1}, {1, 3, 7}, {2, 1, 5}} Output: 2 Explanation: Minimum Cost from source node 1 to destination node N is = 3/2 + 1 = 1 + 1 = 2.Input: N = 3, M = 3, Edges = {{2, 3, 1}, {1, 3, 7}, {2, 1, 5}} Output: 2 Explanation: Minimum Cost from source node 1 to destination node N is = 7/2 = 3. Approach: The idea is to consider every edge to be modified and try to minimize the overall cost by reducing its cost. The main idea is to break the path between node 1 to N into the path from 1 to any vertex u i.e., path(1 to u) and from node N to any vertex v i.e., path(n to v) for all u and v such that u to v forms an edge. We can easily compute the distance from any node lets say, source to all other nodes in the graph by applying single source shortest path algorithm, Dijkstra Algorithm. In this problem we would be applying the Dijkstra Algorithm twice by choosing sources as 1 and N separately and storing the cost to reach each node in the array dist_from_source[] and dist_from_dest[] respectively. After we have computed these two arrays we can easily compute the cost associated after modifying each edge. Lets consider an edge u to v and let the cost associated with it be c. If we try to modify this edge we can compute the minimum cost from 1 to N as dist_from_source[u] + dist_from_dest[v] + c / 2. Doing this for all the edges and minimizing it we can get the minimum cost to travel from source 1 to destination N. Perform a Dijkstra Algorithm to find the single source shortest path for all the vertex from node 1 and store it in an array as dist_from_source[].Perform a Dijkstra Algorithm to find the single source shortest path for all the vertex from node N and store it in an array as dist_from_dest[].Declare a variable minCost and assign it to a very large number initially.Traverse all the given edges [u, v, c] and reduce it like formula discussed above and update the minCost variable as: Perform a Dijkstra Algorithm to find the single source shortest path for all the vertex from node 1 and store it in an array as dist_from_source[]. Perform a Dijkstra Algorithm to find the single source shortest path for all the vertex from node N and store it in an array as dist_from_dest[]. Declare a variable minCost and assign it to a very large number initially. Traverse all the given edges [u, v, c] and reduce it like formula discussed above and update the minCost variable as: minCost = min(minCost, dist_from_source[u] + c/2 + dist_from_dest[v]) where, c is the cost of current edge, dist_from_source[u] is cost of path from node 1 to u dist_from_source[v] is cost of path from node N to v Repeat this process for all the edges and correspondingly update the minCost variable. Print the value of minCost after the above step. Repeat this process for all the edges and correspondingly update the minCost variable. Print the value of minCost after the above step. Below is the implementation of the above approach: C++14 Javascript Python3 // C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define INF 1e9 // Function for Dijkstra Algorithm to// find single source shortest pathvoid dijkstra(int source, int n, vector<pair<int, int> > adj[], vector<int>& dist){ // Resize dist[] to N and assign // any large value to it dist.resize(n, INF); // Initialise distance of source // node as 0 dist = 0; // Using min-heap priority_queue // for sorting wrt edges_cost priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; // Push the current dist // and source to pq pq.push({ dist, source }); // Until priority queue is empty while (!pq.empty()) { // Store the cost of linked // node to edges int u = pq.top().second; // int d = pq.top().first; // Pop the top node pq.pop(); // Iterate over edges for (auto& edge : adj[u]) { // Find the starting and // ending vertex of edge int v = edge.first; int w = edge.second; // Update the distance of // node v to minimum of // dist[u] + w if it is // minimum if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; pq.push({ dist[v], v }); } } }} // Function to find the minimum cost// between node 1 to node nvoid minCostPath( vector<pair<int, pair<int, int> > >& edges, int n, int M){ // To create Adjacency List vector<pair<int, int> > adj[100005]; // Iterate over edges for (int i = 0; i < M; i++) { // Get source, destination and // edges of edges[i] int x = edges[i].first; int y = edges[i].second.first; int z = edges[i].second.second; // Create Adjacency List adj[x].push_back({ y, z }); adj[y].push_back({ x, z }); } // To store the cost from node 1 // and node N vector<int> dist_from_source; vector<int> dist_from_dest; // Find the cost of travel between // source(1) to any vertex dijkstra(1, n + 1, adj, dist_from_source); // Find the cost of travel between // destination(n) to any vertex dijkstra(n, n + 1, adj, dist_from_dest); // Initialise the minimum cost int min_cost = dist_from_source[n]; // Traverse the edges for (auto& it : edges) { // Get the edges int u = it.first; int v = it.second.first; int c = it.second.second; // Find the current cost from // node 1 to u and node u to v // and node v to N with only // current edge cost reduced // to half int cur_cost = dist_from_source[u] + c / 2 + dist_from_dest[v]; // Update the min_cost min_cost = min(min_cost, cur_cost); } // Print the minimum cost cout << min_cost << '\n';} // Driver Codeint main(){ // Give Nodes and Edges int N = 3; int M = 3; // Given Edges with cost vector<pair<int, pair<int, int> > > edges; edges.push_back({ 2, { 3, 1 } }); edges.push_back({ 1, { 3, 7 } }); edges.push_back({ 2, { 1, 5 } }); // Function Call minCostPath(edges, N, M); return 0;} <script> // Javascript program for the above approach // Function for Dijkstra Algorithm to// find single source shortest pathfunction dijkstra(source, n, adj, dist){ // Resize dist[] to N and assign // any large value to it dist = Array(n).fill(1000000000); // Initialise distance of source // node as 0 dist = 0; // Using min-heap priority_queue // for sorting wrt edges_cost var pq = []; // Push the current dist // and source to pq pq.push([dist, source]); // Until priority queue is empty while (pq.length!=0) { // Store the cost of linked // node to edges var u = pq[pq.length-1][1]; // int d = pq.top()[0]; // Pop the top node pq.pop(); // Iterate over edges for (var edge of adj[u]) { // Find the starting and // ending vertex of edge var v = edge[0]; var w = edge[1]; // Update the distance of // node v to minimum of // dist[u] + w if it is // minimum if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; pq.push([dist[v], v ]); } } pq.sort(); } return dist;} // Function to find the minimum cost// between node 1 to node nfunction minCostPath(edges, n, M){ // To create Adjacency List var adj = Array.from(Array(100005), ()=>new Array()); // Iterate over edges for (var i = 0; i < M; i++) { // Get source, destination and // edges of edges[i] var x = edges[i][0]; var y = edges[i][1][0]; var z = edges[i][1][1]; // Create Adjacency List adj[x].push([y, z ]); adj[y].push([x, z ]); } // To store the cost from node 1 // and node N var dist_from_source = []; var dist_from_dest = []; // Find the cost of travel between // source(1) to any vertex dist_from_source = dijkstra(1, n + 1, adj, dist_from_source); // Find the cost of travel between // destination(n) to any vertex dist_from_dest = dijkstra(n, n + 1, adj, dist_from_dest); // Initialise the minimum cost var min_cost = dist_from_source[n]; // Traverse the edges for (var it of edges) { // Get the edges var u = it[0]; var v = it[1][0]; var c = it[1][1]; // Find the current cost from // node 1 to u and node u to v // and node v to N with only // current edge cost reduced // to half var cur_cost = dist_from_source[u] + parseInt(c / 2) + dist_from_dest[v]; // Update the min_cost min_cost = Math.min(min_cost, cur_cost); } // Print the minimum cost document.write( min_cost + "<br>");} // Driver Code// Give Nodes and Edgesvar N = 3;var M = 3; // Given Edges with costvar edges = [];edges.push([2, [3, 1]]);edges.push([1, [3, 7 ]]);edges.push([2, [1, 5 ]]); // Function CallminCostPath(edges, N, M); // This code is contributed by noob2000. </script> # Python3 program for the above approachimport heapq as hq INF = 1e9 # Function for Dijkstra Algorithm to# find single source shortest pathdef dijkstra(source, n, adj, dist): # Initialise distance of source # node as 0 dist = 0 # Using min-heap priority_queue # for sorting wrt edges_cost pq = [] # Push the current dist # and source to pq hq.heappush(pq, (dist, source)) # Until priority queue is empty while pq: # Store the cost of linked # node to edges d, u = hq.heappop(pq) # Iterate over edges for v,w in adj[u]: # Update the distance of # node v to minimum of # dist[u] + w if it is # minimum if dist[u] + w < dist[v]: dist[v] = dist[u] + w hq.heappush(pq, (dist[v], v)) # Function to find the minimum cost# between node 1 to node ndef minCostPath(edges, n, M): # To create Adjacency List adj = [[]for _ in range(100005)] # Iterate over edges for i in range(M): # Get source, destination and # edges of edges[i] x = edges[i][0] y = edges[i][1][0] z = edges[i][1][1] # Create Adjacency List adj[x].append((y, z)) adj[y].append((x, z)) # To store the cost from node 1 # and node N dist_from_source = [INF] * (n+1) dist_from_dest = [INF] * (n+1) # Find the cost of travel between # source(1) to any vertex dijkstra(1, n + 1, adj, dist_from_source) # Find the cost of travel between # destination(n) to any vertex dijkstra(n, n + 1, adj, dist_from_dest) # Initialise the minimum cost min_cost = dist_from_source[n] # Traverse the edges for it in edges: # Get the edges u = it[0] v = it[1][0] c = it[1][1] # Find the current cost from # node 1 to u and node u to v # and node v to N with only # current edge cost reduced # to half cur_cost = dist_from_source[u] + c // 2 + dist_from_dest[v] # Update the min_cost min_cost = min(min_cost, cur_cost) # Print minimum cost print(min_cost) # Driver Codeif __name__ == "__main__": # Give Nodes and Edges N = 3 M = 3 # Given Edges with cost edges = [] edges.append((2, (3, 1))) edges.append((1, (3, 7))) edges.append((2, (1, 5))) # Function Call minCostPath(edges, N, M) 3 Time Complexity: O(M log N), where N is the number of nodes and M is the number of edges. Auxiliary Space: O(N), where N is the number of nodes. noob2000 amartyaghoshgfg khushboogoyal499 sameeralamynwa Algorithms-Graph Traversals cpp-priority-queue Data Structures-Graph Dijkstra priority-queue Algorithms Graph Queue Graph Queue priority-queue Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Graph and its representations Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 429, "s": 52, "text": "Given an undirected weighted graph of N nodes and M edges in the form of a tuple lets say {X, Y, Z} such that there is an edge with cost Z between X and Y. We are supposed to compute the minimum cost of traversal from node 1 to N. However, we can perform one operation before the traversal such that we can reduce the cost of any edge lets say, C to C / 2 (integer division). " }, { "code": null, "e": 440, "s": 429, "text": "Examples: " }, { "code": null, "e": 539, "s": 440, "text": "Input: N = 3, M = 4, Edges = {{1, 2, 3}, {2, 3, 1}, {1, 3, 7}, {2, 1, 5}} Output: 2 Explanation: " }, { "code": null, "e": 706, "s": 539, "text": "Minimum Cost from source node 1 to destination node N is = 3/2 + 1 = 1 + 1 = 2.Input: N = 3, M = 3, Edges = {{2, 3, 1}, {1, 3, 7}, {2, 1, 5}} Output: 2 Explanation: " }, { "code": null, "e": 776, "s": 706, "text": "Minimum Cost from source node 1 to destination node N is = 7/2 = 3. " }, { "code": null, "e": 1914, "s": 776, "text": "Approach: The idea is to consider every edge to be modified and try to minimize the overall cost by reducing its cost. The main idea is to break the path between node 1 to N into the path from 1 to any vertex u i.e., path(1 to u) and from node N to any vertex v i.e., path(n to v) for all u and v such that u to v forms an edge. We can easily compute the distance from any node lets say, source to all other nodes in the graph by applying single source shortest path algorithm, Dijkstra Algorithm. In this problem we would be applying the Dijkstra Algorithm twice by choosing sources as 1 and N separately and storing the cost to reach each node in the array dist_from_source[] and dist_from_dest[] respectively. After we have computed these two arrays we can easily compute the cost associated after modifying each edge. Lets consider an edge u to v and let the cost associated with it be c. If we try to modify this edge we can compute the minimum cost from 1 to N as dist_from_source[u] + dist_from_dest[v] + c / 2. Doing this for all the edges and minimizing it we can get the minimum cost to travel from source 1 to destination N. " }, { "code": null, "e": 2399, "s": 1914, "text": "Perform a Dijkstra Algorithm to find the single source shortest path for all the vertex from node 1 and store it in an array as dist_from_source[].Perform a Dijkstra Algorithm to find the single source shortest path for all the vertex from node N and store it in an array as dist_from_dest[].Declare a variable minCost and assign it to a very large number initially.Traverse all the given edges [u, v, c] and reduce it like formula discussed above and update the minCost variable as: " }, { "code": null, "e": 2547, "s": 2399, "text": "Perform a Dijkstra Algorithm to find the single source shortest path for all the vertex from node 1 and store it in an array as dist_from_source[]." }, { "code": null, "e": 2693, "s": 2547, "text": "Perform a Dijkstra Algorithm to find the single source shortest path for all the vertex from node N and store it in an array as dist_from_dest[]." }, { "code": null, "e": 2768, "s": 2693, "text": "Declare a variable minCost and assign it to a very large number initially." }, { "code": null, "e": 2887, "s": 2768, "text": "Traverse all the given edges [u, v, c] and reduce it like formula discussed above and update the minCost variable as: " }, { "code": null, "e": 3103, "s": 2887, "text": "minCost = min(minCost, dist_from_source[u] + c/2 + dist_from_dest[v]) where, c is the cost of current edge, dist_from_source[u] is cost of path from node 1 to u dist_from_source[v] is cost of path from node N to v " }, { "code": null, "e": 3239, "s": 3103, "text": "Repeat this process for all the edges and correspondingly update the minCost variable. Print the value of minCost after the above step." }, { "code": null, "e": 3327, "s": 3239, "text": "Repeat this process for all the edges and correspondingly update the minCost variable. " }, { "code": null, "e": 3376, "s": 3327, "text": "Print the value of minCost after the above step." }, { "code": null, "e": 3428, "s": 3376, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 3434, "s": 3428, "text": "C++14" }, { "code": null, "e": 3445, "s": 3434, "text": "Javascript" }, { "code": null, "e": 3453, "s": 3445, "text": "Python3" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define INF 1e9 // Function for Dijkstra Algorithm to// find single source shortest pathvoid dijkstra(int source, int n, vector<pair<int, int> > adj[], vector<int>& dist){ // Resize dist[] to N and assign // any large value to it dist.resize(n, INF); // Initialise distance of source // node as 0 dist = 0; // Using min-heap priority_queue // for sorting wrt edges_cost priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; // Push the current dist // and source to pq pq.push({ dist, source }); // Until priority queue is empty while (!pq.empty()) { // Store the cost of linked // node to edges int u = pq.top().second; // int d = pq.top().first; // Pop the top node pq.pop(); // Iterate over edges for (auto& edge : adj[u]) { // Find the starting and // ending vertex of edge int v = edge.first; int w = edge.second; // Update the distance of // node v to minimum of // dist[u] + w if it is // minimum if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; pq.push({ dist[v], v }); } } }} // Function to find the minimum cost// between node 1 to node nvoid minCostPath( vector<pair<int, pair<int, int> > >& edges, int n, int M){ // To create Adjacency List vector<pair<int, int> > adj[100005]; // Iterate over edges for (int i = 0; i < M; i++) { // Get source, destination and // edges of edges[i] int x = edges[i].first; int y = edges[i].second.first; int z = edges[i].second.second; // Create Adjacency List adj[x].push_back({ y, z }); adj[y].push_back({ x, z }); } // To store the cost from node 1 // and node N vector<int> dist_from_source; vector<int> dist_from_dest; // Find the cost of travel between // source(1) to any vertex dijkstra(1, n + 1, adj, dist_from_source); // Find the cost of travel between // destination(n) to any vertex dijkstra(n, n + 1, adj, dist_from_dest); // Initialise the minimum cost int min_cost = dist_from_source[n]; // Traverse the edges for (auto& it : edges) { // Get the edges int u = it.first; int v = it.second.first; int c = it.second.second; // Find the current cost from // node 1 to u and node u to v // and node v to N with only // current edge cost reduced // to half int cur_cost = dist_from_source[u] + c / 2 + dist_from_dest[v]; // Update the min_cost min_cost = min(min_cost, cur_cost); } // Print the minimum cost cout << min_cost << '\\n';} // Driver Codeint main(){ // Give Nodes and Edges int N = 3; int M = 3; // Given Edges with cost vector<pair<int, pair<int, int> > > edges; edges.push_back({ 2, { 3, 1 } }); edges.push_back({ 1, { 3, 7 } }); edges.push_back({ 2, { 1, 5 } }); // Function Call minCostPath(edges, N, M); return 0;}", "e": 6890, "s": 3453, "text": null }, { "code": "<script> // Javascript program for the above approach // Function for Dijkstra Algorithm to// find single source shortest pathfunction dijkstra(source, n, adj, dist){ // Resize dist[] to N and assign // any large value to it dist = Array(n).fill(1000000000); // Initialise distance of source // node as 0 dist = 0; // Using min-heap priority_queue // for sorting wrt edges_cost var pq = []; // Push the current dist // and source to pq pq.push([dist, source]); // Until priority queue is empty while (pq.length!=0) { // Store the cost of linked // node to edges var u = pq[pq.length-1][1]; // int d = pq.top()[0]; // Pop the top node pq.pop(); // Iterate over edges for (var edge of adj[u]) { // Find the starting and // ending vertex of edge var v = edge[0]; var w = edge[1]; // Update the distance of // node v to minimum of // dist[u] + w if it is // minimum if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; pq.push([dist[v], v ]); } } pq.sort(); } return dist;} // Function to find the minimum cost// between node 1 to node nfunction minCostPath(edges, n, M){ // To create Adjacency List var adj = Array.from(Array(100005), ()=>new Array()); // Iterate over edges for (var i = 0; i < M; i++) { // Get source, destination and // edges of edges[i] var x = edges[i][0]; var y = edges[i][1][0]; var z = edges[i][1][1]; // Create Adjacency List adj[x].push([y, z ]); adj[y].push([x, z ]); } // To store the cost from node 1 // and node N var dist_from_source = []; var dist_from_dest = []; // Find the cost of travel between // source(1) to any vertex dist_from_source = dijkstra(1, n + 1, adj, dist_from_source); // Find the cost of travel between // destination(n) to any vertex dist_from_dest = dijkstra(n, n + 1, adj, dist_from_dest); // Initialise the minimum cost var min_cost = dist_from_source[n]; // Traverse the edges for (var it of edges) { // Get the edges var u = it[0]; var v = it[1][0]; var c = it[1][1]; // Find the current cost from // node 1 to u and node u to v // and node v to N with only // current edge cost reduced // to half var cur_cost = dist_from_source[u] + parseInt(c / 2) + dist_from_dest[v]; // Update the min_cost min_cost = Math.min(min_cost, cur_cost); } // Print the minimum cost document.write( min_cost + \"<br>\");} // Driver Code// Give Nodes and Edgesvar N = 3;var M = 3; // Given Edges with costvar edges = [];edges.push([2, [3, 1]]);edges.push([1, [3, 7 ]]);edges.push([2, [1, 5 ]]); // Function CallminCostPath(edges, N, M); // This code is contributed by noob2000. </script>", "e": 9941, "s": 6890, "text": null }, { "code": "# Python3 program for the above approachimport heapq as hq INF = 1e9 # Function for Dijkstra Algorithm to# find single source shortest pathdef dijkstra(source, n, adj, dist): # Initialise distance of source # node as 0 dist = 0 # Using min-heap priority_queue # for sorting wrt edges_cost pq = [] # Push the current dist # and source to pq hq.heappush(pq, (dist, source)) # Until priority queue is empty while pq: # Store the cost of linked # node to edges d, u = hq.heappop(pq) # Iterate over edges for v,w in adj[u]: # Update the distance of # node v to minimum of # dist[u] + w if it is # minimum if dist[u] + w < dist[v]: dist[v] = dist[u] + w hq.heappush(pq, (dist[v], v)) # Function to find the minimum cost# between node 1 to node ndef minCostPath(edges, n, M): # To create Adjacency List adj = [[]for _ in range(100005)] # Iterate over edges for i in range(M): # Get source, destination and # edges of edges[i] x = edges[i][0] y = edges[i][1][0] z = edges[i][1][1] # Create Adjacency List adj[x].append((y, z)) adj[y].append((x, z)) # To store the cost from node 1 # and node N dist_from_source = [INF] * (n+1) dist_from_dest = [INF] * (n+1) # Find the cost of travel between # source(1) to any vertex dijkstra(1, n + 1, adj, dist_from_source) # Find the cost of travel between # destination(n) to any vertex dijkstra(n, n + 1, adj, dist_from_dest) # Initialise the minimum cost min_cost = dist_from_source[n] # Traverse the edges for it in edges: # Get the edges u = it[0] v = it[1][0] c = it[1][1] # Find the current cost from # node 1 to u and node u to v # and node v to N with only # current edge cost reduced # to half cur_cost = dist_from_source[u] + c // 2 + dist_from_dest[v] # Update the min_cost min_cost = min(min_cost, cur_cost) # Print minimum cost print(min_cost) # Driver Codeif __name__ == \"__main__\": # Give Nodes and Edges N = 3 M = 3 # Given Edges with cost edges = [] edges.append((2, (3, 1))) edges.append((1, (3, 7))) edges.append((2, (1, 5))) # Function Call minCostPath(edges, N, M)", "e": 12364, "s": 9941, "text": null }, { "code": null, "e": 12366, "s": 12364, "text": "3" }, { "code": null, "e": 12514, "s": 12368, "text": "Time Complexity: O(M log N), where N is the number of nodes and M is the number of edges. Auxiliary Space: O(N), where N is the number of nodes. " }, { "code": null, "e": 12523, "s": 12514, "text": "noob2000" }, { "code": null, "e": 12539, "s": 12523, "text": "amartyaghoshgfg" }, { "code": null, "e": 12556, "s": 12539, "text": "khushboogoyal499" }, { "code": null, "e": 12571, "s": 12556, "text": "sameeralamynwa" }, { "code": null, "e": 12599, "s": 12571, "text": "Algorithms-Graph Traversals" }, { "code": null, "e": 12618, "s": 12599, "text": "cpp-priority-queue" }, { "code": null, "e": 12640, "s": 12618, "text": "Data Structures-Graph" }, { "code": null, "e": 12649, "s": 12640, "text": "Dijkstra" }, { "code": null, "e": 12664, "s": 12649, "text": "priority-queue" }, { "code": null, "e": 12675, "s": 12664, "text": "Algorithms" }, { "code": null, "e": 12681, "s": 12675, "text": "Graph" }, { "code": null, "e": 12687, "s": 12681, "text": "Queue" }, { "code": null, "e": 12693, "s": 12687, "text": "Graph" }, { "code": null, "e": 12699, "s": 12693, "text": "Queue" }, { "code": null, "e": 12714, "s": 12699, "text": "priority-queue" }, { "code": null, "e": 12725, "s": 12714, "text": "Algorithms" }, { "code": null, "e": 12823, "s": 12725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12861, "s": 12823, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 12929, "s": 12861, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 12956, "s": 12929, "text": "How to Start Learning DSA?" }, { "code": null, "e": 12999, "s": 12956, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 13066, "s": 12999, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 13106, "s": 13066, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 13144, "s": 13106, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 13195, "s": 13144, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 13225, "s": 13195, "text": "Graph and its representations" } ]
Find Perimeter of a triangle
22 Jun, 2022 Given side (a, b, c) of a triangle, we have to find the perimeter of a triangle. Perimeter : Perimeter of a triangle is the sum of the length of side of a triangle. where a, b, c are length of side of a triangle.Perimeter of a triangle can simply be evaluated using following formula : Examples : Input : a = 2.0, b = 3.0, c = 5.0 Output : 10.0 Input : a = 5.0, b = 6.0, c = 7.0 Output : 18.0 C++ C Java Python C# PHP Javascript // A simple C++ program to find the perimeter// of triangle#include <iostream>using namespace std; // Function to find perimeterfloat findPerimeter(float a, float b, float c){ // Formula for finding a perimeter // of triangle return (a + b + c);} // Driver Codeint main(){ float a = 2.0, b = 3.0, c = 5.0; cout << findPerimeter(a, b, c); return 0;} // This code is contributed by Ankita saini // A simple C program to find the perimeter// of triangle#include <stdio.h> // Function to find perimeterfloat findPerimeter(float a, float b, float c){ // Formula for finding a perimeter of triangle return (a + b + c);} // Driver Codeint main(){ float a = 2.0, b = 3.0, c = 5.0; printf("%f", findPerimeter(a, b, c)); return 0;} // Java program to find perimeter// of triangleclass Test { static float findPerimeter(float a, float b, float c) { // Formula for Perimeter of triangle return (a + b + c); } // Driver method public static void main(String[] args) { float a = 2.0, b = 3.0, c = 5.0; System.out.println(findPerimeter(a, b, c)); }} # Python Program to find a perimeter# of triangle # Function to find perimeterdef findPerimeter(a, b, c): # Calculate the perimeter return (a + b + c) # Driver Code a = 2.0b = 3.0c = 5.0print(findPerimeter(a, b, c)) // C# program to find perimeter// of triangleusing System; class Test { static float findPerimeter(float a, float b, float c) { // Formula for Perimeter of triangle return (a + b + c); } // Driver method public static void Main() { float a = 2.0f, b = 3.0f, c = 5.0f; Console.WriteLine(findPerimeter(a, b, c)); }} //This code is contributed by vt_m. <?php// A simple PHP program// to find the perimeter// of triangle // Function to find perimeterfunction findPerimeter($a, $b, $c){ // Formula for finding a // perimeter of triangle return ($a + $b + $c);} // Driver Code $a = 2.0; $b = 3.0; $c = 5.0; echo findPerimeter($a, $b, $c); // This code is contributed by anuj_67.?> <script> // JavaScript program to find perimeter// of trianglefunction findPerimeter(a, b, c){ // Formula for Perimeter of triangle return (a + b + c);} // Driver Codelet a = 2.0, b = 3.0, c = 5.0; document.write(findPerimeter(a, b, c)); // This code is contributed by code_hunt </script> Output : 10.0 Time Complexity: O(1) Auxiliary Space: O(1) vt_m code_hunt ankita_saini sooda367 hasani triangle Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 110, "s": 28, "text": "Given side (a, b, c) of a triangle, we have to find the perimeter of a triangle. " }, { "code": null, "e": 196, "s": 110, "text": "Perimeter : Perimeter of a triangle is the sum of the length of side of a triangle. " }, { "code": null, "e": 318, "s": 196, "text": "where a, b, c are length of side of a triangle.Perimeter of a triangle can simply be evaluated using following formula : " }, { "code": null, "e": 331, "s": 318, "text": "Examples : " }, { "code": null, "e": 430, "s": 331, "text": "Input : a = 2.0, b = 3.0, c = 5.0\nOutput : 10.0\n\n\nInput : a = 5.0, b = 6.0, c = 7.0 \nOutput : 18.0" }, { "code": null, "e": 434, "s": 430, "text": "C++" }, { "code": null, "e": 436, "s": 434, "text": "C" }, { "code": null, "e": 441, "s": 436, "text": "Java" }, { "code": null, "e": 448, "s": 441, "text": "Python" }, { "code": null, "e": 451, "s": 448, "text": "C#" }, { "code": null, "e": 455, "s": 451, "text": "PHP" }, { "code": null, "e": 466, "s": 455, "text": "Javascript" }, { "code": "// A simple C++ program to find the perimeter// of triangle#include <iostream>using namespace std; // Function to find perimeterfloat findPerimeter(float a, float b, float c){ // Formula for finding a perimeter // of triangle return (a + b + c);} // Driver Codeint main(){ float a = 2.0, b = 3.0, c = 5.0; cout << findPerimeter(a, b, c); return 0;} // This code is contributed by Ankita saini", "e": 883, "s": 466, "text": null }, { "code": "// A simple C program to find the perimeter// of triangle#include <stdio.h> // Function to find perimeterfloat findPerimeter(float a, float b, float c){ // Formula for finding a perimeter of triangle return (a + b + c);} // Driver Codeint main(){ float a = 2.0, b = 3.0, c = 5.0; printf(\"%f\", findPerimeter(a, b, c)); return 0;}", "e": 1228, "s": 883, "text": null }, { "code": "// Java program to find perimeter// of triangleclass Test { static float findPerimeter(float a, float b, float c) { // Formula for Perimeter of triangle return (a + b + c); } // Driver method public static void main(String[] args) { float a = 2.0, b = 3.0, c = 5.0; System.out.println(findPerimeter(a, b, c)); }}", "e": 1591, "s": 1228, "text": null }, { "code": "# Python Program to find a perimeter# of triangle # Function to find perimeterdef findPerimeter(a, b, c): # Calculate the perimeter return (a + b + c) # Driver Code a = 2.0b = 3.0c = 5.0print(findPerimeter(a, b, c))", "e": 1816, "s": 1591, "text": null }, { "code": "// C# program to find perimeter// of triangleusing System; class Test { static float findPerimeter(float a, float b, float c) { // Formula for Perimeter of triangle return (a + b + c); } // Driver method public static void Main() { float a = 2.0f, b = 3.0f, c = 5.0f; Console.WriteLine(findPerimeter(a, b, c)); }} //This code is contributed by vt_m.", "e": 2265, "s": 1816, "text": null }, { "code": "<?php// A simple PHP program// to find the perimeter// of triangle // Function to find perimeterfunction findPerimeter($a, $b, $c){ // Formula for finding a // perimeter of triangle return ($a + $b + $c);} // Driver Code $a = 2.0; $b = 3.0; $c = 5.0; echo findPerimeter($a, $b, $c); // This code is contributed by anuj_67.?>", "e": 2624, "s": 2265, "text": null }, { "code": "<script> // JavaScript program to find perimeter// of trianglefunction findPerimeter(a, b, c){ // Formula for Perimeter of triangle return (a + b + c);} // Driver Codelet a = 2.0, b = 3.0, c = 5.0; document.write(findPerimeter(a, b, c)); // This code is contributed by code_hunt </script>", "e": 2924, "s": 2624, "text": null }, { "code": null, "e": 2934, "s": 2924, "text": "Output : " }, { "code": null, "e": 2939, "s": 2934, "text": "10.0" }, { "code": null, "e": 2961, "s": 2939, "text": "Time Complexity: O(1)" }, { "code": null, "e": 2983, "s": 2961, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2988, "s": 2983, "text": "vt_m" }, { "code": null, "e": 2998, "s": 2988, "text": "code_hunt" }, { "code": null, "e": 3011, "s": 2998, "text": "ankita_saini" }, { "code": null, "e": 3020, "s": 3011, "text": "sooda367" }, { "code": null, "e": 3027, "s": 3020, "text": "hasani" }, { "code": null, "e": 3036, "s": 3027, "text": "triangle" }, { "code": null, "e": 3049, "s": 3036, "text": "Mathematical" }, { "code": null, "e": 3068, "s": 3049, "text": "School Programming" }, { "code": null, "e": 3081, "s": 3068, "text": "Mathematical" } ]