title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
p5.js | loadTable() Function | 21 Mar, 2020
The loadTable() function is used to read the contents of a file or URL and create a p5.Table object from it. The options parameter can be used to define the type of format that the data is expected to be read. All the files loaded and saved are in UTF-8 encoding.
This function is asynchronous, therefore it is recommended to be called in the preload() function to ensure that the function is executed before the other functions.
Syntax:
loadTable(filename, options, [callback], [errorCallback])
or
loadTable(filename, [callback], [errorCallback])
Parameters: This function accepts four parameter as mentioned above and described below.
filename: This is a string which denotes the file path or URL from where the data has to be loaded.
options: It is a string which denotes the format of the file to be loaded. It can be either “csv” which loads the table using comma-separated-values or “tsv” which loads the table using tab-separated-values. Also the value “header” can be specified to denote if the table has a header value. Multiple commands can be used by passing them as separate parameters. It is an optional parameter.
callback: This is a function which is called when this function executes successfully. The first argument for this function is the XML data loaded from the file. It is an optional parameter.
errorCallback: This is a function which is called if there is any error in executing the function. The first argument for this function is the error response. It is an optional parameter.
Below examples illustrate the loadTable() function in p5.js:
Example 1:
// Contents of books.csv // Book One, Author One, Price One// Book Two, Author Two, Price Two// Book Three, Author Three, Price Three let loadedTable = null; function setup() { createCanvas(500, 300); textSize(18); text("Click on the button below to"+ " load Table from file", 20, 20); // Create a button for loading the table loadBtn = createButton("Load Table from file"); loadBtn.position(30, 50) loadBtn.mousePressed(loadFile);} function loadFile() { // Load the table from file loadedTable = loadTable('books.csv', 'csv', onFileload);} function onFileload() { text("Table loaded successfully...", 20, 100); // Display through the table for (let r = 0; r < loadedTable.getRowCount(); r++) { for (let c = 0; c < loadedTable.getColumnCount(); c++) { text(loadedTable.getString(r, c), 20 + c * 200, 150 + r * 20); } }}
Output:
Example 2:
// Contents of books_header.csv // title, author, price// Book One, Author One, Price One// Book Two, Author Two, Price Two// Book Three, Author Three, Price Three let loadedTable = null; function setup() { createCanvas(500, 300); textSize(22); text("Click on the button below to " + "load Table from file", 20, 20); // Create a button for loading the table loadBtn = createButton("Load Table from file"); loadBtn.position(30, 50) loadBtn.mousePressed(loadFile);} function loadFile() { // Load the table from file with headers loadedTable = loadTable('books_header.csv', 'csv', 'header', onFileload);} function onFileload() { text("Table loaded successfully...", 20, 100); // Display the headers for (let h = 0; h < loadedTable.getColumnCount(); h++) { text(loadedTable.columns[h], 20 + h * 200, 150); } textSize(16); // Display the data in the table for (let r = 0; r < loadedTable.getRowCount(); r++) { for (let c = 0; c < loadedTable.getColumnCount(); c++) { text(loadedTable.getString(r, c), 20 + c * 200, 170 + r * 20); } }}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/loadTable
JavaScript-p5.js
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": "\n21 Mar, 2020"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "The loadTable() function is used to read the contents of a file or URL and create a p5.Table object from it. The options parameter can be used to define the type of format that the data is expected to be read. All the files loaded and saved are in UTF-8 encoding."
},
{
"code": null,
"e": 458,
"s": 292,
"text": "This function is asynchronous, therefore it is recommended to be called in the preload() function to ensure that the function is executed before the other functions."
},
{
"code": null,
"e": 466,
"s": 458,
"text": "Syntax:"
},
{
"code": null,
"e": 524,
"s": 466,
"text": "loadTable(filename, options, [callback], [errorCallback])"
},
{
"code": null,
"e": 527,
"s": 524,
"text": "or"
},
{
"code": null,
"e": 576,
"s": 527,
"text": "loadTable(filename, [callback], [errorCallback])"
},
{
"code": null,
"e": 665,
"s": 576,
"text": "Parameters: This function accepts four parameter as mentioned above and described below."
},
{
"code": null,
"e": 765,
"s": 665,
"text": "filename: This is a string which denotes the file path or URL from where the data has to be loaded."
},
{
"code": null,
"e": 1156,
"s": 765,
"text": "options: It is a string which denotes the format of the file to be loaded. It can be either “csv” which loads the table using comma-separated-values or “tsv” which loads the table using tab-separated-values. Also the value “header” can be specified to denote if the table has a header value. Multiple commands can be used by passing them as separate parameters. It is an optional parameter."
},
{
"code": null,
"e": 1347,
"s": 1156,
"text": "callback: This is a function which is called when this function executes successfully. The first argument for this function is the XML data loaded from the file. It is an optional parameter."
},
{
"code": null,
"e": 1535,
"s": 1347,
"text": "errorCallback: This is a function which is called if there is any error in executing the function. The first argument for this function is the error response. It is an optional parameter."
},
{
"code": null,
"e": 1596,
"s": 1535,
"text": "Below examples illustrate the loadTable() function in p5.js:"
},
{
"code": null,
"e": 1607,
"s": 1596,
"text": "Example 1:"
},
{
"code": "// Contents of books.csv // Book One, Author One, Price One// Book Two, Author Two, Price Two// Book Three, Author Three, Price Three let loadedTable = null; function setup() { createCanvas(500, 300); textSize(18); text(\"Click on the button below to\"+ \" load Table from file\", 20, 20); // Create a button for loading the table loadBtn = createButton(\"Load Table from file\"); loadBtn.position(30, 50) loadBtn.mousePressed(loadFile);} function loadFile() { // Load the table from file loadedTable = loadTable('books.csv', 'csv', onFileload);} function onFileload() { text(\"Table loaded successfully...\", 20, 100); // Display through the table for (let r = 0; r < loadedTable.getRowCount(); r++) { for (let c = 0; c < loadedTable.getColumnCount(); c++) { text(loadedTable.getString(r, c), 20 + c * 200, 150 + r * 20); } }}",
"e": 2482,
"s": 1607,
"text": null
},
{
"code": null,
"e": 2490,
"s": 2482,
"text": "Output:"
},
{
"code": null,
"e": 2501,
"s": 2490,
"text": "Example 2:"
},
{
"code": "// Contents of books_header.csv // title, author, price// Book One, Author One, Price One// Book Two, Author Two, Price Two// Book Three, Author Three, Price Three let loadedTable = null; function setup() { createCanvas(500, 300); textSize(22); text(\"Click on the button below to \" + \"load Table from file\", 20, 20); // Create a button for loading the table loadBtn = createButton(\"Load Table from file\"); loadBtn.position(30, 50) loadBtn.mousePressed(loadFile);} function loadFile() { // Load the table from file with headers loadedTable = loadTable('books_header.csv', 'csv', 'header', onFileload);} function onFileload() { text(\"Table loaded successfully...\", 20, 100); // Display the headers for (let h = 0; h < loadedTable.getColumnCount(); h++) { text(loadedTable.columns[h], 20 + h * 200, 150); } textSize(16); // Display the data in the table for (let r = 0; r < loadedTable.getRowCount(); r++) { for (let c = 0; c < loadedTable.getColumnCount(); c++) { text(loadedTable.getString(r, c), 20 + c * 200, 170 + r * 20); } }}",
"e": 3608,
"s": 2501,
"text": null
},
{
"code": null,
"e": 3616,
"s": 3608,
"text": "Output:"
},
{
"code": null,
"e": 3656,
"s": 3616,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 3754,
"s": 3656,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 3807,
"s": 3754,
"text": "Reference: https://p5js.org/reference/#/p5/loadTable"
},
{
"code": null,
"e": 3824,
"s": 3807,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 3835,
"s": 3824,
"text": "JavaScript"
},
{
"code": null,
"e": 3852,
"s": 3835,
"text": "Web Technologies"
}
]
|
MongoDB – findOneAndDelete() Method | 08 Feb, 2021
The findOneAndDelete() method deletes a single document based on the selection criteria from the collection. It deletes the first document from the collection that matches the given filter query expression. It takes five parameters the first parameter is the selection criteria and the others are optional.
Syntax:
db.Collection_name.findOneAndDelete(
Selection_criteria,
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
collation: <document>
})
Parameters:
The first parameter is a selection criteria. The type of this parameter is a document.
The second parameter is optional.
Optional Parameters:
projection: It allows you to select only the necessary data rather than selecting whole data from the document.
sort: It specifies the sorting order for the documents matched by the selection criteria. The value 1 sort in increasing order and -1 sort in decreasing order.
maxTimeMs: It is the maximum amount of time to allow the query to run.
collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
Return:
If a document matches the given filter query then this method returns the deleted document.
If no document matches the given filter query then this method return null.
Examples:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Four documents contains name and age of the students
Find and Delete the first document according to the selection criteria:
db.student.findOneAndDelete({name:"Bablue"})
Here we find and delete the document whose name is Bablue.
After deletion:
Find and Delete the document according to the selection criteria:
db.student.findOneAndDelete({age:17},{sort:{age:-1}})
Here, we first sort the documents according to the age field in decreasing order and then delete the first document whose age is 17.
After deletion:
When no document matches the filter query:
db.student.findOneAndDelete({name: "Sumit"})
Here, no sumit named document is present in the student collection. So, this method return null.
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 336,
"s": 28,
"text": "The findOneAndDelete() method deletes a single document based on the selection criteria from the collection. It deletes the first document from the collection that matches the given filter query expression. It takes five parameters the first parameter is the selection criteria and the others are optional. "
},
{
"code": null,
"e": 344,
"s": 336,
"text": "Syntax:"
},
{
"code": null,
"e": 381,
"s": 344,
"text": "db.Collection_name.findOneAndDelete("
},
{
"code": null,
"e": 402,
"s": 381,
"text": " Selection_criteria,"
},
{
"code": null,
"e": 404,
"s": 402,
"text": "{"
},
{
"code": null,
"e": 432,
"s": 404,
"text": " projection: <document>,"
},
{
"code": null,
"e": 454,
"s": 432,
"text": " sort: <document>,"
},
{
"code": null,
"e": 479,
"s": 454,
"text": " maxTimeMS: <number>,"
},
{
"code": null,
"e": 505,
"s": 479,
"text": " collation: <document>"
},
{
"code": null,
"e": 508,
"s": 505,
"text": "})"
},
{
"code": null,
"e": 520,
"s": 508,
"text": "Parameters:"
},
{
"code": null,
"e": 607,
"s": 520,
"text": "The first parameter is a selection criteria. The type of this parameter is a document."
},
{
"code": null,
"e": 641,
"s": 607,
"text": "The second parameter is optional."
},
{
"code": null,
"e": 662,
"s": 641,
"text": "Optional Parameters:"
},
{
"code": null,
"e": 774,
"s": 662,
"text": "projection: It allows you to select only the necessary data rather than selecting whole data from the document."
},
{
"code": null,
"e": 934,
"s": 774,
"text": "sort: It specifies the sorting order for the documents matched by the selection criteria. The value 1 sort in increasing order and -1 sort in decreasing order."
},
{
"code": null,
"e": 1005,
"s": 934,
"text": "maxTimeMs: It is the maximum amount of time to allow the query to run."
},
{
"code": null,
"e": 1233,
"s": 1005,
"text": "collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document."
},
{
"code": null,
"e": 1241,
"s": 1233,
"text": "Return:"
},
{
"code": null,
"e": 1333,
"s": 1241,
"text": "If a document matches the given filter query then this method returns the deleted document."
},
{
"code": null,
"e": 1409,
"s": 1333,
"text": "If no document matches the given filter query then this method return null."
},
{
"code": null,
"e": 1419,
"s": 1409,
"text": "Examples:"
},
{
"code": null,
"e": 1467,
"s": 1419,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 1481,
"s": 1467,
"text": "Database: gfg"
},
{
"code": null,
"e": 1502,
"s": 1481,
"text": "Collections: student"
},
{
"code": null,
"e": 1565,
"s": 1502,
"text": "Document: Four documents contains name and age of the students"
},
{
"code": null,
"e": 1637,
"s": 1565,
"text": "Find and Delete the first document according to the selection criteria:"
},
{
"code": null,
"e": 1682,
"s": 1637,
"text": "db.student.findOneAndDelete({name:\"Bablue\"})"
},
{
"code": null,
"e": 1741,
"s": 1682,
"text": "Here we find and delete the document whose name is Bablue."
},
{
"code": null,
"e": 1757,
"s": 1741,
"text": "After deletion:"
},
{
"code": null,
"e": 1823,
"s": 1757,
"text": "Find and Delete the document according to the selection criteria:"
},
{
"code": null,
"e": 1877,
"s": 1823,
"text": "db.student.findOneAndDelete({age:17},{sort:{age:-1}})"
},
{
"code": null,
"e": 2010,
"s": 1877,
"text": "Here, we first sort the documents according to the age field in decreasing order and then delete the first document whose age is 17."
},
{
"code": null,
"e": 2026,
"s": 2010,
"text": "After deletion:"
},
{
"code": null,
"e": 2069,
"s": 2026,
"text": "When no document matches the filter query:"
},
{
"code": null,
"e": 2114,
"s": 2069,
"text": "db.student.findOneAndDelete({name: \"Sumit\"})"
},
{
"code": null,
"e": 2211,
"s": 2114,
"text": "Here, no sumit named document is present in the student collection. So, this method return null."
},
{
"code": null,
"e": 2226,
"s": 2211,
"text": "MongoDB-method"
},
{
"code": null,
"e": 2233,
"s": 2226,
"text": "Picked"
},
{
"code": null,
"e": 2241,
"s": 2233,
"text": "MongoDB"
}
]
|
Working with Legends in R using ggplot2 | 28 Jul, 2021
A legend in a plot helps us to understand which groups belong to each bar, line, or box based on its type, color, etc. We can add a legend box in R using the legend() function. These work as guides. The keys can be determined by scale breaks. In this article, we will be working with legends and associated customization using ggplot2 in R programming language.
Syntax :
legend(x, y = NULL, legend, fill = NULL, col = par(“col”), border = “black”, lty, lwd, pch)
We will first install and load the ggplot2 package since, without this package, we would not be able to plot our data. So, we can install the package using the below command.
install.packages("ggplot2")
Load the package using the library function in the R programming language.
We will try to plot different aspects of the data using the ggplot() function. For a plot dealing with data that can be compared with one another, an appropriate legend will be generated by default for reference.
Example: R program to show default legend
R
library(ggplot2) # Read the datasetdata("USArrests") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() plt
Output :
The legend so generated can be easily customized as per requirements.
Here, we will change the color and size of the title of the legend formed from the plot. This can be done using the theme() function. We will pass the legend.title argument inside this function. The legend.title argument basically refers to the title of the legend formed. The legend.title argument is equal to the element_text function which is inherited from the title and accepts arguments like color, size, etc.
Syntax :
theme( legend.title = element_text(), ...., complete = FALSE, validate = TRUE)
Example: R program to customize legend title
R
# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata("USArrests") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() # Changing the title and font style of the # text of legendplt + theme(legend.title = element_text(colour = "red", size = 12))
Output :
Here, we will change the color and size of the labels of the legend formed. This can be done using the theme() function by passing legend.text as the argument. The legend.text is equal to element_text() function which is inherited from text and accepts arguments like color, size, font, etc. The legend.text argument basically refers to labels of legend items.
Syntax :
theme( legend.text = element_text(), ... , complete = FALSE, validate = TRUE)
Example: R program to customize legend labels
R
library(ggplot2) # Read the datasetdata("USArrests") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() plt + theme(legend.text = element_text(colour = "blue", size = 9)) plt
Output :
We will hide the legend title here using the theme() function providing legend.title as an argument. Here, the legend.title is equal to element_blank() function. The element_blank() assigns no space and also draws nothing.
Syntax :
theme( legend.title = element_blank(),...., complete = FALSE, validate = TRUE)
Example: R program to hide legend title
R
# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata("USArrests") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() # Hiding legend titleplt + theme(legend.title = element_blank())
Output :
We can remove the legend by providing “none” in legend.position as an argument of theme() function. The legend.position argument refers to the position of the legends.
Syntax :
theme( legend.position = “none”, ... , complete = FALSE, validate = TRUE)
Example: R program to remove legends
R
# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata("USArrests") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop))+geom_point() # Removing legend plt + theme(legend.position = "none")
Output :
Here, we will change the position of the legend from side to top. We will do this using the theme() function and providing legend.position as an argument. The legend.position argument will be assigned as a top.
Syntax :
theme( legend.position = “top”, ..., complete = FALSE, validate = TRUE)
Example : R program to place the legend at the top
R
# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata("USArrests") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) + geom_point() # For placing the legend position as topplt + theme(legend.position = "top")
Output :
Here, we will change the position of the legend and place it at the bottom. We will be using the theme() function and we will pass the legend.position argument. The legend.position argument will be assigned with the bottom.
Syntax :
theme( legend.position = “bottom”, ..., complete = FALSE, validate = TRUE)
Example: R program to place the legend at the bottom
R
# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata("USArrests") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) + geom_point() # For placing the legend position as bottomplt + theme(legend.position = "bottom")
Output :
We will add a box around our legend and add color to it using the theme() function and providing legend.background as the argument. The legend.background is equal to element_rect() function, where this function creates a rectangular box around our legend, and we can use the fill argument to add background color to it.
Syntax :
theme( legend.box.background = element_rect(), ...., complete = FALSE, validate = TRUE)
Example: R program to draw a box around a legend and add a background color to it
R
library(ggplot2) # Read the datasetdata("USArrests") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() # Drawing a rectangular box around legend # and adding background color to itplt + theme( legend.background = element_rect( fill = "lightblue", size = 0.5, linetype = "solid", colour = "black"))
Output :
We can change the key style of the legend and legend color using the theme function and providing legend.key as an argument. The legend.key argument is equal to the element_rect function which contains “color” for the outline color of the legend keys and “fill” for the inside color of the keys as its arguments. The as.factor() function will be used for the color argument to convert a vector or column from numeric to factor.
Example: R program change key style and legend color
R
library(ggplot2) data("USArrests") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = as.factor(UrbanPop))) + geom_point()+ theme(legend.key = element_rect( color = "black", fill = "light blue")) plt
Output :
Example 2: R program change key style and legend color
R
library(ggplot2) data("USArrests") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = as.factor(UrbanPop))) +geom_point()+ theme(legend.key = element_rect( color = "white", fill = "black")) plt
Output :
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 391,
"s": 28,
"text": "A legend in a plot helps us to understand which groups belong to each bar, line, or box based on its type, color, etc. We can add a legend box in R using the legend() function. These work as guides. The keys can be determined by scale breaks. In this article, we will be working with legends and associated customization using ggplot2 in R programming language. "
},
{
"code": null,
"e": 401,
"s": 391,
"text": "Syntax : "
},
{
"code": null,
"e": 493,
"s": 401,
"text": "legend(x, y = NULL, legend, fill = NULL, col = par(“col”), border = “black”, lty, lwd, pch)"
},
{
"code": null,
"e": 668,
"s": 493,
"text": "We will first install and load the ggplot2 package since, without this package, we would not be able to plot our data. So, we can install the package using the below command."
},
{
"code": null,
"e": 696,
"s": 668,
"text": "install.packages(\"ggplot2\")"
},
{
"code": null,
"e": 771,
"s": 696,
"text": "Load the package using the library function in the R programming language."
},
{
"code": null,
"e": 984,
"s": 771,
"text": "We will try to plot different aspects of the data using the ggplot() function. For a plot dealing with data that can be compared with one another, an appropriate legend will be generated by default for reference."
},
{
"code": null,
"e": 1026,
"s": 984,
"text": "Example: R program to show default legend"
},
{
"code": null,
"e": 1028,
"s": 1026,
"text": "R"
},
{
"code": "library(ggplot2) # Read the datasetdata(\"USArrests\") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() plt",
"e": 1200,
"s": 1028,
"text": null
},
{
"code": null,
"e": 1209,
"s": 1200,
"text": "Output :"
},
{
"code": null,
"e": 1279,
"s": 1209,
"text": "The legend so generated can be easily customized as per requirements."
},
{
"code": null,
"e": 1695,
"s": 1279,
"text": "Here, we will change the color and size of the title of the legend formed from the plot. This can be done using the theme() function. We will pass the legend.title argument inside this function. The legend.title argument basically refers to the title of the legend formed. The legend.title argument is equal to the element_text function which is inherited from the title and accepts arguments like color, size, etc."
},
{
"code": null,
"e": 1705,
"s": 1695,
"text": "Syntax : "
},
{
"code": null,
"e": 1784,
"s": 1705,
"text": "theme( legend.title = element_text(), ...., complete = FALSE, validate = TRUE)"
},
{
"code": null,
"e": 1829,
"s": 1784,
"text": "Example: R program to customize legend title"
},
{
"code": null,
"e": 1831,
"s": 1829,
"text": "R"
},
{
"code": "# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata(\"USArrests\") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() # Changing the title and font style of the # text of legendplt + theme(legend.title = element_text(colour = \"red\", size = 12))",
"e": 2145,
"s": 1831,
"text": null
},
{
"code": null,
"e": 2154,
"s": 2145,
"text": "Output :"
},
{
"code": null,
"e": 2515,
"s": 2154,
"text": "Here, we will change the color and size of the labels of the legend formed. This can be done using the theme() function by passing legend.text as the argument. The legend.text is equal to element_text() function which is inherited from text and accepts arguments like color, size, font, etc. The legend.text argument basically refers to labels of legend items."
},
{
"code": null,
"e": 2525,
"s": 2515,
"text": "Syntax : "
},
{
"code": null,
"e": 2603,
"s": 2525,
"text": "theme( legend.text = element_text(), ... , complete = FALSE, validate = TRUE)"
},
{
"code": null,
"e": 2649,
"s": 2603,
"text": "Example: R program to customize legend labels"
},
{
"code": null,
"e": 2651,
"s": 2649,
"text": "R"
},
{
"code": "library(ggplot2) # Read the datasetdata(\"USArrests\") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() plt + theme(legend.text = element_text(colour = \"blue\", size = 9)) plt",
"e": 2891,
"s": 2651,
"text": null
},
{
"code": null,
"e": 2900,
"s": 2891,
"text": "Output :"
},
{
"code": null,
"e": 3123,
"s": 2900,
"text": "We will hide the legend title here using the theme() function providing legend.title as an argument. Here, the legend.title is equal to element_blank() function. The element_blank() assigns no space and also draws nothing."
},
{
"code": null,
"e": 3133,
"s": 3123,
"text": "Syntax : "
},
{
"code": null,
"e": 3212,
"s": 3133,
"text": "theme( legend.title = element_blank(),...., complete = FALSE, validate = TRUE)"
},
{
"code": null,
"e": 3252,
"s": 3212,
"text": "Example: R program to hide legend title"
},
{
"code": null,
"e": 3254,
"s": 3252,
"text": "R"
},
{
"code": "# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata(\"USArrests\") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() # Hiding legend titleplt + theme(legend.title = element_blank())",
"e": 3506,
"s": 3254,
"text": null
},
{
"code": null,
"e": 3515,
"s": 3506,
"text": "Output :"
},
{
"code": null,
"e": 3683,
"s": 3515,
"text": "We can remove the legend by providing “none” in legend.position as an argument of theme() function. The legend.position argument refers to the position of the legends."
},
{
"code": null,
"e": 3693,
"s": 3683,
"text": "Syntax : "
},
{
"code": null,
"e": 3767,
"s": 3693,
"text": "theme( legend.position = “none”, ... , complete = FALSE, validate = TRUE)"
},
{
"code": null,
"e": 3804,
"s": 3767,
"text": "Example: R program to remove legends"
},
{
"code": null,
"e": 3806,
"s": 3804,
"text": "R"
},
{
"code": "# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata(\"USArrests\") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop))+geom_point() # Removing legend plt + theme(legend.position = \"none\")",
"e": 4048,
"s": 3806,
"text": null
},
{
"code": null,
"e": 4057,
"s": 4048,
"text": "Output :"
},
{
"code": null,
"e": 4268,
"s": 4057,
"text": "Here, we will change the position of the legend from side to top. We will do this using the theme() function and providing legend.position as an argument. The legend.position argument will be assigned as a top."
},
{
"code": null,
"e": 4278,
"s": 4268,
"text": "Syntax : "
},
{
"code": null,
"e": 4350,
"s": 4278,
"text": "theme( legend.position = “top”, ..., complete = FALSE, validate = TRUE)"
},
{
"code": null,
"e": 4401,
"s": 4350,
"text": "Example : R program to place the legend at the top"
},
{
"code": null,
"e": 4403,
"s": 4401,
"text": "R"
},
{
"code": "# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata(\"USArrests\") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) + geom_point() # For placing the legend position as topplt + theme(legend.position = \"top\")",
"e": 4668,
"s": 4403,
"text": null
},
{
"code": null,
"e": 4677,
"s": 4668,
"text": "Output :"
},
{
"code": null,
"e": 4901,
"s": 4677,
"text": "Here, we will change the position of the legend and place it at the bottom. We will be using the theme() function and we will pass the legend.position argument. The legend.position argument will be assigned with the bottom."
},
{
"code": null,
"e": 4911,
"s": 4901,
"text": "Syntax : "
},
{
"code": null,
"e": 4986,
"s": 4911,
"text": "theme( legend.position = “bottom”, ..., complete = FALSE, validate = TRUE)"
},
{
"code": null,
"e": 5039,
"s": 4986,
"text": "Example: R program to place the legend at the bottom"
},
{
"code": null,
"e": 5041,
"s": 5039,
"text": "R"
},
{
"code": "# Installing and loading the packagelibrary(ggplot2) # Read the datasetdata(\"USArrests\") # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) + geom_point() # For placing the legend position as bottomplt + theme(legend.position = \"bottom\")",
"e": 5312,
"s": 5041,
"text": null
},
{
"code": null,
"e": 5321,
"s": 5312,
"text": "Output :"
},
{
"code": null,
"e": 5641,
"s": 5321,
"text": "We will add a box around our legend and add color to it using the theme() function and providing legend.background as the argument. The legend.background is equal to element_rect() function, where this function creates a rectangular box around our legend, and we can use the fill argument to add background color to it."
},
{
"code": null,
"e": 5651,
"s": 5641,
"text": "Syntax : "
},
{
"code": null,
"e": 5739,
"s": 5651,
"text": "theme( legend.box.background = element_rect(), ...., complete = FALSE, validate = TRUE)"
},
{
"code": null,
"e": 5821,
"s": 5739,
"text": "Example: R program to draw a box around a legend and add a background color to it"
},
{
"code": null,
"e": 5823,
"s": 5821,
"text": "R"
},
{
"code": "library(ggplot2) # Read the datasetdata(\"USArrests\") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = UrbanPop)) +geom_point() # Drawing a rectangular box around legend # and adding background color to itplt + theme( legend.background = element_rect( fill = \"lightblue\", size = 0.5, linetype = \"solid\", colour = \"black\"))",
"e": 6202,
"s": 5823,
"text": null
},
{
"code": null,
"e": 6211,
"s": 6202,
"text": "Output :"
},
{
"code": null,
"e": 6639,
"s": 6211,
"text": "We can change the key style of the legend and legend color using the theme function and providing legend.key as an argument. The legend.key argument is equal to the element_rect function which contains “color” for the outline color of the legend keys and “fill” for the inside color of the keys as its arguments. The as.factor() function will be used for the color argument to convert a vector or column from numeric to factor."
},
{
"code": null,
"e": 6692,
"s": 6639,
"text": "Example: R program change key style and legend color"
},
{
"code": null,
"e": 6694,
"s": 6692,
"text": "R"
},
{
"code": "library(ggplot2) data(\"USArrests\") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = as.factor(UrbanPop))) + geom_point()+ theme(legend.key = element_rect( color = \"black\", fill = \"light blue\")) plt",
"e": 6996,
"s": 6694,
"text": null
},
{
"code": null,
"e": 7005,
"s": 6996,
"text": "Output :"
},
{
"code": null,
"e": 7060,
"s": 7005,
"text": "Example 2: R program change key style and legend color"
},
{
"code": null,
"e": 7062,
"s": 7060,
"text": "R"
},
{
"code": "library(ggplot2) data(\"USArrests\") head(USArrests) # Plot the dataplt <- ggplot(USArrests, aes(Murder, Assault, colour = as.factor(UrbanPop))) +geom_point()+ theme(legend.key = element_rect( color = \"white\", fill = \"black\")) plt",
"e": 7296,
"s": 7062,
"text": null
},
{
"code": null,
"e": 7305,
"s": 7296,
"text": "Output :"
},
{
"code": null,
"e": 7312,
"s": 7305,
"text": "Picked"
},
{
"code": null,
"e": 7321,
"s": 7312,
"text": "R-ggplot"
},
{
"code": null,
"e": 7332,
"s": 7321,
"text": "R Language"
}
]
|
Convert image to binary using Python | 17 Dec, 2020
In this article, we are going to convert the image into its binary form. A binary image is a monochromatic image that consists of pixels that can have one of exactly two colors, usually black and white. Binary images are also called bi-level or two-level. This means that each pixel is stored as a single bit—i.e., 0 or 1.
The most important library needed for image processing in Python is OpenCV. Make sure you have installed the library into your Python. For steps for installing OpenCV refers to this article: Set up Opencv with anaconda environment
Approach:
Read the image from the location.As a colored image has RGB layers in it and is more complex, convert it to its Grayscale form first.Set up a Threshold mark, pixels above the given mark will turn white, and below the mark will turn black.
Read the image from the location.
As a colored image has RGB layers in it and is more complex, convert it to its Grayscale form first.
Set up a Threshold mark, pixels above the given mark will turn white, and below the mark will turn black.
Below is the implementation:
Python3
import cv2 # read the image fileimg = cv2.imread('ff.jpg', 2) ret, bw_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # converting to its binary formbw = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) cv2.imshow("Binary", bw_img)cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Original Image
Binary Form
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "In this article, we are going to convert the image into its binary form. A binary image is a monochromatic image that consists of pixels that can have one of exactly two colors, usually black and white. Binary images are also called bi-level or two-level. This means that each pixel is stored as a single bit—i.e., 0 or 1."
},
{
"code": null,
"e": 582,
"s": 351,
"text": "The most important library needed for image processing in Python is OpenCV. Make sure you have installed the library into your Python. For steps for installing OpenCV refers to this article: Set up Opencv with anaconda environment"
},
{
"code": null,
"e": 592,
"s": 582,
"text": "Approach:"
},
{
"code": null,
"e": 831,
"s": 592,
"text": "Read the image from the location.As a colored image has RGB layers in it and is more complex, convert it to its Grayscale form first.Set up a Threshold mark, pixels above the given mark will turn white, and below the mark will turn black."
},
{
"code": null,
"e": 865,
"s": 831,
"text": "Read the image from the location."
},
{
"code": null,
"e": 966,
"s": 865,
"text": "As a colored image has RGB layers in it and is more complex, convert it to its Grayscale form first."
},
{
"code": null,
"e": 1072,
"s": 966,
"text": "Set up a Threshold mark, pixels above the given mark will turn white, and below the mark will turn black."
},
{
"code": null,
"e": 1101,
"s": 1072,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1109,
"s": 1101,
"text": "Python3"
},
{
"code": "import cv2 # read the image fileimg = cv2.imread('ff.jpg', 2) ret, bw_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # converting to its binary formbw = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) cv2.imshow(\"Binary\", bw_img)cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 1387,
"s": 1109,
"text": null
},
{
"code": null,
"e": 1395,
"s": 1387,
"text": "Output:"
},
{
"code": null,
"e": 1410,
"s": 1395,
"text": "Original Image"
},
{
"code": null,
"e": 1422,
"s": 1410,
"text": "Binary Form"
},
{
"code": null,
"e": 1429,
"s": 1422,
"text": "Picked"
},
{
"code": null,
"e": 1443,
"s": 1429,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 1450,
"s": 1443,
"text": "Python"
},
{
"code": null,
"e": 1548,
"s": 1450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1580,
"s": 1548,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1607,
"s": 1580,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1628,
"s": 1607,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1651,
"s": 1628,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1707,
"s": 1651,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1738,
"s": 1707,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1780,
"s": 1738,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1822,
"s": 1780,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1861,
"s": 1822,
"text": "Python | Get unique values from a list"
}
]
|
Python String splitlines() Method | Python string method splitlines() returns a list with all the lines in string, optionally including the line breaks (if num is supplied and is true)
Following is the syntax for splitlines() method −
str.splitlines()
Keepends − This is an optional parameter, if its value as true, line breaks need are also included in the output.
Keepends − This is an optional parameter, if its value as true, line breaks need are also included in the output.
The following example shows the usage of splitlines() method.
#!/usr/bin/python
str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print str.splitlines( )
print str.splitlines( 0 )
print str.splitlines( 3 )
print str.splitlines( 4 )
print str.splitlines( 5 )
When we run above program, it produces following result −
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
If you pass “True” as a parameter to this method this includes the line breaks in the output.
#!/usr/bin/python
str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
print str.splitlines(True)
print str.splitlines( 0 )
print str.splitlines( 3 )
print str.splitlines( 4 )
print str.splitlines( 5 )
When we run above program, it produces following result −
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d']
['Line1-a b c d e f\n', 'Line2- a b c\n', '\n', 'Line4- a b c d'] | [
{
"code": null,
"e": 2528,
"s": 2378,
"text": "Python string method splitlines() returns a list with all the lines in string, optionally including the line breaks (if num is supplied and is true)"
},
{
"code": null,
"e": 2578,
"s": 2528,
"text": "Following is the syntax for splitlines() method −"
},
{
"code": null,
"e": 2596,
"s": 2578,
"text": "str.splitlines()\n"
},
{
"code": null,
"e": 2710,
"s": 2596,
"text": "Keepends − This is an optional parameter, if its value as true, line breaks need are also included in the output."
},
{
"code": null,
"e": 2824,
"s": 2710,
"text": "Keepends − This is an optional parameter, if its value as true, line breaks need are also included in the output."
},
{
"code": null,
"e": 2886,
"s": 2824,
"text": "The following example shows the usage of splitlines() method."
},
{
"code": null,
"e": 3092,
"s": 2886,
"text": "#!/usr/bin/python\n\nstr = \"Line1-a b c d e f\\nLine2- a b c\\n\\nLine4- a b c d\";\nprint str.splitlines( )\nprint str.splitlines( 0 )\nprint str.splitlines( 3 )\nprint str.splitlines( 4 )\nprint str.splitlines( 5 )"
},
{
"code": null,
"e": 3150,
"s": 3092,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3469,
"s": 3150,
"text": "['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']\n['Line1-a b c d e f', 'Line2- a b c', '', 'Line4- a b c d']\n['Line1-a b c d e f\\n', 'Line2- a b c\\n', '\\n', 'Line4- a b c d']\n['Line1-a b c d e f\\n', 'Line2- a b c\\n', '\\n', 'Line4- a b c d']\n['Line1-a b c d e f\\n', 'Line2- a b c\\n', '\\n', 'Line4- a b c d']\n"
},
{
"code": null,
"e": 3563,
"s": 3469,
"text": "If you pass “True” as a parameter to this method this includes the line breaks in the output."
},
{
"code": null,
"e": 3772,
"s": 3563,
"text": "#!/usr/bin/python\n\nstr = \"Line1-a b c d e f\\nLine2- a b c\\n\\nLine4- a b c d\";\nprint str.splitlines(True)\nprint str.splitlines( 0 )\nprint str.splitlines( 3 )\nprint str.splitlines( 4 )\nprint str.splitlines( 5 )"
},
{
"code": null,
"e": 3830,
"s": 3772,
"text": "When we run above program, it produces following result −"
}
]
|
PyQt5 QDockWidget – Setting Multiple Widgets Inside it | 24 May, 2022
In this article we will see how we add/set multiple widgets to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). We use setWidget method to add/set widget to the dock widget. But this is used to set only single widget.
In order to set multiple widgets inside it we have to do the following1. Create a Main Window Class 2. Inside the class create a QDockWidget object and set its properties 3. Create a QWidget object 4. Create a QLayout object 5. Create various widget object which we want to add in the QDockWidget 6. Add these widgets to the layout created earlier with the help of addWidget method 7. Set this layout to the QWidget object with the help of setLayout method 8. Set this QWidget object to the QDockWidget object with the help of setWidget method
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget(self) # setting title to the dock widget dock.setWindowTitle("GfG ") # creating a QWidget object widget = QWidget(self) # creating a vertical box layout layout = QVBoxLayout(self) # push button 1 push1 = QPushButton("A", self) # push button 2 push2 = QPushButton("B", self) # push button 3 push3 = QPushButton("C", self) # adding these buttons to the layout layout.addWidget(push1) layout.addWidget(push2) layout.addWidget(push3) # setting the layout to the widget widget.setLayout(layout) # adding widget to the layout dock.setWidget(widget) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
masam
sagartomar9927
vinayedula
Python PyQt-QDockWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Stack in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 May, 2022"
},
{
"code": null,
"e": 439,
"s": 28,
"text": "In this article we will see how we add/set multiple widgets to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window). We use setWidget method to add/set widget to the dock widget. But this is used to set only single widget. "
},
{
"code": null,
"e": 985,
"s": 439,
"text": "In order to set multiple widgets inside it we have to do the following1. Create a Main Window Class 2. Inside the class create a QDockWidget object and set its properties 3. Create a QWidget object 4. Create a QLayout object 5. Create various widget object which we want to add in the QDockWidget 6. Add these widgets to the layout created earlier with the help of addWidget method 7. Set this layout to the QWidget object with the help of setLayout method 8. Set this QWidget object to the QDockWidget object with the help of setWidget method "
},
{
"code": null,
"e": 1015,
"s": 985,
"text": "Below is the implementation "
},
{
"code": null,
"e": 1023,
"s": 1015,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating dock widget dock = QDockWidget(self) # setting title to the dock widget dock.setWindowTitle(\"GfG \") # creating a QWidget object widget = QWidget(self) # creating a vertical box layout layout = QVBoxLayout(self) # push button 1 push1 = QPushButton(\"A\", self) # push button 2 push2 = QPushButton(\"B\", self) # push button 3 push3 = QPushButton(\"C\", self) # adding these buttons to the layout layout.addWidget(push1) layout.addWidget(push2) layout.addWidget(push3) # setting the layout to the widget widget.setLayout(layout) # adding widget to the layout dock.setWidget(widget) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # setting geometry tot he dock widget dock.setGeometry(100, 0, 200, 30) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2732,
"s": 1023,
"text": null
},
{
"code": null,
"e": 2743,
"s": 2732,
"text": "Output : "
},
{
"code": null,
"e": 2751,
"s": 2745,
"text": "masam"
},
{
"code": null,
"e": 2766,
"s": 2751,
"text": "sagartomar9927"
},
{
"code": null,
"e": 2777,
"s": 2766,
"text": "vinayedula"
},
{
"code": null,
"e": 2801,
"s": 2777,
"text": "Python PyQt-QDockWidget"
},
{
"code": null,
"e": 2812,
"s": 2801,
"text": "Python-gui"
},
{
"code": null,
"e": 2824,
"s": 2812,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2831,
"s": 2824,
"text": "Python"
},
{
"code": null,
"e": 2929,
"s": 2831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2959,
"s": 2929,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3004,
"s": 2959,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3026,
"s": 3004,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3044,
"s": 3026,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3065,
"s": 3044,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3107,
"s": 3065,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3136,
"s": 3107,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3163,
"s": 3136,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3186,
"s": 3163,
"text": "Introduction To PYTHON"
}
]
|
Final variable in Java | A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object.
However, the data within the object can be changed. So, the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
public class Test {
final int value = 10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue() {
value = 12; // will give an error
}
} | [
{
"code": null,
"e": 1338,
"s": 1187,
"text": "A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. "
},
{
"code": null,
"e": 1456,
"s": 1338,
"text": "However, the data within the object can be changed. So, the state of the object can be changed but not the reference."
},
{
"code": null,
"e": 1556,
"s": 1456,
"text": "With variables, the final modifier often is used with static to make the constant a class variable."
},
{
"code": null,
"e": 1819,
"s": 1556,
"text": "public class Test {\n final int value = 10;\n // The following are examples of declaring constants:\n public static final int BOXWIDTH = 6;\n static final String TITLE = \"Manager\";\n public void changeValue() {\n value = 12; // will give an error\n }\n}"
}
]
|
Django settings file – step by step Explanation | 01 Jun, 2021
Once we create the Django project, it comes with predefined Directory structure having the following files with each file having their own uses.
Lets take an example
// Create a Django Project "mysite"
django-admin startproject mysite
cd /pathTo/mysite
// Create a Django app "polls" inside project "mysite"
python manage.py startapp polls
After these commands on Terminal/CMD Directory structure of project “mysite” will be:
mysite <-- BASE_DIR
--> mysite
-> __init__.py
-> asgi.py
-> settings.py <-- settings.py file
-> urls.py
-> wsgi.py
--> manage.py
--> polls
A Django settings file contains all the configuration of your Django Project. In this article the important points of settings.py file of Django will be discussed. A settings file is just a Python module with module-level variables.
BASE_DIR points to top hierarchy of project i.e. mysite, whatever paths we define in project are all relative to BASE_DIR. To use BASE_DIR we will have to use os module provided by python.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
In Development Error is very obvious to occur. There is no fun in writing a program where we do not face any error. but sometimes tackling errors is very hectic. Django provides an inbuild Debugger which makes the developer’s life very easy. We can use it by doing:
DEBUG = True // It is Default value and is preferred in only Development Phase.
In production, DEBUG = False is preferred.
ALLOWED_HOSTS is list having addresses of all domains which can run your Django Project.
When DEBUG set to True ALLOWED_HOSTS can be an empty list i.e. ALLOWED_HOSTS=[ ] because by Default it is 127.0.0.1 or localhost When DEBUG set to False ALLOWED_HOSTS can not be an empty list. We have to give hosts name in list. i.e. ALLOWED_HOSTS=[“127.0.0.1”, “*.heroku.com”]. “127.0.0.1” represents Your PC, “*.heroku.com” represents this application can be run on heroku also.
In this section, we mention all apps that will be used in our Django project. Previously we made an app polls we have to tell Django its existence To do so have to put into INSTALLED_APPS:
INSTALLED_APPS = [
// Some preloaded apps by Django,
'polls', // don't forget to quote it and also commas after every app
]
Django officially supports the following databases:
PostgreSQL
MariaDB
MySQL
Oracle
SQLite <– By Default
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
There are also a number of database backends provided by third parties. Here is Example of using PostgreSQL
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': YOUR_DB_NAME,
'USER': USERNAME,
'PASSWORD': PASSWORD_FOR_DB,
'HOST': 'localhost' // in Development.
}
}
Note: Before using PostgreSQL we have to install psycopg2 using pip install psycopg2
URL variables are relative to BASE_DIR. These variables are used to store files either media or static. Note: Make static and media folders in Parent Directory.
MEDIA_URL
MEDIA_URL is relative path to BASE_DIR. This variable is use to store the media files.
MEDIA_URL= '/media/'
STATIC_URL
STATIC_URL is relative path to BASE_DIR. This variable is use to store the static files.
STATIC_URL = '/static/'
ROOT variables are absolute paths. These variables are used to retrieve files either media or static.
MEDIA_ROOT
MEDIA_ROOT is absolute path. This variable is use to retrieve the media files.
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
STATIC_ROOT
STATIC_ROOT is absolute path. This variable is use to retrieve the static files.
STATIC_ROOT= os.path.join(BASE_DIR, 'static')
Note: All variable names in Django settings are in CAPITAL.
ManasChhabra2
simmytarika5
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": 53,
"s": 25,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 199,
"s": 53,
"text": "Once we create the Django project, it comes with predefined Directory structure having the following files with each file having their own uses. "
},
{
"code": null,
"e": 222,
"s": 199,
"text": "Lets take an example "
},
{
"code": null,
"e": 398,
"s": 222,
"text": "// Create a Django Project \"mysite\" \ndjango-admin startproject mysite\n\ncd /pathTo/mysite\n// Create a Django app \"polls\" inside project \"mysite\"\npython manage.py startapp polls"
},
{
"code": null,
"e": 486,
"s": 398,
"text": "After these commands on Terminal/CMD Directory structure of project “mysite” will be: "
},
{
"code": null,
"e": 734,
"s": 486,
"text": "mysite <-- BASE_DIR \n --> mysite \n -> __init__.py\n -> asgi.py\n -> settings.py <-- settings.py file \n -> urls.py\n -> wsgi.py\n --> manage.py\n --> polls"
},
{
"code": null,
"e": 971,
"s": 736,
"text": "A Django settings file contains all the configuration of your Django Project. In this article the important points of settings.py file of Django will be discussed. A settings file is just a Python module with module-level variables. "
},
{
"code": null,
"e": 1162,
"s": 971,
"text": "BASE_DIR points to top hierarchy of project i.e. mysite, whatever paths we define in project are all relative to BASE_DIR. To use BASE_DIR we will have to use os module provided by python. "
},
{
"code": null,
"e": 1233,
"s": 1162,
"text": "BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))"
},
{
"code": null,
"e": 1503,
"s": 1235,
"text": "In Development Error is very obvious to occur. There is no fun in writing a program where we do not face any error. but sometimes tackling errors is very hectic. Django provides an inbuild Debugger which makes the developer’s life very easy. We can use it by doing: "
},
{
"code": null,
"e": 1584,
"s": 1503,
"text": "DEBUG = True // It is Default value and is preferred in only Development Phase."
},
{
"code": null,
"e": 1628,
"s": 1584,
"text": "In production, DEBUG = False is preferred. "
},
{
"code": null,
"e": 1721,
"s": 1630,
"text": "ALLOWED_HOSTS is list having addresses of all domains which can run your Django Project. "
},
{
"code": null,
"e": 2104,
"s": 1721,
"text": "When DEBUG set to True ALLOWED_HOSTS can be an empty list i.e. ALLOWED_HOSTS=[ ] because by Default it is 127.0.0.1 or localhost When DEBUG set to False ALLOWED_HOSTS can not be an empty list. We have to give hosts name in list. i.e. ALLOWED_HOSTS=[“127.0.0.1”, “*.heroku.com”]. “127.0.0.1” represents Your PC, “*.heroku.com” represents this application can be run on heroku also. "
},
{
"code": null,
"e": 2297,
"s": 2106,
"text": "In this section, we mention all apps that will be used in our Django project. Previously we made an app polls we have to tell Django its existence To do so have to put into INSTALLED_APPS: "
},
{
"code": null,
"e": 2441,
"s": 2297,
"text": " INSTALLED_APPS = [\n // Some preloaded apps by Django,\n 'polls', // don't forget to quote it and also commas after every app\n]"
},
{
"code": null,
"e": 2497,
"s": 2443,
"text": "Django officially supports the following databases: "
},
{
"code": null,
"e": 2508,
"s": 2497,
"text": "PostgreSQL"
},
{
"code": null,
"e": 2516,
"s": 2508,
"text": "MariaDB"
},
{
"code": null,
"e": 2522,
"s": 2516,
"text": "MySQL"
},
{
"code": null,
"e": 2529,
"s": 2522,
"text": "Oracle"
},
{
"code": null,
"e": 2550,
"s": 2529,
"text": "SQLite <– By Default"
},
{
"code": null,
"e": 2717,
"s": 2552,
"text": " DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n }"
},
{
"code": null,
"e": 2827,
"s": 2717,
"text": "There are also a number of database backends provided by third parties. Here is Example of using PostgreSQL "
},
{
"code": null,
"e": 3094,
"s": 2827,
"text": " DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': YOUR_DB_NAME,\n 'USER': USERNAME,\n 'PASSWORD': PASSWORD_FOR_DB,\n 'HOST': 'localhost' // in Development.\n }\n }"
},
{
"code": null,
"e": 3181,
"s": 3096,
"text": "Note: Before using PostgreSQL we have to install psycopg2 using pip install psycopg2"
},
{
"code": null,
"e": 3348,
"s": 3185,
"text": "URL variables are relative to BASE_DIR. These variables are used to store files either media or static. Note: Make static and media folders in Parent Directory. "
},
{
"code": null,
"e": 3358,
"s": 3348,
"text": "MEDIA_URL"
},
{
"code": null,
"e": 3447,
"s": 3358,
"text": "MEDIA_URL is relative path to BASE_DIR. This variable is use to store the media files. "
},
{
"code": null,
"e": 3468,
"s": 3447,
"text": "MEDIA_URL= '/media/'"
},
{
"code": null,
"e": 3481,
"s": 3470,
"text": "STATIC_URL"
},
{
"code": null,
"e": 3572,
"s": 3481,
"text": "STATIC_URL is relative path to BASE_DIR. This variable is use to store the static files. "
},
{
"code": null,
"e": 3596,
"s": 3572,
"text": "STATIC_URL = '/static/'"
},
{
"code": null,
"e": 3701,
"s": 3598,
"text": "ROOT variables are absolute paths. These variables are used to retrieve files either media or static. "
},
{
"code": null,
"e": 3714,
"s": 3703,
"text": "MEDIA_ROOT"
},
{
"code": null,
"e": 3795,
"s": 3714,
"text": "MEDIA_ROOT is absolute path. This variable is use to retrieve the media files. "
},
{
"code": null,
"e": 3839,
"s": 3795,
"text": "MEDIA_ROOT= os.path.join(BASE_DIR, 'media')"
},
{
"code": null,
"e": 3853,
"s": 3841,
"text": "STATIC_ROOT"
},
{
"code": null,
"e": 3936,
"s": 3853,
"text": "STATIC_ROOT is absolute path. This variable is use to retrieve the static files. "
},
{
"code": null,
"e": 3982,
"s": 3936,
"text": "STATIC_ROOT= os.path.join(BASE_DIR, 'static')"
},
{
"code": null,
"e": 4044,
"s": 3984,
"text": "Note: All variable names in Django settings are in CAPITAL."
},
{
"code": null,
"e": 4060,
"s": 4046,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 4073,
"s": 4060,
"text": "simmytarika5"
},
{
"code": null,
"e": 4080,
"s": 4073,
"text": "Python"
},
{
"code": null,
"e": 4097,
"s": 4080,
"text": "Web Technologies"
},
{
"code": null,
"e": 4195,
"s": 4097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4227,
"s": 4195,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4254,
"s": 4227,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4275,
"s": 4254,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4298,
"s": 4275,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4354,
"s": 4298,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4416,
"s": 4354,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4449,
"s": 4416,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4510,
"s": 4449,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4560,
"s": 4510,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Count common subsequence in two strings | 01 Sep, 2021
Given two string S and Q. The task is to count the number of the common subsequence in S and T.
Examples:
Input : S = “ajblqcpdz”, T = “aefcnbtdi” Output : 11 Common subsequences are : { “a”, “b”, “c”, “d”, “ab”, “bd”, “ad”, “ac”, “cd”, “abd”, “acd” }
Input : S = “a”, T = “ab” Output : 1
To find the number of common subsequences in two string, say S and T, we use Dynamic Programming by defining a 2D array dp[][], where dp[i][j] is the number of common subsequences in the string S[0...i-1] and T[0....j-1]. Now, we can define dp[i][j] as = dp[i][j-1] + dp[i-1][j] + 1, when S[i-1] is equal to T[j-1] This is because when S[i-1] == S[j-1], using the above fact all the previous common sub-sequences are doubled as they get appended by one more character. Both dp[i][j-1] and dp[i-1][j] contain dp[i-1][j-1] and hence it gets added two times in our recurrence which takes care of doubling of count of all previous common sub-sequences. Addition of 1 in recurrence is for the latest character match : common sub-sequence made up of s1[i-1] and s2[j-1]= dp[i-1][j] + dp[i][j-1] – dp[i-1][j-1], when S[i-1] is not equal to T[j-1] Here we subtract dp[i-1][j-1] once because it is present in both dp[i][j – 1] and dp[i – 1][j] and gets added twice.
Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count common subsequence in two strings#include <bits/stdc++.h>using namespace std; // return the number of common subsequence in// two stringsint CommomSubsequencesCount(string s, string t){ int n1 = s.length(); int n2 = t.length(); int dp[n1+1][n2+1]; for (int i = 0; i <= n1; i++) { for (int j = 0; j <= n2; j++) { dp[i][j] = 0; } } // for each character of S for (int i = 1; i <= n1; i++) { // for each character in T for (int j = 1; j <= n2; j++) { // if character are same in both // the string if (s[i - 1] == t[j - 1]) dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j]; else dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]; } } return dp[n1][n2];} // Driver Programint main(){ string s = "ajblqcpdz"; string t = "aefcnbtdi"; cout << CommomSubsequencesCount(s, t) << endl; return 0;}
// Java program to count common subsequence in two stringspublic class GFG { // return the number of common subsequence in // two strings static int CommomSubsequencesCount(String s, String t) { int n1 = s.length(); int n2 = t.length(); int dp[][] = new int [n1+1][n2+1]; char ch1,ch2 ; for (int i = 0; i <= n1; i++) { for (int j = 0; j <= n2; j++) { dp[i][j] = 0; } } // for each character of S for (int i = 1; i <= n1; i++) { // for each character in T for (int j = 1; j <= n2; j++) { ch1 = s.charAt(i - 1); ch2 = t.charAt(j - 1); // if character are same in both // the string if (ch1 == ch2) dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j]; else dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]; } } return dp[n1][n2]; } // Driver code public static void main (String args[]){ String s = "ajblqcpdz"; String t = "aefcnbtdi"; System.out.println(CommomSubsequencesCount(s, t)); } // This code is contributed by ANKITRAI1}
# Python3 program to count common# subsequence in two strings # return the number of common subsequence# in two stringsdef CommomSubsequencesCount(s, t): n1 = len(s) n2 = len(t) dp = [[0 for i in range(n2 + 1)] for i in range(n1 + 1)] # for each character of S for i in range(1, n1 + 1): # for each character in T for j in range(1, n2 + 1): # if character are same in both # the string if (s[i - 1] == t[j - 1]): dp[i][j] = (1 + dp[i][j - 1] + dp[i - 1][j]) else: dp[i][j] = (dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]) return dp[n1][n2] # Driver Codes = "ajblqcpdz"t = "aefcnbtdi" print(CommomSubsequencesCount(s, t)) # This code is contributed by Mohit Kumar
// C# program to count common// subsequence in two stringsusing System; class GFG{ // return the number of common// subsequence in two stringsstatic int CommomSubsequencesCount(string s, string t){ int n1 = s.Length; int n2 = t.Length; int[,] dp = new int [n1 + 1, n2 + 1]; for (int i = 0; i <= n1; i++) { for (int j = 0; j <= n2; j++) { dp[i, j] = 0; } } // for each character of S for (int i = 1; i <= n1; i++) { // for each character in T for (int j = 1; j <= n2; j++) { // if character are same in // both the string if (s[i - 1] == t[j - 1]) dp[i, j] = 1 + dp[i, j - 1] + dp[i - 1, j]; else dp[i, j] = dp[i, j - 1] + dp[i - 1, j] - dp[i - 1, j - 1]; } } return dp[n1, n2];} // Driver codepublic static void Main (){ string s = "ajblqcpdz"; string t = "aefcnbtdi"; Console.Write(CommomSubsequencesCount(s, t));}} // This code is contributed// by ChitraNayal
<?php// PHP program to count common subsequence// in two strings // return the number of common subsequence// in two stringsfunction CommomSubsequencesCount($s, $t){ $n1 = strlen($s); $n2 = strlen($t); $dp = array(); for ($i = 0; $i <= $n1; $i++) { for ($j = 0; $j <= $n2; $j++) { $dp[$i][$j] = 0; } } // for each character of S for ($i = 1; $i <= $n1; $i++) { // for each character in T for ($j = 1; $j <= $n2; $j++) { // if character are same in both // the string if ($s[$i - 1] == $t[$j - 1]) $dp[$i][$j] = 1 + $dp[$i][$j - 1] + $dp[$i - 1][$j]; else $dp[$i][$j] = $dp[$i][$j - 1] + $dp[$i - 1][$j] - $dp[$i - 1][$j - 1]; } } return $dp[$n1][$n2];} // Driver Code$s = "ajblqcpdz";$t = "aefcnbtdi"; echo CommomSubsequencesCount($s, $t) ."\n"; // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to count common subsequence in two strings // return the number of common subsequence in// two stringsfunction CommomSubsequencesCount(s, t){ var n1 = s.length; var n2 = t.length; var dp = Array.from(Array(n1+1), ()=> Array(n2+1)); for (var i = 0; i <= n1; i++) { for (var j = 0; j <= n2; j++) { dp[i][j] = 0; } } // for each character of S for (var i = 1; i <= n1; i++) { // for each character in T for (var j = 1; j <= n2; j++) { // if character are same in both // the string if (s[i - 1] == t[j - 1]) dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j]; else dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]; } } return dp[n1][n2];} // Driver Programvar s = "ajblqcpdz";var t = "aefcnbtdi";document.write( CommomSubsequencesCount(s, t)); </script>
11
Time Complexity : O(n1 * n2) Auxiliary Space : O(n1 * n2)Source : StackOverflow
ankthon
ukasp
mohit kumar 29
Akanksha_Rai
nidhi_biet
itsok
sweetyty
LCS
subsequence
Dynamic Programming
Strings
Strings
Dynamic Programming
LCS
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
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
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
Different Methods to Reverse a String in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 148,
"s": 52,
"text": "Given two string S and Q. The task is to count the number of the common subsequence in S and T."
},
{
"code": null,
"e": 158,
"s": 148,
"text": "Examples:"
},
{
"code": null,
"e": 304,
"s": 158,
"text": "Input : S = “ajblqcpdz”, T = “aefcnbtdi” Output : 11 Common subsequences are : { “a”, “b”, “c”, “d”, “ab”, “bd”, “ad”, “ac”, “cd”, “abd”, “acd” }"
},
{
"code": null,
"e": 341,
"s": 304,
"text": "Input : S = “a”, T = “ab” Output : 1"
},
{
"code": null,
"e": 1298,
"s": 341,
"text": "To find the number of common subsequences in two string, say S and T, we use Dynamic Programming by defining a 2D array dp[][], where dp[i][j] is the number of common subsequences in the string S[0...i-1] and T[0....j-1]. Now, we can define dp[i][j] as = dp[i][j-1] + dp[i-1][j] + 1, when S[i-1] is equal to T[j-1] This is because when S[i-1] == S[j-1], using the above fact all the previous common sub-sequences are doubled as they get appended by one more character. Both dp[i][j-1] and dp[i-1][j] contain dp[i-1][j-1] and hence it gets added two times in our recurrence which takes care of doubling of count of all previous common sub-sequences. Addition of 1 in recurrence is for the latest character match : common sub-sequence made up of s1[i-1] and s2[j-1]= dp[i-1][j] + dp[i][j-1] – dp[i-1][j-1], when S[i-1] is not equal to T[j-1] Here we subtract dp[i-1][j-1] once because it is present in both dp[i][j – 1] and dp[i – 1][j] and gets added twice."
},
{
"code": null,
"e": 1346,
"s": 1298,
"text": "Below is the implementation of this approach: "
},
{
"code": null,
"e": 1350,
"s": 1346,
"text": "C++"
},
{
"code": null,
"e": 1355,
"s": 1350,
"text": "Java"
},
{
"code": null,
"e": 1363,
"s": 1355,
"text": "Python3"
},
{
"code": null,
"e": 1366,
"s": 1363,
"text": "C#"
},
{
"code": null,
"e": 1370,
"s": 1366,
"text": "PHP"
},
{
"code": null,
"e": 1381,
"s": 1370,
"text": "Javascript"
},
{
"code": "// C++ program to count common subsequence in two strings#include <bits/stdc++.h>using namespace std; // return the number of common subsequence in// two stringsint CommomSubsequencesCount(string s, string t){ int n1 = s.length(); int n2 = t.length(); int dp[n1+1][n2+1]; for (int i = 0; i <= n1; i++) { for (int j = 0; j <= n2; j++) { dp[i][j] = 0; } } // for each character of S for (int i = 1; i <= n1; i++) { // for each character in T for (int j = 1; j <= n2; j++) { // if character are same in both // the string if (s[i - 1] == t[j - 1]) dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j]; else dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]; } } return dp[n1][n2];} // Driver Programint main(){ string s = \"ajblqcpdz\"; string t = \"aefcnbtdi\"; cout << CommomSubsequencesCount(s, t) << endl; return 0;}",
"e": 2419,
"s": 1381,
"text": null
},
{
"code": "// Java program to count common subsequence in two stringspublic class GFG { // return the number of common subsequence in // two strings static int CommomSubsequencesCount(String s, String t) { int n1 = s.length(); int n2 = t.length(); int dp[][] = new int [n1+1][n2+1]; char ch1,ch2 ; for (int i = 0; i <= n1; i++) { for (int j = 0; j <= n2; j++) { dp[i][j] = 0; } } // for each character of S for (int i = 1; i <= n1; i++) { // for each character in T for (int j = 1; j <= n2; j++) { ch1 = s.charAt(i - 1); ch2 = t.charAt(j - 1); // if character are same in both // the string if (ch1 == ch2) dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j]; else dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]; } } return dp[n1][n2]; } // Driver code public static void main (String args[]){ String s = \"ajblqcpdz\"; String t = \"aefcnbtdi\"; System.out.println(CommomSubsequencesCount(s, t)); } // This code is contributed by ANKITRAI1}",
"e": 3848,
"s": 2419,
"text": null
},
{
"code": "# Python3 program to count common# subsequence in two strings # return the number of common subsequence# in two stringsdef CommomSubsequencesCount(s, t): n1 = len(s) n2 = len(t) dp = [[0 for i in range(n2 + 1)] for i in range(n1 + 1)] # for each character of S for i in range(1, n1 + 1): # for each character in T for j in range(1, n2 + 1): # if character are same in both # the string if (s[i - 1] == t[j - 1]): dp[i][j] = (1 + dp[i][j - 1] + dp[i - 1][j]) else: dp[i][j] = (dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]) return dp[n1][n2] # Driver Codes = \"ajblqcpdz\"t = \"aefcnbtdi\" print(CommomSubsequencesCount(s, t)) # This code is contributed by Mohit Kumar",
"e": 4718,
"s": 3848,
"text": null
},
{
"code": "// C# program to count common// subsequence in two stringsusing System; class GFG{ // return the number of common// subsequence in two stringsstatic int CommomSubsequencesCount(string s, string t){ int n1 = s.Length; int n2 = t.Length; int[,] dp = new int [n1 + 1, n2 + 1]; for (int i = 0; i <= n1; i++) { for (int j = 0; j <= n2; j++) { dp[i, j] = 0; } } // for each character of S for (int i = 1; i <= n1; i++) { // for each character in T for (int j = 1; j <= n2; j++) { // if character are same in // both the string if (s[i - 1] == t[j - 1]) dp[i, j] = 1 + dp[i, j - 1] + dp[i - 1, j]; else dp[i, j] = dp[i, j - 1] + dp[i - 1, j] - dp[i - 1, j - 1]; } } return dp[n1, n2];} // Driver codepublic static void Main (){ string s = \"ajblqcpdz\"; string t = \"aefcnbtdi\"; Console.Write(CommomSubsequencesCount(s, t));}} // This code is contributed// by ChitraNayal",
"e": 5954,
"s": 4718,
"text": null
},
{
"code": "<?php// PHP program to count common subsequence// in two strings // return the number of common subsequence// in two stringsfunction CommomSubsequencesCount($s, $t){ $n1 = strlen($s); $n2 = strlen($t); $dp = array(); for ($i = 0; $i <= $n1; $i++) { for ($j = 0; $j <= $n2; $j++) { $dp[$i][$j] = 0; } } // for each character of S for ($i = 1; $i <= $n1; $i++) { // for each character in T for ($j = 1; $j <= $n2; $j++) { // if character are same in both // the string if ($s[$i - 1] == $t[$j - 1]) $dp[$i][$j] = 1 + $dp[$i][$j - 1] + $dp[$i - 1][$j]; else $dp[$i][$j] = $dp[$i][$j - 1] + $dp[$i - 1][$j] - $dp[$i - 1][$j - 1]; } } return $dp[$n1][$n2];} // Driver Code$s = \"ajblqcpdz\";$t = \"aefcnbtdi\"; echo CommomSubsequencesCount($s, $t) .\"\\n\"; // This code is contributed// by Akanksha Rai?>",
"e": 7019,
"s": 5954,
"text": null
},
{
"code": "<script> // Javascript program to count common subsequence in two strings // return the number of common subsequence in// two stringsfunction CommomSubsequencesCount(s, t){ var n1 = s.length; var n2 = t.length; var dp = Array.from(Array(n1+1), ()=> Array(n2+1)); for (var i = 0; i <= n1; i++) { for (var j = 0; j <= n2; j++) { dp[i][j] = 0; } } // for each character of S for (var i = 1; i <= n1; i++) { // for each character in T for (var j = 1; j <= n2; j++) { // if character are same in both // the string if (s[i - 1] == t[j - 1]) dp[i][j] = 1 + dp[i][j - 1] + dp[i - 1][j]; else dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1]; } } return dp[n1][n2];} // Driver Programvar s = \"ajblqcpdz\";var t = \"aefcnbtdi\";document.write( CommomSubsequencesCount(s, t)); </script>",
"e": 8016,
"s": 7019,
"text": null
},
{
"code": null,
"e": 8019,
"s": 8016,
"text": "11"
},
{
"code": null,
"e": 8102,
"s": 8021,
"text": "Time Complexity : O(n1 * n2) Auxiliary Space : O(n1 * n2)Source : StackOverflow "
},
{
"code": null,
"e": 8110,
"s": 8102,
"text": "ankthon"
},
{
"code": null,
"e": 8116,
"s": 8110,
"text": "ukasp"
},
{
"code": null,
"e": 8131,
"s": 8116,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8144,
"s": 8131,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 8155,
"s": 8144,
"text": "nidhi_biet"
},
{
"code": null,
"e": 8161,
"s": 8155,
"text": "itsok"
},
{
"code": null,
"e": 8170,
"s": 8161,
"text": "sweetyty"
},
{
"code": null,
"e": 8174,
"s": 8170,
"text": "LCS"
},
{
"code": null,
"e": 8186,
"s": 8174,
"text": "subsequence"
},
{
"code": null,
"e": 8206,
"s": 8186,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8214,
"s": 8206,
"text": "Strings"
},
{
"code": null,
"e": 8222,
"s": 8214,
"text": "Strings"
},
{
"code": null,
"e": 8242,
"s": 8222,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8246,
"s": 8242,
"text": "LCS"
},
{
"code": null,
"e": 8344,
"s": 8246,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8371,
"s": 8344,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 8409,
"s": 8371,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 8442,
"s": 8409,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 8461,
"s": 8442,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 8496,
"s": 8461,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 8521,
"s": 8496,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 8581,
"s": 8521,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8596,
"s": 8581,
"text": "C++ Data Types"
},
{
"code": null,
"e": 8671,
"s": 8596,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
]
|
Simple Tic-Tac-Toe Game using JavaScript | 02 Feb, 2022
How to implement a 2-player Tic-Tac-Toe game using JavaScript?
It is quite easy to develop with some simple validations and error checks. Player-1 starts playing the game and both the players make their moves in consecutive turns. The player who makes a straight 3-block chain wins the game. This game is built on the front-end using simple logic and validation checks only.
Prerequisite: Basic knowledge of some front-end technologies like HTML, CSS, JavaScript.
View of Tic-Tac-Toe Game
Filename: index.html
HTML
<!DOCTYPE html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <!-- CSS file Included --> <link rel="stylesheet" type="text/css" href="tic.css"> <!-- JavaScript file included --> <script src="tic.js"></script></head> <body> <div id="main"> <h1>TIC TAC TOE</h1> <!-- Game Instructions --> <p id="ins">Game starts by just Tap on box<br><br>First Player starts as <b>Player X</b><br>And<br>Second Player as <b>Player 0</b> </p> <br><br> <!-- 3*3 grid of Boxes --> <input type="text" id="b1" onclick= "myfunc_3(); myfunc();" readonly> <input type="text" id="b2" onclick= "myfunc_4(); myfunc();" readonly> <input type="text" id="b3" onclick= "myfunc_5(); myfunc();" readonly> <br><br> <input type="text" id="b4" onclick= "myfunc_6(); myfunc();" readonly> <input type="text" id="b5" onclick= "myfunc_7(); myfunc();" readonly> <input type="text" id="b6" onclick= "myfunc_8(); myfunc();" readonly> <br><br> <input type="text" id="b7" onclick= "myfunc_9(); myfunc();" readonly> <input type="text" id="b8" onclick= "myfunc_10();myfunc();" readonly> <input type="text" id="b9" onclick= "myfunc_11();myfunc();" readonly> <!-- Grid end here --> <br><br><br> <!-- Button to reset game --> <button id="but" onclick="myfunc_2()"> RESET </button> <br><br> <!-- Space to show player turn --> <p id="print"></p> </div></body> </html>
Filename: tic.css
CSS
<style> /* CSS Code */ /* Heading */ h1 { color: orangered; font-size: 45px; } /* 3*3 Grid */ #b1, #b2, #b3, #b4, #b5, #b6, #b7, #b8, #b9 { width: 80px; height: 52px; margin: auto; border: 1px solid gray; border-radius: 6px; font-size: 30px; text-align: center; } /* Reset Button */ #but { box-sizing: border-box; width: 95px; height: 40px; border: 1px solid dodgerblue; margin: auto; border-radius: 4px; font-family: Verdana, Geneva, Tahoma, sans-serif; background-color: dodgerblue; color: white; font-size: 20px; cursor: pointer; } /* Player turn space */ #print { font-family: Verdana, Geneva, Tahoma, sans-serif; color: dodgerblue; font-size: 20px; } /* Main Container */ #main { text-align: center; } /* Game Instruction Text */ #ins { font-family: Verdana, Geneva, Tahoma, sans-serif; color: dodgerblue; font-size: 17px; }</style>
Filename: tic.js
JavaScript
// Function called whenever user tab on any boxfunction myfunc() { // Setting DOM to all boxes or input field var b1, b2, b3, b4, b5, b6, b7, b8, b9; b1 = document.getElementById("b1").value; b2 = document.getElementById("b2").value; b3 = document.getElementById("b3").value; b4 = document.getElementById("b4").value; b5 = document.getElementById("b5").value; b6 = document.getElementById("b6").value; b7 = document.getElementById("b7").value; b8 = document.getElementById("b8").value; b9 = document.getElementById("b9").value; // Checking if Player X won or not and after // that disabled all the other fields if ((b1 == 'x' || b1 == 'X') && (b2 == 'x' || b2 == 'X') && (b3 == 'x' || b3 == 'X')) { document.getElementById('print') .innerHTML = "Player X won"; document.getElementById("b4").disabled = true; document.getElementById("b5").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b8").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player X won'); } else if ((b1 == 'x' || b1 == 'X') && (b4 == 'x' || b4 == 'X') && (b7 == 'x' || b7 == 'X')) { document.getElementById('print') .innerHTML = "Player X won"; document.getElementById("b2").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b5").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b8").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player X won'); } else if ((b7 == 'x' || b7 == 'X') && (b8 == 'x' || b8 == 'X') && (b9 == 'x' || b9 == 'X')) { document.getElementById('print') .innerHTML = "Player X won"; document.getElementById("b1").disabled = true; document.getElementById("b2").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b5").disabled = true; document.getElementById("b6").disabled = true; window.alert('Player X won'); } else if ((b3 == 'x' || b3 == 'X') && (b6 == 'x' || b6 == 'X') && (b9 == 'x' || b9 == 'X')) { document.getElementById('print') .innerHTML = "Player X won"; document.getElementById("b1").disabled = true; document.getElementById("b2").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b5").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b8").disabled = true; window.alert('Player X won'); } else if ((b1 == 'x' || b1 == 'X') && (b5 == 'x' || b5 == 'X') && (b9 == 'x' || b9 == 'X')) { document.getElementById('print') .innerHTML = "Player X won"; document.getElementById("b2").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b8").disabled = true; window.alert('Player X won'); } else if ((b3 == 'x' || b3 == 'X') && (b5 == 'x' || b5 == 'X') && (b7 == 'x' || b7 == 'X')) { document.getElementById('print') .innerHTML = "Player X won"; document.getElementById("b1").disabled = true; document.getElementById("b2").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b8").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player X won'); } else if ((b2 == 'x' || b2 == 'X') && (b5 == 'x' || b5 == 'X') && (b8 == 'x' || b8 == 'X')) { document.getElementById('print') .innerHTML = "Player X won"; document.getElementById("b1").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player X won'); } else if ((b4 == 'x' || b4 == 'X') && (b5 == 'x' || b5 == 'X') && (b6 == 'x' || b6 == 'X')) { document.getElementById('print') .innerHTML = "Player X won"; document.getElementById("b1").disabled = true; document.getElementById("b2").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b8").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player X won'); } // Checking of Player X finish // Checking for Player 0 starts, Is player 0 won or // not and after that disabled all the other fields else if ((b1 == '0' || b1 == '0') && (b2 == '0' || b2 == '0') && (b3 == '0' || b3 == '0')) { document.getElementById('print') .innerHTML = "Player 0 won"; document.getElementById("b4").disabled = true; document.getElementById("b5").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b8").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player 0 won'); } else if ((b1 == '0' || b1 == '0') && (b4 == '0' || b4 == '0') && (b7 == '0' || b7 == '0')) { document.getElementById('print') .innerHTML = "Player 0 won"; document.getElementById("b2").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b5").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b8").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player 0 won'); } else if ((b7 == '0' || b7 == '0') && (b8 == '0' || b8 == '0') && (b9 == '0' || b9 == '0')) { document.getElementById('print') .innerHTML = "Player 0 won"; document.getElementById("b1").disabled = true; document.getElementById("b2").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b5").disabled = true; document.getElementById("b6").disabled = true; window.alert('Player 0 won'); } else if ((b3 == '0' || b3 == '0') && (b6 == '0' || b6 == '0') && (b9 == '0' || b9 == '0')) { document.getElementById('print') .innerHTML = "Player 0 won"; document.getElementById("b1").disabled = true; document.getElementById("b2").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b5").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b8").disabled = true; window.alert('Player 0 won'); } else if ((b1 == '0' || b1 == '0') && (b5 == '0' || b5 == '0') && (b9 == '0' || b9 == '0')) { document.getElementById('print') .innerHTML = "Player 0 won"; document.getElementById("b2").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b8").disabled = true; window.alert('Player 0 won'); } else if ((b3 == '0' || b3 == '0') && (b5 == '0' || b5 == '0') && (b7 == '0' || b7 == '0')) { document.getElementById('print') .innerHTML = "Player 0 won"; document.getElementById("b1").disabled = true; document.getElementById("b2").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b8").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player 0 won'); } else if ((b2 == '0' || b2 == '0') && (b5 == '0' || b5 == '0') && (b8 == '0' || b8 == '0')) { document.getElementById('print') .innerHTML = "Player 0 won"; document.getElementById("b1").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b4").disabled = true; document.getElementById("b6").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player 0 won'); } else if ((b4 == '0' || b4 == '0') && (b5 == '0' || b5 == '0') && (b6 == '0' || b6 == '0')) { document.getElementById('print') .innerHTML = "Player 0 won"; document.getElementById("b1").disabled = true; document.getElementById("b2").disabled = true; document.getElementById("b3").disabled = true; document.getElementById("b7").disabled = true; document.getElementById("b8").disabled = true; document.getElementById("b9").disabled = true; window.alert('Player 0 won'); } // Checking of Player 0 finish // Here, Checking about Tie else if ((b1 == 'X' || b1 == '0') && (b2 == 'X' || b2 == '0') && (b3 == 'X' || b3 == '0') && (b4 == 'X' || b4 == '0') && (b5 == 'X' || b5 == '0') && (b6 == 'X' || b6 == '0') && (b7 == 'X' || b7 == '0') && (b8 == 'X' || b8 == '0') && (b9 == 'X' || b9 == '0')) { document.getElementById('print') .innerHTML = "Match Tie"; window.alert('Match Tie'); } else { // Here, Printing Result if (flag == 1) { document.getElementById('print') .innerHTML = "Player X Turn"; } else { document.getElementById('print') .innerHTML = "Player 0 Turn"; } }} // Function to reset gamefunction myfunc_2() { location.reload(); document.getElementById('b1').value = ''; document.getElementById("b2").value = ''; document.getElementById("b3").value = ''; document.getElementById("b4").value = ''; document.getElementById("b5").value = ''; document.getElementById("b6").value = ''; document.getElementById("b7").value = ''; document.getElementById("b8").value = ''; document.getElementById("b9").value = ''; } // Here onwards, functions check turn of the player// and put accordingly value X or 0flag = 1;function myfunc_3() { if (flag == 1) { document.getElementById("b1").value = "X"; document.getElementById("b1").disabled = true; flag = 0; } else { document.getElementById("b1").value = "0"; document.getElementById("b1").disabled = true; flag = 1; }} function myfunc_4() { if (flag == 1) { document.getElementById("b2").value = "X"; document.getElementById("b2").disabled = true; flag = 0; } else { document.getElementById("b2").value = "0"; document.getElementById("b2").disabled = true; flag = 1; }} function myfunc_5() { if (flag == 1) { document.getElementById("b3").value = "X"; document.getElementById("b3").disabled = true; flag = 0; } else { document.getElementById("b3").value = "0"; document.getElementById("b3").disabled = true; flag = 1; }} function myfunc_6() { if (flag == 1) { document.getElementById("b4").value = "X"; document.getElementById("b4").disabled = true; flag = 0; } else { document.getElementById("b4").value = "0"; document.getElementById("b4").disabled = true; flag = 1; }} function myfunc_7() { if (flag == 1) { document.getElementById("b5").value = "X"; document.getElementById("b5").disabled = true; flag = 0; } else { document.getElementById("b5").value = "0"; document.getElementById("b5").disabled = true; flag = 1; }} function myfunc_8() { if (flag == 1) { document.getElementById("b6").value = "X"; document.getElementById("b6").disabled = true; flag = 0; } else { document.getElementById("b6").value = "0"; document.getElementById("b6").disabled = true; flag = 1; }} function myfunc_9() { if (flag == 1) { document.getElementById("b7").value = "X"; document.getElementById("b7").disabled = true; flag = 0; } else { document.getElementById("b7").value = "0"; document.getElementById("b7").disabled = true; flag = 1; }} function myfunc_10() { if (flag == 1) { document.getElementById("b8").value = "X"; document.getElementById("b8").disabled = true; flag = 0; } else { document.getElementById("b8").value = "0"; document.getElementById("b8").disabled = true; flag = 1; }} function myfunc_11() { if (flag == 1) { document.getElementById("b9").value = "X"; document.getElementById("b9").disabled = true; flag = 0; } else { document.getElementById("b9").value = "0"; document.getElementById("b9").disabled = true; flag = 1; }}
Step to run the program:
Run the index.html file by opening it in any browser.
Output:
When Player 'X' Won
Player X Won
When Player '0' Won
Player 0 Won
When Match is Tie
Match Tie
kalrap615
prachisoda1234
germanshephered48
CSS-Misc
HTML-Misc
JavaScript-Misc
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 118,
"s": 54,
"text": "How to implement a 2-player Tic-Tac-Toe game using JavaScript? "
},
{
"code": null,
"e": 433,
"s": 118,
"text": "It is quite easy to develop with some simple validations and error checks. Player-1 starts playing the game and both the players make their moves in consecutive turns. The player who makes a straight 3-block chain wins the game. This game is built on the front-end using simple logic and validation checks only. "
},
{
"code": null,
"e": 523,
"s": 433,
"text": "Prerequisite: Basic knowledge of some front-end technologies like HTML, CSS, JavaScript. "
},
{
"code": null,
"e": 548,
"s": 523,
"text": "View of Tic-Tac-Toe Game"
},
{
"code": null,
"e": 569,
"s": 548,
"text": "Filename: index.html"
},
{
"code": null,
"e": 574,
"s": 569,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <!-- CSS file Included --> <link rel=\"stylesheet\" type=\"text/css\" href=\"tic.css\"> <!-- JavaScript file included --> <script src=\"tic.js\"></script></head> <body> <div id=\"main\"> <h1>TIC TAC TOE</h1> <!-- Game Instructions --> <p id=\"ins\">Game starts by just Tap on box<br><br>First Player starts as <b>Player X</b><br>And<br>Second Player as <b>Player 0</b> </p> <br><br> <!-- 3*3 grid of Boxes --> <input type=\"text\" id=\"b1\" onclick= \"myfunc_3(); myfunc();\" readonly> <input type=\"text\" id=\"b2\" onclick= \"myfunc_4(); myfunc();\" readonly> <input type=\"text\" id=\"b3\" onclick= \"myfunc_5(); myfunc();\" readonly> <br><br> <input type=\"text\" id=\"b4\" onclick= \"myfunc_6(); myfunc();\" readonly> <input type=\"text\" id=\"b5\" onclick= \"myfunc_7(); myfunc();\" readonly> <input type=\"text\" id=\"b6\" onclick= \"myfunc_8(); myfunc();\" readonly> <br><br> <input type=\"text\" id=\"b7\" onclick= \"myfunc_9(); myfunc();\" readonly> <input type=\"text\" id=\"b8\" onclick= \"myfunc_10();myfunc();\" readonly> <input type=\"text\" id=\"b9\" onclick= \"myfunc_11();myfunc();\" readonly> <!-- Grid end here --> <br><br><br> <!-- Button to reset game --> <button id=\"but\" onclick=\"myfunc_2()\"> RESET </button> <br><br> <!-- Space to show player turn --> <p id=\"print\"></p> </div></body> </html>",
"e": 2353,
"s": 574,
"text": null
},
{
"code": null,
"e": 2372,
"s": 2353,
"text": "Filename: tic.css "
},
{
"code": null,
"e": 2376,
"s": 2372,
"text": "CSS"
},
{
"code": "<style> /* CSS Code */ /* Heading */ h1 { color: orangered; font-size: 45px; } /* 3*3 Grid */ #b1, #b2, #b3, #b4, #b5, #b6, #b7, #b8, #b9 { width: 80px; height: 52px; margin: auto; border: 1px solid gray; border-radius: 6px; font-size: 30px; text-align: center; } /* Reset Button */ #but { box-sizing: border-box; width: 95px; height: 40px; border: 1px solid dodgerblue; margin: auto; border-radius: 4px; font-family: Verdana, Geneva, Tahoma, sans-serif; background-color: dodgerblue; color: white; font-size: 20px; cursor: pointer; } /* Player turn space */ #print { font-family: Verdana, Geneva, Tahoma, sans-serif; color: dodgerblue; font-size: 20px; } /* Main Container */ #main { text-align: center; } /* Game Instruction Text */ #ins { font-family: Verdana, Geneva, Tahoma, sans-serif; color: dodgerblue; font-size: 17px; }</style>",
"e": 3516,
"s": 2376,
"text": null
},
{
"code": null,
"e": 3534,
"s": 3516,
"text": "Filename: tic.js "
},
{
"code": null,
"e": 3545,
"s": 3534,
"text": "JavaScript"
},
{
"code": "// Function called whenever user tab on any boxfunction myfunc() { // Setting DOM to all boxes or input field var b1, b2, b3, b4, b5, b6, b7, b8, b9; b1 = document.getElementById(\"b1\").value; b2 = document.getElementById(\"b2\").value; b3 = document.getElementById(\"b3\").value; b4 = document.getElementById(\"b4\").value; b5 = document.getElementById(\"b5\").value; b6 = document.getElementById(\"b6\").value; b7 = document.getElementById(\"b7\").value; b8 = document.getElementById(\"b8\").value; b9 = document.getElementById(\"b9\").value; // Checking if Player X won or not and after // that disabled all the other fields if ((b1 == 'x' || b1 == 'X') && (b2 == 'x' || b2 == 'X') && (b3 == 'x' || b3 == 'X')) { document.getElementById('print') .innerHTML = \"Player X won\"; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b5\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b8\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player X won'); } else if ((b1 == 'x' || b1 == 'X') && (b4 == 'x' || b4 == 'X') && (b7 == 'x' || b7 == 'X')) { document.getElementById('print') .innerHTML = \"Player X won\"; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b5\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b8\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player X won'); } else if ((b7 == 'x' || b7 == 'X') && (b8 == 'x' || b8 == 'X') && (b9 == 'x' || b9 == 'X')) { document.getElementById('print') .innerHTML = \"Player X won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b5\").disabled = true; document.getElementById(\"b6\").disabled = true; window.alert('Player X won'); } else if ((b3 == 'x' || b3 == 'X') && (b6 == 'x' || b6 == 'X') && (b9 == 'x' || b9 == 'X')) { document.getElementById('print') .innerHTML = \"Player X won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b5\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b8\").disabled = true; window.alert('Player X won'); } else if ((b1 == 'x' || b1 == 'X') && (b5 == 'x' || b5 == 'X') && (b9 == 'x' || b9 == 'X')) { document.getElementById('print') .innerHTML = \"Player X won\"; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b8\").disabled = true; window.alert('Player X won'); } else if ((b3 == 'x' || b3 == 'X') && (b5 == 'x' || b5 == 'X') && (b7 == 'x' || b7 == 'X')) { document.getElementById('print') .innerHTML = \"Player X won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b8\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player X won'); } else if ((b2 == 'x' || b2 == 'X') && (b5 == 'x' || b5 == 'X') && (b8 == 'x' || b8 == 'X')) { document.getElementById('print') .innerHTML = \"Player X won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player X won'); } else if ((b4 == 'x' || b4 == 'X') && (b5 == 'x' || b5 == 'X') && (b6 == 'x' || b6 == 'X')) { document.getElementById('print') .innerHTML = \"Player X won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b8\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player X won'); } // Checking of Player X finish // Checking for Player 0 starts, Is player 0 won or // not and after that disabled all the other fields else if ((b1 == '0' || b1 == '0') && (b2 == '0' || b2 == '0') && (b3 == '0' || b3 == '0')) { document.getElementById('print') .innerHTML = \"Player 0 won\"; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b5\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b8\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player 0 won'); } else if ((b1 == '0' || b1 == '0') && (b4 == '0' || b4 == '0') && (b7 == '0' || b7 == '0')) { document.getElementById('print') .innerHTML = \"Player 0 won\"; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b5\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b8\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player 0 won'); } else if ((b7 == '0' || b7 == '0') && (b8 == '0' || b8 == '0') && (b9 == '0' || b9 == '0')) { document.getElementById('print') .innerHTML = \"Player 0 won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b5\").disabled = true; document.getElementById(\"b6\").disabled = true; window.alert('Player 0 won'); } else if ((b3 == '0' || b3 == '0') && (b6 == '0' || b6 == '0') && (b9 == '0' || b9 == '0')) { document.getElementById('print') .innerHTML = \"Player 0 won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b5\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b8\").disabled = true; window.alert('Player 0 won'); } else if ((b1 == '0' || b1 == '0') && (b5 == '0' || b5 == '0') && (b9 == '0' || b9 == '0')) { document.getElementById('print') .innerHTML = \"Player 0 won\"; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b8\").disabled = true; window.alert('Player 0 won'); } else if ((b3 == '0' || b3 == '0') && (b5 == '0' || b5 == '0') && (b7 == '0' || b7 == '0')) { document.getElementById('print') .innerHTML = \"Player 0 won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b8\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player 0 won'); } else if ((b2 == '0' || b2 == '0') && (b5 == '0' || b5 == '0') && (b8 == '0' || b8 == '0')) { document.getElementById('print') .innerHTML = \"Player 0 won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b4\").disabled = true; document.getElementById(\"b6\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player 0 won'); } else if ((b4 == '0' || b4 == '0') && (b5 == '0' || b5 == '0') && (b6 == '0' || b6 == '0')) { document.getElementById('print') .innerHTML = \"Player 0 won\"; document.getElementById(\"b1\").disabled = true; document.getElementById(\"b2\").disabled = true; document.getElementById(\"b3\").disabled = true; document.getElementById(\"b7\").disabled = true; document.getElementById(\"b8\").disabled = true; document.getElementById(\"b9\").disabled = true; window.alert('Player 0 won'); } // Checking of Player 0 finish // Here, Checking about Tie else if ((b1 == 'X' || b1 == '0') && (b2 == 'X' || b2 == '0') && (b3 == 'X' || b3 == '0') && (b4 == 'X' || b4 == '0') && (b5 == 'X' || b5 == '0') && (b6 == 'X' || b6 == '0') && (b7 == 'X' || b7 == '0') && (b8 == 'X' || b8 == '0') && (b9 == 'X' || b9 == '0')) { document.getElementById('print') .innerHTML = \"Match Tie\"; window.alert('Match Tie'); } else { // Here, Printing Result if (flag == 1) { document.getElementById('print') .innerHTML = \"Player X Turn\"; } else { document.getElementById('print') .innerHTML = \"Player 0 Turn\"; } }} // Function to reset gamefunction myfunc_2() { location.reload(); document.getElementById('b1').value = ''; document.getElementById(\"b2\").value = ''; document.getElementById(\"b3\").value = ''; document.getElementById(\"b4\").value = ''; document.getElementById(\"b5\").value = ''; document.getElementById(\"b6\").value = ''; document.getElementById(\"b7\").value = ''; document.getElementById(\"b8\").value = ''; document.getElementById(\"b9\").value = ''; } // Here onwards, functions check turn of the player// and put accordingly value X or 0flag = 1;function myfunc_3() { if (flag == 1) { document.getElementById(\"b1\").value = \"X\"; document.getElementById(\"b1\").disabled = true; flag = 0; } else { document.getElementById(\"b1\").value = \"0\"; document.getElementById(\"b1\").disabled = true; flag = 1; }} function myfunc_4() { if (flag == 1) { document.getElementById(\"b2\").value = \"X\"; document.getElementById(\"b2\").disabled = true; flag = 0; } else { document.getElementById(\"b2\").value = \"0\"; document.getElementById(\"b2\").disabled = true; flag = 1; }} function myfunc_5() { if (flag == 1) { document.getElementById(\"b3\").value = \"X\"; document.getElementById(\"b3\").disabled = true; flag = 0; } else { document.getElementById(\"b3\").value = \"0\"; document.getElementById(\"b3\").disabled = true; flag = 1; }} function myfunc_6() { if (flag == 1) { document.getElementById(\"b4\").value = \"X\"; document.getElementById(\"b4\").disabled = true; flag = 0; } else { document.getElementById(\"b4\").value = \"0\"; document.getElementById(\"b4\").disabled = true; flag = 1; }} function myfunc_7() { if (flag == 1) { document.getElementById(\"b5\").value = \"X\"; document.getElementById(\"b5\").disabled = true; flag = 0; } else { document.getElementById(\"b5\").value = \"0\"; document.getElementById(\"b5\").disabled = true; flag = 1; }} function myfunc_8() { if (flag == 1) { document.getElementById(\"b6\").value = \"X\"; document.getElementById(\"b6\").disabled = true; flag = 0; } else { document.getElementById(\"b6\").value = \"0\"; document.getElementById(\"b6\").disabled = true; flag = 1; }} function myfunc_9() { if (flag == 1) { document.getElementById(\"b7\").value = \"X\"; document.getElementById(\"b7\").disabled = true; flag = 0; } else { document.getElementById(\"b7\").value = \"0\"; document.getElementById(\"b7\").disabled = true; flag = 1; }} function myfunc_10() { if (flag == 1) { document.getElementById(\"b8\").value = \"X\"; document.getElementById(\"b8\").disabled = true; flag = 0; } else { document.getElementById(\"b8\").value = \"0\"; document.getElementById(\"b8\").disabled = true; flag = 1; }} function myfunc_11() { if (flag == 1) { document.getElementById(\"b9\").value = \"X\"; document.getElementById(\"b9\").disabled = true; flag = 0; } else { document.getElementById(\"b9\").value = \"0\"; document.getElementById(\"b9\").disabled = true; flag = 1; }}",
"e": 17216,
"s": 3545,
"text": null
},
{
"code": null,
"e": 17241,
"s": 17216,
"text": "Step to run the program:"
},
{
"code": null,
"e": 17295,
"s": 17241,
"text": "Run the index.html file by opening it in any browser."
},
{
"code": null,
"e": 17304,
"s": 17295,
"text": "Output: "
},
{
"code": null,
"e": 17324,
"s": 17304,
"text": "When Player 'X' Won"
},
{
"code": null,
"e": 17337,
"s": 17324,
"text": "Player X Won"
},
{
"code": null,
"e": 17357,
"s": 17337,
"text": "When Player '0' Won"
},
{
"code": null,
"e": 17370,
"s": 17357,
"text": "Player 0 Won"
},
{
"code": null,
"e": 17388,
"s": 17370,
"text": "When Match is Tie"
},
{
"code": null,
"e": 17398,
"s": 17388,
"text": "Match Tie"
},
{
"code": null,
"e": 17408,
"s": 17398,
"text": "kalrap615"
},
{
"code": null,
"e": 17423,
"s": 17408,
"text": "prachisoda1234"
},
{
"code": null,
"e": 17441,
"s": 17423,
"text": "germanshephered48"
},
{
"code": null,
"e": 17450,
"s": 17441,
"text": "CSS-Misc"
},
{
"code": null,
"e": 17460,
"s": 17450,
"text": "HTML-Misc"
},
{
"code": null,
"e": 17476,
"s": 17460,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 17500,
"s": 17476,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 17504,
"s": 17500,
"text": "CSS"
},
{
"code": null,
"e": 17509,
"s": 17504,
"text": "HTML"
},
{
"code": null,
"e": 17520,
"s": 17509,
"text": "JavaScript"
},
{
"code": null,
"e": 17539,
"s": 17520,
"text": "Technical Scripter"
},
{
"code": null,
"e": 17556,
"s": 17539,
"text": "Web Technologies"
},
{
"code": null,
"e": 17561,
"s": 17556,
"text": "HTML"
},
{
"code": null,
"e": 17659,
"s": 17561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17707,
"s": 17659,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 17769,
"s": 17707,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 17819,
"s": 17769,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 17877,
"s": 17819,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 17927,
"s": 17877,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 17975,
"s": 17927,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 18037,
"s": 17975,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 18087,
"s": 18037,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 18111,
"s": 18087,
"text": "REST API (Introduction)"
}
]
|
PySpark Groupby | 19 Dec, 2021
In this article, we are going to discuss Groupby function in PySpark using Python.
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.show()
Output:
In PySpark, groupBy() is used to collect the identical data into groups on the PySpark DataFrame and perform aggregate functions on the grouped data
count(): This will return the count of rows for each group.
dataframe.groupBy(‘column_name_group’).count()
mean(): This will return the mean of values for each group.
dataframe.groupBy(‘column_name_group’).mean(‘column_name’)
max(): This will return the maximum of values for each group.
dataframe.groupBy(‘column_name_group’).max(‘column_name’)
min(): This will return the minimum of values for each group.
dataframe.groupBy(‘column_name_group’).min(‘column_name’)
sum(): This will return the total values for each group.
dataframe.groupBy(‘column_name_group’).sum(‘column_name’)
avg(): This will return the average for values for each group.
dataframe.groupBy(‘column_name_group’).avg(‘column_name’).show()
We have to use any one of the functions with groupby while using the method
Syntax: dataframe.groupBy(‘column_name_group’).aggregate_operation(‘column_name’)
Groupby with DEPT along FEE with sum().
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT along FEE with sum()dataframe.groupBy('DEPT').sum('FEE').show()
Output:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT along FEE with min()dataframe.groupBy('DEPT').min('FEE').show()
Output:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT along FEE with max()dataframe.groupBy('DEPT').max('FEE').show()
Output:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT along FEE with avg()dataframe.groupBy('DEPT').avg('FEE').show()
Output:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with count()dataframe.groupBy('DEPT').count().show()
Output:
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with mean()dataframe.groupBy('DEPT').mean('FEE').show()
Output:
Here we are going to use groupby() on multiple columns.
Syntax: dataframe.groupBy(‘column_name_group1′,’column_name_group2′,............,’column_name_group n’).aggregate_operation(‘column_name’)
Python3
# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT and NAME with mean()dataframe.groupBy('DEPT', 'NAME').mean('FEE').show()
Output:
We can also groupBy and aggregate on multiple columns at a time by using the following syntax:
dataframe.groupBy(“group_column”).agg( max(“column_name”),sum(“column_name”),min(“column_name”),mean(“column_name”),count(“column_name”)).show()
We have to import these agg functions from the module sql.functions.
Example:
Python3
# importing moduleimport pyspark # import sum, min,avg,count,mean and max functionsfrom pyspark.sql.functions import sum, max, min, avg, count, mean # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [["1", "sravan", "IT", 45000], ["2", "ojaswi", "CS", 85000], ["3", "rohith", "CS", 41000], ["4", "sridevi", "IT", 56000], ["5", "bobby", "ECE", 45000], ["6", "gayatri", "ECE", 49000], ["7", "gnanesh", "CS", 45000], ["8", "bhanu", "Mech", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum() , min() , max()dataframe.groupBy("DEPT").agg(max("FEE"), sum("FEE"), min("FEE"), mean("FEE"), count("FEE")).show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "In this article, we are going to discuss Groupby function in PySpark using Python."
},
{
"code": null,
"e": 119,
"s": 111,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # displaydataframe.show()",
"e": 867,
"s": 119,
"text": null
},
{
"code": null,
"e": 875,
"s": 867,
"text": "Output:"
},
{
"code": null,
"e": 1025,
"s": 875,
"text": "In PySpark, groupBy() is used to collect the identical data into groups on the PySpark DataFrame and perform aggregate functions on the grouped data"
},
{
"code": null,
"e": 1085,
"s": 1025,
"text": "count(): This will return the count of rows for each group."
},
{
"code": null,
"e": 1132,
"s": 1085,
"text": "dataframe.groupBy(‘column_name_group’).count()"
},
{
"code": null,
"e": 1192,
"s": 1132,
"text": "mean(): This will return the mean of values for each group."
},
{
"code": null,
"e": 1251,
"s": 1192,
"text": "dataframe.groupBy(‘column_name_group’).mean(‘column_name’)"
},
{
"code": null,
"e": 1313,
"s": 1251,
"text": "max(): This will return the maximum of values for each group."
},
{
"code": null,
"e": 1371,
"s": 1313,
"text": "dataframe.groupBy(‘column_name_group’).max(‘column_name’)"
},
{
"code": null,
"e": 1433,
"s": 1371,
"text": "min(): This will return the minimum of values for each group."
},
{
"code": null,
"e": 1491,
"s": 1433,
"text": "dataframe.groupBy(‘column_name_group’).min(‘column_name’)"
},
{
"code": null,
"e": 1548,
"s": 1491,
"text": "sum(): This will return the total values for each group."
},
{
"code": null,
"e": 1606,
"s": 1548,
"text": "dataframe.groupBy(‘column_name_group’).sum(‘column_name’)"
},
{
"code": null,
"e": 1669,
"s": 1606,
"text": "avg(): This will return the average for values for each group."
},
{
"code": null,
"e": 1734,
"s": 1669,
"text": "dataframe.groupBy(‘column_name_group’).avg(‘column_name’).show()"
},
{
"code": null,
"e": 1810,
"s": 1734,
"text": "We have to use any one of the functions with groupby while using the method"
},
{
"code": null,
"e": 1892,
"s": 1810,
"text": "Syntax: dataframe.groupBy(‘column_name_group’).aggregate_operation(‘column_name’)"
},
{
"code": null,
"e": 1932,
"s": 1892,
"text": "Groupby with DEPT along FEE with sum()."
},
{
"code": null,
"e": 1940,
"s": 1932,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT along FEE with sum()dataframe.groupBy('DEPT').sum('FEE').show()",
"e": 2746,
"s": 1940,
"text": null
},
{
"code": null,
"e": 2754,
"s": 2746,
"text": "Output:"
},
{
"code": null,
"e": 2762,
"s": 2754,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT along FEE with min()dataframe.groupBy('DEPT').min('FEE').show()",
"e": 3568,
"s": 2762,
"text": null
},
{
"code": null,
"e": 3576,
"s": 3568,
"text": "Output:"
},
{
"code": null,
"e": 3584,
"s": 3576,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT along FEE with max()dataframe.groupBy('DEPT').max('FEE').show()",
"e": 4390,
"s": 3584,
"text": null
},
{
"code": null,
"e": 4398,
"s": 4390,
"text": "Output:"
},
{
"code": null,
"e": 4406,
"s": 4398,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT along FEE with avg()dataframe.groupBy('DEPT').avg('FEE').show()",
"e": 5212,
"s": 4406,
"text": null
},
{
"code": null,
"e": 5220,
"s": 5212,
"text": "Output:"
},
{
"code": null,
"e": 5228,
"s": 5220,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with count()dataframe.groupBy('DEPT').count().show()",
"e": 6024,
"s": 5228,
"text": null
},
{
"code": null,
"e": 6032,
"s": 6024,
"text": "Output:"
},
{
"code": null,
"e": 6040,
"s": 6032,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with mean()dataframe.groupBy('DEPT').mean('FEE').show()",
"e": 6839,
"s": 6040,
"text": null
},
{
"code": null,
"e": 6847,
"s": 6839,
"text": "Output:"
},
{
"code": null,
"e": 6903,
"s": 6847,
"text": "Here we are going to use groupby() on multiple columns."
},
{
"code": null,
"e": 7042,
"s": 6903,
"text": "Syntax: dataframe.groupBy(‘column_name_group1′,’column_name_group2′,............,’column_name_group n’).aggregate_operation(‘column_name’)"
},
{
"code": null,
"e": 7050,
"s": 7042,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT and NAME with mean()dataframe.groupBy('DEPT', 'NAME').mean('FEE').show()",
"e": 7865,
"s": 7050,
"text": null
},
{
"code": null,
"e": 7873,
"s": 7865,
"text": "Output:"
},
{
"code": null,
"e": 7969,
"s": 7873,
"text": "We can also groupBy and aggregate on multiple columns at a time by using the following syntax:"
},
{
"code": null,
"e": 8114,
"s": 7969,
"text": "dataframe.groupBy(“group_column”).agg( max(“column_name”),sum(“column_name”),min(“column_name”),mean(“column_name”),count(“column_name”)).show()"
},
{
"code": null,
"e": 8183,
"s": 8114,
"text": "We have to import these agg functions from the module sql.functions."
},
{
"code": null,
"e": 8192,
"s": 8183,
"text": "Example:"
},
{
"code": null,
"e": 8200,
"s": 8192,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # import sum, min,avg,count,mean and max functionsfrom pyspark.sql.functions import sum, max, min, avg, count, mean # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of student datadata = [[\"1\", \"sravan\", \"IT\", 45000], [\"2\", \"ojaswi\", \"CS\", 85000], [\"3\", \"rohith\", \"CS\", 41000], [\"4\", \"sridevi\", \"IT\", 56000], [\"5\", \"bobby\", \"ECE\", 45000], [\"6\", \"gayatri\", \"ECE\", 49000], [\"7\", \"gnanesh\", \"CS\", 45000], [\"8\", \"bhanu\", \"Mech\", 21000] ] # specify column namescolumns = ['ID', 'NAME', 'DEPT', 'FEE'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # Groupby with DEPT with sum() , min() , max()dataframe.groupBy(\"DEPT\").agg(max(\"FEE\"), sum(\"FEE\"), min(\"FEE\"), mean(\"FEE\"), count(\"FEE\")).show()",
"e": 9245,
"s": 8200,
"text": null
},
{
"code": null,
"e": 9253,
"s": 9245,
"text": "Output:"
},
{
"code": null,
"e": 9260,
"s": 9253,
"text": "Picked"
},
{
"code": null,
"e": 9275,
"s": 9260,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 9282,
"s": 9275,
"text": "Python"
}
]
|
Perl | Passing Complex Parameters to a Subroutine | 07 May, 2019
Prerequisite: Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language, the user wants to reuse the code. So the user puts the section of code in a function or subroutine so that there will be no need to rewrite the same code again and again. For this reason, function or subroutine is used in every programming language. These functions or subroutines can take various different types of data structures as parameters. Some of these are explained below:
Passing Lists or Arrays to a SubroutinePassing References to a SubroutinePassing Hashes to a SubroutinePassing File Handles to a Subroutine
Passing Lists or Arrays to a Subroutine
Passing References to a Subroutine
Passing Hashes to a Subroutine
Passing File Handles to a Subroutine
Passing Lists or Arrays to a Subroutine: An array or list can be passed to the subroutine as a parameter and an array variable @_ is used to accept the list value inside of the subroutine or function.
Example 1: Here a single list is passed to the subroutine and their elements are displayed.
#!/usr/bin/perl # Defining Subroutinesub Display_List { # array variable to store # the passed arguments my @List1 = @_; # Printing the passed list elements print "Given list is @List1\n"; } # Driver Code # passing list @list = (1, 2, 3, 4); # Calling Subroutine with # list parameter Display_List(@list);
Given list is 1 2 3 4
Example 2: Here two lists are passed to the subroutine and their elements are displayed.
#!/usr/bin/perl # Defining Subroutinesub Display_List { # array variable to store # the passed arguments my @List3 = @_; # Printing the passed lists' elements print "Given lists' elements are @List3\n"; } # Driver Code # passing lists@List1 = (1, 2, 3, 4); @List2 = (10, 20, 30, 40); # Calling Subroutine with # list parametersDisplay_List(@List1, @List2);
Given lists' elements are 1 2 3 4 10 20 30 40
Example 3: Here a scalar argument and list is passed to the subroutine and their elements are displayed.
#!/usr/bin/perl # Defining Subroutinesub Display_List { # array variable to store # the passed arguments my @List2 = @_; # Printing the passed list and scalar elements print "List and scalar elements are @List2\n"; } # Driver Code # passing lists@List = (1, 2, 3, 4); # passing scalar argument $scalar = 100; # Calling Subroutine with # list parametersDisplay_List(@List, $scalar);
List and scalar elements are 1 2 3 4 100
Passing References to a Subroutine: References can also be passed to the subroutines as a parameter. Here the reference of the given array is passed to the subroutine and the maximum value of array elements is returned.
Example:
#!/usr/bin/perluse warnings;use strict; # Creating an array of some elementsmy @Array = (10, 20, 30, 40, 50); # Making reference of the above array# and calling the subroutine with # reference of the array as the parametermy $m = max(\@Array); # Defining subroutinesub max{ # Getting the array elements my $Array_ref = $_[0]; my $k = $Array_ref->[0]; # Iterating over each element of the # array and finding maximum value for(@$Array_ref) { $k = $_ if($k < $_); } print "The max of @Array is $k\n";}
The max of 10 20 30 40 50 is 50
Passing Hash to a Subroutine: A Hash can also be passed to a subroutine as a parameter and its key-value pair is displayed.
Example:
#!/usr/bin/perl # Subroutine definition sub Display_Hash { # Hash variable to store # the passed arguments my (%Hash_var) = @_; # Displaying the passed list elements foreach my $key (keys %Hash_var) { my $value = $Hash_var{$key}; print "$key : $value\n"; } } # Driver Code # defining hash %Hash = ('Company' => 'GeeksforGeeks', 'Location' => 'Noida'); # calling Subroutine with hash parameter Display_Hash(%Hash);
Company : GeeksforGeeks
Location : Noida
Passing File Handles to a Subroutine: For creating a file or accessing the file contents one needs a filehandle which is nothing but a structure which is used along with the operators to access the file in a certain mode like reading, writing, appending, etc. FileHandles can also be passed to a subroutine as a parameter to perform various operations on Files.In the below example, a filehandle is passed to a subroutine:-Example:
#!/usr/bin/perl sub printem{ my $file = shift; while (<$file>) { print; }} open(fh, "Hello.txt") or die "File '$filename' can't be opened"; printem *fh;
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | Polymorphism in OOPs
Perl | length() Function
Perl | Boolean Values
Perl | Basic Syntax of a Perl Program
Perl | ne operator
Hello World Program in Perl
Perl | join() Function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 74,
"s": 28,
"text": "Prerequisite: Perl | Subroutines or Functions"
},
{
"code": null,
"e": 582,
"s": 74,
"text": "A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language, the user wants to reuse the code. So the user puts the section of code in a function or subroutine so that there will be no need to rewrite the same code again and again. For this reason, function or subroutine is used in every programming language. These functions or subroutines can take various different types of data structures as parameters. Some of these are explained below:"
},
{
"code": null,
"e": 722,
"s": 582,
"text": "Passing Lists or Arrays to a SubroutinePassing References to a SubroutinePassing Hashes to a SubroutinePassing File Handles to a Subroutine"
},
{
"code": null,
"e": 762,
"s": 722,
"text": "Passing Lists or Arrays to a Subroutine"
},
{
"code": null,
"e": 797,
"s": 762,
"text": "Passing References to a Subroutine"
},
{
"code": null,
"e": 828,
"s": 797,
"text": "Passing Hashes to a Subroutine"
},
{
"code": null,
"e": 865,
"s": 828,
"text": "Passing File Handles to a Subroutine"
},
{
"code": null,
"e": 1066,
"s": 865,
"text": "Passing Lists or Arrays to a Subroutine: An array or list can be passed to the subroutine as a parameter and an array variable @_ is used to accept the list value inside of the subroutine or function."
},
{
"code": null,
"e": 1158,
"s": 1066,
"text": "Example 1: Here a single list is passed to the subroutine and their elements are displayed."
},
{
"code": "#!/usr/bin/perl # Defining Subroutinesub Display_List { # array variable to store # the passed arguments my @List1 = @_; # Printing the passed list elements print \"Given list is @List1\\n\"; } # Driver Code # passing list @list = (1, 2, 3, 4); # Calling Subroutine with # list parameter Display_List(@list); ",
"e": 1508,
"s": 1158,
"text": null
},
{
"code": null,
"e": 1531,
"s": 1508,
"text": "Given list is 1 2 3 4\n"
},
{
"code": null,
"e": 1620,
"s": 1531,
"text": "Example 2: Here two lists are passed to the subroutine and their elements are displayed."
},
{
"code": "#!/usr/bin/perl # Defining Subroutinesub Display_List { # array variable to store # the passed arguments my @List3 = @_; # Printing the passed lists' elements print \"Given lists' elements are @List3\\n\"; } # Driver Code # passing lists@List1 = (1, 2, 3, 4); @List2 = (10, 20, 30, 40); # Calling Subroutine with # list parametersDisplay_List(@List1, @List2); ",
"e": 2020,
"s": 1620,
"text": null
},
{
"code": null,
"e": 2067,
"s": 2020,
"text": "Given lists' elements are 1 2 3 4 10 20 30 40\n"
},
{
"code": null,
"e": 2172,
"s": 2067,
"text": "Example 3: Here a scalar argument and list is passed to the subroutine and their elements are displayed."
},
{
"code": "#!/usr/bin/perl # Defining Subroutinesub Display_List { # array variable to store # the passed arguments my @List2 = @_; # Printing the passed list and scalar elements print \"List and scalar elements are @List2\\n\"; } # Driver Code # passing lists@List = (1, 2, 3, 4); # passing scalar argument $scalar = 100; # Calling Subroutine with # list parametersDisplay_List(@List, $scalar); ",
"e": 2598,
"s": 2172,
"text": null
},
{
"code": null,
"e": 2640,
"s": 2598,
"text": "List and scalar elements are 1 2 3 4 100\n"
},
{
"code": null,
"e": 2860,
"s": 2640,
"text": "Passing References to a Subroutine: References can also be passed to the subroutines as a parameter. Here the reference of the given array is passed to the subroutine and the maximum value of array elements is returned."
},
{
"code": null,
"e": 2869,
"s": 2860,
"text": "Example:"
},
{
"code": "#!/usr/bin/perluse warnings;use strict; # Creating an array of some elementsmy @Array = (10, 20, 30, 40, 50); # Making reference of the above array# and calling the subroutine with # reference of the array as the parametermy $m = max(\\@Array); # Defining subroutinesub max{ # Getting the array elements my $Array_ref = $_[0]; my $k = $Array_ref->[0]; # Iterating over each element of the # array and finding maximum value for(@$Array_ref) { $k = $_ if($k < $_); } print \"The max of @Array is $k\\n\";}",
"e": 3415,
"s": 2869,
"text": null
},
{
"code": null,
"e": 3448,
"s": 3415,
"text": "The max of 10 20 30 40 50 is 50\n"
},
{
"code": null,
"e": 3572,
"s": 3448,
"text": "Passing Hash to a Subroutine: A Hash can also be passed to a subroutine as a parameter and its key-value pair is displayed."
},
{
"code": null,
"e": 3581,
"s": 3572,
"text": "Example:"
},
{
"code": "#!/usr/bin/perl # Subroutine definition sub Display_Hash { # Hash variable to store # the passed arguments my (%Hash_var) = @_; # Displaying the passed list elements foreach my $key (keys %Hash_var) { my $value = $Hash_var{$key}; print \"$key : $value\\n\"; } } # Driver Code # defining hash %Hash = ('Company' => 'GeeksforGeeks', 'Location' => 'Noida'); # calling Subroutine with hash parameter Display_Hash(%Hash); ",
"e": 4072,
"s": 3581,
"text": null
},
{
"code": null,
"e": 4114,
"s": 4072,
"text": "Company : GeeksforGeeks\nLocation : Noida\n"
},
{
"code": null,
"e": 4546,
"s": 4114,
"text": "Passing File Handles to a Subroutine: For creating a file or accessing the file contents one needs a filehandle which is nothing but a structure which is used along with the operators to access the file in a certain mode like reading, writing, appending, etc. FileHandles can also be passed to a subroutine as a parameter to perform various operations on Files.In the below example, a filehandle is passed to a subroutine:-Example:"
},
{
"code": "#!/usr/bin/perl sub printem{ my $file = shift; while (<$file>) { print; }} open(fh, \"Hello.txt\") or die \"File '$filename' can't be opened\"; printem *fh;",
"e": 4728,
"s": 4546,
"text": null
},
{
"code": null,
"e": 4735,
"s": 4728,
"text": "Picked"
},
{
"code": null,
"e": 4740,
"s": 4735,
"text": "Perl"
},
{
"code": null,
"e": 4745,
"s": 4740,
"text": "Perl"
},
{
"code": null,
"e": 4843,
"s": 4745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4885,
"s": 4843,
"text": "Perl | Arrays (push, pop, shift, unshift)"
},
{
"code": null,
"e": 4899,
"s": 4885,
"text": "Perl | Arrays"
},
{
"code": null,
"e": 4940,
"s": 4899,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 4968,
"s": 4940,
"text": "Perl | Polymorphism in OOPs"
},
{
"code": null,
"e": 4993,
"s": 4968,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 5015,
"s": 4993,
"text": "Perl | Boolean Values"
},
{
"code": null,
"e": 5053,
"s": 5015,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 5072,
"s": 5053,
"text": "Perl | ne operator"
},
{
"code": null,
"e": 5100,
"s": 5072,
"text": "Hello World Program in Perl"
}
]
|
TextView in Kotlin | 29 Oct, 2021
Android TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it. First of all, open Kotlin project in Android Studio.Following steps are used to create TextView in Kotlin:
Add a TextView in activity_main.xml file inside LinearLayout.Add attributes like text, textColor, textSize, textStyle in the activity_main.xml file.Open MainActivity.kt file and set OnClickListener for the textView to show the Toast message.
Add a TextView in activity_main.xml file inside LinearLayout.
Add attributes like text, textColor, textSize, textStyle in the activity_main.xml file.
Open MainActivity.kt file and set OnClickListener for the textView to show the Toast message.
We can add strings in the strings.xml file and use in the other files easily by calling them with their names.
<resources> <string name="app_name">TextViewInKotlin</string> <string name="text_view">GeeksForGeeks</string> <string name="text_on_click">COMPUTER SCIENCE PORTAL</string></resources>
Open activity_main.xml file and create a TextView using id textView.
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--EditText with id editText--> <TextView android:id="@+id/text_view_id" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/text_view" android:textColor="#008000" android:textSize="40dp" android:textStyle="bold"/></LinearLayout>
Open MainActivity.kt file and get the reference of TextView defined in the layout file.
// finding the textView
val textView = findViewById(R.id.text_view_id) as TextView
Setting the on click listener to the button
textView?.setOnClickListener{ Toast.makeText(this@MainActivity,
"COMPUTER SCIENCE PORTAL", Toast.LENGTH_LONG).show() }
Open app/src/main/java/yourPackageName/MainActivity.kt to get the reference of TextView.
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //accessing our textview from layout val textView = findViewById<TextView>(R.id.text_view_id) as TextView textView?.setOnClickListener{ Toast.makeText(this@MainActivity, R.string.text_on_click, Toast.LENGTH_LONG).show() } } }
We are also going to see the code inside main/AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.geeksforgeeks.myfirstkotlinapp"> <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>
ruhelaa48
Android-View
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 286,
"s": 53,
"text": "Android TextView is simply a view that are used to display the text to the user and optionally allow us to modify or edit it. First of all, open Kotlin project in Android Studio.Following steps are used to create TextView in Kotlin:"
},
{
"code": null,
"e": 528,
"s": 286,
"text": "Add a TextView in activity_main.xml file inside LinearLayout.Add attributes like text, textColor, textSize, textStyle in the activity_main.xml file.Open MainActivity.kt file and set OnClickListener for the textView to show the Toast message."
},
{
"code": null,
"e": 590,
"s": 528,
"text": "Add a TextView in activity_main.xml file inside LinearLayout."
},
{
"code": null,
"e": 678,
"s": 590,
"text": "Add attributes like text, textColor, textSize, textStyle in the activity_main.xml file."
},
{
"code": null,
"e": 772,
"s": 678,
"text": "Open MainActivity.kt file and set OnClickListener for the textView to show the Toast message."
},
{
"code": null,
"e": 883,
"s": 772,
"text": "We can add strings in the strings.xml file and use in the other files easily by calling them with their names."
},
{
"code": "<resources> <string name=\"app_name\">TextViewInKotlin</string> <string name=\"text_view\">GeeksForGeeks</string> <string name=\"text_on_click\">COMPUTER SCIENCE PORTAL</string></resources>",
"e": 1076,
"s": 883,
"text": null
},
{
"code": null,
"e": 1145,
"s": 1076,
"text": "Open activity_main.xml file and create a TextView using id textView."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--EditText with id editText--> <TextView android:id=\"@+id/text_view_id\" android:layout_height=\"wrap_content\" android:layout_width=\"wrap_content\" android:text=\"@string/text_view\" android:textColor=\"#008000\" android:textSize=\"40dp\" android:textStyle=\"bold\"/></LinearLayout>",
"e": 1789,
"s": 1145,
"text": null
},
{
"code": null,
"e": 1877,
"s": 1789,
"text": "Open MainActivity.kt file and get the reference of TextView defined in the layout file."
},
{
"code": null,
"e": 1965,
"s": 1877,
"text": " \n// finding the textView\n val textView = findViewById(R.id.text_view_id) as TextView\n"
},
{
"code": null,
"e": 2009,
"s": 1965,
"text": "Setting the on click listener to the button"
},
{
"code": null,
"e": 2145,
"s": 2009,
"text": "textView?.setOnClickListener{ Toast.makeText(this@MainActivity,\n \"COMPUTER SCIENCE PORTAL\", Toast.LENGTH_LONG).show() }\n"
},
{
"code": null,
"e": 2234,
"s": 2145,
"text": "Open app/src/main/java/yourPackageName/MainActivity.kt to get the reference of TextView."
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //accessing our textview from layout val textView = findViewById<TextView>(R.id.text_view_id) as TextView textView?.setOnClickListener{ Toast.makeText(this@MainActivity, R.string.text_on_click, Toast.LENGTH_LONG).show() } } }",
"e": 2893,
"s": 2234,
"text": null
},
{
"code": null,
"e": 2965,
"s": 2893,
"text": "We are also going to see the code inside main/AndroidManifest.xml file."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.geeksforgeeks.myfirstkotlinapp\"> <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>",
"e": 3680,
"s": 2965,
"text": null
},
{
"code": null,
"e": 3690,
"s": 3680,
"text": "ruhelaa48"
},
{
"code": null,
"e": 3703,
"s": 3690,
"text": "Android-View"
},
{
"code": null,
"e": 3718,
"s": 3703,
"text": "Kotlin Android"
},
{
"code": null,
"e": 3725,
"s": 3718,
"text": "Picked"
},
{
"code": null,
"e": 3733,
"s": 3725,
"text": "Android"
},
{
"code": null,
"e": 3740,
"s": 3733,
"text": "Kotlin"
},
{
"code": null,
"e": 3748,
"s": 3740,
"text": "Android"
}
]
|
Dictionary and counter in Python to find winner of election | 16 Jun, 2022
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name.Examples:
Input : votes[] = {"john", "johnny", "jackie",
"johnny", "john", "jackie",
"jamie", "jamie", "john",
"johnny", "jamie", "johnny",
"john"};
Output : John
We have four Candidates with name as 'John',
'Johnny', 'jamie', 'jackie'. The candidates
John and Johny get maximum votes. Since John
is alphabetically smaller, we print it.
We have existing solution for this problem please refer Find winner of an election where votes are represented as candidate names link. We can solve this problem quickly in python using Dictionary data structure. Method 1: Approach is very simple,
Convert given list of votes into dictionary using Counter(iterator) method. We will have a dictionary having candidate names as Key and their frequency ( counts ) as Value.Since more than 1 candidate may get same number of votes and in this situation we need to print lexicographically smaller name, so now we will create another dictionary by traversing previously created dictionary, counts of votes will be Key and candidate names will be Value.Now find value of maximum vote casted for a candidate and get list of candidates mapped on that count value.Sort list of candidates having same number of maximum votes and print first element of sorted list in order to print lexicographically smaller name.
Convert given list of votes into dictionary using Counter(iterator) method. We will have a dictionary having candidate names as Key and their frequency ( counts ) as Value.
Since more than 1 candidate may get same number of votes and in this situation we need to print lexicographically smaller name, so now we will create another dictionary by traversing previously created dictionary, counts of votes will be Key and candidate names will be Value.
Now find value of maximum vote casted for a candidate and get list of candidates mapped on that count value.
Sort list of candidates having same number of maximum votes and print first element of sorted list in order to print lexicographically smaller name.
Python3
# Function to find winner of an election where votes# are represented as candidate namesfrom collections import Counter def winner(input): # convert list of candidates into dictionary # output will be likes candidates = {'A':2, 'B':4} votes = Counter(input) # create another dictionary and it's key will # be count of votes values will be name of # candidates dict = {} for value in votes.values(): # initialize empty list to each key to # insert candidate names having same # number of votes dict[value] = [] for (key,value) in votes.items(): dict[value].append(key) # sort keys in descending order to get maximum # value of votes maxVote = sorted(dict.keys(),reverse=True)[0] # check if more than 1 candidates have same # number of votes. If yes, then sort the list # first and print first element if len(dict[maxVote])>1: print (sorted(dict[maxVote])[0]) else: print (dict[maxVote][0]) # Driver programif __name__ == "__main__": input =['john','johnny','jackie','johnny', 'john','jackie','jamie','jamie', 'john','johnny','jamie','johnny', 'john'] winner(input)
Output:
john
Time complexity : O(nlogn) Auxiliary Space : O(n)
Method 2: This is a shorter method. 1. Count the number of votes for each person and stores in a dictionary. 2. Find the maximum number of votes. 3. Find corresponding person(s) having votes equal to maximum votes. 4. As we want output according to lexicographical order, so sort the list and print first element.
Python3
from collections import Counter votes =['john','johnny','jackie','johnny','john','jackie', 'jamie','jamie','john','johnny','jamie','johnny','john'] #Count the votes for persons and stores in the dictionaryvote_count=Counter(votes) #Find the maximum number of votesmax_votes=max(vote_count.values()) #Search for people having maximum votes and store in a listlst=[i for i in vote_count.keys() if vote_count[i]==max_votes] #Sort the list and print lexicographical smallest nameprint(sorted(lst)[0])
Output:
john
Time complexity : O(n) Auxiliary Space : O(1)
gopalgupta7799
rajeev0719singh
a7977370173
python-dict
Python
Strings
python-dict
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
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": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 293,
"s": 52,
"text": "Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name.Examples: "
},
{
"code": null,
"e": 705,
"s": 293,
"text": "Input : votes[] = {\"john\", \"johnny\", \"jackie\", \n \"johnny\", \"john\", \"jackie\", \n \"jamie\", \"jamie\", \"john\",\n \"johnny\", \"jamie\", \"johnny\", \n \"john\"};\nOutput : John\nWe have four Candidates with name as 'John', \n'Johnny', 'jamie', 'jackie'. The candidates\nJohn and Johny get maximum votes. Since John\nis alphabetically smaller, we print it."
},
{
"code": null,
"e": 957,
"s": 707,
"text": "We have existing solution for this problem please refer Find winner of an election where votes are represented as candidate names link. We can solve this problem quickly in python using Dictionary data structure. Method 1: Approach is very simple, "
},
{
"code": null,
"e": 1662,
"s": 957,
"text": "Convert given list of votes into dictionary using Counter(iterator) method. We will have a dictionary having candidate names as Key and their frequency ( counts ) as Value.Since more than 1 candidate may get same number of votes and in this situation we need to print lexicographically smaller name, so now we will create another dictionary by traversing previously created dictionary, counts of votes will be Key and candidate names will be Value.Now find value of maximum vote casted for a candidate and get list of candidates mapped on that count value.Sort list of candidates having same number of maximum votes and print first element of sorted list in order to print lexicographically smaller name."
},
{
"code": null,
"e": 1835,
"s": 1662,
"text": "Convert given list of votes into dictionary using Counter(iterator) method. We will have a dictionary having candidate names as Key and their frequency ( counts ) as Value."
},
{
"code": null,
"e": 2112,
"s": 1835,
"text": "Since more than 1 candidate may get same number of votes and in this situation we need to print lexicographically smaller name, so now we will create another dictionary by traversing previously created dictionary, counts of votes will be Key and candidate names will be Value."
},
{
"code": null,
"e": 2221,
"s": 2112,
"text": "Now find value of maximum vote casted for a candidate and get list of candidates mapped on that count value."
},
{
"code": null,
"e": 2370,
"s": 2221,
"text": "Sort list of candidates having same number of maximum votes and print first element of sorted list in order to print lexicographically smaller name."
},
{
"code": null,
"e": 2380,
"s": 2372,
"text": "Python3"
},
{
"code": "# Function to find winner of an election where votes# are represented as candidate namesfrom collections import Counter def winner(input): # convert list of candidates into dictionary # output will be likes candidates = {'A':2, 'B':4} votes = Counter(input) # create another dictionary and it's key will # be count of votes values will be name of # candidates dict = {} for value in votes.values(): # initialize empty list to each key to # insert candidate names having same # number of votes dict[value] = [] for (key,value) in votes.items(): dict[value].append(key) # sort keys in descending order to get maximum # value of votes maxVote = sorted(dict.keys(),reverse=True)[0] # check if more than 1 candidates have same # number of votes. If yes, then sort the list # first and print first element if len(dict[maxVote])>1: print (sorted(dict[maxVote])[0]) else: print (dict[maxVote][0]) # Driver programif __name__ == \"__main__\": input =['john','johnny','jackie','johnny', 'john','jackie','jamie','jamie', 'john','johnny','jamie','johnny', 'john'] winner(input)",
"e": 3594,
"s": 2380,
"text": null
},
{
"code": null,
"e": 3604,
"s": 3594,
"text": "Output: "
},
{
"code": null,
"e": 3609,
"s": 3604,
"text": "john"
},
{
"code": null,
"e": 3659,
"s": 3609,
"text": "Time complexity : O(nlogn) Auxiliary Space : O(n)"
},
{
"code": null,
"e": 3975,
"s": 3659,
"text": "Method 2: This is a shorter method. 1. Count the number of votes for each person and stores in a dictionary. 2. Find the maximum number of votes. 3. Find corresponding person(s) having votes equal to maximum votes. 4. As we want output according to lexicographical order, so sort the list and print first element. "
},
{
"code": null,
"e": 3983,
"s": 3975,
"text": "Python3"
},
{
"code": "from collections import Counter votes =['john','johnny','jackie','johnny','john','jackie', 'jamie','jamie','john','johnny','jamie','johnny','john'] #Count the votes for persons and stores in the dictionaryvote_count=Counter(votes) #Find the maximum number of votesmax_votes=max(vote_count.values()) #Search for people having maximum votes and store in a listlst=[i for i in vote_count.keys() if vote_count[i]==max_votes] #Sort the list and print lexicographical smallest nameprint(sorted(lst)[0])",
"e": 4483,
"s": 3983,
"text": null
},
{
"code": null,
"e": 4493,
"s": 4483,
"text": "Output: "
},
{
"code": null,
"e": 4498,
"s": 4493,
"text": "john"
},
{
"code": null,
"e": 4545,
"s": 4498,
"text": "Time complexity : O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 4560,
"s": 4545,
"text": "gopalgupta7799"
},
{
"code": null,
"e": 4576,
"s": 4560,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 4588,
"s": 4576,
"text": "a7977370173"
},
{
"code": null,
"e": 4600,
"s": 4588,
"text": "python-dict"
},
{
"code": null,
"e": 4607,
"s": 4600,
"text": "Python"
},
{
"code": null,
"e": 4615,
"s": 4607,
"text": "Strings"
},
{
"code": null,
"e": 4627,
"s": 4615,
"text": "python-dict"
},
{
"code": null,
"e": 4635,
"s": 4627,
"text": "Strings"
},
{
"code": null,
"e": 4733,
"s": 4635,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4751,
"s": 4733,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4793,
"s": 4751,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4815,
"s": 4793,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4850,
"s": 4815,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4876,
"s": 4850,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4922,
"s": 4876,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4947,
"s": 4922,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5007,
"s": 4947,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5022,
"s": 5007,
"text": "C++ Data Types"
}
]
|
Character.isLetterOrDigit() in Java with examples | 06 Dec, 2018
The java.lang.Character.isLetterOrDigit(char ch) is an inbuilt method in java which determines if the specified character is a letter or digit.
Syntax:
public static boolean isLetterOrDigit(char ch)
Parameters: The function accepts a single mandatory parameter ch which signifies the character to be tested.
Return value: This function returns a boolean value. The boolean value is true if the character is a letter or digit else it false.
Below programs illustrate the above method:
Program 1:
// Java program to illustrate the// Character.isLetterOrDigit() method import java.lang.*; public class GFG { public static void main(String[] args) { // two characters char c1 = 'Z', c2 = '2'; // Function to check if the character is letter or digit boolean bool1 = Character.isLetterOrDigit(c1); System.out.println(c1 + " is a letter/digit ? " + bool1); // Function to check if the character is letter or digit boolean bool2 = Character.isLetterOrDigit(c2); System.out.println(c2 + " is a letter/digit ? " + bool2); }}
Z is a letter/digit ? true
2 is a letter/digit ? true
Program 2:
// Java program to illustrate the// Character.isLetterOrDigit() method import java.lang.*; public class GFG { public static void main(String[] args) { // assign character char c1 = 'D', c2 = '/'; // Function to check if the character is letter or digit boolean bool1 = Character.isLetterOrDigit(c1); System.out.println(c1 + " is a letter/digit ? " + bool1); // Function to check if the character is letter or digit boolean bool2 = Character.isLetterOrDigit(c2); System.out.println(c2 + " is a letter/digit ? " + bool2); }}
D is a letter/digit ? true
/ is a letter/digit ? false
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isLetterOrDigit(char)
Java-Character
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 172,
"s": 28,
"text": "The java.lang.Character.isLetterOrDigit(char ch) is an inbuilt method in java which determines if the specified character is a letter or digit."
},
{
"code": null,
"e": 180,
"s": 172,
"text": "Syntax:"
},
{
"code": null,
"e": 228,
"s": 180,
"text": "public static boolean isLetterOrDigit(char ch)\n"
},
{
"code": null,
"e": 337,
"s": 228,
"text": "Parameters: The function accepts a single mandatory parameter ch which signifies the character to be tested."
},
{
"code": null,
"e": 469,
"s": 337,
"text": "Return value: This function returns a boolean value. The boolean value is true if the character is a letter or digit else it false."
},
{
"code": null,
"e": 513,
"s": 469,
"text": "Below programs illustrate the above method:"
},
{
"code": null,
"e": 524,
"s": 513,
"text": "Program 1:"
},
{
"code": "// Java program to illustrate the// Character.isLetterOrDigit() method import java.lang.*; public class GFG { public static void main(String[] args) { // two characters char c1 = 'Z', c2 = '2'; // Function to check if the character is letter or digit boolean bool1 = Character.isLetterOrDigit(c1); System.out.println(c1 + \" is a letter/digit ? \" + bool1); // Function to check if the character is letter or digit boolean bool2 = Character.isLetterOrDigit(c2); System.out.println(c2 + \" is a letter/digit ? \" + bool2); }}",
"e": 1120,
"s": 524,
"text": null
},
{
"code": null,
"e": 1175,
"s": 1120,
"text": "Z is a letter/digit ? true\n2 is a letter/digit ? true\n"
},
{
"code": null,
"e": 1186,
"s": 1175,
"text": "Program 2:"
},
{
"code": "// Java program to illustrate the// Character.isLetterOrDigit() method import java.lang.*; public class GFG { public static void main(String[] args) { // assign character char c1 = 'D', c2 = '/'; // Function to check if the character is letter or digit boolean bool1 = Character.isLetterOrDigit(c1); System.out.println(c1 + \" is a letter/digit ? \" + bool1); // Function to check if the character is letter or digit boolean bool2 = Character.isLetterOrDigit(c2); System.out.println(c2 + \" is a letter/digit ? \" + bool2); }}",
"e": 1784,
"s": 1186,
"text": null
},
{
"code": null,
"e": 1840,
"s": 1784,
"text": "D is a letter/digit ? true\n/ is a letter/digit ? false\n"
},
{
"code": null,
"e": 1940,
"s": 1840,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isLetterOrDigit(char)"
},
{
"code": null,
"e": 1955,
"s": 1940,
"text": "Java-Character"
},
{
"code": null,
"e": 1970,
"s": 1955,
"text": "Java-Functions"
},
{
"code": null,
"e": 1988,
"s": 1970,
"text": "Java-lang package"
},
{
"code": null,
"e": 1993,
"s": 1988,
"text": "Java"
},
{
"code": null,
"e": 1998,
"s": 1993,
"text": "Java"
},
{
"code": null,
"e": 2096,
"s": 1998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2111,
"s": 2096,
"text": "Stream In Java"
},
{
"code": null,
"e": 2132,
"s": 2111,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2153,
"s": 2132,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2172,
"s": 2153,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2189,
"s": 2172,
"text": "Generics in Java"
},
{
"code": null,
"e": 2219,
"s": 2189,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2245,
"s": 2219,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2261,
"s": 2245,
"text": "Strings in Java"
},
{
"code": null,
"e": 2298,
"s": 2261,
"text": "Differences between JDK, JRE and JVM"
}
]
|
LinkedList toArray() method in Java with Example | 27 May, 2022
This java.util.LinkedList.toArray() method is used to convert and LinkedList into an Array. It returns the same LinkedList elements but in the form of Array only.
We have to method to convert LinkedList into an Array
toArray() – without parameter
toArray(arrayName) – with parameter
The Java.util.LinkedList.toArray() method returns an array containing all the elements in the list in proper sequence i.e. from first to last. The returned array will be safe as a new array is created (hence new memory is allocated). Thus the caller is free to modify the array. It acts as a bridge between array-based and collection-based APIs.
Syntax:
LinkedListName.toArray()
Parameters: It does not take in any parameter.
Return Value: It returns an array containing all the elements in the list. Below examples illustrates the LinkedList.toArray() method:
Example: toArray() – without parameter (with Integer type LinkedList)
Java
// Java Program Demonstrate toArray()// method of LinkedList import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { //Ceate object of LinkedList LinkedList<Integer> list = new LinkedList<Integer>(); //Add numbers to end of LinkedList list.add(7855642); list.add(35658786); list.add(5278367); list.add(74381793); //Prints the LinkedList elements System.out.println("LinkedList: " + list); //Convert LinkedList into an Array the method has no parameter Object[] a = list.toArray(); //Print all elements of the Array System.out.print("After converted LinkedList to Array: "); for(Object element : a) System.out.print(element+" "); }}
Output:
LinkedList: [7855642, 35658786, 5278367, 74381793]
After converted LinkedList to Array: 7855642 35658786 5278367 74381793
The toArray(arrayName) method method of LinkedList class in Java is used to form an array of the same elements as that of the LinkedList. It returns an array containing all of the elements in this LinkedList in the correct order; the run-time type of the returned array is that of the specified array. If the LinkedList fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the run time type of the specified array and the size of this LinkedList. If the LinkedList fits in the specified array with room to spare (i.e., the array has more elements than the LinkedList), the element in the array immediately following the end of the LinkedList is set to null. (This is useful in determining the length of the LinkedList only if the caller knows that the LinkedList does not contain any null elements.)
Syntax:
LinkedListName.toArray(ArrayName)
Parameters: The method accepts one parameter arrayName which is the array into which the elements of the LinkedList are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Return Value: The method returns an array containing the elements similar to the LinkedList.
Exception: The method might throw two types of exception:
ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the LinkedList.
NullPointerException: If the array is Null, then this exception is thrown.
Below program illustrates the working of the LinkedList.toArray(arrayName) method.
Example: toArray(arrayName) – with parameter (with String type LinkedList)
Java
// Java code to illustrate toArray(arr[]) import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add // elements into the LinkedList list.add("Welcome"); list.add("To"); list.add("Geeks"); list.add("For"); list.add("Geeks"); // Displaying the LinkedList System.out.println("The LinkedList: " + list); // Creating the array and using toArray() String[] arr = new String[5]; list.toArray(arr); //Print all elements of the Array System.out.print("After converted LinkedList to Array: "); for(String elements:list) System.out.print(elements+" "); }}
Output:
The LinkedList: [Welcome, To, Geeks, For, Geeks]
After converted LinkedList to Array: Welcome To Geeks For Geeks
nandinigujral
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Picked
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 218,
"s": 54,
"text": "This java.util.LinkedList.toArray() method is used to convert and LinkedList into an Array. It returns the same LinkedList elements but in the form of Array only."
},
{
"code": null,
"e": 272,
"s": 218,
"text": "We have to method to convert LinkedList into an Array"
},
{
"code": null,
"e": 302,
"s": 272,
"text": "toArray() – without parameter"
},
{
"code": null,
"e": 338,
"s": 302,
"text": "toArray(arrayName) – with parameter"
},
{
"code": null,
"e": 685,
"s": 338,
"text": "The Java.util.LinkedList.toArray() method returns an array containing all the elements in the list in proper sequence i.e. from first to last. The returned array will be safe as a new array is created (hence new memory is allocated). Thus the caller is free to modify the array. It acts as a bridge between array-based and collection-based APIs. "
},
{
"code": null,
"e": 693,
"s": 685,
"text": "Syntax:"
},
{
"code": null,
"e": 718,
"s": 693,
"text": "LinkedListName.toArray()"
},
{
"code": null,
"e": 766,
"s": 718,
"text": "Parameters: It does not take in any parameter. "
},
{
"code": null,
"e": 902,
"s": 766,
"text": "Return Value: It returns an array containing all the elements in the list. Below examples illustrates the LinkedList.toArray() method: "
},
{
"code": null,
"e": 973,
"s": 902,
"text": "Example: toArray() – without parameter (with Integer type LinkedList)"
},
{
"code": null,
"e": 978,
"s": 973,
"text": "Java"
},
{
"code": "// Java Program Demonstrate toArray()// method of LinkedList import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { //Ceate object of LinkedList LinkedList<Integer> list = new LinkedList<Integer>(); //Add numbers to end of LinkedList list.add(7855642); list.add(35658786); list.add(5278367); list.add(74381793); //Prints the LinkedList elements System.out.println(\"LinkedList: \" + list); //Convert LinkedList into an Array the method has no parameter Object[] a = list.toArray(); //Print all elements of the Array System.out.print(\"After converted LinkedList to Array: \"); for(Object element : a) System.out.print(element+\" \"); }}",
"e": 1845,
"s": 978,
"text": null
},
{
"code": null,
"e": 1853,
"s": 1845,
"text": "Output:"
},
{
"code": null,
"e": 1976,
"s": 1853,
"text": "LinkedList: [7855642, 35658786, 5278367, 74381793]\nAfter converted LinkedList to Array: 7855642 35658786 5278367 74381793 "
},
{
"code": null,
"e": 2817,
"s": 1976,
"text": "The toArray(arrayName) method method of LinkedList class in Java is used to form an array of the same elements as that of the LinkedList. It returns an array containing all of the elements in this LinkedList in the correct order; the run-time type of the returned array is that of the specified array. If the LinkedList fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the run time type of the specified array and the size of this LinkedList. If the LinkedList fits in the specified array with room to spare (i.e., the array has more elements than the LinkedList), the element in the array immediately following the end of the LinkedList is set to null. (This is useful in determining the length of the LinkedList only if the caller knows that the LinkedList does not contain any null elements.)"
},
{
"code": null,
"e": 2825,
"s": 2817,
"text": "Syntax:"
},
{
"code": null,
"e": 2859,
"s": 2825,
"text": "LinkedListName.toArray(ArrayName)"
},
{
"code": null,
"e": 3094,
"s": 2859,
"text": "Parameters: The method accepts one parameter arrayName which is the array into which the elements of the LinkedList are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose. "
},
{
"code": null,
"e": 3188,
"s": 3094,
"text": "Return Value: The method returns an array containing the elements similar to the LinkedList. "
},
{
"code": null,
"e": 3246,
"s": 3188,
"text": "Exception: The method might throw two types of exception:"
},
{
"code": null,
"e": 3391,
"s": 3246,
"text": "ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the LinkedList."
},
{
"code": null,
"e": 3466,
"s": 3391,
"text": "NullPointerException: If the array is Null, then this exception is thrown."
},
{
"code": null,
"e": 3550,
"s": 3466,
"text": "Below program illustrates the working of the LinkedList.toArray(arrayName) method. "
},
{
"code": null,
"e": 3626,
"s": 3550,
"text": "Example: toArray(arrayName) – with parameter (with String type LinkedList)"
},
{
"code": null,
"e": 3631,
"s": 3626,
"text": "Java"
},
{
"code": "// Java code to illustrate toArray(arr[]) import java.util.*; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add // elements into the LinkedList list.add(\"Welcome\"); list.add(\"To\"); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"Geeks\"); // Displaying the LinkedList System.out.println(\"The LinkedList: \" + list); // Creating the array and using toArray() String[] arr = new String[5]; list.toArray(arr); //Print all elements of the Array System.out.print(\"After converted LinkedList to Array: \"); for(String elements:list) System.out.print(elements+\" \"); }}",
"e": 4493,
"s": 3631,
"text": null
},
{
"code": null,
"e": 4501,
"s": 4493,
"text": "Output:"
},
{
"code": null,
"e": 4615,
"s": 4501,
"text": "The LinkedList: [Welcome, To, Geeks, For, Geeks]\nAfter converted LinkedList to Array: Welcome To Geeks For Geeks "
},
{
"code": null,
"e": 4629,
"s": 4615,
"text": "nandinigujral"
},
{
"code": null,
"e": 4649,
"s": 4629,
"text": "Java - util package"
},
{
"code": null,
"e": 4666,
"s": 4649,
"text": "Java-Collections"
},
{
"code": null,
"e": 4681,
"s": 4666,
"text": "Java-Functions"
},
{
"code": null,
"e": 4697,
"s": 4681,
"text": "java-LinkedList"
},
{
"code": null,
"e": 4704,
"s": 4697,
"text": "Picked"
},
{
"code": null,
"e": 4709,
"s": 4704,
"text": "Java"
},
{
"code": null,
"e": 4714,
"s": 4709,
"text": "Java"
},
{
"code": null,
"e": 4731,
"s": 4714,
"text": "Java-Collections"
}
]
|
Graph - GeeksforGeeks | 19 Nov, 2018
I. 7, 6, 5, 4, 4, 3, 2, 1
II. 6, 6, 6, 6, 3, 3, 2, 2
III. 7, 6, 6, 4, 4, 3, 2, 2
IV. 8, 7, 7, 6, 4, 2, 1, 1
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Append Pandas DataFrame to Existing CSV File?
How to Replace Values in a List in Python?
Spring - REST Controller
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python? | [
{
"code": null,
"e": 28965,
"s": 28937,
"text": "\n19 Nov, 2018"
},
{
"code": null,
"e": 29074,
"s": 28965,
"text": "I. 7, 6, 5, 4, 4, 3, 2, 1\nII. 6, 6, 6, 6, 3, 3, 2, 2\nIII. 7, 6, 6, 4, 4, 3, 2, 2\nIV. 8, 7, 7, 6, 4, 2, 1, 1 "
},
{
"code": null,
"e": 29172,
"s": 29074,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29225,
"s": 29172,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29287,
"s": 29225,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29367,
"s": 29287,
"text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python"
},
{
"code": null,
"e": 29408,
"s": 29367,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29488,
"s": 29408,
"text": "How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?"
},
{
"code": null,
"e": 29541,
"s": 29488,
"text": "How to Append Pandas DataFrame to Existing CSV File?"
},
{
"code": null,
"e": 29584,
"s": 29541,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29609,
"s": 29584,
"text": "Spring - REST Controller"
},
{
"code": null,
"e": 29645,
"s": 29609,
"text": "How to Read Text Files with Pandas?"
}
]
|
Find subarray with given sum | Set 1 (Nonnegative Numbers) - GeeksforGeeks | 29 Mar, 2022
Given an unsorted array arr of nonnegative integers and an integer sum, find a continuous subarray which adds to a given sum. There may be more than one subarrays with sum as the given sum, print first such subarray. Examples :
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33Output: Sum found between indexes 2 and 4Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33
Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7Output: Sum found between indexes 1 and 4Sum of elements between indices 1 and 4 is 4 + 0 + 0 + 3 = 7
Input: arr[] = {1, 4}, sum = 0Output: No subarray foundThere is no subarray with 0 sum
Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.Algorithm:
Traverse the array from start to end.From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.For every index in inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray.
Traverse the array from start to end.
From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.
For every index in inner loop update sum = sum + array[j]
If the sum is equal to the given sum then print the subarray.
C++
C
Java
Python3
C#
PHP
Javascript
/* A simple program to print subarray with sum as given sum */#include <bits/stdc++.h>using namespace std; /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { cout << "Sum found between indexes " << i << " and " << j - 1; return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } cout << "No subarray found"; return 0;} // Driver Codeint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;} // This code is contributed// by rathbhupendra
/* A simple program to print subarray with sum as given sum */#include <stdio.h> /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { printf( "Sum found between indexes %d and %d", i, j - 1); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } printf("No subarray found"); return 0;} // Driver program to test above functionint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}
class SubarraySum { /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { int p = j - 1; System.out.println( "Sum found between indexes " + i + " and " + p); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } System.out.println("No subarray found"); return 0; } public static void main(String[] args) { SubarraySum arraysum = new SubarraySum(); int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.length; int sum = 23; arraysum.subArraySum(arr, n, sum); }} // This code has been contributed by Mayank Jaiswal(mayank_24)
# Returns true if the# there is a subarray# of arr[] with sum# equal to 'sum' # otherwise returns# false. Also, prints# the result def subArraySum(arr, n, sum_): # Pick a starting # point for i in range(n): curr_sum = arr[i] # try all subarrays # starting with 'i' j = i + 1 while j <= n: if curr_sum == sum_: print ("Sum found between") print("indexes % d and % d"%( i, j-1)) return 1 if curr_sum > sum_ or j == n: break curr_sum = curr_sum + arr[j] j += 1 print ("No subarray found") return 0 # Driver program arr = [15, 2, 4, 8, 9, 5, 10, 23]n = len(arr)sum_ = 23 subArraySum(arr, n, sum_) # This code is Contributed by shreyanshi_arun.
// C# code to Find subarray// with given sumusing System; class GFG { // Returns true if the there is a // subarray of arr[] with sum // equal to 'sum' otherwise returns // false. Also, prints the result int subArraySum(int[] arr, int n, int sum) { int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays // starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { int p = j - 1; Console.Write("Sum found between " + "indexes " + i + " and " + p); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } Console.Write("No subarray found"); return 0; } // Driver Code public static void Main() { GFG arraysum = new GFG(); int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.Length; int sum = 23; arraysum.subArraySum(arr, n, sum); }} // This code has been contributed// by nitin mittal
<?php// A simple program to print subarray// with sum as given sum /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */function subArraySum($arr, $n, $sum){ $curr_sum; $i; $j; // Pick a starting point for ($i = 0; $i < $n; $i++) { $curr_sum = $arr[$i]; // try all subarrays // starting with 'i' for ($j = $i + 1; $j <= $n; $j++) { if ($curr_sum == $sum) { echo "Sum found between indexes ", $i, " and ", $j-1 ; return 1; } if ($curr_sum > $sum || $j == $n) break; $curr_sum = $curr_sum + $arr[$j]; } } echo "No subarray found"; return 0;} // Driver Code $arr= array(15, 2, 4, 8, 9, 5, 10, 23); $n = sizeof($arr); $sum = 23; subArraySum($arr, $n, $sum); return 0; // This code is contributed by AJit?>
<script> /* A simple program to print subarray with sum as given sum */ /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */function subArraySum(arr, n, sum){ let curr_sum=0; // Pick a starting point for (let i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (let j = i + 1; j <= n; j++) { if (curr_sum == sum) { document.write("Sum found between indexes "+i+" and "+(j - 1)); return; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } document.write("No subarray found"); return;} // Driver Code let arr= [15, 2, 4, 8, 9, 5, 10, 23];let n = arr.length;let sum = 23;subArraySum(arr, n, sum); </script>
Sum found between indexes 1 and 4
Complexity Analysis:
Time Complexity: O(n^2) in worst case. Nested loop is used to traverse the array so the time complexity is O(n^2)
Space Complexity: O(1). As constant extra space is required.
Efficient Approach: There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.Algorithm:
Create three variables, l=0, sum = 0Traverse the array from start to end.Update the variable sum by adding current element, sum = sum + array[i]If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.If the sum is equal to given sum, print the subarray and break the loop.
Create three variables, l=0, sum = 0
Traverse the array from start to end.
Update the variable sum by adding current element, sum = sum + array[i]
If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.
If the sum is equal to given sum, print the subarray and break the loop.
C++
C
Java
Python3
C#
PHP
Javascript
/* An efficient program to print subarray with sum as given sum */#include <iostream>using namespace std; /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ int curr_sum = arr[0], start = 0, i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { cout << "Sum found between indexes " << start << " and " << i - 1; return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } // If we reach here, then no subarray cout << "No subarray found"; return 0;} // Driver Codeint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;} // This code is contributed by SHUBHAMSINGH10
/* An efficient program to print subarray with sum as given sum */#include <stdio.h> /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ int curr_sum = arr[0], start = 0, i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { printf( "Sum found between indexes %d and %d", start, i - 1); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } // If we reach here, then no subarray printf("No subarray found"); return 0;} // Driver program to test above functionint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}
class SubarraySum { /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { int curr_sum = arr[0], start = 0, i; // Pick a starting point for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { int p = i - 1; System.out.println( "Sum found between indexes " + start + " and " + p); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } System.out.println("No subarray found"); return 0; } public static void main(String[] args) { SubarraySum arraysum = new SubarraySum(); int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.length; int sum = 23; arraysum.subArraySum(arr, n, sum); }} // This code has been contributed by Mayank Jaiswal(mayank_24)
# An efficient program # to print subarray# with sum as given sum # Returns true if the # there is a subarray # of arr[] with sum# equal to 'sum' # otherwise returns # false. Also, prints # the result.def subArraySum(arr, n, sum_): # Initialize curr_sum as # value of first element # and starting point as 0 curr_sum = arr[0] start = 0 # Add elements one by # one to curr_sum and # if the curr_sum exceeds # the sum, then remove # starting element i = 1 while i <= n: # If curr_sum exceeds # the sum, then remove # the starting elements while curr_sum > sum_ and start < i-1: curr_sum = curr_sum - arr[start] start += 1 # If curr_sum becomes # equal to sum, then # return true if curr_sum == sum_: print ("Sum found between indexes") print ("% d and % d"%(start, i-1)) return 1 # Add this element # to curr_sum if i < n: curr_sum = curr_sum + arr[i] i += 1 # If we reach here, # then no subarray print ("No subarray found") return 0 # Driver programarr = [15, 2, 4, 8, 9, 5, 10, 23]n = len(arr)sum_ = 23 subArraySum(arr, n, sum_) # This code is Contributed by shreyanshi_arun.
// An efficient C# program to print// subarray with sum as given sumusing System; class GFG { // Returns true if the // there is a subarray of // arr[] with sum equal to // 'sum' otherwise returns false. // Also, prints the result int subArraySum(int[] arr, int n, int sum) { int curr_sum = arr[0], start = 0, i; // Pick a starting point for (i = 1; i <= n; i++) { // If curr_sum exceeds // the sum, then remove // the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to // sum, then return true if (curr_sum == sum) { int p = i - 1; Console.WriteLine("Sum found between " + "indexes " + start + " and " + p); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } Console.WriteLine("No subarray found"); return 0; } // Driver code public static void Main() { GFG arraysum = new GFG(); int[] arr = new int[] { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.Length; int sum = 23; arraysum.subArraySum(arr, n, sum); }} // This code has been contributed by KRV.
<?php/* An efficient program to print subarray with sum as given sum */ /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */function subArraySum($arr, $n, $sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ $curr_sum = $arr[0]; $start = 0; $i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for ($i = 1; $i <= $n; $i++) { // If curr_sum exceeds the sum, // then remove the starting elements while ($curr_sum > $sum and $start < $i - 1) { $curr_sum = $curr_sum - $arr[$start]; $start++; } // If curr_sum becomes equal // to sum, then return true if ($curr_sum == $sum) { echo "Sum found between indexes", " ", $start, " ", "and ", " ", $i - 1; return 1; } // Add this element // to curr_sum if ($i < $n) $curr_sum = $curr_sum + $arr[$i]; } // If we reach here, // then no subarray echo "No subarray found"; return 0;} // Driver Code$arr = array(15, 2, 4, 8, 9, 5, 10, 23);$n = count($arr);$sum = 23;subArraySum($arr, $n, $sum); // This code has been// contributed by anuj_67.?>
<script>/* Returns true if the there isa subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ function subArraySum(arr,n,sum) { let curr_sum = arr[0], start = 0, i; // Pick a starting point for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { let p = i - 1; document.write( "Sum found between indexes " + start + " and " + p+"<br>"); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } document.write("No subarray found"); return 0; } let arr=[15, 2, 4, 8, 9, 5, 10, 23 ]; let n = arr.length; let sum = 23; subArraySum(arr, n, sum); // This code is contributed by unknown2108</script>
Sum found between indexes 1 and 4
Complexity Analysis:
Time Complexity : O(n). The Array is traversed only once to insert elements into the window. It will take O(N) timeThe Array is traversed again once to remove elements from the window. It will also take O(N) time.So the total time will be O(N) + O(N) = O(2*N), which is similar to O(N)
The Array is traversed only once to insert elements into the window. It will take O(N) time
The Array is traversed again once to remove elements from the window. It will also take O(N) time.
So the total time will be O(N) + O(N) = O(2*N), which is similar to O(N)
Space Complexity: O(1). As constant extra space is required.
YouTubeGeeksforGeeks506K subscribersFind subarray with given sum | Set 1 (Non-negative Numbers) | GeeksforGeeksWatch laterShareCopy link71/101InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=GY-KULykGaw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
The above solution doesn’t handle negative numbers. We can use hashing to handle negative numbers. See below set 2.
Find subarray with given sum | Set 2 (Handles Negative Numbers)
Find subarray with given sum with negatives allowed in constant space
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
KRV
jit_t
nitin mittal
vt_m
rathbhupendra
gfg_sal_gfg
nidhi_biet
SHUBHAMSINGH10
andrew1234
ch17btech11023
mohit kumar 29
unknown2108
sooda367
sweetyty
anikakapoor
RishabhPrabhu
Amazon
Facebook
FactSet
Google
Morgan Stanley
sliding-window
subarray
subarray-sum
Visa
Zoho
Arrays
Zoho
Morgan Stanley
Amazon
FactSet
Visa
Google
Facebook
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays in C/C++
Write a program to reverse an array or string
Program for array rotation
Largest Sum Contiguous Subarray
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java | [
{
"code": null,
"e": 41374,
"s": 41346,
"text": "\n29 Mar, 2022"
},
{
"code": null,
"e": 41603,
"s": 41374,
"text": "Given an unsorted array arr of nonnegative integers and an integer sum, find a continuous subarray which adds to a given sum. There may be more than one subarrays with sum as the given sum, print first such subarray. Examples : "
},
{
"code": null,
"e": 41749,
"s": 41603,
"text": "Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33Output: Sum found between indexes 2 and 4Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33"
},
{
"code": null,
"e": 41897,
"s": 41749,
"text": "Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7Output: Sum found between indexes 1 and 4Sum of elements between indices 1 and 4 is 4 + 0 + 0 + 3 = 7"
},
{
"code": null,
"e": 41984,
"s": 41897,
"text": "Input: arr[] = {1, 4}, sum = 0Output: No subarray foundThere is no subarray with 0 sum"
},
{
"code": null,
"e": 42269,
"s": 41984,
"text": "Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. Following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.Algorithm: "
},
{
"code": null,
"e": 42566,
"s": 42269,
"text": "Traverse the array from start to end.From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum.For every index in inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray."
},
{
"code": null,
"e": 42604,
"s": 42566,
"text": "Traverse the array from start to end."
},
{
"code": null,
"e": 42746,
"s": 42604,
"text": "From every index start another loop from i to the end of array to get all subarray starting from i, keep a variable sum to calculate the sum."
},
{
"code": null,
"e": 42804,
"s": 42746,
"text": "For every index in inner loop update sum = sum + array[j]"
},
{
"code": null,
"e": 42866,
"s": 42804,
"text": "If the sum is equal to the given sum then print the subarray."
},
{
"code": null,
"e": 42870,
"s": 42866,
"text": "C++"
},
{
"code": null,
"e": 42872,
"s": 42870,
"text": "C"
},
{
"code": null,
"e": 42877,
"s": 42872,
"text": "Java"
},
{
"code": null,
"e": 42885,
"s": 42877,
"text": "Python3"
},
{
"code": null,
"e": 42888,
"s": 42885,
"text": "C#"
},
{
"code": null,
"e": 42892,
"s": 42888,
"text": "PHP"
},
{
"code": null,
"e": 42903,
"s": 42892,
"text": "Javascript"
},
{
"code": "/* A simple program to print subarray with sum as given sum */#include <bits/stdc++.h>using namespace std; /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { cout << \"Sum found between indexes \" << i << \" and \" << j - 1; return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } cout << \"No subarray found\"; return 0;} // Driver Codeint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;} // This code is contributed// by rathbhupendra",
"e": 43934,
"s": 42903,
"text": null
},
{
"code": "/* A simple program to print subarray with sum as given sum */#include <stdio.h> /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { printf( \"Sum found between indexes %d and %d\", i, j - 1); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } printf(\"No subarray found\"); return 0;} // Driver program to test above functionint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}",
"e": 44935,
"s": 43934,
"text": null
},
{
"code": "class SubarraySum { /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { int p = j - 1; System.out.println( \"Sum found between indexes \" + i + \" and \" + p); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } System.out.println(\"No subarray found\"); return 0; } public static void main(String[] args) { SubarraySum arraysum = new SubarraySum(); int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.length; int sum = 23; arraysum.subArraySum(arr, n, sum); }} // This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 46134,
"s": 44935,
"text": null
},
{
"code": "# Returns true if the# there is a subarray# of arr[] with sum# equal to 'sum' # otherwise returns# false. Also, prints# the result def subArraySum(arr, n, sum_): # Pick a starting # point for i in range(n): curr_sum = arr[i] # try all subarrays # starting with 'i' j = i + 1 while j <= n: if curr_sum == sum_: print (\"Sum found between\") print(\"indexes % d and % d\"%( i, j-1)) return 1 if curr_sum > sum_ or j == n: break curr_sum = curr_sum + arr[j] j += 1 print (\"No subarray found\") return 0 # Driver program arr = [15, 2, 4, 8, 9, 5, 10, 23]n = len(arr)sum_ = 23 subArraySum(arr, n, sum_) # This code is Contributed by shreyanshi_arun.",
"e": 47006,
"s": 46134,
"text": null
},
{
"code": "// C# code to Find subarray// with given sumusing System; class GFG { // Returns true if the there is a // subarray of arr[] with sum // equal to 'sum' otherwise returns // false. Also, prints the result int subArraySum(int[] arr, int n, int sum) { int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays // starting with 'i' for (j = i + 1; j <= n; j++) { if (curr_sum == sum) { int p = j - 1; Console.Write(\"Sum found between \" + \"indexes \" + i + \" and \" + p); return 1; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } Console.Write(\"No subarray found\"); return 0; } // Driver Code public static void Main() { GFG arraysum = new GFG(); int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.Length; int sum = 23; arraysum.subArraySum(arr, n, sum); }} // This code has been contributed// by nitin mittal",
"e": 48254,
"s": 47006,
"text": null
},
{
"code": "<?php// A simple program to print subarray// with sum as given sum /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */function subArraySum($arr, $n, $sum){ $curr_sum; $i; $j; // Pick a starting point for ($i = 0; $i < $n; $i++) { $curr_sum = $arr[$i]; // try all subarrays // starting with 'i' for ($j = $i + 1; $j <= $n; $j++) { if ($curr_sum == $sum) { echo \"Sum found between indexes \", $i, \" and \", $j-1 ; return 1; } if ($curr_sum > $sum || $j == $n) break; $curr_sum = $curr_sum + $arr[$j]; } } echo \"No subarray found\"; return 0;} // Driver Code $arr= array(15, 2, 4, 8, 9, 5, 10, 23); $n = sizeof($arr); $sum = 23; subArraySum($arr, $n, $sum); return 0; // This code is contributed by AJit?>",
"e": 49233,
"s": 48254,
"text": null
},
{
"code": "<script> /* A simple program to print subarray with sum as given sum */ /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */function subArraySum(arr, n, sum){ let curr_sum=0; // Pick a starting point for (let i = 0; i < n; i++) { curr_sum = arr[i]; // try all subarrays starting with 'i' for (let j = i + 1; j <= n; j++) { if (curr_sum == sum) { document.write(\"Sum found between indexes \"+i+\" and \"+(j - 1)); return; } if (curr_sum > sum || j == n) break; curr_sum = curr_sum + arr[j]; } } document.write(\"No subarray found\"); return;} // Driver Code let arr= [15, 2, 4, 8, 9, 5, 10, 23];let n = arr.length;let sum = 23;subArraySum(arr, n, sum); </script>",
"e": 50113,
"s": 49233,
"text": null
},
{
"code": null,
"e": 50147,
"s": 50113,
"text": "Sum found between indexes 1 and 4"
},
{
"code": null,
"e": 50170,
"s": 50147,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 50284,
"s": 50170,
"text": "Time Complexity: O(n^2) in worst case. Nested loop is used to traverse the array so the time complexity is O(n^2)"
},
{
"code": null,
"e": 50345,
"s": 50284,
"text": "Space Complexity: O(1). As constant extra space is required."
},
{
"code": null,
"e": 50825,
"s": 50345,
"text": "Efficient Approach: There is an idea if all the elements of the array are positive. If a subarray has sum greater than the given sum then there is no possibility that adding elements to the current subarray the sum will be x (given sum). Idea is to use a similar approach to a sliding window. Start with an empty subarray, add elements to the subarray until the sum is less than x. If the sum is greater than x, remove elements from the start of the current subarray.Algorithm: "
},
{
"code": null,
"e": 51154,
"s": 50825,
"text": "Create three variables, l=0, sum = 0Traverse the array from start to end.Update the variable sum by adding current element, sum = sum + array[i]If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++.If the sum is equal to given sum, print the subarray and break the loop."
},
{
"code": null,
"e": 51191,
"s": 51154,
"text": "Create three variables, l=0, sum = 0"
},
{
"code": null,
"e": 51229,
"s": 51191,
"text": "Traverse the array from start to end."
},
{
"code": null,
"e": 51301,
"s": 51229,
"text": "Update the variable sum by adding current element, sum = sum + array[i]"
},
{
"code": null,
"e": 51414,
"s": 51301,
"text": "If the sum is greater than the given sum, update the variable sum as sum = sum – array[l], and update l as, l++."
},
{
"code": null,
"e": 51487,
"s": 51414,
"text": "If the sum is equal to given sum, print the subarray and break the loop."
},
{
"code": null,
"e": 51491,
"s": 51487,
"text": "C++"
},
{
"code": null,
"e": 51493,
"s": 51491,
"text": "C"
},
{
"code": null,
"e": 51498,
"s": 51493,
"text": "Java"
},
{
"code": null,
"e": 51506,
"s": 51498,
"text": "Python3"
},
{
"code": null,
"e": 51509,
"s": 51506,
"text": "C#"
},
{
"code": null,
"e": 51513,
"s": 51509,
"text": "PHP"
},
{
"code": null,
"e": 51524,
"s": 51513,
"text": "Javascript"
},
{
"code": "/* An efficient program to print subarray with sum as given sum */#include <iostream>using namespace std; /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ int curr_sum = arr[0], start = 0, i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { cout << \"Sum found between indexes \" << start << \" and \" << i - 1; return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } // If we reach here, then no subarray cout << \"No subarray found\"; return 0;} // Driver Codeint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 52925,
"s": 51524,
"text": null
},
{
"code": "/* An efficient program to print subarray with sum as given sum */#include <stdio.h> /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ int curr_sum = arr[0], start = 0, i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { printf( \"Sum found between indexes %d and %d\", start, i - 1); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } // If we reach here, then no subarray printf(\"No subarray found\"); return 0;} // Driver program to test above functionint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}",
"e": 54297,
"s": 52925,
"text": null
},
{
"code": "class SubarraySum { /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { int curr_sum = arr[0], start = 0, i; // Pick a starting point for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { int p = i - 1; System.out.println( \"Sum found between indexes \" + start + \" and \" + p); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } System.out.println(\"No subarray found\"); return 0; } public static void main(String[] args) { SubarraySum arraysum = new SubarraySum(); int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.length; int sum = 23; arraysum.subArraySum(arr, n, sum); }} // This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 55658,
"s": 54297,
"text": null
},
{
"code": "# An efficient program # to print subarray# with sum as given sum # Returns true if the # there is a subarray # of arr[] with sum# equal to 'sum' # otherwise returns # false. Also, prints # the result.def subArraySum(arr, n, sum_): # Initialize curr_sum as # value of first element # and starting point as 0 curr_sum = arr[0] start = 0 # Add elements one by # one to curr_sum and # if the curr_sum exceeds # the sum, then remove # starting element i = 1 while i <= n: # If curr_sum exceeds # the sum, then remove # the starting elements while curr_sum > sum_ and start < i-1: curr_sum = curr_sum - arr[start] start += 1 # If curr_sum becomes # equal to sum, then # return true if curr_sum == sum_: print (\"Sum found between indexes\") print (\"% d and % d\"%(start, i-1)) return 1 # Add this element # to curr_sum if i < n: curr_sum = curr_sum + arr[i] i += 1 # If we reach here, # then no subarray print (\"No subarray found\") return 0 # Driver programarr = [15, 2, 4, 8, 9, 5, 10, 23]n = len(arr)sum_ = 23 subArraySum(arr, n, sum_) # This code is Contributed by shreyanshi_arun.",
"e": 56992,
"s": 55658,
"text": null
},
{
"code": "// An efficient C# program to print// subarray with sum as given sumusing System; class GFG { // Returns true if the // there is a subarray of // arr[] with sum equal to // 'sum' otherwise returns false. // Also, prints the result int subArraySum(int[] arr, int n, int sum) { int curr_sum = arr[0], start = 0, i; // Pick a starting point for (i = 1; i <= n; i++) { // If curr_sum exceeds // the sum, then remove // the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to // sum, then return true if (curr_sum == sum) { int p = i - 1; Console.WriteLine(\"Sum found between \" + \"indexes \" + start + \" and \" + p); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } Console.WriteLine(\"No subarray found\"); return 0; } // Driver code public static void Main() { GFG arraysum = new GFG(); int[] arr = new int[] { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.Length; int sum = 23; arraysum.subArraySum(arr, n, sum); }} // This code has been contributed by KRV.",
"e": 58492,
"s": 56992,
"text": null
},
{
"code": "<?php/* An efficient program to print subarray with sum as given sum */ /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */function subArraySum($arr, $n, $sum){ /* Initialize curr_sum as value of first element and starting point as 0 */ $curr_sum = $arr[0]; $start = 0; $i; /* Add elements one by one to curr_sum and if the curr_sum exceeds the sum, then remove starting element */ for ($i = 1; $i <= $n; $i++) { // If curr_sum exceeds the sum, // then remove the starting elements while ($curr_sum > $sum and $start < $i - 1) { $curr_sum = $curr_sum - $arr[$start]; $start++; } // If curr_sum becomes equal // to sum, then return true if ($curr_sum == $sum) { echo \"Sum found between indexes\", \" \", $start, \" \", \"and \", \" \", $i - 1; return 1; } // Add this element // to curr_sum if ($i < $n) $curr_sum = $curr_sum + $arr[$i]; } // If we reach here, // then no subarray echo \"No subarray found\"; return 0;} // Driver Code$arr = array(15, 2, 4, 8, 9, 5, 10, 23);$n = count($arr);$sum = 23;subArraySum($arr, $n, $sum); // This code has been// contributed by anuj_67.?>",
"e": 59951,
"s": 58492,
"text": null
},
{
"code": "<script>/* Returns true if the there isa subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ function subArraySum(arr,n,sum) { let curr_sum = arr[0], start = 0, i; // Pick a starting point for (i = 1; i <= n; i++) { // If curr_sum exceeds the sum, // then remove the starting elements while (curr_sum > sum && start < i - 1) { curr_sum = curr_sum - arr[start]; start++; } // If curr_sum becomes equal to sum, // then return true if (curr_sum == sum) { let p = i - 1; document.write( \"Sum found between indexes \" + start + \" and \" + p+\"<br>\"); return 1; } // Add this element to curr_sum if (i < n) curr_sum = curr_sum + arr[i]; } document.write(\"No subarray found\"); return 0; } let arr=[15, 2, 4, 8, 9, 5, 10, 23 ]; let n = arr.length; let sum = 23; subArraySum(arr, n, sum); // This code is contributed by unknown2108</script>",
"e": 61162,
"s": 59951,
"text": null
},
{
"code": null,
"e": 61196,
"s": 61162,
"text": "Sum found between indexes 1 and 4"
},
{
"code": null,
"e": 61219,
"s": 61196,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 61505,
"s": 61219,
"text": "Time Complexity : O(n). The Array is traversed only once to insert elements into the window. It will take O(N) timeThe Array is traversed again once to remove elements from the window. It will also take O(N) time.So the total time will be O(N) + O(N) = O(2*N), which is similar to O(N)"
},
{
"code": null,
"e": 61597,
"s": 61505,
"text": "The Array is traversed only once to insert elements into the window. It will take O(N) time"
},
{
"code": null,
"e": 61696,
"s": 61597,
"text": "The Array is traversed again once to remove elements from the window. It will also take O(N) time."
},
{
"code": null,
"e": 61769,
"s": 61696,
"text": "So the total time will be O(N) + O(N) = O(2*N), which is similar to O(N)"
},
{
"code": null,
"e": 61830,
"s": 61769,
"text": "Space Complexity: O(1). As constant extra space is required."
},
{
"code": null,
"e": 62694,
"s": 61830,
"text": "YouTubeGeeksforGeeks506K subscribersFind subarray with given sum | Set 1 (Non-negative Numbers) | GeeksforGeeksWatch laterShareCopy link71/101InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:50•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=GY-KULykGaw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 62810,
"s": 62694,
"text": "The above solution doesn’t handle negative numbers. We can use hashing to handle negative numbers. See below set 2."
},
{
"code": null,
"e": 62874,
"s": 62810,
"text": "Find subarray with given sum | Set 2 (Handles Negative Numbers)"
},
{
"code": null,
"e": 62944,
"s": 62874,
"text": "Find subarray with given sum with negatives allowed in constant space"
},
{
"code": null,
"e": 63070,
"s": 62944,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 63074,
"s": 63070,
"text": "KRV"
},
{
"code": null,
"e": 63080,
"s": 63074,
"text": "jit_t"
},
{
"code": null,
"e": 63093,
"s": 63080,
"text": "nitin mittal"
},
{
"code": null,
"e": 63098,
"s": 63093,
"text": "vt_m"
},
{
"code": null,
"e": 63112,
"s": 63098,
"text": "rathbhupendra"
},
{
"code": null,
"e": 63124,
"s": 63112,
"text": "gfg_sal_gfg"
},
{
"code": null,
"e": 63135,
"s": 63124,
"text": "nidhi_biet"
},
{
"code": null,
"e": 63150,
"s": 63135,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 63161,
"s": 63150,
"text": "andrew1234"
},
{
"code": null,
"e": 63176,
"s": 63161,
"text": "ch17btech11023"
},
{
"code": null,
"e": 63191,
"s": 63176,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 63203,
"s": 63191,
"text": "unknown2108"
},
{
"code": null,
"e": 63212,
"s": 63203,
"text": "sooda367"
},
{
"code": null,
"e": 63221,
"s": 63212,
"text": "sweetyty"
},
{
"code": null,
"e": 63233,
"s": 63221,
"text": "anikakapoor"
},
{
"code": null,
"e": 63247,
"s": 63233,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 63254,
"s": 63247,
"text": "Amazon"
},
{
"code": null,
"e": 63263,
"s": 63254,
"text": "Facebook"
},
{
"code": null,
"e": 63271,
"s": 63263,
"text": "FactSet"
},
{
"code": null,
"e": 63278,
"s": 63271,
"text": "Google"
},
{
"code": null,
"e": 63293,
"s": 63278,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 63308,
"s": 63293,
"text": "sliding-window"
},
{
"code": null,
"e": 63317,
"s": 63308,
"text": "subarray"
},
{
"code": null,
"e": 63330,
"s": 63317,
"text": "subarray-sum"
},
{
"code": null,
"e": 63335,
"s": 63330,
"text": "Visa"
},
{
"code": null,
"e": 63340,
"s": 63335,
"text": "Zoho"
},
{
"code": null,
"e": 63347,
"s": 63340,
"text": "Arrays"
},
{
"code": null,
"e": 63352,
"s": 63347,
"text": "Zoho"
},
{
"code": null,
"e": 63367,
"s": 63352,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 63374,
"s": 63367,
"text": "Amazon"
},
{
"code": null,
"e": 63382,
"s": 63374,
"text": "FactSet"
},
{
"code": null,
"e": 63387,
"s": 63382,
"text": "Visa"
},
{
"code": null,
"e": 63394,
"s": 63387,
"text": "Google"
},
{
"code": null,
"e": 63403,
"s": 63394,
"text": "Facebook"
},
{
"code": null,
"e": 63418,
"s": 63403,
"text": "sliding-window"
},
{
"code": null,
"e": 63425,
"s": 63418,
"text": "Arrays"
},
{
"code": null,
"e": 63523,
"s": 63425,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 63538,
"s": 63523,
"text": "Arrays in Java"
},
{
"code": null,
"e": 63554,
"s": 63538,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 63600,
"s": 63554,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 63627,
"s": 63600,
"text": "Program for array rotation"
},
{
"code": null,
"e": 63659,
"s": 63627,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 63703,
"s": 63659,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 63751,
"s": 63703,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 63774,
"s": 63751,
"text": "Introduction to Arrays"
}
]
|
How to validate if input in input field must contains a seed word using express-validator ? - GeeksforGeeks | 14 Jan, 2022
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, we often need to validate input so that it must contain a seed word i.e. input can be anything(any string) but must contain a particular word(seed word). We can also validate these input fields to accept only those values that contain the seed word using express-validator middleware.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on validation contains(seed) with ‘ . ‘
If want to ignore the case sensitivity add options object argument {ignoreCase:true}. By default ignoreCase set to true.
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate a input field to only allow the values that contains the seed word.
Filename – index.js
javascript
const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validatePlayerName } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/info', [validatePlayerName], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {name, dept, event, pname} = req.body // New record await repo.create({ 'Name':name, 'Department':dept, 'Event Name':event, 'Player Name':pname, }) res.send('<strong>Registered Successfully for the event!!</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs) { // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')
Filename – form.js: This file contains logic to show the form to submit the data.
javascript
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/info' method='POST'> <div> <div> <label class='label' id='name'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Vinit singh' for='name'> </div> <div> <div> <label class='label' id='dept'> Department </label> </div> <input class='input' type='text' name='dept' placeholder='Department' for='dept'> </div> <div> <div> <label class='label' id='event'> Event Name </label> </div> <input class='input' type='text' name='event' placeholder='Event Name' for='event'> </div> <div> <div> <label class='label' id='pname'> Player Name </label> </div> <input class='input' type='text' name='pname' placeholder= "Player Name must contains the word 'jolite'" for='pname'> <p class="help is-danger"> ${getError(errors, 'pname')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}
Filename – validator.js: This file contain all the validation logic (Logic to validate an input field to only allow the value that contains the seed word).
javascript
const {check} = require('express-validator')const repo = require('./repository')module.exports = { validatePlayerName : check('pname') // To delete leading and trailing space .trim() // Validate player name to accept only // the string that contains the word 'jolite' // ignorecase is an optional attribute // and it is by default set to false if // ignorecase attribute set to be true, // it ignores the case sensitivity // of the required seed word .contains('jolite', { ignoreCase: true}) // Custom message .withMessage("Player Name must contains the word 'jolite'") }
Filename – package.json
package.json file
Database:
Database
Output:
Attempt to submit form data when player name input field not contains the seed word ‘jolite’
Response when attempt to submit form data where player name input field not contains the seed word ‘jolite’
Attempt to submit form data when player name input field contains the seed word ‘jolite’
Attempt to submit form data when player name input field contains the seed word ‘jolite'(in capital letter)
Response when attempt to submit form data where player name input field contains the seed word ‘jolite’
Database after successful submission of form:
Database after successful submission of form
Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content.
kk9826225
clintra
Express.js
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26897,
"s": 26869,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 27428,
"s": 26897,
"text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, we often need to validate input so that it must contain a seed word i.e. input can be anything(any string) but must contain a particular word(seed word). We can also validate these input fields to accept only those values that contain the seed word using express-validator middleware."
},
{
"code": null,
"e": 27466,
"s": 27428,
"text": "Command to install express-validator:"
},
{
"code": null,
"e": 27496,
"s": 27466,
"text": "npm install express-validator"
},
{
"code": null,
"e": 27551,
"s": 27496,
"text": "Steps to use express-validator to implement the logic:"
},
{
"code": null,
"e": 27589,
"s": 27551,
"text": "Install express-validator middleware."
},
{
"code": null,
"e": 27650,
"s": 27589,
"text": "Create a validator.js file to code all the validation logic."
},
{
"code": null,
"e": 27762,
"s": 27650,
"text": "Validate input by validateInputField: check(input field name) and chain on validation contains(seed) with ‘ . ‘"
},
{
"code": null,
"e": 27883,
"s": 27762,
"text": "If want to ignore the case sensitivity add options object argument {ignoreCase:true}. By default ignoreCase set to true."
},
{
"code": null,
"e": 27985,
"s": 27883,
"text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations."
},
{
"code": null,
"e": 28078,
"s": 27985,
"text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors."
},
{
"code": null,
"e": 28151,
"s": 28078,
"text": "If error occurs redirect to the same page passing the error information."
},
{
"code": null,
"e": 28227,
"s": 28151,
"text": "If error list is empty, give access to the user for the subsequent request."
},
{
"code": null,
"e": 28393,
"s": 28227,
"text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."
},
{
"code": null,
"e": 28511,
"s": 28393,
"text": "Example: This example illustrates how to validate a input field to only allow the values that contains the seed word."
},
{
"code": null,
"e": 28531,
"s": 28511,
"text": "Filename – index.js"
},
{
"code": null,
"e": 28542,
"s": 28531,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validatePlayerName } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/info', [validatePlayerName], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()) { return res.send(formTemplet({errors})) } const {name, dept, event, pname} = req.body // New record await repo.create({ 'Name':name, 'Department':dept, 'Event Name':event, 'Player Name':pname, }) res.send('<strong>Registered Successfully for the event!!</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 29636,
"s": 28542,
"text": null
},
{
"code": null,
"e": 29744,
"s": 29636,
"text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it."
},
{
"code": null,
"e": 29755,
"s": 29744,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // Filename where datas are going to store if(!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs) { // Fetch all existing records const records = await this.getAll() // All the existing records with new // record push back to database records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 30892,
"s": 29755,
"text": null
},
{
"code": null,
"e": 30974,
"s": 30892,
"text": "Filename – form.js: This file contains logic to show the form to submit the data."
},
{
"code": null,
"e": 30985,
"s": 30974,
"text": "javascript"
},
{
"code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return `<!DOCTYPE html><html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns { margin-top: 100px; } .button { margin-top: 10px } </style></head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/info' method='POST'> <div> <div> <label class='label' id='name'> Name </label> </div> <input class='input' type='text' name='name' placeholder='Vinit singh' for='name'> </div> <div> <div> <label class='label' id='dept'> Department </label> </div> <input class='input' type='text' name='dept' placeholder='Department' for='dept'> </div> <div> <div> <label class='label' id='event'> Event Name </label> </div> <input class='input' type='text' name='event' placeholder='Event Name' for='event'> </div> <div> <div> <label class='label' id='pname'> Player Name </label> </div> <input class='input' type='text' name='pname' placeholder= \"Player Name must contains the word 'jolite'\" for='pname'> <p class=\"help is-danger\"> ${getError(errors, 'pname')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div></body> </html> `}",
"e": 32968,
"s": 30985,
"text": null
},
{
"code": null,
"e": 33124,
"s": 32968,
"text": "Filename – validator.js: This file contain all the validation logic (Logic to validate an input field to only allow the value that contains the seed word)."
},
{
"code": null,
"e": 33135,
"s": 33124,
"text": "javascript"
},
{
"code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validatePlayerName : check('pname') // To delete leading and trailing space .trim() // Validate player name to accept only // the string that contains the word 'jolite' // ignorecase is an optional attribute // and it is by default set to false if // ignorecase attribute set to be true, // it ignores the case sensitivity // of the required seed word .contains('jolite', { ignoreCase: true}) // Custom message .withMessage(\"Player Name must contains the word 'jolite'\") }",
"e": 33751,
"s": 33135,
"text": null
},
{
"code": null,
"e": 33775,
"s": 33751,
"text": "Filename – package.json"
},
{
"code": null,
"e": 33793,
"s": 33775,
"text": "package.json file"
},
{
"code": null,
"e": 33803,
"s": 33793,
"text": "Database:"
},
{
"code": null,
"e": 33812,
"s": 33803,
"text": "Database"
},
{
"code": null,
"e": 33820,
"s": 33812,
"text": "Output:"
},
{
"code": null,
"e": 33914,
"s": 33820,
"text": "Attempt to submit form data when player name input field not contains the seed word ‘jolite’"
},
{
"code": null,
"e": 34023,
"s": 33914,
"text": "Response when attempt to submit form data where player name input field not contains the seed word ‘jolite’"
},
{
"code": null,
"e": 34113,
"s": 34023,
"text": "Attempt to submit form data when player name input field contains the seed word ‘jolite’"
},
{
"code": null,
"e": 34222,
"s": 34113,
"text": "Attempt to submit form data when player name input field contains the seed word ‘jolite'(in capital letter)"
},
{
"code": null,
"e": 34326,
"s": 34222,
"text": "Response when attempt to submit form data where player name input field contains the seed word ‘jolite’"
},
{
"code": null,
"e": 34372,
"s": 34326,
"text": "Database after successful submission of form:"
},
{
"code": null,
"e": 34417,
"s": 34372,
"text": "Database after successful submission of form"
},
{
"code": null,
"e": 34513,
"s": 34417,
"text": "Note: We have used some Bulma classes(CSS framework) in the form.js file to design the content."
},
{
"code": null,
"e": 34523,
"s": 34513,
"text": "kk9826225"
},
{
"code": null,
"e": 34531,
"s": 34523,
"text": "clintra"
},
{
"code": null,
"e": 34542,
"s": 34531,
"text": "Express.js"
},
{
"code": null,
"e": 34555,
"s": 34542,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 34563,
"s": 34555,
"text": "Node.js"
},
{
"code": null,
"e": 34580,
"s": 34563,
"text": "Web Technologies"
},
{
"code": null,
"e": 34678,
"s": 34580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34708,
"s": 34678,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 34737,
"s": 34708,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 34794,
"s": 34737,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 34848,
"s": 34794,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 34885,
"s": 34848,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 34925,
"s": 34885,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34970,
"s": 34925,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35013,
"s": 34970,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 35063,
"s": 35013,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
ByteBuffer getLong() method in Java with Examples - GeeksforGeeks | 17 Jun, 2019
The getLong() method of java.nio.ByteBuffer class is used to read the next eight bytes at this buffer’s current position, composing them into a long value according to the current byte order, and then increments the position by eight.
Syntax:
public abstract long getLong()
Return Value: This method returns the long value at the buffer’s current position.
Throws: This method throws BufferUnderflowException – If there are fewer than four bytes remaining in this buffer.
Below are the examples to illustrate the getLong() method:
Examples 1:
// Java program to demonstrate// getLong() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 16; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the long value in the bytebuffer bb.asLongBuffer() .put(1233003) .put(2292292); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 8; i++) System.out.print(bb.getLong() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the long at this buffer's current position // using getLong() method long value = bb.getLong(); // print the long value System.out.println("\n\nByte Value: " + value); // Reads the long at this buffer's next position // using getLong() method long value1 = bb.getLong(); // print the long value System.out.print("\nNext Byte Value: " + value1); } catch (BufferUnderflowException e) { System.out.println("\nException Thrown : " + e); } }}
Original ByteBuffer:
1233003 2292292
Byte Value: 1233003
Next Byte Value: 2292292
Examples 2:
// Java program to demonstrate// getLong() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 16; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the long value in the bytebuffer bb.asLongBuffer() .put(1233003) .put(2292292); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 8; i++) System.out.print(bb.getLong() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the long at this buffer's current position // using getLong() method long value = bb.getLong(); // print the long value System.out.println("\n\nByte Value: " + value); // Reads the long at this buffer's next position // using getLong() method long value1 = bb.getLong(); // print the long value System.out.print("\nNext Byte Value: " + value1); // Reads the long at this buffer's next position // using getLong() method long value2 = bb.getLong(); } catch (BufferUnderflowException e) { System.out.println("\nthere are fewer than " + "eight bytes remaining in this buffer"); System.out.println("Exception Thrown : " + e); } }}
Original ByteBuffer:
1233003 2292292
Byte Value: 1233003
Next Byte Value: 2292292
there are fewer than eight bytes remaining in this buffer
Exception Thrown : java.nio.BufferUnderflowException
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getLong–
The getLong(int index) method of ByteBuffer is used to read four bytes at the given index, composing them into a float value according to the current byte order.
Syntax:
public abstract long getLong(int index)
Parameters: This method takes index (The index from which the Byte will be read) as a parameter.
Return Value: This method returns the long value at the given index.
Exception: This method throws IndexOutOfBoundsException. If index is negative or not smaller than the buffer’s limit this exception is thrown.
Below are the examples to illustrate the getLong(int index) method:
Examples 1:
// Java program to demonstrate// getLong() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 16; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the long value in the bytebuffer bb.asLongBuffer() .put(1233003) .put(2292292); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 8; i++) System.out.print(bb.getLong() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the long at this buffer's current position // using getLong() method long value = bb.getLong(0); // print the long value System.out.println("\n\nByte Value: " + value); // Reads the long at this buffer's next position // using getLong() method long value1 = bb.getLong(8); // print the long value System.out.print("\nNext Byte Value: " + value1); } catch (IndexOutOfBoundsException e) { System.out.println("\nindex is negative or " + "smaller than the buffer's limit, " + "minus seven"); System.out.println("Exception Thrown : " + e); } }}
Original ByteBuffer:
1233003 2292292
Byte Value: 1233003
Next Byte Value: 2292292
Examples 2:
// Java program to demonstrate// getLong() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 16; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the long value in the bytebuffer bb.asLongBuffer() .put(1233003) .put(2292292); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 8; i++) System.out.print(bb.getLong() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the long at this buffer's current position // using getLong() method long value = bb.getLong(0); // print the long value System.out.println("\n\nByte Value: " + value); // Reads the long at this buffer's next position // using getLong() method long value1 = bb.getLong(11); // print the long value System.out.print("\nNext Byte Value: " + value1); } catch (IndexOutOfBoundsException e) { System.out.println("\nindex is negative or" + " smaller than the buffer's limit, " + "minus seven"); System.out.println("Exception Thrown : " + e); } }}
Original ByteBuffer:
1233003 2292292
Byte Value: 1233003
index is negative or smaller than the buffer's limit, minus seven
Exception Thrown : java.lang.IndexOutOfBoundsException
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getLong-int-
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
PriorityQueue in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n17 Jun, 2019"
},
{
"code": null,
"e": 25582,
"s": 25347,
"text": "The getLong() method of java.nio.ByteBuffer class is used to read the next eight bytes at this buffer’s current position, composing them into a long value according to the current byte order, and then increments the position by eight."
},
{
"code": null,
"e": 25590,
"s": 25582,
"text": "Syntax:"
},
{
"code": null,
"e": 25621,
"s": 25590,
"text": "public abstract long getLong()"
},
{
"code": null,
"e": 25704,
"s": 25621,
"text": "Return Value: This method returns the long value at the buffer’s current position."
},
{
"code": null,
"e": 25819,
"s": 25704,
"text": "Throws: This method throws BufferUnderflowException – If there are fewer than four bytes remaining in this buffer."
},
{
"code": null,
"e": 25878,
"s": 25819,
"text": "Below are the examples to illustrate the getLong() method:"
},
{
"code": null,
"e": 25890,
"s": 25878,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// getLong() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 16; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the long value in the bytebuffer bb.asLongBuffer() .put(1233003) .put(2292292); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= capacity / 8; i++) System.out.print(bb.getLong() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the long at this buffer's current position // using getLong() method long value = bb.getLong(); // print the long value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the long at this buffer's next position // using getLong() method long value1 = bb.getLong(); // print the long value System.out.print(\"\\nNext Byte Value: \" + value1); } catch (BufferUnderflowException e) { System.out.println(\"\\nException Thrown : \" + e); } }}",
"e": 27394,
"s": 25890,
"text": null
},
{
"code": null,
"e": 27481,
"s": 27394,
"text": "Original ByteBuffer: \n1233003 2292292 \n\nByte Value: 1233003\n\nNext Byte Value: 2292292\n"
},
{
"code": null,
"e": 27493,
"s": 27481,
"text": "Examples 2:"
},
{
"code": "// Java program to demonstrate// getLong() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 16; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the long value in the bytebuffer bb.asLongBuffer() .put(1233003) .put(2292292); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= capacity / 8; i++) System.out.print(bb.getLong() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the long at this buffer's current position // using getLong() method long value = bb.getLong(); // print the long value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the long at this buffer's next position // using getLong() method long value1 = bb.getLong(); // print the long value System.out.print(\"\\nNext Byte Value: \" + value1); // Reads the long at this buffer's next position // using getLong() method long value2 = bb.getLong(); } catch (BufferUnderflowException e) { System.out.println(\"\\nthere are fewer than \" + \"eight bytes remaining in this buffer\"); System.out.println(\"Exception Thrown : \" + e); } }}",
"e": 29261,
"s": 27493,
"text": null
},
{
"code": null,
"e": 29459,
"s": 29261,
"text": "Original ByteBuffer: \n1233003 2292292 \n\nByte Value: 1233003\n\nNext Byte Value: 2292292\nthere are fewer than eight bytes remaining in this buffer\nException Thrown : java.nio.BufferUnderflowException\n"
},
{
"code": null,
"e": 29546,
"s": 29459,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getLong–"
},
{
"code": null,
"e": 29708,
"s": 29546,
"text": "The getLong(int index) method of ByteBuffer is used to read four bytes at the given index, composing them into a float value according to the current byte order."
},
{
"code": null,
"e": 29716,
"s": 29708,
"text": "Syntax:"
},
{
"code": null,
"e": 29756,
"s": 29716,
"text": "public abstract long getLong(int index)"
},
{
"code": null,
"e": 29853,
"s": 29756,
"text": "Parameters: This method takes index (The index from which the Byte will be read) as a parameter."
},
{
"code": null,
"e": 29922,
"s": 29853,
"text": "Return Value: This method returns the long value at the given index."
},
{
"code": null,
"e": 30065,
"s": 29922,
"text": "Exception: This method throws IndexOutOfBoundsException. If index is negative or not smaller than the buffer’s limit this exception is thrown."
},
{
"code": null,
"e": 30133,
"s": 30065,
"text": "Below are the examples to illustrate the getLong(int index) method:"
},
{
"code": null,
"e": 30145,
"s": 30133,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// getLong() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 16; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the long value in the bytebuffer bb.asLongBuffer() .put(1233003) .put(2292292); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= capacity / 8; i++) System.out.print(bb.getLong() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the long at this buffer's current position // using getLong() method long value = bb.getLong(0); // print the long value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the long at this buffer's next position // using getLong() method long value1 = bb.getLong(8); // print the long value System.out.print(\"\\nNext Byte Value: \" + value1); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nindex is negative or \" + \"smaller than the buffer's limit, \" + \"minus seven\"); System.out.println(\"Exception Thrown : \" + e); } }}",
"e": 31822,
"s": 30145,
"text": null
},
{
"code": null,
"e": 31909,
"s": 31822,
"text": "Original ByteBuffer: \n1233003 2292292 \n\nByte Value: 1233003\n\nNext Byte Value: 2292292\n"
},
{
"code": null,
"e": 31921,
"s": 31909,
"text": "Examples 2:"
},
{
"code": "// Java program to demonstrate// getLong() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 16; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the long value in the bytebuffer bb.asLongBuffer() .put(1233003) .put(2292292); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= capacity / 8; i++) System.out.print(bb.getLong() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the long at this buffer's current position // using getLong() method long value = bb.getLong(0); // print the long value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the long at this buffer's next position // using getLong() method long value1 = bb.getLong(11); // print the long value System.out.print(\"\\nNext Byte Value: \" + value1); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nindex is negative or\" + \" smaller than the buffer's limit, \" + \"minus seven\"); System.out.println(\"Exception Thrown : \" + e); } }}",
"e": 33599,
"s": 31921,
"text": null
},
{
"code": null,
"e": 33782,
"s": 33599,
"text": "Original ByteBuffer: \n1233003 2292292 \n\nByte Value: 1233003\n\nindex is negative or smaller than the buffer's limit, minus seven\nException Thrown : java.lang.IndexOutOfBoundsException\n"
},
{
"code": null,
"e": 33873,
"s": 33782,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getLong-int-"
},
{
"code": null,
"e": 33889,
"s": 33873,
"text": "Java-ByteBuffer"
},
{
"code": null,
"e": 33904,
"s": 33889,
"text": "Java-Functions"
},
{
"code": null,
"e": 33921,
"s": 33904,
"text": "Java-NIO package"
},
{
"code": null,
"e": 33926,
"s": 33921,
"text": "Java"
},
{
"code": null,
"e": 33931,
"s": 33926,
"text": "Java"
},
{
"code": null,
"e": 34029,
"s": 33931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34044,
"s": 34029,
"text": "Stream In Java"
},
{
"code": null,
"e": 34063,
"s": 34044,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 34084,
"s": 34063,
"text": "Constructors in Java"
},
{
"code": null,
"e": 34130,
"s": 34084,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 34160,
"s": 34130,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 34177,
"s": 34160,
"text": "Generics in Java"
},
{
"code": null,
"e": 34220,
"s": 34177,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 34241,
"s": 34220,
"text": "Introduction to Java"
},
{
"code": null,
"e": 34263,
"s": 34241,
"text": "PriorityQueue in Java"
}
]
|
How to clear Tkinter Canvas? - GeeksforGeeks | 11 Dec, 2020
Tkinter is a Python Package for creating effective GUI applications. Tkinter’s Canvas widget is nothing but a rectangular area that is used for drawing pictures, simple shapes, or any complex graph. We can place any widgets like text, button, or frames on the canvas.
The task here is to generate a Python script that can clear Tkinter Canvas. For that delete function of this module will be employed. This method has a special parameter all which represents all the component on the canvas. To clear this canvas give this special parameter to the delete method. Thus, the line below is sufficient to clear the canvas:
delete('all')
If you want to delete any specific item then you can assign a tag to that item and instead of all pass that tag to the delete method.
Given below is the code to achieve this specific functionality:
Program:
Before clearing canvas
Python3
# import tkinterfrom tkinter import * # make an object of Tk interfacewindow = Tk() # Give the title to out windowwindow.title('GFG') # creating canvascanvas = Canvas(window, width=300, height=200)canvas.pack() # draw line to out canvascanvas.create_line(0, 0, 300, 200)canvas.create_line(0, 200, 300, 0) # draw oval to out canvascanvas.create_oval(50, 25, 250, 175, fill="yellow") window.mainloop()
Output:
Simple canvas Example
After clearing canvas
Python3
# import tkinterfrom tkinter import * # make an object of Tk interfacewindow = Tk() # Give the title to out windowwindow.title('GFG') # creating canvascanvas = Canvas(window, width=300, height=200)canvas.pack() # draw line to out canvascanvas.create_line(0, 0, 300, 200)canvas.create_line(0, 200, 300, 0) # draw oval to out canvascanvas.create_oval(50, 25, 250, 175, fill="yellow") # clear the canvascanvas.delete('all') window.mainloop()
Output:
Cleared canvas
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 25915,
"s": 25647,
"text": "Tkinter is a Python Package for creating effective GUI applications. Tkinter’s Canvas widget is nothing but a rectangular area that is used for drawing pictures, simple shapes, or any complex graph. We can place any widgets like text, button, or frames on the canvas."
},
{
"code": null,
"e": 26266,
"s": 25915,
"text": "The task here is to generate a Python script that can clear Tkinter Canvas. For that delete function of this module will be employed. This method has a special parameter all which represents all the component on the canvas. To clear this canvas give this special parameter to the delete method. Thus, the line below is sufficient to clear the canvas:"
},
{
"code": null,
"e": 26280,
"s": 26266,
"text": "delete('all')"
},
{
"code": null,
"e": 26416,
"s": 26280,
"text": "If you want to delete any specific item then you can assign a tag to that item and instead of all pass that tag to the delete method. "
},
{
"code": null,
"e": 26480,
"s": 26416,
"text": "Given below is the code to achieve this specific functionality:"
},
{
"code": null,
"e": 26489,
"s": 26480,
"text": "Program:"
},
{
"code": null,
"e": 26512,
"s": 26489,
"text": "Before clearing canvas"
},
{
"code": null,
"e": 26520,
"s": 26512,
"text": "Python3"
},
{
"code": "# import tkinterfrom tkinter import * # make an object of Tk interfacewindow = Tk() # Give the title to out windowwindow.title('GFG') # creating canvascanvas = Canvas(window, width=300, height=200)canvas.pack() # draw line to out canvascanvas.create_line(0, 0, 300, 200)canvas.create_line(0, 200, 300, 0) # draw oval to out canvascanvas.create_oval(50, 25, 250, 175, fill=\"yellow\") window.mainloop()",
"e": 26926,
"s": 26520,
"text": null
},
{
"code": null,
"e": 26934,
"s": 26926,
"text": "Output:"
},
{
"code": null,
"e": 26956,
"s": 26934,
"text": "Simple canvas Example"
},
{
"code": null,
"e": 26978,
"s": 26956,
"text": "After clearing canvas"
},
{
"code": null,
"e": 26986,
"s": 26978,
"text": "Python3"
},
{
"code": "# import tkinterfrom tkinter import * # make an object of Tk interfacewindow = Tk() # Give the title to out windowwindow.title('GFG') # creating canvascanvas = Canvas(window, width=300, height=200)canvas.pack() # draw line to out canvascanvas.create_line(0, 0, 300, 200)canvas.create_line(0, 200, 300, 0) # draw oval to out canvascanvas.create_oval(50, 25, 250, 175, fill=\"yellow\") # clear the canvascanvas.delete('all') window.mainloop()",
"e": 27432,
"s": 26986,
"text": null
},
{
"code": null,
"e": 27440,
"s": 27432,
"text": "Output:"
},
{
"code": null,
"e": 27455,
"s": 27440,
"text": "Cleared canvas"
},
{
"code": null,
"e": 27470,
"s": 27455,
"text": "Python-tkinter"
},
{
"code": null,
"e": 27494,
"s": 27470,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27501,
"s": 27494,
"text": "Python"
},
{
"code": null,
"e": 27520,
"s": 27501,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27618,
"s": 27520,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27650,
"s": 27618,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27692,
"s": 27650,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27734,
"s": 27692,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27790,
"s": 27734,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27817,
"s": 27790,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27848,
"s": 27817,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27884,
"s": 27848,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27913,
"s": 27884,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27935,
"s": 27913,
"text": "Defaultdict in Python"
}
]
|
A Practical Approach Using YOUR Uber Rides Dataset | by Felipe Alves Santos | Towards Data Science | Exploring data is certainly one of the most important stages in Data Science processes. Despite its simplicity, it can be a powerful tool to put you ahead on data and business context, as well as to determine crutial treatments before creating machine learning models.
To turn things a little bit more interesting, I’ve decided to have some fun with Python on my personal Uber rides data and see which insights I could extract.
In this post, I will guide you through the following steps:
1. Business Problem Definition
2. Data Discovery
3. Data Preparation
4. Data Analysis & Storytelling
Note: Data Preparation is usually a stage that requires lots of work around data formatting, cleansing and manipulation, but making your data CONSISTENT is surely a success factor for your analysis and future modeling.
Uber’s data download feature provides you in-depth information about your rides. You can request access to your data through the following link: https://myprivacy.uber.com/privacy/exploreyourdata/download
After your request is done, an email with the download link will be sent to you (usually in the same day).
For security purposes, your data is only available during 7 days.
Before starting manipulating and analysing data, the first thing you should do is to think about THE PURPOSE. What mean is that you should think about the reasons why you are up to conduct any analysis. If you are uncertain about this, simply starting formulating questions regarding your subject like What? When? Where? Who? Which? How? How many? How much?.
Depending on how many data and features you have, analysis could go to the infinite and beyond. So that’s why (after thinking process) I decided to focus on the following questions:
a. How many trips I did over the years?b. How many trips were Completed and Canceled?c. Where most of the dropoffs ocurred?d. What product type is usually chosen?e. What is the avg. fare, distance, amount and time spent on rides?f. Which weekdays have the highest average fares?g. Which was the longest/shortest and more expensive/cheaper ride?h. What is the average lead time before begining a trip?
Importing libraries and dataset.
Checking basic dataset information (data types and dimensions)
<class 'pandas.core.frame.DataFrame'>RangeIndex: 554 entries, 0 to 553Data columns (total 13 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 City 554 non-null int64 1 Product Type 551 non-null object 2 Trip or Order Status 554 non-null object 3 Request Time 554 non-null object 4 Begin Trip Time 554 non-null object 5 Begin Trip Lat 525 non-null float64 6 Begin Trip Lng 525 non-null float64 7 Dropoff Time 554 non-null object 8 Dropoff Lat 525 non-null float64 9 Dropoff Lng 525 non-null float64 10 Distance (miles) 554 non-null float64 11 Fare Amount 554 non-null float64 12 Fare Currency 551 non-null object dtypes: float64(6), int64(1), object(6)memory usage: 56.4+ KB
.rename( ) method allows you to rename axis labels (indexes and columns). In this case I decided to normalize column names to clean up coding, as long you can columns by typing <data_frame>.<column>
Use .head( ) method to gain more sensibility around data formatting and understand the overall structure of the dataset values.
Taking a look on the continuous variables, we notice the presence of some outliers. However these outliers do not seem to reflect any abnormal value (e.g. fare_amount = 1000 BRL), which may let us a little bit more comfortable.
P.S. In case abnormal values are found, some treatment should be probably considered (e.g. outliers replacement/removal).
The charts below show a different perspective of the variables distribution. In this case, we see that both variables present an assimetric distribution (positive). For distance we notice that the higher frequency values are shorter distances, and for fare amount we have the same behaviour.
Additionally, we also notice that the standard deviation are high, taking ‘means’ as our reference. This means that values in both variables are very dispersal.
Not surprisingly we have a strong correlation between ‘fare_amount’ and ‘distance_miles’, inferring that as much you stay on the ride, higher will the fare be.
sns.scatterplot(x='distance_miles',y='fare_amount',data=df1);
I decided to remove the column fare_currency, since all my trips happened inside a single country (Brazil).
Now let’s check existance of missing values.
Despite empty Lng and Lat values (29 total), there were found 3 records without product_type. As shown below, these records are insignificant to my dataset, since practically no columns are fulfilled.
So now, let’s get rid of these 3 records before proceding.
While analysing the first categorical column <product_type>, I could clearly see that some work was necessary, since I could find different values referring to the same category. Then, I summarized 15 original categories in 5 ones.
As the scope of this analysis is only around Uber rides, I removed UberEATS records from my dataset.
Our second categorical feature <status> seems well classified in 3 status, which will not require any kind of treatment.
Dates usually increase a lot your power of analysis, since you can break it down to different parts and generate insights from different perspectives. As previously shown, our dates features are in fact object data types, so we need to convert them into datetime format.
Now, let’s break down <request_time> feature into different date parts. I just did that for <request_time>, since I'm assuming that all rides were completed in the same day (believe me, I have already checked that! :D ).
Based on <fare_amount> and <distance_miles> features I've created a new feature called <amount_km>, which would help us understand how much is payed by kilometer ridden.
Delta time between <request_time> and <begin_time> will let us now how much time (in minutes) I usually waited for Uber cars to arrive at my destination. In this case, it was calculated in a minutes base.
Similarly, delta time between <dropoff_time> and <begin_time> will let us now how much time (in minutes) was spent on each trip.
As features in records with Canceled and Driver_Cancelled status will not be useful for my analysis, I set them as null values to clean up a little bit more my dataset.
RECOMMENDATION: Do not start your analysis without completing the Business Problem Definition, since it determines your analysis’ focus and quality. Besides that, this process will help you to think about new possibilities/questions while trying to answer the previous ones set.
NOTE: In order to organize better my analysis, I will create an additional dataframe, removing all trips with status CANCELED and DRIVER_CANCELED, since they should be disconsider in some questions.
A total of 444 trips were completed from Apr’16 to Jan’21. If we disconsider 2016 and 2021 (not full years), we can clearly see that from 2017 to 2019 the average rides per year is 124, and that there is a huge drop from 2019 to 2020 (-51%). This is easily explained by the COVID outbreak.
Now, imagine if we extrapolate this result to all Uber users...
Looking at the stacked bars below, we can see that excluding 2015 and 2021 (due to low trips volume), 2020 has the highest cancelation ratem. This could be an alarming indicator, considering the drastical impacts caused to the businesses after Covid outbreak. In overall, cancelation rate was 17.9% (considering RIDERS and DRIVERS cancelations).
The following heatmap dynamically shows the most frequented areas throughout different hues and intensities. This could be a valuable information for Uber to adjust prices and optimize demand in certain regions, also combining time space data to track users behaviours.
UberX is far the prefered product type with a frequency of 90.3%. So I could say I am the type of user which usually looks for affordable prices.
Considering all trips, the average amount spent by trip is 19.2 BRL, ridding in approx. 8.1 km. So, if we do a quick simulation on how much I would spend in a year to do daily round trips we would have: 365 days * 2 trips * 19.2 BRL/fare = 14,016 BRL/year
Also in average, It was spent approx. 2.4 BRL/km and 21.4 minutes by trip.
According to the chart below, we can see that Mondays, Wednesdays, Fridays and Sundays were (in average) the most expensive weekdays. Therefore, it allows us to better understand the weekly seasonality, and find out days with higher profitability for Uber and its drivers.
The table below show records with the longest (31.77 km) and shortest rides (0.24 km).
Analysing amount paid by km ridden we have: expensive (46.96 BRL/km) and cheaper (0 BRL/km). Cheaper trip certainly refers to a free ride, while the expensive cost 46.96 BRL. This effect is basicaly driven by fixed minimum fare in high demand periods, since the total distance was only 0.24km.
It takes approximately 5 minutes to start trips, after they are requested.
4.9 minutes
Exploratory Data Analysis is not a trivial task! It requires lots of work and patience, however it is surely a powerful tool if correctly applied to your business context.
This post briefly demonstrated some tips and steps to make analysis easier and undoubtely highlighted the crutial importance of a well defined business problem, guiding all coding effort to a specific objective, also highlighting important insights. This business case also tried to reflect a pratical application of python in daily business activities, showing how fun, valuable and interesting it could become.
Thank you so much for getting here! I hope you liked it! 😃 | [
{
"code": null,
"e": 441,
"s": 172,
"text": "Exploring data is certainly one of the most important stages in Data Science processes. Despite its simplicity, it can be a powerful tool to put you ahead on data and business context, as well as to determine crutial treatments before creating machine learning models."
},
{
"code": null,
"e": 600,
"s": 441,
"text": "To turn things a little bit more interesting, I’ve decided to have some fun with Python on my personal Uber rides data and see which insights I could extract."
},
{
"code": null,
"e": 660,
"s": 600,
"text": "In this post, I will guide you through the following steps:"
},
{
"code": null,
"e": 691,
"s": 660,
"text": "1. Business Problem Definition"
},
{
"code": null,
"e": 709,
"s": 691,
"text": "2. Data Discovery"
},
{
"code": null,
"e": 729,
"s": 709,
"text": "3. Data Preparation"
},
{
"code": null,
"e": 761,
"s": 729,
"text": "4. Data Analysis & Storytelling"
},
{
"code": null,
"e": 980,
"s": 761,
"text": "Note: Data Preparation is usually a stage that requires lots of work around data formatting, cleansing and manipulation, but making your data CONSISTENT is surely a success factor for your analysis and future modeling."
},
{
"code": null,
"e": 1185,
"s": 980,
"text": "Uber’s data download feature provides you in-depth information about your rides. You can request access to your data through the following link: https://myprivacy.uber.com/privacy/exploreyourdata/download"
},
{
"code": null,
"e": 1292,
"s": 1185,
"text": "After your request is done, an email with the download link will be sent to you (usually in the same day)."
},
{
"code": null,
"e": 1358,
"s": 1292,
"text": "For security purposes, your data is only available during 7 days."
},
{
"code": null,
"e": 1717,
"s": 1358,
"text": "Before starting manipulating and analysing data, the first thing you should do is to think about THE PURPOSE. What mean is that you should think about the reasons why you are up to conduct any analysis. If you are uncertain about this, simply starting formulating questions regarding your subject like What? When? Where? Who? Which? How? How many? How much?."
},
{
"code": null,
"e": 1899,
"s": 1717,
"text": "Depending on how many data and features you have, analysis could go to the infinite and beyond. So that’s why (after thinking process) I decided to focus on the following questions:"
},
{
"code": null,
"e": 2300,
"s": 1899,
"text": "a. How many trips I did over the years?b. How many trips were Completed and Canceled?c. Where most of the dropoffs ocurred?d. What product type is usually chosen?e. What is the avg. fare, distance, amount and time spent on rides?f. Which weekdays have the highest average fares?g. Which was the longest/shortest and more expensive/cheaper ride?h. What is the average lead time before begining a trip?"
},
{
"code": null,
"e": 2333,
"s": 2300,
"text": "Importing libraries and dataset."
},
{
"code": null,
"e": 2396,
"s": 2333,
"text": "Checking basic dataset information (data types and dimensions)"
},
{
"code": null,
"e": 3310,
"s": 2396,
"text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 554 entries, 0 to 553Data columns (total 13 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 City 554 non-null int64 1 Product Type 551 non-null object 2 Trip or Order Status 554 non-null object 3 Request Time 554 non-null object 4 Begin Trip Time 554 non-null object 5 Begin Trip Lat 525 non-null float64 6 Begin Trip Lng 525 non-null float64 7 Dropoff Time 554 non-null object 8 Dropoff Lat 525 non-null float64 9 Dropoff Lng 525 non-null float64 10 Distance (miles) 554 non-null float64 11 Fare Amount 554 non-null float64 12 Fare Currency 551 non-null object dtypes: float64(6), int64(1), object(6)memory usage: 56.4+ KB"
},
{
"code": null,
"e": 3509,
"s": 3310,
"text": ".rename( ) method allows you to rename axis labels (indexes and columns). In this case I decided to normalize column names to clean up coding, as long you can columns by typing <data_frame>.<column>"
},
{
"code": null,
"e": 3637,
"s": 3509,
"text": "Use .head( ) method to gain more sensibility around data formatting and understand the overall structure of the dataset values."
},
{
"code": null,
"e": 3865,
"s": 3637,
"text": "Taking a look on the continuous variables, we notice the presence of some outliers. However these outliers do not seem to reflect any abnormal value (e.g. fare_amount = 1000 BRL), which may let us a little bit more comfortable."
},
{
"code": null,
"e": 3987,
"s": 3865,
"text": "P.S. In case abnormal values are found, some treatment should be probably considered (e.g. outliers replacement/removal)."
},
{
"code": null,
"e": 4279,
"s": 3987,
"text": "The charts below show a different perspective of the variables distribution. In this case, we see that both variables present an assimetric distribution (positive). For distance we notice that the higher frequency values are shorter distances, and for fare amount we have the same behaviour."
},
{
"code": null,
"e": 4440,
"s": 4279,
"text": "Additionally, we also notice that the standard deviation are high, taking ‘means’ as our reference. This means that values in both variables are very dispersal."
},
{
"code": null,
"e": 4600,
"s": 4440,
"text": "Not surprisingly we have a strong correlation between ‘fare_amount’ and ‘distance_miles’, inferring that as much you stay on the ride, higher will the fare be."
},
{
"code": null,
"e": 4662,
"s": 4600,
"text": "sns.scatterplot(x='distance_miles',y='fare_amount',data=df1);"
},
{
"code": null,
"e": 4770,
"s": 4662,
"text": "I decided to remove the column fare_currency, since all my trips happened inside a single country (Brazil)."
},
{
"code": null,
"e": 4815,
"s": 4770,
"text": "Now let’s check existance of missing values."
},
{
"code": null,
"e": 5016,
"s": 4815,
"text": "Despite empty Lng and Lat values (29 total), there were found 3 records without product_type. As shown below, these records are insignificant to my dataset, since practically no columns are fulfilled."
},
{
"code": null,
"e": 5075,
"s": 5016,
"text": "So now, let’s get rid of these 3 records before proceding."
},
{
"code": null,
"e": 5307,
"s": 5075,
"text": "While analysing the first categorical column <product_type>, I could clearly see that some work was necessary, since I could find different values referring to the same category. Then, I summarized 15 original categories in 5 ones."
},
{
"code": null,
"e": 5408,
"s": 5307,
"text": "As the scope of this analysis is only around Uber rides, I removed UberEATS records from my dataset."
},
{
"code": null,
"e": 5529,
"s": 5408,
"text": "Our second categorical feature <status> seems well classified in 3 status, which will not require any kind of treatment."
},
{
"code": null,
"e": 5800,
"s": 5529,
"text": "Dates usually increase a lot your power of analysis, since you can break it down to different parts and generate insights from different perspectives. As previously shown, our dates features are in fact object data types, so we need to convert them into datetime format."
},
{
"code": null,
"e": 6021,
"s": 5800,
"text": "Now, let’s break down <request_time> feature into different date parts. I just did that for <request_time>, since I'm assuming that all rides were completed in the same day (believe me, I have already checked that! :D )."
},
{
"code": null,
"e": 6191,
"s": 6021,
"text": "Based on <fare_amount> and <distance_miles> features I've created a new feature called <amount_km>, which would help us understand how much is payed by kilometer ridden."
},
{
"code": null,
"e": 6396,
"s": 6191,
"text": "Delta time between <request_time> and <begin_time> will let us now how much time (in minutes) I usually waited for Uber cars to arrive at my destination. In this case, it was calculated in a minutes base."
},
{
"code": null,
"e": 6525,
"s": 6396,
"text": "Similarly, delta time between <dropoff_time> and <begin_time> will let us now how much time (in minutes) was spent on each trip."
},
{
"code": null,
"e": 6694,
"s": 6525,
"text": "As features in records with Canceled and Driver_Cancelled status will not be useful for my analysis, I set them as null values to clean up a little bit more my dataset."
},
{
"code": null,
"e": 6973,
"s": 6694,
"text": "RECOMMENDATION: Do not start your analysis without completing the Business Problem Definition, since it determines your analysis’ focus and quality. Besides that, this process will help you to think about new possibilities/questions while trying to answer the previous ones set."
},
{
"code": null,
"e": 7172,
"s": 6973,
"text": "NOTE: In order to organize better my analysis, I will create an additional dataframe, removing all trips with status CANCELED and DRIVER_CANCELED, since they should be disconsider in some questions."
},
{
"code": null,
"e": 7462,
"s": 7172,
"text": "A total of 444 trips were completed from Apr’16 to Jan’21. If we disconsider 2016 and 2021 (not full years), we can clearly see that from 2017 to 2019 the average rides per year is 124, and that there is a huge drop from 2019 to 2020 (-51%). This is easily explained by the COVID outbreak."
},
{
"code": null,
"e": 7526,
"s": 7462,
"text": "Now, imagine if we extrapolate this result to all Uber users..."
},
{
"code": null,
"e": 7872,
"s": 7526,
"text": "Looking at the stacked bars below, we can see that excluding 2015 and 2021 (due to low trips volume), 2020 has the highest cancelation ratem. This could be an alarming indicator, considering the drastical impacts caused to the businesses after Covid outbreak. In overall, cancelation rate was 17.9% (considering RIDERS and DRIVERS cancelations)."
},
{
"code": null,
"e": 8142,
"s": 7872,
"text": "The following heatmap dynamically shows the most frequented areas throughout different hues and intensities. This could be a valuable information for Uber to adjust prices and optimize demand in certain regions, also combining time space data to track users behaviours."
},
{
"code": null,
"e": 8288,
"s": 8142,
"text": "UberX is far the prefered product type with a frequency of 90.3%. So I could say I am the type of user which usually looks for affordable prices."
},
{
"code": null,
"e": 8544,
"s": 8288,
"text": "Considering all trips, the average amount spent by trip is 19.2 BRL, ridding in approx. 8.1 km. So, if we do a quick simulation on how much I would spend in a year to do daily round trips we would have: 365 days * 2 trips * 19.2 BRL/fare = 14,016 BRL/year"
},
{
"code": null,
"e": 8619,
"s": 8544,
"text": "Also in average, It was spent approx. 2.4 BRL/km and 21.4 minutes by trip."
},
{
"code": null,
"e": 8892,
"s": 8619,
"text": "According to the chart below, we can see that Mondays, Wednesdays, Fridays and Sundays were (in average) the most expensive weekdays. Therefore, it allows us to better understand the weekly seasonality, and find out days with higher profitability for Uber and its drivers."
},
{
"code": null,
"e": 8979,
"s": 8892,
"text": "The table below show records with the longest (31.77 km) and shortest rides (0.24 km)."
},
{
"code": null,
"e": 9273,
"s": 8979,
"text": "Analysing amount paid by km ridden we have: expensive (46.96 BRL/km) and cheaper (0 BRL/km). Cheaper trip certainly refers to a free ride, while the expensive cost 46.96 BRL. This effect is basicaly driven by fixed minimum fare in high demand periods, since the total distance was only 0.24km."
},
{
"code": null,
"e": 9348,
"s": 9273,
"text": "It takes approximately 5 minutes to start trips, after they are requested."
},
{
"code": null,
"e": 9360,
"s": 9348,
"text": "4.9 minutes"
},
{
"code": null,
"e": 9532,
"s": 9360,
"text": "Exploratory Data Analysis is not a trivial task! It requires lots of work and patience, however it is surely a powerful tool if correctly applied to your business context."
},
{
"code": null,
"e": 9945,
"s": 9532,
"text": "This post briefly demonstrated some tips and steps to make analysis easier and undoubtely highlighted the crutial importance of a well defined business problem, guiding all coding effort to a specific objective, also highlighting important insights. This business case also tried to reflect a pratical application of python in daily business activities, showing how fun, valuable and interesting it could become."
}
]
|
How to Check if Android EditText is empty in Kotlin? | This example demonstrates how to Check if Android EditText is empty in Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:textSize="24sp" />
<Button
android:id="@+id/buttonCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editText"
android:layout_centerInParent="true"
android:layout_marginTop="25sp"
android:text="Check Edit" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var editText: EditText
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
button = findViewById(R.id.buttonCheck)
button.setOnClickListener {
if (TextUtils.isEmpty(editText.text.toString())) {
Toast.makeText(this, "Empty field not allowed!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Proceed..", Toast.LENGTH_SHORT).show()
}
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q1">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "This example demonstrates how to Check if Android EditText is empty in Kotlin."
},
{
"code": null,
"e": 1269,
"s": 1141,
"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": 1334,
"s": 1269,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2191,
"s": 1334,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"2dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"45dp\"\n android:textSize=\"24sp\" />\n <Button\n android:id=\"@+id/buttonCheck\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/editText\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"25sp\"\n android:text=\"Check Edit\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2246,
"s": 2191,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3059,
"s": 2246,
"text": "import android.os.Bundle\nimport android.text.TextUtils\nimport android.widget.Button\nimport android.widget.EditText\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var editText: EditText\n lateinit var button: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n button = findViewById(R.id.buttonCheck)\n button.setOnClickListener {\n if (TextUtils.isEmpty(editText.text.toString())) {\n Toast.makeText(this, \"Empty field not allowed!\", Toast.LENGTH_SHORT).show()\n } else {\n Toast.makeText(this, \"Proceed..\", Toast.LENGTH_SHORT).show()\n }\n }\n }\n}"
},
{
"code": null,
"e": 3114,
"s": 3059,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3780,
"s": 3114,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q1\">\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": 4128,
"s": 3780,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
]
|
BaseExpandableListAdapter in Android with Example - GeeksforGeeks | 10 Nov, 2020
In many android apps, the developer may need to show multi-data for huge main data items. i.e. as per our example, under “Programming languages”, we need to show “Python”, “Java” etc., and under “Relational database” we need to show “Oracle”, “MySQL’ etc., For that purpose, we can use “BaseExpandableListAdapter“. It is a bridge between the UI component and the data source which fills data in the UI component. It holds the data and then sends the data to the Adapter view then the view can take the data from the Adapter view and shows the data on different views like ExpandableListView. It will provide access to the data of the children (categorized by groups), and also instantiate views for the children and groups. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Let us see via code. Here is the code snippet for the CustomizedAdapter.java file:
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseExpandableListAdapter;import android.widget.TextView;import java.util.ArrayList; public class CustomizedAdapter extends BaseExpandableListAdapter { private Context context; private ArrayList<GroupInformation> mainSetName; public CustomizedAdapter(Context context, ArrayList<GroupInformation> deptList) { this.context = context; this.mainSetName = deptList; } @Override public Object getChild(int groupPosition, int childPosition) { ArrayList<ChildInfo> productList = mainSetName.get(groupPosition).getSubsetName(); return productList.get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) { ChildInfo detailInfo = (ChildInfo) getChild(groupPosition, childPosition); if (view == null) { LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = infalInflater.inflate(R.layout.child_items, null); } TextView childItem = (TextView) view.findViewById(R.id.childItm); childItem.setText(detailInfo.getName().trim()); return view; } @Override public int getChildrenCount(int groupPosition) { ArrayList<ChildInfo> productList = mainSetName.get(groupPosition).getSubsetName(); return productList.size(); } @Override public Object getGroup(int groupPosition) { return mainSetName.get(groupPosition); } @Override public int getGroupCount() { return mainSetName.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isLastChild, View view, ViewGroup parent) { GroupInformation headerInfo = (GroupInformation) getGroup(groupPosition); if (view == null) { LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inf.inflate(R.layout.group_items, null); } TextView heading = (TextView) view.findViewById(R.id.data); heading.setText(headerInfo.getName().trim()); return view; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
Check out the methods getChildView() and getGroupView(). They are used to create the View corresponding to the layout.
Method 1:
getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
Explanation: Used to create a child View means a child item for a parent or group
Parameters:
groupPosition: Position for the parent(group) of the current child. The function returns an integer type value. Eg: Programming_Languages
childPosition: Position for current child item of the parent.
isLastChild: It returns either true/false for the current child item is the last child within its group.
convertView: It returns View which is used to set the layout for child items.
Parent: Set the view for the parent or group item. The eventual parent of this new View.
Method 2:
View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
Explanation: Used to create our group or parent View
Parameters:
groupPosition: It tells the position of the parent or group of the child. The return type is an integer.
isExpanded: To indicate whether the group expanded and if so returns true or otherwise false.
convertView: Returns View which is used to set the layout for group items.
Parent: Used to set the view for the parent or group item. The eventual parent of this new View.
Method 3:
getChild(int groupPosition, int childPosition)
Explanation: Gets the data associated with the given child within the given group.
Parameters:
groupPosition: It tells the position for the parent or group of the child and returns an integer type value.
childPosition: It tells the position for the child of the given group and returns an integer type value.
Method 4:
getGroup(int groupPosition)
Explanation: Gets the data associated with the given group.
Parameters:
groupPosition: It tells the position for the parent or group of the child and returns an integer type value.
Method 5:
getChildrenCount(int groupPosition)
Explanation: Gets the number of children in a specified group.
Parameters:
groupPosition: It tells the position for the parent or group of the child and by using that position we calculate the number of children in that group.
Method 6:
getGroupCount()
Explanation: Get the total number of groups.
Method 7:
getGroupId(int groupPosition)
Explanation: Get the ID for the group at the given position.
Parameters:
groupPosition: It tells the position for the parent or group of the child and by using that position we get the ID for the group.
Method 8:
getChildId(int groupPosition, int childPosition)
Explanation: To get the ID for the given child within the given group.
Parameters:
groupPosition: It tells the position for the parent or group of the child and returns an integer type value.
childPosition: It tells the position for the child of the given group and returns an integer type value.
Method 9:
isChildSelectable(int groupPosition, int childPosition)
Explanation: Checks whether the child at the specified position is selectable or not and returns a Boolean value
Parameters:
groupPosition: It tells the position for the parent or group of the child and returns an integer type value.
childPosition: It tells the position for the child of the given group and returns an integer type value.and by using that value we check whether the child is selectable or not.
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 Java as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:orientation="vertical"> <ExpandableListView android:id="@+id/simpleExpandableListView1" android:layout_width="match_parent" android:layout_height="fill_parent" android:divider="#0f0" android:dividerHeight="2dp" /> </RelativeLayout>
Step 3: Create new XML files
Go to the app > res > layout > right-click > New > Layout Resource File and name the file as child_items. Below is the code for the child_items.xml file. Here TextView is used for a subset of items Eg: Python.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorAccent" android:orientation="vertical"> <TextView android:id="@+id/childItm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="15dp" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout>
Similarly, create another layout resource file and name the file as group_items. Below is the code for the group_items.xml file. Here TextView is used for the main set of items Eg: Programming_Languages
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="55dip" android:orientation="vertical"> <TextView android:id="@+id/data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="35sp" android:textAppearance="?android:attr/textAppearanceLarge" android:textStyle="bold" /> </LinearLayout>
Step 4: Create new Java files
Go to the app > java > your package name > right-click > New > Java Classe and name the file as ChildInfo. Below is the code for the ChildInfo.java file.
Java
public class ChildInfo { private String name = ""; // Getter , setter methods public String getName() { return name; } public void setName(String name) { this.name = name; }}
Similarly, create another java class file and name the file as CustomizedAdapter. We have discussed this in the beginning section and also each overridden method. So you may copy the same code and implement it in the project.
Now create another java file and name the file as GroupInformation. Below is the code for the GroupInformation.java file.
Java
import java.util.ArrayList; public class GroupInformation { private String mainSetName; private ArrayList<ChildInfo> list = new ArrayList<ChildInfo>(); public String getName() { return mainSetName; } public void setName(String mainSetName) { this.mainSetName = mainSetName; } public ArrayList<ChildInfo> getSubsetName() { return list; } public void setSubsetName(ArrayList<ChildInfo> subSetName) { this.list = subSetName; } }
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View;import android.widget.ExpandableListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.LinkedHashMap; public class MainActivity extends AppCompatActivity { private LinkedHashMap<String, GroupInformation> mainSet = new LinkedHashMap<String, GroupInformation>(); private ArrayList<GroupInformation> subSet = new ArrayList<GroupInformation>(); private CustomizedAdapter listAdapter; private ExpandableListView simpleExpandableListView1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // add data for displaying in expandable list view loadData(); // get reference of the ExpandableListView from activity_main simpleExpandableListView1 = (ExpandableListView) findViewById(R.id.simpleExpandableListView1); // create the adapter and by passing your ArrayList data listAdapter = new CustomizedAdapter(MainActivity.this, subSet); simpleExpandableListView1.setAdapter(listAdapter); // setOnChildClickListener listener for child row click, so that we can get the value simpleExpandableListView1.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // get the group header GroupInformation headerInfo = subSet.get(groupPosition); // get the child info ChildInfo detailInfo = headerInfo.getSubsetName().get(childPosition); // display it or do something with it Toast.makeText(getBaseContext(), headerInfo.getName() + "/" + detailInfo.getName(), Toast.LENGTH_LONG).show(); return false; } }); // setOnGroupClickListener listener for group heading click simpleExpandableListView1.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // get the group header GroupInformation headerInfo = subSet.get(groupPosition); // display it or do something with it Toast.makeText(getBaseContext(), headerInfo.getName(), Toast.LENGTH_LONG).show(); return false; } }); } // load some initial data into out list private void loadData() { addDetails("Programming_Languages", "Python"); addDetails("Programming_Languages", "Java"); addDetails("Programming_Languages", "Kotlin"); addDetails("Programming_Languages", "NodeJS"); addDetails("Programming_Languages", "GO"); addDetails("Relational_Database", "Oracle"); addDetails("Relational_Database", "SQLServer"); addDetails("Relational_Database", "MySQL"); addDetails("NoSQL_Database", "MongoDB"); addDetails("NoSQL_Database", "Cassandra"); addDetails("NoSQL_Database", "CouchDB"); } // here we maintain main set like Programming languages and subsets like Python private int addDetails(String mainSet, String subSet) { int groupPosition = 0; // check the hash map if the group already exists GroupInformation headerInfo = this.mainSet.get(mainSet); // add the group if doesn't exists if (headerInfo == null) { headerInfo = new GroupInformation(); headerInfo.setName(mainSet); this.mainSet.put(mainSet, headerInfo); this.subSet.add(headerInfo); } // get the children for the group ArrayList<ChildInfo> subList = headerInfo.getSubsetName(); // size of the children list int listSize = subList.size(); // add to the counter listSize++; // create a new child and add that to the group ChildInfo detailInfo = new ChildInfo(); detailInfo.setName(subSet); subList.add(detailInfo); headerInfo.setSubsetName(subList); // find the group position inside the list groupPosition = this.subSet.indexOf(headerInfo); return groupPosition; }}
On running the app, on the emulator, we can able to view the output as attached in the video. This feature is a much-required feature across many apps.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create and Add Data to SQLite Database in Android?
Services in Android with Example
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java | [
{
"code": null,
"e": 24534,
"s": 24506,
"text": "\n10 Nov, 2020"
},
{
"code": null,
"e": 25423,
"s": 24534,
"text": "In many android apps, the developer may need to show multi-data for huge main data items. i.e. as per our example, under “Programming languages”, we need to show “Python”, “Java” etc., and under “Relational database” we need to show “Oracle”, “MySQL’ etc., For that purpose, we can use “BaseExpandableListAdapter“. It is a bridge between the UI component and the data source which fills data in the UI component. It holds the data and then sends the data to the Adapter view then the view can take the data from the Adapter view and shows the data on different views like ExpandableListView. It will provide access to the data of the children (categorized by groups), and also instantiate views for the children and groups. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25506,
"s": 25423,
"text": "Let us see via code. Here is the code snippet for the CustomizedAdapter.java file:"
},
{
"code": null,
"e": 25511,
"s": 25506,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseExpandableListAdapter;import android.widget.TextView;import java.util.ArrayList; public class CustomizedAdapter extends BaseExpandableListAdapter { private Context context; private ArrayList<GroupInformation> mainSetName; public CustomizedAdapter(Context context, ArrayList<GroupInformation> deptList) { this.context = context; this.mainSetName = deptList; } @Override public Object getChild(int groupPosition, int childPosition) { ArrayList<ChildInfo> productList = mainSetName.get(groupPosition).getSubsetName(); return productList.get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View view, ViewGroup parent) { ChildInfo detailInfo = (ChildInfo) getChild(groupPosition, childPosition); if (view == null) { LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = infalInflater.inflate(R.layout.child_items, null); } TextView childItem = (TextView) view.findViewById(R.id.childItm); childItem.setText(detailInfo.getName().trim()); return view; } @Override public int getChildrenCount(int groupPosition) { ArrayList<ChildInfo> productList = mainSetName.get(groupPosition).getSubsetName(); return productList.size(); } @Override public Object getGroup(int groupPosition) { return mainSetName.get(groupPosition); } @Override public int getGroupCount() { return mainSetName.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isLastChild, View view, ViewGroup parent) { GroupInformation headerInfo = (GroupInformation) getGroup(groupPosition); if (view == null) { LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inf.inflate(R.layout.group_items, null); } TextView heading = (TextView) view.findViewById(R.id.data); heading.setText(headerInfo.getName().trim()); return view; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }",
"e": 28274,
"s": 25511,
"text": null
},
{
"code": null,
"e": 28393,
"s": 28274,
"text": "Check out the methods getChildView() and getGroupView(). They are used to create the View corresponding to the layout."
},
{
"code": null,
"e": 28404,
"s": 28393,
"text": "Method 1: "
},
{
"code": null,
"e": 28512,
"s": 28404,
"text": "getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)"
},
{
"code": null,
"e": 28594,
"s": 28512,
"text": "Explanation: Used to create a child View means a child item for a parent or group"
},
{
"code": null,
"e": 28606,
"s": 28594,
"text": "Parameters:"
},
{
"code": null,
"e": 28744,
"s": 28606,
"text": "groupPosition: Position for the parent(group) of the current child. The function returns an integer type value. Eg: Programming_Languages"
},
{
"code": null,
"e": 28806,
"s": 28744,
"text": "childPosition: Position for current child item of the parent."
},
{
"code": null,
"e": 28911,
"s": 28806,
"text": "isLastChild: It returns either true/false for the current child item is the last child within its group."
},
{
"code": null,
"e": 28989,
"s": 28911,
"text": "convertView: It returns View which is used to set the layout for child items."
},
{
"code": null,
"e": 29079,
"s": 28989,
"text": "Parent: Set the view for the parent or group item. The eventual parent of this new View."
},
{
"code": null,
"e": 29090,
"s": 29079,
"text": "Method 2: "
},
{
"code": null,
"e": 29183,
"s": 29090,
"text": "View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)"
},
{
"code": null,
"e": 29237,
"s": 29183,
"text": "Explanation: Used to create our group or parent View"
},
{
"code": null,
"e": 29249,
"s": 29237,
"text": "Parameters:"
},
{
"code": null,
"e": 29354,
"s": 29249,
"text": "groupPosition: It tells the position of the parent or group of the child. The return type is an integer."
},
{
"code": null,
"e": 29448,
"s": 29354,
"text": "isExpanded: To indicate whether the group expanded and if so returns true or otherwise false."
},
{
"code": null,
"e": 29523,
"s": 29448,
"text": "convertView: Returns View which is used to set the layout for group items."
},
{
"code": null,
"e": 29621,
"s": 29523,
"text": "Parent: Used to set the view for the parent or group item. The eventual parent of this new View."
},
{
"code": null,
"e": 29632,
"s": 29621,
"text": "Method 3: "
},
{
"code": null,
"e": 29679,
"s": 29632,
"text": "getChild(int groupPosition, int childPosition)"
},
{
"code": null,
"e": 29762,
"s": 29679,
"text": "Explanation: Gets the data associated with the given child within the given group."
},
{
"code": null,
"e": 29774,
"s": 29762,
"text": "Parameters:"
},
{
"code": null,
"e": 29883,
"s": 29774,
"text": "groupPosition: It tells the position for the parent or group of the child and returns an integer type value."
},
{
"code": null,
"e": 29988,
"s": 29883,
"text": "childPosition: It tells the position for the child of the given group and returns an integer type value."
},
{
"code": null,
"e": 29998,
"s": 29988,
"text": "Method 4:"
},
{
"code": null,
"e": 30026,
"s": 29998,
"text": "getGroup(int groupPosition)"
},
{
"code": null,
"e": 30086,
"s": 30026,
"text": "Explanation: Gets the data associated with the given group."
},
{
"code": null,
"e": 30098,
"s": 30086,
"text": "Parameters:"
},
{
"code": null,
"e": 30207,
"s": 30098,
"text": "groupPosition: It tells the position for the parent or group of the child and returns an integer type value."
},
{
"code": null,
"e": 30217,
"s": 30207,
"text": "Method 5:"
},
{
"code": null,
"e": 30253,
"s": 30217,
"text": "getChildrenCount(int groupPosition)"
},
{
"code": null,
"e": 30316,
"s": 30253,
"text": "Explanation: Gets the number of children in a specified group."
},
{
"code": null,
"e": 30328,
"s": 30316,
"text": "Parameters:"
},
{
"code": null,
"e": 30480,
"s": 30328,
"text": "groupPosition: It tells the position for the parent or group of the child and by using that position we calculate the number of children in that group."
},
{
"code": null,
"e": 30490,
"s": 30480,
"text": "Method 6:"
},
{
"code": null,
"e": 30506,
"s": 30490,
"text": "getGroupCount()"
},
{
"code": null,
"e": 30551,
"s": 30506,
"text": "Explanation: Get the total number of groups."
},
{
"code": null,
"e": 30562,
"s": 30551,
"text": "Method 7:"
},
{
"code": null,
"e": 30592,
"s": 30562,
"text": "getGroupId(int groupPosition)"
},
{
"code": null,
"e": 30653,
"s": 30592,
"text": "Explanation: Get the ID for the group at the given position."
},
{
"code": null,
"e": 30665,
"s": 30653,
"text": "Parameters:"
},
{
"code": null,
"e": 30795,
"s": 30665,
"text": "groupPosition: It tells the position for the parent or group of the child and by using that position we get the ID for the group."
},
{
"code": null,
"e": 30806,
"s": 30795,
"text": "Method 8:"
},
{
"code": null,
"e": 30855,
"s": 30806,
"text": "getChildId(int groupPosition, int childPosition)"
},
{
"code": null,
"e": 30926,
"s": 30855,
"text": "Explanation: To get the ID for the given child within the given group."
},
{
"code": null,
"e": 30938,
"s": 30926,
"text": "Parameters:"
},
{
"code": null,
"e": 31047,
"s": 30938,
"text": "groupPosition: It tells the position for the parent or group of the child and returns an integer type value."
},
{
"code": null,
"e": 31152,
"s": 31047,
"text": "childPosition: It tells the position for the child of the given group and returns an integer type value."
},
{
"code": null,
"e": 31163,
"s": 31152,
"text": "Method 9: "
},
{
"code": null,
"e": 31219,
"s": 31163,
"text": "isChildSelectable(int groupPosition, int childPosition)"
},
{
"code": null,
"e": 31332,
"s": 31219,
"text": "Explanation: Checks whether the child at the specified position is selectable or not and returns a Boolean value"
},
{
"code": null,
"e": 31344,
"s": 31332,
"text": "Parameters:"
},
{
"code": null,
"e": 31453,
"s": 31344,
"text": "groupPosition: It tells the position for the parent or group of the child and returns an integer type value."
},
{
"code": null,
"e": 31630,
"s": 31453,
"text": "childPosition: It tells the position for the child of the given group and returns an integer type value.and by using that value we check whether the child is selectable or not."
},
{
"code": null,
"e": 31659,
"s": 31630,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 31821,
"s": 31659,
"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 Java as the programming language."
},
{
"code": null,
"e": 31869,
"s": 31821,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 31985,
"s": 31869,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 31989,
"s": 31985,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#fff\" android:orientation=\"vertical\"> <ExpandableListView android:id=\"@+id/simpleExpandableListView1\" android:layout_width=\"match_parent\" android:layout_height=\"fill_parent\" android:divider=\"#0f0\" android:dividerHeight=\"2dp\" /> </RelativeLayout>",
"e": 32498,
"s": 31989,
"text": null
},
{
"code": null,
"e": 32527,
"s": 32498,
"text": "Step 3: Create new XML files"
},
{
"code": null,
"e": 32737,
"s": 32527,
"text": "Go to the app > res > layout > right-click > New > Layout Resource File and name the file as child_items. Below is the code for the child_items.xml file. Here TextView is used for a subset of items Eg: Python."
},
{
"code": null,
"e": 32741,
"s": 32737,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/colorAccent\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/childItm\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentTop=\"true\" android:layout_marginLeft=\"15dp\" android:textAppearance=\"?android:attr/textAppearanceMedium\" /> </RelativeLayout>",
"e": 33324,
"s": 32741,
"text": null
},
{
"code": null,
"e": 33527,
"s": 33324,
"text": "Similarly, create another layout resource file and name the file as group_items. Below is the code for the group_items.xml file. Here TextView is used for the main set of items Eg: Programming_Languages"
},
{
"code": null,
"e": 33531,
"s": 33527,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"fill_parent\" android:layout_height=\"55dip\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/data\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:paddingLeft=\"35sp\" android:textAppearance=\"?android:attr/textAppearanceLarge\" android:textStyle=\"bold\" /> </LinearLayout>",
"e": 34036,
"s": 33531,
"text": null
},
{
"code": null,
"e": 34066,
"s": 34036,
"text": "Step 4: Create new Java files"
},
{
"code": null,
"e": 34220,
"s": 34066,
"text": "Go to the app > java > your package name > right-click > New > Java Classe and name the file as ChildInfo. Below is the code for the ChildInfo.java file."
},
{
"code": null,
"e": 34225,
"s": 34220,
"text": "Java"
},
{
"code": "public class ChildInfo { private String name = \"\"; // Getter , setter methods public String getName() { return name; } public void setName(String name) { this.name = name; }}",
"e": 34440,
"s": 34225,
"text": null
},
{
"code": null,
"e": 34666,
"s": 34440,
"text": "Similarly, create another java class file and name the file as CustomizedAdapter. We have discussed this in the beginning section and also each overridden method. So you may copy the same code and implement it in the project."
},
{
"code": null,
"e": 34788,
"s": 34666,
"text": "Now create another java file and name the file as GroupInformation. Below is the code for the GroupInformation.java file."
},
{
"code": null,
"e": 34793,
"s": 34788,
"text": "Java"
},
{
"code": "import java.util.ArrayList; public class GroupInformation { private String mainSetName; private ArrayList<ChildInfo> list = new ArrayList<ChildInfo>(); public String getName() { return mainSetName; } public void setName(String mainSetName) { this.mainSetName = mainSetName; } public ArrayList<ChildInfo> getSubsetName() { return list; } public void setSubsetName(ArrayList<ChildInfo> subSetName) { this.list = subSetName; } }",
"e": 35289,
"s": 34793,
"text": null
},
{
"code": null,
"e": 35337,
"s": 35289,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 35527,
"s": 35337,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 35532,
"s": 35527,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.ExpandableListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.LinkedHashMap; public class MainActivity extends AppCompatActivity { private LinkedHashMap<String, GroupInformation> mainSet = new LinkedHashMap<String, GroupInformation>(); private ArrayList<GroupInformation> subSet = new ArrayList<GroupInformation>(); private CustomizedAdapter listAdapter; private ExpandableListView simpleExpandableListView1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // add data for displaying in expandable list view loadData(); // get reference of the ExpandableListView from activity_main simpleExpandableListView1 = (ExpandableListView) findViewById(R.id.simpleExpandableListView1); // create the adapter and by passing your ArrayList data listAdapter = new CustomizedAdapter(MainActivity.this, subSet); simpleExpandableListView1.setAdapter(listAdapter); // setOnChildClickListener listener for child row click, so that we can get the value simpleExpandableListView1.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // get the group header GroupInformation headerInfo = subSet.get(groupPosition); // get the child info ChildInfo detailInfo = headerInfo.getSubsetName().get(childPosition); // display it or do something with it Toast.makeText(getBaseContext(), headerInfo.getName() + \"/\" + detailInfo.getName(), Toast.LENGTH_LONG).show(); return false; } }); // setOnGroupClickListener listener for group heading click simpleExpandableListView1.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // get the group header GroupInformation headerInfo = subSet.get(groupPosition); // display it or do something with it Toast.makeText(getBaseContext(), headerInfo.getName(), Toast.LENGTH_LONG).show(); return false; } }); } // load some initial data into out list private void loadData() { addDetails(\"Programming_Languages\", \"Python\"); addDetails(\"Programming_Languages\", \"Java\"); addDetails(\"Programming_Languages\", \"Kotlin\"); addDetails(\"Programming_Languages\", \"NodeJS\"); addDetails(\"Programming_Languages\", \"GO\"); addDetails(\"Relational_Database\", \"Oracle\"); addDetails(\"Relational_Database\", \"SQLServer\"); addDetails(\"Relational_Database\", \"MySQL\"); addDetails(\"NoSQL_Database\", \"MongoDB\"); addDetails(\"NoSQL_Database\", \"Cassandra\"); addDetails(\"NoSQL_Database\", \"CouchDB\"); } // here we maintain main set like Programming languages and subsets like Python private int addDetails(String mainSet, String subSet) { int groupPosition = 0; // check the hash map if the group already exists GroupInformation headerInfo = this.mainSet.get(mainSet); // add the group if doesn't exists if (headerInfo == null) { headerInfo = new GroupInformation(); headerInfo.setName(mainSet); this.mainSet.put(mainSet, headerInfo); this.subSet.add(headerInfo); } // get the children for the group ArrayList<ChildInfo> subList = headerInfo.getSubsetName(); // size of the children list int listSize = subList.size(); // add to the counter listSize++; // create a new child and add that to the group ChildInfo detailInfo = new ChildInfo(); detailInfo.setName(subSet); subList.add(detailInfo); headerInfo.setSubsetName(subList); // find the group position inside the list groupPosition = this.subSet.indexOf(headerInfo); return groupPosition; }}",
"e": 39992,
"s": 35532,
"text": null
},
{
"code": null,
"e": 40144,
"s": 39992,
"text": "On running the app, on the emulator, we can able to view the output as attached in the video. This feature is a much-required feature across many apps."
},
{
"code": null,
"e": 40152,
"s": 40144,
"text": "android"
},
{
"code": null,
"e": 40176,
"s": 40152,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 40184,
"s": 40176,
"text": "Android"
},
{
"code": null,
"e": 40189,
"s": 40184,
"text": "Java"
},
{
"code": null,
"e": 40208,
"s": 40189,
"text": "Technical Scripter"
},
{
"code": null,
"e": 40213,
"s": 40208,
"text": "Java"
},
{
"code": null,
"e": 40221,
"s": 40213,
"text": "Android"
},
{
"code": null,
"e": 40319,
"s": 40221,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40328,
"s": 40319,
"text": "Comments"
},
{
"code": null,
"e": 40341,
"s": 40328,
"text": "Old Comments"
},
{
"code": null,
"e": 40399,
"s": 40341,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 40432,
"s": 40399,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 40475,
"s": 40432,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 40517,
"s": 40475,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 40548,
"s": 40517,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 40563,
"s": 40548,
"text": "Arrays in Java"
},
{
"code": null,
"e": 40607,
"s": 40563,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 40629,
"s": 40607,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 40665,
"s": 40629,
"text": "Arrays.sort() in Java with examples"
}
]
|
Write your own len() in Python - GeeksforGeeks | 01 Feb, 2018
The method len() returns the number of elements in the list or length of the string depending upon the argument you are passing.
How to implement without using len():
1. Take input and pass the string/list into
a function which return its length.
2. Initialize a count variable to 0, this count
variable count character in the string.
3. Run a loop till length if the string and increment
count by 1.
4. When loop is completed return count.
Python implementation:
# Function which return length of stringdef findLength(string): # Initialize count to zero count = 0 # Counting character in a string for i in string: count+= 1 # Returning count return count # Driver codestring = "geeksforgeeks"print(findLength(string))
Output:
13
This article is contributed by Sahil Rajput. 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.
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n01 Feb, 2018"
},
{
"code": null,
"e": 25690,
"s": 25561,
"text": "The method len() returns the number of elements in the list or length of the string depending upon the argument you are passing."
},
{
"code": null,
"e": 25728,
"s": 25690,
"text": "How to implement without using len():"
},
{
"code": null,
"e": 26014,
"s": 25728,
"text": "1. Take input and pass the string/list into\n a function which return its length.\n2. Initialize a count variable to 0, this count \n variable count character in the string.\n3. Run a loop till length if the string and increment \n count by 1.\n4. When loop is completed return count.\n"
},
{
"code": null,
"e": 26037,
"s": 26014,
"text": "Python implementation:"
},
{
"code": "# Function which return length of stringdef findLength(string): # Initialize count to zero count = 0 # Counting character in a string for i in string: count+= 1 # Returning count return count # Driver codestring = \"geeksforgeeks\"print(findLength(string))",
"e": 26322,
"s": 26037,
"text": null
},
{
"code": null,
"e": 26330,
"s": 26322,
"text": "Output:"
},
{
"code": null,
"e": 26334,
"s": 26330,
"text": "13\n"
},
{
"code": null,
"e": 26634,
"s": 26334,
"text": "This article is contributed by Sahil Rajput. 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": 26759,
"s": 26634,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26785,
"s": 26759,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 26792,
"s": 26785,
"text": "Python"
},
{
"code": null,
"e": 26890,
"s": 26792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26922,
"s": 26890,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26964,
"s": 26922,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27006,
"s": 26964,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27062,
"s": 27006,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27089,
"s": 27062,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27120,
"s": 27089,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27159,
"s": 27120,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27188,
"s": 27159,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27210,
"s": 27188,
"text": "Defaultdict in Python"
}
]
|
How To Merge Two DataFrames in R ? - GeeksforGeeks | 26 Mar, 2021
In this article, We are going to see how to merge two R dataFrames. Merging of Data frames in R can be done in two ways.
Merging columns
Merging rows
In this way, we merge the database horizontally. We use the merge function to merge two frames by one or more common key variables(i.e., an inner join).
dataframe_AB = merge(dataframe_A, dataframe_B, by="ID")
Below is the implementation:
R
# merging two datasetsauthors <- data.frame( name = c("kapil", "sachin", "Rahul","Nikhil","Rohan"), nationality = c("US","Australia","US","UK","India"), retired = c("Yes","No","Yes","No","No")) books <-data.frame( name = c("C", "C++","Java","php",".net","R"), title = c("Intro to C","Intro to C++", "Intro to java", "Intro to php", "Intro to .net", "Intro to R"), author = c("kapil", "kapil","sachin", "Rahul", "Nikhil","Nikhil")) merge(authors, books, by.x = "name", by.y = "author")
Output:
In this way, we merge the data frames vertically and use the rbind() function. rbind stands for row binding. The two data frames must have the same variables but need not be in the same order.
Note: If dataframe_A has variables that dataframe_B doesn’t have, either Delete the extra variables in dataframe_A or create the additional variables in dataframe_B and set them to NA.
As we can see from the below diagram, it combines rows of two dataframes.
Below is the implementation:
R
# merging two datasetsauthors_A <- data.frame( name = c("kapil", "sachin", "Rahul"), nationality = c("US", "Australia", "US"), retired = c("Yes", "No", "Yes")) authors_B <- data.frame( name = c("Nikhil", "Rohan"), nationality = c("UK", "India"), retired = c("No", "No")) rbind(authors_A, authors_B)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 26608,
"s": 26487,
"text": "In this article, We are going to see how to merge two R dataFrames. Merging of Data frames in R can be done in two ways."
},
{
"code": null,
"e": 26624,
"s": 26608,
"text": "Merging columns"
},
{
"code": null,
"e": 26637,
"s": 26624,
"text": "Merging rows"
},
{
"code": null,
"e": 26790,
"s": 26637,
"text": "In this way, we merge the database horizontally. We use the merge function to merge two frames by one or more common key variables(i.e., an inner join)."
},
{
"code": null,
"e": 26846,
"s": 26790,
"text": "dataframe_AB = merge(dataframe_A, dataframe_B, by=\"ID\")"
},
{
"code": null,
"e": 26875,
"s": 26846,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 26877,
"s": 26875,
"text": "R"
},
{
"code": "# merging two datasetsauthors <- data.frame( name = c(\"kapil\", \"sachin\", \"Rahul\",\"Nikhil\",\"Rohan\"), nationality = c(\"US\",\"Australia\",\"US\",\"UK\",\"India\"), retired = c(\"Yes\",\"No\",\"Yes\",\"No\",\"No\")) books <-data.frame( name = c(\"C\", \"C++\",\"Java\",\"php\",\".net\",\"R\"), title = c(\"Intro to C\",\"Intro to C++\", \"Intro to java\", \"Intro to php\", \"Intro to .net\", \"Intro to R\"), author = c(\"kapil\", \"kapil\",\"sachin\", \"Rahul\", \"Nikhil\",\"Nikhil\")) merge(authors, books, by.x = \"name\", by.y = \"author\")",
"e": 27411,
"s": 26877,
"text": null
},
{
"code": null,
"e": 27419,
"s": 27411,
"text": "Output:"
},
{
"code": null,
"e": 27612,
"s": 27419,
"text": "In this way, we merge the data frames vertically and use the rbind() function. rbind stands for row binding. The two data frames must have the same variables but need not be in the same order."
},
{
"code": null,
"e": 27797,
"s": 27612,
"text": "Note: If dataframe_A has variables that dataframe_B doesn’t have, either Delete the extra variables in dataframe_A or create the additional variables in dataframe_B and set them to NA."
},
{
"code": null,
"e": 27871,
"s": 27797,
"text": "As we can see from the below diagram, it combines rows of two dataframes."
},
{
"code": null,
"e": 27900,
"s": 27871,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 27902,
"s": 27900,
"text": "R"
},
{
"code": "# merging two datasetsauthors_A <- data.frame( name = c(\"kapil\", \"sachin\", \"Rahul\"), nationality = c(\"US\", \"Australia\", \"US\"), retired = c(\"Yes\", \"No\", \"Yes\")) authors_B <- data.frame( name = c(\"Nikhil\", \"Rohan\"), nationality = c(\"UK\", \"India\"), retired = c(\"No\", \"No\")) rbind(authors_A, authors_B)",
"e": 28209,
"s": 27902,
"text": null
},
{
"code": null,
"e": 28217,
"s": 28209,
"text": "Output:"
},
{
"code": null,
"e": 28224,
"s": 28217,
"text": "Picked"
},
{
"code": null,
"e": 28245,
"s": 28224,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 28257,
"s": 28245,
"text": "R-DataFrame"
},
{
"code": null,
"e": 28268,
"s": 28257,
"text": "R Language"
},
{
"code": null,
"e": 28279,
"s": 28268,
"text": "R Programs"
},
{
"code": null,
"e": 28377,
"s": 28279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28429,
"s": 28377,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28464,
"s": 28429,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28502,
"s": 28464,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28560,
"s": 28502,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28603,
"s": 28560,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28661,
"s": 28603,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28704,
"s": 28661,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28753,
"s": 28704,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28803,
"s": 28753,
"text": "How to filter R dataframe by multiple conditions?"
}
]
|
Sum of all proper divisors from 1 to N - GeeksforGeeks | 06 Jun, 2021
Given a positive integer N, the task is to find the value of where function F(x) can be defined as sum of all proper divisors of ‘x‘.Examples:
Input: N = 4 Output: 5 Explanation: Sum of all proper divisors of numbers: F(1) = 0 F(2) = 1 F(3) = 1 F(4) = 1 + 2 = 3 Total Sum = F(1) + F(2) + F(3) + F(4) = 0 + 1 + 1 + 3 = 5Input: N = 5 Output: 6 Explanation: Sum of all proper divisors of numbers: F(1) = 0 F(2) = 1 F(3) = 1 F(4) = 1 + 2 = 3 F(5) = 1 Total Sum = F(1) + F(2) + F(3) + F(4) + F(5) = 0 + 1 + 1 + 3 + 1 = 6
Naive approach: The idea is to find the sum of proper divisors of each number in the range [1, N] individually, and then add them to find the required sum.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find sum of all// proper divisor of number up to N#include <bits/stdc++.h>using namespace std; // Utility function to find sum of// all proper divisor of number up to Nint properDivisorSum(int n){ int sum = 0; // Loop to iterate over all the // numbers from 1 to N for (int i = 1; i <= n; ++i) { // Find all divisors of // i and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } // Subtracting 'i' so that the // number itself is not included sum = sum - i; } return sum;} // Driver Codeint main(){ int n = 4; cout << properDivisorSum(n) << endl; n = 5; cout << properDivisorSum(n) << endl; return 0;}
// Java implementation to find sum of all// proper divisor of number up to Nclass GFG { // Utility function to find sum of // all proper divisor of number up to N static int properDivisorSum(int n) { int sum = 0; // Loop to iterate over all the // numbers from 1 to N for (int i = 1; i <= n; ++i) { // Find all divisors of // i and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } // Subtracting 'i' so that the // number itself is not included sum = sum - i; } return sum; } // Driver Code public static void main (String[] args) { int n = 4; System.out.println(properDivisorSum(n)); n = 5; System.out.println(properDivisorSum(n)) ; }} // This code is contributed by Yash_R
# Python3 implementation to find sum of all# proper divisor of number up to N # Utility function to find sum of# all proper divisor of number up to Ndef properDivisorSum(n): sum = 0 # Loop to iterate over all the # numbers from 1 to N for i in range(n+1): # Find all divisors of # i and add them for j in range(1, i + 1): if j * j > i: break if (i % j == 0): if (i // j == j): sum += j else: sum += j + i // j # Subtracting 'i' so that the # number itself is not included sum = sum - i return sum # Driver Codeif __name__ == '__main__': n = 4 print(properDivisorSum(n)) n = 5 print(properDivisorSum(n)) # This code is contributed by mohit kumar 29
// C# implementation to find sum of all// proper divisor of number up to Nusing System; class GFG { // Utility function to find sum of // all proper divisor of number up to N static int properDivisorSum(int n) { int sum = 0; // Loop to iterate over all the // numbers from 1 to N for (int i = 1; i <= n; ++i) { // Find all divisors of // i and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } // Subtracting 'i' so that the // number itself is not included sum = sum - i; } return sum; } // Driver Code public static void Main (string[] args) { int n = 4; Console.WriteLine(properDivisorSum(n)); n = 5; Console.WriteLine(properDivisorSum(n)) ; }} // This code is contributed by Yash_R
<script> //Javascript implementation to find sum of all// proper divisor of number up to N // Utility function to find sum of// all proper divisor of number up to Nfunction properDivisorSum(n){ let sum = 0; // Loop to iterate over all the // numbers from 1 to N for (let i = 1; i <= n; ++i) { // Find all divisors of // i and add them for (let j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } // Subtracting 'i' so that the // number itself is not included sum = sum - i; } return sum;} // Driver Code let n = 4; document.write(properDivisorSum(n) + "<br>"); n = 5; document.write(properDivisorSum(n) + "<br>"); // This code is contributed by Mayank Tyagi </script>
5
6
Time complexity: O(N * √N) Auxiliary space: O(1)Efficient approach: Upon observing the pattern in the function, it can be seen that “For a given number N, every number ‘x’ in the range [1, N] occurs (N/x) number of times”.For example:
Let N = 6 => G(N) = F(1) + F(2) + F(3) + F(4) + F(5) + F(6) x = 1 => 1 will occurs 6 times (in F(1), F(2), F(3), F(4), F(5) and F(6)) x = 2 => 2 will occurs 3 times (in F(2), F(4) and F(6)) x = 3 => 3 will occur 2 times (in F(3) and F(6)) x = 4 => 4 will occur 1 times (in F(4)) x = 5 => 5 will occur 1 times (in F(5)) x = 6 => 6 will occur 1 times (in F(6))
From above observation, it can easily be observed that number x occurs only in its multiple less than or equal to N. Therefore, we just need to find the count of such multiples, for each value of x in [1, N], and then multiply it with x. This value is then added to the final sum.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find sum of all// proper divisor of numbers up to N #include <bits/stdc++.h>using namespace std; // Utility function to find sum of// all proper divisor of number up to Nint properDivisorSum(int n){ int sum = 0; // Loop to find the proper // divisor of every number // from 1 to N for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum - n * (n + 1) / 2;} // Driver Codeint main(){ int n = 4; cout << properDivisorSum(n) << endl; n = 5; cout << properDivisorSum(n) << endl; return 0;}
// Java implementation to find sum of all// proper divisor of numbers up to N // Utility function to find sum of// all proper divisor of number up to N class GFG{ static int properDivisorSum(int n) { int sum = 0; int i; // Loop to find the proper // divisor of every number // from 1 to N for (i = 1; i <= n; ++i) sum += (n / i) * i; return sum - n * (n + 1) / 2; } // Driver Code public static void main(String []args) { int n = 4; System.out.println(properDivisorSum(n)); n = 5; System.out.println(properDivisorSum(n)); }}
# Python3 implementation to find sum of all# proper divisor of numbers up to N # Utility function to find sum of# all proper divisor of number up to Ndef properDivisorSum(n): sum = 0 # Loop to find the proper # divisor of every number # from 1 to N for i in range(1, n + 1): sum += (n // i) * i return sum - n * (n + 1) // 2 # Driver Coden = 4print(properDivisorSum(n)) n = 5print(properDivisorSum(n)) # This code is contributed by shubhamsingh10
// C# implementation to find sum of all// proper divisor of numbers up to N // Utility function to find sum of// all proper divisor of number up to Nusing System; class GFG{ static int properDivisorSum(int n) { int sum = 0; int i; // Loop to find the proper // divisor of every number // from 1 to N for (i = 1; i <= n; ++i) sum += (n / i) * i; return sum - n * (n + 1) / 2; } // Driver Code public static void Main(String []args) { int n = 4; Console.WriteLine(properDivisorSum(n)); n = 5; Console.WriteLine(properDivisorSum(n)); }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation to find sum of all// proper divisor of numbers up to N // Utility function to find sum of// all proper divisor of number up to Nfunction properDivisorSum(n){ var sum = 0; // Loop to find the proper // divisor of every number // from 1 to N for (var i = 1; i <= n; ++i) sum += parseInt(n / i) * i; return sum - n * ((n + 1) / 2);} // Driver Codevar n = 4;document.write(properDivisorSum(n)+"<br>");n = 5;document.write(properDivisorSum(n)+"<br>"); // This code is contributed by rutvik_56.</script>
5
6
Time complexity: O(N) Auxiliary space: O(1)
mohit kumar 29
SHUBHAMSINGH10
Yash_R
ukasp
29AjayKumar
nidhi_biet
mayanktyagi1709
rutvik_56
sooda367
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair | [
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 26082,
"s": 25937,
"text": "Given a positive integer N, the task is to find the value of where function F(x) can be defined as sum of all proper divisors of ‘x‘.Examples: "
},
{
"code": null,
"e": 26457,
"s": 26082,
"text": "Input: N = 4 Output: 5 Explanation: Sum of all proper divisors of numbers: F(1) = 0 F(2) = 1 F(3) = 1 F(4) = 1 + 2 = 3 Total Sum = F(1) + F(2) + F(3) + F(4) = 0 + 1 + 1 + 3 = 5Input: N = 5 Output: 6 Explanation: Sum of all proper divisors of numbers: F(1) = 0 F(2) = 1 F(3) = 1 F(4) = 1 + 2 = 3 F(5) = 1 Total Sum = F(1) + F(2) + F(3) + F(4) + F(5) = 0 + 1 + 1 + 3 + 1 = 6 "
},
{
"code": null,
"e": 26666,
"s": 26459,
"text": "Naive approach: The idea is to find the sum of proper divisors of each number in the range [1, N] individually, and then add them to find the required sum.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26670,
"s": 26666,
"text": "C++"
},
{
"code": null,
"e": 26675,
"s": 26670,
"text": "Java"
},
{
"code": null,
"e": 26683,
"s": 26675,
"text": "Python3"
},
{
"code": null,
"e": 26686,
"s": 26683,
"text": "C#"
},
{
"code": null,
"e": 26697,
"s": 26686,
"text": "Javascript"
},
{
"code": "// C++ implementation to find sum of all// proper divisor of number up to N#include <bits/stdc++.h>using namespace std; // Utility function to find sum of// all proper divisor of number up to Nint properDivisorSum(int n){ int sum = 0; // Loop to iterate over all the // numbers from 1 to N for (int i = 1; i <= n; ++i) { // Find all divisors of // i and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } // Subtracting 'i' so that the // number itself is not included sum = sum - i; } return sum;} // Driver Codeint main(){ int n = 4; cout << properDivisorSum(n) << endl; n = 5; cout << properDivisorSum(n) << endl; return 0;}",
"e": 27566,
"s": 26697,
"text": null
},
{
"code": "// Java implementation to find sum of all// proper divisor of number up to Nclass GFG { // Utility function to find sum of // all proper divisor of number up to N static int properDivisorSum(int n) { int sum = 0; // Loop to iterate over all the // numbers from 1 to N for (int i = 1; i <= n; ++i) { // Find all divisors of // i and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } // Subtracting 'i' so that the // number itself is not included sum = sum - i; } return sum; } // Driver Code public static void main (String[] args) { int n = 4; System.out.println(properDivisorSum(n)); n = 5; System.out.println(properDivisorSum(n)) ; }} // This code is contributed by Yash_R",
"e": 28630,
"s": 27566,
"text": null
},
{
"code": "# Python3 implementation to find sum of all# proper divisor of number up to N # Utility function to find sum of# all proper divisor of number up to Ndef properDivisorSum(n): sum = 0 # Loop to iterate over all the # numbers from 1 to N for i in range(n+1): # Find all divisors of # i and add them for j in range(1, i + 1): if j * j > i: break if (i % j == 0): if (i // j == j): sum += j else: sum += j + i // j # Subtracting 'i' so that the # number itself is not included sum = sum - i return sum # Driver Codeif __name__ == '__main__': n = 4 print(properDivisorSum(n)) n = 5 print(properDivisorSum(n)) # This code is contributed by mohit kumar 29",
"e": 29459,
"s": 28630,
"text": null
},
{
"code": "// C# implementation to find sum of all// proper divisor of number up to Nusing System; class GFG { // Utility function to find sum of // all proper divisor of number up to N static int properDivisorSum(int n) { int sum = 0; // Loop to iterate over all the // numbers from 1 to N for (int i = 1; i <= n; ++i) { // Find all divisors of // i and add them for (int j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } // Subtracting 'i' so that the // number itself is not included sum = sum - i; } return sum; } // Driver Code public static void Main (string[] args) { int n = 4; Console.WriteLine(properDivisorSum(n)); n = 5; Console.WriteLine(properDivisorSum(n)) ; }} // This code is contributed by Yash_R",
"e": 30531,
"s": 29459,
"text": null
},
{
"code": "<script> //Javascript implementation to find sum of all// proper divisor of number up to N // Utility function to find sum of// all proper divisor of number up to Nfunction properDivisorSum(n){ let sum = 0; // Loop to iterate over all the // numbers from 1 to N for (let i = 1; i <= n; ++i) { // Find all divisors of // i and add them for (let j = 1; j * j <= i; ++j) { if (i % j == 0) { if (i / j == j) sum += j; else sum += j + i / j; } } // Subtracting 'i' so that the // number itself is not included sum = sum - i; } return sum;} // Driver Code let n = 4; document.write(properDivisorSum(n) + \"<br>\"); n = 5; document.write(properDivisorSum(n) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>",
"e": 31430,
"s": 30531,
"text": null
},
{
"code": null,
"e": 31434,
"s": 31430,
"text": "5\n6"
},
{
"code": null,
"e": 31673,
"s": 31436,
"text": "Time complexity: O(N * √N) Auxiliary space: O(1)Efficient approach: Upon observing the pattern in the function, it can be seen that “For a given number N, every number ‘x’ in the range [1, N] occurs (N/x) number of times”.For example: "
},
{
"code": null,
"e": 32034,
"s": 31673,
"text": "Let N = 6 => G(N) = F(1) + F(2) + F(3) + F(4) + F(5) + F(6) x = 1 => 1 will occurs 6 times (in F(1), F(2), F(3), F(4), F(5) and F(6)) x = 2 => 2 will occurs 3 times (in F(2), F(4) and F(6)) x = 3 => 3 will occur 2 times (in F(3) and F(6)) x = 4 => 4 will occur 1 times (in F(4)) x = 5 => 5 will occur 1 times (in F(5)) x = 6 => 6 will occur 1 times (in F(6)) "
},
{
"code": null,
"e": 32367,
"s": 32034,
"text": "From above observation, it can easily be observed that number x occurs only in its multiple less than or equal to N. Therefore, we just need to find the count of such multiples, for each value of x in [1, N], and then multiply it with x. This value is then added to the final sum.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 32371,
"s": 32367,
"text": "C++"
},
{
"code": null,
"e": 32376,
"s": 32371,
"text": "Java"
},
{
"code": null,
"e": 32384,
"s": 32376,
"text": "Python3"
},
{
"code": null,
"e": 32387,
"s": 32384,
"text": "C#"
},
{
"code": null,
"e": 32398,
"s": 32387,
"text": "Javascript"
},
{
"code": "// C++ implementation to find sum of all// proper divisor of numbers up to N #include <bits/stdc++.h>using namespace std; // Utility function to find sum of// all proper divisor of number up to Nint properDivisorSum(int n){ int sum = 0; // Loop to find the proper // divisor of every number // from 1 to N for (int i = 1; i <= n; ++i) sum += (n / i) * i; return sum - n * (n + 1) / 2;} // Driver Codeint main(){ int n = 4; cout << properDivisorSum(n) << endl; n = 5; cout << properDivisorSum(n) << endl; return 0;}",
"e": 32956,
"s": 32398,
"text": null
},
{
"code": "// Java implementation to find sum of all// proper divisor of numbers up to N // Utility function to find sum of// all proper divisor of number up to N class GFG{ static int properDivisorSum(int n) { int sum = 0; int i; // Loop to find the proper // divisor of every number // from 1 to N for (i = 1; i <= n; ++i) sum += (n / i) * i; return sum - n * (n + 1) / 2; } // Driver Code public static void main(String []args) { int n = 4; System.out.println(properDivisorSum(n)); n = 5; System.out.println(properDivisorSum(n)); }}",
"e": 33618,
"s": 32956,
"text": null
},
{
"code": "# Python3 implementation to find sum of all# proper divisor of numbers up to N # Utility function to find sum of# all proper divisor of number up to Ndef properDivisorSum(n): sum = 0 # Loop to find the proper # divisor of every number # from 1 to N for i in range(1, n + 1): sum += (n // i) * i return sum - n * (n + 1) // 2 # Driver Coden = 4print(properDivisorSum(n)) n = 5print(properDivisorSum(n)) # This code is contributed by shubhamsingh10",
"e": 34110,
"s": 33618,
"text": null
},
{
"code": "// C# implementation to find sum of all// proper divisor of numbers up to N // Utility function to find sum of// all proper divisor of number up to Nusing System; class GFG{ static int properDivisorSum(int n) { int sum = 0; int i; // Loop to find the proper // divisor of every number // from 1 to N for (i = 1; i <= n; ++i) sum += (n / i) * i; return sum - n * (n + 1) / 2; } // Driver Code public static void Main(String []args) { int n = 4; Console.WriteLine(properDivisorSum(n)); n = 5; Console.WriteLine(properDivisorSum(n)); }} // This code is contributed by 29AjayKumar",
"e": 34829,
"s": 34110,
"text": null
},
{
"code": "<script> // Javascript implementation to find sum of all// proper divisor of numbers up to N // Utility function to find sum of// all proper divisor of number up to Nfunction properDivisorSum(n){ var sum = 0; // Loop to find the proper // divisor of every number // from 1 to N for (var i = 1; i <= n; ++i) sum += parseInt(n / i) * i; return sum - n * ((n + 1) / 2);} // Driver Codevar n = 4;document.write(properDivisorSum(n)+\"<br>\");n = 5;document.write(properDivisorSum(n)+\"<br>\"); // This code is contributed by rutvik_56.</script>",
"e": 35392,
"s": 34829,
"text": null
},
{
"code": null,
"e": 35396,
"s": 35392,
"text": "5\n6"
},
{
"code": null,
"e": 35443,
"s": 35398,
"text": "Time complexity: O(N) Auxiliary space: O(1) "
},
{
"code": null,
"e": 35458,
"s": 35443,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35473,
"s": 35458,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 35480,
"s": 35473,
"text": "Yash_R"
},
{
"code": null,
"e": 35486,
"s": 35480,
"text": "ukasp"
},
{
"code": null,
"e": 35498,
"s": 35486,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35509,
"s": 35498,
"text": "nidhi_biet"
},
{
"code": null,
"e": 35525,
"s": 35509,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 35535,
"s": 35525,
"text": "rutvik_56"
},
{
"code": null,
"e": 35544,
"s": 35535,
"text": "sooda367"
},
{
"code": null,
"e": 35557,
"s": 35544,
"text": "Mathematical"
},
{
"code": null,
"e": 35570,
"s": 35557,
"text": "Mathematical"
},
{
"code": null,
"e": 35668,
"s": 35570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35712,
"s": 35668,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 35754,
"s": 35712,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 35785,
"s": 35754,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 35856,
"s": 35785,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 35881,
"s": 35856,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 35913,
"s": 35881,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 35946,
"s": 35913,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 35992,
"s": 35946,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 36036,
"s": 35992,
"text": "Generate all permutation of a set in Python"
}
]
|
Python String | ljust(), rjust(), center() - GeeksforGeeks | 02 Feb, 2018
String alignment is frequently used in many day-day applications. Python in its language offers several functions that helps to align string. Also, offers a way to add user specified padding instead of blank space.
These functions are :
str.ljust(s, width[, fillchar])
str.rjust(s, width[, fillchar])
str.center(s, width[, fillchar])
These functions respectively left-justify, right-justify and center a string in a field of given width. They return a string that is at least width characters wide, created by padding the string s with the character fillchar (default is a space) until the given width on the right, left or both sides. The string is never truncated.
This function center aligns the string according to the width specified and fills remaining space of line with blank space if ‘ fillchr ‘ argument is not passed.
Syntax :center( len, fillchr )
Parameters :len : The width of string to expand it.fillchr (optional): The character to fill in remaining space.
Return Value :The resultant center aligned string expanding the given width.
# Python3 code to demonstrate # the working of center() cstr = "I love geeksforgeeks" # Printing the original stringprint ("The original string is : \n", cstr, "\n") # Printing the center aligned string print ("The center aligned string is : ")print (cstr.center(40), "\n") # Printing the center aligned # string with fillchrprint ("Center aligned string with fillchr: ")print (cstr.center(40, '#'))
Output :
The original string is :
I love geeksforgeeks
The center aligned string is :
I love geeksforgeeks
Center aligned string with fillchr:
##########I love geeksforgeeks##########
This function left aligns the string according to the width specified and fills remaining space of line with blank space if ‘ fillchr ‘ argument is not passed.
Syntax :ljust( len, fillchr )
Parameters :len : The width of string to expand it.fillchr (optional): The character to fill in remaining space.
Return Value :The resultant left aligned string expanding the given width.
# Python3 code to demonstrate # the working of ljust() lstr = "I love geeksforgeeks" # Printing the original stringprint ("The original string is : \n", lstr, "\n") # Printing the left aligned # string with "-" padding print ("The left aligned string is : ")print (lstr.ljust(40, '-'))
Output :
The original string is :
I love geeksforgeeks
The left aligned string is :
I love geeksforgeeks--------------------
This function right aligns the string according to the width specified and fills remaining space of line with blank space if ‘ fillchr ‘ argument is not passed.
Syntax :rjust( len, fillchr )
Parameters :len : The width of string to expand it.fillchr (optional) : The character to fill in remaining space.
Return Value :The resultant right aligned string expanding the given width.
# Python3 code to demonstrate # the working of rjust() rstr = "I love geeksforgeeks" # Printing the original stringprint ("The original string is : \n", rstr, "\n") # Printing the right aligned string# with "-" padding print ("The right aligned string is : ")print (rstr.rjust(40, '-'))
Output :
The original string is :
I love geeksforgeeks
The right aligned string is :
--------------------I love geeksforgeeks
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 25473,
"s": 25445,
"text": "\n02 Feb, 2018"
},
{
"code": null,
"e": 25688,
"s": 25473,
"text": "String alignment is frequently used in many day-day applications. Python in its language offers several functions that helps to align string. Also, offers a way to add user specified padding instead of blank space."
},
{
"code": null,
"e": 25710,
"s": 25688,
"text": "These functions are :"
},
{
"code": null,
"e": 25808,
"s": 25710,
"text": "str.ljust(s, width[, fillchar])\nstr.rjust(s, width[, fillchar])\nstr.center(s, width[, fillchar])\n"
},
{
"code": null,
"e": 26141,
"s": 25808,
"text": "These functions respectively left-justify, right-justify and center a string in a field of given width. They return a string that is at least width characters wide, created by padding the string s with the character fillchar (default is a space) until the given width on the right, left or both sides. The string is never truncated."
},
{
"code": null,
"e": 26303,
"s": 26141,
"text": "This function center aligns the string according to the width specified and fills remaining space of line with blank space if ‘ fillchr ‘ argument is not passed."
},
{
"code": null,
"e": 26334,
"s": 26303,
"text": "Syntax :center( len, fillchr )"
},
{
"code": null,
"e": 26447,
"s": 26334,
"text": "Parameters :len : The width of string to expand it.fillchr (optional): The character to fill in remaining space."
},
{
"code": null,
"e": 26524,
"s": 26447,
"text": "Return Value :The resultant center aligned string expanding the given width."
},
{
"code": "# Python3 code to demonstrate # the working of center() cstr = \"I love geeksforgeeks\" # Printing the original stringprint (\"The original string is : \\n\", cstr, \"\\n\") # Printing the center aligned string print (\"The center aligned string is : \")print (cstr.center(40), \"\\n\") # Printing the center aligned # string with fillchrprint (\"Center aligned string with fillchr: \")print (cstr.center(40, '#'))",
"e": 26928,
"s": 26524,
"text": null
},
{
"code": null,
"e": 26937,
"s": 26928,
"text": "Output :"
},
{
"code": null,
"e": 27141,
"s": 26937,
"text": "The original string is : \n I love geeksforgeeks \n\nThe center aligned string is : \n I love geeksforgeeks \n\nCenter aligned string with fillchr: \n##########I love geeksforgeeks##########\n"
},
{
"code": null,
"e": 27301,
"s": 27141,
"text": "This function left aligns the string according to the width specified and fills remaining space of line with blank space if ‘ fillchr ‘ argument is not passed."
},
{
"code": null,
"e": 27331,
"s": 27301,
"text": "Syntax :ljust( len, fillchr )"
},
{
"code": null,
"e": 27444,
"s": 27331,
"text": "Parameters :len : The width of string to expand it.fillchr (optional): The character to fill in remaining space."
},
{
"code": null,
"e": 27519,
"s": 27444,
"text": "Return Value :The resultant left aligned string expanding the given width."
},
{
"code": "# Python3 code to demonstrate # the working of ljust() lstr = \"I love geeksforgeeks\" # Printing the original stringprint (\"The original string is : \\n\", lstr, \"\\n\") # Printing the left aligned # string with \"-\" padding print (\"The left aligned string is : \")print (lstr.ljust(40, '-'))",
"e": 27809,
"s": 27519,
"text": null
},
{
"code": null,
"e": 27818,
"s": 27809,
"text": "Output :"
},
{
"code": null,
"e": 27939,
"s": 27818,
"text": "The original string is : \n I love geeksforgeeks \n\nThe left aligned string is : \nI love geeksforgeeks--------------------"
},
{
"code": null,
"e": 28100,
"s": 27939,
"text": "This function right aligns the string according to the width specified and fills remaining space of line with blank space if ‘ fillchr ‘ argument is not passed."
},
{
"code": null,
"e": 28130,
"s": 28100,
"text": "Syntax :rjust( len, fillchr )"
},
{
"code": null,
"e": 28244,
"s": 28130,
"text": "Parameters :len : The width of string to expand it.fillchr (optional) : The character to fill in remaining space."
},
{
"code": null,
"e": 28320,
"s": 28244,
"text": "Return Value :The resultant right aligned string expanding the given width."
},
{
"code": "# Python3 code to demonstrate # the working of rjust() rstr = \"I love geeksforgeeks\" # Printing the original stringprint (\"The original string is : \\n\", rstr, \"\\n\") # Printing the right aligned string# with \"-\" padding print (\"The right aligned string is : \")print (rstr.rjust(40, '-'))",
"e": 28610,
"s": 28320,
"text": null
},
{
"code": null,
"e": 28619,
"s": 28610,
"text": "Output :"
},
{
"code": null,
"e": 28741,
"s": 28619,
"text": "The original string is : \n I love geeksforgeeks \n\nThe right aligned string is : \n--------------------I love geeksforgeeks"
},
{
"code": null,
"e": 28767,
"s": 28741,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 28781,
"s": 28767,
"text": "python-string"
},
{
"code": null,
"e": 28788,
"s": 28781,
"text": "Python"
},
{
"code": null,
"e": 28886,
"s": 28788,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28918,
"s": 28886,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28940,
"s": 28918,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28982,
"s": 28940,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29008,
"s": 28982,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29037,
"s": 29008,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29081,
"s": 29037,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29118,
"s": 29081,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29154,
"s": 29118,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 29196,
"s": 29154,
"text": "Check if element exists in list in Python"
}
]
|
Remove end characters from strings in Julia - strip(), lstrip() and rstrip() Methods - GeeksforGeeks | 01 Apr, 2020
The strip() is an inbuilt function in julia which is used to remove leading and trailing characters from the specified string str. These removing elements is specified by given characters chars.
Syntax:strip(str::AbstractString, chars)
Parameters:
str::AbstractString: Specified string.
chars: Specified characters.
Returns: It returns a stripped part of the given string.
Example:
# Julia program to illustrate # the use of strip() method # Getting a stripped part of the given string.println(strip("Geeks", ['s']))println(strip("GFG", ['G']))println(strip("1 + 2+3 + 4", ['+']))println(strip("+1 + 2+3 + 4+", ['+']))
Output:
Geek
F
1+2+3+4
1+2+3+4
The lstrip() is an inbuilt function in julia which is used to remove leading characters from the specified string str. These removing elements is specified by given characters chars.
Syntax:lstrip(str::AbstractString, chars)
Parameters:
str::AbstractString: Specified string.
chars: Specified characters.
Returns: It returns a stripped part of the given string.
Example:
# Julia program to illustrate # the use of lstrip() method # Getting a stripped part of the given string.println(lstrip("Geek", ['G']))println(lstrip("GFG", ['G']))println(lstrip("1 + 2+3 + 4+", ['+']))println(lstrip("+1 + 2+3 + 4", ['+']))
Output:
eek
FG
1+2+3+4+
1+2+3+4
The rstrip() is an inbuilt function in julia which is used to remove trailing characters from the specified string str. These removing elements is specified by given characters chars.
Syntax:rstrip(str::AbstractString, chars)
Parameters:
str::AbstractString: Specified string.
chars: Specified characters.
Returns: It returns a stripped part of the given string.
Example:
# Julia program to illustrate # the use of rstrip() method # Getting a stripped part of the given string.println(rstrip("Geek", ['G']))println(rstrip("GFG", ['G']))println(rstrip("1 + 2+3 + 4+", ['+']))println(rstrip("+1 + 2+3 + 4", ['+']))
Output:
Geek
GF
1+2+3+4
+1+2+3+4
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
while loop in Julia
Get array dimensions and size of a dimension in Julia - size() Method | [
{
"code": null,
"e": 25533,
"s": 25505,
"text": "\n01 Apr, 2020"
},
{
"code": null,
"e": 25728,
"s": 25533,
"text": "The strip() is an inbuilt function in julia which is used to remove leading and trailing characters from the specified string str. These removing elements is specified by given characters chars."
},
{
"code": null,
"e": 25769,
"s": 25728,
"text": "Syntax:strip(str::AbstractString, chars)"
},
{
"code": null,
"e": 25781,
"s": 25769,
"text": "Parameters:"
},
{
"code": null,
"e": 25820,
"s": 25781,
"text": "str::AbstractString: Specified string."
},
{
"code": null,
"e": 25849,
"s": 25820,
"text": "chars: Specified characters."
},
{
"code": null,
"e": 25906,
"s": 25849,
"text": "Returns: It returns a stripped part of the given string."
},
{
"code": null,
"e": 25915,
"s": 25906,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of strip() method # Getting a stripped part of the given string.println(strip(\"Geeks\", ['s']))println(strip(\"GFG\", ['G']))println(strip(\"1 + 2+3 + 4\", ['+']))println(strip(\"+1 + 2+3 + 4+\", ['+']))",
"e": 26154,
"s": 25915,
"text": null
},
{
"code": null,
"e": 26162,
"s": 26154,
"text": "Output:"
},
{
"code": null,
"e": 26186,
"s": 26162,
"text": "Geek\nF\n1+2+3+4\n1+2+3+4\n"
},
{
"code": null,
"e": 26369,
"s": 26186,
"text": "The lstrip() is an inbuilt function in julia which is used to remove leading characters from the specified string str. These removing elements is specified by given characters chars."
},
{
"code": null,
"e": 26411,
"s": 26369,
"text": "Syntax:lstrip(str::AbstractString, chars)"
},
{
"code": null,
"e": 26423,
"s": 26411,
"text": "Parameters:"
},
{
"code": null,
"e": 26462,
"s": 26423,
"text": "str::AbstractString: Specified string."
},
{
"code": null,
"e": 26491,
"s": 26462,
"text": "chars: Specified characters."
},
{
"code": null,
"e": 26548,
"s": 26491,
"text": "Returns: It returns a stripped part of the given string."
},
{
"code": null,
"e": 26557,
"s": 26548,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of lstrip() method # Getting a stripped part of the given string.println(lstrip(\"Geek\", ['G']))println(lstrip(\"GFG\", ['G']))println(lstrip(\"1 + 2+3 + 4+\", ['+']))println(lstrip(\"+1 + 2+3 + 4\", ['+']))",
"e": 26800,
"s": 26557,
"text": null
},
{
"code": null,
"e": 26808,
"s": 26800,
"text": "Output:"
},
{
"code": null,
"e": 26833,
"s": 26808,
"text": "eek\nFG\n1+2+3+4+\n1+2+3+4\n"
},
{
"code": null,
"e": 27017,
"s": 26833,
"text": "The rstrip() is an inbuilt function in julia which is used to remove trailing characters from the specified string str. These removing elements is specified by given characters chars."
},
{
"code": null,
"e": 27059,
"s": 27017,
"text": "Syntax:rstrip(str::AbstractString, chars)"
},
{
"code": null,
"e": 27071,
"s": 27059,
"text": "Parameters:"
},
{
"code": null,
"e": 27110,
"s": 27071,
"text": "str::AbstractString: Specified string."
},
{
"code": null,
"e": 27139,
"s": 27110,
"text": "chars: Specified characters."
},
{
"code": null,
"e": 27196,
"s": 27139,
"text": "Returns: It returns a stripped part of the given string."
},
{
"code": null,
"e": 27205,
"s": 27196,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of rstrip() method # Getting a stripped part of the given string.println(rstrip(\"Geek\", ['G']))println(rstrip(\"GFG\", ['G']))println(rstrip(\"1 + 2+3 + 4+\", ['+']))println(rstrip(\"+1 + 2+3 + 4\", ['+']))",
"e": 27448,
"s": 27205,
"text": null
},
{
"code": null,
"e": 27456,
"s": 27448,
"text": "Output:"
},
{
"code": null,
"e": 27482,
"s": 27456,
"text": "Geek\nGF\n1+2+3+4\n+1+2+3+4\n"
},
{
"code": null,
"e": 27488,
"s": 27482,
"text": "Julia"
},
{
"code": null,
"e": 27586,
"s": 27488,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27603,
"s": 27586,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 27663,
"s": 27603,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 27736,
"s": 27663,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 27770,
"s": 27736,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 27801,
"s": 27770,
"text": "Formatting of Strings in Julia"
},
{
"code": null,
"e": 27862,
"s": 27801,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 27893,
"s": 27862,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 27958,
"s": 27893,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 27978,
"s": 27958,
"text": "while loop in Julia"
}
]
|
HTML <pre> Tag - GeeksforGeeks | 17 Mar, 2022
The <pre> tag in HTML is used to define the block of preformatted text which preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers. Text in the <pre> element is displayed in a fixed-width font, but it can be changed using CSS. The <pre> tag requires a starting and end tag.Syntax:
<pre> Contents... </pre>
Below examples illustrate the <pre> tag in HTML:Example 1:
HTML
<html> <body> <!-- html pre tag starts here --> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> <!-- html pre tag ends here --> </body></html>
Output:
Example 2:
HTML
<html> <head> <title>pre tag with CSS</title> <style> pre { font-family: Arial; color: #009900; margin: 25px; } </style> </head> <body> <!-- html pre tag starts here --> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> <!-- html pre tag ends here --> </body></html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to 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 ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet) | [
{
"code": null,
"e": 24331,
"s": 24303,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 24672,
"s": 24331,
"text": "The <pre> tag in HTML is used to define the block of preformatted text which preserves the text spaces, line breaks, tabs, and other formatting characters which are ignored by web browsers. Text in the <pre> element is displayed in a fixed-width font, but it can be changed using CSS. The <pre> tag requires a starting and end tag.Syntax: "
},
{
"code": null,
"e": 24697,
"s": 24672,
"text": "<pre> Contents... </pre>"
},
{
"code": null,
"e": 24758,
"s": 24697,
"text": "Below examples illustrate the <pre> tag in HTML:Example 1: "
},
{
"code": null,
"e": 24763,
"s": 24758,
"text": "HTML"
},
{
"code": "<html> <body> <!-- html pre tag starts here --> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> <!-- html pre tag ends here --> </body></html> ",
"e": 25000,
"s": 24763,
"text": null
},
{
"code": null,
"e": 25010,
"s": 25000,
"text": "Output: "
},
{
"code": null,
"e": 25023,
"s": 25010,
"text": "Example 2: "
},
{
"code": null,
"e": 25028,
"s": 25023,
"text": "HTML"
},
{
"code": "<html> <head> <title>pre tag with CSS</title> <style> pre { font-family: Arial; color: #009900; margin: 25px; } </style> </head> <body> <!-- html pre tag starts here --> <pre> GeeksforGeeks A Computer Science Portal For Geeks </pre> <!-- html pre tag ends here --> </body></html>",
"e": 25462,
"s": 25028,
"text": null
},
{
"code": null,
"e": 25472,
"s": 25462,
"text": "Output: "
},
{
"code": null,
"e": 25494,
"s": 25472,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 25508,
"s": 25494,
"text": "Google Chrome"
},
{
"code": null,
"e": 25526,
"s": 25508,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25534,
"s": 25526,
"text": "Firefox"
},
{
"code": null,
"e": 25540,
"s": 25534,
"text": "Opera"
},
{
"code": null,
"e": 25547,
"s": 25540,
"text": "Safari"
},
{
"code": null,
"e": 25686,
"s": 25549,
"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": 25700,
"s": 25686,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 25710,
"s": 25700,
"text": "HTML-Tags"
},
{
"code": null,
"e": 25715,
"s": 25710,
"text": "HTML"
},
{
"code": null,
"e": 25720,
"s": 25715,
"text": "HTML"
},
{
"code": null,
"e": 25818,
"s": 25720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25868,
"s": 25818,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 25930,
"s": 25868,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 25978,
"s": 25930,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26038,
"s": 25978,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 26091,
"s": 26038,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 26152,
"s": 26091,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 26176,
"s": 26152,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26226,
"s": 26176,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26276,
"s": 26226,
"text": "CSS to put icon inside an input element in a form"
}
]
|
How to compile 32-bit program on 64-bit gcc in C and C++ - GeeksforGeeks | 11 Oct, 2021
Mostly compiler(gcc or clang) of C and C++, nowadays come with default 64-bit version. Well it would be a good option in terms of speed purposes. But it would lead to problem, if someone wants to run their program as a 32-bit rather than 64-bit for testing or debugging purposes. Therefore we must have a knowledge about this.Before proceeding forward, let’s confirm which bit-version of gcc is currently installed in our system. Just type the following command on Linux terminal.
Command: gcc -v
Output
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper
Target: x86_64-linux-gnu
......................
......................
Hence the fourth line Target: x86_64-linux-gnu confirms that we are running 64-bit gcc.Now in order to compile with 32-bit gcc, just add a flag -m32 in the command line of compiling the ‘C’ language program. For instance, to compile a file of geek.c through Linux terminal, you must write the following command with -m32 flag.
Command: gcc -m32 geek.c -o geek
If you get an error as follows:
fatal error: bits/predefs.h: No such file or directory
Then it indicates that a standard library of gcc is been missing. In that case you must install gcc-multlib by using the following command:
For C language:
sudo apt-get install gcc-multilib
For C++ language:
sudo apt-get install g++-multilib
After that you will be able to compile a 32-bit binary on a 64-bit system.How to check whether a program is compiled with 32-bit after adding a “-m32” flag? Well we can easily check this by the following program.
CPP
// C program to demonstrate difference// in output in 32-bit and 64-bit gcc// File name: geek.c#include<stdio.h>int main(){ printf("Size = %lu", sizeof(size_t));}
Compile the above program in Linux by these two different commands, Default 64-bit compilation,
Input: gcc -m64 geek.c -o out
Output: ./out
Size = 8
Forced 32-bit compilation,
Input: gcc -m32 geek.c -o out
Output: ./out
Size = 4
Can we conclude anything from above program. Yes maybe, let’s try to understand more. Since the size of data types like long, size_t, pointer data type(int*, char* etc) is compiler dependent, therefore it will generate a different output according to bit of compiler.This article is contributed by Shubham Bansal. 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.
vaibhavsinghtanwar
abhishek0719kadiyan
CPP-Basics
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Substring in C++
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects | [
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 26044,
"s": 25561,
"text": "Mostly compiler(gcc or clang) of C and C++, nowadays come with default 64-bit version. Well it would be a good option in terms of speed purposes. But it would lead to problem, if someone wants to run their program as a 32-bit rather than 64-bit for testing or debugging purposes. Therefore we must have a knowledge about this.Before proceeding forward, let’s confirm which bit-version of gcc is currently installed in our system. Just type the following command on Linux terminal. "
},
{
"code": null,
"e": 26241,
"s": 26044,
"text": "Command: gcc -v\nOutput \nUsing built-in specs.\nCOLLECT_GCC=gcc\nCOLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper\nTarget: x86_64-linux-gnu\n......................\n......................"
},
{
"code": null,
"e": 26570,
"s": 26241,
"text": "Hence the fourth line Target: x86_64-linux-gnu confirms that we are running 64-bit gcc.Now in order to compile with 32-bit gcc, just add a flag -m32 in the command line of compiling the ‘C’ language program. For instance, to compile a file of geek.c through Linux terminal, you must write the following command with -m32 flag. "
},
{
"code": null,
"e": 26603,
"s": 26570,
"text": "Command: gcc -m32 geek.c -o geek"
},
{
"code": null,
"e": 26637,
"s": 26603,
"text": "If you get an error as follows: "
},
{
"code": null,
"e": 26692,
"s": 26637,
"text": "fatal error: bits/predefs.h: No such file or directory"
},
{
"code": null,
"e": 26834,
"s": 26692,
"text": "Then it indicates that a standard library of gcc is been missing. In that case you must install gcc-multlib by using the following command: "
},
{
"code": null,
"e": 26936,
"s": 26834,
"text": "For C language:\nsudo apt-get install gcc-multilib\nFor C++ language:\nsudo apt-get install g++-multilib"
},
{
"code": null,
"e": 27151,
"s": 26936,
"text": "After that you will be able to compile a 32-bit binary on a 64-bit system.How to check whether a program is compiled with 32-bit after adding a “-m32” flag? Well we can easily check this by the following program. "
},
{
"code": null,
"e": 27155,
"s": 27151,
"text": "CPP"
},
{
"code": "// C program to demonstrate difference// in output in 32-bit and 64-bit gcc// File name: geek.c#include<stdio.h>int main(){ printf(\"Size = %lu\", sizeof(size_t));}",
"e": 27321,
"s": 27155,
"text": null
},
{
"code": null,
"e": 27419,
"s": 27321,
"text": "Compile the above program in Linux by these two different commands, Default 64-bit compilation, "
},
{
"code": null,
"e": 27472,
"s": 27419,
"text": "Input: gcc -m64 geek.c -o out\nOutput: ./out\nSize = 8"
},
{
"code": null,
"e": 27501,
"s": 27472,
"text": "Forced 32-bit compilation, "
},
{
"code": null,
"e": 27554,
"s": 27501,
"text": "Input: gcc -m32 geek.c -o out\nOutput: ./out\nSize = 4"
},
{
"code": null,
"e": 28120,
"s": 27554,
"text": "Can we conclude anything from above program. Yes maybe, let’s try to understand more. Since the size of data types like long, size_t, pointer data type(int*, char* etc) is compiler dependent, therefore it will generate a different output according to bit of compiler.This article is contributed by Shubham Bansal. 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": 28139,
"s": 28120,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 28159,
"s": 28139,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 28170,
"s": 28159,
"text": "CPP-Basics"
},
{
"code": null,
"e": 28181,
"s": 28170,
"text": "C Language"
},
{
"code": null,
"e": 28185,
"s": 28181,
"text": "C++"
},
{
"code": null,
"e": 28189,
"s": 28185,
"text": "CPP"
},
{
"code": null,
"e": 28287,
"s": 28189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28322,
"s": 28287,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 28368,
"s": 28322,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28385,
"s": 28368,
"text": "Substring in C++"
},
{
"code": null,
"e": 28425,
"s": 28385,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 28453,
"s": 28425,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 28471,
"s": 28453,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28490,
"s": 28471,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28536,
"s": 28490,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28579,
"s": 28536,
"text": "Map in C++ Standard Template Library (STL)"
}
]
|
Sliding Window Maximum (Maximum of all subarrays of size k) - GeeksforGeeks | 11 May, 2022
Given an array and an integer K, find the maximum for each and every contiguous subarray of size k.
Examples :
Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3
Output: 3 3 4 5 5 5 6
Explanation:
Maximum of 1, 2, 3 is 3
Maximum of 2, 3, 1 is 3
Maximum of 3, 1, 4 is 4
Maximum of 1, 4, 5 is 5
Maximum of 4, 5, 2 is 5
Maximum of 5, 2, 3 is 5
Maximum of 2, 3, 6 is 6
Input: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4
Output: 10 10 10 15 15 90 90
Explanation:
Maximum of first 4 elements is 10, similarly for next 4
elements (i.e from index 1 to 4) is 10, So the sequence
generated is 10 10 10 15 15 90 90
Method 1: This is a simple method to solve the above problem.
Approach: The idea is very basic run a nested loop, the outer loop which will mark the starting point of the subarray of length k, the inner loop will run from the starting index to index+k, k elements from starting index and print the maximum element among these k elements.
Algorithm:
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.
Create a nested loop, the outer loop from starting index to n – k th elements. The inner loop will run for k iterations.Create a variable to store the maximum of k elements traversed by the inner loop.Find the maximum of k elements traversed by the inner loop.Print the maximum element in every iteration of outer loop
Create a nested loop, the outer loop from starting index to n – k th elements. The inner loop will run for k iterations.
Create a variable to store the maximum of k elements traversed by the inner loop.
Find the maximum of k elements traversed by the inner loop.
Print the maximum element in every iteration of outer loop
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to find the maximum for// each and every contiguous subarray of size k.#include <bits/stdc++.h>using namespace std; // Method to find the maximum for each// and every contiguous subarray of size k.void printKMax(int arr[], int n, int k){ int j, max; for (int i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } cout << max << " "; }} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; printKMax(arr, n, k); return 0;} // This code is contributed by rathbhupendra
#include <stdio.h> void printKMax(int arr[], int n, int k){ int j, max; for (int i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } printf("%d ", max); }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; printKMax(arr, n, k); return 0;}
// Java Program to find the maximum// for each and every contiguous// subarray of size k. public class GFG{ // Method to find the maximum for // each and every contiguous // subarray of size k. static void printKMax(int arr[], int n, int k) { int j, max; for (int i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } System.out.print(max + " "); } } // Driver code public static void main(String args[]) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int k = 3; printKMax(arr, arr.length, k); }} // This code is contributed by Sumit Ghosh
# Python program to find the maximum for# each and every contiguous subarray of# size k # Method to find the maximum for each# and every contiguous subarray# of size kdef printMax(arr, n, k): max = 0 for i in range(n - k + 1): max = arr[i] for j in range(1, k): if arr[i + j] > max: max = arr[i + j] print(str(max) + " ", end = "") # Driver methodif __name__=="__main__": arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] n = len(arr) k = 3 printMax(arr, n, k) # This code is contributed by Shiv Shankar
// C# program to find the maximum for// each and every contiguous subarray of// size kusing System;using System; class GFG { // Method to find the maximum for // each and every contiguous subarray // of size k. static void printKMax(int[] arr, int n, int k) { int j, max; for (int i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } Console.Write(max + " "); } } // Driver method public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int k = 3; printKMax(arr, arr.Length, k); }} // This Code is Contributed by Sam007
<?php// PHP program to find the maximum// for each and every contiguous// subarray of size k function printKMax($arr, $n, $k){ $j; $max; for ($i = 0; $i <= $n - $k; $i++) { $max = $arr[$i]; for ($j = 1; $j < $k; $j++) { if ($arr[$i + $j] > $max) $max = $arr[$i + $j]; } printf("%d ", $max); }} // Driver Code$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);$n = count($arr);$k = 3;printKMax($arr, $n, $k); // This Code is Contributed by anuj_67.?>
<script> // JavaScript Program to find the maximum for// each and every contiguous subarray of size k. // Method to find the maximum for each// and every contiguous subarray of size k.function printKMax(arr,n,k){ let j, max; for (let i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } document.write( max + " "); }} // Driver code let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; let n =arr.length; let k = 3; printKMax(arr, n, k); // This code contributed by gauravrajput1 </script>
3 4 5 6 7 8 9 10
Complexity Analysis:
Time Complexity: O(N * K). The outer loop runs n-k+1 times and the inner loop runs k times for every iteration of outer loop. So time complexity is O((n-k+1)*k) which can also be written as O(N * K).
Space Complexity: O(1). No extra space is required.
Method 2: This method uses the Self-Balancing BST to solve the given problem.
Approach: To find maximum among k elements of the subarray the previous method uses a loop traversing through the elements. To reduce that time the idea is to use an AVL tree which returns the maximum element in log n time. So, traverse through the array and keep k elements in the BST and print the maximum in every iteration. AVL tree is a suitable data structure as lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation.
Algorithm:
Create a Self-balancing BST (AVL tree) to store and find the maximum element.Traverse through the array from start to end.Insert the element in the AVL tree.If the loop counter is greater than or equal to k then delete i-k th element from the BSTPrint the maximum element of the BST.
Create a Self-balancing BST (AVL tree) to store and find the maximum element.
Traverse through the array from start to end.
Insert the element in the AVL tree.
If the loop counter is greater than or equal to k then delete i-k th element from the BST
Print the maximum element of the BST.
Implementation:
C++14
Java
Python3
C#
Javascript
// C++ program to delete a node from AVL Tree#include<bits/stdc++.h>using namespace std; // An AVL tree nodeclass Node{ public: int key; Node *left; Node *right; int height;}; // A utility function to get maximum// of two integersint max(int a, int b); // A utility function to get height// of the treeint height(Node *N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum// of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates anew node with the given key andNULL left and right pointers. */Node* newNode(int key){ Node* node = new Node(); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially // added at leaf return(node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.Node *rightRotate(Node *y){ Node *x = y->left; Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.Node *leftRotate(Node *x){ Node *y = x->right; Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} Node* insert(Node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree,return the node with minimum key valuefound in that tree. Note that the entiretree does not need to be searched. */Node * minValueNode(Node* node){ Node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} // Recursive function to delete a node// with given key from subtree with// given root. It returns root of the// modified subtree.Node* deleteNode(Node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller // than the root's key, then it lies // in left subtree if ( key < root->key ) root->left = deleteNode(root->left, key); // If the key to be deleted is greater // than the root's key, then it lies // in right subtree else if( key > root->key ) root->right = deleteNode(root->right, key); // if key is same as root's key, then // This is the node to be deleted else { // node with only one child or no child if( (root->left == NULL) || (root->right == NULL) ) { Node *temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of // the non-empty child free(temp); } else { // node with two children: Get the inorder // successor (smallest in the right subtree) Node* temp = minValueNode(root->right); // Copy the inorder successor's // data to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node // then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = 1 + max(height(root->left), height(root->right)); // STEP 3: GET THE BALANCE FACTOR OF // THIS NODE (to check whether this // node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder// traversal of the tree.// The function also prints height// of every nodevoid preOrder(Node *root){ if(root != NULL) { cout << root->key << " "; preOrder(root->left); preOrder(root->right); }} // Returns maximum value in a given // Binary Tree int findMax(Node* root) { // Base case if (root == NULL) return INT_MIN; // Return maximum of 3 values: // 1) Root's data 2) Max in Left Subtree // 3) Max in right subtree int res = root->key; int lres = findMax(root->left); int rres = findMax(root->right); if (lres > res) res = lres; if (rres > res) res = rres; return res; } // Method to find the maximum for each// and every contiguous subarray of size k.void printKMax(int arr[], int n, int k){ int c = 0,l=0; Node *root = NULL; //traverse the array ; for(int i=0; i<n; i++) { c++; //insert the element in BST root = insert(root, arr[i]); //size of subarray greater than k if(c > k) { root = deleteNode(root, arr[l++]); c--; } //size of subarray equal to k if(c == k) { cout<<findMax(root)<<" "; } }}// Driver codeint main(){ int arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, k = 4; int n = sizeof(arr) / sizeof(arr[0]); printKMax(arr, n, k); return 0;}
// JAVA program to delete a node from AVL Treeimport java.io.*;import java.util.*; class GFG { static ArrayList<Integer> findKMaxElement(int[] arr, int k, int n) { // creating the max heap ,to get max element always PriorityQueue<Integer> queue = new PriorityQueue<>( Collections.reverseOrder()); ArrayList<Integer> res = new ArrayList<>(); int i = 0; for (; i < k; i++) queue.add(arr[i]); // adding the maximum element among first k elements res.add(queue.peek()); // removing the first element of the array queue.remove(arr[0]); // iterarting for the next elements for (; i < n; i++) { // adding the new element in the window queue.add(arr[i]); // finding & adding the max element in the // current sliding window res.add(queue.peek()); // finally removing the first element from front // end of queue queue.remove(arr[i - k + 1]); } return res; // this code is Contributed by Pradeep Mondal P } // Driver Code public static void main(String[] args) { int arr[] = { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 }; int k = 4, n = arr.length; List<Integer> res = findKMaxElement(arr, k, n); for (int x : res) System.out.print(x + " "); }}
# Python code for the above approachdef findKMaxElement(arr, k, n): # creating the max heap ,to get max element always queue = [] res = [] i = 0 while(i<k): queue.append(arr[i]) i += 1 queue.sort(reverse=True) # adding the maximum element among first k elements res.append(queue[0]) # removing the first element of the array queue.remove(arr[0]) # iterarting for the next elements while(i<n): # adding the new element in the window queue.append(arr[i]) queue.sort(reverse=True) # finding & adding the max element in the # current sliding window res.append(queue[0]) # finally removing the first element from front # end of queue queue.remove(arr[i - k + 1]) i += 1 return res # Driver Codearr = [ 8, 5, 10, 7, 9, 4, 15, 12, 90, 13]k,n = 4,len(arr)res = findKMaxElement(arr, k, n)for x in res: print(x ,end = " ") # This code is contributed by shinjanpatra
// C# program to delete a node from AVL Treeusing System;using System.Collections.Generic; public class GFG { static List<int> findKMaxElement(int[] arr, int k, int n) { // creating the max heap ,to get max element always List<int> queue = new List<int>(); List<int> res = new List<int>(); int i = 0; for (; i < k; i++) queue.Add(arr[i]); queue.Sort(); queue.Reverse(); // adding the maximum element among first k elements res.Add(queue[0]); // removing the first element of the array queue.Remove(arr[0]); // iterarting for the next elements for (; i < n; i++) { // adding the new element in the window queue.Add(arr[i]); queue.Sort(); queue.Reverse(); // finding & adding the max element in the // current sliding window res.Add(queue[0]); // finally removing the first element from front // end of queue queue.Remove(arr[i - k + 1]); } return res; // this code is Contributed by Pradeep Mondal P } // Driver Code public static void Main(String[] args) { int[] arr = { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 }; int k = 4, n = arr.Length; List<int> res = findKMaxElement(arr, k, n); foreach(int x in res) Console.Write(x + " "); }} // This code is contributed by umadevi9616
<script>// JAVAscript program to delete a node from AVL Tree function findKMaxElement(arr, k, n){ // creating the max heap ,to get max element always let queue = []; let res = []; let i = 0; for (; i < k; i++) queue.push(arr[i]); queue.sort(function(a,b){return b-a;}); // adding the maximum element among first k elements res.push(queue[0]); // removing the first element of the array queue.splice(arr[0],1); // iterarting for the next elements for (; i < n; i++) { // adding the new element in the window queue.push(arr[i]); queue.sort(function(a,b){return b-a;}); // finding & adding the max element in the // current sliding window res.push(queue[0]); // finally removing the first element from front // end of queue queue.splice(arr[i - k + 1],1); } return res; // this code is Contributed by Pradeep Mondal P} // Driver Codelet arr = [ 8, 5, 10, 7, 9, 4, 15, 12, 90, 13];let k = 4, n = arr.length;let res = findKMaxElement(arr, k, n);for (let x of res) document.write(x + " "); // This code is contributed by avanitrachhadiya2155</script>
10 10 10 15 15 90 90
Complexity Analysis:
Time Complexity: O(N * Log k). Insertion, deletion and search takes log k time in a AVL tree. So the overall time Complexity is O(N * log k)
Space Complexity: O(k). The space required to store k elements in a BST is O(k).
Method 3: This method uses Deque to solve the above problem
Approach: Create a Deque, Qi of capacity k, that stores only useful elements of current window of k elements. An element is useful if it is in current window and is greater than all other elements on right side of it in current window. Process all array elements one by one and maintain Qi to contain useful elements of current window and these useful elements are maintained in sorted order. The element at front of the Qi is the largest and element at rear/back of Qi is the smallest of current window. Thanks to Aashish for suggesting this method.
Dry run of the above approach:
Algorithm:
Create a deque to store k elements.Run a loop and insert first k elements in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque, until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque.Now, run a loop from k to end of the array.Print the front element of the deque.Remove the element from the front of the queue if they are out of the current window.Insert the next element in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque, until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque.Print the maximum element of the last window.
Create a deque to store k elements.
Run a loop and insert first k elements in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque, until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque.
Now, run a loop from k to end of the array.
Print the front element of the deque.
Remove the element from the front of the queue if they are out of the current window.
Insert the next element in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque, until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque.
Print the maximum element of the last window.
Implementation:
C++
Java
Python3
C#
// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // A Dequeue (Double ended queue) based// method for printing maximum element of// all subarrays of size kvoid printKMax(int arr[], int n, int k){ // Create a Double Ended Queue, // Qi that will store indexes // of array elements // The queue will store indexes // of useful elements in every // window and it will // maintain decreasing order of // values from front to rear in Qi, i.e., // arr[Qi.front[]] to arr[Qi.rear()] // are sorted in decreasing order std::deque<int> Qi(k); /* Process first k (or first window) elements of array */ int i; for (i = 0; i < k; ++i) { // For every element, the previous // smaller elements are useless so // remove them from Qi while ((!Qi.empty()) && arr[i] >= arr[Qi.back()]) // Remove from rear Qi.pop_back(); // Add new element at rear of queue Qi.push_back(i); } // Process rest of the elements, // i.e., from arr[k] to arr[n-1] for (; i < n; ++i) { // The element at the front of // the queue is the largest element of // previous window, so print it cout << arr[Qi.front()] << " "; // Remove the elements which // are out of this window while ((!Qi.empty()) && Qi.front() <= i - k) // Remove from front of queue Qi.pop_front(); // Remove all elements // smaller than the currently // being added element (remove // useless elements) while ((!Qi.empty()) && arr[i] >= arr[Qi.back()]) Qi.pop_back(); // Add current element at the rear of Qi Qi.push_back(i); } // Print the maximum element // of last window cout << arr[Qi.front()];} // Driver codeint main(){ int arr[] = { 12, 1, 78, 90, 57, 89, 56 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; printKMax(arr, n, k); return 0;}
// Java Program to find the maximum for// each and every contiguous subarray of size k.import java.util.Deque;import java.util.LinkedList; public class SlidingWindow{ // A Dequeue (Double ended queue) // based method for printing // maximum element of // all subarrays of size k static void printMax(int arr[], int n, int k) { // Create a Double Ended Queue, Qi // that will store indexes of array elements // The queue will store indexes of // useful elements in every window and it will // maintain decreasing order of values // from front to rear in Qi, i.e., // arr[Qi.front[]] to arr[Qi.rear()] // are sorted in decreasing order Deque<Integer> Qi = new LinkedList<Integer>(); /* Process first k (or first window) elements of array */ int i; for (i = 0; i < k; ++i) { // For every element, the previous // smaller elements are useless so // remove them from Qi while (!Qi.isEmpty() && arr[i] >= arr[Qi.peekLast()]) // Remove from rear Qi.removeLast(); // Add new element at rear of queue Qi.addLast(i); } // Process rest of the elements, // i.e., from arr[k] to arr[n-1] for (; i < n; ++i) { // The element at the front of the // queue is the largest element of // previous window, so print it System.out.print(arr[Qi.peek()] + " "); // Remove the elements which // are out of this window while ((!Qi.isEmpty()) && Qi.peek() <= i - k) Qi.removeFirst(); // Remove all elements smaller // than the currently // being added element (remove // useless elements) while ((!Qi.isEmpty()) && arr[i] >= arr[Qi.peekLast()]) Qi.removeLast(); // Add current element at the rear of Qi Qi.addLast(i); } // Print the maximum element of last window System.out.print(arr[Qi.peek()]); } // Driver code public static void main(String[] args) { int arr[] = { 12, 1, 78, 90, 57, 89, 56 }; int k = 3; printMax(arr, arr.length, k); }}// This code is contributed by Sumit Ghosh
# Python program to find the maximum for# each and every contiguous subarray of# size k from collections import deque # A Deque (Double ended queue) based# method for printing maximum element# of all subarrays of size kdef printMax(arr, n, k): """ Create a Double Ended Queue, Qi that will store indexes of array elements. The queue will store indexes of useful elements in every window and it will maintain decreasing order of values from front to rear in Qi, i.e., arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order""" Qi = deque() # Process first k (or first window) # elements of array for i in range(k): # For every element, the previous # smaller elements are useless # so remove them from Qi while Qi and arr[i] >= arr[Qi[-1]] : Qi.pop() # Add new element at rear of queue Qi.append(i); # Process rest of the elements, i.e. # from arr[k] to arr[n-1] for i in range(k, n): # The element at the front of the # queue is the largest element of # previous window, so print it print(str(arr[Qi[0]]) + " ", end = "") # Remove the elements which are # out of this window while Qi and Qi[0] <= i-k: # remove from front of deque Qi.popleft() # Remove all elements smaller than # the currently being added element # (Remove useless elements) while Qi and arr[i] >= arr[Qi[-1]] : Qi.pop() # Add current element at the rear of Qi Qi.append(i) # Print the maximum element of last window print(str(arr[Qi[0]])) # Driver codeif __name__=="__main__": arr = [12, 1, 78, 90, 57, 89, 56] k = 3 printMax(arr, len(arr), k) # This code is contributed by Shiv Shankar
// C# Program to find the maximum for each// and every contiguous subarray of size k.using System;using System.Collections.Generic; public class SlidingWindow{ // A Dequeue (Double ended queue) based // method for printing maximum element of // all subarrays of size k static void printMax(int []arr, int n, int k) { // Create a Double Ended Queue, Qi that // will store indexes of array elements // The queue will store indexes of useful // elements in every window and it will // maintain decreasing order of values // from front to rear in Qi, i.e., // arr[Qi.front[]] to arr[Qi.rear()] // are sorted in decreasing order List<int> Qi = new List<int>(); /* Process first k (or first window) elements of array */ int i; for (i = 0; i < k; ++i) { // For every element, the previous // smaller elements are useless so // remove them from Qi while (Qi.Count != 0 && arr[i] >= arr[Qi[Qi.Count-1]]) // Remove from rear Qi.RemoveAt(Qi.Count-1); // Add new element at rear of queue Qi.Insert(Qi.Count, i); } // Process rest of the elements, // i.e., from arr[k] to arr[n-1] for (; i < n; ++i) { // The element at the front of // the queue is the largest element of // previous window, so print it Console.Write(arr[Qi[0]] + " "); // Remove the elements which are // out of this window while ((Qi.Count != 0) && Qi[0] <= i - k) Qi.RemoveAt(0); // Remove all elements smaller // than the currently // being added element (remove // useless elements) while ((Qi.Count != 0) && arr[i] >= arr[Qi[Qi.Count - 1]]) Qi.RemoveAt(Qi.Count - 1); // Add current element at the rear of Qi Qi.Insert(Qi.Count, i); } // Print the maximum element of last window Console.Write(arr[Qi[0]]); } // Driver code public static void Main(String[] args) { int []arr = { 12, 1, 78, 90, 57, 89, 56 }; int k = 3; printMax(arr, arr.Length, k); }} // This code has been contributed by 29AjayKumar
78 90 90 90 89
Complexity Analysis:
Time Complexity: O(n). It seems more than O(n) at first look. It can be observed that every element of array is added and removed at most once. So there are total 2n operations.
Auxiliary Space: O(k). Elements stored in the dequeue take O(k) space.
Below is an extension of this problem: Sum of minimum and maximum elements of all subarrays of size k.
Method 4: This method is modification in queue implementation of two stack:
Algorithm :
While pushing the element, we constantly push in stack 2. The maximum of stack 2 will always be the maximum of the top element of stack 2.
While popping, we will always pop from stack 1, and if stack 1 is empty then we shall push every element of stack 2 to stack 1 and updating the maximum
The above two-step are followed in queue implementation of stack
Now to find the maximum of the whole queue (Same as both stack), we will take the top element of both stack maximum; hence this is the maximum of the whole queue.
Now, this technique can be used to slide window and get maximum.
while sliding window by 1 index delete the last one, insert the new one and then take a maximum of both stack
Implementation
C++
#include <bits/stdc++.h>using namespace std; struct node{ int data; int maximum;}; // it is a modification in the way of implementation of queue using two stack void insert(stack<node> &s2 , int val){ //inserting the element in s2 node other; other.data=val; if(s2.empty()) other.maximum=val; else { node front=s2.top(); //updating maximum in that stack push it other.maximum=max(val,front.maximum); } s2.push(other); return;} void delete(stack<node> &s1 ,stack<node> &s2 ){ //if s1 is not empty directly pop //else we have to push all element from s2 and thatn pop from s1 //while pushing from s2 to s1 update maximum variable in s1 if(s1.size()) s1.pop(); else { while(!s2.empty()) { node val=s2.top(); insert(s1,val.data); s2.pop(); } s1.pop(); }} int get_max(stack<node> &s1 ,stack<node> &s2 ){ // the maximum of both stack will be the maximum of overall window int ans=-1; if(s1.size()) ans=max(ans,s1.top().maximum); if(s2.size()) ans=max(ans,s2.top().maximum); return ans;} vector<int> slidingMaximum(int a[], int b,int n) { //s2 for push //s1 for pop vector<int>ans; stack<node>s1,s2; //shifting all value except the last one if first window for(int i=0;i<b-1;i++) insert(s2,a[i]); for(int i=0;i<=n-b;i++) { //removing the last element of previous window as window has shift by one if(i-1>=0) delete(s1,s2); //adding the new element to the window as the window is shift by one insert(s2,a[i+b-1]); ans.push_back(get_max(s1,s2)); } return ans;} int main(){ int arr[] = { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; vector<int> ans=slidingMaximum(arr,k,n); for(auto x:ans) cout<<x<<" "; return 0;}
78 90 90 90 89
Complexity Analysis:
Time Complexity: O(N): This is because every element will just two types push and pop; hence time complexity is linear.
Space Complexity: O(K): This is because at any moment, the sum of stack size of both stacks will exactly equal to K, As every time we pop exactly one element and push exactly One.
Method 5: This method uses Max-Heap to solve the above problem.
Approach: In the above-mentioned methods, one of them was using AVL tree. This approach is very similar to that approach. The difference is that instead of using the AVL tree, Max-Heap will be used in this approach. The elements of the current window will be stored in the Max-Heap and the maximum element or the root will be printed in each iteration. Max-heap is a suitable data structure as it provides constant-time retrieval and logarithmic time removal of both the minimum and maximum elements in it, i.e. it takes constant time to find the maximum element, and insertion and deletion takes log n time.
Algorithm:
Pick first k elements and create a max heap of size k.Perform heapify and print the root element.Store the next and last element from the arrayRun a loop from k – 1 to n Replace the value of element which is got out of the window with new element which came inside the window.Perform heapify.Print the root of the Heap.
Pick first k elements and create a max heap of size k.
Perform heapify and print the root element.
Store the next and last element from the array
Run a loop from k – 1 to n Replace the value of element which is got out of the window with new element which came inside the window.Perform heapify.Print the root of the Heap.
Replace the value of element which is got out of the window with new element which came inside the window.
Perform heapify.
Print the root of the Heap.
vt_m
Roy19
MuninderJeetSingh
29AjayKumar
nidhi_biet
rathbhupendra
andrew1234
agrwl.harsh16
hsnice16
pradeepmondalp
single__loop
GauravRajput1
ankitkay
happy2000jain
architgwl2000
avanitrachhadiya2155
anikakapoor
krishna_97
surinderdawra388
prophet1999
umadevi9616
Rajput-Ji
menonkartikeya
simmytarika5
shinjanpatra
Amazon
Directi
Flipkart
SAP Labs
sliding-window
Zoho
Arrays
Heap
Queue
Zoho
Flipkart
Amazon
Directi
SAP Labs
sliding-window
Arrays
Queue
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
HeapSort
Binary Heap
Huffman Coding | Greedy Algo-3
K'th Smallest/Largest Element in Unsorted Array | Set 1
k largest(or smallest) elements in an array | [
{
"code": null,
"e": 26375,
"s": 26347,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 26475,
"s": 26375,
"text": "Given an array and an integer K, find the maximum for each and every contiguous subarray of size k."
},
{
"code": null,
"e": 26487,
"s": 26475,
"text": "Examples : "
},
{
"code": null,
"e": 26993,
"s": 26487,
"text": "Input: arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, K = 3 \nOutput: 3 3 4 5 5 5 6\nExplanation: \nMaximum of 1, 2, 3 is 3\nMaximum of 2, 3, 1 is 3\nMaximum of 3, 1, 4 is 4\nMaximum of 1, 4, 5 is 5\nMaximum of 4, 5, 2 is 5 \nMaximum of 5, 2, 3 is 5\nMaximum of 2, 3, 6 is 6\n\nInput: arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, K = 4 \nOutput: 10 10 10 15 15 90 90\nExplanation:\nMaximum of first 4 elements is 10, similarly for next 4 \nelements (i.e from index 1 to 4) is 10, So the sequence \ngenerated is 10 10 10 15 15 90 90"
},
{
"code": null,
"e": 27055,
"s": 26993,
"text": "Method 1: This is a simple method to solve the above problem."
},
{
"code": null,
"e": 27332,
"s": 27055,
"text": "Approach: The idea is very basic run a nested loop, the outer loop which will mark the starting point of the subarray of length k, the inner loop will run from the starting index to index+k, k elements from starting index and print the maximum element among these k elements. "
},
{
"code": null,
"e": 27344,
"s": 27332,
"text": "Algorithm: "
},
{
"code": null,
"e": 27353,
"s": 27344,
"text": "Chapters"
},
{
"code": null,
"e": 27380,
"s": 27353,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 27430,
"s": 27380,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 27453,
"s": 27430,
"text": "captions off, selected"
},
{
"code": null,
"e": 27461,
"s": 27453,
"text": "English"
},
{
"code": null,
"e": 27485,
"s": 27461,
"text": "This is a modal window."
},
{
"code": null,
"e": 27554,
"s": 27485,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 27576,
"s": 27554,
"text": "End of dialog window."
},
{
"code": null,
"e": 27895,
"s": 27576,
"text": "Create a nested loop, the outer loop from starting index to n – k th elements. The inner loop will run for k iterations.Create a variable to store the maximum of k elements traversed by the inner loop.Find the maximum of k elements traversed by the inner loop.Print the maximum element in every iteration of outer loop"
},
{
"code": null,
"e": 28016,
"s": 27895,
"text": "Create a nested loop, the outer loop from starting index to n – k th elements. The inner loop will run for k iterations."
},
{
"code": null,
"e": 28098,
"s": 28016,
"text": "Create a variable to store the maximum of k elements traversed by the inner loop."
},
{
"code": null,
"e": 28158,
"s": 28098,
"text": "Find the maximum of k elements traversed by the inner loop."
},
{
"code": null,
"e": 28217,
"s": 28158,
"text": "Print the maximum element in every iteration of outer loop"
},
{
"code": null,
"e": 28234,
"s": 28217,
"text": "Implementation: "
},
{
"code": null,
"e": 28238,
"s": 28234,
"text": "C++"
},
{
"code": null,
"e": 28240,
"s": 28238,
"text": "C"
},
{
"code": null,
"e": 28245,
"s": 28240,
"text": "Java"
},
{
"code": null,
"e": 28253,
"s": 28245,
"text": "Python3"
},
{
"code": null,
"e": 28256,
"s": 28253,
"text": "C#"
},
{
"code": null,
"e": 28260,
"s": 28256,
"text": "PHP"
},
{
"code": null,
"e": 28271,
"s": 28260,
"text": "Javascript"
},
{
"code": "// C++ Program to find the maximum for// each and every contiguous subarray of size k.#include <bits/stdc++.h>using namespace std; // Method to find the maximum for each// and every contiguous subarray of size k.void printKMax(int arr[], int n, int k){ int j, max; for (int i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } cout << max << \" \"; }} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; printKMax(arr, n, k); return 0;} // This code is contributed by rathbhupendra",
"e": 28966,
"s": 28271,
"text": null
},
{
"code": "#include <stdio.h> void printKMax(int arr[], int n, int k){ int j, max; for (int i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } printf(\"%d \", max); }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; printKMax(arr, n, k); return 0;}",
"e": 29413,
"s": 28966,
"text": null
},
{
"code": "// Java Program to find the maximum// for each and every contiguous// subarray of size k. public class GFG{ // Method to find the maximum for // each and every contiguous // subarray of size k. static void printKMax(int arr[], int n, int k) { int j, max; for (int i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } System.out.print(max + \" \"); } } // Driver code public static void main(String args[]) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int k = 3; printKMax(arr, arr.length, k); }} // This code is contributed by Sumit Ghosh",
"e": 30163,
"s": 29413,
"text": null
},
{
"code": "# Python program to find the maximum for# each and every contiguous subarray of# size k # Method to find the maximum for each# and every contiguous subarray# of size kdef printMax(arr, n, k): max = 0 for i in range(n - k + 1): max = arr[i] for j in range(1, k): if arr[i + j] > max: max = arr[i + j] print(str(max) + \" \", end = \"\") # Driver methodif __name__==\"__main__\": arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] n = len(arr) k = 3 printMax(arr, n, k) # This code is contributed by Shiv Shankar",
"e": 30723,
"s": 30163,
"text": null
},
{
"code": "// C# program to find the maximum for// each and every contiguous subarray of// size kusing System;using System; class GFG { // Method to find the maximum for // each and every contiguous subarray // of size k. static void printKMax(int[] arr, int n, int k) { int j, max; for (int i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } Console.Write(max + \" \"); } } // Driver method public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int k = 3; printKMax(arr, arr.Length, k); }} // This Code is Contributed by Sam007",
"e": 31471,
"s": 30723,
"text": null
},
{
"code": "<?php// PHP program to find the maximum// for each and every contiguous// subarray of size k function printKMax($arr, $n, $k){ $j; $max; for ($i = 0; $i <= $n - $k; $i++) { $max = $arr[$i]; for ($j = 1; $j < $k; $j++) { if ($arr[$i + $j] > $max) $max = $arr[$i + $j]; } printf(\"%d \", $max); }} // Driver Code$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);$n = count($arr);$k = 3;printKMax($arr, $n, $k); // This Code is Contributed by anuj_67.?>",
"e": 31997,
"s": 31471,
"text": null
},
{
"code": "<script> // JavaScript Program to find the maximum for// each and every contiguous subarray of size k. // Method to find the maximum for each// and every contiguous subarray of size k.function printKMax(arr,n,k){ let j, max; for (let i = 0; i <= n - k; i++) { max = arr[i]; for (j = 1; j < k; j++) { if (arr[i + j] > max) max = arr[i + j]; } document.write( max + \" \"); }} // Driver code let arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; let n =arr.length; let k = 3; printKMax(arr, n, k); // This code contributed by gauravrajput1 </script>",
"e": 32623,
"s": 31997,
"text": null
},
{
"code": null,
"e": 32641,
"s": 32623,
"text": "3 4 5 6 7 8 9 10 "
},
{
"code": null,
"e": 32663,
"s": 32641,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 32863,
"s": 32663,
"text": "Time Complexity: O(N * K). The outer loop runs n-k+1 times and the inner loop runs k times for every iteration of outer loop. So time complexity is O((n-k+1)*k) which can also be written as O(N * K)."
},
{
"code": null,
"e": 32915,
"s": 32863,
"text": "Space Complexity: O(1). No extra space is required."
},
{
"code": null,
"e": 32993,
"s": 32915,
"text": "Method 2: This method uses the Self-Balancing BST to solve the given problem."
},
{
"code": null,
"e": 33522,
"s": 32993,
"text": "Approach: To find maximum among k elements of the subarray the previous method uses a loop traversing through the elements. To reduce that time the idea is to use an AVL tree which returns the maximum element in log n time. So, traverse through the array and keep k elements in the BST and print the maximum in every iteration. AVL tree is a suitable data structure as lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. "
},
{
"code": null,
"e": 33534,
"s": 33522,
"text": "Algorithm: "
},
{
"code": null,
"e": 33818,
"s": 33534,
"text": "Create a Self-balancing BST (AVL tree) to store and find the maximum element.Traverse through the array from start to end.Insert the element in the AVL tree.If the loop counter is greater than or equal to k then delete i-k th element from the BSTPrint the maximum element of the BST."
},
{
"code": null,
"e": 33896,
"s": 33818,
"text": "Create a Self-balancing BST (AVL tree) to store and find the maximum element."
},
{
"code": null,
"e": 33942,
"s": 33896,
"text": "Traverse through the array from start to end."
},
{
"code": null,
"e": 33978,
"s": 33942,
"text": "Insert the element in the AVL tree."
},
{
"code": null,
"e": 34068,
"s": 33978,
"text": "If the loop counter is greater than or equal to k then delete i-k th element from the BST"
},
{
"code": null,
"e": 34106,
"s": 34068,
"text": "Print the maximum element of the BST."
},
{
"code": null,
"e": 34123,
"s": 34106,
"text": "Implementation: "
},
{
"code": null,
"e": 34129,
"s": 34123,
"text": "C++14"
},
{
"code": null,
"e": 34134,
"s": 34129,
"text": "Java"
},
{
"code": null,
"e": 34142,
"s": 34134,
"text": "Python3"
},
{
"code": null,
"e": 34145,
"s": 34142,
"text": "C#"
},
{
"code": null,
"e": 34156,
"s": 34145,
"text": "Javascript"
},
{
"code": "// C++ program to delete a node from AVL Tree#include<bits/stdc++.h>using namespace std; // An AVL tree nodeclass Node{ public: int key; Node *left; Node *right; int height;}; // A utility function to get maximum// of two integersint max(int a, int b); // A utility function to get height// of the treeint height(Node *N){ if (N == NULL) return 0; return N->height;} // A utility function to get maximum// of two integersint max(int a, int b){ return (a > b)? a : b;} /* Helper function that allocates anew node with the given key andNULL left and right pointers. */Node* newNode(int key){ Node* node = new Node(); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially // added at leaf return(node);} // A utility function to right// rotate subtree rooted with y// See the diagram given above.Node *rightRotate(Node *y){ Node *x = y->left; Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x;} // A utility function to left// rotate subtree rooted with x// See the diagram given above.Node *leftRotate(Node *x){ Node *y = x->right; Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y;} // Get Balance factor of node Nint getBalance(Node *N){ if (N == NULL) return 0; return height(N->left) - height(N->right);} Node* insert(Node* node, int key){ /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys not allowed return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node;} /* Given a non-empty binary search tree,return the node with minimum key valuefound in that tree. Note that the entiretree does not need to be searched. */Node * minValueNode(Node* node){ Node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current;} // Recursive function to delete a node// with given key from subtree with// given root. It returns root of the// modified subtree.Node* deleteNode(Node* root, int key){ // STEP 1: PERFORM STANDARD BST DELETE if (root == NULL) return root; // If the key to be deleted is smaller // than the root's key, then it lies // in left subtree if ( key < root->key ) root->left = deleteNode(root->left, key); // If the key to be deleted is greater // than the root's key, then it lies // in right subtree else if( key > root->key ) root->right = deleteNode(root->right, key); // if key is same as root's key, then // This is the node to be deleted else { // node with only one child or no child if( (root->left == NULL) || (root->right == NULL) ) { Node *temp = root->left ? root->left : root->right; // No child case if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; // Copy the contents of // the non-empty child free(temp); } else { // node with two children: Get the inorder // successor (smallest in the right subtree) Node* temp = minValueNode(root->right); // Copy the inorder successor's // data to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } } // If the tree had only one node // then return if (root == NULL) return root; // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE root->height = 1 + max(height(root->left), height(root->right)); // STEP 3: GET THE BALANCE FACTOR OF // THIS NODE (to check whether this // node became unbalanced) int balance = getBalance(root); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && getBalance(root->left) >= 0) return rightRotate(root); // Left Right Case if (balance > 1 && getBalance(root->left) < 0) { root->left = leftRotate(root->left); return rightRotate(root); } // Right Right Case if (balance < -1 && getBalance(root->right) <= 0) return leftRotate(root); // Right Left Case if (balance < -1 && getBalance(root->right) > 0) { root->right = rightRotate(root->right); return leftRotate(root); } return root;} // A utility function to print preorder// traversal of the tree.// The function also prints height// of every nodevoid preOrder(Node *root){ if(root != NULL) { cout << root->key << \" \"; preOrder(root->left); preOrder(root->right); }} // Returns maximum value in a given // Binary Tree int findMax(Node* root) { // Base case if (root == NULL) return INT_MIN; // Return maximum of 3 values: // 1) Root's data 2) Max in Left Subtree // 3) Max in right subtree int res = root->key; int lres = findMax(root->left); int rres = findMax(root->right); if (lres > res) res = lres; if (rres > res) res = rres; return res; } // Method to find the maximum for each// and every contiguous subarray of size k.void printKMax(int arr[], int n, int k){ int c = 0,l=0; Node *root = NULL; //traverse the array ; for(int i=0; i<n; i++) { c++; //insert the element in BST root = insert(root, arr[i]); //size of subarray greater than k if(c > k) { root = deleteNode(root, arr[l++]); c--; } //size of subarray equal to k if(c == k) { cout<<findMax(root)<<\" \"; } }}// Driver codeint main(){ int arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, k = 4; int n = sizeof(arr) / sizeof(arr[0]); printKMax(arr, n, k); return 0;}",
"e": 41783,
"s": 34156,
"text": null
},
{
"code": "// JAVA program to delete a node from AVL Treeimport java.io.*;import java.util.*; class GFG { static ArrayList<Integer> findKMaxElement(int[] arr, int k, int n) { // creating the max heap ,to get max element always PriorityQueue<Integer> queue = new PriorityQueue<>( Collections.reverseOrder()); ArrayList<Integer> res = new ArrayList<>(); int i = 0; for (; i < k; i++) queue.add(arr[i]); // adding the maximum element among first k elements res.add(queue.peek()); // removing the first element of the array queue.remove(arr[0]); // iterarting for the next elements for (; i < n; i++) { // adding the new element in the window queue.add(arr[i]); // finding & adding the max element in the // current sliding window res.add(queue.peek()); // finally removing the first element from front // end of queue queue.remove(arr[i - k + 1]); } return res; // this code is Contributed by Pradeep Mondal P } // Driver Code public static void main(String[] args) { int arr[] = { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 }; int k = 4, n = arr.length; List<Integer> res = findKMaxElement(arr, k, n); for (int x : res) System.out.print(x + \" \"); }}",
"e": 43237,
"s": 41783,
"text": null
},
{
"code": "# Python code for the above approachdef findKMaxElement(arr, k, n): # creating the max heap ,to get max element always queue = [] res = [] i = 0 while(i<k): queue.append(arr[i]) i += 1 queue.sort(reverse=True) # adding the maximum element among first k elements res.append(queue[0]) # removing the first element of the array queue.remove(arr[0]) # iterarting for the next elements while(i<n): # adding the new element in the window queue.append(arr[i]) queue.sort(reverse=True) # finding & adding the max element in the # current sliding window res.append(queue[0]) # finally removing the first element from front # end of queue queue.remove(arr[i - k + 1]) i += 1 return res # Driver Codearr = [ 8, 5, 10, 7, 9, 4, 15, 12, 90, 13]k,n = 4,len(arr)res = findKMaxElement(arr, k, n)for x in res: print(x ,end = \" \") # This code is contributed by shinjanpatra",
"e": 44237,
"s": 43237,
"text": null
},
{
"code": "// C# program to delete a node from AVL Treeusing System;using System.Collections.Generic; public class GFG { static List<int> findKMaxElement(int[] arr, int k, int n) { // creating the max heap ,to get max element always List<int> queue = new List<int>(); List<int> res = new List<int>(); int i = 0; for (; i < k; i++) queue.Add(arr[i]); queue.Sort(); queue.Reverse(); // adding the maximum element among first k elements res.Add(queue[0]); // removing the first element of the array queue.Remove(arr[0]); // iterarting for the next elements for (; i < n; i++) { // adding the new element in the window queue.Add(arr[i]); queue.Sort(); queue.Reverse(); // finding & adding the max element in the // current sliding window res.Add(queue[0]); // finally removing the first element from front // end of queue queue.Remove(arr[i - k + 1]); } return res; // this code is Contributed by Pradeep Mondal P } // Driver Code public static void Main(String[] args) { int[] arr = { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 }; int k = 4, n = arr.Length; List<int> res = findKMaxElement(arr, k, n); foreach(int x in res) Console.Write(x + \" \"); }} // This code is contributed by umadevi9616",
"e": 45576,
"s": 44237,
"text": null
},
{
"code": "<script>// JAVAscript program to delete a node from AVL Tree function findKMaxElement(arr, k, n){ // creating the max heap ,to get max element always let queue = []; let res = []; let i = 0; for (; i < k; i++) queue.push(arr[i]); queue.sort(function(a,b){return b-a;}); // adding the maximum element among first k elements res.push(queue[0]); // removing the first element of the array queue.splice(arr[0],1); // iterarting for the next elements for (; i < n; i++) { // adding the new element in the window queue.push(arr[i]); queue.sort(function(a,b){return b-a;}); // finding & adding the max element in the // current sliding window res.push(queue[0]); // finally removing the first element from front // end of queue queue.splice(arr[i - k + 1],1); } return res; // this code is Contributed by Pradeep Mondal P} // Driver Codelet arr = [ 8, 5, 10, 7, 9, 4, 15, 12, 90, 13];let k = 4, n = arr.length;let res = findKMaxElement(arr, k, n);for (let x of res) document.write(x + \" \"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 46907,
"s": 45576,
"text": null
},
{
"code": null,
"e": 46929,
"s": 46907,
"text": "10 10 10 15 15 90 90 "
},
{
"code": null,
"e": 46952,
"s": 46929,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 47093,
"s": 46952,
"text": "Time Complexity: O(N * Log k). Insertion, deletion and search takes log k time in a AVL tree. So the overall time Complexity is O(N * log k)"
},
{
"code": null,
"e": 47174,
"s": 47093,
"text": "Space Complexity: O(k). The space required to store k elements in a BST is O(k)."
},
{
"code": null,
"e": 47234,
"s": 47174,
"text": "Method 3: This method uses Deque to solve the above problem"
},
{
"code": null,
"e": 47785,
"s": 47234,
"text": "Approach: Create a Deque, Qi of capacity k, that stores only useful elements of current window of k elements. An element is useful if it is in current window and is greater than all other elements on right side of it in current window. Process all array elements one by one and maintain Qi to contain useful elements of current window and these useful elements are maintained in sorted order. The element at front of the Qi is the largest and element at rear/back of Qi is the smallest of current window. Thanks to Aashish for suggesting this method."
},
{
"code": null,
"e": 47817,
"s": 47785,
"text": "Dry run of the above approach: "
},
{
"code": null,
"e": 47830,
"s": 47817,
"text": "Algorithm: "
},
{
"code": null,
"e": 48777,
"s": 47830,
"text": "Create a deque to store k elements.Run a loop and insert first k elements in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque, until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque.Now, run a loop from k to end of the array.Print the front element of the deque.Remove the element from the front of the queue if they are out of the current window.Insert the next element in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque, until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque.Print the maximum element of the last window."
},
{
"code": null,
"e": 48813,
"s": 48777,
"text": "Create a deque to store k elements."
},
{
"code": null,
"e": 49172,
"s": 48813,
"text": "Run a loop and insert first k elements in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque, until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque."
},
{
"code": null,
"e": 49216,
"s": 49172,
"text": "Now, run a loop from k to end of the array."
},
{
"code": null,
"e": 49254,
"s": 49216,
"text": "Print the front element of the deque."
},
{
"code": null,
"e": 49340,
"s": 49254,
"text": "Remove the element from the front of the queue if they are out of the current window."
},
{
"code": null,
"e": 49684,
"s": 49340,
"text": "Insert the next element in the deque. Before inserting the element, check if the element at the back of the queue is smaller than the current element, if it is so remove the element from the back of the deque, until all elements left in the deque are greater than the current element. Then insert the current element, at the back of the deque."
},
{
"code": null,
"e": 49730,
"s": 49684,
"text": "Print the maximum element of the last window."
},
{
"code": null,
"e": 49747,
"s": 49730,
"text": "Implementation: "
},
{
"code": null,
"e": 49751,
"s": 49747,
"text": "C++"
},
{
"code": null,
"e": 49756,
"s": 49751,
"text": "Java"
},
{
"code": null,
"e": 49764,
"s": 49756,
"text": "Python3"
},
{
"code": null,
"e": 49767,
"s": 49764,
"text": "C#"
},
{
"code": "// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // A Dequeue (Double ended queue) based// method for printing maximum element of// all subarrays of size kvoid printKMax(int arr[], int n, int k){ // Create a Double Ended Queue, // Qi that will store indexes // of array elements // The queue will store indexes // of useful elements in every // window and it will // maintain decreasing order of // values from front to rear in Qi, i.e., // arr[Qi.front[]] to arr[Qi.rear()] // are sorted in decreasing order std::deque<int> Qi(k); /* Process first k (or first window) elements of array */ int i; for (i = 0; i < k; ++i) { // For every element, the previous // smaller elements are useless so // remove them from Qi while ((!Qi.empty()) && arr[i] >= arr[Qi.back()]) // Remove from rear Qi.pop_back(); // Add new element at rear of queue Qi.push_back(i); } // Process rest of the elements, // i.e., from arr[k] to arr[n-1] for (; i < n; ++i) { // The element at the front of // the queue is the largest element of // previous window, so print it cout << arr[Qi.front()] << \" \"; // Remove the elements which // are out of this window while ((!Qi.empty()) && Qi.front() <= i - k) // Remove from front of queue Qi.pop_front(); // Remove all elements // smaller than the currently // being added element (remove // useless elements) while ((!Qi.empty()) && arr[i] >= arr[Qi.back()]) Qi.pop_back(); // Add current element at the rear of Qi Qi.push_back(i); } // Print the maximum element // of last window cout << arr[Qi.front()];} // Driver codeint main(){ int arr[] = { 12, 1, 78, 90, 57, 89, 56 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; printKMax(arr, n, k); return 0;}",
"e": 51905,
"s": 49767,
"text": null
},
{
"code": "// Java Program to find the maximum for// each and every contiguous subarray of size k.import java.util.Deque;import java.util.LinkedList; public class SlidingWindow{ // A Dequeue (Double ended queue) // based method for printing // maximum element of // all subarrays of size k static void printMax(int arr[], int n, int k) { // Create a Double Ended Queue, Qi // that will store indexes of array elements // The queue will store indexes of // useful elements in every window and it will // maintain decreasing order of values // from front to rear in Qi, i.e., // arr[Qi.front[]] to arr[Qi.rear()] // are sorted in decreasing order Deque<Integer> Qi = new LinkedList<Integer>(); /* Process first k (or first window) elements of array */ int i; for (i = 0; i < k; ++i) { // For every element, the previous // smaller elements are useless so // remove them from Qi while (!Qi.isEmpty() && arr[i] >= arr[Qi.peekLast()]) // Remove from rear Qi.removeLast(); // Add new element at rear of queue Qi.addLast(i); } // Process rest of the elements, // i.e., from arr[k] to arr[n-1] for (; i < n; ++i) { // The element at the front of the // queue is the largest element of // previous window, so print it System.out.print(arr[Qi.peek()] + \" \"); // Remove the elements which // are out of this window while ((!Qi.isEmpty()) && Qi.peek() <= i - k) Qi.removeFirst(); // Remove all elements smaller // than the currently // being added element (remove // useless elements) while ((!Qi.isEmpty()) && arr[i] >= arr[Qi.peekLast()]) Qi.removeLast(); // Add current element at the rear of Qi Qi.addLast(i); } // Print the maximum element of last window System.out.print(arr[Qi.peek()]); } // Driver code public static void main(String[] args) { int arr[] = { 12, 1, 78, 90, 57, 89, 56 }; int k = 3; printMax(arr, arr.length, k); }}// This code is contributed by Sumit Ghosh",
"e": 54404,
"s": 51905,
"text": null
},
{
"code": "# Python program to find the maximum for# each and every contiguous subarray of# size k from collections import deque # A Deque (Double ended queue) based# method for printing maximum element# of all subarrays of size kdef printMax(arr, n, k): \"\"\" Create a Double Ended Queue, Qi that will store indexes of array elements. The queue will store indexes of useful elements in every window and it will maintain decreasing order of values from front to rear in Qi, i.e., arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order\"\"\" Qi = deque() # Process first k (or first window) # elements of array for i in range(k): # For every element, the previous # smaller elements are useless # so remove them from Qi while Qi and arr[i] >= arr[Qi[-1]] : Qi.pop() # Add new element at rear of queue Qi.append(i); # Process rest of the elements, i.e. # from arr[k] to arr[n-1] for i in range(k, n): # The element at the front of the # queue is the largest element of # previous window, so print it print(str(arr[Qi[0]]) + \" \", end = \"\") # Remove the elements which are # out of this window while Qi and Qi[0] <= i-k: # remove from front of deque Qi.popleft() # Remove all elements smaller than # the currently being added element # (Remove useless elements) while Qi and arr[i] >= arr[Qi[-1]] : Qi.pop() # Add current element at the rear of Qi Qi.append(i) # Print the maximum element of last window print(str(arr[Qi[0]])) # Driver codeif __name__==\"__main__\": arr = [12, 1, 78, 90, 57, 89, 56] k = 3 printMax(arr, len(arr), k) # This code is contributed by Shiv Shankar",
"e": 56303,
"s": 54404,
"text": null
},
{
"code": "// C# Program to find the maximum for each// and every contiguous subarray of size k.using System;using System.Collections.Generic; public class SlidingWindow{ // A Dequeue (Double ended queue) based // method for printing maximum element of // all subarrays of size k static void printMax(int []arr, int n, int k) { // Create a Double Ended Queue, Qi that // will store indexes of array elements // The queue will store indexes of useful // elements in every window and it will // maintain decreasing order of values // from front to rear in Qi, i.e., // arr[Qi.front[]] to arr[Qi.rear()] // are sorted in decreasing order List<int> Qi = new List<int>(); /* Process first k (or first window) elements of array */ int i; for (i = 0; i < k; ++i) { // For every element, the previous // smaller elements are useless so // remove them from Qi while (Qi.Count != 0 && arr[i] >= arr[Qi[Qi.Count-1]]) // Remove from rear Qi.RemoveAt(Qi.Count-1); // Add new element at rear of queue Qi.Insert(Qi.Count, i); } // Process rest of the elements, // i.e., from arr[k] to arr[n-1] for (; i < n; ++i) { // The element at the front of // the queue is the largest element of // previous window, so print it Console.Write(arr[Qi[0]] + \" \"); // Remove the elements which are // out of this window while ((Qi.Count != 0) && Qi[0] <= i - k) Qi.RemoveAt(0); // Remove all elements smaller // than the currently // being added element (remove // useless elements) while ((Qi.Count != 0) && arr[i] >= arr[Qi[Qi.Count - 1]]) Qi.RemoveAt(Qi.Count - 1); // Add current element at the rear of Qi Qi.Insert(Qi.Count, i); } // Print the maximum element of last window Console.Write(arr[Qi[0]]); } // Driver code public static void Main(String[] args) { int []arr = { 12, 1, 78, 90, 57, 89, 56 }; int k = 3; printMax(arr, arr.Length, k); }} // This code has been contributed by 29AjayKumar",
"e": 58727,
"s": 56303,
"text": null
},
{
"code": null,
"e": 58742,
"s": 58727,
"text": "78 90 90 90 89"
},
{
"code": null,
"e": 58764,
"s": 58742,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 58942,
"s": 58764,
"text": "Time Complexity: O(n). It seems more than O(n) at first look. It can be observed that every element of array is added and removed at most once. So there are total 2n operations."
},
{
"code": null,
"e": 59013,
"s": 58942,
"text": "Auxiliary Space: O(k). Elements stored in the dequeue take O(k) space."
},
{
"code": null,
"e": 59116,
"s": 59013,
"text": "Below is an extension of this problem: Sum of minimum and maximum elements of all subarrays of size k."
},
{
"code": null,
"e": 59192,
"s": 59116,
"text": "Method 4: This method is modification in queue implementation of two stack:"
},
{
"code": null,
"e": 59204,
"s": 59192,
"text": "Algorithm :"
},
{
"code": null,
"e": 59343,
"s": 59204,
"text": "While pushing the element, we constantly push in stack 2. The maximum of stack 2 will always be the maximum of the top element of stack 2."
},
{
"code": null,
"e": 59495,
"s": 59343,
"text": "While popping, we will always pop from stack 1, and if stack 1 is empty then we shall push every element of stack 2 to stack 1 and updating the maximum"
},
{
"code": null,
"e": 59560,
"s": 59495,
"text": "The above two-step are followed in queue implementation of stack"
},
{
"code": null,
"e": 59723,
"s": 59560,
"text": "Now to find the maximum of the whole queue (Same as both stack), we will take the top element of both stack maximum; hence this is the maximum of the whole queue."
},
{
"code": null,
"e": 59788,
"s": 59723,
"text": "Now, this technique can be used to slide window and get maximum."
},
{
"code": null,
"e": 59898,
"s": 59788,
"text": "while sliding window by 1 index delete the last one, insert the new one and then take a maximum of both stack"
},
{
"code": null,
"e": 59913,
"s": 59898,
"text": "Implementation"
},
{
"code": null,
"e": 59917,
"s": 59913,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; struct node{ int data; int maximum;}; // it is a modification in the way of implementation of queue using two stack void insert(stack<node> &s2 , int val){ //inserting the element in s2 node other; other.data=val; if(s2.empty()) other.maximum=val; else { node front=s2.top(); //updating maximum in that stack push it other.maximum=max(val,front.maximum); } s2.push(other); return;} void delete(stack<node> &s1 ,stack<node> &s2 ){ //if s1 is not empty directly pop //else we have to push all element from s2 and thatn pop from s1 //while pushing from s2 to s1 update maximum variable in s1 if(s1.size()) s1.pop(); else { while(!s2.empty()) { node val=s2.top(); insert(s1,val.data); s2.pop(); } s1.pop(); }} int get_max(stack<node> &s1 ,stack<node> &s2 ){ // the maximum of both stack will be the maximum of overall window int ans=-1; if(s1.size()) ans=max(ans,s1.top().maximum); if(s2.size()) ans=max(ans,s2.top().maximum); return ans;} vector<int> slidingMaximum(int a[], int b,int n) { //s2 for push //s1 for pop vector<int>ans; stack<node>s1,s2; //shifting all value except the last one if first window for(int i=0;i<b-1;i++) insert(s2,a[i]); for(int i=0;i<=n-b;i++) { //removing the last element of previous window as window has shift by one if(i-1>=0) delete(s1,s2); //adding the new element to the window as the window is shift by one insert(s2,a[i+b-1]); ans.push_back(get_max(s1,s2)); } return ans;} int main(){ int arr[] = { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; vector<int> ans=slidingMaximum(arr,k,n); for(auto x:ans) cout<<x<<\" \"; return 0;}",
"e": 61834,
"s": 59917,
"text": null
},
{
"code": null,
"e": 61850,
"s": 61834,
"text": "78 90 90 90 89 "
},
{
"code": null,
"e": 61872,
"s": 61850,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 61992,
"s": 61872,
"text": "Time Complexity: O(N): This is because every element will just two types push and pop; hence time complexity is linear."
},
{
"code": null,
"e": 62172,
"s": 61992,
"text": "Space Complexity: O(K): This is because at any moment, the sum of stack size of both stacks will exactly equal to K, As every time we pop exactly one element and push exactly One."
},
{
"code": null,
"e": 62236,
"s": 62172,
"text": "Method 5: This method uses Max-Heap to solve the above problem."
},
{
"code": null,
"e": 62847,
"s": 62236,
"text": "Approach: In the above-mentioned methods, one of them was using AVL tree. This approach is very similar to that approach. The difference is that instead of using the AVL tree, Max-Heap will be used in this approach. The elements of the current window will be stored in the Max-Heap and the maximum element or the root will be printed in each iteration. Max-heap is a suitable data structure as it provides constant-time retrieval and logarithmic time removal of both the minimum and maximum elements in it, i.e. it takes constant time to find the maximum element, and insertion and deletion takes log n time. "
},
{
"code": null,
"e": 62858,
"s": 62847,
"text": "Algorithm:"
},
{
"code": null,
"e": 63178,
"s": 62858,
"text": "Pick first k elements and create a max heap of size k.Perform heapify and print the root element.Store the next and last element from the arrayRun a loop from k – 1 to n Replace the value of element which is got out of the window with new element which came inside the window.Perform heapify.Print the root of the Heap."
},
{
"code": null,
"e": 63233,
"s": 63178,
"text": "Pick first k elements and create a max heap of size k."
},
{
"code": null,
"e": 63277,
"s": 63233,
"text": "Perform heapify and print the root element."
},
{
"code": null,
"e": 63324,
"s": 63277,
"text": "Store the next and last element from the array"
},
{
"code": null,
"e": 63501,
"s": 63324,
"text": "Run a loop from k – 1 to n Replace the value of element which is got out of the window with new element which came inside the window.Perform heapify.Print the root of the Heap."
},
{
"code": null,
"e": 63608,
"s": 63501,
"text": "Replace the value of element which is got out of the window with new element which came inside the window."
},
{
"code": null,
"e": 63625,
"s": 63608,
"text": "Perform heapify."
},
{
"code": null,
"e": 63653,
"s": 63625,
"text": "Print the root of the Heap."
},
{
"code": null,
"e": 63658,
"s": 63653,
"text": "vt_m"
},
{
"code": null,
"e": 63664,
"s": 63658,
"text": "Roy19"
},
{
"code": null,
"e": 63682,
"s": 63664,
"text": "MuninderJeetSingh"
},
{
"code": null,
"e": 63694,
"s": 63682,
"text": "29AjayKumar"
},
{
"code": null,
"e": 63705,
"s": 63694,
"text": "nidhi_biet"
},
{
"code": null,
"e": 63719,
"s": 63705,
"text": "rathbhupendra"
},
{
"code": null,
"e": 63730,
"s": 63719,
"text": "andrew1234"
},
{
"code": null,
"e": 63744,
"s": 63730,
"text": "agrwl.harsh16"
},
{
"code": null,
"e": 63753,
"s": 63744,
"text": "hsnice16"
},
{
"code": null,
"e": 63768,
"s": 63753,
"text": "pradeepmondalp"
},
{
"code": null,
"e": 63781,
"s": 63768,
"text": "single__loop"
},
{
"code": null,
"e": 63795,
"s": 63781,
"text": "GauravRajput1"
},
{
"code": null,
"e": 63804,
"s": 63795,
"text": "ankitkay"
},
{
"code": null,
"e": 63818,
"s": 63804,
"text": "happy2000jain"
},
{
"code": null,
"e": 63832,
"s": 63818,
"text": "architgwl2000"
},
{
"code": null,
"e": 63853,
"s": 63832,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 63865,
"s": 63853,
"text": "anikakapoor"
},
{
"code": null,
"e": 63876,
"s": 63865,
"text": "krishna_97"
},
{
"code": null,
"e": 63893,
"s": 63876,
"text": "surinderdawra388"
},
{
"code": null,
"e": 63905,
"s": 63893,
"text": "prophet1999"
},
{
"code": null,
"e": 63917,
"s": 63905,
"text": "umadevi9616"
},
{
"code": null,
"e": 63927,
"s": 63917,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 63942,
"s": 63927,
"text": "menonkartikeya"
},
{
"code": null,
"e": 63955,
"s": 63942,
"text": "simmytarika5"
},
{
"code": null,
"e": 63968,
"s": 63955,
"text": "shinjanpatra"
},
{
"code": null,
"e": 63975,
"s": 63968,
"text": "Amazon"
},
{
"code": null,
"e": 63983,
"s": 63975,
"text": "Directi"
},
{
"code": null,
"e": 63992,
"s": 63983,
"text": "Flipkart"
},
{
"code": null,
"e": 64001,
"s": 63992,
"text": "SAP Labs"
},
{
"code": null,
"e": 64016,
"s": 64001,
"text": "sliding-window"
},
{
"code": null,
"e": 64021,
"s": 64016,
"text": "Zoho"
},
{
"code": null,
"e": 64028,
"s": 64021,
"text": "Arrays"
},
{
"code": null,
"e": 64033,
"s": 64028,
"text": "Heap"
},
{
"code": null,
"e": 64039,
"s": 64033,
"text": "Queue"
},
{
"code": null,
"e": 64044,
"s": 64039,
"text": "Zoho"
},
{
"code": null,
"e": 64053,
"s": 64044,
"text": "Flipkart"
},
{
"code": null,
"e": 64060,
"s": 64053,
"text": "Amazon"
},
{
"code": null,
"e": 64068,
"s": 64060,
"text": "Directi"
},
{
"code": null,
"e": 64077,
"s": 64068,
"text": "SAP Labs"
},
{
"code": null,
"e": 64092,
"s": 64077,
"text": "sliding-window"
},
{
"code": null,
"e": 64099,
"s": 64092,
"text": "Arrays"
},
{
"code": null,
"e": 64105,
"s": 64099,
"text": "Queue"
},
{
"code": null,
"e": 64110,
"s": 64105,
"text": "Heap"
},
{
"code": null,
"e": 64208,
"s": 64110,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 64231,
"s": 64208,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 64263,
"s": 64231,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 64284,
"s": 64263,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 64329,
"s": 64284,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 64377,
"s": 64329,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 64386,
"s": 64377,
"text": "HeapSort"
},
{
"code": null,
"e": 64398,
"s": 64386,
"text": "Binary Heap"
},
{
"code": null,
"e": 64429,
"s": 64398,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 64485,
"s": 64429,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
]
|
Queries for decimal values of subarrays of a binary array - GeeksforGeeks | 23 Aug, 2021
Given a binary array arr[], we to find the number represented by the subarray a[l..r]. There are multiple such queries.Examples:
Input : arr[] = {1, 0, 1, 0, 1, 1};
l = 2, r = 4
l = 4, r = 5
Output : 5
3
Subarray 2 to 4 is 101 which is 5 in decimal.
Subarray 4 to 5 is 11 which is 3 in decimal.
Input : arr[] = {1, 1, 1}
l = 0, r = 2
l = 1, r = 2
Output : 7
3
A Simple Solution is to compute decimal value for every given range using simple binary to decimal conversion. Here each query takes O(len) time where len is length of range.An Efficient Solution is to do per-computations, so that queries can be answered in O(1) time. The number represented by subarray arr[l..r] is arr[l]*+ arr[l+1]*..... + arr[r]*
Make an array pre[] of same size as of given array where pre[i] stores the sum of arr[j]*where j includes each value from i to n-1.The number represented by subarray arr[l..r] will be equal to (pre[l] – pre[r+1])/.pre[l] – pre[r+1] is equal to arr[l]*+ arr[l+1]*+......arr[r]*. So if we divide it by , we get the required answer
Make an array pre[] of same size as of given array where pre[i] stores the sum of arr[j]*where j includes each value from i to n-1.
The number represented by subarray arr[l..r] will be equal to (pre[l] – pre[r+1])/.pre[l] – pre[r+1] is equal to arr[l]*+ arr[l+1]*+......arr[r]*. So if we divide it by , we get the required answer
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of finding number// represented by binary subarray#include <bits/stdc++.h>using namespace std; // Fills pre[]void precompute(int arr[], int n, int pre[]){ memset(pre, 0, n * sizeof(int)); pre[n - 1] = arr[n - 1] * pow(2, 0); for (int i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i));} // returns the number represented by a binary// subarray l to rint decimalOfSubarr(int arr[], int l, int r, int n, int pre[]){ // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r));} // Driver Functionint main(){ int arr[] = { 1, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int pre[n]; precompute(arr, n, pre); cout << decimalOfSubarr(arr, 2, 4, n, pre) << endl; cout << decimalOfSubarr(arr, 4, 5, n, pre) << endl; return 0;}
// Java implementation of finding number// represented by binary subarrayimport java.util.Arrays; class GFG { // Fills pre[] static void precompute(int arr[], int n, int pre[]) { Arrays.fill(pre, 0); pre[n - 1] = arr[n - 1] * (int)(Math.pow(2, 0)); for (int i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i)); } // returns the number represented by a binary // subarray l to r static int decimalOfSubarr(int arr[], int l, int r, int n, int pre[]) { // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r)); } // Driver code public static void main(String[] args) { int arr[] = { 1, 0, 1, 0, 1, 1 }; int n = arr.length; int pre[] = new int[n]; precompute(arr, n, pre); System.out.println(decimalOfSubarr(arr, 2, 4, n, pre)); System.out.println(decimalOfSubarr(arr, 4, 5, n, pre)); }} // This code is contributed by Anant Agarwal.
# implementation of finding number# represented by binary subarrayfrom math import pow # Fills pre[]def precompute(arr, n, pre): pre[n - 1] = arr[n - 1] * pow(2, 0) i = n - 2 while(i >= 0): pre[i] = (pre[i + 1] + arr[i] * (1 << (n - 1 - i))) i -= 1 # returns the number represented by# a binary subarray l to rdef decimalOfSubarr(arr, l, r, n, pre): # if r is equal to n-1 r+1 does not exist if (r != n - 1): return ((pre[l] - pre[r + 1]) / (1 << (n - 1 - r))) return pre[l] / (1 << (n - 1 - r)) # Driver Codeif __name__ == '__main__': arr = [1, 0, 1, 0, 1, 1] n = len(arr) pre = [0 for i in range(n)] precompute(arr, n, pre) print(int(decimalOfSubarr(arr, 2, 4, n, pre))) print(int(decimalOfSubarr(arr, 4, 5, n, pre))) # This code is contributed by# Surendra_Gangwar
// C# implementation of finding number// represented by binary subarrayusing System; class GFG { // Fills pre[] static void precompute(int[] arr, int n, int[] pre) { for (int i = 0; i < n; i++) pre[i] = 0; pre[n - 1] = arr[n - 1] * (int)(Math.Pow(2, 0)); for (int i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i)); } // returns the number represented by // a binary subarray l to r static int decimalOfSubarr(int[] arr, int l, int r, int n, int[] pre) { // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r)); } // Driver code public static void Main() { int[] arr = { 1, 0, 1, 0, 1, 1 }; int n = arr.Length; int[] pre = new int[n]; precompute(arr, n, pre); Console.WriteLine(decimalOfSubarr(arr, 2, 4, n, pre)); Console.WriteLine(decimalOfSubarr(arr, 4, 5, n, pre)); }} // This code is contributed by vt_m.
<?php// PHP implementation of finding number// represented by binary subarray // Fills pre[]function precompute(&$arr, $n, &$pre){ $pre[$n - 1] = $arr[$n - 1] * pow(2, 0); for ($i = $n - 2; $i >= 0; $i--) $pre[$i] = $pre[$i + 1] + $arr[$i] * (1 << ($n - 1 - $i));} // returns the number represented by// a binary subarray l to rfunction decimalOfSubarr(&$arr, $l, $r, $n, &$pre){ // if r is equal to n-1 r+1 does not exist if ($r != $n - 1) return ($pre[$l] - $pre[$r + 1]) / (1 << ($n - 1 - $r)); return $pre[$l] / (1 << ($n - 1 - $r));} // Driver Code$arr = array(1, 0, 1, 0, 1, 1 );$n = sizeof($arr); $pre = array_fill(0, $n, NULL);precompute($arr, $n, $pre);echo decimalOfSubarr($arr, 2, 4, $n, $pre) . "\n";echo decimalOfSubarr($arr, 4, 5, $n, $pre) . "\n"; // This code is contributed by ita_c?>
<script> // Javascript implementation of finding number// represented by binary subarray // Fills pre[]function precompute(arr, n, pre){ for (let i = 0; i < n; i++) pre[i] = 0; pre[n - 1] = arr[n - 1] * (Math.pow(2, 0)); for (let i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i));} // returns the number represented by// a binary subarray l to rfunction decimalOfSubarr(arr, l, r,n, pre){ // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r));} // Driver code let arr = [1, 0, 1, 0, 1, 1];let n = arr.length; let pre = new Array(n)precompute(arr, n, pre); document.write(decimalOfSubarr(arr,2, 4, n, pre)+"<br>"); document.write(decimalOfSubarr(arr, 4, 5, n, pre)); </script>
Output:
5
3
This article is contributed by Ayush Jha. 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
SURENDRA_GANGWAR
ukasp
mohit kumar 29
sweetyty
array-range-queries
binary-representation
binary-string
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array | [
{
"code": null,
"e": 26527,
"s": 26499,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 26658,
"s": 26527,
"text": "Given a binary array arr[], we to find the number represented by the subarray a[l..r]. There are multiple such queries.Examples: "
},
{
"code": null,
"e": 26944,
"s": 26658,
"text": "Input : arr[] = {1, 0, 1, 0, 1, 1};\n l = 2, r = 4\n l = 4, r = 5\nOutput : 5\n 3 \nSubarray 2 to 4 is 101 which is 5 in decimal.\nSubarray 4 to 5 is 11 which is 3 in decimal.\n\nInput : arr[] = {1, 1, 1}\n l = 0, r = 2\n l = 1, r = 2\nOutput : 7\n 3"
},
{
"code": null,
"e": 27298,
"s": 26946,
"text": "A Simple Solution is to compute decimal value for every given range using simple binary to decimal conversion. Here each query takes O(len) time where len is length of range.An Efficient Solution is to do per-computations, so that queries can be answered in O(1) time. The number represented by subarray arr[l..r] is arr[l]*+ arr[l+1]*..... + arr[r]* "
},
{
"code": null,
"e": 27627,
"s": 27298,
"text": "Make an array pre[] of same size as of given array where pre[i] stores the sum of arr[j]*where j includes each value from i to n-1.The number represented by subarray arr[l..r] will be equal to (pre[l] – pre[r+1])/.pre[l] – pre[r+1] is equal to arr[l]*+ arr[l+1]*+......arr[r]*. So if we divide it by , we get the required answer"
},
{
"code": null,
"e": 27759,
"s": 27627,
"text": "Make an array pre[] of same size as of given array where pre[i] stores the sum of arr[j]*where j includes each value from i to n-1."
},
{
"code": null,
"e": 27957,
"s": 27759,
"text": "The number represented by subarray arr[l..r] will be equal to (pre[l] – pre[r+1])/.pre[l] – pre[r+1] is equal to arr[l]*+ arr[l+1]*+......arr[r]*. So if we divide it by , we get the required answer"
},
{
"code": null,
"e": 27963,
"s": 27959,
"text": "C++"
},
{
"code": null,
"e": 27968,
"s": 27963,
"text": "Java"
},
{
"code": null,
"e": 27976,
"s": 27968,
"text": "Python3"
},
{
"code": null,
"e": 27979,
"s": 27976,
"text": "C#"
},
{
"code": null,
"e": 27983,
"s": 27979,
"text": "PHP"
},
{
"code": null,
"e": 27994,
"s": 27983,
"text": "Javascript"
},
{
"code": "// C++ implementation of finding number// represented by binary subarray#include <bits/stdc++.h>using namespace std; // Fills pre[]void precompute(int arr[], int n, int pre[]){ memset(pre, 0, n * sizeof(int)); pre[n - 1] = arr[n - 1] * pow(2, 0); for (int i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i));} // returns the number represented by a binary// subarray l to rint decimalOfSubarr(int arr[], int l, int r, int n, int pre[]){ // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r));} // Driver Functionint main(){ int arr[] = { 1, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int pre[n]; precompute(arr, n, pre); cout << decimalOfSubarr(arr, 2, 4, n, pre) << endl; cout << decimalOfSubarr(arr, 4, 5, n, pre) << endl; return 0;}",
"e": 28928,
"s": 27994,
"text": null
},
{
"code": "// Java implementation of finding number// represented by binary subarrayimport java.util.Arrays; class GFG { // Fills pre[] static void precompute(int arr[], int n, int pre[]) { Arrays.fill(pre, 0); pre[n - 1] = arr[n - 1] * (int)(Math.pow(2, 0)); for (int i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i)); } // returns the number represented by a binary // subarray l to r static int decimalOfSubarr(int arr[], int l, int r, int n, int pre[]) { // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r)); } // Driver code public static void main(String[] args) { int arr[] = { 1, 0, 1, 0, 1, 1 }; int n = arr.length; int pre[] = new int[n]; precompute(arr, n, pre); System.out.println(decimalOfSubarr(arr, 2, 4, n, pre)); System.out.println(decimalOfSubarr(arr, 4, 5, n, pre)); }} // This code is contributed by Anant Agarwal.",
"e": 30136,
"s": 28928,
"text": null
},
{
"code": "# implementation of finding number# represented by binary subarrayfrom math import pow # Fills pre[]def precompute(arr, n, pre): pre[n - 1] = arr[n - 1] * pow(2, 0) i = n - 2 while(i >= 0): pre[i] = (pre[i + 1] + arr[i] * (1 << (n - 1 - i))) i -= 1 # returns the number represented by# a binary subarray l to rdef decimalOfSubarr(arr, l, r, n, pre): # if r is equal to n-1 r+1 does not exist if (r != n - 1): return ((pre[l] - pre[r + 1]) / (1 << (n - 1 - r))) return pre[l] / (1 << (n - 1 - r)) # Driver Codeif __name__ == '__main__': arr = [1, 0, 1, 0, 1, 1] n = len(arr) pre = [0 for i in range(n)] precompute(arr, n, pre) print(int(decimalOfSubarr(arr, 2, 4, n, pre))) print(int(decimalOfSubarr(arr, 4, 5, n, pre))) # This code is contributed by# Surendra_Gangwar",
"e": 31004,
"s": 30136,
"text": null
},
{
"code": "// C# implementation of finding number// represented by binary subarrayusing System; class GFG { // Fills pre[] static void precompute(int[] arr, int n, int[] pre) { for (int i = 0; i < n; i++) pre[i] = 0; pre[n - 1] = arr[n - 1] * (int)(Math.Pow(2, 0)); for (int i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i)); } // returns the number represented by // a binary subarray l to r static int decimalOfSubarr(int[] arr, int l, int r, int n, int[] pre) { // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r)); } // Driver code public static void Main() { int[] arr = { 1, 0, 1, 0, 1, 1 }; int n = arr.Length; int[] pre = new int[n]; precompute(arr, n, pre); Console.WriteLine(decimalOfSubarr(arr, 2, 4, n, pre)); Console.WriteLine(decimalOfSubarr(arr, 4, 5, n, pre)); }} // This code is contributed by vt_m.",
"e": 32205,
"s": 31004,
"text": null
},
{
"code": "<?php// PHP implementation of finding number// represented by binary subarray // Fills pre[]function precompute(&$arr, $n, &$pre){ $pre[$n - 1] = $arr[$n - 1] * pow(2, 0); for ($i = $n - 2; $i >= 0; $i--) $pre[$i] = $pre[$i + 1] + $arr[$i] * (1 << ($n - 1 - $i));} // returns the number represented by// a binary subarray l to rfunction decimalOfSubarr(&$arr, $l, $r, $n, &$pre){ // if r is equal to n-1 r+1 does not exist if ($r != $n - 1) return ($pre[$l] - $pre[$r + 1]) / (1 << ($n - 1 - $r)); return $pre[$l] / (1 << ($n - 1 - $r));} // Driver Code$arr = array(1, 0, 1, 0, 1, 1 );$n = sizeof($arr); $pre = array_fill(0, $n, NULL);precompute($arr, $n, $pre);echo decimalOfSubarr($arr, 2, 4, $n, $pre) . \"\\n\";echo decimalOfSubarr($arr, 4, 5, $n, $pre) . \"\\n\"; // This code is contributed by ita_c?>",
"e": 33082,
"s": 32205,
"text": null
},
{
"code": "<script> // Javascript implementation of finding number// represented by binary subarray // Fills pre[]function precompute(arr, n, pre){ for (let i = 0; i < n; i++) pre[i] = 0; pre[n - 1] = arr[n - 1] * (Math.pow(2, 0)); for (let i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i));} // returns the number represented by// a binary subarray l to rfunction decimalOfSubarr(arr, l, r,n, pre){ // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r));} // Driver code let arr = [1, 0, 1, 0, 1, 1];let n = arr.length; let pre = new Array(n)precompute(arr, n, pre); document.write(decimalOfSubarr(arr,2, 4, n, pre)+\"<br>\"); document.write(decimalOfSubarr(arr, 4, 5, n, pre)); </script>",
"e": 33931,
"s": 33082,
"text": null
},
{
"code": null,
"e": 33940,
"s": 33931,
"text": "Output: "
},
{
"code": null,
"e": 33944,
"s": 33940,
"text": "5\n3"
},
{
"code": null,
"e": 34362,
"s": 33944,
"text": "This article is contributed by Ayush Jha. 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": 34367,
"s": 34362,
"text": "vt_m"
},
{
"code": null,
"e": 34384,
"s": 34367,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 34390,
"s": 34384,
"text": "ukasp"
},
{
"code": null,
"e": 34405,
"s": 34390,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34414,
"s": 34405,
"text": "sweetyty"
},
{
"code": null,
"e": 34434,
"s": 34414,
"text": "array-range-queries"
},
{
"code": null,
"e": 34456,
"s": 34434,
"text": "binary-representation"
},
{
"code": null,
"e": 34470,
"s": 34456,
"text": "binary-string"
},
{
"code": null,
"e": 34477,
"s": 34470,
"text": "Arrays"
},
{
"code": null,
"e": 34484,
"s": 34477,
"text": "Arrays"
},
{
"code": null,
"e": 34582,
"s": 34484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34650,
"s": 34582,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34694,
"s": 34650,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34742,
"s": 34694,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34765,
"s": 34742,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34797,
"s": 34765,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34811,
"s": 34797,
"text": "Linear Search"
},
{
"code": null,
"e": 34832,
"s": 34811,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 34917,
"s": 34832,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 34962,
"s": 34917,
"text": "Python | Using 2D arrays/lists the right way"
}
]
|
How to make animated counter using JavaScript ? - GeeksforGeeks | 31 Oct, 2021
In this article, we will create an animated counter using JavaScript and basic HTML for designing.
An animated counter is used to display the counts in an animation starting from 0 and ending at a specific number. This is generally used by many websites to make a web page more attractive.
Approach:
In the HTML body tag, specify the div tag with an id.
Add JavaScript code to the script tag.
Use the setInterval() method to execute the update function which will increment the count value.
Get the id using the getElementById() method and use the innerHTML property to display the count.
If the count value reached the required count then stop executing the code using the clearInterval() method.
The setInterval() method repeats a given function at every given time interval and this method executes until clearInterval() is called.
Note: Please refer to the above-mentioned article links for a better understanding.
Example 1: In the following code, we have taken variable “counts” which executes the setInterval() method which calls the updated() function. Once the “upto” variable value reaches the value of 1000, the clearInterval() method is executed. We have incremented the value of the counter value from 0 to 1000.
HTML
<!DOCTYPE html><html lang="en"> <body style="text-align:center"> <h1>GeeksforGeeks</h1> <p>COUNTS</p> <div id="counter"> <!-- counts --> </div> <script> let counts=setInterval(updated); let upto=0; function updated(){ var count= document.getElementById("counter"); count.innerHTML=++upto; if(upto===1000) { clearInterval(counts); } } </script></body></html>
Output:
Example 2: Decrement the counter value from 1000 to 0 using JavaScript. We have added some CSS styles under the style tag in the body tag to make the webpage more attractive.
HTML
<!DOCTYPE html><html lang="en"><head> <style> body{ background-color: green; } #counter{ color:white; } </style></head><body style="text-align:center"> <h1>GeeksforGeeks</h1> <p>COUNTS DECREMENT</p> <div id="counter"> <!-- counts --> </div> <script> let counts=setInterval(updated); let upto=1000; function updated(){ var count= document.getElementById("counter"); count.innerHTML=--upto; if(upto === 0) { clearInterval(counts); } } </script></body></html>
Output:
HTML-Tags
JavaScript-Questions
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 26164,
"s": 26136,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 26263,
"s": 26164,
"text": "In this article, we will create an animated counter using JavaScript and basic HTML for designing."
},
{
"code": null,
"e": 26454,
"s": 26263,
"text": "An animated counter is used to display the counts in an animation starting from 0 and ending at a specific number. This is generally used by many websites to make a web page more attractive."
},
{
"code": null,
"e": 26464,
"s": 26454,
"text": "Approach:"
},
{
"code": null,
"e": 26518,
"s": 26464,
"text": "In the HTML body tag, specify the div tag with an id."
},
{
"code": null,
"e": 26557,
"s": 26518,
"text": "Add JavaScript code to the script tag."
},
{
"code": null,
"e": 26655,
"s": 26557,
"text": "Use the setInterval() method to execute the update function which will increment the count value."
},
{
"code": null,
"e": 26753,
"s": 26655,
"text": "Get the id using the getElementById() method and use the innerHTML property to display the count."
},
{
"code": null,
"e": 26862,
"s": 26753,
"text": "If the count value reached the required count then stop executing the code using the clearInterval() method."
},
{
"code": null,
"e": 26999,
"s": 26862,
"text": "The setInterval() method repeats a given function at every given time interval and this method executes until clearInterval() is called."
},
{
"code": null,
"e": 27084,
"s": 26999,
"text": "Note: Please refer to the above-mentioned article links for a better understanding. "
},
{
"code": null,
"e": 27391,
"s": 27084,
"text": "Example 1: In the following code, we have taken variable “counts” which executes the setInterval() method which calls the updated() function. Once the “upto” variable value reaches the value of 1000, the clearInterval() method is executed. We have incremented the value of the counter value from 0 to 1000."
},
{
"code": null,
"e": 27396,
"s": 27391,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <body style=\"text-align:center\"> <h1>GeeksforGeeks</h1> <p>COUNTS</p> <div id=\"counter\"> <!-- counts --> </div> <script> let counts=setInterval(updated); let upto=0; function updated(){ var count= document.getElementById(\"counter\"); count.innerHTML=++upto; if(upto===1000) { clearInterval(counts); } } </script></body></html>",
"e": 27880,
"s": 27396,
"text": null
},
{
"code": null,
"e": 27889,
"s": 27880,
"text": "Output: "
},
{
"code": null,
"e": 28065,
"s": 27889,
"text": "Example 2: Decrement the counter value from 1000 to 0 using JavaScript. We have added some CSS styles under the style tag in the body tag to make the webpage more attractive. "
},
{
"code": null,
"e": 28070,
"s": 28065,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <style> body{ background-color: green; } #counter{ color:white; } </style></head><body style=\"text-align:center\"> <h1>GeeksforGeeks</h1> <p>COUNTS DECREMENT</p> <div id=\"counter\"> <!-- counts --> </div> <script> let counts=setInterval(updated); let upto=1000; function updated(){ var count= document.getElementById(\"counter\"); count.innerHTML=--upto; if(upto === 0) { clearInterval(counts); } } </script></body></html>",
"e": 28697,
"s": 28070,
"text": null
},
{
"code": null,
"e": 28706,
"s": 28697,
"text": "Output: "
},
{
"code": null,
"e": 28716,
"s": 28706,
"text": "HTML-Tags"
},
{
"code": null,
"e": 28737,
"s": 28716,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28742,
"s": 28737,
"text": "HTML"
},
{
"code": null,
"e": 28753,
"s": 28742,
"text": "JavaScript"
},
{
"code": null,
"e": 28770,
"s": 28753,
"text": "Web Technologies"
},
{
"code": null,
"e": 28775,
"s": 28770,
"text": "HTML"
},
{
"code": null,
"e": 28873,
"s": 28775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28897,
"s": 28873,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28938,
"s": 28897,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 28975,
"s": 28938,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29004,
"s": 28975,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29024,
"s": 29004,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29064,
"s": 29024,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29109,
"s": 29064,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29170,
"s": 29109,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29242,
"s": 29170,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
Java Program for Insertion Sort - GeeksforGeeks | 06 Aug, 2018
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
// Java program for implementation of Insertion Sortclass InsertionSort{ /*Function to sort array using insertion sort*/ void sort(int arr[]) { int n = arr.length; for (int i=1; i<n; ++i) { int key = arr[i]; int j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j>=0 && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; } } /* A utility function to print array of size n*/ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method public static void main(String args[]) { int arr[] = {12, 11, 13, 5, 6}; InsertionSort ob = new InsertionSort(); ob.sort(arr); printArray(arr); }} /* This code is contributed by Rajat Mishra. */
Please refer complete article on Insertion Sort for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Find Sum of Array Elements
How to Replace a Element in Java ArrayList?
Java Program to Read a File to String
Tic-Tac-Toe Game in Java
Removing last element from ArrayList in Java
How to Write Data into Excel Sheet using Java?
Java Program to Write an Array of Strings to the Output Console | [
{
"code": null,
"e": 26131,
"s": 26103,
"text": "\n06 Aug, 2018"
},
{
"code": null,
"e": 26231,
"s": 26131,
"text": "Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands."
},
{
"code": "// Java program for implementation of Insertion Sortclass InsertionSort{ /*Function to sort array using insertion sort*/ void sort(int arr[]) { int n = arr.length; for (int i=1; i<n; ++i) { int key = arr[i]; int j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j>=0 && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; } } /* A utility function to print array of size n*/ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver method public static void main(String args[]) { int arr[] = {12, 11, 13, 5, 6}; InsertionSort ob = new InsertionSort(); ob.sort(arr); printArray(arr); }} /* This code is contributed by Rajat Mishra. */",
"e": 27336,
"s": 26231,
"text": null
},
{
"code": null,
"e": 27402,
"s": 27336,
"text": "Please refer complete article on Insertion Sort for more details!"
},
{
"code": null,
"e": 27416,
"s": 27402,
"text": "Java Programs"
},
{
"code": null,
"e": 27514,
"s": 27416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27562,
"s": 27514,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 27613,
"s": 27562,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 27647,
"s": 27613,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 27690,
"s": 27647,
"text": "Java Program to Find Sum of Array Elements"
},
{
"code": null,
"e": 27734,
"s": 27690,
"text": "How to Replace a Element in Java ArrayList?"
},
{
"code": null,
"e": 27772,
"s": 27734,
"text": "Java Program to Read a File to String"
},
{
"code": null,
"e": 27797,
"s": 27772,
"text": "Tic-Tac-Toe Game in Java"
},
{
"code": null,
"e": 27842,
"s": 27797,
"text": "Removing last element from ArrayList in Java"
},
{
"code": null,
"e": 27889,
"s": 27842,
"text": "How to Write Data into Excel Sheet using Java?"
}
]
|
Merge two sorted arrays with O(1) extra space - GeeksforGeeks | 10 May, 2022
We are given two sorted arrays. We need to merge these two arrays such that the initial numbers (after complete sorting) are in the first array and the remaining numbers are in the second array. Extra space allowed in O(1).
Example:
Input: ar1[] = {10};
ar2[] = {2, 3};
Output: ar1[] = {2}
ar2[] = {3, 10}
Input: ar1[] = {1, 5, 9, 10, 15, 20};
ar2[] = {2, 3, 8, 13};
Output: ar1[] = {1, 2, 3, 5, 8, 9}
ar2[] = {10, 13, 15, 20}
This task is simple and O(m+n) if we are allowed to use extra space. But it becomes really complicated when extra space is not allowed and doesn’t look possible in less than O(m*n) worst case time. Though further optimizations are possibleThe idea is to begin from last element of ar2[] and search it in ar1[]. If there is a greater element in ar1[], then we move last element of ar1[] to ar2[]. To keep ar1[] and ar2[] sorted, we need to place last element of ar2[] at correct place in ar1[]. We can use Insertion Sort type of insertion for this.
1. Method 1
Algorithm:
1) Iterate through every element of ar2[] starting from last
element. Do following for every element ar2[i]
a) Store last element of ar1[i]: last = ar1[i]
b) Loop from last element of ar1[] while element ar1[j] is
greater than ar2[i].
ar1[j+1] = ar1[j] // Move element one position ahead
j--
c) If any element of ar1[] was moved or (j != m-1)
ar1[j+1] = ar2[i]
ar2[i] = last
In above loop, elements in ar1[] and ar2[] are always kept sorted.
Below is the implementation of above algorithm.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to merge two sorted// arrays with O(1) extra space.#include <bits/stdc++.h>using namespace std; // Merge ar1[] and ar2[] with O(1) extra spacevoid merge(int ar1[], int ar2[], int m, int n){ // Iterate through all elements // of ar2[] starting from the last element for (int i = n - 1; i >= 0; i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ int j, last = ar1[m - 1]; for (j = m - 2; j >= 0 && ar1[j] > ar2[i]; j--) ar1[j + 1] = ar1[j]; // If there was a greater element if (j != m - 2 || last > ar2[i]) { ar1[j + 1] = ar2[i]; ar2[i] = last; } }} // Driver programint main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0;}
// Java program to merge two// sorted arrays with O(1) extra space. import java.util.Arrays; class Test{ static int arr1[] = new int[]{1, 5, 9, 10, 15, 20}; static int arr2[] = new int[]{2, 3, 8, 13}; static void merge(int m, int n) { // Iterate through all elements of ar2[] starting from // the last element for (int i=n-1; i>=0; i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ int j, last = arr1[m-1]; for (j=m-2; j >= 0 && arr1[j] > arr2[i]; j--) arr1[j+1] = arr1[j]; // If there was a greater element if (j != m-2 || last > arr2[i]) { arr1[j+1] = arr2[i]; arr2[i] = last; } } } // Driver method to test the above function public static void main(String[] args) { merge(arr1.length,arr2.length); System.out.print("After Merging nFirst Array: "); System.out.println(Arrays.toString(arr1)); System.out.print("Second Array: "); System.out.println(Arrays.toString(arr2)); }}
# Python program to merge# two sorted arrays# with O(1) extra space. # Merge ar1[] and ar2[]# with O(1) extra spacedef merge(ar1, ar2, m, n): # Iterate through all # elements of ar2[] starting from # the last element for i in range(n-1, -1, -1): # Find the smallest element # greater than ar2[i]. Move all # elements one position ahead # till the smallest greater # element is not found last = ar1[m-1] j=m-2 while(j >= 0 and ar1[j] > ar2[i]): ar1[j+1] = ar1[j] j-=1 # If there was a greater element if (j != m-2 or last > ar2[i]): ar1[j+1] = ar2[i] ar2[i] = last # Driver program ar1 = [1, 5, 9, 10, 15, 20]ar2 = [2, 3, 8, 13]m = len(ar1)n = len(ar2) merge(ar1, ar2, m, n) print("After Merging \nFirst Array:", end="")for i in range(m): print(ar1[i] , " ", end="") print("\nSecond Array: ", end="")for i in range(n): print(ar2[i] , " ", end="") # This code is contributed# by Anant Agarwal.
// C# program to merge two// sorted arrays with O(1) extra space.using System; // Java program program to merge two// sorted arrays with O(1) extra space. public class Test{ static int []arr1 = new int[]{1, 5, 9, 10, 15, 20}; static int []arr2 = new int[]{2, 3, 8, 13}; static void merge(int m, int n) { // Iterate through all elements of ar2[] starting from // the last element for (int i=n-1; i>=0; i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ int j, last = arr1[m-1]; for (j=m-2; j >= 0 && arr1[j] > arr2[i]; j--) arr1[j+1] = arr1[j]; // If there was a greater element if (j != m-2 || last > arr2[i]) { arr1[j+1] = arr2[i]; arr2[i] = last; } } } // Driver method to test the above function public static void Main() { merge(arr1.Length,arr2.Length); Console.Write("After Merging \nFirst Array: "); for(int i =0; i< arr1.Length;i++){ Console.Write(arr1[i]+" "); } Console.Write("\nSecond Array: "); for(int i =0; i< arr2.Length;i++){ Console.Write(arr2[i]+" "); } }} /*This code is contributed by 29AjayKumar*/
<?php// PHP program to merge two sorted arrays with O(1) extra space. // Merge ar1[] and ar2[] with O(1) extra spacefunction merge(&$ar1, &$ar2, $m, $n){ // Iterate through all elements of ar2[] starting from // the last element for ($i = $n-1; $i >= 0; $i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ $last = $ar1[$m-1]; for ($j = $m-2; $j >= 0 && $ar1[$j] > $ar2[$i]; $j--) $ar1[$j+1] = $ar1[$j]; // If there was a greater element if ($j != $m-2 || $last > $ar2[$i]) { $ar1[$j+1] = $ar2[$i]; $ar2[$i] = $last; } }} // Driver program $ar1 = array(1, 5, 9, 10, 15, 20);$ar2 = array(2, 3, 8, 13);$m = sizeof($ar1)/sizeof($ar1[0]);$n = sizeof($ar2)/sizeof($ar2[0]);merge($ar1, $ar2, $m, $n); echo "After Merging \nFirst Array: ";for ($i=0; $i<$m; $i++) echo $ar1[$i] . " ";echo "\nSecond Array: ";for ($i=0; $i<$n; $i++) echo $ar2[$i] ." ";return 0;?>
<script> // Javascript program to merge two// sorted arrays with O(1) extra space. let arr1=[1, 5, 9, 10, 15, 20]; let arr2=[2, 3, 8, 13]; function merge(m,n) { // Iterate through all elements of ar2[] starting from // the last element for (let i=n-1; i>=0; i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ let j, last = arr1[m-1]; for (j=m-2; j >= 0 && arr1[j] > arr2[i]; j--) arr1[j+1] = arr1[j]; // If there was a greater element if (j != m-2 || last > arr2[i]) { arr1[j+1] = arr2[i]; arr2[i] = last; } } } // Driver method to test the above function merge(arr1.length,arr2.length); document.write("After Merging <br>First Array: "); for(let i=0;i<arr1.length;i++) { document.write(arr1[i]+" "); } document.write("<br>Second Array: "); for(let i=0;i<arr2.length;i++) { document.write(arr2[i]+" "); } // This code is contributed by avanitrachhadiya2155 </script>
After Merging nFirst Array: 1 2 3 5 8 9 nSecond Array: 10 13 15 20
Output:
After Merging
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Time Complexity: The worst case time complexity of code/algorithm is O(m*n). The worst case occurs when all elements of ar1[] are greater than all elements of ar2[].
Illustration:
<!— Initial Arrays: ar1[] = {1, 5, 9, 10, 15, 20}; ar2[] = {2, 3, 8, 13};After First Iteration: ar1[] = {1, 5, 9, 10, 13, 15}; ar2[] = {2, 3, 8, 20}; // 20 is moved from ar1[] to ar2[] // 13 from ar2[] is inserted in ar1[]After Second Iteration: ar1[] = {1, 5, 8, 9, 10, 13}; ar2[] = {2, 3, 15, 20}; // 15 is moved from ar1[] to ar2[] // 8 from ar2[] is inserted in ar1[]After Third Iteration: ar1[] = {1, 3, 5, 8, 9, 10}; ar2[] = {2, 13, 15, 20}; // 13 is moved from ar1[] to ar2[] // 3 from ar2[] is inserted in ar1[]After Fourth Iteration: ar1[] = {1, 2, 3, 5, 8, 9}; ar2[] = {10, 13, 15, 20}; // 10 is moved from ar1[] to ar2[] // 2 from ar2[] is inserted in ar1[] —!>
Method 2:
The solution can be further optimized by observing that while traversing the two sorted arrays parallelly, if we encounter the jth second array element is smaller than ith first array element, then jth element is to be included and replace some kth element in the first array. This observation helps us with the following algorithm
Algorithm
1) Initialize i,j,k as 0,0,n-1 where n is size of arr1
2) Iterate through every element of arr1 and arr2 using two pointers i and j respectively
if arr1[i] is less than arr2[j]
increment i
else
swap the arr2[j] and arr1[k]
increment j and decrement k
3) Sort both arr1 and arr2
Below is the implementation of above algorithm
C++
Java
Python3
C#
Javascript
// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // Function to merge two arraysvoid merge(int arr1[], int arr2[], int n, int m){ int i = 0, j = 0, k = n - 1; // Until i less than equal to k // or j is less than m while (i <= k && j < m) { if (arr1[i] < arr2[j]) i++; else { swap(arr2[j++], arr1[k--]); } } // Sort first array sort(arr1, arr1 + n); // Sort second array sort(arr2, arr2 + m);} // Driver Codeint main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0;}
// Java program for the above approachimport java.util.Arrays;import java.util.Collections; class GFG { static int arr1[] = new int[] { 1, 5, 9, 10, 15, 20 }; static int arr2[] = new int[] { 2, 3, 8, 13 }; // Function to merge two arrays static void merge(int m, int n) { int i = 0, j = 0, k = m - 1; while (i <= k && j < n) { if (arr1[i] < arr2[j]) i++; else { int temp = arr2[j]; arr2[j] = arr1[k]; arr1[k] = temp; j++; k--; } } Arrays.sort(arr1); Arrays.sort(arr2); } public static void main(String[] args) { merge(arr1.length, arr2.length); System.out.print("After Merging \nFirst Array: "); System.out.println(Arrays.toString(arr1)); System.out.print("Second Array: "); System.out.println(Arrays.toString(arr2)); }}
# Python program for the above approacharr1 = [1, 5, 9, 10, 15, 20 ];arr2 = [2, 3, 8, 13 ]; # Function to merge two arraysdef merge(m, n): i = 0; j = 0; k = n - 1; while (i <= k and j < m): if (arr1[i] < arr2[j]): i+=1; else: temp = arr2[j]; arr2[j] = arr1[k]; arr1[k] = temp; j += 1; k -= 1; arr1.sort(); arr2.sort(); # Driver codeif __name__ == '__main__': merge(len(arr1), len(arr2)); print("After Merging \nFirst Array: "); print(','.join(str(x) for x in arr1)); print("Second Array: "); print(','.join(str(x) for x in arr2)); # This code is contributed by gauravrajput1
// C# program for the above approachusing System; public class GFG { static int []arr1 ={ 1, 5, 9, 10, 15, 20 }; static int []arr2 = { 2, 3, 8, 13 }; // Function to merge two arrays static void merge(int m, int n) { int i = 0, j = 0, k = n - 1; while (i <= k && j < m) { if (arr1[i] < arr2[j]) i++; else { int temp = arr2[j]; arr2[j] = arr1[k]; arr1[k] = temp; j++; k--; } } Array.Sort(arr1); Array.Sort(arr2); } public static void Main(String[] args) { merge(arr1.Length, arr2.Length); Console.Write("After Merging \nFirst Array: "); foreach(int i in arr1){ Console.Write(i+" "); } Console.Write("\nSecond Array: "); foreach(int i in arr2){ Console.Write(i+" "); } }} // This code is contributed by gauravrajput1
<script>// javascript program for the above approachvar arr1 = [ 1, 5, 9, 10, 15, 20 ]; var arr2 = [ 2, 3, 8, 13 ]; // Function to merge two arrays function merge(m , n) { var i = 0, j = 0, k = n - 1; while (i <= k && j < m) { if (arr1[i] < arr2[j]) i++; else { var temp = arr2[j]; arr2[j] = arr1[k]; arr1[k] = temp; j++; k--; } } arr1.sort((a,b)=>a-b); arr2.sort((a,b)=>a-b); } merge(arr1.length, arr2.length); document.write("After Merging <br/>First Array:<br/> "); for(var a of arr1) document.write(a+" "); document.write("<br/>Second Array: <br/> "); for(var a of arr2) document.write(a+" "); // This code is contributed by gauravrajput1</script>
After Merging
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Complexities:
Time Complexity: The time complexity while traversing the arrays in while loop is O(n+m) in worst case and sorting is O(nlog(n) + mlog(m)). So overall time complexity of the code becomes O((n+m)log(n+m)).
Space Complexity: As the function doesn’t use any extra array for any operations, the space complexity is O(1).
Method 3:
Algorithm:
1) Initialize i with 0
2) Iterate while loop until last element of array 1 is greater than first element of array 2
if arr1[i] greater than first element of arr2
swap arr1[i] with arr2[0]
sort arr2
incrementing i
C++
Java
Python3
C#
Javascript
#include<iostream>#include<bits/stdc++.h>using namespace std; void merge(int arr1[], int arr2[], int n, int m) { int i=0; // while loop till last element of array 1(sorted) is greater than // first element of array 2(sorted) while(arr1[n-1]>arr2[0]) { if(arr1[i]>arr2[0]) { // swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) swap(arr1[i],arr2[0]); sort(arr2,arr2+m); } i++; } } int main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0; }
import java.io.*;import java.util.Arrays;import java.util.Collections; class GFG{ static int arr1[] = new int[]{ 1, 5, 9, 10, 15, 20 };static int arr2[] = new int[]{ 2, 3, 8, 13 }; static void merge(int n, int m){ int i = 0; int temp = 0; // While loop till last element // of array 1(sorted) // is greater than first element // of array 2(sorted) while (arr1[n - 1] > arr2[0]) { if (arr1[i] > arr2[0]) { // Swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) // swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; Arrays.sort(arr2); } i++; }} // Driver codepublic static void main(String[] args){ merge(arr1.length, arr2.length); System.out.print("After Merging \nFirst Array: "); System.out.println(Arrays.toString(arr1)); System.out.print("Second Array: "); System.out.println(Arrays.toString(arr2));}} // This code is contributed by Aakash Tiwari(nighteagle)
arr1 = [1, 5, 9, 10, 15, 20 ];arr2 =[ 2, 3, 8, 13 ]; def merge(n, m): i = 0; temp = 0; # While loop till last element # of array 1(sorted) # is greater than first element # of array 2(sorted) while (arr1[n - 1] > arr2[0]): if (arr1[i] > arr2[0]): # Swap arr1[i] with first element # of arr2 and sorting the updated # arr2(arr1 is already sorted) # swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; arr2.sort(); i+=1; # Driver codeif __name__ == '__main__': merge(len(arr1), len(arr2)); print("After Merging \nFirst Array: "); print((arr1)); print("Second Array: "); print((arr2)); # This code contributed by gauravrajput1
using System; public class GFG { static int []arr1 = new int[] { 1, 5, 9, 10, 15, 20 }; static int []arr2 = new int[] { 2, 3, 8, 13 }; static void merge(int n, int m) { int i = 0; int temp = 0; // While loop till last element // of array 1(sorted) // is greater than first element // of array 2(sorted) while (arr1[n - 1] > arr2[0]) { if (arr1[i] > arr2[0]) { // Swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) // swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; Array.Sort(arr2); } i++; } } // Driver code public static void Main(String[] args) { merge(arr1.Length, arr2.Length); Console.Write("After Merging \nFirst Array: "); foreach(int i in arr1) Console.Write(i+" "); Console.Write("\nSecond Array: "); foreach(int i in arr2) Console.Write(i+" "); }} // This code is contributed by gauravrajput1
<script> var arr1 = [1, 5, 9, 10, 15, 20 ]; var arr2 =[2, 3, 8, 13 ]; function merge(n , m) { var i = 0; var temp = 0; // While loop till last element // of array 1(sorted) // is greater than first element // of array 2(sorted) while (arr1[n - 1] > arr2[0]) { if (arr1[i] > arr2[0]) { // Swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) // swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; arr2.sort((a,b)=>a-b); } i++; } } // Driver code merge(arr1.length, arr2.length); document.write("After Merging <br\>First Array: "); document.write(arr1.toString()); document.write("<br\>Second Array: "); document.write(arr2.toString()); // This code is contributed by umadevi9616</script>
After Merging
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Efficiently merging two sorted arrays with O(1) extra space
Method 4: Let length of shorter array be ‘m’ and larger array be ‘n’
Step 1: Select the shorter array and find the index at which partition should be done. Similar to this https://www.geeksforgeeks.org/median-of-two-sorted-arrays-of-different-sizes/
Step 1: Partition the shorter array at its median (l1).
Step 2: Select the first n-l1 elements from the second array.
Step 3: Compare the border elements i.e.
if l1 < r2 and l2 < r2 we have found the index
else if l1 > r2 we have to search in the left subarray
else we have to search in the right subarray
NOTE : This step will store all the smallest elements in the shorter array.
Step 2: Swap all the elements right to the index(i) of the shorter array with the first n-i elements of the larger array.
Step 3: Sort both the arrays.
::::: if len(arr1) > len(arr2) all the smallest elements are stored in arr2 so we have to move all the elements in arr1 since we have to print arr1 first.
Step 4: Rotate the larger array (arr1) m times counter-clockwise.
Step 5: Swap the first m elements of both the arrays.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; void swap(int& a, int& b){ int temp = a; a = b; b = temp;} void rotate(int a[], int n, int idx){ int i; for (i = 0; i < idx / 2; i++) swap(a[i], a[idx - 1 - i]); for (i = idx; i < (n + idx) / 2; i++) swap(a[i], a[n - 1 - (i - idx)]); for (i = 0; i < n / 2; i++) swap(a[i], a[n - 1 - i]);} void sol(int a1[], int a2[], int n, int m){ int l = 0, h = n - 1, idx = 0; //--------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray int c1 = (l + h) / 2; // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array int c2 = n - c1 - 1; int l1 = a1[c1]; int l2 = a2[c2 - 1]; int r1 = c1 == n - 1 ? INT_MAX : a1[c1 + 1]; int r2 = c2 == m ? INT_MAX : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (int i = idx; i < n; i++) swap(a1[i], a2[i - idx]); sort(a1, a1 + n); sort(a2, a2 + m);} void merge(int arr1[], int arr2[], int n, int m){ // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (int i = 0; i < m; i++) swap(arr2[i], arr1[i]); } else { sol(arr1, arr2, n, m); }} int main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0;}
// Java program for the above approachimport java.util.*; class GFG{ static void swap(int a, int b){ int temp = a; a = b; b = temp;} static void rotate(int a[], int n, int idx){ int i; for (i = 0; i < idx / 2; i++) swap(a[i], a[idx - 1 - i]); for (i = idx; i < (n + idx) / 2; i++) swap(a[i], a[n - 1 - (i - idx)]); for (i = 0; i < n / 2; i++) swap(a[i], a[n - 1 - i]);} static void sol(int a1[], int a2[], int n, int m){ int l = 0, h = n - 1, idx = 0; //--------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray int c1 = (int)(l + h) / 2; // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array int c2 = n - c1 - 1; int l1 = a1[c1]; int l2 = a2[c2 - 1]; int r1 = (c1 == n - 1) ? Integer.MAX_VALUE : a1[c1 + 1]; int r2 = (c2 == m) ? Integer.MAX_VALUE : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (int i = idx; i < n; i++) swap(a1[i], a2[i - idx]); Arrays.sort(a1); Arrays.sort(a2);} static void merge(int arr1[], int arr2[], int n, int m){ // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (int i = 0; i < m; i++) swap(arr2[i], arr1[i]); } else { sol(arr1, arr2, n, m); }} // Driver Codepublic static void main (String[] args){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = ar1.length; int n = ar2.length; merge(ar1, ar2, m, n); System.out.print("After Merging \nFirst Array: "); for (int i = 0; i < m; i++) System.out.print(ar1[i] + " "); System.out.print("\nSecond Array: "); for (int i = 0; i < n; i++) System.out.print(ar2[i] + " "); }} // This code is contributed by sanjoy_62.
# Python program to merge# two sorted arrays# with O(1) extra space. # Merge ar1[] and ar2[]# with O(1) extra space def rotate(a, n, idx): for i in range((int)(idx/2)): a[i], a[idx-1-i] = a[idx-1-i], a[i] for i in range(idx, (int)((n+idx)/2)): a[i], a[n-1-(i-idx)] = a[n-1-(i-idx)], a[i] for i in range((int)(n/2)): a[i], a[n-1-i] = a[n-1-i], a[i] def sol(a1, a2, n, m): l = 0 h = n-1 idx = 0 while (l <= h): c1 = (int)((l+h)/2) c2 = n-c1-1 l1 = a1[c1] l2 = a2[c2-1] r1 = sys.maxint if c1 == n-1 else a1[c1+1] r2 = sys.maxint if c2 == m else a2[c2] if l1 > r2: h = c1-1 if h == -1: idx = 0 elif l2 > r1: l = c1+1 if l == n-1: idx = n else: idx = c1+1 break for i in range(idx, n): a1[i], a2[i-idx] = a2[i-idx], a1[i] a1.sort() a2.sort() def merge(a1, a2, n, m): if n > m: sol(a2, a1, m, n) rotate(a1, n, n-m) for i in range(m): a1[i], a2[i] = a2[i], a1[i] else: sol(a1, a2, n, m)# Driver program ar1 = [1, 5, 9, 10, 15, 20]ar2 = [2, 3, 8, 13]m = len(ar1)n = len(ar2) merge(ar1, ar2, m, n) print("After Merging \nFirst Array:", end="")for i in range(m): print(ar1[i], " ", end="")print("\nSecond Array: ", end="")for i in range(n): print(ar2[i], " ", end="")# This code is contributed# by Aditya Anand.
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG { static void swap(int a, int b) { int temp = a; a = b; b = temp; } static void rotate(int []a, int n, int idx) { int i; for (i = 0; i < idx / 2; i++) swap(a[i], a[idx - 1 - i]); for (i = idx; i < (n + idx) / 2; i++) swap(a[i], a[n - 1 - (i - idx)]); for (i = 0; i < n / 2; i++) swap(a[i], a[n - 1 - i]); } static void sol(int []a1, int []a2, int n, int m) { int l = 0, h = n - 1, idx = 0; // --------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray int c1 = (int) (l + h) / 2; // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array int c2 = n - c1 - 1; int l1 = a1[c1]; int l2 = a2[c2 - 1]; int r1 = (c1 == n - 1) ? int.MaxValue : a1[c1 + 1]; int r2 = (c2 == m) ? int.MaxValue : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (int i = idx; i < n; i++) swap(a1[i], a2[i - idx]); Array.Sort(a1); Array.Sort(a2); } static void merge(int []arr1, int []arr2, int n, int m) { // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (int i = 0; i < m; i++) swap(arr2[i], arr1[i]); } else { sol(arr1, arr2, n, m); } } // Driver Code public static void Main(String[] args) { int []ar1 = { 1, 5, 9, 10, 15, 20 }; int []ar2 = { 2, 3, 8, 13 }; int m = ar1.Length; int n = ar2.Length; merge(ar1, ar2, m, n); Console.Write("After Merging \nFirst Array: "); for (int i = 0; i < m; i++) Console.Write(ar1[i] + " "); Console.Write("\nSecond Array: "); for (int i = 0; i < n; i++) Console.Write(ar2[i] + " "); }} // This code contributed by gauravrajput1
<script>// javascript program for the above approach function swap(a , b) { var temp = a; a = b; b = temp; } function rotate(a , n , idx) { var i; for (i = 0; i < idx / 2; i++) { var temp =a[i] a[i]= a[idx - 1 - i]; a[idx - 1 - i] = temp; } for (i = idx; i < (n + idx) / 2; i++) { var temp =a[i] a[i]= a[n - 1 - (i - idx)]; a[n - 1 - (i - idx)] = temp; } for (i = 0; i < n / 2; i++) { var temp =a[i] a[i]= a[n - 1 - i]; a[n - 1 - i] = temp; } } function sol(a1 , a2 , n , m) { var l = 0, h = n - 1, idx = 0; // --------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray var c1 = parseInt( (l + h) / 2); // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array var c2 = n - c1 - 1; var l1 = a1[c1]; var l2 = a2[c2 - 1]; var r1 = (c1 == n - 1) ? Number.MAX_VALUE : a1[c1 + 1]; var r2 = (c2 == m) ? Number.MAX_VALUE : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (i = idx; i < n; i++) { var temp =a1[i] a1[i]= a2[i - idx]; a2[i - idx] = temp; } a1.sort((a,b)=>a-b); a2.sort((a,b)=>a-b); } function merge(arr1 , arr2 , n , m) { // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (i = 0; i < m; i++) { var temp =arr2[i] arr2[i]= arr1[i]; arr1[i] = temp; } } else { sol(arr1, arr2, n, m); } } // Driver Code var ar1 = [ 1, 5, 9, 10, 15, 20 ]; var ar2 = [ 2, 3, 8, 13 ]; var m = ar1.length; var n = ar2.length; merge(ar1, ar2, m, n); document.write("After Merging \nFirst Array: "); for (i = 0; i < m; i++) document.write(ar1[i] + " "); document.write("\nSecond Array: "); for (i = 0; i < n; i++) document.write(ar2[i] + " "); // This code is contributed by gauravrajput1</script>
After Merging
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Time Complexity: O(min(nlogn, mlogm))
Method-5 [Insertion Sort with Simultaneous Merge]
Approach:
1. sort list 1 by always comparing with head/first of list 2 and swapping if required2. after each head/first swap, perform insertion of the swapped element into correct position in list 2 which will eventually sort list 2 at the end.
For every swapped item from list 1, perform insertion sort in list 2 to find its correct position so that when list 1 is sorted, list 2 is also sorted.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; void merge(int arr1[], int arr2[], int n, int m){ // two pointer to iterate int i = 0; int j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1[] become sorted then we check that // arr2[j] is smaller then all other element in // right side of arr2[j] if arr2[] is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left swap(arr1[i], arr2[j]); i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { int temp = arr2[j]; int tempj = j + 1; while (arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } }} int main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0;}
import java.util.*;class GFG{ static void merge(int arr1[], int arr2[], int n, int m){ // two pointer to iterate int i = 0; int j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1[] become sorted then we check that // arr2[j] is smaller then all other element in // right side of arr2[j] if arr2[] is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left int t = arr1[i]; arr1[i] = arr2[j]; arr2[j] = t; i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { int temp = arr2[j]; int tempj = j + 1; while (tempj<m && arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } }} public static void main(String[] args){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = ar1.length; int n =ar2.length; merge(ar1, ar2, m, n); System.out.print("After Merging \nFirst Array: "); for (int i = 0; i < m; i++) System.out.print(ar1[i]+ " "); System.out.print("\nSecond Array: "); for (int i = 0; i < n; i++) System.out.print(ar2[i]+ " ");}} // This code is contributed by gauravrajput1
# code contributed by mahee96 # "Insertion sort of list 2 with swaps from list 1"## swap elements to get list 1 correctly, meanwhile# place the swapped item in correct position of list 2# eventually list 2 is also sorted# Time = O(m*n) or O(n*m)# AUX = O(1)def merge(arr1, arr2): x = arr1; y = arr2 end = len(arr1) i = 0 while(i < end): # O(m) or O(n) if(x[i] > y[0]): swap(x,y,i,0) insert(y,0) # O(n) or O(m) number of shifts i+=1 # O(n):def insert(y, i): orig = y[i] i+=1 while (i<len(y) and y[i]<orig): y[i-1] = y[i] i+=1 y[i-1] = orig def swap(x,y,i,j): temp = x[i] x[i] = y[j] y[j] = temp def test(): c1 = [2, 3, 8, 13] c2 = [1, 5, 9, 10, 15, 20 ] for _ in range(2): merge(c1,c2) print(c1,c2) c1, c2 = c2, c1 test()
using System; public class GFG { static void merge(int []arr1, int []arr2, int n, int m) { // two pointer to iterate int i = 0; int j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1[] become sorted then we check that // arr2[j] is smaller then all other element in // right side of arr2[j] if arr2[] is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left int t = arr1[i]; arr1[i] = arr2[j]; arr2[j] = t; i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { int temp = arr2[j]; int tempj = j + 1; while (tempj < m && arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } } } public static void Main(String[] args) { int []ar1 = { 1, 5, 9, 10, 15, 20 }; int []ar2 = { 2, 3, 8, 13 }; int m = ar1.Length; int n = ar2.Length; merge(ar1, ar2, m, n); Console.Write("After Merging \nFirst Array: "); for (int i = 0; i < m; i++) Console.Write(ar1[i] + " "); Console.Write("\nSecond Array: "); for (int i = 0; i < n; i++) Console.Write(ar2[i] + " "); }} // This code is contributed by gauravrajput1
<script> function merge(arr1 , arr2 , n , m) { // two pointer to iterate var i = 0; var j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1 become sorted then we check that // arr2[j] is smaller then all other element in // right side of arr2[j] if arr2 is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left var t = arr1[i]; arr1[i] = arr2[j]; arr2[j] = t; i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { var temp = arr2[j]; var tempj = j + 1; while (tempj < m && arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } } } var ar1 = [ 1, 5, 9, 10, 15, 20 ]; var ar2 = [ 2, 3, 8, 13 ]; var m = ar1.length; var n = ar2.length; merge(ar1, ar2, m, n); document.write("After Merging <br/>First Array: <br/>"); for (i = 0; i < m; i++) document.write(ar1[i] + " "); document.write("<br/>Second Array: <br/>"); for (i = 0; i < n; i++) document.write(ar2[i] + " "); // This code contributed by gauravrajput1</script>
After Merging
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Time Complexity: O(m*n) list 1 traversal and list 2 insertionsAuxiliary Space: O(1)If m == n: Time = O(n^2) insertion sort complexity
Method-6 [Using Euclidean Division Lemma]
Approach:
Just merge the two arrays as we do in merge sort, while simultaneously using Euclidean Division Lemma, i.e. (((Operation on array) % x) * x). And at least after merging divide both the arrays with x. Where x needs to be a number greater than all elements of array. Here in this case x, (according to the constraints) can be 10e7 + 1.
C++
// C++ program to merge two sorted arrays without using extra space#include <bits/stdc++.h> using namespace std; void merge(int arr1[], int arr2[], int n, int m){ // three pointers to iterate int i = 0, j = 0, k = 0; // for euclid's division lemma int x = 10e7 + 1; // in this loop we are rearranging the elements of arr1 while (i < n && (j < n && k < m)) { // if both arr1 and arr2 elements are modified if (arr1[j] >= x && arr2[k] >= x) { if (arr1[j] % x <= arr2[k] % x) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if only arr1 elements are modified else if (arr1[j] >= x) { if (arr1[j] % x <= arr2[k]) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if only arr2 elements are modified else if (arr2[k] >= x) { if (arr1[j] <= arr2[k] % x) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if none elements are modified else { if (arr1[j] <= arr2[k]) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } i++; } // we can copy the elements directly as the other array // is exchausted while (j < n && i < n) { arr1[i++] += (arr1[j++] % x) * x; } while (k < m && i < n) { arr1[i++] += (arr2[k++] % x) * x; } // we need to reset i i = 0; // in this loop we are rearranging the elements of arr2 while (i < m && (j < n && k < m)) { // if both arr1 and arr2 elements are modified if (arr1[j] >= x && arr2[k] >= x) { if (arr1[j] % x <= arr2[k] % x) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } // if only arr1 elements are modified else if (arr1[j] >= x) { if (arr1[j] % x <= arr2[k]) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } // if only arr2 elements are modified else if (arr2[k] >= x) { if (arr1[j] <= arr2[k] % x) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } else { // if none elements are modified if (arr1[j] <= arr2[k]) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } i++; } // we can copy the elements directly as the other array // is exhausted while (j < n && i < m) { arr2[i++] += (arr1[j++] % x) * x; } while (k < m && i < m) { arr2[i++] += (arr2[k++] % x) * x; } // we need to reset i i = 0; // we need to divide the whole arr1 by x while (i < n) { arr1[i++] /= x; } // we need to reset i i = 0; // we need to divide the whole arr2 by x while (i < m) { arr2[i++] /= x; }} int main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0;}// This code is contributed by @ancientmoon8 (Mayank Kashyap)
After Merging
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Time Complexity: O(m + n)
Auxiliary Space: O(1)
Related Articles : Merge two sorted arrays Merge k sorted arrays | Set 1Thanks to Shubham Chauhan for suggesting 1st solution and Himanshu Kaushik for the 2nd solution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ukasp
29AjayKumar
akhilkhubchandani
chaitanyamunje
HimanshuKaushik2
avanitrachhadiya2155
14parikshitsingh
adityaanand12017
nighteagle
ajaymakvana
mahee96
sivananth321
sumitgumber28
architgwl2000
GauravRajput1
clintra
umadevi9616
sanjoy_62
surindertarika1234
sudhanshublaze
ancientmoon8
sweetyty
Amazon
Amdocs
Brocade
Goldman Sachs
Insertion Sort
Juniper Networks
Linkedin
Merge Sort
Microsoft
Quikr
Snapdeal
Synopsys
Zoho
Arrays
Mathematical
Sorting
Zoho
Amazon
Microsoft
Snapdeal
Goldman Sachs
Linkedin
Amdocs
Brocade
Juniper Networks
Quikr
Synopsys
Arrays
Mathematical
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays in C/C++
Write a program to reverse an array or string
Program for array rotation
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 42521,
"s": 42493,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 42745,
"s": 42521,
"text": "We are given two sorted arrays. We need to merge these two arrays such that the initial numbers (after complete sorting) are in the first array and the remaining numbers are in the second array. Extra space allowed in O(1)."
},
{
"code": null,
"e": 42755,
"s": 42745,
"text": "Example: "
},
{
"code": null,
"e": 42982,
"s": 42755,
"text": "Input: ar1[] = {10};\n ar2[] = {2, 3};\nOutput: ar1[] = {2}\n ar2[] = {3, 10} \n\nInput: ar1[] = {1, 5, 9, 10, 15, 20};\n ar2[] = {2, 3, 8, 13};\nOutput: ar1[] = {1, 2, 3, 5, 8, 9}\n ar2[] = {10, 13, 15, 20}"
},
{
"code": null,
"e": 43532,
"s": 42982,
"text": "This task is simple and O(m+n) if we are allowed to use extra space. But it becomes really complicated when extra space is not allowed and doesn’t look possible in less than O(m*n) worst case time. Though further optimizations are possibleThe idea is to begin from last element of ar2[] and search it in ar1[]. If there is a greater element in ar1[], then we move last element of ar1[] to ar2[]. To keep ar1[] and ar2[] sorted, we need to place last element of ar2[] at correct place in ar1[]. We can use Insertion Sort type of insertion for this. "
},
{
"code": null,
"e": 43544,
"s": 43532,
"text": "1. Method 1"
},
{
"code": null,
"e": 43556,
"s": 43544,
"text": "Algorithm: "
},
{
"code": null,
"e": 43996,
"s": 43556,
"text": "1) Iterate through every element of ar2[] starting from last \n element. Do following for every element ar2[i]\n a) Store last element of ar1[i]: last = ar1[i]\n b) Loop from last element of ar1[] while element ar1[j] is \n greater than ar2[i].\n ar1[j+1] = ar1[j] // Move element one position ahead\n j--\n c) If any element of ar1[] was moved or (j != m-1)\n ar1[j+1] = ar2[i] \n ar2[i] = last"
},
{
"code": null,
"e": 44063,
"s": 43996,
"text": "In above loop, elements in ar1[] and ar2[] are always kept sorted."
},
{
"code": null,
"e": 44112,
"s": 44063,
"text": "Below is the implementation of above algorithm. "
},
{
"code": null,
"e": 44116,
"s": 44112,
"text": "C++"
},
{
"code": null,
"e": 44121,
"s": 44116,
"text": "Java"
},
{
"code": null,
"e": 44129,
"s": 44121,
"text": "Python3"
},
{
"code": null,
"e": 44132,
"s": 44129,
"text": "C#"
},
{
"code": null,
"e": 44136,
"s": 44132,
"text": "PHP"
},
{
"code": null,
"e": 44147,
"s": 44136,
"text": "Javascript"
},
{
"code": "// C++ program to merge two sorted// arrays with O(1) extra space.#include <bits/stdc++.h>using namespace std; // Merge ar1[] and ar2[] with O(1) extra spacevoid merge(int ar1[], int ar2[], int m, int n){ // Iterate through all elements // of ar2[] starting from the last element for (int i = n - 1; i >= 0; i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ int j, last = ar1[m - 1]; for (j = m - 2; j >= 0 && ar1[j] > ar2[i]; j--) ar1[j + 1] = ar1[j]; // If there was a greater element if (j != m - 2 || last > ar2[i]) { ar1[j + 1] = ar2[i]; ar2[i] = last; } }} // Driver programint main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << \"After Merging nFirst Array: \"; for (int i = 0; i < m; i++) cout << ar1[i] << \" \"; cout << \"nSecond Array: \"; for (int i = 0; i < n; i++) cout << ar2[i] << \" \"; return 0;}",
"e": 45348,
"s": 44147,
"text": null
},
{
"code": "// Java program to merge two// sorted arrays with O(1) extra space. import java.util.Arrays; class Test{ static int arr1[] = new int[]{1, 5, 9, 10, 15, 20}; static int arr2[] = new int[]{2, 3, 8, 13}; static void merge(int m, int n) { // Iterate through all elements of ar2[] starting from // the last element for (int i=n-1; i>=0; i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ int j, last = arr1[m-1]; for (j=m-2; j >= 0 && arr1[j] > arr2[i]; j--) arr1[j+1] = arr1[j]; // If there was a greater element if (j != m-2 || last > arr2[i]) { arr1[j+1] = arr2[i]; arr2[i] = last; } } } // Driver method to test the above function public static void main(String[] args) { merge(arr1.length,arr2.length); System.out.print(\"After Merging nFirst Array: \"); System.out.println(Arrays.toString(arr1)); System.out.print(\"Second Array: \"); System.out.println(Arrays.toString(arr2)); }}",
"e": 46584,
"s": 45348,
"text": null
},
{
"code": "# Python program to merge# two sorted arrays# with O(1) extra space. # Merge ar1[] and ar2[]# with O(1) extra spacedef merge(ar1, ar2, m, n): # Iterate through all # elements of ar2[] starting from # the last element for i in range(n-1, -1, -1): # Find the smallest element # greater than ar2[i]. Move all # elements one position ahead # till the smallest greater # element is not found last = ar1[m-1] j=m-2 while(j >= 0 and ar1[j] > ar2[i]): ar1[j+1] = ar1[j] j-=1 # If there was a greater element if (j != m-2 or last > ar2[i]): ar1[j+1] = ar2[i] ar2[i] = last # Driver program ar1 = [1, 5, 9, 10, 15, 20]ar2 = [2, 3, 8, 13]m = len(ar1)n = len(ar2) merge(ar1, ar2, m, n) print(\"After Merging \\nFirst Array:\", end=\"\")for i in range(m): print(ar1[i] , \" \", end=\"\") print(\"\\nSecond Array: \", end=\"\")for i in range(n): print(ar2[i] , \" \", end=\"\") # This code is contributed# by Anant Agarwal.",
"e": 47627,
"s": 46584,
"text": null
},
{
"code": "// C# program to merge two// sorted arrays with O(1) extra space.using System; // Java program program to merge two// sorted arrays with O(1) extra space. public class Test{ static int []arr1 = new int[]{1, 5, 9, 10, 15, 20}; static int []arr2 = new int[]{2, 3, 8, 13}; static void merge(int m, int n) { // Iterate through all elements of ar2[] starting from // the last element for (int i=n-1; i>=0; i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ int j, last = arr1[m-1]; for (j=m-2; j >= 0 && arr1[j] > arr2[i]; j--) arr1[j+1] = arr1[j]; // If there was a greater element if (j != m-2 || last > arr2[i]) { arr1[j+1] = arr2[i]; arr2[i] = last; } } } // Driver method to test the above function public static void Main() { merge(arr1.Length,arr2.Length); Console.Write(\"After Merging \\nFirst Array: \"); for(int i =0; i< arr1.Length;i++){ Console.Write(arr1[i]+\" \"); } Console.Write(\"\\nSecond Array: \"); for(int i =0; i< arr2.Length;i++){ Console.Write(arr2[i]+\" \"); } }} /*This code is contributed by 29AjayKumar*/",
"e": 49033,
"s": 47627,
"text": null
},
{
"code": "<?php// PHP program to merge two sorted arrays with O(1) extra space. // Merge ar1[] and ar2[] with O(1) extra spacefunction merge(&$ar1, &$ar2, $m, $n){ // Iterate through all elements of ar2[] starting from // the last element for ($i = $n-1; $i >= 0; $i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ $last = $ar1[$m-1]; for ($j = $m-2; $j >= 0 && $ar1[$j] > $ar2[$i]; $j--) $ar1[$j+1] = $ar1[$j]; // If there was a greater element if ($j != $m-2 || $last > $ar2[$i]) { $ar1[$j+1] = $ar2[$i]; $ar2[$i] = $last; } }} // Driver program $ar1 = array(1, 5, 9, 10, 15, 20);$ar2 = array(2, 3, 8, 13);$m = sizeof($ar1)/sizeof($ar1[0]);$n = sizeof($ar2)/sizeof($ar2[0]);merge($ar1, $ar2, $m, $n); echo \"After Merging \\nFirst Array: \";for ($i=0; $i<$m; $i++) echo $ar1[$i] . \" \";echo \"\\nSecond Array: \";for ($i=0; $i<$n; $i++) echo $ar2[$i] .\" \";return 0;?>",
"e": 50107,
"s": 49033,
"text": null
},
{
"code": "<script> // Javascript program to merge two// sorted arrays with O(1) extra space. let arr1=[1, 5, 9, 10, 15, 20]; let arr2=[2, 3, 8, 13]; function merge(m,n) { // Iterate through all elements of ar2[] starting from // the last element for (let i=n-1; i>=0; i--) { /* Find the smallest element greater than ar2[i]. Move all elements one position ahead till the smallest greater element is not found */ let j, last = arr1[m-1]; for (j=m-2; j >= 0 && arr1[j] > arr2[i]; j--) arr1[j+1] = arr1[j]; // If there was a greater element if (j != m-2 || last > arr2[i]) { arr1[j+1] = arr2[i]; arr2[i] = last; } } } // Driver method to test the above function merge(arr1.length,arr2.length); document.write(\"After Merging <br>First Array: \"); for(let i=0;i<arr1.length;i++) { document.write(arr1[i]+\" \"); } document.write(\"<br>Second Array: \"); for(let i=0;i<arr2.length;i++) { document.write(arr2[i]+\" \"); } // This code is contributed by avanitrachhadiya2155 </script>",
"e": 51348,
"s": 50107,
"text": null
},
{
"code": null,
"e": 51416,
"s": 51348,
"text": "After Merging nFirst Array: 1 2 3 5 8 9 nSecond Array: 10 13 15 20 "
},
{
"code": null,
"e": 51425,
"s": 51416,
"text": "Output: "
},
{
"code": null,
"e": 51492,
"s": 51425,
"text": "After Merging \nFirst Array: 1 2 3 5 8 9 \nSecond Array: 10 13 15 20"
},
{
"code": null,
"e": 51658,
"s": 51492,
"text": "Time Complexity: The worst case time complexity of code/algorithm is O(m*n). The worst case occurs when all elements of ar1[] are greater than all elements of ar2[]."
},
{
"code": null,
"e": 51673,
"s": 51658,
"text": "Illustration: "
},
{
"code": null,
"e": 52346,
"s": 51673,
"text": "<!— Initial Arrays: ar1[] = {1, 5, 9, 10, 15, 20}; ar2[] = {2, 3, 8, 13};After First Iteration: ar1[] = {1, 5, 9, 10, 13, 15}; ar2[] = {2, 3, 8, 20}; // 20 is moved from ar1[] to ar2[] // 13 from ar2[] is inserted in ar1[]After Second Iteration: ar1[] = {1, 5, 8, 9, 10, 13}; ar2[] = {2, 3, 15, 20}; // 15 is moved from ar1[] to ar2[] // 8 from ar2[] is inserted in ar1[]After Third Iteration: ar1[] = {1, 3, 5, 8, 9, 10}; ar2[] = {2, 13, 15, 20}; // 13 is moved from ar1[] to ar2[] // 3 from ar2[] is inserted in ar1[]After Fourth Iteration: ar1[] = {1, 2, 3, 5, 8, 9}; ar2[] = {10, 13, 15, 20}; // 10 is moved from ar1[] to ar2[] // 2 from ar2[] is inserted in ar1[] —!>"
},
{
"code": null,
"e": 52356,
"s": 52346,
"text": "Method 2:"
},
{
"code": null,
"e": 52688,
"s": 52356,
"text": "The solution can be further optimized by observing that while traversing the two sorted arrays parallelly, if we encounter the jth second array element is smaller than ith first array element, then jth element is to be included and replace some kth element in the first array. This observation helps us with the following algorithm"
},
{
"code": null,
"e": 52698,
"s": 52688,
"text": "Algorithm"
},
{
"code": null,
"e": 53011,
"s": 52698,
"text": "1) Initialize i,j,k as 0,0,n-1 where n is size of arr1 \n2) Iterate through every element of arr1 and arr2 using two pointers i and j respectively\n if arr1[i] is less than arr2[j]\n increment i\n else\n swap the arr2[j] and arr1[k]\n increment j and decrement k\n\n3) Sort both arr1 and arr2 "
},
{
"code": null,
"e": 53058,
"s": 53011,
"text": "Below is the implementation of above algorithm"
},
{
"code": null,
"e": 53062,
"s": 53058,
"text": "C++"
},
{
"code": null,
"e": 53067,
"s": 53062,
"text": "Java"
},
{
"code": null,
"e": 53075,
"s": 53067,
"text": "Python3"
},
{
"code": null,
"e": 53078,
"s": 53075,
"text": "C#"
},
{
"code": null,
"e": 53089,
"s": 53078,
"text": "Javascript"
},
{
"code": "// CPP program for the above approach#include <bits/stdc++.h>using namespace std; // Function to merge two arraysvoid merge(int arr1[], int arr2[], int n, int m){ int i = 0, j = 0, k = n - 1; // Until i less than equal to k // or j is less than m while (i <= k && j < m) { if (arr1[i] < arr2[j]) i++; else { swap(arr2[j++], arr1[k--]); } } // Sort first array sort(arr1, arr1 + n); // Sort second array sort(arr2, arr2 + m);} // Driver Codeint main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << \"After Merging \\nFirst Array: \"; for (int i = 0; i < m; i++) cout << ar1[i] << \" \"; cout << \"\\nSecond Array: \"; for (int i = 0; i < n; i++) cout << ar2[i] << \" \"; return 0;}",
"e": 54013,
"s": 53089,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Arrays;import java.util.Collections; class GFG { static int arr1[] = new int[] { 1, 5, 9, 10, 15, 20 }; static int arr2[] = new int[] { 2, 3, 8, 13 }; // Function to merge two arrays static void merge(int m, int n) { int i = 0, j = 0, k = m - 1; while (i <= k && j < n) { if (arr1[i] < arr2[j]) i++; else { int temp = arr2[j]; arr2[j] = arr1[k]; arr1[k] = temp; j++; k--; } } Arrays.sort(arr1); Arrays.sort(arr2); } public static void main(String[] args) { merge(arr1.length, arr2.length); System.out.print(\"After Merging \\nFirst Array: \"); System.out.println(Arrays.toString(arr1)); System.out.print(\"Second Array: \"); System.out.println(Arrays.toString(arr2)); }}",
"e": 54957,
"s": 54013,
"text": null
},
{
"code": "# Python program for the above approacharr1 = [1, 5, 9, 10, 15, 20 ];arr2 = [2, 3, 8, 13 ]; # Function to merge two arraysdef merge(m, n): i = 0; j = 0; k = n - 1; while (i <= k and j < m): if (arr1[i] < arr2[j]): i+=1; else: temp = arr2[j]; arr2[j] = arr1[k]; arr1[k] = temp; j += 1; k -= 1; arr1.sort(); arr2.sort(); # Driver codeif __name__ == '__main__': merge(len(arr1), len(arr2)); print(\"After Merging \\nFirst Array: \"); print(','.join(str(x) for x in arr1)); print(\"Second Array: \"); print(','.join(str(x) for x in arr2)); # This code is contributed by gauravrajput1",
"e": 55659,
"s": 54957,
"text": null
},
{
"code": "// C# program for the above approachusing System; public class GFG { static int []arr1 ={ 1, 5, 9, 10, 15, 20 }; static int []arr2 = { 2, 3, 8, 13 }; // Function to merge two arrays static void merge(int m, int n) { int i = 0, j = 0, k = n - 1; while (i <= k && j < m) { if (arr1[i] < arr2[j]) i++; else { int temp = arr2[j]; arr2[j] = arr1[k]; arr1[k] = temp; j++; k--; } } Array.Sort(arr1); Array.Sort(arr2); } public static void Main(String[] args) { merge(arr1.Length, arr2.Length); Console.Write(\"After Merging \\nFirst Array: \"); foreach(int i in arr1){ Console.Write(i+\" \"); } Console.Write(\"\\nSecond Array: \"); foreach(int i in arr2){ Console.Write(i+\" \"); } }} // This code is contributed by gauravrajput1",
"e": 56489,
"s": 55659,
"text": null
},
{
"code": "<script>// javascript program for the above approachvar arr1 = [ 1, 5, 9, 10, 15, 20 ]; var arr2 = [ 2, 3, 8, 13 ]; // Function to merge two arrays function merge(m , n) { var i = 0, j = 0, k = n - 1; while (i <= k && j < m) { if (arr1[i] < arr2[j]) i++; else { var temp = arr2[j]; arr2[j] = arr1[k]; arr1[k] = temp; j++; k--; } } arr1.sort((a,b)=>a-b); arr2.sort((a,b)=>a-b); } merge(arr1.length, arr2.length); document.write(\"After Merging <br/>First Array:<br/> \"); for(var a of arr1) document.write(a+\" \"); document.write(\"<br/>Second Array: <br/> \"); for(var a of arr2) document.write(a+\" \"); // This code is contributed by gauravrajput1</script>",
"e": 57367,
"s": 56489,
"text": null
},
{
"code": null,
"e": 57435,
"s": 57367,
"text": "After Merging \nFirst Array: 1 2 3 5 8 9 \nSecond Array: 10 13 15 20 "
},
{
"code": null,
"e": 57449,
"s": 57435,
"text": "Complexities:"
},
{
"code": null,
"e": 57654,
"s": 57449,
"text": "Time Complexity: The time complexity while traversing the arrays in while loop is O(n+m) in worst case and sorting is O(nlog(n) + mlog(m)). So overall time complexity of the code becomes O((n+m)log(n+m))."
},
{
"code": null,
"e": 57766,
"s": 57654,
"text": "Space Complexity: As the function doesn’t use any extra array for any operations, the space complexity is O(1)."
},
{
"code": null,
"e": 57776,
"s": 57766,
"text": "Method 3:"
},
{
"code": null,
"e": 57787,
"s": 57776,
"text": "Algorithm:"
},
{
"code": null,
"e": 58049,
"s": 57787,
"text": "1) Initialize i with 0\n2) Iterate while loop until last element of array 1 is greater than first element of array 2\n if arr1[i] greater than first element of arr2\n swap arr1[i] with arr2[0]\n sort arr2\n incrementing i "
},
{
"code": null,
"e": 58053,
"s": 58049,
"text": "C++"
},
{
"code": null,
"e": 58058,
"s": 58053,
"text": "Java"
},
{
"code": null,
"e": 58066,
"s": 58058,
"text": "Python3"
},
{
"code": null,
"e": 58069,
"s": 58066,
"text": "C#"
},
{
"code": null,
"e": 58080,
"s": 58069,
"text": "Javascript"
},
{
"code": "#include<iostream>#include<bits/stdc++.h>using namespace std; void merge(int arr1[], int arr2[], int n, int m) { int i=0; // while loop till last element of array 1(sorted) is greater than // first element of array 2(sorted) while(arr1[n-1]>arr2[0]) { if(arr1[i]>arr2[0]) { // swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) swap(arr1[i],arr2[0]); sort(arr2,arr2+m); } i++; } } int main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << \"After Merging \\nFirst Array: \"; for (int i = 0; i < m; i++) cout << ar1[i] << \" \"; cout << \"\\nSecond Array: \"; for (int i = 0; i < n; i++) cout << ar2[i] << \" \"; return 0; }",
"e": 59083,
"s": 58080,
"text": null
},
{
"code": "import java.io.*;import java.util.Arrays;import java.util.Collections; class GFG{ static int arr1[] = new int[]{ 1, 5, 9, 10, 15, 20 };static int arr2[] = new int[]{ 2, 3, 8, 13 }; static void merge(int n, int m){ int i = 0; int temp = 0; // While loop till last element // of array 1(sorted) // is greater than first element // of array 2(sorted) while (arr1[n - 1] > arr2[0]) { if (arr1[i] > arr2[0]) { // Swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) // swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; Arrays.sort(arr2); } i++; }} // Driver codepublic static void main(String[] args){ merge(arr1.length, arr2.length); System.out.print(\"After Merging \\nFirst Array: \"); System.out.println(Arrays.toString(arr1)); System.out.print(\"Second Array: \"); System.out.println(Arrays.toString(arr2));}} // This code is contributed by Aakash Tiwari(nighteagle)",
"e": 60198,
"s": 59083,
"text": null
},
{
"code": "arr1 = [1, 5, 9, 10, 15, 20 ];arr2 =[ 2, 3, 8, 13 ]; def merge(n, m): i = 0; temp = 0; # While loop till last element # of array 1(sorted) # is greater than first element # of array 2(sorted) while (arr1[n - 1] > arr2[0]): if (arr1[i] > arr2[0]): # Swap arr1[i] with first element # of arr2 and sorting the updated # arr2(arr1 is already sorted) # swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; arr2.sort(); i+=1; # Driver codeif __name__ == '__main__': merge(len(arr1), len(arr2)); print(\"After Merging \\nFirst Array: \"); print((arr1)); print(\"Second Array: \"); print((arr2)); # This code contributed by gauravrajput1",
"e": 61003,
"s": 60198,
"text": null
},
{
"code": "using System; public class GFG { static int []arr1 = new int[] { 1, 5, 9, 10, 15, 20 }; static int []arr2 = new int[] { 2, 3, 8, 13 }; static void merge(int n, int m) { int i = 0; int temp = 0; // While loop till last element // of array 1(sorted) // is greater than first element // of array 2(sorted) while (arr1[n - 1] > arr2[0]) { if (arr1[i] > arr2[0]) { // Swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) // swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; Array.Sort(arr2); } i++; } } // Driver code public static void Main(String[] args) { merge(arr1.Length, arr2.Length); Console.Write(\"After Merging \\nFirst Array: \"); foreach(int i in arr1) Console.Write(i+\" \"); Console.Write(\"\\nSecond Array: \"); foreach(int i in arr2) Console.Write(i+\" \"); }} // This code is contributed by gauravrajput1",
"e": 62175,
"s": 61003,
"text": null
},
{
"code": "<script> var arr1 = [1, 5, 9, 10, 15, 20 ]; var arr2 =[2, 3, 8, 13 ]; function merge(n , m) { var i = 0; var temp = 0; // While loop till last element // of array 1(sorted) // is greater than first element // of array 2(sorted) while (arr1[n - 1] > arr2[0]) { if (arr1[i] > arr2[0]) { // Swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) // swap(arr1[i],arr2[0]); temp = arr1[i]; arr1[i] = arr2[0]; arr2[0] = temp; arr2.sort((a,b)=>a-b); } i++; } } // Driver code merge(arr1.length, arr2.length); document.write(\"After Merging <br\\>First Array: \"); document.write(arr1.toString()); document.write(\"<br\\>Second Array: \"); document.write(arr2.toString()); // This code is contributed by umadevi9616</script>",
"e": 63197,
"s": 62175,
"text": null
},
{
"code": null,
"e": 63265,
"s": 63197,
"text": "After Merging \nFirst Array: 1 2 3 5 8 9 \nSecond Array: 10 13 15 20 "
},
{
"code": null,
"e": 63325,
"s": 63265,
"text": "Efficiently merging two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 63394,
"s": 63325,
"text": "Method 4: Let length of shorter array be ‘m’ and larger array be ‘n’"
},
{
"code": null,
"e": 63575,
"s": 63394,
"text": "Step 1: Select the shorter array and find the index at which partition should be done. Similar to this https://www.geeksforgeeks.org/median-of-two-sorted-arrays-of-different-sizes/"
},
{
"code": null,
"e": 63644,
"s": 63575,
"text": " Step 1: Partition the shorter array at its median (l1)."
},
{
"code": null,
"e": 63719,
"s": 63644,
"text": " Step 2: Select the first n-l1 elements from the second array."
},
{
"code": null,
"e": 63773,
"s": 63719,
"text": " Step 3: Compare the border elements i.e."
},
{
"code": null,
"e": 63848,
"s": 63773,
"text": " if l1 < r2 and l2 < r2 we have found the index"
},
{
"code": null,
"e": 63930,
"s": 63848,
"text": " else if l1 > r2 we have to search in the left subarray"
},
{
"code": null,
"e": 64002,
"s": 63930,
"text": " else we have to search in the right subarray"
},
{
"code": null,
"e": 64078,
"s": 64002,
"text": "NOTE : This step will store all the smallest elements in the shorter array."
},
{
"code": null,
"e": 64200,
"s": 64078,
"text": "Step 2: Swap all the elements right to the index(i) of the shorter array with the first n-i elements of the larger array."
},
{
"code": null,
"e": 64230,
"s": 64200,
"text": "Step 3: Sort both the arrays."
},
{
"code": null,
"e": 64385,
"s": 64230,
"text": "::::: if len(arr1) > len(arr2) all the smallest elements are stored in arr2 so we have to move all the elements in arr1 since we have to print arr1 first."
},
{
"code": null,
"e": 64464,
"s": 64385,
"text": " Step 4: Rotate the larger array (arr1) m times counter-clockwise."
},
{
"code": null,
"e": 64531,
"s": 64464,
"text": " Step 5: Swap the first m elements of both the arrays."
},
{
"code": null,
"e": 64535,
"s": 64531,
"text": "C++"
},
{
"code": null,
"e": 64540,
"s": 64535,
"text": "Java"
},
{
"code": null,
"e": 64548,
"s": 64540,
"text": "Python3"
},
{
"code": null,
"e": 64551,
"s": 64548,
"text": "C#"
},
{
"code": null,
"e": 64562,
"s": 64551,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void swap(int& a, int& b){ int temp = a; a = b; b = temp;} void rotate(int a[], int n, int idx){ int i; for (i = 0; i < idx / 2; i++) swap(a[i], a[idx - 1 - i]); for (i = idx; i < (n + idx) / 2; i++) swap(a[i], a[n - 1 - (i - idx)]); for (i = 0; i < n / 2; i++) swap(a[i], a[n - 1 - i]);} void sol(int a1[], int a2[], int n, int m){ int l = 0, h = n - 1, idx = 0; //--------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray int c1 = (l + h) / 2; // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array int c2 = n - c1 - 1; int l1 = a1[c1]; int l2 = a2[c2 - 1]; int r1 = c1 == n - 1 ? INT_MAX : a1[c1 + 1]; int r2 = c2 == m ? INT_MAX : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (int i = idx; i < n; i++) swap(a1[i], a2[i - idx]); sort(a1, a1 + n); sort(a2, a2 + m);} void merge(int arr1[], int arr2[], int n, int m){ // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (int i = 0; i < m; i++) swap(arr2[i], arr1[i]); } else { sol(arr1, arr2, n, m); }} int main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << \"After Merging \\nFirst Array: \"; for (int i = 0; i < m; i++) cout << ar1[i] << \" \"; cout << \"\\nSecond Array: \"; for (int i = 0; i < n; i++) cout << ar2[i] << \" \"; return 0;}",
"e": 66653,
"s": 64562,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ static void swap(int a, int b){ int temp = a; a = b; b = temp;} static void rotate(int a[], int n, int idx){ int i; for (i = 0; i < idx / 2; i++) swap(a[i], a[idx - 1 - i]); for (i = idx; i < (n + idx) / 2; i++) swap(a[i], a[n - 1 - (i - idx)]); for (i = 0; i < n / 2; i++) swap(a[i], a[n - 1 - i]);} static void sol(int a1[], int a2[], int n, int m){ int l = 0, h = n - 1, idx = 0; //--------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray int c1 = (int)(l + h) / 2; // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array int c2 = n - c1 - 1; int l1 = a1[c1]; int l2 = a2[c2 - 1]; int r1 = (c1 == n - 1) ? Integer.MAX_VALUE : a1[c1 + 1]; int r2 = (c2 == m) ? Integer.MAX_VALUE : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (int i = idx; i < n; i++) swap(a1[i], a2[i - idx]); Arrays.sort(a1); Arrays.sort(a2);} static void merge(int arr1[], int arr2[], int n, int m){ // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (int i = 0; i < m; i++) swap(arr2[i], arr1[i]); } else { sol(arr1, arr2, n, m); }} // Driver Codepublic static void main (String[] args){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = ar1.length; int n = ar2.length; merge(ar1, ar2, m, n); System.out.print(\"After Merging \\nFirst Array: \"); for (int i = 0; i < m; i++) System.out.print(ar1[i] + \" \"); System.out.print(\"\\nSecond Array: \"); for (int i = 0; i < n; i++) System.out.print(ar2[i] + \" \"); }} // This code is contributed by sanjoy_62.",
"e": 68897,
"s": 66653,
"text": null
},
{
"code": "# Python program to merge# two sorted arrays# with O(1) extra space. # Merge ar1[] and ar2[]# with O(1) extra space def rotate(a, n, idx): for i in range((int)(idx/2)): a[i], a[idx-1-i] = a[idx-1-i], a[i] for i in range(idx, (int)((n+idx)/2)): a[i], a[n-1-(i-idx)] = a[n-1-(i-idx)], a[i] for i in range((int)(n/2)): a[i], a[n-1-i] = a[n-1-i], a[i] def sol(a1, a2, n, m): l = 0 h = n-1 idx = 0 while (l <= h): c1 = (int)((l+h)/2) c2 = n-c1-1 l1 = a1[c1] l2 = a2[c2-1] r1 = sys.maxint if c1 == n-1 else a1[c1+1] r2 = sys.maxint if c2 == m else a2[c2] if l1 > r2: h = c1-1 if h == -1: idx = 0 elif l2 > r1: l = c1+1 if l == n-1: idx = n else: idx = c1+1 break for i in range(idx, n): a1[i], a2[i-idx] = a2[i-idx], a1[i] a1.sort() a2.sort() def merge(a1, a2, n, m): if n > m: sol(a2, a1, m, n) rotate(a1, n, n-m) for i in range(m): a1[i], a2[i] = a2[i], a1[i] else: sol(a1, a2, n, m)# Driver program ar1 = [1, 5, 9, 10, 15, 20]ar2 = [2, 3, 8, 13]m = len(ar1)n = len(ar2) merge(ar1, ar2, m, n) print(\"After Merging \\nFirst Array:\", end=\"\")for i in range(m): print(ar1[i], \" \", end=\"\")print(\"\\nSecond Array: \", end=\"\")for i in range(n): print(ar2[i], \" \", end=\"\")# This code is contributed# by Aditya Anand.",
"e": 70372,
"s": 68897,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG { static void swap(int a, int b) { int temp = a; a = b; b = temp; } static void rotate(int []a, int n, int idx) { int i; for (i = 0; i < idx / 2; i++) swap(a[i], a[idx - 1 - i]); for (i = idx; i < (n + idx) / 2; i++) swap(a[i], a[n - 1 - (i - idx)]); for (i = 0; i < n / 2; i++) swap(a[i], a[n - 1 - i]); } static void sol(int []a1, int []a2, int n, int m) { int l = 0, h = n - 1, idx = 0; // --------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray int c1 = (int) (l + h) / 2; // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array int c2 = n - c1 - 1; int l1 = a1[c1]; int l2 = a2[c2 - 1]; int r1 = (c1 == n - 1) ? int.MaxValue : a1[c1 + 1]; int r2 = (c2 == m) ? int.MaxValue : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (int i = idx; i < n; i++) swap(a1[i], a2[i - idx]); Array.Sort(a1); Array.Sort(a2); } static void merge(int []arr1, int []arr2, int n, int m) { // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (int i = 0; i < m; i++) swap(arr2[i], arr1[i]); } else { sol(arr1, arr2, n, m); } } // Driver Code public static void Main(String[] args) { int []ar1 = { 1, 5, 9, 10, 15, 20 }; int []ar2 = { 2, 3, 8, 13 }; int m = ar1.Length; int n = ar2.Length; merge(ar1, ar2, m, n); Console.Write(\"After Merging \\nFirst Array: \"); for (int i = 0; i < m; i++) Console.Write(ar1[i] + \" \"); Console.Write(\"\\nSecond Array: \"); for (int i = 0; i < n; i++) Console.Write(ar2[i] + \" \"); }} // This code contributed by gauravrajput1",
"e": 72907,
"s": 70372,
"text": null
},
{
"code": "<script>// javascript program for the above approach function swap(a , b) { var temp = a; a = b; b = temp; } function rotate(a , n , idx) { var i; for (i = 0; i < idx / 2; i++) { var temp =a[i] a[i]= a[idx - 1 - i]; a[idx - 1 - i] = temp; } for (i = idx; i < (n + idx) / 2; i++) { var temp =a[i] a[i]= a[n - 1 - (i - idx)]; a[n - 1 - (i - idx)] = temp; } for (i = 0; i < n / 2; i++) { var temp =a[i] a[i]= a[n - 1 - i]; a[n - 1 - i] = temp; } } function sol(a1 , a2 , n , m) { var l = 0, h = n - 1, idx = 0; // --------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray var c1 = parseInt( (l + h) / 2); // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array var c2 = n - c1 - 1; var l1 = a1[c1]; var l2 = a2[c2 - 1]; var r1 = (c1 == n - 1) ? Number.MAX_VALUE : a1[c1 + 1]; var r2 = (c2 == m) ? Number.MAX_VALUE : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (i = idx; i < n; i++) { var temp =a1[i] a1[i]= a2[i - idx]; a2[i - idx] = temp; } a1.sort((a,b)=>a-b); a2.sort((a,b)=>a-b); } function merge(arr1 , arr2 , n , m) { // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (i = 0; i < m; i++) { var temp =arr2[i] arr2[i]= arr1[i]; arr1[i] = temp; } } else { sol(arr1, arr2, n, m); } } // Driver Code var ar1 = [ 1, 5, 9, 10, 15, 20 ]; var ar2 = [ 2, 3, 8, 13 ]; var m = ar1.length; var n = ar2.length; merge(ar1, ar2, m, n); document.write(\"After Merging \\nFirst Array: \"); for (i = 0; i < m; i++) document.write(ar1[i] + \" \"); document.write(\"\\nSecond Array: \"); for (i = 0; i < n; i++) document.write(ar2[i] + \" \"); // This code is contributed by gauravrajput1</script>",
"e": 75710,
"s": 72907,
"text": null
},
{
"code": null,
"e": 75778,
"s": 75710,
"text": "After Merging \nFirst Array: 1 2 3 5 8 9 \nSecond Array: 10 13 15 20 "
},
{
"code": null,
"e": 75816,
"s": 75778,
"text": "Time Complexity: O(min(nlogn, mlogm))"
},
{
"code": null,
"e": 75866,
"s": 75816,
"text": "Method-5 [Insertion Sort with Simultaneous Merge]"
},
{
"code": null,
"e": 75876,
"s": 75866,
"text": "Approach:"
},
{
"code": null,
"e": 76112,
"s": 75876,
"text": "1. sort list 1 by always comparing with head/first of list 2 and swapping if required2. after each head/first swap, perform insertion of the swapped element into correct position in list 2 which will eventually sort list 2 at the end. "
},
{
"code": null,
"e": 76264,
"s": 76112,
"text": "For every swapped item from list 1, perform insertion sort in list 2 to find its correct position so that when list 1 is sorted, list 2 is also sorted."
},
{
"code": null,
"e": 76268,
"s": 76264,
"text": "C++"
},
{
"code": null,
"e": 76273,
"s": 76268,
"text": "Java"
},
{
"code": null,
"e": 76281,
"s": 76273,
"text": "Python3"
},
{
"code": null,
"e": 76284,
"s": 76281,
"text": "C#"
},
{
"code": null,
"e": 76295,
"s": 76284,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void merge(int arr1[], int arr2[], int n, int m){ // two pointer to iterate int i = 0; int j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1[] become sorted then we check that // arr2[j] is smaller then all other element in // right side of arr2[j] if arr2[] is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left swap(arr1[i], arr2[j]); i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { int temp = arr2[j]; int tempj = j + 1; while (arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } }} int main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << \"After Merging \\nFirst Array: \"; for (int i = 0; i < m; i++) cout << ar1[i] << \" \"; cout << \"\\nSecond Array: \"; for (int i = 0; i < n; i++) cout << ar2[i] << \" \"; return 0;}",
"e": 77973,
"s": 76295,
"text": null
},
{
"code": "import java.util.*;class GFG{ static void merge(int arr1[], int arr2[], int n, int m){ // two pointer to iterate int i = 0; int j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1[] become sorted then we check that // arr2[j] is smaller then all other element in // right side of arr2[j] if arr2[] is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left int t = arr1[i]; arr1[i] = arr2[j]; arr2[j] = t; i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { int temp = arr2[j]; int tempj = j + 1; while (tempj<m && arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } }} public static void main(String[] args){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = ar1.length; int n =ar2.length; merge(ar1, ar2, m, n); System.out.print(\"After Merging \\nFirst Array: \"); for (int i = 0; i < m; i++) System.out.print(ar1[i]+ \" \"); System.out.print(\"\\nSecond Array: \"); for (int i = 0; i < n; i++) System.out.print(ar2[i]+ \" \");}} // This code is contributed by gauravrajput1",
"e": 79789,
"s": 77973,
"text": null
},
{
"code": "# code contributed by mahee96 # \"Insertion sort of list 2 with swaps from list 1\"## swap elements to get list 1 correctly, meanwhile# place the swapped item in correct position of list 2# eventually list 2 is also sorted# Time = O(m*n) or O(n*m)# AUX = O(1)def merge(arr1, arr2): x = arr1; y = arr2 end = len(arr1) i = 0 while(i < end): # O(m) or O(n) if(x[i] > y[0]): swap(x,y,i,0) insert(y,0) # O(n) or O(m) number of shifts i+=1 # O(n):def insert(y, i): orig = y[i] i+=1 while (i<len(y) and y[i]<orig): y[i-1] = y[i] i+=1 y[i-1] = orig def swap(x,y,i,j): temp = x[i] x[i] = y[j] y[j] = temp def test(): c1 = [2, 3, 8, 13] c2 = [1, 5, 9, 10, 15, 20 ] for _ in range(2): merge(c1,c2) print(c1,c2) c1, c2 = c2, c1 test()",
"e": 80651,
"s": 79789,
"text": null
},
{
"code": "using System; public class GFG { static void merge(int []arr1, int []arr2, int n, int m) { // two pointer to iterate int i = 0; int j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1[] become sorted then we check that // arr2[j] is smaller then all other element in // right side of arr2[j] if arr2[] is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left int t = arr1[i]; arr1[i] = arr2[j]; arr2[j] = t; i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { int temp = arr2[j]; int tempj = j + 1; while (tempj < m && arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } } } public static void Main(String[] args) { int []ar1 = { 1, 5, 9, 10, 15, 20 }; int []ar2 = { 2, 3, 8, 13 }; int m = ar1.Length; int n = ar2.Length; merge(ar1, ar2, m, n); Console.Write(\"After Merging \\nFirst Array: \"); for (int i = 0; i < m; i++) Console.Write(ar1[i] + \" \"); Console.Write(\"\\nSecond Array: \"); for (int i = 0; i < n; i++) Console.Write(ar2[i] + \" \"); }} // This code is contributed by gauravrajput1",
"e": 82628,
"s": 80651,
"text": null
},
{
"code": "<script> function merge(arr1 , arr2 , n , m) { // two pointer to iterate var i = 0; var j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1 become sorted then we check that // arr2[j] is smaller then all other element in // right side of arr2[j] if arr2 is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left var t = arr1[i]; arr1[i] = arr2[j]; arr2[j] = t; i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { var temp = arr2[j]; var tempj = j + 1; while (tempj < m && arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } } } var ar1 = [ 1, 5, 9, 10, 15, 20 ]; var ar2 = [ 2, 3, 8, 13 ]; var m = ar1.length; var n = ar2.length; merge(ar1, ar2, m, n); document.write(\"After Merging <br/>First Array: <br/>\"); for (i = 0; i < m; i++) document.write(ar1[i] + \" \"); document.write(\"<br/>Second Array: <br/>\"); for (i = 0; i < n; i++) document.write(ar2[i] + \" \"); // This code contributed by gauravrajput1</script>",
"e": 84525,
"s": 82628,
"text": null
},
{
"code": null,
"e": 84593,
"s": 84525,
"text": "After Merging \nFirst Array: 1 2 3 5 8 9 \nSecond Array: 10 13 15 20 "
},
{
"code": null,
"e": 84727,
"s": 84593,
"text": "Time Complexity: O(m*n) list 1 traversal and list 2 insertionsAuxiliary Space: O(1)If m == n: Time = O(n^2) insertion sort complexity"
},
{
"code": null,
"e": 84769,
"s": 84727,
"text": "Method-6 [Using Euclidean Division Lemma]"
},
{
"code": null,
"e": 84779,
"s": 84769,
"text": "Approach:"
},
{
"code": null,
"e": 85113,
"s": 84779,
"text": "Just merge the two arrays as we do in merge sort, while simultaneously using Euclidean Division Lemma, i.e. (((Operation on array) % x) * x). And at least after merging divide both the arrays with x. Where x needs to be a number greater than all elements of array. Here in this case x, (according to the constraints) can be 10e7 + 1."
},
{
"code": null,
"e": 85117,
"s": 85113,
"text": "C++"
},
{
"code": "// C++ program to merge two sorted arrays without using extra space#include <bits/stdc++.h> using namespace std; void merge(int arr1[], int arr2[], int n, int m){ // three pointers to iterate int i = 0, j = 0, k = 0; // for euclid's division lemma int x = 10e7 + 1; // in this loop we are rearranging the elements of arr1 while (i < n && (j < n && k < m)) { // if both arr1 and arr2 elements are modified if (arr1[j] >= x && arr2[k] >= x) { if (arr1[j] % x <= arr2[k] % x) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if only arr1 elements are modified else if (arr1[j] >= x) { if (arr1[j] % x <= arr2[k]) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if only arr2 elements are modified else if (arr2[k] >= x) { if (arr1[j] <= arr2[k] % x) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if none elements are modified else { if (arr1[j] <= arr2[k]) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } i++; } // we can copy the elements directly as the other array // is exchausted while (j < n && i < n) { arr1[i++] += (arr1[j++] % x) * x; } while (k < m && i < n) { arr1[i++] += (arr2[k++] % x) * x; } // we need to reset i i = 0; // in this loop we are rearranging the elements of arr2 while (i < m && (j < n && k < m)) { // if both arr1 and arr2 elements are modified if (arr1[j] >= x && arr2[k] >= x) { if (arr1[j] % x <= arr2[k] % x) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } // if only arr1 elements are modified else if (arr1[j] >= x) { if (arr1[j] % x <= arr2[k]) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } // if only arr2 elements are modified else if (arr2[k] >= x) { if (arr1[j] <= arr2[k] % x) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } else { // if none elements are modified if (arr1[j] <= arr2[k]) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } i++; } // we can copy the elements directly as the other array // is exhausted while (j < n && i < m) { arr2[i++] += (arr1[j++] % x) * x; } while (k < m && i < m) { arr2[i++] += (arr2[k++] % x) * x; } // we need to reset i i = 0; // we need to divide the whole arr1 by x while (i < n) { arr1[i++] /= x; } // we need to reset i i = 0; // we need to divide the whole arr2 by x while (i < m) { arr2[i++] /= x; }} int main(){ int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << \"After Merging \\nFirst Array: \"; for (int i = 0; i < m; i++) cout << ar1[i] << \" \"; cout << \"\\nSecond Array: \"; for (int i = 0; i < n; i++) cout << ar2[i] << \" \"; return 0;}// This code is contributed by @ancientmoon8 (Mayank Kashyap)",
"e": 88950,
"s": 85117,
"text": null
},
{
"code": null,
"e": 89018,
"s": 88950,
"text": "After Merging \nFirst Array: 1 2 3 5 8 9 \nSecond Array: 10 13 15 20 "
},
{
"code": null,
"e": 89044,
"s": 89018,
"text": "Time Complexity: O(m + n)"
},
{
"code": null,
"e": 89066,
"s": 89044,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 89360,
"s": 89066,
"text": "Related Articles : Merge two sorted arrays Merge k sorted arrays | Set 1Thanks to Shubham Chauhan for suggesting 1st solution and Himanshu Kaushik for the 2nd solution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 89366,
"s": 89360,
"text": "ukasp"
},
{
"code": null,
"e": 89378,
"s": 89366,
"text": "29AjayKumar"
},
{
"code": null,
"e": 89396,
"s": 89378,
"text": "akhilkhubchandani"
},
{
"code": null,
"e": 89411,
"s": 89396,
"text": "chaitanyamunje"
},
{
"code": null,
"e": 89428,
"s": 89411,
"text": "HimanshuKaushik2"
},
{
"code": null,
"e": 89449,
"s": 89428,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 89466,
"s": 89449,
"text": "14parikshitsingh"
},
{
"code": null,
"e": 89483,
"s": 89466,
"text": "adityaanand12017"
},
{
"code": null,
"e": 89494,
"s": 89483,
"text": "nighteagle"
},
{
"code": null,
"e": 89506,
"s": 89494,
"text": "ajaymakvana"
},
{
"code": null,
"e": 89514,
"s": 89506,
"text": "mahee96"
},
{
"code": null,
"e": 89527,
"s": 89514,
"text": "sivananth321"
},
{
"code": null,
"e": 89541,
"s": 89527,
"text": "sumitgumber28"
},
{
"code": null,
"e": 89555,
"s": 89541,
"text": "architgwl2000"
},
{
"code": null,
"e": 89569,
"s": 89555,
"text": "GauravRajput1"
},
{
"code": null,
"e": 89577,
"s": 89569,
"text": "clintra"
},
{
"code": null,
"e": 89589,
"s": 89577,
"text": "umadevi9616"
},
{
"code": null,
"e": 89599,
"s": 89589,
"text": "sanjoy_62"
},
{
"code": null,
"e": 89618,
"s": 89599,
"text": "surindertarika1234"
},
{
"code": null,
"e": 89633,
"s": 89618,
"text": "sudhanshublaze"
},
{
"code": null,
"e": 89646,
"s": 89633,
"text": "ancientmoon8"
},
{
"code": null,
"e": 89655,
"s": 89646,
"text": "sweetyty"
},
{
"code": null,
"e": 89662,
"s": 89655,
"text": "Amazon"
},
{
"code": null,
"e": 89669,
"s": 89662,
"text": "Amdocs"
},
{
"code": null,
"e": 89677,
"s": 89669,
"text": "Brocade"
},
{
"code": null,
"e": 89691,
"s": 89677,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 89706,
"s": 89691,
"text": "Insertion Sort"
},
{
"code": null,
"e": 89723,
"s": 89706,
"text": "Juniper Networks"
},
{
"code": null,
"e": 89732,
"s": 89723,
"text": "Linkedin"
},
{
"code": null,
"e": 89743,
"s": 89732,
"text": "Merge Sort"
},
{
"code": null,
"e": 89753,
"s": 89743,
"text": "Microsoft"
},
{
"code": null,
"e": 89759,
"s": 89753,
"text": "Quikr"
},
{
"code": null,
"e": 89768,
"s": 89759,
"text": "Snapdeal"
},
{
"code": null,
"e": 89777,
"s": 89768,
"text": "Synopsys"
},
{
"code": null,
"e": 89782,
"s": 89777,
"text": "Zoho"
},
{
"code": null,
"e": 89789,
"s": 89782,
"text": "Arrays"
},
{
"code": null,
"e": 89802,
"s": 89789,
"text": "Mathematical"
},
{
"code": null,
"e": 89810,
"s": 89802,
"text": "Sorting"
},
{
"code": null,
"e": 89815,
"s": 89810,
"text": "Zoho"
},
{
"code": null,
"e": 89822,
"s": 89815,
"text": "Amazon"
},
{
"code": null,
"e": 89832,
"s": 89822,
"text": "Microsoft"
},
{
"code": null,
"e": 89841,
"s": 89832,
"text": "Snapdeal"
},
{
"code": null,
"e": 89855,
"s": 89841,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 89864,
"s": 89855,
"text": "Linkedin"
},
{
"code": null,
"e": 89871,
"s": 89864,
"text": "Amdocs"
},
{
"code": null,
"e": 89879,
"s": 89871,
"text": "Brocade"
},
{
"code": null,
"e": 89896,
"s": 89879,
"text": "Juniper Networks"
},
{
"code": null,
"e": 89902,
"s": 89896,
"text": "Quikr"
},
{
"code": null,
"e": 89911,
"s": 89902,
"text": "Synopsys"
},
{
"code": null,
"e": 89918,
"s": 89911,
"text": "Arrays"
},
{
"code": null,
"e": 89931,
"s": 89918,
"text": "Mathematical"
},
{
"code": null,
"e": 89939,
"s": 89931,
"text": "Sorting"
},
{
"code": null,
"e": 89950,
"s": 89939,
"text": "Merge Sort"
},
{
"code": null,
"e": 90048,
"s": 89950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 90063,
"s": 90048,
"text": "Arrays in Java"
},
{
"code": null,
"e": 90079,
"s": 90063,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 90125,
"s": 90079,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 90152,
"s": 90125,
"text": "Program for array rotation"
},
{
"code": null,
"e": 90184,
"s": 90152,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 90214,
"s": 90184,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 90274,
"s": 90214,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 90289,
"s": 90274,
"text": "C++ Data Types"
},
{
"code": null,
"e": 90332,
"s": 90289,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
PYGLET – Drawing Circle - GeeksforGeeks | 25 Aug, 2021
In this article we will see how we can draw circles on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A circle is a shape consisting of all points in a plane that are a given distance from a given point, the centre; equivalently it is the curve traced out by a point that moves in a plane so that its distance from a given point is constant. Circle is drawn with the help of shapes module in pyglet.We can create a window with the help of command given below
# creating a window
window = pyglet.window.Window(width, height, title)
In order to create window we use Circle method with pyglet.shapesSyntax : shapes.Circle(x, y, size, color)Argument : It takes first two integer i.e circle position, third integer as size of circle and forth is tuple i.e color of circle as argumentReturn : It returns Circle object
Below is the implementation
Python3
# importing pyglet moduleimport pyglet # importing shapes from the pygletfrom pyglet import shapes # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # creating a batch objectbatch = pyglet.graphics.Batch() # properties of circle# co-ordinates of circlecircle_x = 250circle_y = 250 # size of circle# color = greensize_circle = 100 # creating a circlecircle1 = shapes.Circle(circle_x, circle_y, size_circle, color =(50, 225, 30), batch = batch) # changing opacity of the circle1# opacity is visibility (0 = invisible, 255 means visible)circle1.opacity = 250 # creating another circle with other properties# new position = circle1_position - 50# new size = previous radius -20# new color = redcircle2 = shapes.Circle(circle_x-50, circle_y-50, size_circle-20, color =(250, 25, 30), batch = batch) # changing opacity of the circle2circle2.opacity = 150 # window draw [email protected] on_draw(): # clear the window window.clear() # draw the batch batch.draw() # run the pyglet applicationpyglet.app.run()
sumitgumber28
Python-gui
Python-Pyglet
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 26268,
"s": 25537,
"text": "In this article we will see how we can draw circles on window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). A circle is a shape consisting of all points in a plane that are a given distance from a given point, the centre; equivalently it is the curve traced out by a point that moves in a plane so that its distance from a given point is constant. Circle is drawn with the help of shapes module in pyglet.We can create a window with the help of command given below "
},
{
"code": null,
"e": 26340,
"s": 26268,
"text": "# creating a window\nwindow = pyglet.window.Window(width, height, title)"
},
{
"code": null,
"e": 26625,
"s": 26342,
"text": "In order to create window we use Circle method with pyglet.shapesSyntax : shapes.Circle(x, y, size, color)Argument : It takes first two integer i.e circle position, third integer as size of circle and forth is tuple i.e color of circle as argumentReturn : It returns Circle object "
},
{
"code": null,
"e": 26655,
"s": 26625,
"text": "Below is the implementation "
},
{
"code": null,
"e": 26663,
"s": 26655,
"text": "Python3"
},
{
"code": "# importing pyglet moduleimport pyglet # importing shapes from the pygletfrom pyglet import shapes # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = \"Geeksforgeeks\" # creating a windowwindow = pyglet.window.Window(width, height, title) # creating a batch objectbatch = pyglet.graphics.Batch() # properties of circle# co-ordinates of circlecircle_x = 250circle_y = 250 # size of circle# color = greensize_circle = 100 # creating a circlecircle1 = shapes.Circle(circle_x, circle_y, size_circle, color =(50, 225, 30), batch = batch) # changing opacity of the circle1# opacity is visibility (0 = invisible, 255 means visible)circle1.opacity = 250 # creating another circle with other properties# new position = circle1_position - 50# new size = previous radius -20# new color = redcircle2 = shapes.Circle(circle_x-50, circle_y-50, size_circle-20, color =(250, 25, 30), batch = batch) # changing opacity of the circle2circle2.opacity = 150 # window draw [email protected] on_draw(): # clear the window window.clear() # draw the batch batch.draw() # run the pyglet applicationpyglet.app.run()",
"e": 27835,
"s": 26663,
"text": null
},
{
"code": null,
"e": 27849,
"s": 27835,
"text": "sumitgumber28"
},
{
"code": null,
"e": 27860,
"s": 27849,
"text": "Python-gui"
},
{
"code": null,
"e": 27874,
"s": 27860,
"text": "Python-Pyglet"
},
{
"code": null,
"e": 27881,
"s": 27874,
"text": "Python"
},
{
"code": null,
"e": 27979,
"s": 27881,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28011,
"s": 27979,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28053,
"s": 28011,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28095,
"s": 28053,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28122,
"s": 28095,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28178,
"s": 28122,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28200,
"s": 28178,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28239,
"s": 28200,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28270,
"s": 28239,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28299,
"s": 28270,
"text": "Create a directory in Python"
}
]
|
List retainAll() Method in Java with Examples - GeeksforGeeks | 02 Jan, 2019
This method is used to retain all the elements present in the collection from the specified collection into the list.
Syntax:
boolean retainAll(Collection c)
Parameters: This method has only argument, collection of which elements are to be retained in the given list.
Returns: This method returns True if elements are retained and list changes.
Below programs show the implementation of this method.
Program 1:
// Java code to show the implementation of// retainAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(1); l.add(3); l.add(5); l.add(7); l.add(9); System.out.println(l); ArrayList<Integer> arr = new ArrayList<>(); arr.add(3); arr.add(5); l.retainAll(arr); System.out.println(l); }}
[1, 3, 5, 7, 9]
[3, 5]
Program 2: Below is the code to show implementation of list.retainAll() using Linkedlist.
// Java code to show the implementation of// retainAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<String> l = new LinkedList<>(); l.add("10"); l.add("30"); l.add("50"); l.add("70"); l.add("90"); System.out.println(l); ArrayList<String> arr = new ArrayList<>(); arr.add("30"); arr.add("50"); l.retainAll(arr); System.out.println(l); }}
[10, 30, 50, 70, 90]
[30, 50]
Reference:Oracle Docs
Java - util package
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 25343,
"s": 25225,
"text": "This method is used to retain all the elements present in the collection from the specified collection into the list."
},
{
"code": null,
"e": 25351,
"s": 25343,
"text": "Syntax:"
},
{
"code": null,
"e": 25383,
"s": 25351,
"text": "boolean retainAll(Collection c)"
},
{
"code": null,
"e": 25493,
"s": 25383,
"text": "Parameters: This method has only argument, collection of which elements are to be retained in the given list."
},
{
"code": null,
"e": 25570,
"s": 25493,
"text": "Returns: This method returns True if elements are retained and list changes."
},
{
"code": null,
"e": 25625,
"s": 25570,
"text": "Below programs show the implementation of this method."
},
{
"code": null,
"e": 25636,
"s": 25625,
"text": "Program 1:"
},
{
"code": "// Java code to show the implementation of// retainAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(1); l.add(3); l.add(5); l.add(7); l.add(9); System.out.println(l); ArrayList<Integer> arr = new ArrayList<>(); arr.add(3); arr.add(5); l.retainAll(arr); System.out.println(l); }}",
"e": 26185,
"s": 25636,
"text": null
},
{
"code": null,
"e": 26209,
"s": 26185,
"text": "[1, 3, 5, 7, 9]\n[3, 5]\n"
},
{
"code": null,
"e": 26299,
"s": 26209,
"text": "Program 2: Below is the code to show implementation of list.retainAll() using Linkedlist."
},
{
"code": "// Java code to show the implementation of// retainAll method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<String> l = new LinkedList<>(); l.add(\"10\"); l.add(\"30\"); l.add(\"50\"); l.add(\"70\"); l.add(\"90\"); System.out.println(l); ArrayList<String> arr = new ArrayList<>(); arr.add(\"30\"); arr.add(\"50\"); l.retainAll(arr); System.out.println(l); }}",
"e": 26867,
"s": 26299,
"text": null
},
{
"code": null,
"e": 26898,
"s": 26867,
"text": "[10, 30, 50, 70, 90]\n[30, 50]\n"
},
{
"code": null,
"e": 26920,
"s": 26898,
"text": "Reference:Oracle Docs"
},
{
"code": null,
"e": 26940,
"s": 26920,
"text": "Java - util package"
},
{
"code": null,
"e": 26957,
"s": 26940,
"text": "Java-Collections"
},
{
"code": null,
"e": 26972,
"s": 26957,
"text": "Java-Functions"
},
{
"code": null,
"e": 26982,
"s": 26972,
"text": "java-list"
},
{
"code": null,
"e": 26987,
"s": 26982,
"text": "Java"
},
{
"code": null,
"e": 26992,
"s": 26987,
"text": "Java"
},
{
"code": null,
"e": 27009,
"s": 26992,
"text": "Java-Collections"
},
{
"code": null,
"e": 27107,
"s": 27009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27122,
"s": 27107,
"text": "Stream In Java"
},
{
"code": null,
"e": 27143,
"s": 27122,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27162,
"s": 27143,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27192,
"s": 27162,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27238,
"s": 27192,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27255,
"s": 27238,
"text": "Generics in Java"
},
{
"code": null,
"e": 27276,
"s": 27255,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27319,
"s": 27276,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27355,
"s": 27319,
"text": "Internal Working of HashMap in Java"
}
]
|
Combinations from n arrays picking one element from each array - GeeksforGeeks | 18 Feb, 2022
Given a list of arrays, find all combinations where each combination contains one element from each given array.
Examples:
Input : [ [1, 2], [3, 4] ]
Output : 1 3
1 4
2 3
2 4
Input : [ [1], [2, 3, 4], [5] ]
Output : 1 2 5
1 3 5
1 4 5
We keep an array of size equal to the total no of arrays. This array called indices helps us keep track of the index of the current element in each of the n arrays. Initially, it is initialized with all 0s indicating the current index in each array is that of the first element. We keep printing the combinations until no new combinations can be found. Starting from the rightmost array we check if more elements are there in that array. If yes, we increment the entry for that array in indices i.e. moves to the next element in that array. We also make the current indices 0 in all the arrays to the right of this array. We keep moving left to check all arrays until one such array is found. If no more arrays are found we stop there.
C++
Java
Python3
C#
Javascript
// C++ program to find combinations from n// arrays such that one element from each// array is present#include <bits/stdc++.h> using namespace std; // function to print combinations that contain// one element from each of the given arraysvoid print(vector<vector<int> >& arr){ // number of arrays int n = arr.size(); // to keep track of next element in each of // the n arrays int* indices = new int[n]; // initialize with first element's index for (int i = 0; i < n; i++) indices[i] = 0; while (1) { // print current combination for (int i = 0; i < n; i++) cout << arr[i][indices[i]] << " "; cout << endl; // find the rightmost array that has more // elements left after the current element // in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].size())) next--; // no such array is found so no more // combinations left if (next < 0) return; // if found move to next element in that // array indices[next]++; // for all arrays to the right of this // array current index again points to // first element for (int i = next + 1; i < n; i++) indices[i] = 0; }} // driver function to test above functionint main(){ // initializing a vector with 3 empty vectors vector<vector<int> > arr(3, vector<int>(0, 0)); // now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].push_back(1); arr[0].push_back(2); arr[0].push_back(3); arr[1].push_back(4); arr[2].push_back(5); arr[2].push_back(6); print(arr);}
// Java program to find combinations from n// arrays such that one element from each// array is presentimport java.util.*; class GFG{ // Function to print combinations that contain// one element from each of the given arraysstatic void print(Vector<Integer> []arr){ // Number of arrays int n = arr.length; // To keep track of next element in // each of the n arrays int []indices = new int[n]; // Initialize with first element's index for(int i = 0; i < n; i++) indices[i] = 0; while (true) { // Print current combination for(int i = 0; i < n; i++) System.out.print( arr[i].get(indices[i]) + " "); System.out.println(); // Find the rightmost array that has more // elements left after the current element // in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].size())) next--; // No such array is found so no more // combinations left if (next < 0) return; // If found move to next element in that // array indices[next]++; // For all arrays to the right of this // array current index again points to // first element for(int i = next + 1; i < n; i++) indices[i] = 0; }} // Driver codepublic static void main(String[] args){ // Initializing a vector with 3 empty vectors @SuppressWarnings("unchecked") Vector<Integer> []arr = new Vector[3]; for(int i = 0; i < arr.length; i++) arr[i] = new Vector<Integer>(); // Now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].add(1); arr[0].add(2); arr[0].add(3); arr[1].add(4); arr[2].add(5); arr[2].add(6); print(arr);}} // This code is contributed by amal kumar choubey
# Python3 program to find combinations from n# arrays such that one element from each# array is present # function to print combinations that contain# one element from each of the given arraysdef print1(arr): # number of arrays n = len(arr) # to keep track of next element # in each of the n arrays indices = [0 for i in range(n)] while (1): # print current combination for i in range(n): print(arr[i][indices[i]], end = " ") print() # find the rightmost array that has more # elements left after the current element # in that array next = n - 1 while (next >= 0 and (indices[next] + 1 >= len(arr[next]))): next-=1 # no such array is found so no more # combinations left if (next < 0): return # if found move to next element in that # array indices[next] += 1 # for all arrays to the right of this # array current index again points to # first element for i in range(next + 1, n): indices[i] = 0 # Driver Code # initializing a vector with 3 empty vectorsarr = [[] for i in range(3)] # now entering data# [[1, 2, 3], [4], [5, 6]]arr[0].append(1)arr[0].append(2)arr[0].append(3)arr[1].append(4)arr[2].append(5)arr[2].append(6) print1(arr) # This code is contributed by mohit kumar
// C# program to find// combinations from n// arrays such that one// element from each// array is presentusing System;using System.Collections.Generic;class GFG{ // Function to print combinations// that contain one element from// each of the given arraysstatic void print(List<int> []arr){ // Number of arrays int n = arr.Length; // To keep track of next // element in each of // the n arrays int []indices = new int[n]; // Initialize with first // element's index for(int i = 0; i < n; i++) indices[i] = 0; while (true) { // Print current combination for(int i = 0; i < n; i++) Console.Write(arr[i][indices[i]] + " "); Console.WriteLine(); // Find the rightmost array // that has more elements // left after the current // element in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].Count)) next--; // No such array is found // so no more combinations left if (next < 0) return; // If found move to next // element in that array indices[next]++; // For all arrays to the right // of this array current index // again points to first element for(int i = next + 1; i < n; i++) indices[i] = 0; }} // Driver codepublic static void Main(String[] args){ // Initializing a vector // with 3 empty vectors List<int> []arr = new List<int>[3]; for(int i = 0; i < arr.Length; i++) arr[i] = new List<int>(); // Now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].Add(1); arr[0].Add(2); arr[0].Add(3); arr[1].Add(4); arr[2].Add(5); arr[2].Add(6); print(arr);}} // This code is contributed by shikhasingrajput
<script> // Javascript program to find combinations from n// arrays such that one element from each// array is present // Function to print combinations that contain// one element from each of the given arraysfunction print(arr){ // Number of arrays let n = arr.length; // To keep track of next element in // each of the n arrays let indices = new Array(n); // Initialize with first element's index for(let i = 0; i < n; i++) indices[i] = 0; while (true) { // Print current combination for(let i = 0; i < n; i++) document.write( arr[i][indices[i]] + " "); document.write("<br>"); // Find the rightmost array that has more // elements left after the current element // in that array let next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].length)) next--; // No such array is found so no more // combinations left if (next < 0) return; // If found move to next element in that // array indices[next]++; // For all arrays to the right of this // array current index again points to // first element for(let i = next + 1; i < n; i++) indices[i] = 0; }} // Driver code // Initializing a vector with 3 empty vectorslet arr = new Array(3);for(let i = 0; i < arr.length; i++) arr[i] = []; // Now entering data// [[1, 2, 3], [4], [5, 6]]arr[0].push(1);arr[0].push(2);arr[0].push(3);arr[1].push(4);arr[2].push(5);arr[2].push(6); print(arr); // This code is contributed by unknown2108 </script>
Output:
1 4 5
1 4 6
2 4 5
2 4 6
3 4 5
3 4 6
This article is contributed by aditi sharma 2. 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.
NimeshDesai
mohit kumar 29
Amal Kumar Choubey
shikhasingrajput
unknown2108
surinderdawra388
simmytarika5
Whatfix
Arrays
Combinatorial
Arrays
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Combinational Sum
Factorial of a large number | [
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 26180,
"s": 26067,
"text": "Given a list of arrays, find all combinations where each combination contains one element from each given array."
},
{
"code": null,
"e": 26190,
"s": 26180,
"text": "Examples:"
},
{
"code": null,
"e": 26371,
"s": 26190,
"text": "Input : [ [1, 2], [3, 4] ]\nOutput : 1 3 \n 1 4 \n 2 3 \n 2 4 \n\nInput : [ [1], [2, 3, 4], [5] ]\nOutput : 1 2 5 \n 1 3 5\n 1 4 5 "
},
{
"code": null,
"e": 27107,
"s": 26371,
"text": "We keep an array of size equal to the total no of arrays. This array called indices helps us keep track of the index of the current element in each of the n arrays. Initially, it is initialized with all 0s indicating the current index in each array is that of the first element. We keep printing the combinations until no new combinations can be found. Starting from the rightmost array we check if more elements are there in that array. If yes, we increment the entry for that array in indices i.e. moves to the next element in that array. We also make the current indices 0 in all the arrays to the right of this array. We keep moving left to check all arrays until one such array is found. If no more arrays are found we stop there."
},
{
"code": null,
"e": 27111,
"s": 27107,
"text": "C++"
},
{
"code": null,
"e": 27116,
"s": 27111,
"text": "Java"
},
{
"code": null,
"e": 27124,
"s": 27116,
"text": "Python3"
},
{
"code": null,
"e": 27127,
"s": 27124,
"text": "C#"
},
{
"code": null,
"e": 27138,
"s": 27127,
"text": "Javascript"
},
{
"code": "// C++ program to find combinations from n// arrays such that one element from each// array is present#include <bits/stdc++.h> using namespace std; // function to print combinations that contain// one element from each of the given arraysvoid print(vector<vector<int> >& arr){ // number of arrays int n = arr.size(); // to keep track of next element in each of // the n arrays int* indices = new int[n]; // initialize with first element's index for (int i = 0; i < n; i++) indices[i] = 0; while (1) { // print current combination for (int i = 0; i < n; i++) cout << arr[i][indices[i]] << \" \"; cout << endl; // find the rightmost array that has more // elements left after the current element // in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].size())) next--; // no such array is found so no more // combinations left if (next < 0) return; // if found move to next element in that // array indices[next]++; // for all arrays to the right of this // array current index again points to // first element for (int i = next + 1; i < n; i++) indices[i] = 0; }} // driver function to test above functionint main(){ // initializing a vector with 3 empty vectors vector<vector<int> > arr(3, vector<int>(0, 0)); // now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].push_back(1); arr[0].push_back(2); arr[0].push_back(3); arr[1].push_back(4); arr[2].push_back(5); arr[2].push_back(6); print(arr);}",
"e": 28825,
"s": 27138,
"text": null
},
{
"code": "// Java program to find combinations from n// arrays such that one element from each// array is presentimport java.util.*; class GFG{ // Function to print combinations that contain// one element from each of the given arraysstatic void print(Vector<Integer> []arr){ // Number of arrays int n = arr.length; // To keep track of next element in // each of the n arrays int []indices = new int[n]; // Initialize with first element's index for(int i = 0; i < n; i++) indices[i] = 0; while (true) { // Print current combination for(int i = 0; i < n; i++) System.out.print( arr[i].get(indices[i]) + \" \"); System.out.println(); // Find the rightmost array that has more // elements left after the current element // in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].size())) next--; // No such array is found so no more // combinations left if (next < 0) return; // If found move to next element in that // array indices[next]++; // For all arrays to the right of this // array current index again points to // first element for(int i = next + 1; i < n; i++) indices[i] = 0; }} // Driver codepublic static void main(String[] args){ // Initializing a vector with 3 empty vectors @SuppressWarnings(\"unchecked\") Vector<Integer> []arr = new Vector[3]; for(int i = 0; i < arr.length; i++) arr[i] = new Vector<Integer>(); // Now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].add(1); arr[0].add(2); arr[0].add(3); arr[1].add(4); arr[2].add(5); arr[2].add(6); print(arr);}} // This code is contributed by amal kumar choubey",
"e": 30714,
"s": 28825,
"text": null
},
{
"code": "# Python3 program to find combinations from n# arrays such that one element from each# array is present # function to print combinations that contain# one element from each of the given arraysdef print1(arr): # number of arrays n = len(arr) # to keep track of next element # in each of the n arrays indices = [0 for i in range(n)] while (1): # print current combination for i in range(n): print(arr[i][indices[i]], end = \" \") print() # find the rightmost array that has more # elements left after the current element # in that array next = n - 1 while (next >= 0 and (indices[next] + 1 >= len(arr[next]))): next-=1 # no such array is found so no more # combinations left if (next < 0): return # if found move to next element in that # array indices[next] += 1 # for all arrays to the right of this # array current index again points to # first element for i in range(next + 1, n): indices[i] = 0 # Driver Code # initializing a vector with 3 empty vectorsarr = [[] for i in range(3)] # now entering data# [[1, 2, 3], [4], [5, 6]]arr[0].append(1)arr[0].append(2)arr[0].append(3)arr[1].append(4)arr[2].append(5)arr[2].append(6) print1(arr) # This code is contributed by mohit kumar",
"e": 32106,
"s": 30714,
"text": null
},
{
"code": "// C# program to find// combinations from n// arrays such that one// element from each// array is presentusing System;using System.Collections.Generic;class GFG{ // Function to print combinations// that contain one element from// each of the given arraysstatic void print(List<int> []arr){ // Number of arrays int n = arr.Length; // To keep track of next // element in each of // the n arrays int []indices = new int[n]; // Initialize with first // element's index for(int i = 0; i < n; i++) indices[i] = 0; while (true) { // Print current combination for(int i = 0; i < n; i++) Console.Write(arr[i][indices[i]] + \" \"); Console.WriteLine(); // Find the rightmost array // that has more elements // left after the current // element in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].Count)) next--; // No such array is found // so no more combinations left if (next < 0) return; // If found move to next // element in that array indices[next]++; // For all arrays to the right // of this array current index // again points to first element for(int i = next + 1; i < n; i++) indices[i] = 0; }} // Driver codepublic static void Main(String[] args){ // Initializing a vector // with 3 empty vectors List<int> []arr = new List<int>[3]; for(int i = 0; i < arr.Length; i++) arr[i] = new List<int>(); // Now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].Add(1); arr[0].Add(2); arr[0].Add(3); arr[1].Add(4); arr[2].Add(5); arr[2].Add(6); print(arr);}} // This code is contributed by shikhasingrajput",
"e": 33776,
"s": 32106,
"text": null
},
{
"code": "<script> // Javascript program to find combinations from n// arrays such that one element from each// array is present // Function to print combinations that contain// one element from each of the given arraysfunction print(arr){ // Number of arrays let n = arr.length; // To keep track of next element in // each of the n arrays let indices = new Array(n); // Initialize with first element's index for(let i = 0; i < n; i++) indices[i] = 0; while (true) { // Print current combination for(let i = 0; i < n; i++) document.write( arr[i][indices[i]] + \" \"); document.write(\"<br>\"); // Find the rightmost array that has more // elements left after the current element // in that array let next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].length)) next--; // No such array is found so no more // combinations left if (next < 0) return; // If found move to next element in that // array indices[next]++; // For all arrays to the right of this // array current index again points to // first element for(let i = next + 1; i < n; i++) indices[i] = 0; }} // Driver code // Initializing a vector with 3 empty vectorslet arr = new Array(3);for(let i = 0; i < arr.length; i++) arr[i] = []; // Now entering data// [[1, 2, 3], [4], [5, 6]]arr[0].push(1);arr[0].push(2);arr[0].push(3);arr[1].push(4);arr[2].push(5);arr[2].push(6); print(arr); // This code is contributed by unknown2108 </script>",
"e": 35503,
"s": 33776,
"text": null
},
{
"code": null,
"e": 35511,
"s": 35503,
"text": "Output:"
},
{
"code": null,
"e": 35547,
"s": 35511,
"text": "1 4 5\n1 4 6\n2 4 5\n2 4 6\n3 4 5\n3 4 6"
},
{
"code": null,
"e": 35970,
"s": 35547,
"text": "This article is contributed by aditi sharma 2. 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": 35982,
"s": 35970,
"text": "NimeshDesai"
},
{
"code": null,
"e": 35997,
"s": 35982,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 36016,
"s": 35997,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 36033,
"s": 36016,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 36045,
"s": 36033,
"text": "unknown2108"
},
{
"code": null,
"e": 36062,
"s": 36045,
"text": "surinderdawra388"
},
{
"code": null,
"e": 36075,
"s": 36062,
"text": "simmytarika5"
},
{
"code": null,
"e": 36083,
"s": 36075,
"text": "Whatfix"
},
{
"code": null,
"e": 36090,
"s": 36083,
"text": "Arrays"
},
{
"code": null,
"e": 36104,
"s": 36090,
"text": "Combinatorial"
},
{
"code": null,
"e": 36111,
"s": 36104,
"text": "Arrays"
},
{
"code": null,
"e": 36125,
"s": 36111,
"text": "Combinatorial"
},
{
"code": null,
"e": 36223,
"s": 36125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36250,
"s": 36223,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36281,
"s": 36250,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 36306,
"s": 36281,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36344,
"s": 36306,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36365,
"s": 36344,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36425,
"s": 36365,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36463,
"s": 36425,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 36540,
"s": 36463,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 36558,
"s": 36540,
"text": "Combinational Sum"
}
]
|
Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 in C++ | We are given two numbers L and R that define a range [L,R]. The goal is to find all numbers between L and R that are even, and sum of whose digits is divisible by 3.
We will do this by calculating the sum of digits of all even numbers between L and R and increment count if that sum%3==0.
Let us understand with examples.
Input − L=10, R=20
Output − Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3: 2
Explanation − Numbers between 10 and 20 that are even. 10,12,14,16,18,20. Sum of whose digits divisible by 3= 12 and 18.
Input − L=100, R=108
Output− Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3: 2
Explanation − Numbers between 100 and 108 that are even. 100,102,104,106,108. Sum of whose digits divisible by 3= 102 and 108.
We take variables first and last to define range.
We take variables first and last to define range.
Function Digit_sum(int num) takes the number and returns the sum of its digits.
Function Digit_sum(int num) takes the number and returns the sum of its digits.
Using while loop, till num!=0, add num%10, (unit digit) to total.
Using while loop, till num!=0, add num%10, (unit digit) to total.
Divide num by 10 to reduce it.
Divide num by 10 to reduce it.
At the end total will have sum of all digits.
At the end total will have sum of all digits.
Function divisible_3(int first, int last) takes the range of numbers and returns the count of even numbers that have digit sum divisible by 3.
Function divisible_3(int first, int last) takes the range of numbers and returns the count of even numbers that have digit sum divisible by 3.
Starting from index i=first to i<=last. Check if number i is even. (i%2==0).
Starting from index i=first to i<=last. Check if number i is even. (i%2==0).
If true, then calculate sum of digits of i by calling Digit_sum(i). If that sum%3==0. Then increment count.
If true, then calculate sum of digits of i by calling Digit_sum(i). If that sum%3==0. Then increment count.
At the end of for loop return count as result.
At the end of for loop return count as result.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int Digit_sum(int num){
int total = 0;
while (num!= 0){
total += num % 10;
num = num / 10;
}
return total;
}
int divisible_3(int first, int last){
int count = 0;
for (int i = first; i <= last; i++){
if (i % 2 == 0 && Digit_sum(i) % 3 == 0){
count++;
}
}
return count;
}
int main(){
int first = 300, last = 500;
cout<<"Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 are: "<<divisible_3(first, last);
return 0;
}
If we run the above code it will generate the following output −
Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 are: 34 | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "We are given two numbers L and R that define a range [L,R]. The goal is to find all numbers between L and R that are even, and sum of whose digits is divisible by 3."
},
{
"code": null,
"e": 1351,
"s": 1228,
"text": "We will do this by calculating the sum of digits of all even numbers between L and R and increment count if that sum%3==0."
},
{
"code": null,
"e": 1384,
"s": 1351,
"text": "Let us understand with examples."
},
{
"code": null,
"e": 1403,
"s": 1384,
"text": "Input − L=10, R=20"
},
{
"code": null,
"e": 1499,
"s": 1403,
"text": "Output − Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3: 2"
},
{
"code": null,
"e": 1620,
"s": 1499,
"text": "Explanation − Numbers between 10 and 20 that are even. 10,12,14,16,18,20. Sum of whose digits divisible by 3= 12 and 18."
},
{
"code": null,
"e": 1641,
"s": 1620,
"text": "Input − L=100, R=108"
},
{
"code": null,
"e": 1736,
"s": 1641,
"text": "Output− Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3: 2"
},
{
"code": null,
"e": 1863,
"s": 1736,
"text": "Explanation − Numbers between 100 and 108 that are even. 100,102,104,106,108. Sum of whose digits divisible by 3= 102 and 108."
},
{
"code": null,
"e": 1913,
"s": 1863,
"text": "We take variables first and last to define range."
},
{
"code": null,
"e": 1963,
"s": 1913,
"text": "We take variables first and last to define range."
},
{
"code": null,
"e": 2043,
"s": 1963,
"text": "Function Digit_sum(int num) takes the number and returns the sum of its digits."
},
{
"code": null,
"e": 2123,
"s": 2043,
"text": "Function Digit_sum(int num) takes the number and returns the sum of its digits."
},
{
"code": null,
"e": 2189,
"s": 2123,
"text": "Using while loop, till num!=0, add num%10, (unit digit) to total."
},
{
"code": null,
"e": 2255,
"s": 2189,
"text": "Using while loop, till num!=0, add num%10, (unit digit) to total."
},
{
"code": null,
"e": 2286,
"s": 2255,
"text": "Divide num by 10 to reduce it."
},
{
"code": null,
"e": 2317,
"s": 2286,
"text": "Divide num by 10 to reduce it."
},
{
"code": null,
"e": 2363,
"s": 2317,
"text": "At the end total will have sum of all digits."
},
{
"code": null,
"e": 2409,
"s": 2363,
"text": "At the end total will have sum of all digits."
},
{
"code": null,
"e": 2552,
"s": 2409,
"text": "Function divisible_3(int first, int last) takes the range of numbers and returns the count of even numbers that have digit sum divisible by 3."
},
{
"code": null,
"e": 2695,
"s": 2552,
"text": "Function divisible_3(int first, int last) takes the range of numbers and returns the count of even numbers that have digit sum divisible by 3."
},
{
"code": null,
"e": 2772,
"s": 2695,
"text": "Starting from index i=first to i<=last. Check if number i is even. (i%2==0)."
},
{
"code": null,
"e": 2849,
"s": 2772,
"text": "Starting from index i=first to i<=last. Check if number i is even. (i%2==0)."
},
{
"code": null,
"e": 2957,
"s": 2849,
"text": "If true, then calculate sum of digits of i by calling Digit_sum(i). If that sum%3==0. Then increment count."
},
{
"code": null,
"e": 3065,
"s": 2957,
"text": "If true, then calculate sum of digits of i by calling Digit_sum(i). If that sum%3==0. Then increment count."
},
{
"code": null,
"e": 3112,
"s": 3065,
"text": "At the end of for loop return count as result."
},
{
"code": null,
"e": 3159,
"s": 3112,
"text": "At the end of for loop return count as result."
},
{
"code": null,
"e": 3170,
"s": 3159,
"text": " Live Demo"
},
{
"code": null,
"e": 3730,
"s": 3170,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint Digit_sum(int num){\n int total = 0;\n while (num!= 0){\n total += num % 10;\n num = num / 10;\n }\n return total;\n}\nint divisible_3(int first, int last){\n int count = 0;\n for (int i = first; i <= last; i++){\n if (i % 2 == 0 && Digit_sum(i) % 3 == 0){\n count++;\n }\n }\n return count;\n}\nint main(){\n int first = 300, last = 500;\n cout<<\"Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 are: \"<<divisible_3(first, last);\n return 0;\n}"
},
{
"code": null,
"e": 3795,
"s": 3730,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3887,
"s": 3795,
"text": "Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 are: 34"
}
]
|
Android Animations in Kotlin - GeeksforGeeks | 12 Nov, 2021
Animation is a method in which a collection of images are combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seem to be alive. Android has quite a few tools to help you create animations with relative ease. so in this article we will learn to create animations using Kotlin. below are some attributes which we are using while writing the code in xml.
Table of Attributes :
At first, we will create a new android application. Then, we will create some animations. If you already created the project then ignore step 1.
Open Android StudioGo to File => New => New Project.Then, select Empty Activity and click on nextWrite application name as DynamicEditTextKotlinSelect minimum SDK as you need, here we have selected 21 as minimum SDKChoose language as Kotlin and click on finish button.
Open Android Studio
Go to File => New => New Project.
Then, select Empty Activity and click on nextWrite application name as DynamicEditTextKotlinSelect minimum SDK as you need, here we have selected 21 as minimum SDKChoose language as Kotlin and click on finish button.
Write application name as DynamicEditTextKotlin
Select minimum SDK as you need, here we have selected 21 as minimum SDK
Choose language as Kotlin and click on finish button.
If you have followed above process correctly, you will get a newly created project successfully.After creating project we will modify xml files. In xml file we will create one TextView where all the animations are performed and Eight Buttons for Eight different animations.
Open res/layout/activity_main.xml file and add code into it.
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"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/linearLayout" android:gravity="center" android:text="Geeks for Geeks" android:textSize="32sp" android:textColor="@color/colorPrimaryDark" android:textStyle="bold" /> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="2"> <Button android:id="@+id/fade_in" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Fade In" android:textAllCaps="false" /> <Button android:id="@+id/fade_out" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Fade Out" android:textAllCaps="false" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="2"> <Button android:id="@+id/zoom_in" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Zoom In" android:textAllCaps="false" /> <Button android:id="@+id/zoom_out" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Zoom Out" android:textAllCaps="false" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="2"> <Button android:id="@+id/slide_down" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Slide Down" android:textAllCaps="false" /> <Button android:id="@+id/slide_up" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Slide Up" android:textAllCaps="false" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="2"> <Button android:id="@+id/bounce" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Bounce" android:textAllCaps="false" /> <Button android:id="@+id/rotate" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="Rotate" android:textAllCaps="false" /> </LinearLayout> </LinearLayout></RelativeLayout>
After modifying the layout we will create xml files for animations. so we will first create a folder name anim.In this folder, we will be adding the XML files which will be used to produce the animations. For this to happen, go to app/res right click and then select, Android Resource Directory and name it as anim.
In this animation the text is bounce like a ball.
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/linear_interpolator" android:fillAfter="true"> <translate android:fromYDelta="100%" android:toYDelta="-20%" android:duration="300" /> <translate android:startOffset="500" android:fromYDelta="-20%" android:toYDelta="10%" android:duration="150" /> <translate android:startOffset="1000" android:fromYDelta="10%" android:toYDelta="0" android:duration="100" /></set>
In Fade In animation the text will appear from background.
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/linear_interpolator"> <alpha android:duration="1000" android:fromAlpha="0.1" android:toAlpha="1.0" /></set>
In Fade Out animation the colour of text is faded for a particular amount of time.
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/linear_interpolator"> <alpha android:duration="1000" android:fromAlpha="1.0" android:toAlpha="0.1" /></set>
In rotate animation the text is rotated for a particular amount of time.
XML
<?xml version="1.0" encoding="utf-8"?><rotate xmlns:android="http://schemas.android.com/apk/res/android" android:duration="1000" android:fromDegrees="0" android:interpolator="@android:anim/linear_interpolator" android:pivotX="50%" android:pivotY="50%" android:startOffset="0" android:toDegrees="360" />
In this animation the text will come from top to bottom.
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:duration="1000" android:fromYDelta="-100%" android:toYDelta="0" /></set>
In this animation the text will go from bottom to top.
XML
<set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:duration="1000" android:fromYDelta="0" android:toYDelta="-100%" /></set>
In this animation the text will appear bigger for a particular amount of time.
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true"> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration="1000" android:fromXScale="1" android:fromYScale="1" android:pivotX="50%" android:pivotY="50%" android:toXScale="1.5" android:toYScale="1.5"> </scale></set>
In this animation the text will appear smaller for a particular amount of time.
XML
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" > <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration="1000" android:fromXScale="1.0" android:fromYScale="1.0" android:pivotX="50%" android:pivotY="50%" android:toXScale="0.5" android:toYScale="0.5" > </scale></set>
After creating all animations in xml. we will create MainActivity.
Open app/src/main/java/net.geeksforgeeks.AnimationsInKotlin/MainActivity.kt file and add below code into it.
Java
package net.geeksforgeeks.animationsinkotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Handlerimport android.view.Viewimport android.view.animation.AnimationUtilsimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) fade_in.setOnClickListener { textView.visibility = View.VISIBLE val animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in) textView.startAnimation(animationFadeIn) } fade_out.setOnClickListener { val animationFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out) textView.startAnimation(animationFadeOut) Handler().postDelayed({ textView.visibility = View.GONE }, 1000) } zoom_in.setOnClickListener { val animationZoomIn = AnimationUtils.loadAnimation(this, R.anim.zoom_in) textView.startAnimation(animationZoomIn) } zoom_out.setOnClickListener { val animationZoomOut = AnimationUtils.loadAnimation(this, R.anim.zoom_out) textView.startAnimation(animationZoomOut) } slide_down.setOnClickListener { val animationSlideDown = AnimationUtils.loadAnimation(this, R.anim.slide_in) textView.startAnimation(animationSlideDown) } slide_up.setOnClickListener { val animationSlideUp = AnimationUtils.loadAnimation(this, R.anim.slide_out) textView.startAnimation(animationSlideUp) } bounce.setOnClickListener { val animationBounce = AnimationUtils.loadAnimation(this, R.anim.bounce) textView.startAnimation(animationBounce) } rotate.setOnClickListener { val animationRotate = AnimationUtils.loadAnimation(this, R.anim.rotate) textView.startAnimation(animationRotate) } }}
As, AndroidManifest.xml file is very important file in android application, so below is the code of manifest file.
Code inside src/main/AndroidManifest.xml file would look like below
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.geeksforgeeks.animationsinkotlin"> <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>
You can find the complete code here: https://github.com/missyadavmanisha/AnimationsInKotlin
anikakapoor
sooda367
varshagumber28
Android-Animation
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
How to Create and Add Data to SQLite Database in Android?
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Android UI Layouts | [
{
"code": null,
"e": 24042,
"s": 24014,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 24461,
"s": 24042,
"text": "Animation is a method in which a collection of images are combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seem to be alive. Android has quite a few tools to help you create animations with relative ease. so in this article we will learn to create animations using Kotlin. below are some attributes which we are using while writing the code in xml."
},
{
"code": null,
"e": 24484,
"s": 24461,
"text": "Table of Attributes : "
},
{
"code": null,
"e": 24630,
"s": 24484,
"text": "At first, we will create a new android application. Then, we will create some animations. If you already created the project then ignore step 1. "
},
{
"code": null,
"e": 24899,
"s": 24630,
"text": "Open Android StudioGo to File => New => New Project.Then, select Empty Activity and click on nextWrite application name as DynamicEditTextKotlinSelect minimum SDK as you need, here we have selected 21 as minimum SDKChoose language as Kotlin and click on finish button."
},
{
"code": null,
"e": 24919,
"s": 24899,
"text": "Open Android Studio"
},
{
"code": null,
"e": 24953,
"s": 24919,
"text": "Go to File => New => New Project."
},
{
"code": null,
"e": 25170,
"s": 24953,
"text": "Then, select Empty Activity and click on nextWrite application name as DynamicEditTextKotlinSelect minimum SDK as you need, here we have selected 21 as minimum SDKChoose language as Kotlin and click on finish button."
},
{
"code": null,
"e": 25218,
"s": 25170,
"text": "Write application name as DynamicEditTextKotlin"
},
{
"code": null,
"e": 25290,
"s": 25218,
"text": "Select minimum SDK as you need, here we have selected 21 as minimum SDK"
},
{
"code": null,
"e": 25344,
"s": 25290,
"text": "Choose language as Kotlin and click on finish button."
},
{
"code": null,
"e": 25619,
"s": 25344,
"text": "If you have followed above process correctly, you will get a newly created project successfully.After creating project we will modify xml files. In xml file we will create one TextView where all the animations are performed and Eight Buttons for Eight different animations. "
},
{
"code": null,
"e": 25681,
"s": 25619,
"text": "Open res/layout/activity_main.xml file and add code into it. "
},
{
"code": null,
"e": 25685,
"s": 25681,
"text": "XML"
},
{
"code": "<?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\"> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_above=\"@+id/linearLayout\" android:gravity=\"center\" android:text=\"Geeks for Geeks\" android:textSize=\"32sp\" android:textColor=\"@color/colorPrimaryDark\" android:textStyle=\"bold\" /> <LinearLayout android:id=\"@+id/linearLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:orientation=\"vertical\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <Button android:id=\"@+id/fade_in\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:text=\"Fade In\" android:textAllCaps=\"false\" /> <Button android:id=\"@+id/fade_out\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:text=\"Fade Out\" android:textAllCaps=\"false\" /> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <Button android:id=\"@+id/zoom_in\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:text=\"Zoom In\" android:textAllCaps=\"false\" /> <Button android:id=\"@+id/zoom_out\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:text=\"Zoom Out\" android:textAllCaps=\"false\" /> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <Button android:id=\"@+id/slide_down\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:text=\"Slide Down\" android:textAllCaps=\"false\" /> <Button android:id=\"@+id/slide_up\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:text=\"Slide Up\" android:textAllCaps=\"false\" /> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" android:weightSum=\"2\"> <Button android:id=\"@+id/bounce\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:text=\"Bounce\" android:textAllCaps=\"false\" /> <Button android:id=\"@+id/rotate\" android:layout_width=\"0dp\" android:layout_height=\"match_parent\" android:layout_weight=\"1\" android:text=\"Rotate\" android:textAllCaps=\"false\" /> </LinearLayout> </LinearLayout></RelativeLayout>",
"e": 29702,
"s": 25685,
"text": null
},
{
"code": null,
"e": 30018,
"s": 29702,
"text": "After modifying the layout we will create xml files for animations. so we will first create a folder name anim.In this folder, we will be adding the XML files which will be used to produce the animations. For this to happen, go to app/res right click and then select, Android Resource Directory and name it as anim."
},
{
"code": null,
"e": 30070,
"s": 30018,
"text": "In this animation the text is bounce like a ball. "
},
{
"code": null,
"e": 30074,
"s": 30070,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:interpolator=\"@android:anim/linear_interpolator\" android:fillAfter=\"true\"> <translate android:fromYDelta=\"100%\" android:toYDelta=\"-20%\" android:duration=\"300\" /> <translate android:startOffset=\"500\" android:fromYDelta=\"-20%\" android:toYDelta=\"10%\" android:duration=\"150\" /> <translate android:startOffset=\"1000\" android:fromYDelta=\"10%\" android:toYDelta=\"0\" android:duration=\"100\" /></set>",
"e": 30669,
"s": 30074,
"text": null
},
{
"code": null,
"e": 30729,
"s": 30669,
"text": "In Fade In animation the text will appear from background. "
},
{
"code": null,
"e": 30733,
"s": 30729,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:interpolator=\"@android:anim/linear_interpolator\"> <alpha android:duration=\"1000\" android:fromAlpha=\"0.1\" android:toAlpha=\"1.0\" /></set>",
"e": 31006,
"s": 30733,
"text": null
},
{
"code": null,
"e": 31090,
"s": 31006,
"text": "In Fade Out animation the colour of text is faded for a particular amount of time. "
},
{
"code": null,
"e": 31094,
"s": 31090,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:interpolator=\"@android:anim/linear_interpolator\"> <alpha android:duration=\"1000\" android:fromAlpha=\"1.0\" android:toAlpha=\"0.1\" /></set>",
"e": 31367,
"s": 31094,
"text": null
},
{
"code": null,
"e": 31441,
"s": 31367,
"text": "In rotate animation the text is rotated for a particular amount of time. "
},
{
"code": null,
"e": 31445,
"s": 31441,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><rotate xmlns:android=\"http://schemas.android.com/apk/res/android\" android:duration=\"1000\" android:fromDegrees=\"0\" android:interpolator=\"@android:anim/linear_interpolator\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:startOffset=\"0\" android:toDegrees=\"360\" />",
"e": 31769,
"s": 31445,
"text": null
},
{
"code": null,
"e": 31827,
"s": 31769,
"text": "In this animation the text will come from top to bottom. "
},
{
"code": null,
"e": 31831,
"s": 31827,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <translate android:duration=\"1000\" android:fromYDelta=\"-100%\" android:toYDelta=\"0\" /></set>",
"e": 32050,
"s": 31831,
"text": null
},
{
"code": null,
"e": 32106,
"s": 32050,
"text": "In this animation the text will go from bottom to top. "
},
{
"code": null,
"e": 32110,
"s": 32106,
"text": "XML"
},
{
"code": "<set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <translate android:duration=\"1000\" android:fromYDelta=\"0\" android:toYDelta=\"-100%\" /></set>",
"e": 32291,
"s": 32110,
"text": null
},
{
"code": null,
"e": 32371,
"s": 32291,
"text": "In this animation the text will appear bigger for a particular amount of time. "
},
{
"code": null,
"e": 32375,
"s": 32371,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter=\"true\"> <scale xmlns:android=\"http://schemas.android.com/apk/res/android\" android:duration=\"1000\" android:fromXScale=\"1\" android:fromYScale=\"1\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:toXScale=\"1.5\" android:toYScale=\"1.5\"> </scale></set>",
"e": 32801,
"s": 32375,
"text": null
},
{
"code": null,
"e": 32882,
"s": 32801,
"text": "In this animation the text will appear smaller for a particular amount of time. "
},
{
"code": null,
"e": 32886,
"s": 32882,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter=\"true\" > <scale xmlns:android=\"http://schemas.android.com/apk/res/android\" android:duration=\"1000\" android:fromXScale=\"1.0\" android:fromYScale=\"1.0\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:toXScale=\"0.5\" android:toYScale=\"0.5\" > </scale></set>",
"e": 33325,
"s": 32886,
"text": null
},
{
"code": null,
"e": 33393,
"s": 33325,
"text": "After creating all animations in xml. we will create MainActivity. "
},
{
"code": null,
"e": 33503,
"s": 33393,
"text": "Open app/src/main/java/net.geeksforgeeks.AnimationsInKotlin/MainActivity.kt file and add below code into it. "
},
{
"code": null,
"e": 33508,
"s": 33503,
"text": "Java"
},
{
"code": "package net.geeksforgeeks.animationsinkotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Handlerimport android.view.Viewimport android.view.animation.AnimationUtilsimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) fade_in.setOnClickListener { textView.visibility = View.VISIBLE val animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in) textView.startAnimation(animationFadeIn) } fade_out.setOnClickListener { val animationFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out) textView.startAnimation(animationFadeOut) Handler().postDelayed({ textView.visibility = View.GONE }, 1000) } zoom_in.setOnClickListener { val animationZoomIn = AnimationUtils.loadAnimation(this, R.anim.zoom_in) textView.startAnimation(animationZoomIn) } zoom_out.setOnClickListener { val animationZoomOut = AnimationUtils.loadAnimation(this, R.anim.zoom_out) textView.startAnimation(animationZoomOut) } slide_down.setOnClickListener { val animationSlideDown = AnimationUtils.loadAnimation(this, R.anim.slide_in) textView.startAnimation(animationSlideDown) } slide_up.setOnClickListener { val animationSlideUp = AnimationUtils.loadAnimation(this, R.anim.slide_out) textView.startAnimation(animationSlideUp) } bounce.setOnClickListener { val animationBounce = AnimationUtils.loadAnimation(this, R.anim.bounce) textView.startAnimation(animationBounce) } rotate.setOnClickListener { val animationRotate = AnimationUtils.loadAnimation(this, R.anim.rotate) textView.startAnimation(animationRotate) } }}",
"e": 35581,
"s": 33508,
"text": null
},
{
"code": null,
"e": 35697,
"s": 35581,
"text": "As, AndroidManifest.xml file is very important file in android application, so below is the code of manifest file. "
},
{
"code": null,
"e": 35765,
"s": 35697,
"text": "Code inside src/main/AndroidManifest.xml file would look like below"
},
{
"code": null,
"e": 35769,
"s": 35765,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"net.geeksforgeeks.animationsinkotlin\"> <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>",
"e": 36486,
"s": 35769,
"text": null
},
{
"code": null,
"e": 36579,
"s": 36486,
"text": "You can find the complete code here: https://github.com/missyadavmanisha/AnimationsInKotlin "
},
{
"code": null,
"e": 36591,
"s": 36579,
"text": "anikakapoor"
},
{
"code": null,
"e": 36600,
"s": 36591,
"text": "sooda367"
},
{
"code": null,
"e": 36615,
"s": 36600,
"text": "varshagumber28"
},
{
"code": null,
"e": 36633,
"s": 36615,
"text": "Android-Animation"
},
{
"code": null,
"e": 36648,
"s": 36633,
"text": "Kotlin Android"
},
{
"code": null,
"e": 36655,
"s": 36648,
"text": "Picked"
},
{
"code": null,
"e": 36663,
"s": 36655,
"text": "Android"
},
{
"code": null,
"e": 36670,
"s": 36663,
"text": "Kotlin"
},
{
"code": null,
"e": 36678,
"s": 36670,
"text": "Android"
},
{
"code": null,
"e": 36776,
"s": 36678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36785,
"s": 36776,
"text": "Comments"
},
{
"code": null,
"e": 36798,
"s": 36785,
"text": "Old Comments"
},
{
"code": null,
"e": 36841,
"s": 36798,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 36899,
"s": 36841,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 36932,
"s": 36899,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 36974,
"s": 36932,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 37005,
"s": 36974,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 37048,
"s": 37005,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 37081,
"s": 37048,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 37123,
"s": 37081,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 37154,
"s": 37123,
"text": "Android RecyclerView in Kotlin"
}
]
|
How to Create a Dynamic Audio Player in Android with Firebase Realtime Database? - GeeksforGeeks | 20 Jan, 2021
Many online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implementing a dynamic audio player in our Android app.
In this article, we will be building a simple application in which we will b playing an audio file from a web URL and we will be changing that audio file URL in runtime to update our audio file. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Firebase
After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.
Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase.
After completing this process you will get to see the below screen.
Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle (app) file and make sure that the below dependency is added in your dependencies section.
implementation ‘com.google.firebase:firebase-database:19.6.0’
After adding this dependency add the dependency of ExoPlayer in your Gradle file.
Step 3: Adding permission for the Internet
As we are loading our video from the internet so we have to add permissions for the Internet in the Manifest file. Navigate to the app > AndroidManifest.xml file and add the below permissions in it.
XML
<!--Permissions for internet--><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><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" android:orientation="vertical" tools:context=".MainActivity"> <!--Button for playing audio--> <Button android:id="@+id/idBtnPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Play Audio file" android:textAllCaps="false" /> <!--Button for pausing the audio--> <Button android:id="@+id/idBtnPause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/idBtnPlay" android:layout_centerInParent="true" android:text="Pause Audio" android:textAllCaps="false" /> </RelativeLayout>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; import java.io.IOException; public class MainActivity extends AppCompatActivity { // creating a variable for // button and media player Button playBtn, pauseBtn; MediaPlayer mediaPlayer; // creating a string for storing // our audio url from firebase. String audioUrl; // creating a variable for our Firebase Database. FirebaseDatabase firebaseDatabase; // creating a variable for our // Database Reference for Firebase. DatabaseReference databaseReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // below line is used to get the instance // of our Firebase database. firebaseDatabase = FirebaseDatabase.getInstance(); // below line is used to get reference for our database. databaseReference = firebaseDatabase.getReference("url"); // calling add value event listener method for getting the values from database. databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // this method is call to get the realtime updates in the data. // this method is called when the data is changed in our Firebase console. // below line is for getting the data from snapshot of our database. audioUrl = snapshot.getValue(String.class); // after getting the value for our audio url we are storing it in our string. } @Override public void onCancelled(@NonNull DatabaseError error) { // calling on cancelled method when we receive any error or we are not able to get the data. Toast.makeText(MainActivity.this, "Fail to get audio url.", Toast.LENGTH_SHORT).show(); } }); // initializing our buttons playBtn = findViewById(R.id.idBtnPlay); pauseBtn = findViewById(R.id.idBtnPause); // setting on click listener for our play and pause buttons. playBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to play audio. playAudio(audioUrl); } }); pauseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking the media player // if the audio is playing or not. if (mediaPlayer.isPlaying()) { // pausing the media player if // media player is playing we are // calling below line to stop our media player. mediaPlayer.stop(); mediaPlayer.reset(); mediaPlayer.release(); // below line is to display a message when media player is paused. Toast.makeText(MainActivity.this, "Audio has been paused", Toast.LENGTH_SHORT).show(); } else { // this method is called when media player is not playing. Toast.makeText(MainActivity.this, "Audio has not played", Toast.LENGTH_SHORT).show(); } } }); } private void playAudio(String audioUrl) { // initializing media player mediaPlayer = new MediaPlayer(); // below line is use to set the audio stream type for our media player. mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { // below line is use to set our // url to our media player. mediaPlayer.setDataSource(audioUrl); // below line is use to prepare // and start our media player. mediaPlayer.prepare(); mediaPlayer.start(); // below line is use to display a toast message. Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show(); } catch (IOException e) { // this line of code is use to handle error while playing our audio file. Toast.makeText(this, "Error found is " + e, Toast.LENGTH_SHORT).show(); } }}
Step 6: Adding URL for your audio file in Firebase Console
For adding audio URL in Firebase Console. Browse for Firebase in your browser and Click on Go to Console option in the top right corner as shown in the below screenshot.
After clicking on Go to Console option you will get to see your project. Click on your project name from the available list of projects.
After clicking on your project. Click on the Realtime Database option in the left window.
After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen.
In this project, we are adding our rules as true for reading as well as write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself.
Inside Firebase Realtime Database. Navigate to the Data tab. Inside this tab on the database section click on the “+” icon. After clicking on the “+” icon you will get to see two input fields which are the Name and Value fields. Inside the Name field, you have to add the reference for your video file which in our case is “url“. And in our value field, we have to add the URL for our audio file. After adding the value in this field. Click on the Add button and your data will be added to Firebase Console.
After adding the URL for your video. Now run your app and see the output of the app below:
You can change the URL of your audio dynamically.
android
Firebase
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 25116,
"s": 25088,
"text": "\n20 Jan, 2021"
},
{
"code": null,
"e": 25467,
"s": 25116,
"text": "Many online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implementing a dynamic audio player in our Android app. "
},
{
"code": null,
"e": 25829,
"s": 25467,
"text": "In this article, we will be building a simple application in which we will b playing an audio file from a web URL and we will be changing that audio file URL in runtime to update our audio file. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 25858,
"s": 25829,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26020,
"s": 25858,
"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 Java as the programming language."
},
{
"code": null,
"e": 26059,
"s": 26020,
"text": "Step 2: Connect your app to Firebase "
},
{
"code": null,
"e": 26266,
"s": 26059,
"text": "After creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. "
},
{
"code": null,
"e": 26612,
"s": 26266,
"text": "Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. "
},
{
"code": null,
"e": 26682,
"s": 26612,
"text": "After completing this process you will get to see the below screen. "
},
{
"code": null,
"e": 26914,
"s": 26682,
"text": "Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle (app) file and make sure that the below dependency is added in your dependencies section. "
},
{
"code": null,
"e": 26976,
"s": 26914,
"text": "implementation ‘com.google.firebase:firebase-database:19.6.0’"
},
{
"code": null,
"e": 27060,
"s": 26976,
"text": "After adding this dependency add the dependency of ExoPlayer in your Gradle file. "
},
{
"code": null,
"e": 27105,
"s": 27060,
"text": "Step 3: Adding permission for the Internet "
},
{
"code": null,
"e": 27306,
"s": 27105,
"text": "As we are loading our video from the internet so we have to add permissions for the Internet in the Manifest file. Navigate to the app > AndroidManifest.xml file and add the below permissions in it. "
},
{
"code": null,
"e": 27310,
"s": 27306,
"text": "XML"
},
{
"code": "<!--Permissions for internet--><uses-permission android:name=\"android.permission.INTERNET\" /><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />",
"e": 27478,
"s": 27310,
"text": null
},
{
"code": null,
"e": 27526,
"s": 27478,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27642,
"s": 27526,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 27646,
"s": 27642,
"text": "XML"
},
{
"code": "<?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\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Button for playing audio--> <Button android:id=\"@+id/idBtnPlay\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Play Audio file\" android:textAllCaps=\"false\" /> <!--Button for pausing the audio--> <Button android:id=\"@+id/idBtnPause\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idBtnPlay\" android:layout_centerInParent=\"true\" android:text=\"Pause Audio\" android:textAllCaps=\"false\" /> </RelativeLayout>",
"e": 28608,
"s": 27646,
"text": null
},
{
"code": null,
"e": 28656,
"s": 28608,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 28846,
"s": 28656,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 28851,
"s": 28846,
"text": "Java"
},
{
"code": "import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; import java.io.IOException; public class MainActivity extends AppCompatActivity { // creating a variable for // button and media player Button playBtn, pauseBtn; MediaPlayer mediaPlayer; // creating a string for storing // our audio url from firebase. String audioUrl; // creating a variable for our Firebase Database. FirebaseDatabase firebaseDatabase; // creating a variable for our // Database Reference for Firebase. DatabaseReference databaseReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // below line is used to get the instance // of our Firebase database. firebaseDatabase = FirebaseDatabase.getInstance(); // below line is used to get reference for our database. databaseReference = firebaseDatabase.getReference(\"url\"); // calling add value event listener method for getting the values from database. databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // this method is call to get the realtime updates in the data. // this method is called when the data is changed in our Firebase console. // below line is for getting the data from snapshot of our database. audioUrl = snapshot.getValue(String.class); // after getting the value for our audio url we are storing it in our string. } @Override public void onCancelled(@NonNull DatabaseError error) { // calling on cancelled method when we receive any error or we are not able to get the data. Toast.makeText(MainActivity.this, \"Fail to get audio url.\", Toast.LENGTH_SHORT).show(); } }); // initializing our buttons playBtn = findViewById(R.id.idBtnPlay); pauseBtn = findViewById(R.id.idBtnPause); // setting on click listener for our play and pause buttons. playBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to play audio. playAudio(audioUrl); } }); pauseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking the media player // if the audio is playing or not. if (mediaPlayer.isPlaying()) { // pausing the media player if // media player is playing we are // calling below line to stop our media player. mediaPlayer.stop(); mediaPlayer.reset(); mediaPlayer.release(); // below line is to display a message when media player is paused. Toast.makeText(MainActivity.this, \"Audio has been paused\", Toast.LENGTH_SHORT).show(); } else { // this method is called when media player is not playing. Toast.makeText(MainActivity.this, \"Audio has not played\", Toast.LENGTH_SHORT).show(); } } }); } private void playAudio(String audioUrl) { // initializing media player mediaPlayer = new MediaPlayer(); // below line is use to set the audio stream type for our media player. mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { // below line is use to set our // url to our media player. mediaPlayer.setDataSource(audioUrl); // below line is use to prepare // and start our media player. mediaPlayer.prepare(); mediaPlayer.start(); // below line is use to display a toast message. Toast.makeText(this, \"Audio started playing..\", Toast.LENGTH_SHORT).show(); } catch (IOException e) { // this line of code is use to handle error while playing our audio file. Toast.makeText(this, \"Error found is \" + e, Toast.LENGTH_SHORT).show(); } }}",
"e": 33770,
"s": 28851,
"text": null
},
{
"code": null,
"e": 33831,
"s": 33770,
"text": "Step 6: Adding URL for your audio file in Firebase Console "
},
{
"code": null,
"e": 34003,
"s": 33831,
"text": "For adding audio URL in Firebase Console. Browse for Firebase in your browser and Click on Go to Console option in the top right corner as shown in the below screenshot. "
},
{
"code": null,
"e": 34142,
"s": 34003,
"text": " After clicking on Go to Console option you will get to see your project. Click on your project name from the available list of projects. "
},
{
"code": null,
"e": 34234,
"s": 34142,
"text": "After clicking on your project. Click on the Realtime Database option in the left window. "
},
{
"code": null,
"e": 34426,
"s": 34234,
"text": "After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen. "
},
{
"code": null,
"e": 34858,
"s": 34426,
"text": "In this project, we are adding our rules as true for reading as well as write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself."
},
{
"code": null,
"e": 35368,
"s": 34858,
"text": "Inside Firebase Realtime Database. Navigate to the Data tab. Inside this tab on the database section click on the “+” icon. After clicking on the “+” icon you will get to see two input fields which are the Name and Value fields. Inside the Name field, you have to add the reference for your video file which in our case is “url“. And in our value field, we have to add the URL for our audio file. After adding the value in this field. Click on the Add button and your data will be added to Firebase Console. "
},
{
"code": null,
"e": 35460,
"s": 35368,
"text": "After adding the URL for your video. Now run your app and see the output of the app below: "
},
{
"code": null,
"e": 35511,
"s": 35460,
"text": "You can change the URL of your audio dynamically. "
},
{
"code": null,
"e": 35519,
"s": 35511,
"text": "android"
},
{
"code": null,
"e": 35528,
"s": 35519,
"text": "Firebase"
},
{
"code": null,
"e": 35552,
"s": 35528,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 35560,
"s": 35552,
"text": "Android"
},
{
"code": null,
"e": 35565,
"s": 35560,
"text": "Java"
},
{
"code": null,
"e": 35584,
"s": 35565,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35589,
"s": 35584,
"text": "Java"
},
{
"code": null,
"e": 35597,
"s": 35589,
"text": "Android"
},
{
"code": null,
"e": 35695,
"s": 35597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35704,
"s": 35695,
"text": "Comments"
},
{
"code": null,
"e": 35717,
"s": 35704,
"text": "Old Comments"
},
{
"code": null,
"e": 35756,
"s": 35717,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 35798,
"s": 35756,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 35831,
"s": 35798,
"text": "GridView in Android with Example"
},
{
"code": null,
"e": 35869,
"s": 35831,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 35942,
"s": 35869,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 35957,
"s": 35942,
"text": "Arrays in Java"
},
{
"code": null,
"e": 36001,
"s": 35957,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 36023,
"s": 36001,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36059,
"s": 36023,
"text": "Arrays.sort() in Java with examples"
}
]
|
How to use a final or effectively final variable in lambda expression in Java? | The effectively final variables refer to local variables that are not declared final explicitly and can't be changed once initialized. A lambda expression can use a local variable in outer scopes only if they are effectively final.
(optional) (Arguments) -> body
In the below example, the "size" variable is not declared as final but it's effective final because we are not modifying the value of the "size" variable.
interface Employee {
void empData(String empName);
}
public class LambdaEffectivelyFinalTest {
public static void main(String[] args) {
int size = 100;
Employee emp = name -> { // lambda expression
System.out.println("The employee strength is: " + size);
System.out.println("The employee name is: " + name);
};
emp.empData("Adithya");
}
}
The employee strength is: 100
The employee name is: Adithya | [
{
"code": null,
"e": 1294,
"s": 1062,
"text": "The effectively final variables refer to local variables that are not declared final explicitly and can't be changed once initialized. A lambda expression can use a local variable in outer scopes only if they are effectively final."
},
{
"code": null,
"e": 1325,
"s": 1294,
"text": "(optional) (Arguments) -> body"
},
{
"code": null,
"e": 1480,
"s": 1325,
"text": "In the below example, the \"size\" variable is not declared as final but it's effective final because we are not modifying the value of the \"size\" variable."
},
{
"code": null,
"e": 1889,
"s": 1480,
"text": "interface Employee {\n void empData(String empName);\n}\npublic class LambdaEffectivelyFinalTest {\n public static void main(String[] args) {\n int size = 100;\n Employee emp = name -> { // lambda expression\n System.out.println(\"The employee strength is: \" + size);\n System.out.println(\"The employee name is: \" + name);\n };\n emp.empData(\"Adithya\");\n }\n}"
},
{
"code": null,
"e": 1949,
"s": 1889,
"text": "The employee strength is: 100\nThe employee name is: Adithya"
}
]
|
Change Legend background using facecolor in MatplotLib - GeeksforGeeks | 22 Jan, 2021
In this article, we will see how can we can change the background color of a legend in our graph using MatplotLib, Here we will take two different examples to showcase different background colors of a legend in our graph.
Requirements:
pip install matplotlib
Approach:
Import required module.
Create data.
Change the background color of a legend.
Normally plot the data.
Display plot.
Implementation:
Example 1:
In this example, we will draw different lines with the help of matplotlib and Use the facecolor argument to plt.legend() to specify the legend background color.
Python3
# importing package import matplotlib.pyplot as plt import numpy as np # create data X = [1,2,3,4,5] Y = [3,3,3,3,3] # plot lines plt.plot(X, Y, label = "Line-1") plt.plot(Y, X, label = "Line-2") plt.plot(X, np.sin(X), label = "Curve-1") plt.plot(X, np.cos(X), label = "Curve-2") #Change the background color of a legend.plt.legend(facecolor="gray")plt.title("Line Graph - Geeksforgeeks") plt.show()
Output:
Example 2:
In this example, we will draw a Vertical line with the help of matplotlib and Use the facecolor argument to plt.legend() to specify the legend background color.
Python3
# importing package import matplotlib.pyplot as plt #Create data and plot lines.plt.plot([0, 1], [0, 2.0], label='Label-1')plt.plot([1, 2], [0, 2.1], label='Label-2')plt.plot([2, 3], [0, 2.2], label='Label-3') #Change the background color of a legend.plt.legend(facecolor="pink")plt.title("Line Graph - Geeksforgeeks") plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 24514,
"s": 24292,
"text": "In this article, we will see how can we can change the background color of a legend in our graph using MatplotLib, Here we will take two different examples to showcase different background colors of a legend in our graph."
},
{
"code": null,
"e": 24528,
"s": 24514,
"text": "Requirements:"
},
{
"code": null,
"e": 24551,
"s": 24528,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 24561,
"s": 24551,
"text": "Approach:"
},
{
"code": null,
"e": 24585,
"s": 24561,
"text": "Import required module."
},
{
"code": null,
"e": 24598,
"s": 24585,
"text": "Create data."
},
{
"code": null,
"e": 24639,
"s": 24598,
"text": "Change the background color of a legend."
},
{
"code": null,
"e": 24663,
"s": 24639,
"text": "Normally plot the data."
},
{
"code": null,
"e": 24677,
"s": 24663,
"text": "Display plot."
},
{
"code": null,
"e": 24693,
"s": 24677,
"text": "Implementation:"
},
{
"code": null,
"e": 24704,
"s": 24693,
"text": "Example 1:"
},
{
"code": null,
"e": 24865,
"s": 24704,
"text": "In this example, we will draw different lines with the help of matplotlib and Use the facecolor argument to plt.legend() to specify the legend background color."
},
{
"code": null,
"e": 24873,
"s": 24865,
"text": "Python3"
},
{
"code": "# importing package import matplotlib.pyplot as plt import numpy as np # create data X = [1,2,3,4,5] Y = [3,3,3,3,3] # plot lines plt.plot(X, Y, label = \"Line-1\") plt.plot(Y, X, label = \"Line-2\") plt.plot(X, np.sin(X), label = \"Curve-1\") plt.plot(X, np.cos(X), label = \"Curve-2\") #Change the background color of a legend.plt.legend(facecolor=\"gray\")plt.title(\"Line Graph - Geeksforgeeks\") plt.show()",
"e": 25281,
"s": 24873,
"text": null
},
{
"code": null,
"e": 25289,
"s": 25281,
"text": "Output:"
},
{
"code": null,
"e": 25300,
"s": 25289,
"text": "Example 2:"
},
{
"code": null,
"e": 25461,
"s": 25300,
"text": "In this example, we will draw a Vertical line with the help of matplotlib and Use the facecolor argument to plt.legend() to specify the legend background color."
},
{
"code": null,
"e": 25469,
"s": 25461,
"text": "Python3"
},
{
"code": "# importing package import matplotlib.pyplot as plt #Create data and plot lines.plt.plot([0, 1], [0, 2.0], label='Label-1')plt.plot([1, 2], [0, 2.1], label='Label-2')plt.plot([2, 3], [0, 2.2], label='Label-3') #Change the background color of a legend.plt.legend(facecolor=\"pink\")plt.title(\"Line Graph - Geeksforgeeks\") plt.show()",
"e": 25804,
"s": 25469,
"text": null
},
{
"code": null,
"e": 25812,
"s": 25804,
"text": "Output:"
},
{
"code": null,
"e": 25830,
"s": 25812,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 25837,
"s": 25830,
"text": "Python"
},
{
"code": null,
"e": 25935,
"s": 25837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25967,
"s": 25935,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26009,
"s": 25967,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26065,
"s": 26009,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26107,
"s": 26065,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26138,
"s": 26107,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26160,
"s": 26138,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26215,
"s": 26160,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26254,
"s": 26215,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26283,
"s": 26254,
"text": "Create a directory in Python"
}
]
|
PyQt5 QListWidget - Setting Drag Drop Property - GeeksforGeeks | 06 Aug, 2020
In this article we will see how we can set the drag drop property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Describes the various drag and drop events the view can act upon. By default the view does not support dragging or dropping (NoDragDrop). There are many options available like, drag only, drag drop, drop only, no drag drop.
In order to do this we will use setDragDropMode method with the list widget object.
Syntax : list_widget.setDragDropMode(dragdropmode)
Argument : It takes drag drop object as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting drag drop mode list_widget.setDragDropMode(QAbstractItemView.DragDrop) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24758,
"s": 24730,
"text": "\n06 Aug, 2020"
},
{
"code": null,
"e": 25275,
"s": 24758,
"text": "In this article we will see how we can set the drag drop property of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Describes the various drag and drop events the view can act upon. By default the view does not support dragging or dropping (NoDragDrop). There are many options available like, drag only, drag drop, drop only, no drag drop."
},
{
"code": null,
"e": 25359,
"s": 25275,
"text": "In order to do this we will use setDragDropMode method with the list widget object."
},
{
"code": null,
"e": 25410,
"s": 25359,
"text": "Syntax : list_widget.setDragDropMode(dragdropmode)"
},
{
"code": null,
"e": 25459,
"s": 25410,
"text": "Argument : It takes drag drop object as argument"
},
{
"code": null,
"e": 25484,
"s": 25459,
"text": "Return : It returns None"
},
{
"code": null,
"e": 25512,
"s": 25484,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting drag drop mode list_widget.setDragDropMode(QAbstractItemView.DragDrop) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 26938,
"s": 25512,
"text": null
},
{
"code": null,
"e": 26947,
"s": 26938,
"text": "Output :"
},
{
"code": null,
"e": 26971,
"s": 26947,
"text": "Python PyQt-QListWidget"
},
{
"code": null,
"e": 26982,
"s": 26971,
"text": "Python-gui"
},
{
"code": null,
"e": 26994,
"s": 26982,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27001,
"s": 26994,
"text": "Python"
},
{
"code": null,
"e": 27099,
"s": 27001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27117,
"s": 27099,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27152,
"s": 27117,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27174,
"s": 27152,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27206,
"s": 27174,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27236,
"s": 27206,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27278,
"s": 27236,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27304,
"s": 27278,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27341,
"s": 27304,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27384,
"s": 27341,
"text": "Python program to convert a list to string"
}
]
|
Program to find a list of product of all elements except the current index in Python | Suppose we have a list of numbers called nums, we have to find a new list such that each element at index i of the newly generated list is the product of all the numbers in the original list except the one at index i. Here we have to solve it without using division.
So, if the input is like nums = [2, 3, 4, 5, 6], then the output will be [360, 240, 180, 144, 120]
To solve this, we will follow these steps −
if size of nums < 1, thenreturn nums
return nums
l := size of nums
left := a list of size l and initially all values are null
right := a list of size l and initially all values are null
temp := 1
for i in range 0 to size of nums, doif i is same as 0, thenleft[i] := tempotherwise,temp := temp * nums[i - 1]left[i] := temp
if i is same as 0, thenleft[i] := temp
left[i] := temp
otherwise,temp := temp * nums[i - 1]left[i] := temp
temp := temp * nums[i - 1]
left[i] := temp
temp := 1
for i in range size of nums - 1 to 0, decrease by 1, doif i is same as size of nums - 1, thenright[i] := tempotherwise,temp := temp * nums[i + 1]right[i] := temp
if i is same as size of nums - 1, thenright[i] := temp
right[i] := temp
otherwise,temp := temp * nums[i + 1]right[i] := temp
temp := temp * nums[i + 1]
right[i] := temp
for i in range 0 to size of nums, doleft[i] := left[i] * right[i]
left[i] := left[i] * right[i]
return left
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, nums):
if len(nums) < 1:
return nums
l = len(nums)
left = [None] * l
right = [None] * l
temp = 1
for i in range(len(nums)):
if i == 0:
left[i] = temp
else:
temp = temp * nums[i - 1]
left[i] = temp
temp = 1
for i in range(len(nums) - 1, -1, -1):
if i == len(nums) - 1:
right[i] = temp
else:
temp = temp * nums[i + 1]
right[i] = temp
for i in range(len(nums)):
left[i] = left[i] * right[i]
return left
ob = Solution()
nums = [2, 3, 4, 5, 6]
print(ob.solve(nums))
[2, 3, 4, 5, 6]
[360, 240, 180, 144, 120] | [
{
"code": null,
"e": 1329,
"s": 1062,
"text": "Suppose we have a list of numbers called nums, we have to find a new list such that each element at index i of the newly generated list is the product of all the numbers in the original list except the one at index i. Here we have to solve it without using division."
},
{
"code": null,
"e": 1428,
"s": 1329,
"text": "So, if the input is like nums = [2, 3, 4, 5, 6], then the output will be [360, 240, 180, 144, 120]"
},
{
"code": null,
"e": 1472,
"s": 1428,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1509,
"s": 1472,
"text": "if size of nums < 1, thenreturn nums"
},
{
"code": null,
"e": 1521,
"s": 1509,
"text": "return nums"
},
{
"code": null,
"e": 1539,
"s": 1521,
"text": "l := size of nums"
},
{
"code": null,
"e": 1598,
"s": 1539,
"text": "left := a list of size l and initially all values are null"
},
{
"code": null,
"e": 1658,
"s": 1598,
"text": "right := a list of size l and initially all values are null"
},
{
"code": null,
"e": 1668,
"s": 1658,
"text": "temp := 1"
},
{
"code": null,
"e": 1794,
"s": 1668,
"text": "for i in range 0 to size of nums, doif i is same as 0, thenleft[i] := tempotherwise,temp := temp * nums[i - 1]left[i] := temp"
},
{
"code": null,
"e": 1833,
"s": 1794,
"text": "if i is same as 0, thenleft[i] := temp"
},
{
"code": null,
"e": 1849,
"s": 1833,
"text": "left[i] := temp"
},
{
"code": null,
"e": 1901,
"s": 1849,
"text": "otherwise,temp := temp * nums[i - 1]left[i] := temp"
},
{
"code": null,
"e": 1928,
"s": 1901,
"text": "temp := temp * nums[i - 1]"
},
{
"code": null,
"e": 1944,
"s": 1928,
"text": "left[i] := temp"
},
{
"code": null,
"e": 1954,
"s": 1944,
"text": "temp := 1"
},
{
"code": null,
"e": 2116,
"s": 1954,
"text": "for i in range size of nums - 1 to 0, decrease by 1, doif i is same as size of nums - 1, thenright[i] := tempotherwise,temp := temp * nums[i + 1]right[i] := temp"
},
{
"code": null,
"e": 2171,
"s": 2116,
"text": "if i is same as size of nums - 1, thenright[i] := temp"
},
{
"code": null,
"e": 2188,
"s": 2171,
"text": "right[i] := temp"
},
{
"code": null,
"e": 2241,
"s": 2188,
"text": "otherwise,temp := temp * nums[i + 1]right[i] := temp"
},
{
"code": null,
"e": 2268,
"s": 2241,
"text": "temp := temp * nums[i + 1]"
},
{
"code": null,
"e": 2285,
"s": 2268,
"text": "right[i] := temp"
},
{
"code": null,
"e": 2351,
"s": 2285,
"text": "for i in range 0 to size of nums, doleft[i] := left[i] * right[i]"
},
{
"code": null,
"e": 2381,
"s": 2351,
"text": "left[i] := left[i] * right[i]"
},
{
"code": null,
"e": 2393,
"s": 2381,
"text": "return left"
},
{
"code": null,
"e": 2463,
"s": 2393,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2474,
"s": 2463,
"text": " Live Demo"
},
{
"code": null,
"e": 3156,
"s": 2474,
"text": "class Solution:\n def solve(self, nums):\n if len(nums) < 1:\n return nums\n l = len(nums)\n left = [None] * l\n right = [None] * l\n temp = 1\n for i in range(len(nums)):\n if i == 0:\n left[i] = temp\n else:\n temp = temp * nums[i - 1]\n left[i] = temp\n temp = 1\n for i in range(len(nums) - 1, -1, -1):\n if i == len(nums) - 1:\n right[i] = temp\n else:\n temp = temp * nums[i + 1]\n right[i] = temp\n for i in range(len(nums)):\n left[i] = left[i] * right[i]\n return left\nob = Solution()\nnums = [2, 3, 4, 5, 6]\nprint(ob.solve(nums))"
},
{
"code": null,
"e": 3172,
"s": 3156,
"text": "[2, 3, 4, 5, 6]"
},
{
"code": null,
"e": 3198,
"s": 3172,
"text": "[360, 240, 180, 144, 120]"
}
]
|
Execute operations (plus, minus, multiply, divide) while updating a MySQL table? | Following is the syntax executing the plus (+) operator −
update yourTableName set yourColumnName3=(yourColumnName1+yourColumnName2)
The above syntax is only for plus operator. You need to change symbol like -,*,/ for other operations. Let us first create a table −
mysql> create table DemoTable
-> (
-> Number1 int,
-> Number2 int,
-> AddResult int,
-> MinusResult int,
-> MultiplyResult int,
-> DivideResult int
-> );
Query OK, 0 rows affected (0.89 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Number1,Number2) values(40,20);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+---------+-----------+-------------+----------------+--------------+
| Number1 | Number2 | AddResult | MinusResult | MultiplyResult | DivideResult |
+---------+---------+-----------+-------------+----------------+--------------+
| 40 | 20 | NULL | NULL | NULL | NULL |
+---------+---------+-----------+-------------+----------------+--------------+
1 row in set (0.00 sec)
Following is the query to execute operations like plus, minus, multiply and divide while using UPDATE in MySQL −
mysql> update DemoTable set AddResult=(Number1+Number2);
Query OK, 1 row affected (0.22 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update DemoTable set MinusResult=(Number1-Number2);
Query OK, 1 row affected (0.08 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update DemoTable set MultiplyResult=(Number1*Number2);
Query OK, 1 row affected (0.08 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update DemoTable set DivideResult=(Number1/Number2);
Query OK, 1 row affected (0.07 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+---------+---------+-----------+-------------+----------------+--------------+
| Number1 | Number2 | AddResult | MinusResult | MultiplyResult | DivideResult |
+---------+---------+-----------+-------------+----------------+--------------+
| 40 | 20 | 60 | 20 | 800 | 2 |
+---------+---------+-----------+-------------+----------------+--------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1120,
"s": 1062,
"text": "Following is the syntax executing the plus (+) operator −"
},
{
"code": null,
"e": 1195,
"s": 1120,
"text": "update yourTableName set yourColumnName3=(yourColumnName1+yourColumnName2)"
},
{
"code": null,
"e": 1328,
"s": 1195,
"text": "The above syntax is only for plus operator. You need to change symbol like -,*,/ for other operations. Let us first create a table −"
},
{
"code": null,
"e": 1543,
"s": 1328,
"text": "mysql> create table DemoTable\n -> (\n -> Number1 int,\n -> Number2 int,\n -> AddResult int,\n -> MinusResult int,\n -> MultiplyResult int,\n -> DivideResult int\n -> );\nQuery OK, 0 rows affected (0.89 sec)"
},
{
"code": null,
"e": 1599,
"s": 1543,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1696,
"s": 1599,
"text": "mysql> insert into DemoTable(Number1,Number2) values(40,20);\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1756,
"s": 1696,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1787,
"s": 1756,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1828,
"s": 1787,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2252,
"s": 1828,
"text": "+---------+---------+-----------+-------------+----------------+--------------+\n| Number1 | Number2 | AddResult | MinusResult | MultiplyResult | DivideResult |\n+---------+---------+-----------+-------------+----------------+--------------+\n| 40 | 20 | NULL | NULL | NULL | NULL |\n+---------+---------+-----------+-------------+----------------+--------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2365,
"s": 2252,
"text": "Following is the query to execute operations like plus, minus, multiply and divide while using UPDATE in MySQL −"
},
{
"code": null,
"e": 2906,
"s": 2365,
"text": "mysql> update DemoTable set AddResult=(Number1+Number2);\nQuery OK, 1 row affected (0.22 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n\nmysql> update DemoTable set MinusResult=(Number1-Number2);\nQuery OK, 1 row affected (0.08 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n\nmysql> update DemoTable set MultiplyResult=(Number1*Number2);\nQuery OK, 1 row affected (0.08 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n\nmysql> update DemoTable set DivideResult=(Number1/Number2);\nQuery OK, 1 row affected (0.07 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 2950,
"s": 2906,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2981,
"s": 2950,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 3022,
"s": 2981,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3446,
"s": 3022,
"text": "+---------+---------+-----------+-------------+----------------+--------------+\n| Number1 | Number2 | AddResult | MinusResult | MultiplyResult | DivideResult |\n+---------+---------+-----------+-------------+----------------+--------------+\n| 40 | 20 | 60 | 20 | 800 | 2 |\n+---------+---------+-----------+-------------+----------------+--------------+\n1 row in set (0.00 sec)"
}
]
|
How to connect to an already open browser using Selenium Webdriver? | We can connect to an already open browser using Selenium webdriver. This can be done using the Capabilities and ChromeOptions classes. The Capabilities class obtains the browser capabilities with the help of the getCapabilities method.
This is generally used for debugging purposes when we have a large number of steps in a test and we do not want to repeat the same steps. First of all we shall launch the browser and enter some text in the below edit box.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.By;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class ConnectBrwSession{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//get browser capabilities in key value pairs
Capabilities c = driver.getCapabilities();
Map<String, Object> m = c.asMap();
m.forEach((key, value) −> {
System.out.println("Key is: " + key + " Value is: " + value);
});
//set implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
//identify element
WebElement l = driver.findElement(By.id("gsc−i−id1"));
l.sendKeys("Selenium");
}
}
We shall note the parameter {debuggerAddress=localhost:61861} obtained from the Console output to be added to the ChromeOptions object.
Browser window −
Now, let us connect to the same browser session and perform some operations to it. We should not use browser close or quit methods while connecting to an existing session.
Code Modifications done to connect to the same session.
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.By;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
public class ConnectBrwSession{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//object of ChromeOptions class
ChromeOptions o = new ChromeOptions();
//setting debuggerAddress value
o.setExperimentalOption("debuggerAddress", "localhost:61861");
//add options to browser capabilities
Capabilities c = driver.getCapabilities(o);
Map<String, Object> m = c.asMap();
m.forEach((key, value) −> {
System.out.println("Key is: " + key + " Value is: " + value);
});
//set implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//identify element
WebElement l = driver.findElement(By.id("gsc−i−id1"));
//remove existing data in edit box
l.clear();
l.sendKeys("Tutorialspoint");
String s = l.getAttribute("value");
System.out.println("Attribute value: " + s);
}
} | [
{
"code": null,
"e": 1298,
"s": 1062,
"text": "We can connect to an already open browser using Selenium webdriver. This can be done using the Capabilities and ChromeOptions classes. The Capabilities class obtains the browser capabilities with the help of the getCapabilities method."
},
{
"code": null,
"e": 1520,
"s": 1298,
"text": "This is generally used for debugging purposes when we have a large number of steps in a test and we do not want to repeat the same steps. First of all we shall launch the browser and enter some text in the below edit box."
},
{
"code": null,
"e": 2597,
"s": 1520,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.By;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\npublic class ConnectBrwSession{\n public static void main(String[] args)\n throws InterruptedException{\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //get browser capabilities in key value pairs\n Capabilities c = driver.getCapabilities();\n Map<String, Object> m = c.asMap();\n m.forEach((key, value) −> {\n System.out.println(\"Key is: \" + key + \" Value is: \" + value);\n });\n //set implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n //identify element\n WebElement l = driver.findElement(By.id(\"gsc−i−id1\"));\n l.sendKeys(\"Selenium\");\n }\n}"
},
{
"code": null,
"e": 2733,
"s": 2597,
"text": "We shall note the parameter {debuggerAddress=localhost:61861} obtained from the Console output to be added to the ChromeOptions object."
},
{
"code": null,
"e": 2750,
"s": 2733,
"text": "Browser window −"
},
{
"code": null,
"e": 2922,
"s": 2750,
"text": "Now, let us connect to the same browser session and perform some operations to it. We should not use browser close or quit methods while connecting to an existing session."
},
{
"code": null,
"e": 2978,
"s": 2922,
"text": "Code Modifications done to connect to the same session."
},
{
"code": null,
"e": 4368,
"s": 2978,
"text": "import org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.By;\nimport java.util.Map;\nimport org.openqa.selenium.WebDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ConnectBrwSession{\n public static void main(String[] args)\n throws InterruptedException{\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //object of ChromeOptions class\n ChromeOptions o = new ChromeOptions();\n //setting debuggerAddress value\n o.setExperimentalOption(\"debuggerAddress\", \"localhost:61861\");\n //add options to browser capabilities\n Capabilities c = driver.getCapabilities(o);\n Map<String, Object> m = c.asMap();\n m.forEach((key, value) −> {\n System.out.println(\"Key is: \" + key + \" Value is: \" + value);\n });\n //set implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //identify element\n WebElement l = driver.findElement(By.id(\"gsc−i−id1\"));\n //remove existing data in edit box\n l.clear();\n l.sendKeys(\"Tutorialspoint\");\n String s = l.getAttribute(\"value\");\n System.out.println(\"Attribute value: \" + s);\n }\n}"
}
]
|
Group thousands of similar spreadsheet text cells in seconds | by Luke Whyte | Towards Data Science | Here’s a common spreadsheet or database problem:
+-----+-------------------+| row | fullname |+-----+-------------------+| 1 | John F. Doe || 2 | Esquivel, Mara || 3 | Doe, John F || 4 | Whyte, Luke || 5 | Doe, John Francis |+-----+-------------------+
Rows 1, 3 and 5 likely refer to the same person with slight deviations in spelling and formatting. In small datasets, the cells can be cleaned by hand. But what about in huge datasets? How do we comb thousands of text entries and group similar entities?
Ideally, there’d be an easy way to add a third column like this:
+-----+-------------------+---------------+| row | fullname | name_groups |+-----+-------------------+---------------+| 1 | John F. Doe | Doe John F || 2 | Esquivel, Mara | Esquivel Mara || 3 | Doe, John F | Doe John F || 4 | Whyte, Luke | Whyte Luke || 5 | Doe, John Francis | Doe John F |+-----+-------------------+---------------+
Well, there is and thats what we’re going to do.
TLDR: I built a tool for this. You can install the Python module here. But if you want to learn about the concepts behind the tool — or if you just distrust me vehemently (Hi, Honey) — read on.
Topics we’ll cover:
Building a Document Term Matrix with TF-IDF and N-GramsUsing cosine similarity to calculate proximity between stringsUsing a hash table to convert our findings to a “groups” column in our spreadsheet
Building a Document Term Matrix with TF-IDF and N-Grams
Using cosine similarity to calculate proximity between strings
Using a hash table to convert our findings to a “groups” column in our spreadsheet
For this tutorial, I’m going to use this dataset of U.S. Department of Labor wage theft investigations. It contains every DOL investigation of employers due to minimum wage or overtime violations from 1984 through 2018.
The data includes a legal_name column, which lists the name of the company being investigated. However, entry formats vary wildly:
+-----+----------------------+| row | legal_name |+-----+----------------------+| 1 | Wal-mart Inc || 2 | Walmart Stores Inc. || 3 | Wal-mart stores Inc || 4 | Wal-Mart stores Inc. |+-----+----------------------+
We’ll normalize and group the entries under legal_name then use our groups to do some quick analysis.
Our biggest challenge here is that every entry in our column needs to be compared with every other entry. Thus, a sheet with 400,000 rows necessitates 400,0002 calculations, and my laptop overheats when I open Netflix before remembering to close Photoshop.
It would be much faster if we could use matrix multiplication to make simultaneous calculations, which we can do with a Document Term Matrix, TF-IDF and N-Grams.
Lets define those terms:
Document Term Matrix
A Document Term Matrix is essentially an extension of the Bag of Words (BOW) concept, which I love because it sounds like something a masked man would steal on Sesame Street.
BOW involves counting the frequency of words in a string. So, given the sentence:
“Rhode Island is neither a road nor is it an island. Discuss.”
We can produce a BOW representation like this:
+---------+-------+| term | count |+---------+-------+| rhode | 1 || island | 2 || is | 2 || neither | 1 || a | 1 || road | 1 || nor | 1 || it | 1 || an | 1 || discuss | 1 |+---------+-------+
A Document Term Matrix (DTM) extends BOW to multiple strings (or, in the nomenclature, “multiple documents”). Imagine we have the following three strings:
“Even my brother has needs”“My brother needs a lift”“Bro, do you even lift?”
“Even my brother has needs”
“My brother needs a lift”
“Bro, do you even lift?”
The DTM could look like this:
The value of each entry is determined by counting how many times each word appears in each string.
The problem with the above approach is that insignificant words like ‘the’, ‘is’ and ‘if’ tend to appear more frequently than important words, which could skew our analysis.
Thus, instead of counting words, we can assign them a TF-IDF score, which evaluates the importance of each word to the DTM.
TF-IDF
To calculate TF-IDF scores, we multiply the amount of times a term appears in a single document (Term Frequency or TF) by the significance of the term to the whole corpus (Inverse Document Frequency or IDF) — the more documents a word appears in, the less valuable that word is thought to be in differentiating documents from one another.
Take a gander here if you are interested in the math behind calculating TF-IDF scores.
The important takeaway is that, for each word in our Document Term Matrix, if we replace the word count with a TF-IDF score, we can weigh words more effectively when checking for string similarity.
N-Grams
Finally we’ll tackle this problem:
Burger Kingis two words. BurgerKing should be two words, but a computer will see it as one. Thus, when we calculate our Document Term Matrix, these terms won’t match.
N-grams are a way of breaking strings into smaller chunks where N is the size of the chunk. So, if we set N to 3, we get:
['Bur', 'urg', 'rge', 'ger', 'er ', 'r K', ' Ki', 'Kin', 'ing']
and:
['Bur', 'urg', 'rge', 'ger', 'erK', 'rKi', 'Kin', 'ing']
which have significantly more overlap than the original strings.
Thus when we construct our Document Term Matrix, lets calculate the TF-IDF score for N-Grams instead of words.
Finally, some code:
Here’s the code for building a Document Term Matrix with N-Grams as column headers and TF-IDF scores for values:
On line 6, we convert our CSV to a Pandas DataFrame.
Line 10 extracts unique values from the legal_name column of the dataset and places them in a one-dimensional NumPy array.
On line 14, we write the function for building our 5 character N-Grams (I pulled the function from here). A few characters are filtered out using a regular expression.
Line 20 passes the ngrams_analyzer to the TF-IDF vectorizer we’ll use to build out matrix.
Finally, on line 23, we build our Document Term Matrix.
Sparse vs dense matrices and how to crash your computer
The result of the above code, tfidf_matrix, is a Compressed Sparse Row (CSR) matrix.
If you are unfamiliar with sparse matrices, this is a great introduction. For our purposes, know that any matrix of mostly zero values is a sparse matrix. This is distinct from a dense matrix of mostly non-zero values.
Our matrix of N-Grams has 237,573 rows and 389,905 columns. The first 10 rows and columns look like this:
That’s pretty sparse. There’s no reason to store all those zeros in memory. If we do, there’s a chance we’ll run out of RAM and trigger a MemoryError.
Enter the CSR matrix, which stores only the matrix’s nonzero values and references to their original location.
This is an oversimplification and you can learn the nitty gritty here. The important takeaway is that the CSR format saves memory while still allowing for fast row access and matrix multiplication.
Cosine similarity is a metric between 0 and 1 used to determine how similar strings are irrespective of their length.
It measures the cosine of the angle between strings in a multidimensional space. The closer that value is to 1 (cosine of 0°), the higher the string similarity.
Take the following three strings:
I love dogsI love love love love love love love dogsI hate hate hate cats
I love dogs
I love love love love love love love dogs
I hate hate hate cats
And put them in a Document Term Matrix:
Then plot this matrix on a multidimensional space where each dimension corresponds to one of our four terms. That could look something like this:
If we look at the distance between our points, “I love dogs” and “I hate cats” are physically closer to one another than “I love dogs” and “I love ... love dogs”.
However, if we look at the angle between our points’ lines — the cosine distance — we can see that the angle between “I love dogs” and “I love ... love dogs” is much smaller than the angle between “I love dogs” and “I hate cats”.
Thus, the cosine similarity between String 1 and String 2 will be a higher (closer to 1) than the cosine similarity between String 1 and String 3.
Here’s a deeper explanation.
Calculating cosine similarity in Python
We could use scikit-learn to calculate cosine similarity. This would return a pairwise matrix with cosine similarity values like:
We would then filter this matrix by a similarity threshold — something like 0.75 or 0.8 — in order to group strings we believe represent the same entity.
However, if instead we use this module built by the data scientists at ING Bank, we can filter by our similarity threshold as we build the matrix. The approach is faster than scikit-learn and returns a less memory intensive CSR matrix for us to work with.
ING wrote a blog post explaining why, if you’re interested.
So, let’s add the following to our script:
Now we have a CSR matrix representing the cosine similarity between all our strings. Time to bring it home.
We’re now going to build a Python dictionary with a key for each unique string in our legal_name column.
The fastest way to do this is to convert our CSR matrix to a Coordinate (COO) matrix. A COO matrix is another representation of a sparse matrix.
By example, if we have this sparse matrix:
+------------+| 0, 0, 0, 4 || 0, 1, 0, 0 || 0, 0, 0, 0 || 3, 0, 0, 7 |+------------+
And we convert it to a COO matrix, it will become an object with three properties — row, col, data — that containing the following three arrays, respectively:
[0, 1, 3, 3]: The row index for each non-zero value (0-indexed)[3, 1, 0, 3]: The column index for each non-zero value (0-indexed)[4, 1, 3, 7]: The non-zero values from our matrix
[0, 1, 3, 3]: The row index for each non-zero value (0-indexed)
[3, 1, 0, 3]: The column index for each non-zero value (0-indexed)
[4, 1, 3, 7]: The non-zero values from our matrix
Thus, we can say that the coordinates for the value 4(stored in matrix.data[0]) are (0,3)(stored in (matrix.row[0],matrix.col[0]).
Let’s build our COO matrix and use it to populate our dictionary:
On line 2 we convert our cosine matrix to a coordinate matrix.
On lines 39–43 we iterate through our coordinate matrix, pull out the row and column indices for our non-zero values — which, remember, all have a cosine similarity of over 0.8 — and then convert them to their string values.
To clarify, let’s unpack lines 39–43 further with a stripped down example. Again, take this cosine matrix:
If we’d built it using awesome_cossim_topn with the threshold set to 0.8 and then converted it to a COO matrix, we could represent it like this:
(row, col) | data ------------|------ (0,0) | 1 (0,2) | 0.84 (1,1) | 1 (2,0) | 0.84 (2,2) | 1
vals would equal ['Walmart', 'Target', 'Wal-mart stores'].
Thus, inside the loop, our first (row, col) pair to pass the row != col conditional would be (0, 2) which we then pass to add_pair_to_lookup as (vals[0], vals[2) or ('Walmart', 'Wal-mart stores').
Continuing with this example, after all our strings pass through add_pair_to_lookup, we’d end up with:
>>> group_lookup{ 'Walmart': 'Walmart', 'Wal-mart stores': 'Walmart'}
There are no strings similar to ‘Target’, thus it is not assigned a group.
Vectorize that Panda
Finally, we can use the power of vectorization in Pandas, to map each legal_name value to a new Group column in our DataFrame and export our new CSV.
Since Pandas functions can operate on an entire array simultaneously — instead of sequentially on individual values — this process is very fast:
The fillna method allows us to substitute the legal_name value for Group when no key exists in group_lookup.
Putting it all together:
All that is left to do is throw this data into a Pivot Table and see which employers owe(d) the most in back wages to employees.
Spoiler alert: it’s Wal-Mart. 183 investigations have resulted in almost $41 million in back wages that they’ve agreed to pay.
One last note
If you wanted to group by two or more columns instead of one, one approach could be to create a temporary column for grouping in your DataFrame of just the entries for each column concatenated into a single string:
columns_to_group = ['legal_name', 'address']df['grouper'] = df[ columns_to_group.pop(0)].astype(str).str.cat( df[columns_to_group].astype(str))
You would then set vals as:
vals = df['grouper'].unique().astype('U')
And, when exporting at the end, drop that column:
df.drop(columns=['grouper']).to_csv('./dol-data-grouped.csv')
Again, I created a Python module to do all this. Check it out!! | [
{
"code": null,
"e": 221,
"s": 172,
"text": "Here’s a common spreadsheet or database problem:"
},
{
"code": null,
"e": 465,
"s": 221,
"text": "+-----+-------------------+| row | fullname |+-----+-------------------+| 1 | John F. Doe || 2 | Esquivel, Mara || 3 | Doe, John F || 4 | Whyte, Luke || 5 | Doe, John Francis |+-----+-------------------+"
},
{
"code": null,
"e": 719,
"s": 465,
"text": "Rows 1, 3 and 5 likely refer to the same person with slight deviations in spelling and formatting. In small datasets, the cells can be cleaned by hand. But what about in huge datasets? How do we comb thousands of text entries and group similar entities?"
},
{
"code": null,
"e": 784,
"s": 719,
"text": "Ideally, there’d be an easy way to add a third column like this:"
},
{
"code": null,
"e": 1172,
"s": 784,
"text": "+-----+-------------------+---------------+| row | fullname | name_groups |+-----+-------------------+---------------+| 1 | John F. Doe | Doe John F || 2 | Esquivel, Mara | Esquivel Mara || 3 | Doe, John F | Doe John F || 4 | Whyte, Luke | Whyte Luke || 5 | Doe, John Francis | Doe John F |+-----+-------------------+---------------+"
},
{
"code": null,
"e": 1221,
"s": 1172,
"text": "Well, there is and thats what we’re going to do."
},
{
"code": null,
"e": 1415,
"s": 1221,
"text": "TLDR: I built a tool for this. You can install the Python module here. But if you want to learn about the concepts behind the tool — or if you just distrust me vehemently (Hi, Honey) — read on."
},
{
"code": null,
"e": 1435,
"s": 1415,
"text": "Topics we’ll cover:"
},
{
"code": null,
"e": 1635,
"s": 1435,
"text": "Building a Document Term Matrix with TF-IDF and N-GramsUsing cosine similarity to calculate proximity between stringsUsing a hash table to convert our findings to a “groups” column in our spreadsheet"
},
{
"code": null,
"e": 1691,
"s": 1635,
"text": "Building a Document Term Matrix with TF-IDF and N-Grams"
},
{
"code": null,
"e": 1754,
"s": 1691,
"text": "Using cosine similarity to calculate proximity between strings"
},
{
"code": null,
"e": 1837,
"s": 1754,
"text": "Using a hash table to convert our findings to a “groups” column in our spreadsheet"
},
{
"code": null,
"e": 2057,
"s": 1837,
"text": "For this tutorial, I’m going to use this dataset of U.S. Department of Labor wage theft investigations. It contains every DOL investigation of employers due to minimum wage or overtime violations from 1984 through 2018."
},
{
"code": null,
"e": 2188,
"s": 2057,
"text": "The data includes a legal_name column, which lists the name of the company being investigated. However, entry formats vary wildly:"
},
{
"code": null,
"e": 2429,
"s": 2188,
"text": "+-----+----------------------+| row | legal_name |+-----+----------------------+| 1 | Wal-mart Inc || 2 | Walmart Stores Inc. || 3 | Wal-mart stores Inc || 4 | Wal-Mart stores Inc. |+-----+----------------------+"
},
{
"code": null,
"e": 2531,
"s": 2429,
"text": "We’ll normalize and group the entries under legal_name then use our groups to do some quick analysis."
},
{
"code": null,
"e": 2788,
"s": 2531,
"text": "Our biggest challenge here is that every entry in our column needs to be compared with every other entry. Thus, a sheet with 400,000 rows necessitates 400,0002 calculations, and my laptop overheats when I open Netflix before remembering to close Photoshop."
},
{
"code": null,
"e": 2950,
"s": 2788,
"text": "It would be much faster if we could use matrix multiplication to make simultaneous calculations, which we can do with a Document Term Matrix, TF-IDF and N-Grams."
},
{
"code": null,
"e": 2975,
"s": 2950,
"text": "Lets define those terms:"
},
{
"code": null,
"e": 2996,
"s": 2975,
"text": "Document Term Matrix"
},
{
"code": null,
"e": 3171,
"s": 2996,
"text": "A Document Term Matrix is essentially an extension of the Bag of Words (BOW) concept, which I love because it sounds like something a masked man would steal on Sesame Street."
},
{
"code": null,
"e": 3253,
"s": 3171,
"text": "BOW involves counting the frequency of words in a string. So, given the sentence:"
},
{
"code": null,
"e": 3316,
"s": 3253,
"text": "“Rhode Island is neither a road nor is it an island. Discuss.”"
},
{
"code": null,
"e": 3363,
"s": 3316,
"text": "We can produce a BOW representation like this:"
},
{
"code": null,
"e": 3630,
"s": 3363,
"text": "+---------+-------+| term | count |+---------+-------+| rhode | 1 || island | 2 || is | 2 || neither | 1 || a | 1 || road | 1 || nor | 1 || it | 1 || an | 1 || discuss | 1 |+---------+-------+"
},
{
"code": null,
"e": 3785,
"s": 3630,
"text": "A Document Term Matrix (DTM) extends BOW to multiple strings (or, in the nomenclature, “multiple documents”). Imagine we have the following three strings:"
},
{
"code": null,
"e": 3862,
"s": 3785,
"text": "“Even my brother has needs”“My brother needs a lift”“Bro, do you even lift?”"
},
{
"code": null,
"e": 3890,
"s": 3862,
"text": "“Even my brother has needs”"
},
{
"code": null,
"e": 3916,
"s": 3890,
"text": "“My brother needs a lift”"
},
{
"code": null,
"e": 3941,
"s": 3916,
"text": "“Bro, do you even lift?”"
},
{
"code": null,
"e": 3971,
"s": 3941,
"text": "The DTM could look like this:"
},
{
"code": null,
"e": 4070,
"s": 3971,
"text": "The value of each entry is determined by counting how many times each word appears in each string."
},
{
"code": null,
"e": 4244,
"s": 4070,
"text": "The problem with the above approach is that insignificant words like ‘the’, ‘is’ and ‘if’ tend to appear more frequently than important words, which could skew our analysis."
},
{
"code": null,
"e": 4368,
"s": 4244,
"text": "Thus, instead of counting words, we can assign them a TF-IDF score, which evaluates the importance of each word to the DTM."
},
{
"code": null,
"e": 4375,
"s": 4368,
"text": "TF-IDF"
},
{
"code": null,
"e": 4714,
"s": 4375,
"text": "To calculate TF-IDF scores, we multiply the amount of times a term appears in a single document (Term Frequency or TF) by the significance of the term to the whole corpus (Inverse Document Frequency or IDF) — the more documents a word appears in, the less valuable that word is thought to be in differentiating documents from one another."
},
{
"code": null,
"e": 4801,
"s": 4714,
"text": "Take a gander here if you are interested in the math behind calculating TF-IDF scores."
},
{
"code": null,
"e": 4999,
"s": 4801,
"text": "The important takeaway is that, for each word in our Document Term Matrix, if we replace the word count with a TF-IDF score, we can weigh words more effectively when checking for string similarity."
},
{
"code": null,
"e": 5007,
"s": 4999,
"text": "N-Grams"
},
{
"code": null,
"e": 5042,
"s": 5007,
"text": "Finally we’ll tackle this problem:"
},
{
"code": null,
"e": 5209,
"s": 5042,
"text": "Burger Kingis two words. BurgerKing should be two words, but a computer will see it as one. Thus, when we calculate our Document Term Matrix, these terms won’t match."
},
{
"code": null,
"e": 5331,
"s": 5209,
"text": "N-grams are a way of breaking strings into smaller chunks where N is the size of the chunk. So, if we set N to 3, we get:"
},
{
"code": null,
"e": 5395,
"s": 5331,
"text": "['Bur', 'urg', 'rge', 'ger', 'er ', 'r K', ' Ki', 'Kin', 'ing']"
},
{
"code": null,
"e": 5400,
"s": 5395,
"text": "and:"
},
{
"code": null,
"e": 5457,
"s": 5400,
"text": "['Bur', 'urg', 'rge', 'ger', 'erK', 'rKi', 'Kin', 'ing']"
},
{
"code": null,
"e": 5522,
"s": 5457,
"text": "which have significantly more overlap than the original strings."
},
{
"code": null,
"e": 5633,
"s": 5522,
"text": "Thus when we construct our Document Term Matrix, lets calculate the TF-IDF score for N-Grams instead of words."
},
{
"code": null,
"e": 5653,
"s": 5633,
"text": "Finally, some code:"
},
{
"code": null,
"e": 5766,
"s": 5653,
"text": "Here’s the code for building a Document Term Matrix with N-Grams as column headers and TF-IDF scores for values:"
},
{
"code": null,
"e": 5819,
"s": 5766,
"text": "On line 6, we convert our CSV to a Pandas DataFrame."
},
{
"code": null,
"e": 5942,
"s": 5819,
"text": "Line 10 extracts unique values from the legal_name column of the dataset and places them in a one-dimensional NumPy array."
},
{
"code": null,
"e": 6110,
"s": 5942,
"text": "On line 14, we write the function for building our 5 character N-Grams (I pulled the function from here). A few characters are filtered out using a regular expression."
},
{
"code": null,
"e": 6201,
"s": 6110,
"text": "Line 20 passes the ngrams_analyzer to the TF-IDF vectorizer we’ll use to build out matrix."
},
{
"code": null,
"e": 6257,
"s": 6201,
"text": "Finally, on line 23, we build our Document Term Matrix."
},
{
"code": null,
"e": 6313,
"s": 6257,
"text": "Sparse vs dense matrices and how to crash your computer"
},
{
"code": null,
"e": 6398,
"s": 6313,
"text": "The result of the above code, tfidf_matrix, is a Compressed Sparse Row (CSR) matrix."
},
{
"code": null,
"e": 6617,
"s": 6398,
"text": "If you are unfamiliar with sparse matrices, this is a great introduction. For our purposes, know that any matrix of mostly zero values is a sparse matrix. This is distinct from a dense matrix of mostly non-zero values."
},
{
"code": null,
"e": 6723,
"s": 6617,
"text": "Our matrix of N-Grams has 237,573 rows and 389,905 columns. The first 10 rows and columns look like this:"
},
{
"code": null,
"e": 6874,
"s": 6723,
"text": "That’s pretty sparse. There’s no reason to store all those zeros in memory. If we do, there’s a chance we’ll run out of RAM and trigger a MemoryError."
},
{
"code": null,
"e": 6985,
"s": 6874,
"text": "Enter the CSR matrix, which stores only the matrix’s nonzero values and references to their original location."
},
{
"code": null,
"e": 7183,
"s": 6985,
"text": "This is an oversimplification and you can learn the nitty gritty here. The important takeaway is that the CSR format saves memory while still allowing for fast row access and matrix multiplication."
},
{
"code": null,
"e": 7301,
"s": 7183,
"text": "Cosine similarity is a metric between 0 and 1 used to determine how similar strings are irrespective of their length."
},
{
"code": null,
"e": 7462,
"s": 7301,
"text": "It measures the cosine of the angle between strings in a multidimensional space. The closer that value is to 1 (cosine of 0°), the higher the string similarity."
},
{
"code": null,
"e": 7496,
"s": 7462,
"text": "Take the following three strings:"
},
{
"code": null,
"e": 7570,
"s": 7496,
"text": "I love dogsI love love love love love love love dogsI hate hate hate cats"
},
{
"code": null,
"e": 7582,
"s": 7570,
"text": "I love dogs"
},
{
"code": null,
"e": 7624,
"s": 7582,
"text": "I love love love love love love love dogs"
},
{
"code": null,
"e": 7646,
"s": 7624,
"text": "I hate hate hate cats"
},
{
"code": null,
"e": 7686,
"s": 7646,
"text": "And put them in a Document Term Matrix:"
},
{
"code": null,
"e": 7832,
"s": 7686,
"text": "Then plot this matrix on a multidimensional space where each dimension corresponds to one of our four terms. That could look something like this:"
},
{
"code": null,
"e": 7995,
"s": 7832,
"text": "If we look at the distance between our points, “I love dogs” and “I hate cats” are physically closer to one another than “I love dogs” and “I love ... love dogs”."
},
{
"code": null,
"e": 8225,
"s": 7995,
"text": "However, if we look at the angle between our points’ lines — the cosine distance — we can see that the angle between “I love dogs” and “I love ... love dogs” is much smaller than the angle between “I love dogs” and “I hate cats”."
},
{
"code": null,
"e": 8372,
"s": 8225,
"text": "Thus, the cosine similarity between String 1 and String 2 will be a higher (closer to 1) than the cosine similarity between String 1 and String 3."
},
{
"code": null,
"e": 8401,
"s": 8372,
"text": "Here’s a deeper explanation."
},
{
"code": null,
"e": 8441,
"s": 8401,
"text": "Calculating cosine similarity in Python"
},
{
"code": null,
"e": 8571,
"s": 8441,
"text": "We could use scikit-learn to calculate cosine similarity. This would return a pairwise matrix with cosine similarity values like:"
},
{
"code": null,
"e": 8725,
"s": 8571,
"text": "We would then filter this matrix by a similarity threshold — something like 0.75 or 0.8 — in order to group strings we believe represent the same entity."
},
{
"code": null,
"e": 8981,
"s": 8725,
"text": "However, if instead we use this module built by the data scientists at ING Bank, we can filter by our similarity threshold as we build the matrix. The approach is faster than scikit-learn and returns a less memory intensive CSR matrix for us to work with."
},
{
"code": null,
"e": 9041,
"s": 8981,
"text": "ING wrote a blog post explaining why, if you’re interested."
},
{
"code": null,
"e": 9084,
"s": 9041,
"text": "So, let’s add the following to our script:"
},
{
"code": null,
"e": 9192,
"s": 9084,
"text": "Now we have a CSR matrix representing the cosine similarity between all our strings. Time to bring it home."
},
{
"code": null,
"e": 9297,
"s": 9192,
"text": "We’re now going to build a Python dictionary with a key for each unique string in our legal_name column."
},
{
"code": null,
"e": 9442,
"s": 9297,
"text": "The fastest way to do this is to convert our CSR matrix to a Coordinate (COO) matrix. A COO matrix is another representation of a sparse matrix."
},
{
"code": null,
"e": 9485,
"s": 9442,
"text": "By example, if we have this sparse matrix:"
},
{
"code": null,
"e": 9570,
"s": 9485,
"text": "+------------+| 0, 0, 0, 4 || 0, 1, 0, 0 || 0, 0, 0, 0 || 3, 0, 0, 7 |+------------+"
},
{
"code": null,
"e": 9729,
"s": 9570,
"text": "And we convert it to a COO matrix, it will become an object with three properties — row, col, data — that containing the following three arrays, respectively:"
},
{
"code": null,
"e": 9908,
"s": 9729,
"text": "[0, 1, 3, 3]: The row index for each non-zero value (0-indexed)[3, 1, 0, 3]: The column index for each non-zero value (0-indexed)[4, 1, 3, 7]: The non-zero values from our matrix"
},
{
"code": null,
"e": 9972,
"s": 9908,
"text": "[0, 1, 3, 3]: The row index for each non-zero value (0-indexed)"
},
{
"code": null,
"e": 10039,
"s": 9972,
"text": "[3, 1, 0, 3]: The column index for each non-zero value (0-indexed)"
},
{
"code": null,
"e": 10089,
"s": 10039,
"text": "[4, 1, 3, 7]: The non-zero values from our matrix"
},
{
"code": null,
"e": 10220,
"s": 10089,
"text": "Thus, we can say that the coordinates for the value 4(stored in matrix.data[0]) are (0,3)(stored in (matrix.row[0],matrix.col[0])."
},
{
"code": null,
"e": 10286,
"s": 10220,
"text": "Let’s build our COO matrix and use it to populate our dictionary:"
},
{
"code": null,
"e": 10349,
"s": 10286,
"text": "On line 2 we convert our cosine matrix to a coordinate matrix."
},
{
"code": null,
"e": 10574,
"s": 10349,
"text": "On lines 39–43 we iterate through our coordinate matrix, pull out the row and column indices for our non-zero values — which, remember, all have a cosine similarity of over 0.8 — and then convert them to their string values."
},
{
"code": null,
"e": 10681,
"s": 10574,
"text": "To clarify, let’s unpack lines 39–43 further with a stripped down example. Again, take this cosine matrix:"
},
{
"code": null,
"e": 10826,
"s": 10681,
"text": "If we’d built it using awesome_cossim_topn with the threshold set to 0.8 and then converted it to a COO matrix, we could represent it like this:"
},
{
"code": null,
"e": 10968,
"s": 10826,
"text": " (row, col) | data ------------|------ (0,0) | 1 (0,2) | 0.84 (1,1) | 1 (2,0) | 0.84 (2,2) | 1"
},
{
"code": null,
"e": 11027,
"s": 10968,
"text": "vals would equal ['Walmart', 'Target', 'Wal-mart stores']."
},
{
"code": null,
"e": 11224,
"s": 11027,
"text": "Thus, inside the loop, our first (row, col) pair to pass the row != col conditional would be (0, 2) which we then pass to add_pair_to_lookup as (vals[0], vals[2) or ('Walmart', 'Wal-mart stores')."
},
{
"code": null,
"e": 11327,
"s": 11224,
"text": "Continuing with this example, after all our strings pass through add_pair_to_lookup, we’d end up with:"
},
{
"code": null,
"e": 11403,
"s": 11327,
"text": ">>> group_lookup{ 'Walmart': 'Walmart', 'Wal-mart stores': 'Walmart'}"
},
{
"code": null,
"e": 11478,
"s": 11403,
"text": "There are no strings similar to ‘Target’, thus it is not assigned a group."
},
{
"code": null,
"e": 11499,
"s": 11478,
"text": "Vectorize that Panda"
},
{
"code": null,
"e": 11649,
"s": 11499,
"text": "Finally, we can use the power of vectorization in Pandas, to map each legal_name value to a new Group column in our DataFrame and export our new CSV."
},
{
"code": null,
"e": 11794,
"s": 11649,
"text": "Since Pandas functions can operate on an entire array simultaneously — instead of sequentially on individual values — this process is very fast:"
},
{
"code": null,
"e": 11903,
"s": 11794,
"text": "The fillna method allows us to substitute the legal_name value for Group when no key exists in group_lookup."
},
{
"code": null,
"e": 11928,
"s": 11903,
"text": "Putting it all together:"
},
{
"code": null,
"e": 12057,
"s": 11928,
"text": "All that is left to do is throw this data into a Pivot Table and see which employers owe(d) the most in back wages to employees."
},
{
"code": null,
"e": 12184,
"s": 12057,
"text": "Spoiler alert: it’s Wal-Mart. 183 investigations have resulted in almost $41 million in back wages that they’ve agreed to pay."
},
{
"code": null,
"e": 12198,
"s": 12184,
"text": "One last note"
},
{
"code": null,
"e": 12413,
"s": 12198,
"text": "If you wanted to group by two or more columns instead of one, one approach could be to create a temporary column for grouping in your DataFrame of just the entries for each column concatenated into a single string:"
},
{
"code": null,
"e": 12561,
"s": 12413,
"text": "columns_to_group = ['legal_name', 'address']df['grouper'] = df[ columns_to_group.pop(0)].astype(str).str.cat( df[columns_to_group].astype(str))"
},
{
"code": null,
"e": 12589,
"s": 12561,
"text": "You would then set vals as:"
},
{
"code": null,
"e": 12631,
"s": 12589,
"text": "vals = df['grouper'].unique().astype('U')"
},
{
"code": null,
"e": 12681,
"s": 12631,
"text": "And, when exporting at the end, drop that column:"
},
{
"code": null,
"e": 12743,
"s": 12681,
"text": "df.drop(columns=['grouper']).to_csv('./dol-data-grouped.csv')"
}
]
|
Databricks: How to Save Data Frames as CSV Files on Your Local Computer | by Deborah Kewon | Towards Data Science | When I work on Python projects dealing with large datasets, I usually use Spyder. The environment of Spyder is very simple; I can browse through working directories, maintain large code bases and review data frames I create. However, if I don’t subset the large data, I constantly face memory issues and struggle with very long computational time. For this reason, I occasionally use Databricks. Databricks is a Microsoft Azure platform where you can easily parse large amounts of data into “notebooks” and perform Apache Spark-based analytics.
If you want to work with data frames and run models using pyspark, you can easily refer to Databricks’ website for more information. However, while working on Databricks, I noticed that saving files in CSV, which is supposed to be quite easy, is not very straightforward. In the following section, I would like to share how you can save data frames from Databricks into CSV format on your local computer with no hassles.
From Azure Databricks home, you can go to “Upload Data” (under Common Tasks)→ “DBFS” → “FileStore”.
DBFS FileStore is where you create folders and save your data frames into CSV format. By default, FileStore has three folders: import-stage, plots, and tables.
Sample.coalesce(1).write.format(“com.databricks.spark.csv”).option(“header”, “true”).save(“dbfs:/FileStore/df/Sample.csv”)
Using the above code on the notebook, I created a folder “df” and saved a data frame “Sample” into CSV. It is important to use coalesce(1) since it saves the data frame as a whole. At the end of this article, I will also demonstrate what happens when you don’t include coalesce(1) in the code.
Once you convert your data frame into CSV, go to your FileStore. You will see the folder and files you create. The “part-00000” is the CSV file I had to download on my local computer. I copied the path after /FileStore/ for step 3.
In order to download the CSV file located in DBFS FileStore on your local computer, you will have to change the highlighted URL to the following:
https://westeurope.azuredatabricks.net/files/df/Sample.csv/part-00000-tid-8365188928461432060–63d7293d-3b02–43ff-b461-edd732f9e06e-4704-c000.csv?o=3847738880082577
As you noticed, the CSV path in bold (df/Sample.csv/part-00000-tid-8365188928461432060–63d7293d-3b02–43ff-b461-edd732f9e06e-4704-c000.csv) is from step 2. The number (3847738880082577) is from the original URL.
When you change the URL as described above and press enter, the CSV file will be automatically downloaded on your local computer.
dbutils.fs.rm(“/FileStore/df”,True)
If you want to delete files in the FileStore, you can simply use the above code. Once it is deleted, you will get the comment “True”.
As promised earlier, here are the details when you don’t include coalesce(1) in the code.
By default, Databricks saves data into many partitions. Coalesce(1) combines all the files into one and solves this partitioning problem. However, it is not a good idea to use coalesce (1) or repartition (1) when you deal with very big datasets (>1TB, low velocity) because it transfers all the data to a single worker, which causes out of memory issues and slow processing. In this case, parsing by column or distributing to more than one single worker is recommended.
On a side note, there are also two other methods to save data frames as CSV files on your local computer:
Using “Download full results”
Using “Download full results”
This method is the easiest. However, Databricks downloads only up to 1 million rows. Therefore, if you have a data frame that is more than 1 million rows, I recommend you to use the above method or Databricks CLI as below.
2. Using Databricks CLI
Databricks CLI (Databricks command-line interface), which is built on top of the Databricks REST API, interacts with Databricks workspaces and filesystem APIs. Databricks CLI needs some set-ups, but you can also use this method to download your data frames on your local computer. For more details, refer to the Databricks CLI webpage.
Thank you for reading! If you liked what I did, don’t hesitate to follow me on GitHub and connect with me on Linkedin.
Also, feel free to check out my other article(s):
How to Get Twitter Notifications on Currency Exchange Rate: Web Scraping and Automation | [
{
"code": null,
"e": 717,
"s": 172,
"text": "When I work on Python projects dealing with large datasets, I usually use Spyder. The environment of Spyder is very simple; I can browse through working directories, maintain large code bases and review data frames I create. However, if I don’t subset the large data, I constantly face memory issues and struggle with very long computational time. For this reason, I occasionally use Databricks. Databricks is a Microsoft Azure platform where you can easily parse large amounts of data into “notebooks” and perform Apache Spark-based analytics."
},
{
"code": null,
"e": 1138,
"s": 717,
"text": "If you want to work with data frames and run models using pyspark, you can easily refer to Databricks’ website for more information. However, while working on Databricks, I noticed that saving files in CSV, which is supposed to be quite easy, is not very straightforward. In the following section, I would like to share how you can save data frames from Databricks into CSV format on your local computer with no hassles."
},
{
"code": null,
"e": 1238,
"s": 1138,
"text": "From Azure Databricks home, you can go to “Upload Data” (under Common Tasks)→ “DBFS” → “FileStore”."
},
{
"code": null,
"e": 1398,
"s": 1238,
"text": "DBFS FileStore is where you create folders and save your data frames into CSV format. By default, FileStore has three folders: import-stage, plots, and tables."
},
{
"code": null,
"e": 1521,
"s": 1398,
"text": "Sample.coalesce(1).write.format(“com.databricks.spark.csv”).option(“header”, “true”).save(“dbfs:/FileStore/df/Sample.csv”)"
},
{
"code": null,
"e": 1815,
"s": 1521,
"text": "Using the above code on the notebook, I created a folder “df” and saved a data frame “Sample” into CSV. It is important to use coalesce(1) since it saves the data frame as a whole. At the end of this article, I will also demonstrate what happens when you don’t include coalesce(1) in the code."
},
{
"code": null,
"e": 2047,
"s": 1815,
"text": "Once you convert your data frame into CSV, go to your FileStore. You will see the folder and files you create. The “part-00000” is the CSV file I had to download on my local computer. I copied the path after /FileStore/ for step 3."
},
{
"code": null,
"e": 2193,
"s": 2047,
"text": "In order to download the CSV file located in DBFS FileStore on your local computer, you will have to change the highlighted URL to the following:"
},
{
"code": null,
"e": 2357,
"s": 2193,
"text": "https://westeurope.azuredatabricks.net/files/df/Sample.csv/part-00000-tid-8365188928461432060–63d7293d-3b02–43ff-b461-edd732f9e06e-4704-c000.csv?o=3847738880082577"
},
{
"code": null,
"e": 2568,
"s": 2357,
"text": "As you noticed, the CSV path in bold (df/Sample.csv/part-00000-tid-8365188928461432060–63d7293d-3b02–43ff-b461-edd732f9e06e-4704-c000.csv) is from step 2. The number (3847738880082577) is from the original URL."
},
{
"code": null,
"e": 2698,
"s": 2568,
"text": "When you change the URL as described above and press enter, the CSV file will be automatically downloaded on your local computer."
},
{
"code": null,
"e": 2734,
"s": 2698,
"text": "dbutils.fs.rm(“/FileStore/df”,True)"
},
{
"code": null,
"e": 2868,
"s": 2734,
"text": "If you want to delete files in the FileStore, you can simply use the above code. Once it is deleted, you will get the comment “True”."
},
{
"code": null,
"e": 2958,
"s": 2868,
"text": "As promised earlier, here are the details when you don’t include coalesce(1) in the code."
},
{
"code": null,
"e": 3428,
"s": 2958,
"text": "By default, Databricks saves data into many partitions. Coalesce(1) combines all the files into one and solves this partitioning problem. However, it is not a good idea to use coalesce (1) or repartition (1) when you deal with very big datasets (>1TB, low velocity) because it transfers all the data to a single worker, which causes out of memory issues and slow processing. In this case, parsing by column or distributing to more than one single worker is recommended."
},
{
"code": null,
"e": 3534,
"s": 3428,
"text": "On a side note, there are also two other methods to save data frames as CSV files on your local computer:"
},
{
"code": null,
"e": 3564,
"s": 3534,
"text": "Using “Download full results”"
},
{
"code": null,
"e": 3594,
"s": 3564,
"text": "Using “Download full results”"
},
{
"code": null,
"e": 3817,
"s": 3594,
"text": "This method is the easiest. However, Databricks downloads only up to 1 million rows. Therefore, if you have a data frame that is more than 1 million rows, I recommend you to use the above method or Databricks CLI as below."
},
{
"code": null,
"e": 3841,
"s": 3817,
"text": "2. Using Databricks CLI"
},
{
"code": null,
"e": 4177,
"s": 3841,
"text": "Databricks CLI (Databricks command-line interface), which is built on top of the Databricks REST API, interacts with Databricks workspaces and filesystem APIs. Databricks CLI needs some set-ups, but you can also use this method to download your data frames on your local computer. For more details, refer to the Databricks CLI webpage."
},
{
"code": null,
"e": 4296,
"s": 4177,
"text": "Thank you for reading! If you liked what I did, don’t hesitate to follow me on GitHub and connect with me on Linkedin."
},
{
"code": null,
"e": 4346,
"s": 4296,
"text": "Also, feel free to check out my other article(s):"
}
]
|
Android Animation using Android Studio - GeeksforGeeks | 31 Mar, 2021
In today’s world which is filled with full of imagination and visualizations, there are some areas that are covered with the word animation. When this word will come to anyone’s mind they always create a picture of cartoons and some Disney world shows. As we already know that among kids, animation movies are very popular like Disney world, Doraemon, etc. All the cartoons and animation pictures are the types of animation made from thousands of single pictures add together and play according to steps. The same animation, we have tried to add in our android application using Kotlin.
We will be building a simple android application in android studio using Kotlin, in which we will have a start Button and an image, by the time we click on the start button it will start its corresponding animation. In this particular, we have used a man with walking animation. Clicking on the same button again will stop the animation. 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: Upload Images for Animation
Copy the images from your system, go to app > res > drawable and press Ctrl + V, they will get included in the drawable folder.
You can get all the images from this link.
Step 3: Create an XML File for Animation List
For creating an animation list for the application, navigate to app > res > drawable right-click on drawable, select: new > Drawable resource file and name the file as animation_item.xml and refer to the code below.
XML
<?xml version="1.0" encoding="utf-8"?><animation-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- creation of animation list--> <item android:drawable="@drawable/man1" android:duration="100" /> <item android:drawable="@drawable/man2" android:duration="100" /> <item android:drawable="@drawable/man3" android:duration="100" /> <item android:drawable="@drawable/man4" android:duration="100" /> <item android:drawable="@drawable/man5" android:duration="100" /> <item android:drawable="@drawable/man6" android:duration="100" /> <item android:drawable="@drawable/man7" android:duration="100" /> <item android:drawable="@drawable/man8" android:duration="100" /> </animation-list>
Step 4: Working With the activity_main.xml File
Now it’s time to design the layout for the application. So, navigate to app > res > layout > activity_main.xml and refer to the below-written code in the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> <!-- Inserting the image view in Linear Layout --> <ImageView android:id="@+id/img" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:src="@drawable/animation_item" /> <!-- Inserting the button in Linear Layout --> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="@string/start" android:textColor="@color/white" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout> </LinearLayout>
Step 5: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.graphics.Colorimport android.graphics.drawable.AnimationDrawableimport android.os.Bundleimport android.widget.Buttonimport android.widget.ImageViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var isAnimation: AnimationDrawable private lateinit var btn: Button private lateinit var img: ImageView var isStart = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // set find Id for image (img) and button (btn) img = findViewById(R.id.img) btn = findViewById(R.id.btn) img.setImageResource(R.drawable.animation_item) // set Animation isAnimation = img.drawable as AnimationDrawable btn.setBackgroundColor(Color.GREEN) // set animation Start btn.setOnClickListener { if (!isStart) { isAnimation.start() btn.text = "stop" isStart = true btn.setBackgroundColor(Color.RED) } else { isAnimation.stop() btn.text = "Start" isStart = false btn.setBackgroundColor(Color.GREEN) } } }}
That’s all, now the application is ready to install on the device. Here is what the output of the application looks like.
Output:
GitHub Link:
The above-described project is also available on GitHub, to access it click on the link below: Animation in android application
Android-Animation
Android-Studio
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Kotlin Array
Android UI Layouts
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters | [
{
"code": null,
"e": 26407,
"s": 26379,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 26994,
"s": 26407,
"text": "In today’s world which is filled with full of imagination and visualizations, there are some areas that are covered with the word animation. When this word will come to anyone’s mind they always create a picture of cartoons and some Disney world shows. As we already know that among kids, animation movies are very popular like Disney world, Doraemon, etc. All the cartoons and animation pictures are the types of animation made from thousands of single pictures add together and play according to steps. The same animation, we have tried to add in our android application using Kotlin."
},
{
"code": null,
"e": 27422,
"s": 26994,
"text": "We will be building a simple android application in android studio using Kotlin, in which we will have a start Button and an image, by the time we click on the start button it will start its corresponding animation. In this particular, we have used a man with walking animation. Clicking on the same button again will stop the animation. A sample GIF is given below to get an idea about what we are going to do in this article."
},
{
"code": null,
"e": 27451,
"s": 27422,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27615,
"s": 27451,
"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": 27651,
"s": 27615,
"text": "Step 2: Upload Images for Animation"
},
{
"code": null,
"e": 27780,
"s": 27651,
"text": "Copy the images from your system, go to app > res > drawable and press Ctrl + V, they will get included in the drawable folder. "
},
{
"code": null,
"e": 27823,
"s": 27780,
"text": "You can get all the images from this link."
},
{
"code": null,
"e": 27869,
"s": 27823,
"text": "Step 3: Create an XML File for Animation List"
},
{
"code": null,
"e": 28086,
"s": 27869,
"text": "For creating an animation list for the application, navigate to app > res > drawable right-click on drawable, select: new > Drawable resource file and name the file as animation_item.xml and refer to the code below."
},
{
"code": null,
"e": 28090,
"s": 28086,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><animation-list xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!-- creation of animation list--> <item android:drawable=\"@drawable/man1\" android:duration=\"100\" /> <item android:drawable=\"@drawable/man2\" android:duration=\"100\" /> <item android:drawable=\"@drawable/man3\" android:duration=\"100\" /> <item android:drawable=\"@drawable/man4\" android:duration=\"100\" /> <item android:drawable=\"@drawable/man5\" android:duration=\"100\" /> <item android:drawable=\"@drawable/man6\" android:duration=\"100\" /> <item android:drawable=\"@drawable/man7\" android:duration=\"100\" /> <item android:drawable=\"@drawable/man8\" android:duration=\"100\" /> </animation-list>",
"e": 28931,
"s": 28090,
"text": null
},
{
"code": null,
"e": 28979,
"s": 28931,
"text": "Step 4: Working With the activity_main.xml File"
},
{
"code": null,
"e": 29159,
"s": 28979,
"text": "Now it’s time to design the layout for the application. So, navigate to app > res > layout > activity_main.xml and refer to the below-written code in the activity_main.xml file. "
},
{
"code": null,
"e": 29163,
"s": 29159,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:orientation=\"vertical\"> <!-- Inserting the image view in Linear Layout --> <ImageView android:id=\"@+id/img\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" android:layout_weight=\"1\" android:src=\"@drawable/animation_item\" /> <!-- Inserting the button in Linear Layout --> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:text=\"@string/start\" android:textColor=\"@color/white\" android:textSize=\"16sp\" android:textStyle=\"bold\" /> </LinearLayout> </LinearLayout>",
"e": 30363,
"s": 29163,
"text": null
},
{
"code": null,
"e": 30409,
"s": 30363,
"text": "Step 5: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 30595,
"s": 30409,
"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": 30602,
"s": 30595,
"text": "Kotlin"
},
{
"code": "import android.graphics.Colorimport android.graphics.drawable.AnimationDrawableimport android.os.Bundleimport android.widget.Buttonimport android.widget.ImageViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var isAnimation: AnimationDrawable private lateinit var btn: Button private lateinit var img: ImageView var isStart = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // set find Id for image (img) and button (btn) img = findViewById(R.id.img) btn = findViewById(R.id.btn) img.setImageResource(R.drawable.animation_item) // set Animation isAnimation = img.drawable as AnimationDrawable btn.setBackgroundColor(Color.GREEN) // set animation Start btn.setOnClickListener { if (!isStart) { isAnimation.start() btn.text = \"stop\" isStart = true btn.setBackgroundColor(Color.RED) } else { isAnimation.stop() btn.text = \"Start\" isStart = false btn.setBackgroundColor(Color.GREEN) } } }}",
"e": 31929,
"s": 30602,
"text": null
},
{
"code": null,
"e": 32051,
"s": 31929,
"text": "That’s all, now the application is ready to install on the device. Here is what the output of the application looks like."
},
{
"code": null,
"e": 32059,
"s": 32051,
"text": "Output:"
},
{
"code": null,
"e": 32072,
"s": 32059,
"text": "GitHub Link:"
},
{
"code": null,
"e": 32200,
"s": 32072,
"text": "The above-described project is also available on GitHub, to access it click on the link below: Animation in android application"
},
{
"code": null,
"e": 32218,
"s": 32200,
"text": "Android-Animation"
},
{
"code": null,
"e": 32233,
"s": 32218,
"text": "Android-Studio"
},
{
"code": null,
"e": 32241,
"s": 32233,
"text": "Android"
},
{
"code": null,
"e": 32248,
"s": 32241,
"text": "Kotlin"
},
{
"code": null,
"e": 32256,
"s": 32248,
"text": "Android"
},
{
"code": null,
"e": 32354,
"s": 32256,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32392,
"s": 32354,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 32431,
"s": 32392,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32481,
"s": 32431,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 32523,
"s": 32481,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32574,
"s": 32523,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 32587,
"s": 32574,
"text": "Kotlin Array"
},
{
"code": null,
"e": 32606,
"s": 32587,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 32648,
"s": 32606,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 32688,
"s": 32648,
"text": "How to Get Current Location in Android?"
}
]
|
Check if a given array can be divided into pairs with even sum | 13 Sep, 2021
Given an array arr[] consisting of N integers, the task is to check if it is possible to divide the entire array into pairs such that the sum of each pair is even. If it is possible, print “Yes”. Otherwise, print “No”.
Examples:
Input: arr[] = {3, 2, 1, 4, 7, 5, }Output: YesExplanation:The given array can be divided into pairs: {1, 3}, {2, 4}, {5, 7}.
Input: arr[] = {1, 2, 3, 4, 5, 6}Output: NoExplanation:No possible pair distribution exists such that each pair sum is even.
Naive Approach: The simplest approach to solve the problem is to traverse the given array and for each element, find an element having the same parity which has not been picked yet and mark both the elements picked to avoid repetitions. If for any element, no suitable element is found, print “No”. Otherwise, if the entire array could be partitioned into desired pairs, print “Yes”.
Time Complexity: O(N2)Auxiliary Space: O(N)
Efficient Approach: The idea is to observe the fact that if the count of even and odd numbers present in the given array are both even, only then, the given array can be divided into pairs having even sum by odd numbers together and even numbers together. Follow the steps below to solve the problem:
Find the total number of odd and even elements present in the given array and store it in two variables, countEven and countOdd respectively.Check if both countEven and countOdd are even or not. If found to be true, print “Yes”.Otherwise, print “No”.
Find the total number of odd and even elements present in the given array and store it in two variables, countEven and countOdd respectively.
Check if both countEven and countOdd are even or not. If found to be true, print “Yes”.
Otherwise, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if we can split// array into pairs of even sum or notbool canPairs(int arr[], int n){ // If the length is odd then it // is not possible to make pairs if (n % 2 == 1) return false; // Initialize count of odd & even int odd_count = 0, even_count = 0; // Iterate through the array for (int i = 0; i < n; i++) { // Count even element if (arr[i] % 2 == 0) even_count++; else odd_count++; } // If count of even elements // and odd elements are even if (even_count % 2 == 0 && odd_count % 2 == 0) { return true; } return false;} // Driver Codeint main(){ int arr[] = { 3, 2, 1, 4, 7, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call if (canPairs(arr, N)) { cout << "Yes"; } else { cout << "No"; } return 0;}
// Java program for the above approachimport java.io.*; class GFG { // Function to check if we can split // array into pairs of even sum or not static boolean canPairs(int[] arr, int n) { // If the length is odd then it // is not possible to make pairs if (n % 2 == 1) return false; // Initialize count of odd & even int odd_count = 0, even_count = 0; // Iterate through the array for (int i = 0; i < n; i++) { // Count even element if (arr[i] % 2 == 0) even_count++; else odd_count++; } // If count of even elements // and odd elements are even if (even_count % 2 == 0 && odd_count % 2 == 0) { return true; } return false; } // Driver Code public static void main(String[] args) { int[] arr = { 3, 2, 1, 4, 7, 5 }; int N = arr.length; // Function call if (canPairs(arr, N)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by akhilsaini
# Python3 program for the above approach # Function to check if we can split# array into pairs of even sum or not def canPairs(arr, n): # If the length is odd then it # is not possible to make pairs if (n % 2 == 1): return False # Initialize count of odd & even odd_count = 0 even_count = 0 # Iterate through the array for i in range(0, n): # Count even element if (arr[i] % 2 == 0): even_count = even_count + 1 else: odd_count = odd_count + 1 # If count of even elements # and odd elements are even if ((even_count % 2 == 0) and (odd_count % 2 == 0)): return True return False # Driver Codeif __name__ == '__main__': arr = [3, 2, 1, 4, 7, 5] N = len(arr) # Function call if (canPairs(arr, N)): print("Yes") else: print("No") # This code is contributed by akhilsaini
// C# program for the above approachusing System; class GFG { // Function to check if we can split // array into pairs of even sum or not static bool canPairs(int[] arr, int n) { // If the length is odd then it // is not possible to make pairs if (n % 2 == 1) return false; // Initialize count of odd & even int odd_count = 0, even_count = 0; // Iterate through the array for (int i = 0; i < n; i++) { // Count even element if (arr[i] % 2 == 0) even_count++; else odd_count++; } // If count of even elements // and odd elements are even if (even_count % 2 == 0 && odd_count % 2 == 0) { return true; } return false; } // Driver Code public static void Main() { int[] arr = { 3, 2, 1, 4, 7, 5 }; int N = arr.Length; // Function call if (canPairs(arr, N)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by akhilsaini
<script> // Javascript program for the above approach // Function to check if we can split// array into pairs of even sum or notfunction canPairs(arr, n){ // If the length is odd then it // is not possible to make pairs if (n % 2 == 1) return false; // Initialize count of odd & even let odd_count = 0, even_count = 0; // Iterate through the array for(let i = 0; i < n; i++) { // Count even element if (arr[i] % 2 == 0) even_count++; else odd_count++; } // If count of even elements // and odd elements are even if (even_count % 2 == 0 && odd_count % 2 == 0) { return true; } return false;} // Driver Codelet arr = [ 3, 2, 1, 4, 7, 5 ];let N = arr.length; // Function callif (canPairs(arr, N)) document.write("Yes");else document.write("No"); // This code is contributed by target_2 </script>
Yes
Time Complexity: O(N)Auxiliary Space: O(1)
akhilsaini
ArifShaikh
target_2
khushboogoyal499
divisibility
Arrays
Mathematical
School Programming
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
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
Coin Change | DP-7 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 271,
"s": 52,
"text": "Given an array arr[] consisting of N integers, the task is to check if it is possible to divide the entire array into pairs such that the sum of each pair is even. If it is possible, print “Yes”. Otherwise, print “No”."
},
{
"code": null,
"e": 281,
"s": 271,
"text": "Examples:"
},
{
"code": null,
"e": 406,
"s": 281,
"text": "Input: arr[] = {3, 2, 1, 4, 7, 5, }Output: YesExplanation:The given array can be divided into pairs: {1, 3}, {2, 4}, {5, 7}."
},
{
"code": null,
"e": 531,
"s": 406,
"text": "Input: arr[] = {1, 2, 3, 4, 5, 6}Output: NoExplanation:No possible pair distribution exists such that each pair sum is even."
},
{
"code": null,
"e": 916,
"s": 531,
"text": "Naive Approach: The simplest approach to solve the problem is to traverse the given array and for each element, find an element having the same parity which has not been picked yet and mark both the elements picked to avoid repetitions. If for any element, no suitable element is found, print “No”. Otherwise, if the entire array could be partitioned into desired pairs, print “Yes”. "
},
{
"code": null,
"e": 960,
"s": 916,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1261,
"s": 960,
"text": "Efficient Approach: The idea is to observe the fact that if the count of even and odd numbers present in the given array are both even, only then, the given array can be divided into pairs having even sum by odd numbers together and even numbers together. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1512,
"s": 1261,
"text": "Find the total number of odd and even elements present in the given array and store it in two variables, countEven and countOdd respectively.Check if both countEven and countOdd are even or not. If found to be true, print “Yes”.Otherwise, print “No”."
},
{
"code": null,
"e": 1654,
"s": 1512,
"text": "Find the total number of odd and even elements present in the given array and store it in two variables, countEven and countOdd respectively."
},
{
"code": null,
"e": 1742,
"s": 1654,
"text": "Check if both countEven and countOdd are even or not. If found to be true, print “Yes”."
},
{
"code": null,
"e": 1765,
"s": 1742,
"text": "Otherwise, print “No”."
},
{
"code": null,
"e": 1816,
"s": 1765,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1820,
"s": 1816,
"text": "C++"
},
{
"code": null,
"e": 1825,
"s": 1820,
"text": "Java"
},
{
"code": null,
"e": 1833,
"s": 1825,
"text": "Python3"
},
{
"code": null,
"e": 1836,
"s": 1833,
"text": "C#"
},
{
"code": null,
"e": 1847,
"s": 1836,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to check if we can split// array into pairs of even sum or notbool canPairs(int arr[], int n){ // If the length is odd then it // is not possible to make pairs if (n % 2 == 1) return false; // Initialize count of odd & even int odd_count = 0, even_count = 0; // Iterate through the array for (int i = 0; i < n; i++) { // Count even element if (arr[i] % 2 == 0) even_count++; else odd_count++; } // If count of even elements // and odd elements are even if (even_count % 2 == 0 && odd_count % 2 == 0) { return true; } return false;} // Driver Codeint main(){ int arr[] = { 3, 2, 1, 4, 7, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call if (canPairs(arr, N)) { cout << \"Yes\"; } else { cout << \"No\"; } return 0;}",
"e": 2811,
"s": 1847,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG { // Function to check if we can split // array into pairs of even sum or not static boolean canPairs(int[] arr, int n) { // If the length is odd then it // is not possible to make pairs if (n % 2 == 1) return false; // Initialize count of odd & even int odd_count = 0, even_count = 0; // Iterate through the array for (int i = 0; i < n; i++) { // Count even element if (arr[i] % 2 == 0) even_count++; else odd_count++; } // If count of even elements // and odd elements are even if (even_count % 2 == 0 && odd_count % 2 == 0) { return true; } return false; } // Driver Code public static void main(String[] args) { int[] arr = { 3, 2, 1, 4, 7, 5 }; int N = arr.length; // Function call if (canPairs(arr, N)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by akhilsaini",
"e": 3969,
"s": 2811,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check if we can split# array into pairs of even sum or not def canPairs(arr, n): # If the length is odd then it # is not possible to make pairs if (n % 2 == 1): return False # Initialize count of odd & even odd_count = 0 even_count = 0 # Iterate through the array for i in range(0, n): # Count even element if (arr[i] % 2 == 0): even_count = even_count + 1 else: odd_count = odd_count + 1 # If count of even elements # and odd elements are even if ((even_count % 2 == 0) and (odd_count % 2 == 0)): return True return False # Driver Codeif __name__ == '__main__': arr = [3, 2, 1, 4, 7, 5] N = len(arr) # Function call if (canPairs(arr, N)): print(\"Yes\") else: print(\"No\") # This code is contributed by akhilsaini",
"e": 4879,
"s": 3969,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG { // Function to check if we can split // array into pairs of even sum or not static bool canPairs(int[] arr, int n) { // If the length is odd then it // is not possible to make pairs if (n % 2 == 1) return false; // Initialize count of odd & even int odd_count = 0, even_count = 0; // Iterate through the array for (int i = 0; i < n; i++) { // Count even element if (arr[i] % 2 == 0) even_count++; else odd_count++; } // If count of even elements // and odd elements are even if (even_count % 2 == 0 && odd_count % 2 == 0) { return true; } return false; } // Driver Code public static void Main() { int[] arr = { 3, 2, 1, 4, 7, 5 }; int N = arr.Length; // Function call if (canPairs(arr, N)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by akhilsaini",
"e": 6006,
"s": 4879,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to check if we can split// array into pairs of even sum or notfunction canPairs(arr, n){ // If the length is odd then it // is not possible to make pairs if (n % 2 == 1) return false; // Initialize count of odd & even let odd_count = 0, even_count = 0; // Iterate through the array for(let i = 0; i < n; i++) { // Count even element if (arr[i] % 2 == 0) even_count++; else odd_count++; } // If count of even elements // and odd elements are even if (even_count % 2 == 0 && odd_count % 2 == 0) { return true; } return false;} // Driver Codelet arr = [ 3, 2, 1, 4, 7, 5 ];let N = arr.length; // Function callif (canPairs(arr, N)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by target_2 </script>",
"e": 6938,
"s": 6006,
"text": null
},
{
"code": null,
"e": 6942,
"s": 6938,
"text": "Yes"
},
{
"code": null,
"e": 6985,
"s": 6942,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6996,
"s": 6985,
"text": "akhilsaini"
},
{
"code": null,
"e": 7007,
"s": 6996,
"text": "ArifShaikh"
},
{
"code": null,
"e": 7016,
"s": 7007,
"text": "target_2"
},
{
"code": null,
"e": 7033,
"s": 7016,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 7046,
"s": 7033,
"text": "divisibility"
},
{
"code": null,
"e": 7053,
"s": 7046,
"text": "Arrays"
},
{
"code": null,
"e": 7066,
"s": 7053,
"text": "Mathematical"
},
{
"code": null,
"e": 7085,
"s": 7066,
"text": "School Programming"
},
{
"code": null,
"e": 7092,
"s": 7085,
"text": "Arrays"
},
{
"code": null,
"e": 7105,
"s": 7092,
"text": "Mathematical"
},
{
"code": null,
"e": 7203,
"s": 7105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7235,
"s": 7203,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 7282,
"s": 7235,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 7307,
"s": 7282,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 7338,
"s": 7307,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 7396,
"s": 7338,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 7426,
"s": 7396,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 7469,
"s": 7426,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7529,
"s": 7469,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 7544,
"s": 7529,
"text": "C++ Data Types"
}
]
|
Longest Path in a Directed Acyclic Graph | Set 2 | 04 Jul, 2022
Given a Weighted Directed Acyclic Graph (DAG) and a source vertex in it, find the longest distances from source vertex to all other vertices in the given graph.
We have already discussed how we can find Longest Path in Directed Acyclic Graph(DAG) in Set 1. In this post, we will discuss another interesting solution to find longest path of DAG that uses algorithm for finding Shortest Path in a DAG.
The idea is to negate the weights of the path and find the shortest path in the graph. A longest path between two given vertices s and t in a weighted graph G is the same thing as a shortest path in a graph G’ derived from G by changing every weight to its negation. Therefore, if shortest paths can be found in G’, then longest paths can also be found in G. Below is the step by step process of finding longest paths –
We change weight of every edge of given graph to its negation and initialize distances to all vertices as infinite and distance to source as 0, then we find a topological sorting of the graph which represents a linear ordering of the graph. When we consider a vertex u in topological order, it is guaranteed that we have considered every incoming edge to it. i.e. We have already found shortest path to that vertex and we can use that info to update shorter path of all its adjacent vertices. Once we have topological order, we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent vertex using shortest distance of current vertex from source vertex and its edge weight. i.e.
for every adjacent vertex v of every vertex u in topological order
if (dist[v] > dist[u] + weight(u, v))
dist[v] = dist[u] + weight(u, v)
Once we have found all shortest paths from the source vertex, longest paths will be just negation of shortest paths.
Below is the implementation of the above approach:
C++
Python3
C#
// A C++ program to find single source longest distances// in a DAG#include <bits/stdc++.h>using namespace std; // Graph is represented using adjacency list. Every node of// adjacency list contains vertex number of the vertex to// which edge connects. It also contains weight of the edgeclass AdjListNode{ int v; int weight;public: AdjListNode(int _v, int _w) { v = _v; weight = _w; } int getV() { return v; } int getWeight() { return weight; }}; // Graph class represents a directed graph using adjacency// list representationclass Graph{ int V; // No. of vertices // Pointer to an array containing adjacency lists list<AdjListNode>* adj; // This function uses DFS void longestPathUtil(int, vector<bool> &, stack<int> &);public: Graph(int); // Constructor ~Graph(); // Destructor // function to add an edge to graph void addEdge(int, int, int); void longestPath(int);}; Graph::Graph(int V) // Constructor{ this->V = V; adj = new list<AdjListNode>[V];} Graph::~Graph() // Destructor{ delete[] adj;} void Graph::addEdge(int u, int v, int weight){ AdjListNode node(v, weight); adj[u].push_back(node); // Add v to u's list} // A recursive function used by longestPath. See below// link for details.// https://www.geeksforgeeks.org/topological-sorting/void Graph::longestPathUtil(int v, vector<bool> &visited, stack<int> &Stack){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex for (AdjListNode node : adj[v]) { if (!visited[node.getV()]) longestPathUtil(node.getV(), visited, Stack); } // Push current vertex to stack which stores topological // sort Stack.push(v);} // The function do Topological Sort and finds longest// distances from given source vertexvoid Graph::longestPath(int s){ // Initialize distances to all vertices as infinite and // distance to source as 0 int dist[V]; for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[s] = 0; stack<int> Stack; // Mark all the vertices as not visited vector<bool> visited(V, false); for (int i = 0; i < V; i++) if (visited[i] == false) longestPathUtil(i, visited, Stack); // Process vertices in topological order while (!Stack.empty()) { // Get the next vertex from topological order int u = Stack.top(); Stack.pop(); if (dist[u] != INT_MAX) { // Update distances of all adjacent vertices // (edge from u -> v exists) for (AdjListNode v : adj[u]) { // consider negative weight of edges and // find shortest path if (dist[v.getV()] > dist[u] + v.getWeight() * -1) dist[v.getV()] = dist[u] + v.getWeight() * -1; } } } // Print the calculated longest distances for (int i = 0; i < V; i++) { if (dist[i] == INT_MAX) cout << "INT_MIN "; else cout << (dist[i] * -1) << " "; }} // Driver codeint main(){ Graph g(6); g.addEdge(0, 1, 5); g.addEdge(0, 2, 3); g.addEdge(1, 3, 6); g.addEdge(1, 2, 2); g.addEdge(2, 4, 4); g.addEdge(2, 5, 2); g.addEdge(2, 3, 7); g.addEdge(3, 5, 1); g.addEdge(3, 4, -1); g.addEdge(4, 5, -2); int s = 1; cout << "Following are longest distances from " << "source vertex " << s << " \n"; g.longestPath(s); return 0;}
# A Python3 program to find single source# longest distances in a DAGimport sys def addEdge(u, v, w): global adj adj[u].append([v, w]) # A recursive function used by longestPath.# See below link for details.# https:#www.geeksforgeeks.org/topological-sorting/def longestPathUtil(v): global visited, adj,Stack visited[v] = 1 # Recur for all the vertices adjacent # to this vertex for node in adj[v]: if (not visited[node[0]]): longestPathUtil(node[0]) # Push current vertex to stack which # stores topological sort Stack.append(v) # The function do Topological Sort and finds# longest distances from given source vertexdef longestPath(s): # Initialize distances to all vertices # as infinite and global visited, Stack, adj,V dist = [sys.maxsize for i in range(V)] # for (i = 0 i < V i++) # dist[i] = INT_MAX dist[s] = 0 for i in range(V): if (visited[i] == 0): longestPathUtil(i) # print(Stack) while (len(Stack) > 0): # Get the next vertex from topological order u = Stack[-1] del Stack[-1] if (dist[u] != sys.maxsize): # Update distances of all adjacent vertices # (edge from u -> v exists) for v in adj[u]: # Consider negative weight of edges and # find shortest path if (dist[v[0]] > dist[u] + v[1] * -1): dist[v[0]] = dist[u] + v[1] * -1 # Print the calculated longest distances for i in range(V): if (dist[i] == sys.maxsize): print("INT_MIN ", end = " ") else: print(dist[i] * (-1), end = " ") # Driver codeif __name__ == '__main__': V = 6 visited = [0 for i in range(7)] Stack = [] adj = [[] for i in range(7)] addEdge(0, 1, 5) addEdge(0, 2, 3) addEdge(1, 3, 6) addEdge(1, 2, 2) addEdge(2, 4, 4) addEdge(2, 5, 2) addEdge(2, 3, 7) addEdge(3, 5, 1) addEdge(3, 4, -1) addEdge(4, 5, -2) s = 1 print("Following are longest distances from source vertex", s) longestPath(s) # This code is contributed by mohit kumar 29
// C# program to find single source longest distances// in a DAGusing System;using System.Collections.Generic; // Graph is represented using adjacency list. Every node of// adjacency list contains vertex number of the vertex to// which edge connects. It also contains weight of the edgeclass AdjListNode { private int v; private int weight; public AdjListNode(int _v, int _w) { v = _v; weight = _w; } public int getV() { return v; } public int getWeight() { return weight; }} // Graph class represents a directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Pointer to an array containing adjacency lists private List<AdjListNode>[] adj; public Graph(int v) // Constructor { V = v; adj = new List<AdjListNode>[ v ]; for (int i = 0; i < v; i++) adj[i] = new List<AdjListNode>(); } public void AddEdge(int u, int v, int weight) { AdjListNode node = new AdjListNode(v, weight); adj[u].Add(node); // Add v to u's list } // A recursive function used by longestPath. See below // link for details. // https://www.geeksforgeeks.org/topological-sorting/ private void LongestPathUtil(int v, bool[] visited, Stack<int> stack) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this // vertex foreach(AdjListNode node in adj[v]) { if (!visited[node.getV()]) LongestPathUtil(node.getV(), visited, stack); } // Push current vertex to stack which stores // topological sort stack.Push(v); } // The function do Topological Sort and finds longest // distances from given source vertex public void LongestPath(int s) { // Initialize distances to all vertices as infinite // and distance to source as 0 int[] dist = new int[V]; for (int i = 0; i < V; i++) dist[i] = Int32.MaxValue; dist[s] = 0; Stack<int> stack = new Stack<int>(); // Mark all the vertices as not visited bool[] visited = new bool[V]; for (int i = 0; i < V; i++) { if (visited[i] == false) LongestPathUtil(i, visited, stack); } // Process vertices in topological order while (stack.Count > 0) { // Get the next vertex from topological order int u = stack.Pop(); if (dist[u] != Int32.MaxValue) { // Update distances of all adjacent vertices // (edge from u -> v exists) foreach(AdjListNode v in adj[u]) { // consider negative weight of edges and // find shortest path if (dist[v.getV()] > dist[u] + v.getWeight() * -1) dist[v.getV()] = dist[u] + v.getWeight() * -1; } } } // Print the calculated longest distances for (int i = 0; i < V; i++) { if (dist[i] == Int32.MaxValue) Console.Write("INT_MIN "); else Console.Write("{0} ", dist[i] * -1); } Console.WriteLine(); }} public class GFG { // Driver code static void Main(string[] args) { Graph g = new Graph(6); g.AddEdge(0, 1, 5); g.AddEdge(0, 2, 3); g.AddEdge(1, 3, 6); g.AddEdge(1, 2, 2); g.AddEdge(2, 4, 4); g.AddEdge(2, 5, 2); g.AddEdge(2, 3, 7); g.AddEdge(3, 5, 1); g.AddEdge(3, 4, -1); g.AddEdge(4, 5, -2); int s = 1; Console.WriteLine( "Following are longest distances from source vertex {0} ", s); g.LongestPath(s); }} // This code is contributed by cavi4762.
Following are longest distances from source vertex 1
INT_MIN 0 2 9 8 10
Time Complexity: Time complexity of topological sorting is O(V + E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. As total adjacent vertices in a graph is O(E), the inner loop runs O(V + E) times. Therefore, overall time complexity of this algorithm is O(V + E).
This article is contributed by Aditya Goel. 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.
mohit kumar 29
cavi4762
hardikkoriintern
Shortest Path
Topological Sorting
Graph
Graph
Shortest Path
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "Given a Weighted Directed Acyclic Graph (DAG) and a source vertex in it, find the longest distances from source vertex to all other vertices in the given graph."
},
{
"code": null,
"e": 452,
"s": 213,
"text": "We have already discussed how we can find Longest Path in Directed Acyclic Graph(DAG) in Set 1. In this post, we will discuss another interesting solution to find longest path of DAG that uses algorithm for finding Shortest Path in a DAG."
},
{
"code": null,
"e": 872,
"s": 452,
"text": "The idea is to negate the weights of the path and find the shortest path in the graph. A longest path between two given vertices s and t in a weighted graph G is the same thing as a shortest path in a graph G’ derived from G by changing every weight to its negation. Therefore, if shortest paths can be found in G’, then longest paths can also be found in G. Below is the step by step process of finding longest paths –"
},
{
"code": null,
"e": 1619,
"s": 872,
"text": "We change weight of every edge of given graph to its negation and initialize distances to all vertices as infinite and distance to source as 0, then we find a topological sorting of the graph which represents a linear ordering of the graph. When we consider a vertex u in topological order, it is guaranteed that we have considered every incoming edge to it. i.e. We have already found shortest path to that vertex and we can use that info to update shorter path of all its adjacent vertices. Once we have topological order, we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent vertex using shortest distance of current vertex from source vertex and its edge weight. i.e. "
},
{
"code": null,
"e": 1765,
"s": 1619,
"text": "for every adjacent vertex v of every vertex u in topological order\n if (dist[v] > dist[u] + weight(u, v))\n dist[v] = dist[u] + weight(u, v)"
},
{
"code": null,
"e": 1882,
"s": 1765,
"text": "Once we have found all shortest paths from the source vertex, longest paths will be just negation of shortest paths."
},
{
"code": null,
"e": 1933,
"s": 1882,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1937,
"s": 1933,
"text": "C++"
},
{
"code": null,
"e": 1945,
"s": 1937,
"text": "Python3"
},
{
"code": null,
"e": 1948,
"s": 1945,
"text": "C#"
},
{
"code": "// A C++ program to find single source longest distances// in a DAG#include <bits/stdc++.h>using namespace std; // Graph is represented using adjacency list. Every node of// adjacency list contains vertex number of the vertex to// which edge connects. It also contains weight of the edgeclass AdjListNode{ int v; int weight;public: AdjListNode(int _v, int _w) { v = _v; weight = _w; } int getV() { return v; } int getWeight() { return weight; }}; // Graph class represents a directed graph using adjacency// list representationclass Graph{ int V; // No. of vertices // Pointer to an array containing adjacency lists list<AdjListNode>* adj; // This function uses DFS void longestPathUtil(int, vector<bool> &, stack<int> &);public: Graph(int); // Constructor ~Graph(); // Destructor // function to add an edge to graph void addEdge(int, int, int); void longestPath(int);}; Graph::Graph(int V) // Constructor{ this->V = V; adj = new list<AdjListNode>[V];} Graph::~Graph() // Destructor{ delete[] adj;} void Graph::addEdge(int u, int v, int weight){ AdjListNode node(v, weight); adj[u].push_back(node); // Add v to u's list} // A recursive function used by longestPath. See below// link for details.// https://www.geeksforgeeks.org/topological-sorting/void Graph::longestPathUtil(int v, vector<bool> &visited, stack<int> &Stack){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex for (AdjListNode node : adj[v]) { if (!visited[node.getV()]) longestPathUtil(node.getV(), visited, Stack); } // Push current vertex to stack which stores topological // sort Stack.push(v);} // The function do Topological Sort and finds longest// distances from given source vertexvoid Graph::longestPath(int s){ // Initialize distances to all vertices as infinite and // distance to source as 0 int dist[V]; for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[s] = 0; stack<int> Stack; // Mark all the vertices as not visited vector<bool> visited(V, false); for (int i = 0; i < V; i++) if (visited[i] == false) longestPathUtil(i, visited, Stack); // Process vertices in topological order while (!Stack.empty()) { // Get the next vertex from topological order int u = Stack.top(); Stack.pop(); if (dist[u] != INT_MAX) { // Update distances of all adjacent vertices // (edge from u -> v exists) for (AdjListNode v : adj[u]) { // consider negative weight of edges and // find shortest path if (dist[v.getV()] > dist[u] + v.getWeight() * -1) dist[v.getV()] = dist[u] + v.getWeight() * -1; } } } // Print the calculated longest distances for (int i = 0; i < V; i++) { if (dist[i] == INT_MAX) cout << \"INT_MIN \"; else cout << (dist[i] * -1) << \" \"; }} // Driver codeint main(){ Graph g(6); g.addEdge(0, 1, 5); g.addEdge(0, 2, 3); g.addEdge(1, 3, 6); g.addEdge(1, 2, 2); g.addEdge(2, 4, 4); g.addEdge(2, 5, 2); g.addEdge(2, 3, 7); g.addEdge(3, 5, 1); g.addEdge(3, 4, -1); g.addEdge(4, 5, -2); int s = 1; cout << \"Following are longest distances from \" << \"source vertex \" << s << \" \\n\"; g.longestPath(s); return 0;}",
"e": 5514,
"s": 1948,
"text": null
},
{
"code": "# A Python3 program to find single source# longest distances in a DAGimport sys def addEdge(u, v, w): global adj adj[u].append([v, w]) # A recursive function used by longestPath.# See below link for details.# https:#www.geeksforgeeks.org/topological-sorting/def longestPathUtil(v): global visited, adj,Stack visited[v] = 1 # Recur for all the vertices adjacent # to this vertex for node in adj[v]: if (not visited[node[0]]): longestPathUtil(node[0]) # Push current vertex to stack which # stores topological sort Stack.append(v) # The function do Topological Sort and finds# longest distances from given source vertexdef longestPath(s): # Initialize distances to all vertices # as infinite and global visited, Stack, adj,V dist = [sys.maxsize for i in range(V)] # for (i = 0 i < V i++) # dist[i] = INT_MAX dist[s] = 0 for i in range(V): if (visited[i] == 0): longestPathUtil(i) # print(Stack) while (len(Stack) > 0): # Get the next vertex from topological order u = Stack[-1] del Stack[-1] if (dist[u] != sys.maxsize): # Update distances of all adjacent vertices # (edge from u -> v exists) for v in adj[u]: # Consider negative weight of edges and # find shortest path if (dist[v[0]] > dist[u] + v[1] * -1): dist[v[0]] = dist[u] + v[1] * -1 # Print the calculated longest distances for i in range(V): if (dist[i] == sys.maxsize): print(\"INT_MIN \", end = \" \") else: print(dist[i] * (-1), end = \" \") # Driver codeif __name__ == '__main__': V = 6 visited = [0 for i in range(7)] Stack = [] adj = [[] for i in range(7)] addEdge(0, 1, 5) addEdge(0, 2, 3) addEdge(1, 3, 6) addEdge(1, 2, 2) addEdge(2, 4, 4) addEdge(2, 5, 2) addEdge(2, 3, 7) addEdge(3, 5, 1) addEdge(3, 4, -1) addEdge(4, 5, -2) s = 1 print(\"Following are longest distances from source vertex\", s) longestPath(s) # This code is contributed by mohit kumar 29",
"e": 7722,
"s": 5514,
"text": null
},
{
"code": "// C# program to find single source longest distances// in a DAGusing System;using System.Collections.Generic; // Graph is represented using adjacency list. Every node of// adjacency list contains vertex number of the vertex to// which edge connects. It also contains weight of the edgeclass AdjListNode { private int v; private int weight; public AdjListNode(int _v, int _w) { v = _v; weight = _w; } public int getV() { return v; } public int getWeight() { return weight; }} // Graph class represents a directed graph using adjacency// list representationclass Graph { private int V; // No. of vertices // Pointer to an array containing adjacency lists private List<AdjListNode>[] adj; public Graph(int v) // Constructor { V = v; adj = new List<AdjListNode>[ v ]; for (int i = 0; i < v; i++) adj[i] = new List<AdjListNode>(); } public void AddEdge(int u, int v, int weight) { AdjListNode node = new AdjListNode(v, weight); adj[u].Add(node); // Add v to u's list } // A recursive function used by longestPath. See below // link for details. // https://www.geeksforgeeks.org/topological-sorting/ private void LongestPathUtil(int v, bool[] visited, Stack<int> stack) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this // vertex foreach(AdjListNode node in adj[v]) { if (!visited[node.getV()]) LongestPathUtil(node.getV(), visited, stack); } // Push current vertex to stack which stores // topological sort stack.Push(v); } // The function do Topological Sort and finds longest // distances from given source vertex public void LongestPath(int s) { // Initialize distances to all vertices as infinite // and distance to source as 0 int[] dist = new int[V]; for (int i = 0; i < V; i++) dist[i] = Int32.MaxValue; dist[s] = 0; Stack<int> stack = new Stack<int>(); // Mark all the vertices as not visited bool[] visited = new bool[V]; for (int i = 0; i < V; i++) { if (visited[i] == false) LongestPathUtil(i, visited, stack); } // Process vertices in topological order while (stack.Count > 0) { // Get the next vertex from topological order int u = stack.Pop(); if (dist[u] != Int32.MaxValue) { // Update distances of all adjacent vertices // (edge from u -> v exists) foreach(AdjListNode v in adj[u]) { // consider negative weight of edges and // find shortest path if (dist[v.getV()] > dist[u] + v.getWeight() * -1) dist[v.getV()] = dist[u] + v.getWeight() * -1; } } } // Print the calculated longest distances for (int i = 0; i < V; i++) { if (dist[i] == Int32.MaxValue) Console.Write(\"INT_MIN \"); else Console.Write(\"{0} \", dist[i] * -1); } Console.WriteLine(); }} public class GFG { // Driver code static void Main(string[] args) { Graph g = new Graph(6); g.AddEdge(0, 1, 5); g.AddEdge(0, 2, 3); g.AddEdge(1, 3, 6); g.AddEdge(1, 2, 2); g.AddEdge(2, 4, 4); g.AddEdge(2, 5, 2); g.AddEdge(2, 3, 7); g.AddEdge(3, 5, 1); g.AddEdge(3, 4, -1); g.AddEdge(4, 5, -2); int s = 1; Console.WriteLine( \"Following are longest distances from source vertex {0} \", s); g.LongestPath(s); }} // This code is contributed by cavi4762.",
"e": 11699,
"s": 7722,
"text": null
},
{
"code": null,
"e": 11773,
"s": 11699,
"text": "Following are longest distances from source vertex 1 \nINT_MIN 0 2 9 8 10 "
},
{
"code": null,
"e": 12123,
"s": 11773,
"text": "Time Complexity: Time complexity of topological sorting is O(V + E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. As total adjacent vertices in a graph is O(E), the inner loop runs O(V + E) times. Therefore, overall time complexity of this algorithm is O(V + E)."
},
{
"code": null,
"e": 12418,
"s": 12123,
"text": "This article is contributed by Aditya Goel. 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": 12433,
"s": 12418,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 12442,
"s": 12433,
"text": "cavi4762"
},
{
"code": null,
"e": 12459,
"s": 12442,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 12473,
"s": 12459,
"text": "Shortest Path"
},
{
"code": null,
"e": 12493,
"s": 12473,
"text": "Topological Sorting"
},
{
"code": null,
"e": 12499,
"s": 12493,
"text": "Graph"
},
{
"code": null,
"e": 12505,
"s": 12499,
"text": "Graph"
},
{
"code": null,
"e": 12519,
"s": 12505,
"text": "Shortest Path"
}
]
|
Send message to Telegram user using Python | 16 Sep, 2021
Have you ever wondered how people do automation on Telegram? You may know that Telegram has a big user base and so it is one of the preferred social media to read people. What good thing about Telegram is that it provides a bunch of API’s methods, unlike Whatsapp which restricts such things. So in this post, we will be sharing how to send messages to a Telegram user using Python.
First, create a bot using Telegram BotFather. To create a BotFather follow the below steps –
Open the telegram app and search for @BotFather.
Click on the start button or send “/start”.
Then send “/newbot” message to set up a name and a username.
After setting name and username BotFather will give you an API token which is your bot token.
Then create an app on the telegram. Follow the below steps –
Log into the telegram core: https://my.telegram.org
Go to ‘API development tools’ and fill out the form.
You will get the api_id and api_hash parameters required for user authorization.
You need several Python library imports for the script functioning.
telebot: To install this module type the below command in the terminal.
pip install telebot
telethon: To install this module type the below command in the terminal.
pip install telethon
Below is the implementation.
Python3
# importing all required librariesimport telebotfrom telethon.sync import TelegramClientfrom telethon.tl.types import InputPeerUser, InputPeerChannelfrom telethon import TelegramClient, sync, events # get your api_id, api_hash, token# from telegram as described aboveapi_id = 'API_id'api_hash = 'API_hash'token = 'bot token'message = "Working..." # your phone numberphone = 'YOUR_PHONE_NUMBER_WTH_COUNTRY_CODE' # creating a telegram session and assigning# it to a variable clientclient = TelegramClient('session', api_id, api_hash) # connecting and building the sessionclient.connect() # in case of script ran first time it will# ask either to input token or otp sent to# number or sent or your telegram idif not client.is_user_authorized(): client.send_code_request(phone) # signing in the client client.sign_in(phone, input('Enter the code: ')) try: # receiver user_id and access_hash, use # my user_id and access_hash for reference receiver = InputPeerUser('user_id', 'user_hash') # sending message using telegram client client.send_message(receiver, message, parse_mode='html')except Exception as e: # there may be many error coming in while like peer # error, wrong access_hash, flood_error, etc print(e); # disconnecting the telegram sessionclient.disconnect()
divz11
simmytarika5
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 436,
"s": 52,
"text": "Have you ever wondered how people do automation on Telegram? You may know that Telegram has a big user base and so it is one of the preferred social media to read people. What good thing about Telegram is that it provides a bunch of API’s methods, unlike Whatsapp which restricts such things. So in this post, we will be sharing how to send messages to a Telegram user using Python. "
},
{
"code": null,
"e": 531,
"s": 436,
"text": "First, create a bot using Telegram BotFather. To create a BotFather follow the below steps – "
},
{
"code": null,
"e": 580,
"s": 531,
"text": "Open the telegram app and search for @BotFather."
},
{
"code": null,
"e": 624,
"s": 580,
"text": "Click on the start button or send “/start”."
},
{
"code": null,
"e": 685,
"s": 624,
"text": "Then send “/newbot” message to set up a name and a username."
},
{
"code": null,
"e": 781,
"s": 685,
"text": "After setting name and username BotFather will give you an API token which is your bot token. "
},
{
"code": null,
"e": 844,
"s": 781,
"text": "Then create an app on the telegram. Follow the below steps – "
},
{
"code": null,
"e": 896,
"s": 844,
"text": "Log into the telegram core: https://my.telegram.org"
},
{
"code": null,
"e": 949,
"s": 896,
"text": "Go to ‘API development tools’ and fill out the form."
},
{
"code": null,
"e": 1032,
"s": 949,
"text": "You will get the api_id and api_hash parameters required for user authorization. "
},
{
"code": null,
"e": 1104,
"s": 1034,
"text": "You need several Python library imports for the script functioning. "
},
{
"code": null,
"e": 1176,
"s": 1104,
"text": "telebot: To install this module type the below command in the terminal."
},
{
"code": null,
"e": 1196,
"s": 1176,
"text": "pip install telebot"
},
{
"code": null,
"e": 1271,
"s": 1196,
"text": "telethon: To install this module type the below command in the terminal. "
},
{
"code": null,
"e": 1292,
"s": 1271,
"text": "pip install telethon"
},
{
"code": null,
"e": 1322,
"s": 1292,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 1330,
"s": 1322,
"text": "Python3"
},
{
"code": "# importing all required librariesimport telebotfrom telethon.sync import TelegramClientfrom telethon.tl.types import InputPeerUser, InputPeerChannelfrom telethon import TelegramClient, sync, events # get your api_id, api_hash, token# from telegram as described aboveapi_id = 'API_id'api_hash = 'API_hash'token = 'bot token'message = \"Working...\" # your phone numberphone = 'YOUR_PHONE_NUMBER_WTH_COUNTRY_CODE' # creating a telegram session and assigning# it to a variable clientclient = TelegramClient('session', api_id, api_hash) # connecting and building the sessionclient.connect() # in case of script ran first time it will# ask either to input token or otp sent to# number or sent or your telegram idif not client.is_user_authorized(): client.send_code_request(phone) # signing in the client client.sign_in(phone, input('Enter the code: ')) try: # receiver user_id and access_hash, use # my user_id and access_hash for reference receiver = InputPeerUser('user_id', 'user_hash') # sending message using telegram client client.send_message(receiver, message, parse_mode='html')except Exception as e: # there may be many error coming in while like peer # error, wrong access_hash, flood_error, etc print(e); # disconnecting the telegram sessionclient.disconnect()",
"e": 2650,
"s": 1330,
"text": null
},
{
"code": null,
"e": 2657,
"s": 2650,
"text": "divz11"
},
{
"code": null,
"e": 2670,
"s": 2657,
"text": "simmytarika5"
},
{
"code": null,
"e": 2686,
"s": 2670,
"text": "Python-projects"
},
{
"code": null,
"e": 2701,
"s": 2686,
"text": "python-utility"
},
{
"code": null,
"e": 2708,
"s": 2701,
"text": "Python"
}
]
|
Order of operands for logical operators | 28 May, 2017
The order of operands of logical operators &&, || are important in C/C++.
In mathematics, logical AND, OR, etc... operations are commutative. The result will not change even if we swap RHS and LHS of the operator.
In C/C++ (may be in other languages as well) even though these operators are commutative, their order is critical. For example see the following code,
// Traverse every alternative nodewhile( pTemp && pTemp->Next ){ // Jump over to next node pTemp = pTemp->Next->Next;}
The first part pTemp will be evaluated against NULL and followed by pTemp->Next. If pTemp->Next is placed first, the pointer pTemp will be dereferenced and there will be runtime error when pTemp is NULL.
It is mandatory to follow the order. Infact, it helps in generating efficient code. When the pointer pTemp is NULL, the second part will not be evaluated since the outcome of AND (&&) expression is guaranteed to be 0.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Operators
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 128,
"s": 54,
"text": "The order of operands of logical operators &&, || are important in C/C++."
},
{
"code": null,
"e": 268,
"s": 128,
"text": "In mathematics, logical AND, OR, etc... operations are commutative. The result will not change even if we swap RHS and LHS of the operator."
},
{
"code": null,
"e": 420,
"s": 268,
"text": "In C/C++ (may be in other languages as well) even though these operators are commutative, their order is critical. For example see the following code,"
},
{
"code": "// Traverse every alternative nodewhile( pTemp && pTemp->Next ){ // Jump over to next node pTemp = pTemp->Next->Next;}",
"e": 543,
"s": 420,
"text": null
},
{
"code": null,
"e": 747,
"s": 543,
"text": "The first part pTemp will be evaluated against NULL and followed by pTemp->Next. If pTemp->Next is placed first, the pointer pTemp will be dereferenced and there will be runtime error when pTemp is NULL."
},
{
"code": null,
"e": 965,
"s": 747,
"text": "It is mandatory to follow the order. Infact, it helps in generating efficient code. When the pointer pTemp is NULL, the second part will not be evaluated since the outcome of AND (&&) expression is guaranteed to be 0."
},
{
"code": null,
"e": 1090,
"s": 965,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1102,
"s": 1090,
"text": "C-Operators"
},
{
"code": null,
"e": 1113,
"s": 1102,
"text": "C Language"
},
{
"code": null,
"e": 1117,
"s": 1113,
"text": "C++"
},
{
"code": null,
"e": 1121,
"s": 1117,
"text": "CPP"
},
{
"code": null,
"e": 1219,
"s": 1121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1236,
"s": 1219,
"text": "Substring in C++"
},
{
"code": null,
"e": 1258,
"s": 1236,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 1293,
"s": 1258,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 1339,
"s": 1293,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 1384,
"s": 1339,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 1402,
"s": 1384,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 1445,
"s": 1402,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1491,
"s": 1445,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 1534,
"s": 1491,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Underscore.js _.filter Function | 28 Dec, 2021
The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invokes, etc even without using any built-in objects.
The _.filter() is used to check which elements in the passed array satisfy the condition. It will form a new array of all those elements which satisfy the condition passed from the array. It is mostly used when need to find certain elements from a large array.
Syntax:
_.filter( list, predicate, [context] )
Parameters: This function accept three parameters as mentioned above and described below:
list: This parameter is used to hold the list of items.
predicate: This parameter is used to hold the truth condition.
context: The text content which need to be display. It is optional parameter.
Return value: It returns an array consisting of elements which satisfy the condition.
Passing a list of numbers to _.filter() function: The _.filter() function takes the element from the list one by one and checks the specified operations on the code. Like here the operation is to find the elements of the list is even or not. Only the odd elements will be added to the resultant array.
Example:
<!DOCTYPE html><html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> var oddNo = _.filter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(num){ return num % 2 != 0; }); console.log(oddNo); </script> </body></html>
Output:
Passing a list of words to _.filter() function: The _.filter() function takes the element word from the list one by one and checks the specified operations on the code. Like here the operation is to find the elements of the list which have a length of 9. Only those words will be added to the resultant array whose length is equal to 9.
Example:
<!DOCTYPE html><html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> var words = ['javascript', 'java', 'unix', 'hypertext', 'underscore', 'CSS']; const result = words.filter(word => word.length == 9); console.log(result); </script> </body></html>
Output:
Passing a separate function to the _.filter(): Pass a user-defined function to the _.filter() function. First, declare the function like here the function name is ‘largest()’ which returns the element if it is greater than or equal to 100. This function can do any comparison as declared by the user. Then, in the _.filter pass this function. At the end console.log) the resultant array.
Example:
<!DOCTYPE html><html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> function largest(v) { return v >= 100; } var res = [1, 4, 12, 15, 8, 330, 54].filter(largest); console.log(res); </script> </body> </html>
Output:
Using other functions with the _.filter() function: Use toLowerCase() and indexOf() functions in the _.filter() function. First find the index of each element and then check whether it is greater than -1. Since console.log() is used at the end therefore the output will only be seen for the last element of the passed array.
Example:
<!DOCTYPE html><html> <head> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> </head> <body> <script type="text/javascript"> const lang = ['hypertext', 'markup', 'language', 'cascading', 'style', 'sheet', 'javascript']; const func = (query) => { return lang.filter((el) => el.toLowerCase().indexOf(query.toLowerCase()) > -1 ); } console.log(func('pt')); </script> </body> </html>
Output:
Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them.
<script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script>
shubham_singh
arorakashish0911
sumitgumber28
JavaScript - Underscore.js
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
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": "\n28 Dec, 2021"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invokes, etc even without using any built-in objects."
},
{
"code": null,
"e": 447,
"s": 186,
"text": "The _.filter() is used to check which elements in the passed array satisfy the condition. It will form a new array of all those elements which satisfy the condition passed from the array. It is mostly used when need to find certain elements from a large array."
},
{
"code": null,
"e": 455,
"s": 447,
"text": "Syntax:"
},
{
"code": null,
"e": 494,
"s": 455,
"text": "_.filter( list, predicate, [context] )"
},
{
"code": null,
"e": 584,
"s": 494,
"text": "Parameters: This function accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 640,
"s": 584,
"text": "list: This parameter is used to hold the list of items."
},
{
"code": null,
"e": 703,
"s": 640,
"text": "predicate: This parameter is used to hold the truth condition."
},
{
"code": null,
"e": 781,
"s": 703,
"text": "context: The text content which need to be display. It is optional parameter."
},
{
"code": null,
"e": 867,
"s": 781,
"text": "Return value: It returns an array consisting of elements which satisfy the condition."
},
{
"code": null,
"e": 1169,
"s": 867,
"text": "Passing a list of numbers to _.filter() function: The _.filter() function takes the element from the list one by one and checks the specified operations on the code. Like here the operation is to find the elements of the list is even or not. Only the odd elements will be added to the resultant array."
},
{
"code": null,
"e": 1178,
"s": 1169,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> var oddNo = _.filter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(num){ return num % 2 != 0; }); console.log(oddNo); </script> </body></html> ",
"e": 1652,
"s": 1178,
"text": null
},
{
"code": null,
"e": 1660,
"s": 1652,
"text": "Output:"
},
{
"code": null,
"e": 1997,
"s": 1660,
"text": "Passing a list of words to _.filter() function: The _.filter() function takes the element word from the list one by one and checks the specified operations on the code. Like here the operation is to find the elements of the list which have a length of 9. Only those words will be added to the resultant array whose length is equal to 9."
},
{
"code": null,
"e": 2006,
"s": 1997,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> var words = ['javascript', 'java', 'unix', 'hypertext', 'underscore', 'CSS']; const result = words.filter(word => word.length == 9); console.log(result); </script> </body></html> ",
"e": 2488,
"s": 2006,
"text": null
},
{
"code": null,
"e": 2496,
"s": 2488,
"text": "Output:"
},
{
"code": null,
"e": 2884,
"s": 2496,
"text": "Passing a separate function to the _.filter(): Pass a user-defined function to the _.filter() function. First, declare the function like here the function name is ‘largest()’ which returns the element if it is greater than or equal to 100. This function can do any comparison as declared by the user. Then, in the _.filter pass this function. At the end console.log) the resultant array."
},
{
"code": null,
"e": 2893,
"s": 2884,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> function largest(v) { return v >= 100; } var res = [1, 4, 12, 15, 8, 330, 54].filter(largest); console.log(res); </script> </body> </html> ",
"e": 3363,
"s": 2893,
"text": null
},
{
"code": null,
"e": 3371,
"s": 3363,
"text": "Output:"
},
{
"code": null,
"e": 3696,
"s": 3371,
"text": "Using other functions with the _.filter() function: Use toLowerCase() and indexOf() functions in the _.filter() function. First find the index of each element and then check whether it is greater than -1. Since console.log() is used at the end therefore the output will only be seen for the last element of the passed array."
},
{
"code": null,
"e": 3705,
"s": 3696,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> </head> <body> <script type=\"text/javascript\"> const lang = ['hypertext', 'markup', 'language', 'cascading', 'style', 'sheet', 'javascript']; const func = (query) => { return lang.filter((el) => el.toLowerCase().indexOf(query.toLowerCase()) > -1 ); } console.log(func('pt')); </script> </body> </html> ",
"e": 4377,
"s": 3705,
"text": null
},
{
"code": null,
"e": 4385,
"s": 4377,
"text": "Output:"
},
{
"code": null,
"e": 4590,
"s": 4385,
"text": "Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them."
},
{
"code": "<script type=\"text/javascript\" src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script> ",
"e": 4718,
"s": 4590,
"text": null
},
{
"code": null,
"e": 4732,
"s": 4718,
"text": "shubham_singh"
},
{
"code": null,
"e": 4749,
"s": 4732,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4763,
"s": 4749,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4790,
"s": 4763,
"text": "JavaScript - Underscore.js"
},
{
"code": null,
"e": 4811,
"s": 4790,
"text": "javascript-functions"
},
{
"code": null,
"e": 4822,
"s": 4811,
"text": "JavaScript"
},
{
"code": null,
"e": 4839,
"s": 4822,
"text": "Web Technologies"
},
{
"code": null,
"e": 4937,
"s": 4839,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4998,
"s": 4937,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5070,
"s": 4998,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5110,
"s": 5070,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5163,
"s": 5110,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5204,
"s": 5163,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5237,
"s": 5204,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5299,
"s": 5237,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5360,
"s": 5299,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5410,
"s": 5360,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Difference between readonly and const keyword in C# | 12 May, 2021
In C#, a const keyword is used to declare constant fields and constant local. The value of the constant field is the same throughout the program or in other words, once the constant field is assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a constant is a number, string, null reference, boolean values.Example:
CSharp
// C# program to illustrate the// use of const keywordusing System; class GFG { // Constant fields public const int myvar = 10; public const string str = "GeeksforGeeks"; // Main method static public void Main() { // Display the value of Constant fields Console.WriteLine("The value of myvar: {0}", myvar); Console.WriteLine("The value of str: {0}", str); }}
Output:
The value of myvar: 10
The value of str: GeeksforGeeks
In C#, you can use a readonly keyword to declare a readonly variable. This readonly keyword shows that you can assign the variable only when you declare a variable or in a constructor of the same class in which it is declared.Example:
CSharp
// C# program to illustrate the use// of the readonly keywordusing System; class GFG { // readonly variables public readonly int myvar1; public readonly int myvar2; // Values of the readonly // variables are assigned // Using constructor public GFG(int b, int c) { myvar1 = b; myvar2 = c; Console.WriteLine("Display value of myvar1 {0}, "+ "and myvar2 {1}", myvar1, myvar2); } // Main method static public void Main() { GFG obj1 = new GFG(100, 200); }}
Output:
Display value of myvar1 100, and myvar2 200
arorakashish0911
CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 May, 2021"
},
{
"code": null,
"e": 421,
"s": 52,
"text": "In C#, a const keyword is used to declare constant fields and constant local. The value of the constant field is the same throughout the program or in other words, once the constant field is assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a constant is a number, string, null reference, boolean values.Example: "
},
{
"code": null,
"e": 428,
"s": 421,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the// use of const keywordusing System; class GFG { // Constant fields public const int myvar = 10; public const string str = \"GeeksforGeeks\"; // Main method static public void Main() { // Display the value of Constant fields Console.WriteLine(\"The value of myvar: {0}\", myvar); Console.WriteLine(\"The value of str: {0}\", str); }}",
"e": 832,
"s": 428,
"text": null
},
{
"code": null,
"e": 842,
"s": 832,
"text": "Output: "
},
{
"code": null,
"e": 897,
"s": 842,
"text": "The value of myvar: 10\nThe value of str: GeeksforGeeks"
},
{
"code": null,
"e": 1133,
"s": 897,
"text": "In C#, you can use a readonly keyword to declare a readonly variable. This readonly keyword shows that you can assign the variable only when you declare a variable or in a constructor of the same class in which it is declared.Example: "
},
{
"code": null,
"e": 1140,
"s": 1133,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the use// of the readonly keywordusing System; class GFG { // readonly variables public readonly int myvar1; public readonly int myvar2; // Values of the readonly // variables are assigned // Using constructor public GFG(int b, int c) { myvar1 = b; myvar2 = c; Console.WriteLine(\"Display value of myvar1 {0}, \"+ \"and myvar2 {1}\", myvar1, myvar2); } // Main method static public void Main() { GFG obj1 = new GFG(100, 200); }}",
"e": 1687,
"s": 1140,
"text": null
},
{
"code": null,
"e": 1697,
"s": 1687,
"text": "Output: "
},
{
"code": null,
"e": 1741,
"s": 1697,
"text": "Display value of myvar1 100, and myvar2 200"
},
{
"code": null,
"e": 1766,
"s": 1749,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1781,
"s": 1766,
"text": "CSharp-keyword"
},
{
"code": null,
"e": 1784,
"s": 1781,
"text": "C#"
}
]
|
Python | Sum of number digits in List | 30 Jun, 2021
The problem of finding the summation of digits of numbers is quite common. This can sometimes come in form of a list and we need to perform that. This has application in many domains such as school programming and web development. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + str() This is brute force method to perform this particular task. In this, we run a loop for each element, convert each digit to string, and perform the count of the sum of each digit.
Python3
# Python3 code to demonstrate# Sum of number digits in List# using loop + str() # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using loop + str()res = []for ele in test_list: sum = 0 for digit in str(ele): sum += int(digit) res.append(sum) # printing resultprint ("List Integer Summation : " + str(res))
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]
Method #2 : Using sum() + list comprehension This task can also be performed using shorthand using above functionalities. The sum() is used to compute summation and list comprehension is used to compute iterations.
Python3
# Python3 code to demonstrate# Sum of number digits in List# using sum() + list comprehension # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using sum() + list comprehensionres = list(map(lambda ele: sum(int(sub) for sub in str(ele)), test_list)) # printing resultprint ("List Integer Summation : " + str(res))
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]
Method #3 : Using sum() + reduce()This task can also be performed using shorthand using the above functionalities. The sum() is used to compute summation and reduce function from functools module.
Python3
# Python3 code to demonstrate# Sum of number digits in a List# using sum() + reduce()from functools import reduce # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint("The original list is : " + str(test_list)) # Sum of number digits in List# using sum() + reduce()res = [reduce(lambda x, y: int(x) + int(y), list(str(i))) for i in test_list] # printing resultprint("List Integer Summation : " + str(res))
Output:
The original list is : [12, 67, 98, 34]
List Integer Summation : [3, 13, 17, 7]
anjali pardeshi
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 350,
"s": 54,
"text": "The problem of finding the summation of digits of numbers is quite common. This can sometimes come in form of a list and we need to perform that. This has application in many domains such as school programming and web development. Let’s discuss certain ways in which this problem can be solved. "
},
{
"code": null,
"e": 561,
"s": 350,
"text": "Method #1 : Using loop + str() This is brute force method to perform this particular task. In this, we run a loop for each element, convert each digit to string, and perform the count of the sum of each digit. "
},
{
"code": null,
"e": 569,
"s": 561,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Sum of number digits in List# using loop + str() # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint(\"The original list is : \" + str(test_list)) # Sum of number digits in List# using loop + str()res = []for ele in test_list: sum = 0 for digit in str(ele): sum += int(digit) res.append(sum) # printing resultprint (\"List Integer Summation : \" + str(res))",
"e": 1000,
"s": 569,
"text": null
},
{
"code": null,
"e": 1080,
"s": 1000,
"text": "The original list is : [12, 67, 98, 34]\nList Integer Summation : [3, 13, 17, 7]"
},
{
"code": null,
"e": 1299,
"s": 1082,
"text": " Method #2 : Using sum() + list comprehension This task can also be performed using shorthand using above functionalities. The sum() is used to compute summation and list comprehension is used to compute iterations. "
},
{
"code": null,
"e": 1307,
"s": 1299,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Sum of number digits in List# using sum() + list comprehension # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint(\"The original list is : \" + str(test_list)) # Sum of number digits in List# using sum() + list comprehensionres = list(map(lambda ele: sum(int(sub) for sub in str(ele)), test_list)) # printing resultprint (\"List Integer Summation : \" + str(res))",
"e": 1729,
"s": 1307,
"text": null
},
{
"code": null,
"e": 1809,
"s": 1729,
"text": "The original list is : [12, 67, 98, 34]\nList Integer Summation : [3, 13, 17, 7]"
},
{
"code": null,
"e": 2008,
"s": 1811,
"text": "Method #3 : Using sum() + reduce()This task can also be performed using shorthand using the above functionalities. The sum() is used to compute summation and reduce function from functools module."
},
{
"code": null,
"e": 2016,
"s": 2008,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# Sum of number digits in a List# using sum() + reduce()from functools import reduce # Initializing listtest_list = [12, 67, 98, 34] # printing original listprint(\"The original list is : \" + str(test_list)) # Sum of number digits in List# using sum() + reduce()res = [reduce(lambda x, y: int(x) + int(y), list(str(i))) for i in test_list] # printing resultprint(\"List Integer Summation : \" + str(res))",
"e": 2447,
"s": 2016,
"text": null
},
{
"code": null,
"e": 2456,
"s": 2447,
"text": " Output:"
},
{
"code": null,
"e": 2536,
"s": 2456,
"text": "The original list is : [12, 67, 98, 34]\nList Integer Summation : [3, 13, 17, 7]"
},
{
"code": null,
"e": 2552,
"s": 2536,
"text": "anjali pardeshi"
},
{
"code": null,
"e": 2573,
"s": 2552,
"text": "Python list-programs"
},
{
"code": null,
"e": 2580,
"s": 2573,
"text": "Python"
},
{
"code": null,
"e": 2596,
"s": 2580,
"text": "Python Programs"
},
{
"code": null,
"e": 2694,
"s": 2596,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2726,
"s": 2694,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2753,
"s": 2726,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2784,
"s": 2753,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2807,
"s": 2784,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2828,
"s": 2807,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2850,
"s": 2828,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2889,
"s": 2850,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2927,
"s": 2889,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2976,
"s": 2927,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
How to extract certain columns from a list of dataframe in R? | 13 Dec, 2021
A nested list may contain other lists, or various objects, arrays, vectors or dataframes as its components. Each component is mapped to a unique index position in the R programming language. Any element can be easily indexed using the [[]] operator, which is used for referencing the particular indexes of the list. Subsequently, list_name[[ index ]], will get the component stored at the index position. In this scenario, this method returns the dataframe at the index position.
The particular column of the extracted dataframe can then be captured using df$col-name or df[[col-index]] , which fetches the mentioned column in the form of a vector. The mentioned column should be well within the bounds, otherwise, an error is thrown. By default, the indexes start with 1.
Syntax:
df [[ col-index]] OR df$col-name
Example 1:
R
# declaring a dataframedata_frame1 = data.frame(col1 = letters[1:4], col2 = c(5:8) , col3 = TRUE)print ("DataFrame1")print (data_frame1) # declaring a dataframedata_frame2 = data.frame(col1 = c(6:9), col2 = LETTERS[1:4])print ("DataFrame2")print (data_frame2) combined_df <- list(data_frame1,data_frame2)print ("Dataframe2 Column1")col21 <- combined_df[[2]][[1]]print (col21)
Output
[1] "DataFrame1"
col1 col2 col3
1 a 5 TRUE
2 b 6 TRUE
3 c 7 TRUE
4 d 8 TRUE
[1] "DataFrame2"
col1 col2
1 6 A
2 7 B
3 8 C
4 9 D
[1] "Dataframe2 Column1"
[1] 6 7 8 9
The list() method may contain more than two components that can be stacked together. The column of the dataframe may be a single element or a vector of atomic elements.
Example 2:
R
# declaring a dataframedata_frame1 = data.frame(col1 = letters[1:4], col2 = c(5:8) , col3 = TRUE)print ("DataFrame1")print (data_frame1) # declaring a dataframedata_frame2 = data.frame(col1 = c(6:9), col2 = LETTERS[1:4])print ("DataFrame2")print (data_frame2) # declaring a dataframedata_frame3 = data.frame(C1 = FALSE, C2 = 1)print ("DataFrame3")print (data_frame3) combined_df <- list(data_frame1,data_frame2,data_frame3)print ("Dataframe3 Column2")col32 <- combined_df[[3]][[2]]print (col32)
Output
[1] "DataFrame1"
col1 col2 col3
1 a 5 TRUE
2 b 6 TRUE
3 c 7 TRUE
4 d 8 TRUE
[1] "DataFrame2"
col1 col2
1 6 A
2 7 B
3 8 C
4 9 D
[1] "DataFrame3"
C1 C2
1 FALSE 1
[1] "Dataframe3 Column2"
[1] 1
The column name can also be referenced using the $ operator, which is used as an indexing operator in R.
Example 3:
R
# declaring a dataframedata_frame1 = data.frame(col1 = letters[1:4], col2 = c(5:8) , col3 = TRUE)print ("DataFrame1")print (data_frame1) # declaring a dataframedata_frame2 = data.frame(col1 = c(6:9), col2 = LETTERS[1:4])print ("DataFrame2")print (data_frame2) # declaring a dataframedata_frame3 = data.frame(C1 = FALSE, C2 = 1)print ("DataFrame3")print (data_frame3) combined_df <- list(data_frame1,data_frame2,data_frame3)print ("Dataframe1 Column1")col11 <- combined_df[[1]]$col1print (col11)
Output
[1] "DataFrame1"
col1 col2 col3
1 a 5 TRUE
2 b 6 TRUE
3 c 7 TRUE
4 d 8 TRUE
[1] "DataFrame2"
col1 col2
1 6 A
2 7 B
3 8 C
4 9 D
[1] "DataFrame3"
C1 C2
1 FALSE 1
[1] "Dataframe1 Column1"
[1] a b c d
Levels: a b c d
nnr223442
Picked
R DataFrame-Programs
R List-Programs
R-DataFrame
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 509,
"s": 28,
"text": "A nested list may contain other lists, or various objects, arrays, vectors or dataframes as its components. Each component is mapped to a unique index position in the R programming language. Any element can be easily indexed using the [[]] operator, which is used for referencing the particular indexes of the list. Subsequently, list_name[[ index ]], will get the component stored at the index position. In this scenario, this method returns the dataframe at the index position. "
},
{
"code": null,
"e": 803,
"s": 509,
"text": "The particular column of the extracted dataframe can then be captured using df$col-name or df[[col-index]] , which fetches the mentioned column in the form of a vector. The mentioned column should be well within the bounds, otherwise, an error is thrown. By default, the indexes start with 1. "
},
{
"code": null,
"e": 811,
"s": 803,
"text": "Syntax:"
},
{
"code": null,
"e": 844,
"s": 811,
"text": "df [[ col-index]] OR df$col-name"
},
{
"code": null,
"e": 855,
"s": 844,
"text": "Example 1:"
},
{
"code": null,
"e": 857,
"s": 855,
"text": "R"
},
{
"code": "# declaring a dataframedata_frame1 = data.frame(col1 = letters[1:4], col2 = c(5:8) , col3 = TRUE)print (\"DataFrame1\")print (data_frame1) # declaring a dataframedata_frame2 = data.frame(col1 = c(6:9), col2 = LETTERS[1:4])print (\"DataFrame2\")print (data_frame2) combined_df <- list(data_frame1,data_frame2)print (\"Dataframe2 Column1\")col21 <- combined_df[[2]][[1]]print (col21)",
"e": 1281,
"s": 857,
"text": null
},
{
"code": null,
"e": 1288,
"s": 1281,
"text": "Output"
},
{
"code": null,
"e": 1502,
"s": 1288,
"text": "[1] \"DataFrame1\"\n col1 col2 col3\n1 a 5 TRUE\n2 b 6 TRUE\n3 c 7 TRUE\n4 d 8 TRUE\n[1] \"DataFrame2\"\n col1 col2\n1 6 A\n2 7 B\n3 8 C\n4 9 D\n[1] \"Dataframe2 Column1\"\n[1] 6 7 8 9"
},
{
"code": null,
"e": 1672,
"s": 1502,
"text": "The list() method may contain more than two components that can be stacked together. The column of the dataframe may be a single element or a vector of atomic elements. "
},
{
"code": null,
"e": 1683,
"s": 1672,
"text": "Example 2:"
},
{
"code": null,
"e": 1685,
"s": 1683,
"text": "R"
},
{
"code": "# declaring a dataframedata_frame1 = data.frame(col1 = letters[1:4], col2 = c(5:8) , col3 = TRUE)print (\"DataFrame1\")print (data_frame1) # declaring a dataframedata_frame2 = data.frame(col1 = c(6:9), col2 = LETTERS[1:4])print (\"DataFrame2\")print (data_frame2) # declaring a dataframedata_frame3 = data.frame(C1 = FALSE, C2 = 1)print (\"DataFrame3\")print (data_frame3) combined_df <- list(data_frame1,data_frame2,data_frame3)print (\"Dataframe3 Column2\")col32 <- combined_df[[3]][[2]]print (col32)",
"e": 2228,
"s": 1685,
"text": null
},
{
"code": null,
"e": 2235,
"s": 2228,
"text": "Output"
},
{
"code": null,
"e": 2481,
"s": 2235,
"text": "[1] \"DataFrame1\"\n col1 col2 col3\n1 a 5 TRUE\n2 b 6 TRUE\n3 c 7 TRUE\n4 d 8 TRUE\n[1] \"DataFrame2\"\n col1 col2\n1 6 A\n2 7 B\n3 8 C\n4 9 D\n[1] \"DataFrame3\"\n C1 C2\n1 FALSE 1\n[1] \"Dataframe3 Column2\"\n[1] 1"
},
{
"code": null,
"e": 2587,
"s": 2481,
"text": "The column name can also be referenced using the $ operator, which is used as an indexing operator in R. "
},
{
"code": null,
"e": 2598,
"s": 2587,
"text": "Example 3:"
},
{
"code": null,
"e": 2600,
"s": 2598,
"text": "R"
},
{
"code": "# declaring a dataframedata_frame1 = data.frame(col1 = letters[1:4], col2 = c(5:8) , col3 = TRUE)print (\"DataFrame1\")print (data_frame1) # declaring a dataframedata_frame2 = data.frame(col1 = c(6:9), col2 = LETTERS[1:4])print (\"DataFrame2\")print (data_frame2) # declaring a dataframedata_frame3 = data.frame(C1 = FALSE, C2 = 1)print (\"DataFrame3\")print (data_frame3) combined_df <- list(data_frame1,data_frame2,data_frame3)print (\"Dataframe1 Column1\")col11 <- combined_df[[1]]$col1print (col11)",
"e": 3143,
"s": 2600,
"text": null
},
{
"code": null,
"e": 3150,
"s": 3143,
"text": "Output"
},
{
"code": null,
"e": 3418,
"s": 3150,
"text": "[1] \"DataFrame1\"\n col1 col2 col3\n1 a 5 TRUE\n2 b 6 TRUE\n3 c 7 TRUE\n4 d 8 TRUE\n[1] \"DataFrame2\"\n col1 col2\n1 6 A\n2 7 B\n3 8 C\n4 9 D\n[1] \"DataFrame3\"\n C1 C2\n1 FALSE 1\n[1] \"Dataframe1 Column1\"\n[1] a b c d\nLevels: a b c d"
},
{
"code": null,
"e": 3428,
"s": 3418,
"text": "nnr223442"
},
{
"code": null,
"e": 3435,
"s": 3428,
"text": "Picked"
},
{
"code": null,
"e": 3456,
"s": 3435,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 3472,
"s": 3456,
"text": "R List-Programs"
},
{
"code": null,
"e": 3484,
"s": 3472,
"text": "R-DataFrame"
},
{
"code": null,
"e": 3491,
"s": 3484,
"text": "R-List"
},
{
"code": null,
"e": 3502,
"s": 3491,
"text": "R Language"
},
{
"code": null,
"e": 3513,
"s": 3502,
"text": "R Programs"
},
{
"code": null,
"e": 3611,
"s": 3513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3663,
"s": 3611,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3721,
"s": 3663,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3756,
"s": 3721,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3794,
"s": 3756,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 3811,
"s": 3794,
"text": "R - if statement"
},
{
"code": null,
"e": 3869,
"s": 3811,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3918,
"s": 3869,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 3961,
"s": 3918,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 3999,
"s": 3961,
"text": "Merge DataFrames by Column Names in R"
}
]
|
Print all possible permutations of an array with duplicates using Backtracking | 20 Aug, 2021
Given an array nums[] of size N, the task is to print all possible distinct permutations of the array nums[] (including duplicates).
Input: nums[] = { 1, 2, 2 }Output: 1 2 12 1 22 2 1
Input: nums[] = { 1, 1 }Output: 1 1
Approach : Follow the steps below to solve the problem
Traverse the array.Generate permutations of an array.Set an order of selection among duplicate elements.If i > 0 && nums[i] == nums[i – 1]: Add nums[i] in the current permutation only if nums[i – 1] has been added in the permutation, i.e visited[i – 1] is true.Otherwise, continue.Using this approach, print the distinct permutations generated.
Traverse the array.
Generate permutations of an array.
Set an order of selection among duplicate elements.
If i > 0 && nums[i] == nums[i – 1]: Add nums[i] in the current permutation only if nums[i – 1] has been added in the permutation, i.e visited[i – 1] is true.
Otherwise, continue.
Using this approach, print the distinct permutations generated.
Check this Recursion Tree to understand the implementation details of the code.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to fill the vector curr// while maintaining the indices visited// in the array numvoid backtrack(vector<int>& nums, vector<int>& curr, vector<vector<int> >& ans, vector<bool>& visited){ // If current permutation is complete if ((int)curr.size() == (int)nums.size()) { ans.push_back(curr); } // Traverse the input vector for (int i = 0; i < (int)nums.size(); i++) { // If index is already visited if (visited[i]) continue; // If the number is duplicate if (i > 0 and nums[i] == nums[i - 1] and !visited[i - 1]) continue; // Set visited[i] flag as true visited[i] = true; // Push nums[i] to current vector curr.push_back(nums[i]); // Recursive function call backtrack(nums, curr, ans, visited); // Backtrack to the previous // state by unsetting visited[i] visited[i] = false; // Pop nums[i] and place at // the back of the vector curr.pop_back(); }} // Function to pre-process the vector numvector<vector<int> > permuteDuplicates( vector<int>& nums){ // Sort the array sort(nums.begin(), nums.end()); // Stores distinct permutations vector<vector<int> > ans; vector<bool> visited( (int)nums.size(), false); // Store the current permutation vector<int> curr; // Find the distinct permutations of num backtrack(nums, curr, ans, visited); return ans;} // Function call to print all distinct// permutations of the vector numsvoid getDistinctPermutations(vector<int> nums){ // Find the distinct permutations vector<vector<int> > ans = permuteDuplicates(nums); // Traverse every row for (int i = 0; i < (int)ans.size(); i++) { // Traverse every column for (int j = 0; j < (int)ans[i].size(); j++) { cout << ans[i][j] << " "; } cout << '\n'; }} // Driver Codeint main(){ // Input vector<int> nums = { 1, 2, 2 }; // Function call to print // all distinct permutations getDistinctPermutations(nums); return 0;}
// Java Program to implement// the above approachimport java.io.*;import java.util.*;class GFG { static ArrayList<Integer> nums = new ArrayList<Integer>(); static ArrayList<Integer> curr = new ArrayList<Integer>(); static ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); static ArrayList<Boolean> visited = new ArrayList<Boolean>(); // Function to fill the vector curr // while maintaining the indices visited // in the array num static void backtrack() { // If current permutation is complete if (curr.size() == nums.size()) { ans.add(curr); for(int i = 0; i < curr.size(); i++) { System.out.print(curr.get(i) +" "); } System.out.println(); } // Traverse the input vector for (int i = 0; i < (int)nums.size(); i++) { // If index is already visited if (visited.get(i)) continue; // If the number is duplicate if (i > 0 && (nums.get(i) == nums.get(i - 1)) && !visited.get(i - 1)) continue; // Set visited[i] flag as true visited.set(i, true); // Push nums[i] to current vector curr.add(nums.get(i)); // Recursive function call backtrack(); // Backtrack to the previous // state by unsetting visited[i] visited.set(i, false); // Pop nums[i] and place at // the back of the vector curr.remove(curr.size() - 1); } } // Function to pre-process the vector num static ArrayList<ArrayList<Integer>> permuteDuplicates() { // Sort the array Collections.sort(nums); for(int i = 0; i < nums.size(); i++) { visited.add(false); } // Find the distinct permutations of num backtrack(); return ans; } // Function call to print all distinct // permutations of the vector nums static void getDistinctPermutations() { ans = permuteDuplicates(); } // Driver code public static void main (String[] args) { // Input nums.add(1); nums.add(2); nums.add(2); // Function call to print // all distinct permutations getDistinctPermutations(); }} // This code is contributed by avanitrachhadiya2155
# Python3 Program to implement# the above approach # Function to fill the vector curr# while maintaining the indices visited# in the array numdef backtrack(): global ans, curr, visited, nums # If current permutation is complete # print(ans) if (len(curr) == len(nums)): print(*curr) # Traverse the input vector for i in range(len(nums)): # If index is already visited if (visited[i]): continue # If the number is duplicate if (i > 0 and nums[i] == nums[i - 1] and visited[i - 1]==False): continue # Set visited[i] flag as true visited[i] = True # Push nums[i] to current vector curr.append(nums[i]) # Recursive function call backtrack() # Backtrack to the previous # state by unsetting visited[i] visited[i] = False # Pop nums[i] and place at # the back of the vector del curr[-1] # Function to pre-process the vector numdef permuteDuplicates(nums): global ans, visited, curr nums = sorted(nums) # Find the distinct permutations of num backtrack() return ans # Function call to print all distinct# permutations of the vector numsdef getDistinctPermutations(nums): global ans, curr, visited # Find the distinct permutations ans = permuteDuplicates(nums) # Driver Codeif __name__ == '__main__': visited = [False]*(5) ans,curr = [], [] nums = [1, 2, 2] # Function call to print # all distinct permutations getDistinctPermutations(nums) # This code is contributed by mohit kumar 29.
// C# Program to implement// the above approachusing System;using System.Collections.Generic; public class GFG{ static List<int> nums = new List<int>(); static List<int> curr = new List<int>(); static List<List<int>> ans = new List<List<int>>(); static List<bool> visited = new List<bool>(); // Function to fill the vector curr // while maintaining the indices visited // in the array num static void backtrack() { // If current permutation is complete if (curr.Count == nums.Count) { ans.Add(curr); for(int i = 0; i < curr.Count; i++) { Console.Write(curr[i] +" "); } Console.WriteLine(); } // Traverse the input vector for (int i = 0; i < (int)nums.Count; i++) { // If index is already visited if (visited[i]) continue; // If the number is duplicate if (i > 0 && (nums[i] == nums[i-1]) && !visited[i-1]) continue; // Set visited[i] flag as true visited[i] = true; // Push nums[i] to current vector curr.Add(nums[i]); // Recursive function call backtrack(); // Backtrack to the previous // state by unsetting visited[i] visited[i] = false; // Pop nums[i] and place at // the back of the vector curr.RemoveAt(curr.Count - 1); } } // Function to pre-process the vector num static List<List<int>> permuteDuplicates() { // Sort the array nums.Sort(); for(int i = 0; i < nums.Count; i++) { visited.Add(false); } // Find the distinct permutations of num backtrack(); return ans; } // Function call to print all distinct // permutations of the vector nums static void getDistinctPermutations() { ans = permuteDuplicates(); } // Driver code static public void Main (){ // Input nums.Add(1); nums.Add(2); nums.Add(2); // Function call to print // all distinct permutations getDistinctPermutations(); }} // This code is contributed by rag2127
<script> // JavaScript Program to implement// the above approach let nums = [];let curr = [];let ans = [];let visited = []; // Function to fill the vector curr // while maintaining the indices visited // in the array numfunction backtrack(){ // If current permutation is complete if (curr.length == nums.length) { ans.push(curr); for(let i = 0; i < curr.length; i++) { document.write(curr[i] +" "); } document.write("<br>"); } // Traverse the input vector for (let i = 0; i < nums.length; i++) { // If index is already visited if (visited[i]) continue; // If the number is duplicate if (i > 0 && (nums[i] == nums[i - 1]) && !visited[i - 1]) continue; // Set visited[i] flag as true visited[i] = true; // Push nums[i] to current vector curr.push(nums[i]); // Recursive function call backtrack(); // Backtrack to the previous // state by unsetting visited[i] visited[i] = false; // Pop nums[i] and place at // the back of the vector curr.pop(); }} // Function to pre-process the vector numfunction permuteDuplicates(){ // Sort the array (nums).sort(function(a,b){return a-b}); for(let i = 0; i < nums.length; i++) { visited.push(false); } // Find the distinct permutations of num backtrack(); return ans;} // Function call to print all distinct // permutations of the vector numsfunction getDistinctPermutations(){ ans = permuteDuplicates();} // Driver code// Inputnums.push(1);nums.push(2);nums.push(2); // Function call to print// all distinct permutationsgetDistinctPermutations(); // This code is contributed by unknown2108 </script>
1 2 2
2 1 2
2 2 1
Time Complexity: O(N! * N)Auxiliary Space : O(N! * N)
mohit kumar 29
avanitrachhadiya2155
rag2127
unknown2108
surinderdawra388
sagar0719kumar
permutation
Technical Scripter 2020
Arrays
Backtracking
Combinatorial
Recursion
Technical Scripter
Arrays
Recursion
permutation
Combinatorial
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 185,
"s": 52,
"text": "Given an array nums[] of size N, the task is to print all possible distinct permutations of the array nums[] (including duplicates)."
},
{
"code": null,
"e": 236,
"s": 185,
"text": "Input: nums[] = { 1, 2, 2 }Output: 1 2 12 1 22 2 1"
},
{
"code": null,
"e": 272,
"s": 236,
"text": "Input: nums[] = { 1, 1 }Output: 1 1"
},
{
"code": null,
"e": 327,
"s": 272,
"text": "Approach : Follow the steps below to solve the problem"
},
{
"code": null,
"e": 672,
"s": 327,
"text": "Traverse the array.Generate permutations of an array.Set an order of selection among duplicate elements.If i > 0 && nums[i] == nums[i – 1]: Add nums[i] in the current permutation only if nums[i – 1] has been added in the permutation, i.e visited[i – 1] is true.Otherwise, continue.Using this approach, print the distinct permutations generated."
},
{
"code": null,
"e": 692,
"s": 672,
"text": "Traverse the array."
},
{
"code": null,
"e": 727,
"s": 692,
"text": "Generate permutations of an array."
},
{
"code": null,
"e": 779,
"s": 727,
"text": "Set an order of selection among duplicate elements."
},
{
"code": null,
"e": 937,
"s": 779,
"text": "If i > 0 && nums[i] == nums[i – 1]: Add nums[i] in the current permutation only if nums[i – 1] has been added in the permutation, i.e visited[i – 1] is true."
},
{
"code": null,
"e": 958,
"s": 937,
"text": "Otherwise, continue."
},
{
"code": null,
"e": 1022,
"s": 958,
"text": "Using this approach, print the distinct permutations generated."
},
{
"code": null,
"e": 1102,
"s": 1022,
"text": "Check this Recursion Tree to understand the implementation details of the code."
},
{
"code": null,
"e": 1153,
"s": 1102,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1159,
"s": 1153,
"text": "C++14"
},
{
"code": null,
"e": 1164,
"s": 1159,
"text": "Java"
},
{
"code": null,
"e": 1172,
"s": 1164,
"text": "Python3"
},
{
"code": null,
"e": 1175,
"s": 1172,
"text": "C#"
},
{
"code": null,
"e": 1186,
"s": 1175,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to fill the vector curr// while maintaining the indices visited// in the array numvoid backtrack(vector<int>& nums, vector<int>& curr, vector<vector<int> >& ans, vector<bool>& visited){ // If current permutation is complete if ((int)curr.size() == (int)nums.size()) { ans.push_back(curr); } // Traverse the input vector for (int i = 0; i < (int)nums.size(); i++) { // If index is already visited if (visited[i]) continue; // If the number is duplicate if (i > 0 and nums[i] == nums[i - 1] and !visited[i - 1]) continue; // Set visited[i] flag as true visited[i] = true; // Push nums[i] to current vector curr.push_back(nums[i]); // Recursive function call backtrack(nums, curr, ans, visited); // Backtrack to the previous // state by unsetting visited[i] visited[i] = false; // Pop nums[i] and place at // the back of the vector curr.pop_back(); }} // Function to pre-process the vector numvector<vector<int> > permuteDuplicates( vector<int>& nums){ // Sort the array sort(nums.begin(), nums.end()); // Stores distinct permutations vector<vector<int> > ans; vector<bool> visited( (int)nums.size(), false); // Store the current permutation vector<int> curr; // Find the distinct permutations of num backtrack(nums, curr, ans, visited); return ans;} // Function call to print all distinct// permutations of the vector numsvoid getDistinctPermutations(vector<int> nums){ // Find the distinct permutations vector<vector<int> > ans = permuteDuplicates(nums); // Traverse every row for (int i = 0; i < (int)ans.size(); i++) { // Traverse every column for (int j = 0; j < (int)ans[i].size(); j++) { cout << ans[i][j] << \" \"; } cout << '\\n'; }} // Driver Codeint main(){ // Input vector<int> nums = { 1, 2, 2 }; // Function call to print // all distinct permutations getDistinctPermutations(nums); return 0;}",
"e": 3489,
"s": 1186,
"text": null
},
{
"code": "// Java Program to implement// the above approachimport java.io.*;import java.util.*;class GFG { static ArrayList<Integer> nums = new ArrayList<Integer>(); static ArrayList<Integer> curr = new ArrayList<Integer>(); static ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); static ArrayList<Boolean> visited = new ArrayList<Boolean>(); // Function to fill the vector curr // while maintaining the indices visited // in the array num static void backtrack() { // If current permutation is complete if (curr.size() == nums.size()) { ans.add(curr); for(int i = 0; i < curr.size(); i++) { System.out.print(curr.get(i) +\" \"); } System.out.println(); } // Traverse the input vector for (int i = 0; i < (int)nums.size(); i++) { // If index is already visited if (visited.get(i)) continue; // If the number is duplicate if (i > 0 && (nums.get(i) == nums.get(i - 1)) && !visited.get(i - 1)) continue; // Set visited[i] flag as true visited.set(i, true); // Push nums[i] to current vector curr.add(nums.get(i)); // Recursive function call backtrack(); // Backtrack to the previous // state by unsetting visited[i] visited.set(i, false); // Pop nums[i] and place at // the back of the vector curr.remove(curr.size() - 1); } } // Function to pre-process the vector num static ArrayList<ArrayList<Integer>> permuteDuplicates() { // Sort the array Collections.sort(nums); for(int i = 0; i < nums.size(); i++) { visited.add(false); } // Find the distinct permutations of num backtrack(); return ans; } // Function call to print all distinct // permutations of the vector nums static void getDistinctPermutations() { ans = permuteDuplicates(); } // Driver code public static void main (String[] args) { // Input nums.add(1); nums.add(2); nums.add(2); // Function call to print // all distinct permutations getDistinctPermutations(); }} // This code is contributed by avanitrachhadiya2155",
"e": 5638,
"s": 3489,
"text": null
},
{
"code": "# Python3 Program to implement# the above approach # Function to fill the vector curr# while maintaining the indices visited# in the array numdef backtrack(): global ans, curr, visited, nums # If current permutation is complete # print(ans) if (len(curr) == len(nums)): print(*curr) # Traverse the input vector for i in range(len(nums)): # If index is already visited if (visited[i]): continue # If the number is duplicate if (i > 0 and nums[i] == nums[i - 1] and visited[i - 1]==False): continue # Set visited[i] flag as true visited[i] = True # Push nums[i] to current vector curr.append(nums[i]) # Recursive function call backtrack() # Backtrack to the previous # state by unsetting visited[i] visited[i] = False # Pop nums[i] and place at # the back of the vector del curr[-1] # Function to pre-process the vector numdef permuteDuplicates(nums): global ans, visited, curr nums = sorted(nums) # Find the distinct permutations of num backtrack() return ans # Function call to print all distinct# permutations of the vector numsdef getDistinctPermutations(nums): global ans, curr, visited # Find the distinct permutations ans = permuteDuplicates(nums) # Driver Codeif __name__ == '__main__': visited = [False]*(5) ans,curr = [], [] nums = [1, 2, 2] # Function call to print # all distinct permutations getDistinctPermutations(nums) # This code is contributed by mohit kumar 29.",
"e": 7242,
"s": 5638,
"text": null
},
{
"code": "// C# Program to implement// the above approachusing System;using System.Collections.Generic; public class GFG{ static List<int> nums = new List<int>(); static List<int> curr = new List<int>(); static List<List<int>> ans = new List<List<int>>(); static List<bool> visited = new List<bool>(); // Function to fill the vector curr // while maintaining the indices visited // in the array num static void backtrack() { // If current permutation is complete if (curr.Count == nums.Count) { ans.Add(curr); for(int i = 0; i < curr.Count; i++) { Console.Write(curr[i] +\" \"); } Console.WriteLine(); } // Traverse the input vector for (int i = 0; i < (int)nums.Count; i++) { // If index is already visited if (visited[i]) continue; // If the number is duplicate if (i > 0 && (nums[i] == nums[i-1]) && !visited[i-1]) continue; // Set visited[i] flag as true visited[i] = true; // Push nums[i] to current vector curr.Add(nums[i]); // Recursive function call backtrack(); // Backtrack to the previous // state by unsetting visited[i] visited[i] = false; // Pop nums[i] and place at // the back of the vector curr.RemoveAt(curr.Count - 1); } } // Function to pre-process the vector num static List<List<int>> permuteDuplicates() { // Sort the array nums.Sort(); for(int i = 0; i < nums.Count; i++) { visited.Add(false); } // Find the distinct permutations of num backtrack(); return ans; } // Function call to print all distinct // permutations of the vector nums static void getDistinctPermutations() { ans = permuteDuplicates(); } // Driver code static public void Main (){ // Input nums.Add(1); nums.Add(2); nums.Add(2); // Function call to print // all distinct permutations getDistinctPermutations(); }} // This code is contributed by rag2127",
"e": 9233,
"s": 7242,
"text": null
},
{
"code": "<script> // JavaScript Program to implement// the above approach let nums = [];let curr = [];let ans = [];let visited = []; // Function to fill the vector curr // while maintaining the indices visited // in the array numfunction backtrack(){ // If current permutation is complete if (curr.length == nums.length) { ans.push(curr); for(let i = 0; i < curr.length; i++) { document.write(curr[i] +\" \"); } document.write(\"<br>\"); } // Traverse the input vector for (let i = 0; i < nums.length; i++) { // If index is already visited if (visited[i]) continue; // If the number is duplicate if (i > 0 && (nums[i] == nums[i - 1]) && !visited[i - 1]) continue; // Set visited[i] flag as true visited[i] = true; // Push nums[i] to current vector curr.push(nums[i]); // Recursive function call backtrack(); // Backtrack to the previous // state by unsetting visited[i] visited[i] = false; // Pop nums[i] and place at // the back of the vector curr.pop(); }} // Function to pre-process the vector numfunction permuteDuplicates(){ // Sort the array (nums).sort(function(a,b){return a-b}); for(let i = 0; i < nums.length; i++) { visited.push(false); } // Find the distinct permutations of num backtrack(); return ans;} // Function call to print all distinct // permutations of the vector numsfunction getDistinctPermutations(){ ans = permuteDuplicates();} // Driver code// Inputnums.push(1);nums.push(2);nums.push(2); // Function call to print// all distinct permutationsgetDistinctPermutations(); // This code is contributed by unknown2108 </script>",
"e": 10987,
"s": 9233,
"text": null
},
{
"code": null,
"e": 11007,
"s": 10987,
"text": "1 2 2 \n2 1 2 \n2 2 1"
},
{
"code": null,
"e": 11063,
"s": 11009,
"text": "Time Complexity: O(N! * N)Auxiliary Space : O(N! * N)"
},
{
"code": null,
"e": 11080,
"s": 11065,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 11101,
"s": 11080,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 11109,
"s": 11101,
"text": "rag2127"
},
{
"code": null,
"e": 11121,
"s": 11109,
"text": "unknown2108"
},
{
"code": null,
"e": 11138,
"s": 11121,
"text": "surinderdawra388"
},
{
"code": null,
"e": 11153,
"s": 11138,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 11165,
"s": 11153,
"text": "permutation"
},
{
"code": null,
"e": 11189,
"s": 11165,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 11196,
"s": 11189,
"text": "Arrays"
},
{
"code": null,
"e": 11209,
"s": 11196,
"text": "Backtracking"
},
{
"code": null,
"e": 11223,
"s": 11209,
"text": "Combinatorial"
},
{
"code": null,
"e": 11233,
"s": 11223,
"text": "Recursion"
},
{
"code": null,
"e": 11252,
"s": 11233,
"text": "Technical Scripter"
},
{
"code": null,
"e": 11259,
"s": 11252,
"text": "Arrays"
},
{
"code": null,
"e": 11269,
"s": 11259,
"text": "Recursion"
},
{
"code": null,
"e": 11281,
"s": 11269,
"text": "permutation"
},
{
"code": null,
"e": 11295,
"s": 11281,
"text": "Combinatorial"
},
{
"code": null,
"e": 11308,
"s": 11295,
"text": "Backtracking"
}
]
|
JavaScript Error message Property | 19 May, 2022
Below is the example of the Error message property.
Example:
JavaScript
<script> try { alert("A computer science portal"); } catch(err) { document.write(err.message); }</script>
Output:
allert is not defined
In JavaScript error message property is used to set or return the error message.
Syntax:
errorObj.message
Return Value: It returns a string, representing the details of the error. More example codes for the above property are as follows:
Example 1: This example does not contains any error so it does not display error message.
html
<!DOCTYPE html><html> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> JavaScript Error Message Property </h3> <p id="gfg"></p> <script> try { alert("A computer science portal"); } catch(err) { document.getElementById("gfg").innerHTML = err.message; } </script> </body></html>
Output:
Example 2: This example displays an error message when use misspelled ‘alert’ statement.
html
<!DOCTYPE html><html> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> JavaScript Error Message Property </h3> <p id="gfg"></p> <script> try { popup("A computer science portal"); } catch(err) { document.getElementById("gfg").innerHTML = err.message; } </script> </body></html>
Output:
Supported Browsers: The browser supported by JavaScript Error Message Property are listed below:
Google Chrome
Firefox
Internet Explorer
Opera
Safari
p741633
JavaScript-Properties
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js | fs.writeFileSync() Method
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
JavaScript | promise resolve() Method
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
REST API (Introduction)
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 May, 2022"
},
{
"code": null,
"e": 80,
"s": 28,
"text": "Below is the example of the Error message property."
},
{
"code": null,
"e": 90,
"s": 80,
"text": "Example: "
},
{
"code": null,
"e": 101,
"s": 90,
"text": "JavaScript"
},
{
"code": "<script> try { alert(\"A computer science portal\"); } catch(err) { document.write(err.message); }</script>",
"e": 244,
"s": 101,
"text": null
},
{
"code": null,
"e": 252,
"s": 244,
"text": "Output:"
},
{
"code": null,
"e": 274,
"s": 252,
"text": "allert is not defined"
},
{
"code": null,
"e": 356,
"s": 274,
"text": "In JavaScript error message property is used to set or return the error message. "
},
{
"code": null,
"e": 364,
"s": 356,
"text": "Syntax:"
},
{
"code": null,
"e": 381,
"s": 364,
"text": "errorObj.message"
},
{
"code": null,
"e": 514,
"s": 381,
"text": "Return Value: It returns a string, representing the details of the error. More example codes for the above property are as follows: "
},
{
"code": null,
"e": 605,
"s": 514,
"text": "Example 1: This example does not contains any error so it does not display error message. "
},
{
"code": null,
"e": 610,
"s": 605,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> JavaScript Error Message Property </h3> <p id=\"gfg\"></p> <script> try { alert(\"A computer science portal\"); } catch(err) { document.getElementById(\"gfg\").innerHTML = err.message; } </script> </body></html> ",
"e": 1117,
"s": 610,
"text": null
},
{
"code": null,
"e": 1125,
"s": 1117,
"text": "Output:"
},
{
"code": null,
"e": 1218,
"s": 1128,
"text": "Example 2: This example displays an error message when use misspelled ‘alert’ statement. "
},
{
"code": null,
"e": 1223,
"s": 1218,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> JavaScript Error Message Property </h3> <p id=\"gfg\"></p> <script> try { popup(\"A computer science portal\"); } catch(err) { document.getElementById(\"gfg\").innerHTML = err.message; } </script> </body></html> ",
"e": 1739,
"s": 1223,
"text": null
},
{
"code": null,
"e": 1747,
"s": 1739,
"text": "Output:"
},
{
"code": null,
"e": 1847,
"s": 1750,
"text": "Supported Browsers: The browser supported by JavaScript Error Message Property are listed below:"
},
{
"code": null,
"e": 1861,
"s": 1847,
"text": "Google Chrome"
},
{
"code": null,
"e": 1869,
"s": 1861,
"text": "Firefox"
},
{
"code": null,
"e": 1887,
"s": 1869,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1893,
"s": 1887,
"text": "Opera"
},
{
"code": null,
"e": 1900,
"s": 1893,
"text": "Safari"
},
{
"code": null,
"e": 1908,
"s": 1900,
"text": "p741633"
},
{
"code": null,
"e": 1930,
"s": 1908,
"text": "JavaScript-Properties"
},
{
"code": null,
"e": 1937,
"s": 1930,
"text": "Picked"
},
{
"code": null,
"e": 1948,
"s": 1937,
"text": "JavaScript"
},
{
"code": null,
"e": 1965,
"s": 1948,
"text": "Web Technologies"
},
{
"code": null,
"e": 2063,
"s": 1965,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2099,
"s": 2063,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 2160,
"s": 2099,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2232,
"s": 2160,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2272,
"s": 2232,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2310,
"s": 2272,
"text": "JavaScript | promise resolve() Method"
},
{
"code": null,
"e": 2343,
"s": 2310,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2405,
"s": 2343,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2466,
"s": 2405,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2490,
"s": 2466,
"text": "REST API (Introduction)"
}
]
|
Select rows that contain specific text using Pandas | 07 Apr, 2021
While preprocessing data using pandas dataframe there may be a need to find the rows that contain specific text. In this article we will discuss methods to find the rows that contain specific text in the columns or rows of a dataframe in pandas.
Dataset in use:
Using the contains() function of strings to filter the rows. We are filtering the rows based on the ‘Credit-Rating’ column of the dataframe by converting it to string followed by the contains method of string class. contains() method takes an argument and finds the pattern in the objects that calls it.
Example:
Python3
# importing pandas as pdimport pandas as pd # reading csv filedf = pd.read_csv("Assignment.csv") # filtering the rows where Credit-Rating is Fairdf = df[df['Credit-Rating'].str.contains('Fair')]print(df)
Output :
Rows containing Fair as Savings
Using itertuples() to iterate rows with find to get rows that contain the desired text. itertuple method return an iterator producing a named tuple for each row in the DataFrame. It works faster than the iterrows() method of pandas.
Example:
Python3
# importing pandas as pdimport pandas as pd # reading csv filedf = pd.read_csv("Assignment.csv") # filtering the rows where Age_Range contains Youngfor x in df.itertuples(): if x[2].find('Young') != -1: print(x)
Output :
Rows with Age_Range as Young
Using iterrows() to iterate rows with find to get rows that contain the desired text. iterrows() function returns the iterator yielding each index value along with a series containing the data in each row. It is slower as compared to the itertuples because of lot of type checking done by it.
Example:
Python3
# importing pandas as pdimport pandas as pd # reading csv filedf = pd.read_csv("Assignment.csv") # filtering the rows where job is Govtfor index, row in df.iterrows(): if 'Govt' in row['job']: print(index, row['job'], row['Age_Range'], row['Salary'], row['Savings'], row['Credit-Rating'])
Output :
Rows with job as Govt
Using regular expressions to find the rows with the desired text. search() is a method of the module re. re.search(pattern, string): It is similar to re.match() but it doesn’t limit us to find matches at the beginning of the string only. We are iterating over the every row and comparing the job at every index with ‘Govt’ to only select those rows.
Example:
Python3
# using regular expressionsfrom re import search # import pandas as pdimport pandas as pd # reading CSV filedf = pd.read_csv("Assignment.csv") # iterating over rows with job as Govt and printingfor ind in df.index: if search('Govt', df['job'][ind]): print(df['job'][ind], df['Savings'][ind], df['Age_Range'][ind], df['Credit-Rating'][ind])
Output :
Rows where job is Govt
Picked
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 274,
"s": 28,
"text": "While preprocessing data using pandas dataframe there may be a need to find the rows that contain specific text. In this article we will discuss methods to find the rows that contain specific text in the columns or rows of a dataframe in pandas."
},
{
"code": null,
"e": 290,
"s": 274,
"text": "Dataset in use:"
},
{
"code": null,
"e": 594,
"s": 290,
"text": "Using the contains() function of strings to filter the rows. We are filtering the rows based on the ‘Credit-Rating’ column of the dataframe by converting it to string followed by the contains method of string class. contains() method takes an argument and finds the pattern in the objects that calls it."
},
{
"code": null,
"e": 603,
"s": 594,
"text": "Example:"
},
{
"code": null,
"e": 611,
"s": 603,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # reading csv filedf = pd.read_csv(\"Assignment.csv\") # filtering the rows where Credit-Rating is Fairdf = df[df['Credit-Rating'].str.contains('Fair')]print(df)",
"e": 817,
"s": 611,
"text": null
},
{
"code": null,
"e": 827,
"s": 817,
"text": "Output : "
},
{
"code": null,
"e": 859,
"s": 827,
"text": "Rows containing Fair as Savings"
},
{
"code": null,
"e": 1092,
"s": 859,
"text": "Using itertuples() to iterate rows with find to get rows that contain the desired text. itertuple method return an iterator producing a named tuple for each row in the DataFrame. It works faster than the iterrows() method of pandas."
},
{
"code": null,
"e": 1101,
"s": 1092,
"text": "Example:"
},
{
"code": null,
"e": 1109,
"s": 1101,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # reading csv filedf = pd.read_csv(\"Assignment.csv\") # filtering the rows where Age_Range contains Youngfor x in df.itertuples(): if x[2].find('Young') != -1: print(x)",
"e": 1333,
"s": 1109,
"text": null
},
{
"code": null,
"e": 1343,
"s": 1333,
"text": "Output : "
},
{
"code": null,
"e": 1372,
"s": 1343,
"text": "Rows with Age_Range as Young"
},
{
"code": null,
"e": 1665,
"s": 1372,
"text": "Using iterrows() to iterate rows with find to get rows that contain the desired text. iterrows() function returns the iterator yielding each index value along with a series containing the data in each row. It is slower as compared to the itertuples because of lot of type checking done by it."
},
{
"code": null,
"e": 1674,
"s": 1665,
"text": "Example:"
},
{
"code": null,
"e": 1682,
"s": 1674,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # reading csv filedf = pd.read_csv(\"Assignment.csv\") # filtering the rows where job is Govtfor index, row in df.iterrows(): if 'Govt' in row['job']: print(index, row['job'], row['Age_Range'], row['Salary'], row['Savings'], row['Credit-Rating'])",
"e": 1996,
"s": 1682,
"text": null
},
{
"code": null,
"e": 2006,
"s": 1996,
"text": "Output : "
},
{
"code": null,
"e": 2028,
"s": 2006,
"text": "Rows with job as Govt"
},
{
"code": null,
"e": 2378,
"s": 2028,
"text": "Using regular expressions to find the rows with the desired text. search() is a method of the module re. re.search(pattern, string): It is similar to re.match() but it doesn’t limit us to find matches at the beginning of the string only. We are iterating over the every row and comparing the job at every index with ‘Govt’ to only select those rows."
},
{
"code": null,
"e": 2387,
"s": 2378,
"text": "Example:"
},
{
"code": null,
"e": 2395,
"s": 2387,
"text": "Python3"
},
{
"code": "# using regular expressionsfrom re import search # import pandas as pdimport pandas as pd # reading CSV filedf = pd.read_csv(\"Assignment.csv\") # iterating over rows with job as Govt and printingfor ind in df.index: if search('Govt', df['job'][ind]): print(df['job'][ind], df['Savings'][ind], df['Age_Range'][ind], df['Credit-Rating'][ind])",
"e": 2761,
"s": 2395,
"text": null
},
{
"code": null,
"e": 2771,
"s": 2761,
"text": "Output : "
},
{
"code": null,
"e": 2794,
"s": 2771,
"text": "Rows where job is Govt"
},
{
"code": null,
"e": 2801,
"s": 2794,
"text": "Picked"
},
{
"code": null,
"e": 2824,
"s": 2801,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 2838,
"s": 2824,
"text": "Python-pandas"
},
{
"code": null,
"e": 2845,
"s": 2838,
"text": "Python"
},
{
"code": null,
"e": 2943,
"s": 2845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2961,
"s": 2943,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3003,
"s": 2961,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3025,
"s": 3003,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3060,
"s": 3025,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3086,
"s": 3060,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3118,
"s": 3086,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3147,
"s": 3118,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3177,
"s": 3147,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3204,
"s": 3177,
"text": "Python Classes and Objects"
}
]
|
WebAssembly - Working with C | In this chapter, we are going to compile a simple C program to javascript and execute the same in the browser.
For Example − C Program
#include<stdio.h>
int square(int n) {
return n*n;
}
We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as square.c.
We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code.
Compile test.c in your command prompt as shown below −
emcc square.c -s STANDALONE_WASM –o findsquare.wasm
emcc command takes care of compiling the code as well as give you the .wasm code. We have used STANDALONE_WASM option that will give only the .wasm file.
Example − findsquare.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WebAssembly Square function</title>
<style>
div {
font-size : 30px; text-align : center; color:orange;
}
</style>
</head>
<body>
<div id="textcontent"></div>
<script>
let square; fetch("findsquare.wasm").then(bytes => bytes.arrayBuffer())
.then(mod => WebAssembly.compile(mod)) .then(module => {
return new WebAssembly.Instance(module)
})
.then(instance => {
square = instance.exports.square(13);
console.log("The square of 13 = " +square);
document.getElementById("textcontent").innerHTML = "The square of 13 = " +square;
});
</script>
</body>
</html>
The output is as mentioned below − | [
{
"code": null,
"e": 2478,
"s": 2367,
"text": "In this chapter, we are going to compile a simple C program to javascript and execute the same in the browser."
},
{
"code": null,
"e": 2502,
"s": 2478,
"text": "For Example − C Program"
},
{
"code": null,
"e": 2560,
"s": 2502,
"text": "#include<stdio.h> \nint square(int n) { \n return n*n; \n}"
},
{
"code": null,
"e": 2692,
"s": 2560,
"text": "We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as square.c."
},
{
"code": null,
"e": 2818,
"s": 2692,
"text": "We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code."
},
{
"code": null,
"e": 2873,
"s": 2818,
"text": "Compile test.c in your command prompt as shown below −"
},
{
"code": null,
"e": 2926,
"s": 2873,
"text": "emcc square.c -s STANDALONE_WASM –o findsquare.wasm\n"
},
{
"code": null,
"e": 3080,
"s": 2926,
"text": "emcc command takes care of compiling the code as well as give you the .wasm code. We have used STANDALONE_WASM option that will give only the .wasm file."
},
{
"code": null,
"e": 3106,
"s": 3080,
"text": "Example − findsquare.html"
},
{
"code": null,
"e": 3890,
"s": 3106,
"text": "<!doctype html> \n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>WebAssembly Square function</title>\n <style>\n div { \n font-size : 30px; text-align : center; color:orange; \n } \n </style>\n </head> \n <body>\n <div id=\"textcontent\"></div>\n <script> \n let square; fetch(\"findsquare.wasm\").then(bytes => bytes.arrayBuffer()) \n .then(mod => WebAssembly.compile(mod)) .then(module => {\n return new WebAssembly.Instance(module) \n }) \n .then(instance => {\n square = instance.exports.square(13); \n console.log(\"The square of 13 = \" +square); \n document.getElementById(\"textcontent\").innerHTML = \"The square of 13 = \" +square; \n }); \n </script>\n </body>\n</html>"
}
]
|
Benefits of Double Division Operator over Single Division Operator in Python | 24 Feb, 2020
The Double Division operator in Python returns the floor value for both integer and floating-point arguments after division.
# A Python program to demonstrate use of # "//" for both integers and floating points print(5//2)print(-5//2)print(5.0//2)
Output:
2
-3
2.0
The single division operator behaves abnormally generally for very large numbers. Consider the following example.
Examples 1:
# single divisionprint(1000000002/2) # Gives wrong outputprint(int(((10 ** 17) + 2)/2)) # Gives Correct outputprint(((10 ** 17) + 2)//2)
Output:
500000001.0
50000000000000000
50000000000000001
Example 2:
x = 10000000000000000000006if int(x / 2) == x // 2: print("Hello")else: print("World")
Output:
World
The Output should have been Hello if the single division operator behaved normally because 2 properly divides x. But the output is World because The results after Single Division Operator and Double Division Operator ARE NOT THE SAME.
This fact can be used for programs such as finding the sum of first n numbers for a large n.
n = 10000000000 s1 = int(n * (n + 1) / 2)s2 = n * (n + 1) // 2 print("Sum using single division operator : ", s1)print("Sum using double division operator : ", s2)
Output:
Sum using single division operator : 50000000005000003584
Sum using double division operator : 50000000005000000000
Thus the result found by using the single division operator is Wrong, while the result found by using the double division operator is Correct. This is a huge benefit of Double Division Operator over Single Division Operator in Python.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Feb, 2020"
},
{
"code": null,
"e": 177,
"s": 52,
"text": "The Double Division operator in Python returns the floor value for both integer and floating-point arguments after division."
},
{
"code": "# A Python program to demonstrate use of # \"//\" for both integers and floating points print(5//2)print(-5//2)print(5.0//2)",
"e": 302,
"s": 177,
"text": null
},
{
"code": null,
"e": 310,
"s": 302,
"text": "Output:"
},
{
"code": null,
"e": 319,
"s": 310,
"text": "2\n-3\n2.0"
},
{
"code": null,
"e": 433,
"s": 319,
"text": "The single division operator behaves abnormally generally for very large numbers. Consider the following example."
},
{
"code": null,
"e": 445,
"s": 433,
"text": "Examples 1:"
},
{
"code": "# single divisionprint(1000000002/2) # Gives wrong outputprint(int(((10 ** 17) + 2)/2)) # Gives Correct outputprint(((10 ** 17) + 2)//2)",
"e": 584,
"s": 445,
"text": null
},
{
"code": null,
"e": 592,
"s": 584,
"text": "Output:"
},
{
"code": null,
"e": 641,
"s": 592,
"text": "500000001.0\n50000000000000000\n50000000000000001\n"
},
{
"code": null,
"e": 652,
"s": 641,
"text": "Example 2:"
},
{
"code": "x = 10000000000000000000006if int(x / 2) == x // 2: print(\"Hello\")else: print(\"World\")",
"e": 745,
"s": 652,
"text": null
},
{
"code": null,
"e": 753,
"s": 745,
"text": "Output:"
},
{
"code": null,
"e": 760,
"s": 753,
"text": "World\n"
},
{
"code": null,
"e": 995,
"s": 760,
"text": "The Output should have been Hello if the single division operator behaved normally because 2 properly divides x. But the output is World because The results after Single Division Operator and Double Division Operator ARE NOT THE SAME."
},
{
"code": null,
"e": 1088,
"s": 995,
"text": "This fact can be used for programs such as finding the sum of first n numbers for a large n."
},
{
"code": "n = 10000000000 s1 = int(n * (n + 1) / 2)s2 = n * (n + 1) // 2 print(\"Sum using single division operator : \", s1)print(\"Sum using double division operator : \", s2)",
"e": 1254,
"s": 1088,
"text": null
},
{
"code": null,
"e": 1262,
"s": 1254,
"text": "Output:"
},
{
"code": null,
"e": 1381,
"s": 1262,
"text": "Sum using single division operator : 50000000005000003584\nSum using double division operator : 50000000005000000000\n"
},
{
"code": null,
"e": 1616,
"s": 1381,
"text": "Thus the result found by using the single division operator is Wrong, while the result found by using the double division operator is Correct. This is a huge benefit of Double Division Operator over Single Division Operator in Python."
},
{
"code": null,
"e": 1630,
"s": 1616,
"text": "python-basics"
},
{
"code": null,
"e": 1637,
"s": 1630,
"text": "Python"
},
{
"code": null,
"e": 1735,
"s": 1637,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1777,
"s": 1735,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1799,
"s": 1777,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1834,
"s": 1799,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1860,
"s": 1834,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1892,
"s": 1860,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1921,
"s": 1892,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1951,
"s": 1921,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1978,
"s": 1951,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2014,
"s": 1978,
"text": "Convert integer to string in Python"
}
]
|
URL Encoding/Decoding using Base64 in Java | 30 Jul, 2019
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss.(Base 64 format reference).
The URL encoding is the same as Basic encoding the only difference is that it encodes or decodes the URL and Filename safe Base64 alphabet and does not add any line separation.
URL encoding
String encodedURL = Base64.getUrlEncoder()
.encodeToString(actualURL_String.getBytes());
Explanation: In above code we called Base64.Encoder using getUrlEncoder() and then get the encoded URLstring by passing the byte value of actual URL in encodeToString() method as parameter.
URL decoding
byte[] decodedURLBytes = Base64.getUrlDecoder().decode(encodedURLString);
String actualURL= new String(decodedURLBytes);
Explanation: In above code we called Base64.Decoder using getUrlDecoder() and then decoded the URL string passed in decode() method as parameter then convert return value to actual URL.
Below programs illustrate the Encoding and Decoding URL in Java:
Program 1: URL encoding using Base64 class.
// Java program to demonstrate// URL encoding using Base64 class import java.util.*;public class GFG { public static void main(String[] args) { // create a sample url String to encode String sampleURL = "https:// www.geeksforgeeks.org/"; // print actual URL String System.out.println("Sample URL:\n" + sampleURL); // Encode into Base64 URL format String encodedURL = Base64.getUrlEncoder() .encodeToString(sampleURL.getBytes()); // print encoded URL System.out.println("encoded URL:\n" + encodedURL); }}
Sample URL:
https://www.geeksforgeeks.org/
encoded URL:
aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv
Program 2: URL decoding using Base64 class.
// Java program to demonstrate// Decoding Basic Base 64 format to String import java.util.*;public class GFG { public static void main(String[] args) { // create a encoded URL to decode String encoded = "aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv"; // print encoded URL System.out.println("encoded URL:\n" + encoded); // decode into String URL from encoded format byte[] actualByte = Base64.getUrlDecoder() .decode(encoded); String actualURLString = new String(actualByte); // print actual String System.out.println("actual String:\n" + actualURLString); }}
encoded URL:
aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv
actual String:
https://www.geeksforgeeks.org/
References:
https://docs.oracle.com/javase/10/docs/api/java/util/Base64.html
https://www.geeksforgeeks.org/decode-encoded-base-64-string-ascii-string/
https://www.geeksforgeeks.org/encode-ascii-string-base-64-format/
Akanksha_Rai
Java 8
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 236,
"s": 28,
"text": "Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss.(Base 64 format reference)."
},
{
"code": null,
"e": 413,
"s": 236,
"text": "The URL encoding is the same as Basic encoding the only difference is that it encodes or decodes the URL and Filename safe Base64 alphabet and does not add any line separation."
},
{
"code": null,
"e": 426,
"s": 413,
"text": "URL encoding"
},
{
"code": null,
"e": 539,
"s": 426,
"text": "String encodedURL = Base64.getUrlEncoder()\n .encodeToString(actualURL_String.getBytes());\n"
},
{
"code": null,
"e": 729,
"s": 539,
"text": "Explanation: In above code we called Base64.Encoder using getUrlEncoder() and then get the encoded URLstring by passing the byte value of actual URL in encodeToString() method as parameter."
},
{
"code": null,
"e": 742,
"s": 729,
"text": "URL decoding"
},
{
"code": null,
"e": 865,
"s": 742,
"text": "byte[] decodedURLBytes = Base64.getUrlDecoder().decode(encodedURLString);\n\nString actualURL= new String(decodedURLBytes);\n"
},
{
"code": null,
"e": 1051,
"s": 865,
"text": "Explanation: In above code we called Base64.Decoder using getUrlDecoder() and then decoded the URL string passed in decode() method as parameter then convert return value to actual URL."
},
{
"code": null,
"e": 1116,
"s": 1051,
"text": "Below programs illustrate the Encoding and Decoding URL in Java:"
},
{
"code": null,
"e": 1160,
"s": 1116,
"text": "Program 1: URL encoding using Base64 class."
},
{
"code": "// Java program to demonstrate// URL encoding using Base64 class import java.util.*;public class GFG { public static void main(String[] args) { // create a sample url String to encode String sampleURL = \"https:// www.geeksforgeeks.org/\"; // print actual URL String System.out.println(\"Sample URL:\\n\" + sampleURL); // Encode into Base64 URL format String encodedURL = Base64.getUrlEncoder() .encodeToString(sampleURL.getBytes()); // print encoded URL System.out.println(\"encoded URL:\\n\" + encodedURL); }}",
"e": 1819,
"s": 1160,
"text": null
},
{
"code": null,
"e": 1917,
"s": 1819,
"text": "Sample URL:\nhttps://www.geeksforgeeks.org/\nencoded URL:\naHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv\n"
},
{
"code": null,
"e": 1961,
"s": 1917,
"text": "Program 2: URL decoding using Base64 class."
},
{
"code": "// Java program to demonstrate// Decoding Basic Base 64 format to String import java.util.*;public class GFG { public static void main(String[] args) { // create a encoded URL to decode String encoded = \"aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv\"; // print encoded URL System.out.println(\"encoded URL:\\n\" + encoded); // decode into String URL from encoded format byte[] actualByte = Base64.getUrlDecoder() .decode(encoded); String actualURLString = new String(actualByte); // print actual String System.out.println(\"actual String:\\n\" + actualURLString); }}",
"e": 2681,
"s": 1961,
"text": null
},
{
"code": null,
"e": 2782,
"s": 2681,
"text": "encoded URL:\naHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv\nactual String:\nhttps://www.geeksforgeeks.org/\n"
},
{
"code": null,
"e": 2794,
"s": 2782,
"text": "References:"
},
{
"code": null,
"e": 2859,
"s": 2794,
"text": "https://docs.oracle.com/javase/10/docs/api/java/util/Base64.html"
},
{
"code": null,
"e": 2933,
"s": 2859,
"text": "https://www.geeksforgeeks.org/decode-encoded-base-64-string-ascii-string/"
},
{
"code": null,
"e": 2999,
"s": 2933,
"text": "https://www.geeksforgeeks.org/encode-ascii-string-base-64-format/"
},
{
"code": null,
"e": 3012,
"s": 2999,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3019,
"s": 3012,
"text": "Java 8"
},
{
"code": null,
"e": 3034,
"s": 3019,
"text": "Java-Functions"
},
{
"code": null,
"e": 3039,
"s": 3034,
"text": "Java"
},
{
"code": null,
"e": 3044,
"s": 3039,
"text": "Java"
}
]
|
Virtual Reality vs Augmented Reality: What’s the difference? | 26 Aug, 2019
Reality is merely an illusion, albeit a very persistent one!
Can you guess who said that? In case you thought Albert Einstein, you are absolutely correct! (And in case you didn’t, do brush up on your general knowledge!) Anyway, Albert Einstein was probably not thinking about the myriad ways that modern reality can be twisted when he said this, but this quote sure fits the situation.
Both Virtual Reality and Augmented Reality can be used to change our reality. They can expand our vision or even transport us to wonderful new places until the only question that remains is “What is real and what is not?”. However, Virtual Reality and Augmented Reality are not exactly the same (If they were, they wouldn’t have different names!!!). So this article primarily tries to understand Virtual Reality and Augmented Reality and through this understanding, know the answer to “What’s the Difference Between Virtual Reality and Augmented Reality?”.
Imagine really traveling through the Pokemon World! This world is lush green and populated with small towns having identical looking nurses and police officers! You run around collecting pokemon and getting occasional electric shocks from Pikachu! This Pokemon World can truly exist for you using Virtual Reality.
In other words, Virtual Reality can use technology to create a simulated environment (a Pokemon environment in this case!). This simulated environment can be totally different than the reality of this world and yet you can perceive it as reality. So Virtual Reality is really just that, a “Virtual Reality” that you can move around in and experience as if you were really there. This is stated quite succinctly by Palmer Luckey, Founder of Oculus Rift as:
Why shouldn’t people be able to teleport wherever they want?
You can view Virtual Reality using a VR headset such as the Oculus Rift S, PlayStation VR, etc. Another option is just using your phone with specially designed VR apps along with Google Cardboard, Daydream View, etc.
Imagine traveling through the real world...Yes, you do it every day, but how about the addition of Pokemon! You can run around catching not-real Pokemon using your mobile phones and enjoy the presence (and shocks!) of Pikachu while still remaining in the real world. This can be achieved using Augmented Reality (Has actually been achieved by Pokemon Go!)
So Augmented Reality basically involves using technology to create an “Augmented” version of reality by superimposing digital information over the real world. This can be done using AR apps in smartphones that use the camera to display the real world and superimpose extra information like text and images onto that world.
The importance of Augmented Reality cannot be understated. According to Tim Cook, CEO of Apple Inc.
I think that a significant portion of the population of developed countries, and eventually all countries, will have AR experiences every day, almost like eating three meals a day. It will become that much a part of you.
With Virtual Reality, you can actually experience the Pokemon World. On the other hand, with Augmented Reality, you can experience parts of the Pokemon World in the real world. That’s the major difference between the two realities!
Virtual Reality allows for a fully immersive experience for the viewer but it is quite restrictive as it requires a headset. In other words, you can experience a different world using Virtual Reality but you are totally cut-off from the real world for that to happen. On the other hand, Augmented Reality allows more freedom as your normal world view is merely enhanced and not replaced. Also, Augmented Reality is easier to market than Virtual Reality as it does not require any special headsets but only a smartphone (Which most of us already have!!!)
This is the reason that Augmented Reality is projected to be more relevant than Virtual Reality in the long-run. According to Tim Cook, CEO of Apple Inc.
I’m excited about augmented reality because unlike virtual reality, which closes the world out, AR allows individuals to be present in the world but hopefully allows an improvement on what’s happening presently.
But overall, both Virtual Reality and Augmented Reality are hot technologies currently and becoming more and more popular (and better!) with time. So be sure to enjoy this persistent illusion that is a new reality for modern times!
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
Roadmap to Learn JavaScript For Beginners
Types of Software Testing
How To Switch From A Service-Based To A Product-Based Company?
What is Data Structure: Types, Classifications and Applications | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 114,
"s": 53,
"text": "Reality is merely an illusion, albeit a very persistent one!"
},
{
"code": null,
"e": 439,
"s": 114,
"text": "Can you guess who said that? In case you thought Albert Einstein, you are absolutely correct! (And in case you didn’t, do brush up on your general knowledge!) Anyway, Albert Einstein was probably not thinking about the myriad ways that modern reality can be twisted when he said this, but this quote sure fits the situation."
},
{
"code": null,
"e": 996,
"s": 439,
"text": "Both Virtual Reality and Augmented Reality can be used to change our reality. They can expand our vision or even transport us to wonderful new places until the only question that remains is “What is real and what is not?”. However, Virtual Reality and Augmented Reality are not exactly the same (If they were, they wouldn’t have different names!!!). So this article primarily tries to understand Virtual Reality and Augmented Reality and through this understanding, know the answer to “What’s the Difference Between Virtual Reality and Augmented Reality?”."
},
{
"code": null,
"e": 1310,
"s": 996,
"text": "Imagine really traveling through the Pokemon World! This world is lush green and populated with small towns having identical looking nurses and police officers! You run around collecting pokemon and getting occasional electric shocks from Pikachu! This Pokemon World can truly exist for you using Virtual Reality."
},
{
"code": null,
"e": 1766,
"s": 1310,
"text": "In other words, Virtual Reality can use technology to create a simulated environment (a Pokemon environment in this case!). This simulated environment can be totally different than the reality of this world and yet you can perceive it as reality. So Virtual Reality is really just that, a “Virtual Reality” that you can move around in and experience as if you were really there. This is stated quite succinctly by Palmer Luckey, Founder of Oculus Rift as:"
},
{
"code": null,
"e": 1827,
"s": 1766,
"text": "Why shouldn’t people be able to teleport wherever they want?"
},
{
"code": null,
"e": 2044,
"s": 1827,
"text": "You can view Virtual Reality using a VR headset such as the Oculus Rift S, PlayStation VR, etc. Another option is just using your phone with specially designed VR apps along with Google Cardboard, Daydream View, etc."
},
{
"code": null,
"e": 2400,
"s": 2044,
"text": "Imagine traveling through the real world...Yes, you do it every day, but how about the addition of Pokemon! You can run around catching not-real Pokemon using your mobile phones and enjoy the presence (and shocks!) of Pikachu while still remaining in the real world. This can be achieved using Augmented Reality (Has actually been achieved by Pokemon Go!)"
},
{
"code": null,
"e": 2723,
"s": 2400,
"text": "So Augmented Reality basically involves using technology to create an “Augmented” version of reality by superimposing digital information over the real world. This can be done using AR apps in smartphones that use the camera to display the real world and superimpose extra information like text and images onto that world."
},
{
"code": null,
"e": 2823,
"s": 2723,
"text": "The importance of Augmented Reality cannot be understated. According to Tim Cook, CEO of Apple Inc."
},
{
"code": null,
"e": 3044,
"s": 2823,
"text": "I think that a significant portion of the population of developed countries, and eventually all countries, will have AR experiences every day, almost like eating three meals a day. It will become that much a part of you."
},
{
"code": null,
"e": 3276,
"s": 3044,
"text": "With Virtual Reality, you can actually experience the Pokemon World. On the other hand, with Augmented Reality, you can experience parts of the Pokemon World in the real world. That’s the major difference between the two realities!"
},
{
"code": null,
"e": 3830,
"s": 3276,
"text": "Virtual Reality allows for a fully immersive experience for the viewer but it is quite restrictive as it requires a headset. In other words, you can experience a different world using Virtual Reality but you are totally cut-off from the real world for that to happen. On the other hand, Augmented Reality allows more freedom as your normal world view is merely enhanced and not replaced. Also, Augmented Reality is easier to market than Virtual Reality as it does not require any special headsets but only a smartphone (Which most of us already have!!!)"
},
{
"code": null,
"e": 3984,
"s": 3830,
"text": "This is the reason that Augmented Reality is projected to be more relevant than Virtual Reality in the long-run. According to Tim Cook, CEO of Apple Inc."
},
{
"code": null,
"e": 4196,
"s": 3984,
"text": "I’m excited about augmented reality because unlike virtual reality, which closes the world out, AR allows individuals to be present in the world but hopefully allows an improvement on what’s happening presently."
},
{
"code": null,
"e": 4428,
"s": 4196,
"text": "But overall, both Virtual Reality and Augmented Reality are hot technologies currently and becoming more and more popular (and better!) with time. So be sure to enjoy this persistent illusion that is a new reality for modern times!"
},
{
"code": null,
"e": 4434,
"s": 4428,
"text": "GBlog"
},
{
"code": null,
"e": 4532,
"s": 4434,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4557,
"s": 4532,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 4612,
"s": 4557,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 4649,
"s": 4612,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 4687,
"s": 4649,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 4753,
"s": 4687,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 4824,
"s": 4753,
"text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa"
},
{
"code": null,
"e": 4866,
"s": 4824,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 4892,
"s": 4866,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 4955,
"s": 4892,
"text": "How To Switch From A Service-Based To A Product-Based Company?"
}
]
|
Finding the Odd Word amongst given words using Word2Vec embeddings | 27 Jan, 2021
Odd One out the problem is one of the most interesting and goto problems when it comes to testing the logical reasoning skills of an individual. It is often used in many competitive exams and placement rounds as it checks the individual’s analytical skills and decision-making ability. In this article, we are going to write a python code that can be used to find the odd words amongst a given set of words.
Suppose, we are given a set of words like Apple, Mango, Orange, Party, Guava, and we have to find the odd word. We as a human can analyze and predict that Party is the odd word as all other words are names of fruit, but for a model to understand this and find this out is very difficult. Here, we will be using Word2Vec model and a pre-trained model named ‘GoogleNews-vectors-negative300.bin‘ which is trained on over 50 Billion words by Google. Each word inside the pre-trained dataset is embedded in a 300-dimensional space and the words which are similar in context/meaning are placed closer to each other in the space and have a high cosine similarity value.
Methodology to find out the odd word:
We will find the average vector of all the given word vectors, and then we compare cosimilarity value of each word vector with the average vector value, the word with the least cosimilarity will be our odd word.
Importing important libraries:
We need to install an additional gensim library, to use word2vec model, to install gensim use the command ‘pip install gensim‘ on your terminal/command prompt.
Python3
import numpy as npimport gensimfrom gensim.models import word2vec,KeyedVectorsfrom sklearn.metrics.pairwise import cosine_similarity
Loading the word vectors using the pre-trained model:
Python3
vector_word_notations = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin',binary=True)
Defining a function to predict the odd word:
Python3
def odd_word_out(input_words): '''The function accepts a list of word and returns the odd word.''' # Generate all word embeddings for the given list of words whole_word_vectors = [vector_word_notations[i] for i in input_words] # average vector for all word vectors mean_vector = np.mean(whole_word_vectors,axis=0) # Iterate over every word and find similarity odd_word = None minimum_similarity = 99999.0 # Can be any very high value for i in input_words: similarity = cosine_similarity([vector_word_notations[i]],[mean_vector]) if similarity < minimum_similarity: minimum_similarity = similarity odd_word = i print("cosine similarity score between %s and mean_vector is %.3f"%(i,similarity)) print("\nThe odd word is: "+odd_word)
Testing our model:
Python3
input_1 = ['apple','mango','juice','party','orange','guava'] # party is odd wordodd_word_out(input_1)
Output:
cosine similarity score between apple and mean_vector is 0.765
cosine similarity score between mango and mean_vector is 0.808
cosine similarity score between juice and mean_vector is 0.688
cosine similarity score between party and mean_vector is 0.289
cosine similarity score between orange and mean_vector is 0.611
cosine similarity score between guava and mean_vector is 0.790
The odd word is: party
Similarly, for another example, let’s say:
Python
input_2 = ['India','paris','Russia','France','Germany','USA']# paris is an odd word since it is a capital and other are countriesodd_word_out(input_2)
Output:
cosine similarity score between India and mean_vector is 0.660
cosine similarity score between paris and mean_vector is 0.518
cosine similarity score between Russia and mean_vector is 0.691
cosine similarity score between France and mean_vector is 0.758
cosine similarity score between Germany and mean_vector is 0.763
cosine similarity score between USA and mean_vector is 0.564
The odd word is: paris
saurabh48782
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": "\n27 Jan, 2021"
},
{
"code": null,
"e": 437,
"s": 28,
"text": "Odd One out the problem is one of the most interesting and goto problems when it comes to testing the logical reasoning skills of an individual. It is often used in many competitive exams and placement rounds as it checks the individual’s analytical skills and decision-making ability. In this article, we are going to write a python code that can be used to find the odd words amongst a given set of words. "
},
{
"code": null,
"e": 1100,
"s": 437,
"text": "Suppose, we are given a set of words like Apple, Mango, Orange, Party, Guava, and we have to find the odd word. We as a human can analyze and predict that Party is the odd word as all other words are names of fruit, but for a model to understand this and find this out is very difficult. Here, we will be using Word2Vec model and a pre-trained model named ‘GoogleNews-vectors-negative300.bin‘ which is trained on over 50 Billion words by Google. Each word inside the pre-trained dataset is embedded in a 300-dimensional space and the words which are similar in context/meaning are placed closer to each other in the space and have a high cosine similarity value."
},
{
"code": null,
"e": 1138,
"s": 1100,
"text": "Methodology to find out the odd word:"
},
{
"code": null,
"e": 1350,
"s": 1138,
"text": "We will find the average vector of all the given word vectors, and then we compare cosimilarity value of each word vector with the average vector value, the word with the least cosimilarity will be our odd word."
},
{
"code": null,
"e": 1381,
"s": 1350,
"text": "Importing important libraries:"
},
{
"code": null,
"e": 1541,
"s": 1381,
"text": "We need to install an additional gensim library, to use word2vec model, to install gensim use the command ‘pip install gensim‘ on your terminal/command prompt."
},
{
"code": null,
"e": 1549,
"s": 1541,
"text": "Python3"
},
{
"code": "import numpy as npimport gensimfrom gensim.models import word2vec,KeyedVectorsfrom sklearn.metrics.pairwise import cosine_similarity",
"e": 1682,
"s": 1549,
"text": null
},
{
"code": null,
"e": 1739,
"s": 1685,
"text": "Loading the word vectors using the pre-trained model:"
},
{
"code": null,
"e": 1747,
"s": 1739,
"text": "Python3"
},
{
"code": "vector_word_notations = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin',binary=True)",
"e": 1855,
"s": 1747,
"text": null
},
{
"code": null,
"e": 1903,
"s": 1858,
"text": "Defining a function to predict the odd word:"
},
{
"code": null,
"e": 1911,
"s": 1903,
"text": "Python3"
},
{
"code": "def odd_word_out(input_words): '''The function accepts a list of word and returns the odd word.''' # Generate all word embeddings for the given list of words whole_word_vectors = [vector_word_notations[i] for i in input_words] # average vector for all word vectors mean_vector = np.mean(whole_word_vectors,axis=0) # Iterate over every word and find similarity odd_word = None minimum_similarity = 99999.0 # Can be any very high value for i in input_words: similarity = cosine_similarity([vector_word_notations[i]],[mean_vector]) if similarity < minimum_similarity: minimum_similarity = similarity odd_word = i print(\"cosine similarity score between %s and mean_vector is %.3f\"%(i,similarity)) print(\"\\nThe odd word is: \"+odd_word)",
"e": 2750,
"s": 1911,
"text": null
},
{
"code": null,
"e": 2772,
"s": 2753,
"text": "Testing our model:"
},
{
"code": null,
"e": 2780,
"s": 2772,
"text": "Python3"
},
{
"code": "input_1 = ['apple','mango','juice','party','orange','guava'] # party is odd wordodd_word_out(input_1)",
"e": 2882,
"s": 2780,
"text": null
},
{
"code": null,
"e": 2890,
"s": 2882,
"text": "Output:"
},
{
"code": null,
"e": 3294,
"s": 2890,
"text": "cosine similarity score between apple and mean_vector is 0.765\ncosine similarity score between mango and mean_vector is 0.808\ncosine similarity score between juice and mean_vector is 0.688\ncosine similarity score between party and mean_vector is 0.289\ncosine similarity score between orange and mean_vector is 0.611\ncosine similarity score between guava and mean_vector is 0.790\n\nThe odd word is: party"
},
{
"code": null,
"e": 3337,
"s": 3294,
"text": "Similarly, for another example, let’s say:"
},
{
"code": null,
"e": 3344,
"s": 3337,
"text": "Python"
},
{
"code": "input_2 = ['India','paris','Russia','France','Germany','USA']# paris is an odd word since it is a capital and other are countriesodd_word_out(input_2)",
"e": 3495,
"s": 3344,
"text": null
},
{
"code": null,
"e": 3503,
"s": 3495,
"text": "Output:"
},
{
"code": null,
"e": 3913,
"s": 3503,
"text": "cosine similarity score between India and mean_vector is 0.660 \ncosine similarity score between paris and mean_vector is 0.518\ncosine similarity score between Russia and mean_vector is 0.691\ncosine similarity score between France and mean_vector is 0.758\ncosine similarity score between Germany and mean_vector is 0.763 \ncosine similarity score between USA and mean_vector is 0.564\n\nThe odd word is: paris"
},
{
"code": null,
"e": 3926,
"s": 3913,
"text": "saurabh48782"
},
{
"code": null,
"e": 3943,
"s": 3926,
"text": "Machine Learning"
},
{
"code": null,
"e": 3960,
"s": 3943,
"text": "Machine Learning"
}
]
|
Python | Move element to end of the list | 12 Mar, 2019
The manipulation of lists is quite common in day-day programming. One can come across various issues where one wishes to perform using just one-liners. One such problem can be of moving a list element to the rear ( end of list ). Let’s discuss certain ways in which this can be done.
Method #1 : Using append() + pop() + index()This particular functionality can be performed in one line by combining these functions. The append function adds the element removed by pop function using the index provided by index function.
# Python3 code to demonstrate # moving element to end # using append() + pop() + index() # initializing listtest_list = ['3', '5', '7', '9', '11'] # printing original list print ("The original list is : " + str(test_list)) # using append() + pop() + index()# moving element to end test_list.append(test_list.pop(test_list.index(5))) # printing resultprint ("The modified element moved list is : " + str(test_list))
The original list is : ['3', '5', '7', '9', '11']
The modified element moved list is : ['3', '7', '9', '11', '5']
Method #2 : Using sort() + key = (__eq__)The sort method can also be used to achieve this particular task in which we provide the key as equal to the string we wish to shift so that it is moved to the end.
# Python3 code to demonstrate # moving element to end # using sort() + key = (__eq__) # initializing listtest_list = ['3', '5', '7', '9', '11'] # printing original list print ("The original list is : " + str(test_list)) # using sort() + key = (__eq__)# moving element to end test_list.sort(key = '5'.__eq__) # printing resultprint ("The modified element moved list is : " + str(test_list))
The original list is : ['3', '5', '7', '9', '11']
The modified element moved list is : ['3', '7', '9', '11', '5']
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Mar, 2019"
},
{
"code": null,
"e": 312,
"s": 28,
"text": "The manipulation of lists is quite common in day-day programming. One can come across various issues where one wishes to perform using just one-liners. One such problem can be of moving a list element to the rear ( end of list ). Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 550,
"s": 312,
"text": "Method #1 : Using append() + pop() + index()This particular functionality can be performed in one line by combining these functions. The append function adds the element removed by pop function using the index provided by index function."
},
{
"code": "# Python3 code to demonstrate # moving element to end # using append() + pop() + index() # initializing listtest_list = ['3', '5', '7', '9', '11'] # printing original list print (\"The original list is : \" + str(test_list)) # using append() + pop() + index()# moving element to end test_list.append(test_list.pop(test_list.index(5))) # printing resultprint (\"The modified element moved list is : \" + str(test_list))",
"e": 970,
"s": 550,
"text": null
},
{
"code": null,
"e": 1085,
"s": 970,
"text": "The original list is : ['3', '5', '7', '9', '11']\nThe modified element moved list is : ['3', '7', '9', '11', '5']\n"
},
{
"code": null,
"e": 1293,
"s": 1087,
"text": "Method #2 : Using sort() + key = (__eq__)The sort method can also be used to achieve this particular task in which we provide the key as equal to the string we wish to shift so that it is moved to the end."
},
{
"code": "# Python3 code to demonstrate # moving element to end # using sort() + key = (__eq__) # initializing listtest_list = ['3', '5', '7', '9', '11'] # printing original list print (\"The original list is : \" + str(test_list)) # using sort() + key = (__eq__)# moving element to end test_list.sort(key = '5'.__eq__) # printing resultprint (\"The modified element moved list is : \" + str(test_list))",
"e": 1688,
"s": 1293,
"text": null
},
{
"code": null,
"e": 1803,
"s": 1688,
"text": "The original list is : ['3', '5', '7', '9', '11']\nThe modified element moved list is : ['3', '7', '9', '11', '5']\n"
},
{
"code": null,
"e": 1824,
"s": 1803,
"text": "Python list-programs"
},
{
"code": null,
"e": 1831,
"s": 1824,
"text": "Python"
},
{
"code": null,
"e": 1847,
"s": 1831,
"text": "Python Programs"
}
]
|
How to create AGE Calculator Web App PyWebIO in Python ? - GeeksforGeeks | 17 Jun, 2021
In this article, we are going to create an AGE Calculator that will show your age in years, months, and days with the help of the current date. We will use the PyWebIO module for creating a simple and interactive interface on the web. This is a python module mostly used to create simple and interactive interfaces on the web using Python programming. It can be installed using the below command:
pip install pywebio
Stepwise Implementation:
Step 1: Import all the required modules.
Python3
# Import the following modulesfrom dateutil.relativedelta import relativedeltafrom datetime import datetimefrom time import strptimefrom pywebio.input import *from pywebio.output import *from pywebio.session import *import time
Step 2: Getting current time and taking input from the user.
Python3
# Getting Current time.date = datetime.now().strftime("%d/%m/%Y") # Taking age from the userDOB = input("", placeholder = "Your Birth Date(dd/mm/yyyy)")
Step 3: Checking whether the format of age is correct or not.
Python3
try: # Check whether the input age format # is same as given format val = strptime(DOB, "%d/%m/%Y")except: # If format is different, then through # an error. put_error("Alert! This is not the right format") time.sleep(3) # sleep for 3 seconds continue
Step 4: Split the Birth Date of the user and the Current Date by ‘/’. And then Typecast all the split parts into the integer. Swap months and years for both the user’s birth date and current date.
Python3
# Split the age by '/'in_date = DOB.split('/') # split the todays date by '/'date = date.split('/') # Typecast all the converted part # into the int.in_date = [int(i) for i in in_date] date = [int(i) for i in date] newdate = [] # Swap days with yearsin_date[0], in_date[2] = in_date[2], in_date[0] # Swap days with yearsdate[0], date[2] = date[2], date[0]
Step 5: Check whether or not the current year is smaller than the User’s D.O.B year. If the current year is smaller than through an error.
Python3
if in_date <= date: now = datetime.strptime(DOB, "%d/%m/%Y") # Display output in a pop window popup("Your Age",k [put_html("<h4>"f"{relativedelta(datetime.now(),now).years} Years</br> \ {relativedelta(datetime.now(),now).months} Months</br>\ {relativedelta(datetime.now(),now).days} Days""</h4>"), put_buttons( ['Close'], onclick=lambda _: close_popup())], implicit_close=True)else: # If you input the year greater than current year put_warning( f"No result found, this is {date[0]}, and you can't be in {in_date[0]}.")
Complete Code:
Python3
# Import the following modulesfrom dateutil.relativedelta import relativedeltafrom datetime import datetimefrom time import strptimefrom pywebio.input import *from pywebio.output import *from pywebio.session import *import time # Run infinite loopwhile True: clear() # Put a heading Age Calculator put_html("<p align=""left""><h4> AGE CALCULATOR</h4></p>") # Getting Current time. date = datetime.now().strftime("%d/%m/%Y") # Taking age from the user DOB = input("", placeholder="Your Birth Date(dd/mm/yyyy)") try: # Check whether the input age # format is same as given format val = strptime(DOB, "%d/%m/%Y") except: # If format is different, then through an error. put_error("Alert! This is not the right format") # sleep for 3 seconds time.sleep(3) continue in_date = DOB.split('/') date = date.split('/') # Typecast all the converted part into the int. in_date = [int(i) for i in in_date] date = [int(i) for i in date] # Define an empty list newdate = [] # Swap days with years in_date[0], in_date[2] = in_date[2], in_date[0] # Swap days with years date[0], date[2] = date[2], date[0] if in_date <= date: now = datetime.strptime(DOB, "%d/%m/%Y") # Display output popup("Your Age", [put_html("<h4>"f"{relativedelta(datetime.now(),now).years} Years</br> \ {relativedelta(datetime.now(),now).months} Months</br>\ {relativedelta(datetime.now(),now).days} Days""</h4>"), put_buttons( ['Close'], onclick=lambda _: close_popup())], implicit_close=True) else: # If you input the year greater than current year put_warning( f"No result found, this is {date[0]}, and you can't be in {in_date[0]}.") time.sleep(3) clear() # Give user a choice choice = radio("Do you want to calculate again?", options=['Yes', 'No'], required=True) if choice.lower() == 'yes': continue else: clear() # Show a toast notification toast("Thanks a lot!") exit()
Output:
python-modules
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": 23927,
"s": 23899,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 24324,
"s": 23927,
"text": "In this article, we are going to create an AGE Calculator that will show your age in years, months, and days with the help of the current date. We will use the PyWebIO module for creating a simple and interactive interface on the web. This is a python module mostly used to create simple and interactive interfaces on the web using Python programming. It can be installed using the below command:"
},
{
"code": null,
"e": 24344,
"s": 24324,
"text": "pip install pywebio"
},
{
"code": null,
"e": 24369,
"s": 24344,
"text": "Stepwise Implementation:"
},
{
"code": null,
"e": 24410,
"s": 24369,
"text": "Step 1: Import all the required modules."
},
{
"code": null,
"e": 24418,
"s": 24410,
"text": "Python3"
},
{
"code": "# Import the following modulesfrom dateutil.relativedelta import relativedeltafrom datetime import datetimefrom time import strptimefrom pywebio.input import *from pywebio.output import *from pywebio.session import *import time",
"e": 24646,
"s": 24418,
"text": null
},
{
"code": null,
"e": 24707,
"s": 24646,
"text": "Step 2: Getting current time and taking input from the user."
},
{
"code": null,
"e": 24715,
"s": 24707,
"text": "Python3"
},
{
"code": "# Getting Current time.date = datetime.now().strftime(\"%d/%m/%Y\") # Taking age from the userDOB = input(\"\", placeholder = \"Your Birth Date(dd/mm/yyyy)\")",
"e": 24871,
"s": 24715,
"text": null
},
{
"code": null,
"e": 24933,
"s": 24871,
"text": "Step 3: Checking whether the format of age is correct or not."
},
{
"code": null,
"e": 24941,
"s": 24933,
"text": "Python3"
},
{
"code": "try: # Check whether the input age format # is same as given format val = strptime(DOB, \"%d/%m/%Y\")except: # If format is different, then through # an error. put_error(\"Alert! This is not the right format\") time.sleep(3) # sleep for 3 seconds continue",
"e": 25224,
"s": 24941,
"text": null
},
{
"code": null,
"e": 25421,
"s": 25224,
"text": "Step 4: Split the Birth Date of the user and the Current Date by ‘/’. And then Typecast all the split parts into the integer. Swap months and years for both the user’s birth date and current date."
},
{
"code": null,
"e": 25429,
"s": 25421,
"text": "Python3"
},
{
"code": "# Split the age by '/'in_date = DOB.split('/') # split the todays date by '/'date = date.split('/') # Typecast all the converted part # into the int.in_date = [int(i) for i in in_date] date = [int(i) for i in date] newdate = [] # Swap days with yearsin_date[0], in_date[2] = in_date[2], in_date[0] # Swap days with yearsdate[0], date[2] = date[2], date[0]",
"e": 25795,
"s": 25429,
"text": null
},
{
"code": null,
"e": 25934,
"s": 25795,
"text": "Step 5: Check whether or not the current year is smaller than the User’s D.O.B year. If the current year is smaller than through an error."
},
{
"code": null,
"e": 25942,
"s": 25934,
"text": "Python3"
},
{
"code": "if in_date <= date: now = datetime.strptime(DOB, \"%d/%m/%Y\") # Display output in a pop window popup(\"Your Age\",k [put_html(\"<h4>\"f\"{relativedelta(datetime.now(),now).years} Years</br> \\ {relativedelta(datetime.now(),now).months} Months</br>\\ {relativedelta(datetime.now(),now).days} Days\"\"</h4>\"), put_buttons( ['Close'], onclick=lambda _: close_popup())], implicit_close=True)else: # If you input the year greater than current year put_warning( f\"No result found, this is {date[0]}, and you can't be in {in_date[0]}.\")",
"e": 26570,
"s": 25942,
"text": null
},
{
"code": null,
"e": 26585,
"s": 26570,
"text": "Complete Code:"
},
{
"code": null,
"e": 26593,
"s": 26585,
"text": "Python3"
},
{
"code": "# Import the following modulesfrom dateutil.relativedelta import relativedeltafrom datetime import datetimefrom time import strptimefrom pywebio.input import *from pywebio.output import *from pywebio.session import *import time # Run infinite loopwhile True: clear() # Put a heading Age Calculator put_html(\"<p align=\"\"left\"\"><h4> AGE CALCULATOR</h4></p>\") # Getting Current time. date = datetime.now().strftime(\"%d/%m/%Y\") # Taking age from the user DOB = input(\"\", placeholder=\"Your Birth Date(dd/mm/yyyy)\") try: # Check whether the input age # format is same as given format val = strptime(DOB, \"%d/%m/%Y\") except: # If format is different, then through an error. put_error(\"Alert! This is not the right format\") # sleep for 3 seconds time.sleep(3) continue in_date = DOB.split('/') date = date.split('/') # Typecast all the converted part into the int. in_date = [int(i) for i in in_date] date = [int(i) for i in date] # Define an empty list newdate = [] # Swap days with years in_date[0], in_date[2] = in_date[2], in_date[0] # Swap days with years date[0], date[2] = date[2], date[0] if in_date <= date: now = datetime.strptime(DOB, \"%d/%m/%Y\") # Display output popup(\"Your Age\", [put_html(\"<h4>\"f\"{relativedelta(datetime.now(),now).years} Years</br> \\ {relativedelta(datetime.now(),now).months} Months</br>\\ {relativedelta(datetime.now(),now).days} Days\"\"</h4>\"), put_buttons( ['Close'], onclick=lambda _: close_popup())], implicit_close=True) else: # If you input the year greater than current year put_warning( f\"No result found, this is {date[0]}, and you can't be in {in_date[0]}.\") time.sleep(3) clear() # Give user a choice choice = radio(\"Do you want to calculate again?\", options=['Yes', 'No'], required=True) if choice.lower() == 'yes': continue else: clear() # Show a toast notification toast(\"Thanks a lot!\") exit()",
"e": 28840,
"s": 26593,
"text": null
},
{
"code": null,
"e": 28849,
"s": 28840,
"text": "Output: "
},
{
"code": null,
"e": 28864,
"s": 28849,
"text": "python-modules"
},
{
"code": null,
"e": 28871,
"s": 28864,
"text": "Python"
},
{
"code": null,
"e": 28969,
"s": 28871,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28978,
"s": 28969,
"text": "Comments"
},
{
"code": null,
"e": 28991,
"s": 28978,
"text": "Old Comments"
},
{
"code": null,
"e": 29023,
"s": 28991,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29079,
"s": 29023,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29121,
"s": 29079,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29163,
"s": 29121,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29199,
"s": 29163,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29221,
"s": 29199,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29260,
"s": 29221,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29287,
"s": 29260,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29318,
"s": 29287,
"text": "Python | os.path.join() method"
}
]
|
E-Mail Format - GeeksforGeeks | 20 Oct, 2020
Electronic Mail (e-mail) is one of the most widely used services of the Internet. This service allows an Internet user to send a message in a formatted manner (mail) to other Internet users in any part of the world. Message in the mail not only contain text, but it also contains images, audio and videos data. The person who is sending mail is called sender and person who receives mail is called the recipient. It is just like postal mail service.
Format of E-mail : An e-mail consists of three parts that are as follows :
1. Envelope
2. Header
3. Body
These are explained as following below.
1. Envelope : The envelope part encapsulates the message. It contains all information that is required for sending any e-mail such as destination address, priority and security level. The envelope is used by MTAs for routing message.
2. Header : The header consists of a series of lines. Each header field consists of a single line of ASCII text specifying field name, colon and value. The main header fields related to message transport are :
To: It specifies the DNS address of the primary recipient(s).Cc : It refers to carbon copy. It specifies address of secondary recipient(s).BCC: It refers to blind carbon copy. It is very similar to Cc. The only difference between Cc and Bcc is that it allow user to send copy to the third party without primary and secondary recipient knowing about this.From : It specifies name of person who wrote message.Sender : It specifies e-mail address of person who has sent message.Received : It refers to identity of sender’s, data and also time message was received. It also contains the information which is used to find bugs in routing system.Return-Path: It is added by the message transfer agent. This part is used to specify how to get back to the sender.
To: It specifies the DNS address of the primary recipient(s).
Cc : It refers to carbon copy. It specifies address of secondary recipient(s).
BCC: It refers to blind carbon copy. It is very similar to Cc. The only difference between Cc and Bcc is that it allow user to send copy to the third party without primary and secondary recipient knowing about this.
From : It specifies name of person who wrote message.
Sender : It specifies e-mail address of person who has sent message.
Received : It refers to identity of sender’s, data and also time message was received. It also contains the information which is used to find bugs in routing system.
Return-Path: It is added by the message transfer agent. This part is used to specify how to get back to the sender.
3. Body:- The body of a message contains text that is the actual content/message that needs to be sent, such as “Employees who are eligible for the new health care program should contact their supervisors by next Friday if they want to switch.” The message body also may include signatures or automatically generated text that is inserted by the sender’s email system.
The above-discussed field is represented in tabular form as follows :
In addition to above-discussed fields, the header may also contain a variety of other fields which are as follows :
anshitaagarwal
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Top 10 Angular Libraries For Web Developers
Working with csv files in Python
Types of Software Testing
Differences between Procedural and Object Oriented Programming
Top 10 System Design Interview Questions and Answers
XML parsing in Python | [
{
"code": null,
"e": 24982,
"s": 24954,
"text": "\n20 Oct, 2020"
},
{
"code": null,
"e": 25433,
"s": 24982,
"text": "Electronic Mail (e-mail) is one of the most widely used services of the Internet. This service allows an Internet user to send a message in a formatted manner (mail) to other Internet users in any part of the world. Message in the mail not only contain text, but it also contains images, audio and videos data. The person who is sending mail is called sender and person who receives mail is called the recipient. It is just like postal mail service. "
},
{
"code": null,
"e": 25509,
"s": 25433,
"text": "Format of E-mail : An e-mail consists of three parts that are as follows : "
},
{
"code": null,
"e": 25541,
"s": 25509,
"text": "1. Envelope\n2. Header\n3. Body \n"
},
{
"code": null,
"e": 25582,
"s": 25541,
"text": "These are explained as following below. "
},
{
"code": null,
"e": 25817,
"s": 25582,
"text": "1. Envelope : The envelope part encapsulates the message. It contains all information that is required for sending any e-mail such as destination address, priority and security level. The envelope is used by MTAs for routing message. "
},
{
"code": null,
"e": 26028,
"s": 25817,
"text": "2. Header : The header consists of a series of lines. Each header field consists of a single line of ASCII text specifying field name, colon and value. The main header fields related to message transport are : "
},
{
"code": null,
"e": 26784,
"s": 26028,
"text": "To: It specifies the DNS address of the primary recipient(s).Cc : It refers to carbon copy. It specifies address of secondary recipient(s).BCC: It refers to blind carbon copy. It is very similar to Cc. The only difference between Cc and Bcc is that it allow user to send copy to the third party without primary and secondary recipient knowing about this.From : It specifies name of person who wrote message.Sender : It specifies e-mail address of person who has sent message.Received : It refers to identity of sender’s, data and also time message was received. It also contains the information which is used to find bugs in routing system.Return-Path: It is added by the message transfer agent. This part is used to specify how to get back to the sender."
},
{
"code": null,
"e": 26846,
"s": 26784,
"text": "To: It specifies the DNS address of the primary recipient(s)."
},
{
"code": null,
"e": 26925,
"s": 26846,
"text": "Cc : It refers to carbon copy. It specifies address of secondary recipient(s)."
},
{
"code": null,
"e": 27141,
"s": 26925,
"text": "BCC: It refers to blind carbon copy. It is very similar to Cc. The only difference between Cc and Bcc is that it allow user to send copy to the third party without primary and secondary recipient knowing about this."
},
{
"code": null,
"e": 27195,
"s": 27141,
"text": "From : It specifies name of person who wrote message."
},
{
"code": null,
"e": 27264,
"s": 27195,
"text": "Sender : It specifies e-mail address of person who has sent message."
},
{
"code": null,
"e": 27430,
"s": 27264,
"text": "Received : It refers to identity of sender’s, data and also time message was received. It also contains the information which is used to find bugs in routing system."
},
{
"code": null,
"e": 27546,
"s": 27430,
"text": "Return-Path: It is added by the message transfer agent. This part is used to specify how to get back to the sender."
},
{
"code": null,
"e": 27916,
"s": 27546,
"text": "3. Body:- The body of a message contains text that is the actual content/message that needs to be sent, such as “Employees who are eligible for the new health care program should contact their supervisors by next Friday if they want to switch.” The message body also may include signatures or automatically generated text that is inserted by the sender’s email system."
},
{
"code": null,
"e": 27988,
"s": 27916,
"text": "The above-discussed field is represented in tabular form as follows : "
},
{
"code": null,
"e": 28106,
"s": 27988,
"text": "In addition to above-discussed fields, the header may also contain a variety of other fields which are as follows : "
},
{
"code": null,
"e": 28121,
"s": 28106,
"text": "anshitaagarwal"
},
{
"code": null,
"e": 28127,
"s": 28121,
"text": "GBlog"
},
{
"code": null,
"e": 28225,
"s": 28127,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28234,
"s": 28225,
"text": "Comments"
},
{
"code": null,
"e": 28247,
"s": 28234,
"text": "Old Comments"
},
{
"code": null,
"e": 28289,
"s": 28247,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28314,
"s": 28289,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 28349,
"s": 28314,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 28411,
"s": 28349,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28455,
"s": 28411,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 28488,
"s": 28455,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 28514,
"s": 28488,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 28577,
"s": 28514,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 28630,
"s": 28577,
"text": "Top 10 System Design Interview Questions and Answers"
}
]
|
C Program for Rabin-Karp Algorithm for Pattern Searching | Pattern matching in C − We have to find if a string is present in another string, as an example, the string "algorithm” is present within the string "naive algorithm". If it is found, then its location (i.e. position it is present at) is displayed. We tend to create a function that receives 2character arrays and returns the position if matching
happens otherwise returns -1.
Input: txt = "HERE IS A NICE CAP"
pattern = "NICE"
Output: Pattern found at index 10
Input: txt = "XYZXACAADXYZXYZX"
pattern = "XYZX"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
Rabin-Karp is another pattern searching algorithm. It is the string matching
algorithm that was proposed by Rabin and Karp to find the pattern in a more efficient
way. Like the Naive Algorithm, it also checks the pattern by moving the window
one by one, but without checking all characters for all cases, it finds the hash value. When the hash value is matched, then only it proceeds to check each character. In this way, there is only one comparison per text subsequence making it a more efficient algorithm for pattern searching.
Preprocessing time- O(m)
The time complexity of the Rabin-Karp Algorithm is O(m+n), but for the worst case,
it is O(mn).
rabinkarp_algo(text, pattern, prime)
Input − The main text and the pattern. Another prime number of find hash location
Output − locations, where the pattern is found
Start
pat_len := pattern Length
str_len := string Length
patHash := 0 and strHash := 0, h := 1
maxChar := total number of characters in character set
for index i of all character in the pattern, do
h := (h*maxChar) mod prime
for all character index i of pattern, do
patHash := (maxChar*patHash + pattern[i]) mod prime
strHash := (maxChar*strHash + text[i]) mod prime
for i := 0 to (str_len - pat_len), do
if patHash = strHash, then
for charIndex := 0 to pat_len -1, do
if text[i+charIndex] ≠ pattern[charIndex], then
break
if charIndex = pat_len, then
print the location i as pattern found at i position.
if i < (str_len - pat_len), then
strHash := (maxChar*(strHash – text[i]*h)+text[i+patLen]) mod prime, then
if strHash < 0, then
strHash := strHash + prime
End
Live Demo
#include<stdio.h>
#include<string.h>
int main (){
char txt[80], pat[80];
int q;
printf ("Enter the container string \n");
scanf ("%s", &txt);
printf ("Enter the pattern to be searched \n");
scanf ("%s", &pat);
int d = 256;
printf ("Enter a prime number \n");
scanf ("%d", &q);
int M = strlen (pat);
int N = strlen (txt);
int i, j;
int p = 0;
int t = 0;
int h = 1;
for (i = 0; i < M - 1; i++)
h = (h * d) % q;
for (i = 0; i < M; i++){
p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
}
for (i = 0; i <= N - M; i++){
if (p == t){
for (j = 0; j < M; j++){
if (txt[i + j] != pat[j])
break;
}
if (j == M)
printf ("Pattern found at index %d \n", i);
}
if (i < N - M){
t = (d * (t - txt[i] * h) + txt[i + M]) % q;
if (t < 0)
t = (t + q);
}
}
return 0;
}
Enter the container string
tutorialspointisthebestprogrammingwebsite
Enter the pattern to be searched
p
Enter a prime number
3
Pattern found at index 8
Pattern found at index 21 | [
{
"code": null,
"e": 1439,
"s": 1062,
"text": "Pattern matching in C − We have to find if a string is present in another string, as an example, the string \"algorithm” is present within the string \"naive algorithm\". If it is found, then its location (i.e. position it is present at) is displayed. We tend to create a function that receives 2character arrays and returns the position if matching\nhappens otherwise returns -1."
},
{
"code": null,
"e": 1669,
"s": 1439,
"text": "Input: txt = \"HERE IS A NICE CAP\"\n pattern = \"NICE\"\nOutput: Pattern found at index 10\nInput: txt = \"XYZXACAADXYZXYZX\"\n pattern = \"XYZX\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12"
},
{
"code": null,
"e": 2201,
"s": 1669,
"text": "Rabin-Karp is another pattern searching algorithm. It is the string matching\nalgorithm that was proposed by Rabin and Karp to find the pattern in a more efficient\nway. Like the Naive Algorithm, it also checks the pattern by moving the window\none by one, but without checking all characters for all cases, it finds the hash value. When the hash value is matched, then only it proceeds to check each character. In this way, there is only one comparison per text subsequence making it a more efficient algorithm for pattern searching."
},
{
"code": null,
"e": 2226,
"s": 2201,
"text": "Preprocessing time- O(m)"
},
{
"code": null,
"e": 2322,
"s": 2226,
"text": "The time complexity of the Rabin-Karp Algorithm is O(m+n), but for the worst case,\nit is O(mn)."
},
{
"code": null,
"e": 2359,
"s": 2322,
"text": "rabinkarp_algo(text, pattern, prime)"
},
{
"code": null,
"e": 2441,
"s": 2359,
"text": "Input − The main text and the pattern. Another prime number of find hash location"
},
{
"code": null,
"e": 2488,
"s": 2441,
"text": "Output − locations, where the pattern is found"
},
{
"code": null,
"e": 3313,
"s": 2488,
"text": "Start\n pat_len := pattern Length\n str_len := string Length\n patHash := 0 and strHash := 0, h := 1\n maxChar := total number of characters in character set\nfor index i of all character in the pattern, do\n h := (h*maxChar) mod prime\nfor all character index i of pattern, do\n patHash := (maxChar*patHash + pattern[i]) mod prime\n strHash := (maxChar*strHash + text[i]) mod prime\nfor i := 0 to (str_len - pat_len), do\n if patHash = strHash, then\n for charIndex := 0 to pat_len -1, do\n if text[i+charIndex] ≠ pattern[charIndex], then\n break\nif charIndex = pat_len, then\n print the location i as pattern found at i position.\nif i < (str_len - pat_len), then\n strHash := (maxChar*(strHash – text[i]*h)+text[i+patLen]) mod prime, then\n if strHash < 0, then\n strHash := strHash + prime\nEnd"
},
{
"code": null,
"e": 3324,
"s": 3313,
"text": " Live Demo"
},
{
"code": null,
"e": 4272,
"s": 3324,
"text": "#include<stdio.h>\n#include<string.h>\nint main (){\n char txt[80], pat[80];\n int q;\n printf (\"Enter the container string \\n\");\n scanf (\"%s\", &txt);\n printf (\"Enter the pattern to be searched \\n\");\n scanf (\"%s\", &pat);\n int d = 256;\n printf (\"Enter a prime number \\n\");\n scanf (\"%d\", &q);\n int M = strlen (pat);\n int N = strlen (txt);\n int i, j;\n int p = 0;\n int t = 0;\n int h = 1;\n for (i = 0; i < M - 1; i++)\n h = (h * d) % q;\n for (i = 0; i < M; i++){\n p = (d * p + pat[i]) % q;\n t = (d * t + txt[i]) % q;\n }\n for (i = 0; i <= N - M; i++){\n if (p == t){\n for (j = 0; j < M; j++){\n if (txt[i + j] != pat[j])\n break;\n }\n if (j == M)\n printf (\"Pattern found at index %d \\n\", i);\n }\n if (i < N - M){\n t = (d * (t - txt[i] * h) + txt[i + M]) % q;\n if (t < 0)\n t = (t + q);\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 4450,
"s": 4272,
"text": "Enter the container string\ntutorialspointisthebestprogrammingwebsite\nEnter the pattern to be searched\np\nEnter a prime number\n3\nPattern found at index 8\nPattern found at index 21"
}
]
|
IntStream toArray() in Java with Examples - GeeksforGeeks | 06 Dec, 2018
IntStream toArray() returns an array containing the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
Syntax :
int[] toArray()
Return Value : The function returns an array containing the elements of this stream.
Example 1 :
// Java code for IntStream toArray()import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(1, 3, 5, 7, 9); // Using IntStream toArray() int[] arr = stream.toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}
Output :
[1, 3, 5, 7, 9]
Example 2 :
// Java code for IntStream toArray()import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.range(-2, 10); // Using IntStream toArray() int[] arr = stream.toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}
Output :
[-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Java - util package
Java-Functions
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Comparator Interface in Java with Examples
Generics in Java
Functional Interfaces in Java
Java Programming Examples
HashMap get() Method in Java | [
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 24156,
"s": 23868,
"text": "IntStream toArray() returns an array containing the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used."
},
{
"code": null,
"e": 24165,
"s": 24156,
"text": "Syntax :"
},
{
"code": null,
"e": 24182,
"s": 24165,
"text": "int[] toArray()\n"
},
{
"code": null,
"e": 24267,
"s": 24182,
"text": "Return Value : The function returns an array containing the elements of this stream."
},
{
"code": null,
"e": 24279,
"s": 24267,
"text": "Example 1 :"
},
{
"code": "// Java code for IntStream toArray()import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(1, 3, 5, 7, 9); // Using IntStream toArray() int[] arr = stream.toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}",
"e": 24715,
"s": 24279,
"text": null
},
{
"code": null,
"e": 24724,
"s": 24715,
"text": "Output :"
},
{
"code": null,
"e": 24741,
"s": 24724,
"text": "[1, 3, 5, 7, 9]\n"
},
{
"code": null,
"e": 24753,
"s": 24741,
"text": "Example 2 :"
},
{
"code": "// Java code for IntStream toArray()import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.range(-2, 10); // Using IntStream toArray() int[] arr = stream.toArray(); // Displaying the elements in array arr System.out.println(Arrays.toString(arr)); }}",
"e": 25185,
"s": 24753,
"text": null
},
{
"code": null,
"e": 25194,
"s": 25185,
"text": "Output :"
},
{
"code": null,
"e": 25234,
"s": 25194,
"text": "[-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
},
{
"code": null,
"e": 25254,
"s": 25234,
"text": "Java - util package"
},
{
"code": null,
"e": 25269,
"s": 25254,
"text": "Java-Functions"
},
{
"code": null,
"e": 25284,
"s": 25269,
"text": "java-intstream"
},
{
"code": null,
"e": 25296,
"s": 25284,
"text": "java-stream"
},
{
"code": null,
"e": 25301,
"s": 25296,
"text": "Java"
},
{
"code": null,
"e": 25306,
"s": 25301,
"text": "Java"
},
{
"code": null,
"e": 25404,
"s": 25306,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25413,
"s": 25404,
"text": "Comments"
},
{
"code": null,
"e": 25426,
"s": 25413,
"text": "Old Comments"
},
{
"code": null,
"e": 25472,
"s": 25426,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25493,
"s": 25472,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25508,
"s": 25493,
"text": "Stream In Java"
},
{
"code": null,
"e": 25527,
"s": 25508,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25569,
"s": 25527,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 25612,
"s": 25569,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 25629,
"s": 25612,
"text": "Generics in Java"
},
{
"code": null,
"e": 25659,
"s": 25629,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25685,
"s": 25659,
"text": "Java Programming Examples"
}
]
|
Publishing a Docker Image on Dockerhub | Dockerhub or the official docker registry consists of numerous pre-built Docker Images as well as customized images by other users that you can pull to your system if they have been made public. In order to pull or push images to the docker registry, you need to first have an account in Dockerhub.
To create an account and a repository in dockerhub, you can follow these steps −
Visit the docker hub (Link − https://hub.docker.com/).
Visit the docker hub (Link − https://hub.docker.com/).
Create an account or if you already have one, sign in with your account details.
Create an account or if you already have one, sign in with your account details.
After signing in, click on create repository on the welcome page.
After signing in, click on create repository on the welcome page.
Fill in the details such as, repository name, visibility (public or private), etc.
Fill in the details such as, repository name, visibility (public or private), etc.
Let us first see how you can pull an existing image from dockerhub.
You can do so by using the following command −
sudo docker run −it ubuntu
This will check if an ubuntu image already exists in your system or not. If it doesn’t, it will start pulling from the dockerhub.
You can also simply pull the image using the following command.
sudo docker pull ubuntu
Now, we are going to see how to publish your own customized image on dockerhub. After you have created your account on dockerhub and verified your email ID, you are all set to publish your first image.
After you have created the repository in dockerhub using the above discussed steps, open a terminal and run the following command to login yourself.
sudo docker login −−username=<USERNAME> −−email=<EMAIL ID>
Using your username and email ID in the above command, run the command and it will prompt you to enter your correct password. After entering your password, run the following command to check the list of images in your local system
sudo docker images
You can tag the image you want to publish using the following command.
sudo docker tag <image−id> <user−name>/<image−name>:<tag>
You should use such a tag name which will describe your image properly. You can either use the version of your image or simply a suitable project name.
After that you can push your image to the docker registry using the following command −
sudo push <user−name>/image−name
After this, your image will be published on dockerhub and if it has been made public, anybody on dockerhub will be able to pull it and use it accordingly.
To pull the image back and run it, you can use the following commands −
sudo docker pull <user−name>/<image−name>:<tag>
sudo docker run −it <user−name>/<image−name>:<tag>
However, if your target is to just keep a backup or store your image somewhere so that you will be able to restore it back for future use, you should avoid publishing your image on dockerhub. The reason behind that is if you want to make frequent changes to your image and publish it multiple times and then push it back, it will consume a lot of bandwidth and if you are working on multiple images, it will cost you a lot of resources as well. One possible solution to this, is to just save the image as a tar file in your local system and load it back in case you need it.
To save a local copy of an image as a tar file, you can use the following command.
sudo docker save image−name > tar−file−name.tar
To load the image back, you can use −
sudo docker load −−input tar−file−name.tar
To conclude, in this article, we have seen how to create an account in the docker’s official registry called dockerhub, create a repository there, push a customized docker image there and pull it back and run it. We have also seen an alternative and effective way if you want to backup and restore your images by saving it in a tar file and loading it back for further use.
Creating a backup for docker images is very necessary because in case of a mishap, you don’t want to lose all your work and re creating all the stuff of that image exactly without having access to your previous dockerfile is a very hefty task. | [
{
"code": null,
"e": 1361,
"s": 1062,
"text": "Dockerhub or the official docker registry consists of numerous pre-built Docker Images as well as customized images by other users that you can pull to your system if they have been made public. In order to pull or push images to the docker registry, you need to first have an account in Dockerhub."
},
{
"code": null,
"e": 1442,
"s": 1361,
"text": "To create an account and a repository in dockerhub, you can follow these steps −"
},
{
"code": null,
"e": 1497,
"s": 1442,
"text": "Visit the docker hub (Link − https://hub.docker.com/)."
},
{
"code": null,
"e": 1552,
"s": 1497,
"text": "Visit the docker hub (Link − https://hub.docker.com/)."
},
{
"code": null,
"e": 1633,
"s": 1552,
"text": "Create an account or if you already have one, sign in with your account details."
},
{
"code": null,
"e": 1714,
"s": 1633,
"text": "Create an account or if you already have one, sign in with your account details."
},
{
"code": null,
"e": 1780,
"s": 1714,
"text": "After signing in, click on create repository on the welcome page."
},
{
"code": null,
"e": 1846,
"s": 1780,
"text": "After signing in, click on create repository on the welcome page."
},
{
"code": null,
"e": 1929,
"s": 1846,
"text": "Fill in the details such as, repository name, visibility (public or private), etc."
},
{
"code": null,
"e": 2012,
"s": 1929,
"text": "Fill in the details such as, repository name, visibility (public or private), etc."
},
{
"code": null,
"e": 2080,
"s": 2012,
"text": "Let us first see how you can pull an existing image from dockerhub."
},
{
"code": null,
"e": 2127,
"s": 2080,
"text": "You can do so by using the following command −"
},
{
"code": null,
"e": 2154,
"s": 2127,
"text": "sudo docker run −it ubuntu"
},
{
"code": null,
"e": 2284,
"s": 2154,
"text": "This will check if an ubuntu image already exists in your system or not. If it doesn’t, it will start pulling from the dockerhub."
},
{
"code": null,
"e": 2348,
"s": 2284,
"text": "You can also simply pull the image using the following command."
},
{
"code": null,
"e": 2372,
"s": 2348,
"text": "sudo docker pull ubuntu"
},
{
"code": null,
"e": 2574,
"s": 2372,
"text": "Now, we are going to see how to publish your own customized image on dockerhub. After you have created your account on dockerhub and verified your email ID, you are all set to publish your first image."
},
{
"code": null,
"e": 2723,
"s": 2574,
"text": "After you have created the repository in dockerhub using the above discussed steps, open a terminal and run the following command to login yourself."
},
{
"code": null,
"e": 2782,
"s": 2723,
"text": "sudo docker login −−username=<USERNAME> −−email=<EMAIL ID>"
},
{
"code": null,
"e": 3013,
"s": 2782,
"text": "Using your username and email ID in the above command, run the command and it will prompt you to enter your correct password. After entering your password, run the following command to check the list of images in your local system"
},
{
"code": null,
"e": 3033,
"s": 3013,
"text": "sudo docker images\n"
},
{
"code": null,
"e": 3104,
"s": 3033,
"text": "You can tag the image you want to publish using the following command."
},
{
"code": null,
"e": 3162,
"s": 3104,
"text": "sudo docker tag <image−id> <user−name>/<image−name>:<tag>"
},
{
"code": null,
"e": 3314,
"s": 3162,
"text": "You should use such a tag name which will describe your image properly. You can either use the version of your image or simply a suitable project name."
},
{
"code": null,
"e": 3402,
"s": 3314,
"text": "After that you can push your image to the docker registry using the following command −"
},
{
"code": null,
"e": 3435,
"s": 3402,
"text": "sudo push <user−name>/image−name"
},
{
"code": null,
"e": 3590,
"s": 3435,
"text": "After this, your image will be published on dockerhub and if it has been made public, anybody on dockerhub will be able to pull it and use it accordingly."
},
{
"code": null,
"e": 3662,
"s": 3590,
"text": "To pull the image back and run it, you can use the following commands −"
},
{
"code": null,
"e": 3761,
"s": 3662,
"text": "sudo docker pull <user−name>/<image−name>:<tag>\nsudo docker run −it <user−name>/<image−name>:<tag>"
},
{
"code": null,
"e": 4336,
"s": 3761,
"text": "However, if your target is to just keep a backup or store your image somewhere so that you will be able to restore it back for future use, you should avoid publishing your image on dockerhub. The reason behind that is if you want to make frequent changes to your image and publish it multiple times and then push it back, it will consume a lot of bandwidth and if you are working on multiple images, it will cost you a lot of resources as well. One possible solution to this, is to just save the image as a tar file in your local system and load it back in case you need it."
},
{
"code": null,
"e": 4419,
"s": 4336,
"text": "To save a local copy of an image as a tar file, you can use the following command."
},
{
"code": null,
"e": 4467,
"s": 4419,
"text": "sudo docker save image−name > tar−file−name.tar"
},
{
"code": null,
"e": 4505,
"s": 4467,
"text": "To load the image back, you can use −"
},
{
"code": null,
"e": 4548,
"s": 4505,
"text": "sudo docker load −−input tar−file−name.tar"
},
{
"code": null,
"e": 4922,
"s": 4548,
"text": "To conclude, in this article, we have seen how to create an account in the docker’s official registry called dockerhub, create a repository there, push a customized docker image there and pull it back and run it. We have also seen an alternative and effective way if you want to backup and restore your images by saving it in a tar file and loading it back for further use."
},
{
"code": null,
"e": 5166,
"s": 4922,
"text": "Creating a backup for docker images is very necessary because in case of a mishap, you don’t want to lose all your work and re creating all the stuff of that image exactly without having access to your previous dockerfile is a very hefty task."
}
]
|
How to pass a date variable in sql query in a JSP? | The <sql:dateParam> tag is used as a nested action for the <sql:query> and the <sql:update> tag to supply a date and time value for a value placeholder. If a null value is provided, the value is set to SQL NULL for the placeholder.
The <sql:dateParam> tag has the following attributes −
To start with basic concept, let us create a simple table Students table in the TEST database and create a few records in that table as follows −
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>
Create the Employee table in the TEST database as follows −
mysql> use TEST;
mysql> create table Students (
id int not null,
first varchar (255),
last varchar (255),
dob date
);
Query OK, 0 rows affected (0.08 sec)
mysql>
We will now create a few records in the Employee table as follows −
mysql> INSERT INTO Students
VALUES (100, 'Zara', 'Ali', '2002/05/16');
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO Students
VALUES (101, 'Mahnaz', 'Fatma', '1978/11/28');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Students
VALUES (102, 'Zaid', 'Khan', '1980/10/10');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Students
VALUES (103, 'Sumit', 'Mittal', '1971/05/08');
Query OK, 1 row affected (0.00 sec)
mysql>
Let us now write a JSP which will make use of the <sql:update> tag along with <sql:param> tag and the <sql:dataParam> tag to execute an SQL UPDATE statement to update the date of birth for Zara −
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ page import = "java.util.Date,java.text.*" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<html>
<head>
<title>JSTL sql:dataParam Tag</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST" user = "root" password = "pass123"/>
<%
Date DoB = new Date("2001/12/16");
int studentId = 100;
%>
<sql:update dataSource = "${snapshot}" var = "count">
UPDATE Students SET dob = ? WHERE Id = ?
<sql:dateParam value = "<%=DoB%>" type = "DATE" />
<sql:param value = "<%=studentId%>" />
</sql:update>
<sql:query dataSource = "${snapshot}" var = "result">
SELECT * from Students;
</sql:query>
<table border = "1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>DoB</th>
</tr>
<c:forEach var = "row" items = "${result.rows}">
<tr>
<td> <c:out value = "${row.id}"/></td>
<td> <c:out value = "${row.first}"/></td>
<td> <c:out value = "${row.last}"/></td>
<td> <c:out value = "${row.dob}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
Access the above JSP, the following result will be displayed. The dob from 2002/05/16 to 2001/12/16 for the record with ID = 100 −
+-------------+----------------+-----------------+-----------------+
| Emp ID | First Name | Last Name | DoB |
+-------------+----------------+-----------------+-----------------+
| 100 | Zara | Ali | 2001-12-16 |
| 101 | Mahnaz | Fatma | 1978-11-28 |
| 102 | Zaid | Khan | 1980-10-10 |
| 103 | Sumit | Mittal | 1971-05-08 |
+-------------+----------------+-----------------+-----------------+ | [
{
"code": null,
"e": 1294,
"s": 1062,
"text": "The <sql:dateParam> tag is used as a nested action for the <sql:query> and the <sql:update> tag to supply a date and time value for a value placeholder. If a null value is provided, the value is set to SQL NULL for the placeholder."
},
{
"code": null,
"e": 1349,
"s": 1294,
"text": "The <sql:dateParam> tag has the following attributes −"
},
{
"code": null,
"e": 1495,
"s": 1349,
"text": "To start with basic concept, let us create a simple table Students table in the TEST database and create a few records in that table as follows −"
},
{
"code": null,
"e": 1571,
"s": 1495,
"text": "Open a Command Prompt and change to the installation directory as follows −"
},
{
"code": null,
"e": 1635,
"s": 1571,
"text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>"
},
{
"code": null,
"e": 1670,
"s": 1635,
"text": "Login to the database as follows −"
},
{
"code": null,
"e": 1746,
"s": 1670,
"text": "C:\\Program Files\\MySQL\\bin>mysql -u root -p\nEnter password: ********\nmysql>"
},
{
"code": null,
"e": 1806,
"s": 1746,
"text": "Create the Employee table in the TEST database as follows −"
},
{
"code": null,
"e": 2001,
"s": 1806,
"text": "mysql> use TEST;\n mysql> create table Students (\n id int not null,\n first varchar (255),\n last varchar (255),\n dob date\n );\n Query OK, 0 rows affected (0.08 sec)\nmysql>"
},
{
"code": null,
"e": 2069,
"s": 2001,
"text": "We will now create a few records in the Employee table as follows −"
},
{
"code": null,
"e": 2517,
"s": 2069,
"text": "mysql> INSERT INTO Students\nVALUES (100, 'Zara', 'Ali', '2002/05/16');\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> INSERT INTO Students\nVALUES (101, 'Mahnaz', 'Fatma', '1978/11/28');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Students\nVALUES (102, 'Zaid', 'Khan', '1980/10/10');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Students\nVALUES (103, 'Sumit', 'Mittal', '1971/05/08');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql>"
},
{
"code": null,
"e": 2713,
"s": 2517,
"text": "Let us now write a JSP which will make use of the <sql:update> tag along with <sql:param> tag and the <sql:dataParam> tag to execute an SQL UPDATE statement to update the date of birth for Zara −"
},
{
"code": null,
"e": 4222,
"s": 2713,
"text": "<%@ page import = \"java.io.*,java.util.*,java.sql.*\"%>\n<%@ page import = \"javax.servlet.http.*,javax.servlet.*\" %>\n<%@ page import = \"java.util.Date,java.text.*\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\"%>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/sql\" prefix = \"sql\"%>\n<html>\n <head>\n <title>JSTL sql:dataParam Tag</title>\n </head>\n <body>\n <sql:setDataSource var = \"snapshot\" driver = \"com.mysql.jdbc.Driver\"\n url = \"jdbc:mysql://localhost/TEST\" user = \"root\" password = \"pass123\"/>\n <%\n Date DoB = new Date(\"2001/12/16\");\n int studentId = 100;\n %>\n <sql:update dataSource = \"${snapshot}\" var = \"count\">\n UPDATE Students SET dob = ? WHERE Id = ?\n <sql:dateParam value = \"<%=DoB%>\" type = \"DATE\" />\n <sql:param value = \"<%=studentId%>\" />\n </sql:update>\n <sql:query dataSource = \"${snapshot}\" var = \"result\">\n SELECT * from Students;\n </sql:query>\n <table border = \"1\" width=\"100%\">\n <tr>\n <th>Emp ID</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>DoB</th>\n </tr>\n <c:forEach var = \"row\" items = \"${result.rows}\">\n <tr>\n <td> <c:out value = \"${row.id}\"/></td>\n <td> <c:out value = \"${row.first}\"/></td>\n <td> <c:out value = \"${row.last}\"/></td>\n <td> <c:out value = \"${row.dob}\"/></td>\n </tr>\n </c:forEach>\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 4353,
"s": 4222,
"text": "Access the above JSP, the following result will be displayed. The dob from 2002/05/16 to 2001/12/16 for the record with ID = 100 −"
},
{
"code": null,
"e": 4905,
"s": 4353,
"text": "+-------------+----------------+-----------------+-----------------+\n| Emp ID | First Name | Last Name | DoB |\n+-------------+----------------+-----------------+-----------------+\n| 100 | Zara | Ali | 2001-12-16 |\n| 101 | Mahnaz | Fatma | 1978-11-28 |\n| 102 | Zaid | Khan | 1980-10-10 |\n| 103 | Sumit | Mittal | 1971-05-08 |\n+-------------+----------------+-----------------+-----------------+"
}
]
|
fgetc() and fputc() in C | The function fgetc() is used to read the character from the file. It returns the character pointed by file pointer, if successful otherwise, returns EOF.
Here is the syntax of fgetc() in C language,
int fgetc(FILE *stream)
Here is an example of fgetc() in C language,
Let’s say we have “new.txt” file with the following content −
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
Now, let us see the example −
#include<stdio.h>
#include<conio.h>
void main() {
FILE *f;
char s;
clrscr();
f=fopen("new.txt","r");
while((s=fgetc(f))!=EOF) {
printf("%c",s);
}
fclose(f);
getch();
}
Here is the output,
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
In the above program, we have a text file “new.txt”. A file pointer is used to open and read the file. It is displaying the content of file.
FILE *f;
char s;
clrscr();
f=fopen("new.txt","r");
The function fputc() is used to write the character to the file. It writes the character to the file, if successful otherwise, returns EOF.
Here is the syntax of fputc() in C language,
int fputc(int character, FILE *stream)
Here,
char − The character is to be written to the file.
stream − This is the pointer to the file where character is to be written.
Here is an example of fputc() in C language,
Let’s say we have “new.txt” file with the following content −
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
Now, let us see the example −
#include <stdio.h>
void main() {
FILE *f;
f = fopen("new.txt", "w");
fputc('a',f);
fclose(f);
}
The program will modify the “new.txt” file. It will not display any output to the screen but it will modify the file directly. You can check the modified file. The following text is the modified text of the file −
A
In the above program, the file pointer f is used to open the file “new.txt” and fputc() is used to write the character to the file.
FILE *f;
f = fopen("new.txt", "w");
fputc('a',f); | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "The function fgetc() is used to read the character from the file. It returns the character pointed by file pointer, if successful otherwise, returns EOF."
},
{
"code": null,
"e": 1261,
"s": 1216,
"text": "Here is the syntax of fgetc() in C language,"
},
{
"code": null,
"e": 1285,
"s": 1261,
"text": "int fgetc(FILE *stream)"
},
{
"code": null,
"e": 1330,
"s": 1285,
"text": "Here is an example of fgetc() in C language,"
},
{
"code": null,
"e": 1392,
"s": 1330,
"text": "Let’s say we have “new.txt” file with the following content −"
},
{
"code": null,
"e": 1431,
"s": 1392,
"text": "0,hell!o\n1,hello!\n2,gfdtrhtrhrt\n3,demo"
},
{
"code": null,
"e": 1461,
"s": 1431,
"text": "Now, let us see the example −"
},
{
"code": null,
"e": 1659,
"s": 1461,
"text": "#include<stdio.h>\n#include<conio.h>\nvoid main() {\n FILE *f;\n char s;\n clrscr();\n f=fopen(\"new.txt\",\"r\");\n while((s=fgetc(f))!=EOF) {\n printf(\"%c\",s);\n }\n fclose(f);\n getch();\n}"
},
{
"code": null,
"e": 1679,
"s": 1659,
"text": "Here is the output,"
},
{
"code": null,
"e": 1718,
"s": 1679,
"text": "0,hell!o\n1,hello!\n2,gfdtrhtrhrt\n3,demo"
},
{
"code": null,
"e": 1859,
"s": 1718,
"text": "In the above program, we have a text file “new.txt”. A file pointer is used to open and read the file. It is displaying the content of file."
},
{
"code": null,
"e": 1910,
"s": 1859,
"text": "FILE *f;\nchar s;\nclrscr();\nf=fopen(\"new.txt\",\"r\");"
},
{
"code": null,
"e": 2050,
"s": 1910,
"text": "The function fputc() is used to write the character to the file. It writes the character to the file, if successful otherwise, returns EOF."
},
{
"code": null,
"e": 2095,
"s": 2050,
"text": "Here is the syntax of fputc() in C language,"
},
{
"code": null,
"e": 2134,
"s": 2095,
"text": "int fputc(int character, FILE *stream)"
},
{
"code": null,
"e": 2140,
"s": 2134,
"text": "Here,"
},
{
"code": null,
"e": 2191,
"s": 2140,
"text": "char − The character is to be written to the file."
},
{
"code": null,
"e": 2266,
"s": 2191,
"text": "stream − This is the pointer to the file where character is to be written."
},
{
"code": null,
"e": 2311,
"s": 2266,
"text": "Here is an example of fputc() in C language,"
},
{
"code": null,
"e": 2373,
"s": 2311,
"text": "Let’s say we have “new.txt” file with the following content −"
},
{
"code": null,
"e": 2412,
"s": 2373,
"text": "0,hell!o\n1,hello!\n2,gfdtrhtrhrt\n3,demo"
},
{
"code": null,
"e": 2442,
"s": 2412,
"text": "Now, let us see the example −"
},
{
"code": null,
"e": 2550,
"s": 2442,
"text": "#include <stdio.h>\nvoid main() {\n FILE *f;\n f = fopen(\"new.txt\", \"w\");\n fputc('a',f);\n fclose(f);\n}"
},
{
"code": null,
"e": 2764,
"s": 2550,
"text": "The program will modify the “new.txt” file. It will not display any output to the screen but it will modify the file directly. You can check the modified file. The following text is the modified text of the file −"
},
{
"code": null,
"e": 2766,
"s": 2764,
"text": "A"
},
{
"code": null,
"e": 2898,
"s": 2766,
"text": "In the above program, the file pointer f is used to open the file “new.txt” and fputc() is used to write the character to the file."
},
{
"code": null,
"e": 2948,
"s": 2898,
"text": "FILE *f;\nf = fopen(\"new.txt\", \"w\");\nfputc('a',f);"
}
]
|
C Quiz - 101 | Question 5 - GeeksforGeeks | 28 Jun, 2021
Consider the following variable declarations and definitions in C
i) int var_9 = 1;ii) int 9_var = 2;iii) int _ = 3;
Choose the correct statement w.r.t. above variables.(A) Both i) and iii) are valid.(B) Only i) is valid.(C) Both i) and ii) are valid.(D) All are valid.Answer: (A)Explanation: In C language, a variable name can consists of letters, digits and underscore i.e. _ . But a variable name has to start with either letter or underscore. It can’t start with a digit. So valid variables are var_9 and _ from the above question. Even two back to back underscore i.e. __ is also a valid variable name. Even _9 is a valid variable. But 9var and 9_ are invalid variables in C. This will be caught at the time of compilation itself. That’s why the correct answer is A).
Quiz of this Question
C Quiz - 101
C-C Quiz - 101
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Converting Strings to Numbers in C/C++
Core Dump (Segmentation fault) in C/C++
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
C | Pointer Basics | Question 14 | [
{
"code": null,
"e": 24540,
"s": 24512,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24606,
"s": 24540,
"text": "Consider the following variable declarations and definitions in C"
},
{
"code": "i) int var_9 = 1;ii) int 9_var = 2;iii) int _ = 3;",
"e": 24657,
"s": 24606,
"text": null
},
{
"code": null,
"e": 25313,
"s": 24657,
"text": "Choose the correct statement w.r.t. above variables.(A) Both i) and iii) are valid.(B) Only i) is valid.(C) Both i) and ii) are valid.(D) All are valid.Answer: (A)Explanation: In C language, a variable name can consists of letters, digits and underscore i.e. _ . But a variable name has to start with either letter or underscore. It can’t start with a digit. So valid variables are var_9 and _ from the above question. Even two back to back underscore i.e. __ is also a valid variable name. Even _9 is a valid variable. But 9var and 9_ are invalid variables in C. This will be caught at the time of compilation itself. That’s why the correct answer is A)."
},
{
"code": null,
"e": 25336,
"s": 25313,
"text": " Quiz of this Question"
},
{
"code": null,
"e": 25349,
"s": 25336,
"text": "C Quiz - 101"
},
{
"code": null,
"e": 25364,
"s": 25349,
"text": "C-C Quiz - 101"
},
{
"code": null,
"e": 25375,
"s": 25364,
"text": "C Language"
},
{
"code": null,
"e": 25382,
"s": 25375,
"text": "C Quiz"
},
{
"code": null,
"e": 25480,
"s": 25382,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25515,
"s": 25480,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25561,
"s": 25515,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25573,
"s": 25561,
"text": "fork() in C"
},
{
"code": null,
"e": 25612,
"s": 25573,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 25652,
"s": 25612,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 25695,
"s": 25652,
"text": "Operator Precedence and Associativity in C"
},
{
"code": null,
"e": 25726,
"s": 25695,
"text": "C | File Handling | Question 1"
},
{
"code": null,
"e": 25750,
"s": 25726,
"text": "C | Arrays | Question 7"
},
{
"code": null,
"e": 25772,
"s": 25750,
"text": "C | Misc | Question 7"
}
]
|
Image Captioning using Python - GeeksforGeeks | 17 Apr, 2019
Image captioning is a very classical and challenging problem coming to Deep Learning domain, in which we generate the textual description of image using its property, but we will not use Deep learning here. In this article, we will simply learn how can we simply caption the images using PIL.
Preprocessing on images is a great utility provided by Python PIL library. Not only we can change size, mode, orientation but we can draw on images, write text over it as well.
Install the required libraries:
urllib
requests
PIL
glob
shutil
Steps to follow first –
Download the font.ttf file (before running the code) using this link.
Make folder with name as “CaptionedImages” beforehand where the output captioned images will be stored.
Below is the stepwise implementation using Python:
Step #1:
# importing required librariesimport urllibimport requestsimport os # retrieving using image url urllib.request.urlretrieve("https://i.ibb.co/xY4DJJ5/img1.jpg", "img1.jpg")urllib.request.urlretrieve("https://i.ibb.co/Gnd1Y1L/img2.jpg", "img2.jpg")urllib.request.urlretrieve("https://i.ibb.co/Z6JgS1L/img3.jpg", "img3.jpg") print('Images downloaded') # get current working directory pathpath = os.getcwd() captionarr = [ "This is the first caption", "This is the second caption", "This is the third caption" ]
Step #2:
# importing necessary functions from PILfrom PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDraw # print(os.getcwd()) # checking the file mime types if# it is jpg, png or jpegdef ext(file): index = file.find(".jpg") current_file = "" current_file = file[index:] return current_file def ext2(file): index = file.find(".jpeg") current_file = "" current_file = file[index:] return current_file def ext3(file): index = file.find(".png") current_file = "" current_file = file[index:] return current_file # converting text from lowercase to uppercasedef convert(words): s = "" for word in words: s += word.upper() return s caption_first = convert(captionarr[0])caption_second = convert(captionarr[1])caption_third = convert(captionarr[2]) print(caption_first)print(caption_second)print(caption_third) count = 0 for f in os.listdir('.'): try: # Checking for file types if jpg, png # or jpeg excluding other files if (ext(f) == '.jpg' or ext2(f) == '.jpeg' or ext3(f) == '.png'): img = Image.open(f) width, height = img.size basewidth = 1200 # print(height) # Resizinng images to same width height wpercent = (basewidth / float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) img = img.resize((basewidth, hsize), Image.ANTIALIAS) new_width, new_height = img.size # print(new_height) # changing image mode if not in RGB if not img.mode == 'RGB': img = img.convert('RGB') draw = ImageDraw.Draw(img) # font = ImageFont.truetype(<font-file>, <font-size>) # initializing which font will be chosen by us font = ImageFont.truetype("Arial Bold.ttf", 35) # First Caption on First image if count == 0: draw.text((new_width / 15 + 25, new_height - 100), caption_first, (255, 0, 0), font = font, align ="center") # Second Caption on Second image elif count == 1: draw.text((new_width / 15 + 25, new_height - 100), caption_second, (255, 0, 0), font = font, align ="center") # Third Caption on Third image else: draw.text(( new_width / 15 + 25, new_height - 100), caption_third, (255, 0, 0), font = font, align ="center") img.save("CaptionedImges/{}".format(f)) print('done') count = count + 1 except OSError: pass
Step #3:Sorting the output files in accordance to last modified time so that they do not get placed in alphabetical or any other mismanaged order.
import osimport globimport shutil # changing directory to CaptionedImagesos.chdir(".\\CaptionedImges") fnames = []for file in os.listdir('.'): # appending files in directory to the frames arr fnames.append(file) # sorting the files in frames array # on the basis of last modified time# reverse = True means ascending order sortingfnames.sort(key = lambda x: os.stat(x).st_ctime, reverse = True)
Output:
Image-Processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 25848,
"s": 25555,
"text": "Image captioning is a very classical and challenging problem coming to Deep Learning domain, in which we generate the textual description of image using its property, but we will not use Deep learning here. In this article, we will simply learn how can we simply caption the images using PIL."
},
{
"code": null,
"e": 26025,
"s": 25848,
"text": "Preprocessing on images is a great utility provided by Python PIL library. Not only we can change size, mode, orientation but we can draw on images, write text over it as well."
},
{
"code": null,
"e": 26057,
"s": 26025,
"text": "Install the required libraries:"
},
{
"code": null,
"e": 26089,
"s": 26057,
"text": "urllib\nrequests\nPIL\nglob\nshutil"
},
{
"code": null,
"e": 26113,
"s": 26089,
"text": "Steps to follow first –"
},
{
"code": null,
"e": 26183,
"s": 26113,
"text": "Download the font.ttf file (before running the code) using this link."
},
{
"code": null,
"e": 26287,
"s": 26183,
"text": "Make folder with name as “CaptionedImages” beforehand where the output captioned images will be stored."
},
{
"code": null,
"e": 26338,
"s": 26287,
"text": "Below is the stepwise implementation using Python:"
},
{
"code": null,
"e": 26347,
"s": 26338,
"text": "Step #1:"
},
{
"code": "# importing required librariesimport urllibimport requestsimport os # retrieving using image url urllib.request.urlretrieve(\"https://i.ibb.co/xY4DJJ5/img1.jpg\", \"img1.jpg\")urllib.request.urlretrieve(\"https://i.ibb.co/Gnd1Y1L/img2.jpg\", \"img2.jpg\")urllib.request.urlretrieve(\"https://i.ibb.co/Z6JgS1L/img3.jpg\", \"img3.jpg\") print('Images downloaded') # get current working directory pathpath = os.getcwd() captionarr = [ \"This is the first caption\", \"This is the second caption\", \"This is the third caption\" ]",
"e": 26874,
"s": 26347,
"text": null
},
{
"code": null,
"e": 26884,
"s": 26874,
"text": " Step #2:"
},
{
"code": "# importing necessary functions from PILfrom PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDraw # print(os.getcwd()) # checking the file mime types if# it is jpg, png or jpegdef ext(file): index = file.find(\".jpg\") current_file = \"\" current_file = file[index:] return current_file def ext2(file): index = file.find(\".jpeg\") current_file = \"\" current_file = file[index:] return current_file def ext3(file): index = file.find(\".png\") current_file = \"\" current_file = file[index:] return current_file # converting text from lowercase to uppercasedef convert(words): s = \"\" for word in words: s += word.upper() return s caption_first = convert(captionarr[0])caption_second = convert(captionarr[1])caption_third = convert(captionarr[2]) print(caption_first)print(caption_second)print(caption_third) count = 0 for f in os.listdir('.'): try: # Checking for file types if jpg, png # or jpeg excluding other files if (ext(f) == '.jpg' or ext2(f) == '.jpeg' or ext3(f) == '.png'): img = Image.open(f) width, height = img.size basewidth = 1200 # print(height) # Resizinng images to same width height wpercent = (basewidth / float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) img = img.resize((basewidth, hsize), Image.ANTIALIAS) new_width, new_height = img.size # print(new_height) # changing image mode if not in RGB if not img.mode == 'RGB': img = img.convert('RGB') draw = ImageDraw.Draw(img) # font = ImageFont.truetype(<font-file>, <font-size>) # initializing which font will be chosen by us font = ImageFont.truetype(\"Arial Bold.ttf\", 35) # First Caption on First image if count == 0: draw.text((new_width / 15 + 25, new_height - 100), caption_first, (255, 0, 0), font = font, align =\"center\") # Second Caption on Second image elif count == 1: draw.text((new_width / 15 + 25, new_height - 100), caption_second, (255, 0, 0), font = font, align =\"center\") # Third Caption on Third image else: draw.text(( new_width / 15 + 25, new_height - 100), caption_third, (255, 0, 0), font = font, align =\"center\") img.save(\"CaptionedImges/{}\".format(f)) print('done') count = count + 1 except OSError: pass",
"e": 29757,
"s": 26884,
"text": null
},
{
"code": null,
"e": 29905,
"s": 29757,
"text": " Step #3:Sorting the output files in accordance to last modified time so that they do not get placed in alphabetical or any other mismanaged order."
},
{
"code": "import osimport globimport shutil # changing directory to CaptionedImagesos.chdir(\".\\\\CaptionedImges\") fnames = []for file in os.listdir('.'): # appending files in directory to the frames arr fnames.append(file) # sorting the files in frames array # on the basis of last modified time# reverse = True means ascending order sortingfnames.sort(key = lambda x: os.stat(x).st_ctime, reverse = True)",
"e": 30311,
"s": 29905,
"text": null
},
{
"code": null,
"e": 30319,
"s": 30311,
"text": "Output:"
},
{
"code": null,
"e": 30336,
"s": 30319,
"text": "Image-Processing"
},
{
"code": null,
"e": 30343,
"s": 30336,
"text": "Python"
},
{
"code": null,
"e": 30441,
"s": 30343,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30473,
"s": 30441,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30515,
"s": 30473,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30557,
"s": 30515,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30613,
"s": 30557,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30640,
"s": 30613,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30671,
"s": 30640,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30700,
"s": 30671,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30722,
"s": 30700,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30761,
"s": 30722,
"text": "Python | Get unique values from a list"
}
]
|
Python | Check if a list exists in given list of lists - GeeksforGeeks | 27 Mar, 2019
Given a list of lists, the task is to check if a list exists in given list of lists.
Input :
lst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]
list_search = [4, 5, 6]
Output: True
Input :
lst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]]
list_search = [4, 12, 54]
Output: False
Let’s discuss certain ways in which this task is performed.
Method #1: Using CounterThe most concise and readable way to find whether a list exists in list of lists is using Counter.
# Python code find whether a list # exists in list of list.import collections # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] # List to be searchedlist_search = [2, 3, 4] # Flag initializationflag = 0 # Using Counterfor elem in Input: if collections.Counter(elem) == collections.Counter(list_search) : flag = 1 # Check whether list exists or not. if flag == 0: print("False")else: print("True")
True
Method #2: Using in
# Python code find whether a list # exists in list of list. # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] # List to be searchedlist_search = [1, 1, 1, 2] # Using in to find whether # list exists or notif list_search in Input: print("True")else: print("False")
True
Method #3: Using any
# Python code find whether a list # exists in list of list. # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] # List to be searchedlist_search = [4, 5, 6] # Using any to find whether # list exists or notif any(list == list_search for list in Input): print("True")else: print("False")
True
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24511,
"s": 24483,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 24596,
"s": 24511,
"text": "Given a list of lists, the task is to check if a list exists in given list of lists."
},
{
"code": null,
"e": 24791,
"s": 24596,
"text": "Input :\nlst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]\nlist_search = [4, 5, 6]\n\nOutput: True\n\nInput :\nlst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]]\nlist_search = [4, 12, 54]\n\nOutput: False\n"
},
{
"code": null,
"e": 24851,
"s": 24791,
"text": "Let’s discuss certain ways in which this task is performed."
},
{
"code": null,
"e": 24974,
"s": 24851,
"text": "Method #1: Using CounterThe most concise and readable way to find whether a list exists in list of lists is using Counter."
},
{
"code": "# Python code find whether a list # exists in list of list.import collections # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] # List to be searchedlist_search = [2, 3, 4] # Flag initializationflag = 0 # Using Counterfor elem in Input: if collections.Counter(elem) == collections.Counter(list_search) : flag = 1 # Check whether list exists or not. if flag == 0: print(\"False\")else: print(\"True\")",
"e": 25433,
"s": 24974,
"text": null
},
{
"code": null,
"e": 25439,
"s": 25433,
"text": "True\n"
},
{
"code": null,
"e": 25460,
"s": 25439,
"text": " Method #2: Using in"
},
{
"code": "# Python code find whether a list # exists in list of list. # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] # List to be searchedlist_search = [1, 1, 1, 2] # Using in to find whether # list exists or notif list_search in Input: print(\"True\")else: print(\"False\")",
"e": 25766,
"s": 25460,
"text": null
},
{
"code": null,
"e": 25772,
"s": 25766,
"text": "True\n"
},
{
"code": null,
"e": 25794,
"s": 25772,
"text": " Method #3: Using any"
},
{
"code": "# Python code find whether a list # exists in list of list. # Input List InitializationInput = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] # List to be searchedlist_search = [4, 5, 6] # Using any to find whether # list exists or notif any(list == list_search for list in Input): print(\"True\")else: print(\"False\") ",
"e": 26125,
"s": 25794,
"text": null
},
{
"code": null,
"e": 26131,
"s": 26125,
"text": "True\n"
},
{
"code": null,
"e": 26152,
"s": 26131,
"text": "Python list-programs"
},
{
"code": null,
"e": 26159,
"s": 26152,
"text": "Python"
},
{
"code": null,
"e": 26175,
"s": 26159,
"text": "Python Programs"
},
{
"code": null,
"e": 26273,
"s": 26175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26282,
"s": 26273,
"text": "Comments"
},
{
"code": null,
"e": 26295,
"s": 26282,
"text": "Old Comments"
},
{
"code": null,
"e": 26313,
"s": 26295,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26348,
"s": 26313,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26370,
"s": 26348,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26402,
"s": 26370,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26432,
"s": 26402,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26475,
"s": 26432,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26497,
"s": 26475,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26536,
"s": 26497,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26582,
"s": 26536,
"text": "Python | Split string into list of characters"
}
]
|
Portable Computer Vision: TensorFlow 2.0 on a Raspberry Pi | by Leigh Johnson | Towards Data Science | For roughly $100 USD, you can add deep learning to an embedded system or your next internet-of-things project.
Are you just getting started with machine/deep learning, TensorFlow, or Raspberry Pi? Perfect, this blog series is for you!
In this series, I will show you how to:
Deploy a pre-trained image classification model (MobileNetV2) using TensorFlow 2.0 and Keras.Convert a model to TensorFlow Lite, a model format optimized for embedded and mobile devices.Accelerate inferences of any TensorFlow Lite model with Coral’s USB Edge TPU Accelerator and Edge TPU Compiler.Employ transfer learning to re-train MobileNetV2 with a custom image classifier.
Deploy a pre-trained image classification model (MobileNetV2) using TensorFlow 2.0 and Keras.
Convert a model to TensorFlow Lite, a model format optimized for embedded and mobile devices.
Accelerate inferences of any TensorFlow Lite model with Coral’s USB Edge TPU Accelerator and Edge TPU Compiler.
Employ transfer learning to re-train MobileNetV2 with a custom image classifier.
The first post in this series (you’re reading it now!) will walk you through build materials, installation, and deploying MobileNetV2 to your Raspberry Pi.
Raspberry Pi — a small, affordable computer popular with educators, hardware hobbyists, and roboticists. 🤖
TensorFlow — an open-source platform for machine learning.
TensorFlow Lite — a lightweight library for deploying TensorFlow models on mobile and embedded devices.
Convolutional Neural Network — a type of deep-learning model well-suited for image classification and object detection applications.
MobileNetV2 — a state-of-the-art image recognition model optimized for performance on modest mobile phone processors.
Edge TPU — a tensor processing unit (TPU) is an integrated circuit for accelerating computations performed by TensorFlow. The Edge TPU was developed with a small footprint, for mobile and embedded devices “at the edge”
If you’re just getting started with Raspberry Pi, I recommend the Pi Camera Pack ($90) by Arrow. It includes everything you need begin immediately:
5V 2.4A MicroUSB Power Supply
320x240 2.8" TFT Model PiTFT Resistive Touch-screen
Raspberry Pi 3 Model B
Raspberry Pi Camera v2
Plastic Case
8GB MicroSD Card with NOOBS installation manager pre-loaded
You can compile TensorFlow Lite models to run on Coral’s USB Accelerator (Link), for quicker model predictions.
Real-time applications benefit significantly from this speed-up. An example would be the decision-making module of an autonomous self-driving robot.
Some applications can tolerate a higher prediction speed and might not require TPU acceleration. For example, you would not need TPU acceleration to build a smart doggie door that unlocks for your pooch (but keeps raccoons out).
If you’re just getting started, skip buying this component.
Are you not sure if you need the USB Accelerator? The MobileNet benchmarks below might help you decide. The measurements below depict inference speed (in ms) — lower speeds are better!
If you already have a Raspberry Pi or some components laying around, the starter kit might include items you don’t need.
Here are the parts I used for my own builds (approximately $250 / unit).
Raspberry Pi Model 3 B+ ($35)
Raspberry Pi Camera v2 ($30)
Coral USB Edge TPU Accelerator — accelerates model inferencing ($75, link)
Pi Foundation Display — 7" Touchscreen Display ($80, link)
SmartiPi Touch Stand ($25, link)
Adjustable Pi Camera Mount ($5, link)
Flex cable for RPi Camera 24'’ ($3, link)
I would love to hear about your own build list! ❤️ Tweet me @grepLeigh or comment below.
If you purchased an SD card pre-loaded with NOOBS, I recommend walking through this overview first: Setting up your Raspberry Pi
Before proceeding, you’ll want to:
Connect your Pi to the internet (doc)
SSH into your Raspberry Pi (doc)
rpi-vision is a set of tools that makes it easier for you to:
Install a lot of dependencies on your Raspberry Pi (TensorFlow Lite, TFT touch screen drivers, tools for copying PiCamera frame buffer to a TFT touch screen).
Deploy models to a Raspberry Pi.
Train new models on your computer or Google Cloud’s AI Platform.
Compile 8-bit quantized models for an Edge TPU.
Clone the rpi-vision repo on your primary computer (not your Raspberry Pi)
Clone the rpi-vision repo on your primary computer (not your Raspberry Pi)
$ git clone [email protected]:leigh-johnson/rpi-vision.git && cd rpi-vision
2. On your primary computer, create a new virtual environment, then install the rpi-vision package.
$ pip install virtualenv; virtualenv -p $(which python3) .venv && source .venv/bin/activate && pip install -e .
3. Verify you can SSH into your Raspberry Pi before proceeding.
If you’re using the default Raspbian image, your Pi’s hostname will beraspberrypi.local
$ ssh [email protected]
rpi-vision uses Ansible to manage deployments and tasks on your Raspberry Pi. Ansible is a framework for automating the configuration of computers.
Create 2 configuration files required by Ansible:
If you’re using a custom hostname for your Pi, replace raspberrypi.local.
tee -a .env/my-inventory.ini <<EOF[rpi_vision]raspberrypi.local[rpi_vision:vars]ansible_connection=sshansible_user=piansible_python=/usr/bin/python3EOF
If you’re using a custom hostname for your Pi, replace raspberrypi.local.
tee -a .env/my-vars.ini <<EOF{ "RPI_HOSTNAME": "raspberrypi.local", "VERSION": "release-v1.0.0"}EOF
$ make rpi-install
You’ll see the output of an Ansible playbook. Ansible is a framework for automating the configuration of computers.
A quick summary of what’s being installed on your Pi:
rpi-vision repo
rpi-fbcp (a tool for copying framebuffer from PiCamera to TFT touch screen display)
TFT touch screen drivers and X11 configuration
You can inspect the tasks run on your Raspberry Pi by opening playbooks/bootstrap-rpi.yml
While the installation is running, read through the next section to learn how CNNS work and why they are useful for computer vision tasks.
CNNs are the key technology powering self-driving cars and image search engines. The technology is common for computer vision, but can also be applied to any problem with a hierarchical pattern in the data, where a complex pattern can be assembled from simpler patterns.
In the late 1950s and 1960s, David H. Hubel and Torton Wielson performed experiments on cats and monkeys to better understand the visual cortex.
They demonstrated neurons in the striate cortex respond to stimuli in a limited visual field, which they called a receptive field.
They noted concentric overlapping responses, where complex patterns were combinations of lower-level patterns.
Their findings also revealed specialization, where some neurons would only respond to a specific shape or pattern.
In the 1980s, inspired by Hubel and Wielson, Kunihiko Fukushima published on the neocognitron, a neural network capable of learning patterns with geometrical similarity.
The neocogitron has two key properties:
Learned patterns are hierarchal. Increasingly complex patterns are composed from simpler patterns.
Learned patterns are position-invariant and translation-invariant. After the network learns a pattern, it can recognize the pattern at different locations. After learning how to classify a dog, the network can accurately classify an upside-down dog without learning an entirely new pattern.
The neocogitron model is the inspiration for modern convolutional neural networks.
The input layer is fed into convolutional layers, which transform regions of the input using a filter.
The filter is also referred to as a kernel.
For each position in the input matrix, the convolution operation performs matrix multiplication on each element.
The resulting matrix is summed and stored in a feature map.
The operation is repeated for each position in the input matrix.
The input layer of a CNN is usually a 3D data structure with height, width, and channel (RGB or greyscale values).
The deeper we go in the feature map stack, the sparser each map layer becomes. That means the filters detect fewer features.
The first few layers of the feature map stack detect simple edges and shapes, and look similar to the input image. As we go deeper into a feature map stack, features become more abstract to the human eye. Deeper feature layers encode classification data, like “cat face” or “cat ear”.
Your dependency installation is probably done by now. To forge ahead, skip to Part 8 - Deploy Pre-trained Model MobileNetV2.
If you plan on training a custom classifier or want to read more about convolutional neural networks, start here:
Applied Deep Learning — Part 4: Convolutional Neural Networks
Hands on Machine Learning with Scikit-learn and TensorFlow, Chapter 13, Convolutional Neural Networks, by Aurélien Géron
Deep Learning with Python, Chapter 5 Deep Learning for Computer Vision, by Francois Chollet
SSH into your Raspberry Pi
SSH into your Raspberry Pi
$ ssh raspberrypi.local
2. Start a new tmux session
pi@raspberryi:~ $ tmux new-session -s mobilenetv2
3. Split the tmux session vertically by pressing control+b, then “
4. Start an fbcp process, which will copy framebuffer from the PiCamera to the TFT display via SPI interface. Leave this process running.
pi@raspberryi:~ $ fbcp
5. Switch tmux panes by pressing control+b, then o.
6. Activate the virtual environment installed in earlier, in Part 6.
pi@raspberryi:~ $ cd ~/rpi-vision && . .venv/bin/activate
7. Start a mobilenetv2 agent process. The agent will take roughly 60 seconds to initialize.
pi@raspberryi:~/rpi-vision $ python rpi_vision/agent/mobilenet_v2.py
You’ll see a summary of the model’s base, and then the agent will print inferences until stopped. Click for a gist of what you should see.
This demo uses weights for ImageNet classifiers, which you can look up at image-net.org.
Congratulations, you just deployed an image classification model to your Raspberry Pi! ✨
Looking for more hands-on examples of Machine Learning for Raspberry Pi and other small device? Sign up for my newsletter!
I publish examples of real-world ML applications (with full source code) and nifty tricks like automating away the pains of bounding-box annotation. | [
{
"code": null,
"e": 283,
"s": 172,
"text": "For roughly $100 USD, you can add deep learning to an embedded system or your next internet-of-things project."
},
{
"code": null,
"e": 407,
"s": 283,
"text": "Are you just getting started with machine/deep learning, TensorFlow, or Raspberry Pi? Perfect, this blog series is for you!"
},
{
"code": null,
"e": 447,
"s": 407,
"text": "In this series, I will show you how to:"
},
{
"code": null,
"e": 825,
"s": 447,
"text": "Deploy a pre-trained image classification model (MobileNetV2) using TensorFlow 2.0 and Keras.Convert a model to TensorFlow Lite, a model format optimized for embedded and mobile devices.Accelerate inferences of any TensorFlow Lite model with Coral’s USB Edge TPU Accelerator and Edge TPU Compiler.Employ transfer learning to re-train MobileNetV2 with a custom image classifier."
},
{
"code": null,
"e": 919,
"s": 825,
"text": "Deploy a pre-trained image classification model (MobileNetV2) using TensorFlow 2.0 and Keras."
},
{
"code": null,
"e": 1013,
"s": 919,
"text": "Convert a model to TensorFlow Lite, a model format optimized for embedded and mobile devices."
},
{
"code": null,
"e": 1125,
"s": 1013,
"text": "Accelerate inferences of any TensorFlow Lite model with Coral’s USB Edge TPU Accelerator and Edge TPU Compiler."
},
{
"code": null,
"e": 1206,
"s": 1125,
"text": "Employ transfer learning to re-train MobileNetV2 with a custom image classifier."
},
{
"code": null,
"e": 1362,
"s": 1206,
"text": "The first post in this series (you’re reading it now!) will walk you through build materials, installation, and deploying MobileNetV2 to your Raspberry Pi."
},
{
"code": null,
"e": 1469,
"s": 1362,
"text": "Raspberry Pi — a small, affordable computer popular with educators, hardware hobbyists, and roboticists. 🤖"
},
{
"code": null,
"e": 1528,
"s": 1469,
"text": "TensorFlow — an open-source platform for machine learning."
},
{
"code": null,
"e": 1632,
"s": 1528,
"text": "TensorFlow Lite — a lightweight library for deploying TensorFlow models on mobile and embedded devices."
},
{
"code": null,
"e": 1765,
"s": 1632,
"text": "Convolutional Neural Network — a type of deep-learning model well-suited for image classification and object detection applications."
},
{
"code": null,
"e": 1883,
"s": 1765,
"text": "MobileNetV2 — a state-of-the-art image recognition model optimized for performance on modest mobile phone processors."
},
{
"code": null,
"e": 2102,
"s": 1883,
"text": "Edge TPU — a tensor processing unit (TPU) is an integrated circuit for accelerating computations performed by TensorFlow. The Edge TPU was developed with a small footprint, for mobile and embedded devices “at the edge”"
},
{
"code": null,
"e": 2250,
"s": 2102,
"text": "If you’re just getting started with Raspberry Pi, I recommend the Pi Camera Pack ($90) by Arrow. It includes everything you need begin immediately:"
},
{
"code": null,
"e": 2280,
"s": 2250,
"text": "5V 2.4A MicroUSB Power Supply"
},
{
"code": null,
"e": 2332,
"s": 2280,
"text": "320x240 2.8\" TFT Model PiTFT Resistive Touch-screen"
},
{
"code": null,
"e": 2355,
"s": 2332,
"text": "Raspberry Pi 3 Model B"
},
{
"code": null,
"e": 2378,
"s": 2355,
"text": "Raspberry Pi Camera v2"
},
{
"code": null,
"e": 2391,
"s": 2378,
"text": "Plastic Case"
},
{
"code": null,
"e": 2451,
"s": 2391,
"text": "8GB MicroSD Card with NOOBS installation manager pre-loaded"
},
{
"code": null,
"e": 2563,
"s": 2451,
"text": "You can compile TensorFlow Lite models to run on Coral’s USB Accelerator (Link), for quicker model predictions."
},
{
"code": null,
"e": 2712,
"s": 2563,
"text": "Real-time applications benefit significantly from this speed-up. An example would be the decision-making module of an autonomous self-driving robot."
},
{
"code": null,
"e": 2941,
"s": 2712,
"text": "Some applications can tolerate a higher prediction speed and might not require TPU acceleration. For example, you would not need TPU acceleration to build a smart doggie door that unlocks for your pooch (but keeps raccoons out)."
},
{
"code": null,
"e": 3001,
"s": 2941,
"text": "If you’re just getting started, skip buying this component."
},
{
"code": null,
"e": 3186,
"s": 3001,
"text": "Are you not sure if you need the USB Accelerator? The MobileNet benchmarks below might help you decide. The measurements below depict inference speed (in ms) — lower speeds are better!"
},
{
"code": null,
"e": 3307,
"s": 3186,
"text": "If you already have a Raspberry Pi or some components laying around, the starter kit might include items you don’t need."
},
{
"code": null,
"e": 3380,
"s": 3307,
"text": "Here are the parts I used for my own builds (approximately $250 / unit)."
},
{
"code": null,
"e": 3410,
"s": 3380,
"text": "Raspberry Pi Model 3 B+ ($35)"
},
{
"code": null,
"e": 3439,
"s": 3410,
"text": "Raspberry Pi Camera v2 ($30)"
},
{
"code": null,
"e": 3514,
"s": 3439,
"text": "Coral USB Edge TPU Accelerator — accelerates model inferencing ($75, link)"
},
{
"code": null,
"e": 3573,
"s": 3514,
"text": "Pi Foundation Display — 7\" Touchscreen Display ($80, link)"
},
{
"code": null,
"e": 3606,
"s": 3573,
"text": "SmartiPi Touch Stand ($25, link)"
},
{
"code": null,
"e": 3644,
"s": 3606,
"text": "Adjustable Pi Camera Mount ($5, link)"
},
{
"code": null,
"e": 3686,
"s": 3644,
"text": "Flex cable for RPi Camera 24'’ ($3, link)"
},
{
"code": null,
"e": 3775,
"s": 3686,
"text": "I would love to hear about your own build list! ❤️ Tweet me @grepLeigh or comment below."
},
{
"code": null,
"e": 3904,
"s": 3775,
"text": "If you purchased an SD card pre-loaded with NOOBS, I recommend walking through this overview first: Setting up your Raspberry Pi"
},
{
"code": null,
"e": 3939,
"s": 3904,
"text": "Before proceeding, you’ll want to:"
},
{
"code": null,
"e": 3977,
"s": 3939,
"text": "Connect your Pi to the internet (doc)"
},
{
"code": null,
"e": 4010,
"s": 3977,
"text": "SSH into your Raspberry Pi (doc)"
},
{
"code": null,
"e": 4072,
"s": 4010,
"text": "rpi-vision is a set of tools that makes it easier for you to:"
},
{
"code": null,
"e": 4231,
"s": 4072,
"text": "Install a lot of dependencies on your Raspberry Pi (TensorFlow Lite, TFT touch screen drivers, tools for copying PiCamera frame buffer to a TFT touch screen)."
},
{
"code": null,
"e": 4264,
"s": 4231,
"text": "Deploy models to a Raspberry Pi."
},
{
"code": null,
"e": 4329,
"s": 4264,
"text": "Train new models on your computer or Google Cloud’s AI Platform."
},
{
"code": null,
"e": 4377,
"s": 4329,
"text": "Compile 8-bit quantized models for an Edge TPU."
},
{
"code": null,
"e": 4452,
"s": 4377,
"text": "Clone the rpi-vision repo on your primary computer (not your Raspberry Pi)"
},
{
"code": null,
"e": 4527,
"s": 4452,
"text": "Clone the rpi-vision repo on your primary computer (not your Raspberry Pi)"
},
{
"code": null,
"e": 4600,
"s": 4527,
"text": "$ git clone [email protected]:leigh-johnson/rpi-vision.git && cd rpi-vision"
},
{
"code": null,
"e": 4700,
"s": 4600,
"text": "2. On your primary computer, create a new virtual environment, then install the rpi-vision package."
},
{
"code": null,
"e": 4812,
"s": 4700,
"text": "$ pip install virtualenv; virtualenv -p $(which python3) .venv && source .venv/bin/activate && pip install -e ."
},
{
"code": null,
"e": 4876,
"s": 4812,
"text": "3. Verify you can SSH into your Raspberry Pi before proceeding."
},
{
"code": null,
"e": 4964,
"s": 4876,
"text": "If you’re using the default Raspbian image, your Pi’s hostname will beraspberrypi.local"
},
{
"code": null,
"e": 4989,
"s": 4964,
"text": "$ ssh [email protected]"
},
{
"code": null,
"e": 5137,
"s": 4989,
"text": "rpi-vision uses Ansible to manage deployments and tasks on your Raspberry Pi. Ansible is a framework for automating the configuration of computers."
},
{
"code": null,
"e": 5187,
"s": 5137,
"text": "Create 2 configuration files required by Ansible:"
},
{
"code": null,
"e": 5261,
"s": 5187,
"text": "If you’re using a custom hostname for your Pi, replace raspberrypi.local."
},
{
"code": null,
"e": 5413,
"s": 5261,
"text": "tee -a .env/my-inventory.ini <<EOF[rpi_vision]raspberrypi.local[rpi_vision:vars]ansible_connection=sshansible_user=piansible_python=/usr/bin/python3EOF"
},
{
"code": null,
"e": 5487,
"s": 5413,
"text": "If you’re using a custom hostname for your Pi, replace raspberrypi.local."
},
{
"code": null,
"e": 5590,
"s": 5487,
"text": "tee -a .env/my-vars.ini <<EOF{ \"RPI_HOSTNAME\": \"raspberrypi.local\", \"VERSION\": \"release-v1.0.0\"}EOF"
},
{
"code": null,
"e": 5609,
"s": 5590,
"text": "$ make rpi-install"
},
{
"code": null,
"e": 5725,
"s": 5609,
"text": "You’ll see the output of an Ansible playbook. Ansible is a framework for automating the configuration of computers."
},
{
"code": null,
"e": 5779,
"s": 5725,
"text": "A quick summary of what’s being installed on your Pi:"
},
{
"code": null,
"e": 5795,
"s": 5779,
"text": "rpi-vision repo"
},
{
"code": null,
"e": 5879,
"s": 5795,
"text": "rpi-fbcp (a tool for copying framebuffer from PiCamera to TFT touch screen display)"
},
{
"code": null,
"e": 5926,
"s": 5879,
"text": "TFT touch screen drivers and X11 configuration"
},
{
"code": null,
"e": 6016,
"s": 5926,
"text": "You can inspect the tasks run on your Raspberry Pi by opening playbooks/bootstrap-rpi.yml"
},
{
"code": null,
"e": 6155,
"s": 6016,
"text": "While the installation is running, read through the next section to learn how CNNS work and why they are useful for computer vision tasks."
},
{
"code": null,
"e": 6426,
"s": 6155,
"text": "CNNs are the key technology powering self-driving cars and image search engines. The technology is common for computer vision, but can also be applied to any problem with a hierarchical pattern in the data, where a complex pattern can be assembled from simpler patterns."
},
{
"code": null,
"e": 6571,
"s": 6426,
"text": "In the late 1950s and 1960s, David H. Hubel and Torton Wielson performed experiments on cats and monkeys to better understand the visual cortex."
},
{
"code": null,
"e": 6702,
"s": 6571,
"text": "They demonstrated neurons in the striate cortex respond to stimuli in a limited visual field, which they called a receptive field."
},
{
"code": null,
"e": 6813,
"s": 6702,
"text": "They noted concentric overlapping responses, where complex patterns were combinations of lower-level patterns."
},
{
"code": null,
"e": 6928,
"s": 6813,
"text": "Their findings also revealed specialization, where some neurons would only respond to a specific shape or pattern."
},
{
"code": null,
"e": 7098,
"s": 6928,
"text": "In the 1980s, inspired by Hubel and Wielson, Kunihiko Fukushima published on the neocognitron, a neural network capable of learning patterns with geometrical similarity."
},
{
"code": null,
"e": 7138,
"s": 7098,
"text": "The neocogitron has two key properties:"
},
{
"code": null,
"e": 7237,
"s": 7138,
"text": "Learned patterns are hierarchal. Increasingly complex patterns are composed from simpler patterns."
},
{
"code": null,
"e": 7528,
"s": 7237,
"text": "Learned patterns are position-invariant and translation-invariant. After the network learns a pattern, it can recognize the pattern at different locations. After learning how to classify a dog, the network can accurately classify an upside-down dog without learning an entirely new pattern."
},
{
"code": null,
"e": 7611,
"s": 7528,
"text": "The neocogitron model is the inspiration for modern convolutional neural networks."
},
{
"code": null,
"e": 7714,
"s": 7611,
"text": "The input layer is fed into convolutional layers, which transform regions of the input using a filter."
},
{
"code": null,
"e": 7758,
"s": 7714,
"text": "The filter is also referred to as a kernel."
},
{
"code": null,
"e": 7871,
"s": 7758,
"text": "For each position in the input matrix, the convolution operation performs matrix multiplication on each element."
},
{
"code": null,
"e": 7931,
"s": 7871,
"text": "The resulting matrix is summed and stored in a feature map."
},
{
"code": null,
"e": 7996,
"s": 7931,
"text": "The operation is repeated for each position in the input matrix."
},
{
"code": null,
"e": 8111,
"s": 7996,
"text": "The input layer of a CNN is usually a 3D data structure with height, width, and channel (RGB or greyscale values)."
},
{
"code": null,
"e": 8236,
"s": 8111,
"text": "The deeper we go in the feature map stack, the sparser each map layer becomes. That means the filters detect fewer features."
},
{
"code": null,
"e": 8521,
"s": 8236,
"text": "The first few layers of the feature map stack detect simple edges and shapes, and look similar to the input image. As we go deeper into a feature map stack, features become more abstract to the human eye. Deeper feature layers encode classification data, like “cat face” or “cat ear”."
},
{
"code": null,
"e": 8646,
"s": 8521,
"text": "Your dependency installation is probably done by now. To forge ahead, skip to Part 8 - Deploy Pre-trained Model MobileNetV2."
},
{
"code": null,
"e": 8760,
"s": 8646,
"text": "If you plan on training a custom classifier or want to read more about convolutional neural networks, start here:"
},
{
"code": null,
"e": 8822,
"s": 8760,
"text": "Applied Deep Learning — Part 4: Convolutional Neural Networks"
},
{
"code": null,
"e": 8945,
"s": 8822,
"text": "Hands on Machine Learning with Scikit-learn and TensorFlow, Chapter 13, Convolutional Neural Networks, by Aurélien Géron"
},
{
"code": null,
"e": 9037,
"s": 8945,
"text": "Deep Learning with Python, Chapter 5 Deep Learning for Computer Vision, by Francois Chollet"
},
{
"code": null,
"e": 9064,
"s": 9037,
"text": "SSH into your Raspberry Pi"
},
{
"code": null,
"e": 9091,
"s": 9064,
"text": "SSH into your Raspberry Pi"
},
{
"code": null,
"e": 9115,
"s": 9091,
"text": "$ ssh raspberrypi.local"
},
{
"code": null,
"e": 9143,
"s": 9115,
"text": "2. Start a new tmux session"
},
{
"code": null,
"e": 9193,
"s": 9143,
"text": "pi@raspberryi:~ $ tmux new-session -s mobilenetv2"
},
{
"code": null,
"e": 9260,
"s": 9193,
"text": "3. Split the tmux session vertically by pressing control+b, then “"
},
{
"code": null,
"e": 9398,
"s": 9260,
"text": "4. Start an fbcp process, which will copy framebuffer from the PiCamera to the TFT display via SPI interface. Leave this process running."
},
{
"code": null,
"e": 9421,
"s": 9398,
"text": "pi@raspberryi:~ $ fbcp"
},
{
"code": null,
"e": 9473,
"s": 9421,
"text": "5. Switch tmux panes by pressing control+b, then o."
},
{
"code": null,
"e": 9542,
"s": 9473,
"text": "6. Activate the virtual environment installed in earlier, in Part 6."
},
{
"code": null,
"e": 9600,
"s": 9542,
"text": "pi@raspberryi:~ $ cd ~/rpi-vision && . .venv/bin/activate"
},
{
"code": null,
"e": 9692,
"s": 9600,
"text": "7. Start a mobilenetv2 agent process. The agent will take roughly 60 seconds to initialize."
},
{
"code": null,
"e": 9761,
"s": 9692,
"text": "pi@raspberryi:~/rpi-vision $ python rpi_vision/agent/mobilenet_v2.py"
},
{
"code": null,
"e": 9900,
"s": 9761,
"text": "You’ll see a summary of the model’s base, and then the agent will print inferences until stopped. Click for a gist of what you should see."
},
{
"code": null,
"e": 9989,
"s": 9900,
"text": "This demo uses weights for ImageNet classifiers, which you can look up at image-net.org."
},
{
"code": null,
"e": 10078,
"s": 9989,
"text": "Congratulations, you just deployed an image classification model to your Raspberry Pi! ✨"
},
{
"code": null,
"e": 10201,
"s": 10078,
"text": "Looking for more hands-on examples of Machine Learning for Raspberry Pi and other small device? Sign up for my newsletter!"
}
]
|
Learning to be precise | Practice | GeeksforGeeks | There are times when your answer is a floating point that contains undesired amount of digits after decimal. Here, we'll learn how to get a precise answer out of a floating number. You are given two floating numbers a and b. You need to output a/b and decimal precision of a/b upto 3 places after the decimal point.
Note: You may use setprecision and fixed.
Example:
Input:
a = 5.43
b = 2.653
Output:
2.04674 2.047
Explanation:
Value of a/b is printed with and
without decimal precision.
User Task:
Your task is to complete the provided function.
Constraints:
1 <= a, b,<= 100
0
69406930ravi2 weeks ago
void precise(float a, float b)
{
float r=a/b;
cout<<r;
cout<<" "<<setprecision(3)<<fixed<<r;
cout<<endl;
}
0
manishv13 weeks ago
{ float c = a/b; double d = a/b; cout<< setprecision(6)<<c <<" " <<setprecision(4)<< d<<endl; cout<<endl;}
0
tshreyastshreyas4 weeks ago
void precise(float a, float b){ float c; c = a / b;//perform a/b cout << setprecision(5)<<fixed<< c <<" "<< setprecision(3) << fixed<< c <<endl; cout<<endl;}
0
shahabuddinbravo402 months ago
void precise(float a, float b){ cout<<setprecision(5)<<fixed<<a/b<<" "<<fixed<<setprecision(3)<<a/b<<endl; cout<<endl;}https://www.geeksforgeeks.org/precision-of-floating-point-numbers-in-c-floor-ceil-trunc-round-and-setprecision/
0
mdsaif04052 months ago
void precise(float a, float b)
{
cout<<a/b<<" "<<setprecision(3)<<fixed<<a/b<<endl;
cout<<endl;
}
-1
neerajjain071120023 months ago
void precise(float a, float b){ //perform a/b float num=a/b; cout<<fixed<<setprecision(5)<<num<<" "<<setprecision(3)<<num<<endl; // cout<</*output the result of a/b here*/<<" "<</*use setprecision(3) here*/<</*use fixed here*/<</*Output c here*/<<endl; cout<<endl;}
0
shivamsourav3 months ago
{ float c=a/b; cout<<c<<" "<<setprecision(4)<<c<<endl; cout<<endl;}
+1
bhabhilover26013 months ago
void precise(float a, float b)
{
float c=a/b;
cout<<a/b <<" "<< setprecision(3)<<fixed<<c<<endl;
}
0
gautambansal1283 months ago
float c=a/b; cout<<c<<" "<< setprecision(3) <<fixed<<c <<endl; cout<<endl;}
0
rushichoudhary994 months ago
why every code a giving wrong answer for multiple cases.
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": 594,
"s": 278,
"text": "There are times when your answer is a floating point that contains undesired amount of digits after decimal. Here, we'll learn how to get a precise answer out of a floating number. You are given two floating numbers a and b. You need to output a/b and decimal precision of a/b upto 3 places after the decimal point."
},
{
"code": null,
"e": 636,
"s": 594,
"text": "Note: You may use setprecision and fixed."
},
{
"code": null,
"e": 645,
"s": 636,
"text": "Example:"
},
{
"code": null,
"e": 767,
"s": 645,
"text": "Input:\na = 5.43\nb = 2.653\nOutput:\n2.04674 2.047\nExplanation:\nValue of a/b is printed with and \nwithout decimal precision."
},
{
"code": null,
"e": 830,
"s": 769,
"text": "User Task: \nYour task is to complete the provided function. "
},
{
"code": null,
"e": 860,
"s": 830,
"text": "Constraints:\n1 <= a, b,<= 100"
},
{
"code": null,
"e": 862,
"s": 860,
"text": "0"
},
{
"code": null,
"e": 886,
"s": 862,
"text": "69406930ravi2 weeks ago"
},
{
"code": null,
"e": 1015,
"s": 886,
"text": "void precise(float a, float b)\n{\n float r=a/b;\n \n cout<<r;\n cout<<\" \"<<setprecision(3)<<fixed<<r;\n \n cout<<endl;\n}\n"
},
{
"code": null,
"e": 1017,
"s": 1015,
"text": "0"
},
{
"code": null,
"e": 1037,
"s": 1017,
"text": "manishv13 weeks ago"
},
{
"code": null,
"e": 1155,
"s": 1037,
"text": "{ float c = a/b; double d = a/b; cout<< setprecision(6)<<c <<\" \" <<setprecision(4)<< d<<endl; cout<<endl;}"
},
{
"code": null,
"e": 1157,
"s": 1155,
"text": "0"
},
{
"code": null,
"e": 1185,
"s": 1157,
"text": "tshreyastshreyas4 weeks ago"
},
{
"code": null,
"e": 1357,
"s": 1185,
"text": "void precise(float a, float b){ float c; c = a / b;//perform a/b cout << setprecision(5)<<fixed<< c <<\" \"<< setprecision(3) << fixed<< c <<endl; cout<<endl;}"
},
{
"code": null,
"e": 1359,
"s": 1357,
"text": "0"
},
{
"code": null,
"e": 1390,
"s": 1359,
"text": "shahabuddinbravo402 months ago"
},
{
"code": null,
"e": 1624,
"s": 1390,
"text": "void precise(float a, float b){ cout<<setprecision(5)<<fixed<<a/b<<\" \"<<fixed<<setprecision(3)<<a/b<<endl; cout<<endl;}https://www.geeksforgeeks.org/precision-of-floating-point-numbers-in-c-floor-ceil-trunc-round-and-setprecision/"
},
{
"code": null,
"e": 1626,
"s": 1624,
"text": "0"
},
{
"code": null,
"e": 1649,
"s": 1626,
"text": "mdsaif04052 months ago"
},
{
"code": null,
"e": 1758,
"s": 1649,
"text": "void precise(float a, float b)\n{\n cout<<a/b<<\" \"<<setprecision(3)<<fixed<<a/b<<endl; \n cout<<endl;\n}"
},
{
"code": null,
"e": 1761,
"s": 1758,
"text": "-1"
},
{
"code": null,
"e": 1792,
"s": 1761,
"text": "neerajjain071120023 months ago"
},
{
"code": null,
"e": 2077,
"s": 1792,
"text": "void precise(float a, float b){ //perform a/b float num=a/b; cout<<fixed<<setprecision(5)<<num<<\" \"<<setprecision(3)<<num<<endl; // cout<</*output the result of a/b here*/<<\" \"<</*use setprecision(3) here*/<</*use fixed here*/<</*Output c here*/<<endl; cout<<endl;}"
},
{
"code": null,
"e": 2081,
"s": 2079,
"text": "0"
},
{
"code": null,
"e": 2106,
"s": 2081,
"text": "shivamsourav3 months ago"
},
{
"code": null,
"e": 2184,
"s": 2106,
"text": "{ float c=a/b; cout<<c<<\" \"<<setprecision(4)<<c<<endl; cout<<endl;}"
},
{
"code": null,
"e": 2187,
"s": 2184,
"text": "+1"
},
{
"code": null,
"e": 2215,
"s": 2187,
"text": "bhabhilover26013 months ago"
},
{
"code": null,
"e": 2336,
"s": 2215,
"text": "void precise(float a, float b)\n{\n float c=a/b;\n \n cout<<a/b <<\" \"<< setprecision(3)<<fixed<<c<<endl;\n \n \n}"
},
{
"code": null,
"e": 2338,
"s": 2336,
"text": "0"
},
{
"code": null,
"e": 2366,
"s": 2338,
"text": "gautambansal1283 months ago"
},
{
"code": null,
"e": 2452,
"s": 2366,
"text": "float c=a/b; cout<<c<<\" \"<< setprecision(3) <<fixed<<c <<endl; cout<<endl;}"
},
{
"code": null,
"e": 2454,
"s": 2452,
"text": "0"
},
{
"code": null,
"e": 2483,
"s": 2454,
"text": "rushichoudhary994 months ago"
},
{
"code": null,
"e": 2540,
"s": 2483,
"text": "why every code a giving wrong answer for multiple cases."
},
{
"code": null,
"e": 2686,
"s": 2540,
"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": 2722,
"s": 2686,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2732,
"s": 2722,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2742,
"s": 2732,
"text": "\nContest\n"
},
{
"code": null,
"e": 2805,
"s": 2742,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2953,
"s": 2805,
"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": 3161,
"s": 2953,
"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": 3267,
"s": 3161,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
How do I find the location of Python module sources? | For a pure python module you can find the location of the source files by looking at the module.__file__. For example,
>>> import mymodule
>>> mymodule.__file__
C:/Users/Ayush/mymodule.py
Many built in modules, however,are written in C, and therefore module.__file__ points to a .so file (there is no module.__file__ on Windows), and therefore, you can't see the source. You can manually go and check the PYTHONPATH variable contents to find the directories from where these built in modules are being imported.
Running "python -v"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built in modules. | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "For a pure python module you can find the location of the source files by looking at the module.__file__. For example,"
},
{
"code": null,
"e": 1252,
"s": 1181,
"text": " >>> import mymodule\n>>> mymodule.__file__\nC:/Users/Ayush/mymodule.py "
},
{
"code": null,
"e": 1578,
"s": 1252,
"text": " Many built in modules, however,are written in C, and therefore module.__file__ points to a .so file (there is no module.__file__ on Windows), and therefore, you can't see the source. You can manually go and check the PYTHONPATH variable contents to find the directories from where these built in modules are being imported. "
},
{
"code": null,
"e": 1738,
"s": 1578,
"text": " Running \"python -v\"from the command line tells you what is being imported and from where. This is useful if you want to know the location of built in modules."
}
]
|
How do we use a simple drop-down list of items in HTML forms? | With HTML, you can create a simple drop-down list of items to get user input in HTML forms. A select box also called drop-down box provides an option to list down various options in the form of drop-down list, from where a user can select one or more options. The <select> tag is used to create a drop-down list in HTML, with the <option> tag.
Here’s the list of attributes of <select> tag:
Here’s the list of attributes of <option> tag:
You can try to run the following to create a simple drop-down list of items to get user input in HTML forms:
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<p>Here's the list of subjects. Select any one:</p>
<form>
<select name = "dropdown">
<option value = "Computer Architecture" selected>Computer Architecture</option>
<option value = "Java">Java</option>
<option value = "Discrete Mathematics">Discrete Mathematics</option>
</select>
</form>
</body>
</html> | [
{
"code": null,
"e": 1406,
"s": 1062,
"text": "With HTML, you can create a simple drop-down list of items to get user input in HTML forms. A select box also called drop-down box provides an option to list down various options in the form of drop-down list, from where a user can select one or more options. The <select> tag is used to create a drop-down list in HTML, with the <option> tag."
},
{
"code": null,
"e": 1453,
"s": 1406,
"text": "Here’s the list of attributes of <select> tag:"
},
{
"code": null,
"e": 1500,
"s": 1453,
"text": "Here’s the list of attributes of <option> tag:"
},
{
"code": null,
"e": 1609,
"s": 1500,
"text": "You can try to run the following to create a simple drop-down list of items to get user input in HTML forms:"
},
{
"code": null,
"e": 1619,
"s": 1609,
"text": "Live Demo"
},
{
"code": null,
"e": 2094,
"s": 1619,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Select Box Control</title>\n </head>\n <body>\n <p>Here's the list of subjects. Select any one:</p>\n <form>\n <select name = \"dropdown\">\n <option value = \"Computer Architecture\" selected>Computer Architecture</option>\n <option value = \"Java\">Java</option>\n <option value = \"Discrete Mathematics\">Discrete Mathematics</option>\n </select>\n </form>\n </body>\n</html>"
}
]
|
Replace a letter with its alphabet position JavaScript | We are required to write a function that takes in a string, trims it off any whitespaces, converts it
to lowercase and returns an array of numbers describing corresponding characters positions in
the english alphabets, any whitespace or special character within the string should be ignored.
For example −
Input → ‘Hello world!’
Output → [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]
The code for this will be −
const str = 'Hello world!';
const mapString = (str) => {
const mappedArray = [];
str
.trim()
.toLowerCase()
.split("")
.forEach(char => {
const ascii = char.charCodeAt();
if(ascii >= 97 && ascii <= 122){
mappedArray.push(ascii - 96);
};
});
return mappedArray;
};
console.log(mapString(str));
The output in the console will be −
[
8, 5, 12, 12, 15,
23, 15, 18, 12, 4
] | [
{
"code": null,
"e": 1354,
"s": 1062,
"text": "We are required to write a function that takes in a string, trims it off any whitespaces, converts it\nto lowercase and returns an array of numbers describing corresponding characters positions in\nthe english alphabets, any whitespace or special character within the string should be ignored."
},
{
"code": null,
"e": 1368,
"s": 1354,
"text": "For example −"
},
{
"code": null,
"e": 1438,
"s": 1368,
"text": "Input → ‘Hello world!’\nOutput → [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]"
},
{
"code": null,
"e": 1466,
"s": 1438,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1810,
"s": 1466,
"text": "const str = 'Hello world!';\nconst mapString = (str) => {\n const mappedArray = [];\n str\n .trim()\n .toLowerCase()\n .split(\"\")\n .forEach(char => {\n const ascii = char.charCodeAt();\n if(ascii >= 97 && ascii <= 122){\n mappedArray.push(ascii - 96);\n };\n });\n return mappedArray;\n};\nconsole.log(mapString(str));"
},
{
"code": null,
"e": 1846,
"s": 1810,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 1892,
"s": 1846,
"text": "[\n 8, 5, 12, 12, 15,\n 23, 15, 18, 12, 4\n]"
}
]
|
Which MySQL datatype to used to store an IP address? | We can store an IP address with the help of INT unsigned. While using INSERT, include INET_ATON() and with SELECT, include INET_NTOA(). IP address is in dotted format.
Let us see an example.
Creating a table.
mysql> create table IPV4AddressDemo
-> (
-> `IPV4Address` INT UNSIGNED
-> );
Query OK, 0 rows affected (0.52 sec)
Inserting IP address into the table, with INET_ATON.
mysql> insert into IPV4AddressDemo values(INET_ATON("120.0.0.1"));
Query OK, 1 row affected (0.17 sec)
To display all records.
mysql> select *from IPV4AddressDemo;
The following is the output, but definitely we want it to be in IP address format.
+-------------+
| IPV4Address |
+-------------+
| 2013265921 |
+-------------+
1 row in set (0.00 sec)
As the above output is giving a sequence of integers, but we can convert them into the original IP address format. For that, use INET_NTOA
mysql> SELECT INET_NTOA(`IPV4Address`) FROM IPV4AddressDemo;
The following is the output that shows IP address in the actual format.
+--------------------------+
| INET_NTOA(`IPV4Address`) |
+--------------------------+
| 120.0.0.1 |
+--------------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1230,
"s": 1062,
"text": "We can store an IP address with the help of INT unsigned. While using INSERT, include INET_ATON() and with SELECT, include INET_NTOA(). IP address is in dotted format."
},
{
"code": null,
"e": 1253,
"s": 1230,
"text": "Let us see an example."
},
{
"code": null,
"e": 1271,
"s": 1253,
"text": "Creating a table."
},
{
"code": null,
"e": 1394,
"s": 1271,
"text": "mysql> create table IPV4AddressDemo\n -> (\n -> `IPV4Address` INT UNSIGNED\n -> );\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1447,
"s": 1394,
"text": "Inserting IP address into the table, with INET_ATON."
},
{
"code": null,
"e": 1550,
"s": 1447,
"text": "mysql> insert into IPV4AddressDemo values(INET_ATON(\"120.0.0.1\"));\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1574,
"s": 1550,
"text": "To display all records."
},
{
"code": null,
"e": 1611,
"s": 1574,
"text": "mysql> select *from IPV4AddressDemo;"
},
{
"code": null,
"e": 1694,
"s": 1611,
"text": "The following is the output, but definitely we want it to be in IP address format."
},
{
"code": null,
"e": 1799,
"s": 1694,
"text": "+-------------+\n| IPV4Address |\n+-------------+\n| 2013265921 |\n+-------------+\n1 row in set (0.00 sec)\n"
},
{
"code": null,
"e": 1938,
"s": 1799,
"text": "As the above output is giving a sequence of integers, but we can convert them into the original IP address format. For that, use INET_NTOA"
},
{
"code": null,
"e": 1999,
"s": 1938,
"text": "mysql> SELECT INET_NTOA(`IPV4Address`) FROM IPV4AddressDemo;"
},
{
"code": null,
"e": 2071,
"s": 1999,
"text": "The following is the output that shows IP address in the actual format."
},
{
"code": null,
"e": 2241,
"s": 2071,
"text": "+--------------------------+\n| INET_NTOA(`IPV4Address`) |\n+--------------------------+\n| 120.0.0.1 |\n+--------------------------+\n1 row in set (0.00 sec)\n"
}
]
|
Building Convolutional Neural Network using NumPy from Scratch | by Ahmed Gad | Towards Data Science | Using already existing models in ML/DL libraries might be helpful in some cases. But to have better control and understanding, you should try to implement them yourself. This article shows how a CNN is implemented just using NumPy.
Convolutional neural network (CNN) is the state-of-art technique for analyzing multidimensional signals such as images. There are different libraries that already implements CNN such as TensorFlow and Keras. Such libraries isolates the developer from some details and just give an abstract API to make life easier and avoid complexity in the implementation. But in practice, such details might make a difference. Sometimes, the data scientist have to go through such details to enhance the performance. The solution in such situation is to build every piece of such model your own. This gives the highest possible level of control over the network. Also, it is recommended to implement such models to have better understanding over them.
In this article, CNN is created using only NumPy library. Just three layers are created which are convolution (conv for short), ReLU, and max pooling. The major steps involved are as follows:
1. Reading the input image.
2. Preparing filters.
3. Conv layer: Convolving each filter with the input image.
4. ReLU layer: Applying ReLU activation function on the feature maps (output of conv layer).
5. Max Pooling layer: Applying the pooling operation on the output of ReLU layer.
6. Stacking conv, ReLU, and max pooling layers.
The following code reads an already existing image from the skimage Python library and converts it into gray.
import skimage.data# Reading the imageimg = skimage.data.chelsea()# Converting the image into gray.img = skimage.color.rgb2gray(img)
Reading image is the first step because next steps depend on the input size. The image after being converted into gray is shown below.
The following code prepares the filters bank for the first conv layer (l1 for short):
l1_filter = numpy.zeros((2,3,3))
A zero array is created according to the number of filters and the size of each filter. 2 filters of size 3x3 are created that is why the zero array is of size (2=num_filters, 3=num_rows_filter, 3=num_columns_filter). Size of the filter is selected to be 2D array without depth because the input image is gray and has no depth (i.e. 2D ). If the image is RGB with 3 channels, the filter size must be (3, 3, 3=depth).
The size of the filters bank is specified by the above zero array but not the actual values of the filters. It is possible to override such values as follows to detect vertical and horizontal edges.
l1_filter[0, :, :] = numpy.array([[[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]])l1_filter[1, :, :] = numpy.array([[[1, 1, 1], [0, 0, 0], [-1, -1, -1]]])
After preparing the filters, next is to convolve the input image by them. The next line convolves the image with the filters bank using a function called conv:
l1_feature_map = conv(img, l1_filter)
Such function accepts just two arguments which are the image and the filter bank which is implemented as below.
def conv(img, conv_filter): if len(img.shape) > 2 or len(conv_filter.shape) > 3: # Check if number of image channels matches the filter depth. if img.shape[-1] != conv_filter.shape[-1]: print("Error: Number of channels in both image and filter must match.") sys.exit() if conv_filter.shape[1] != conv_filter.shape[2]: # Check if filter dimensions are equal. print('Error: Filter must be a square matrix. I.e. number of rows and columns must match.') sys.exit() if conv_filter.shape[1]%2==0: # Check if filter diemnsions are odd. print('Error: Filter must have an odd size. I.e. number of rows and columns must be odd.') sys.exit() # An empty feature map to hold the output of convolving the filter(s) with the image. feature_maps = numpy.zeros((img.shape[0]-conv_filter.shape[1]+1, img.shape[1]-conv_filter.shape[1]+1, conv_filter.shape[0])) # Convolving the image by the filter(s). for filter_num in range(conv_filter.shape[0]): print("Filter ", filter_num + 1) curr_filter = conv_filter[filter_num, :] # getting a filter from the bank. """ Checking if there are mutliple channels for the single filter. If so, then each channel will convolve the image. The result of all convolutions are summed to return a single feature map. """ if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) # Array holding the sum of all feature maps. for ch_num in range(1, curr_filter.shape[-1]): # Convolving each channel with the image and summing the results. conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: # There is just a single channel in the filter. conv_map = conv_(img, curr_filter) feature_maps[:, :, filter_num] = conv_map # Holding feature map with the current filter. return feature_maps # Returning all feature maps.
The function starts by ensuring that the depth of each filter is equal to the number of image channels. In the code below, the outer if checks if the channel and the filter have a depth. If a depth already exists, then the inner if checks their inequality. If there is no match, then the script will exit.
if len(img.shape) > 2 or len(conv_filter.shape) > 3: # Check if number of image channels matches the filter depth. if img.shape[-1] != conv_filter.shape[-1]: print("Error: Number of channels in both image and filter must match.") sys.exit()
Moreover, the size of the filter should be odd and filter dimensions are equal (i.e. number of rows and columns are odd and equal). This is checked according to the following two if blocks. If such conditions don’t met, the script will exit.
if conv_filter.shape[1] != conv_filter.shape[2]: # Check if filter dimensions are equal. print('Error: Filter must be a square matrix. I.e. number of rows and columns must match.') sys.exit() if conv_filter.shape[1]%2==0: # Check if filter diemnsions are odd. print('Error: Filter must have an odd size. I.e. number of rows and columns must be odd.') sys.exit()
Not satisfying any of the conditions above is a proof that the filter depth is suitable with the image and convolution is ready to be applied. Convolving the image by the filter starts by initializing an array to hold the outputs of convolution (i.e. feature maps) by specifying its size according to the following code:
# An empty feature map to hold the output of convolving the filter(s) with the image. feature_maps = numpy.zeros((img.shape[0]-conv_filter.shape[1]+1, img.shape[1]-conv_filter.shape[1]+1, conv_filter.shape[0]))
Because there is no stride nor padding, the feature map size will be equal to (img_rows-filter_rows+1, image_columns-filter_columns+1, num_filters) as above in the code. Note that there is an output feature map for every filter in the bank. That is why the number of filters in the filter bank (conv_filter.shape[0]) is used to specify the size as a third argument.
After preparing the inputs and outputs of the convolution operation, next is to apply it according to the following code:
# Convolving the image by the filter(s). for filter_num in range(conv_filter.shape[0]): print("Filter ", filter_num + 1) curr_filter = conv_filter[filter_num, :] # getting a filter from the bank. """ Checking if there are mutliple channels for the single filter. If so, then each channel will convolve the image. The result of all convolutions are summed to return a single feature map. """ if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) # Array holding the sum of all feature maps. for ch_num in range(1, curr_filter.shape[-1]): # Convolving each channel with the image and summing the results. conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: # There is just a single channel in the filter. conv_map = conv_(img, curr_filter) feature_maps[:, :, filter_num] = conv_map # Holding feature map with the current filter. return feature_maps # Returning all feature maps.
The outer loop iterates over each filter in the filter bank and returns it for further steps according to this line:
curr_filter = conv_filter[filter_num, :] # getting a filter from the bank.
If the image to be convolved has more than one channel, then the filter must has a depth equal to such number of channels. Convolution in this case is done by convolving each image channel with its corresponding channel in the filter. Finally, the sum of the results will be the output feature map. If the image has just a single channel, then convolution will be straight forward. Determining such behavior is done in such if-else block:
if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) # Array holding the sum of all feature maps. for ch_num in range(1, curr_filter.shape[-1]): # Convolving each channel with the image and summing the results. conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: # There is just a single channel in the filter. conv_map = conv_(img, curr_filter)
You might notice that the convolution is applied by a function called conv_ which is different from the conv function. The function conv just accepts the input image and the filter bank but doesn’t apply convolution its own. It just passes each set of input-filter pairs to be convolved to the conv_ function. This is just for making the code simpler to investigate. Here is the implementation of the conv_ function:
def conv_(img, conv_filter): filter_size = conv_filter.shape[1] result = numpy.zeros((img.shape)) #Looping through the image to apply the convolution operation. for r in numpy.uint16(numpy.arange(filter_size/2.0, img.shape[0]-filter_size/2.0+1)): for c in numpy.uint16(numpy.arange(filter_size/2.0, img.shape[1]-filter_size/2.0+1)): """ Getting the current region to get multiplied with the filter. How to loop through the image and get the region based on the image and filer sizes is the most tricky part of convolution. """ curr_region = img[r-numpy.uint16(numpy.floor(filter_size/2.0)):r+numpy.uint16(numpy.ceil(filter_size/2.0)), c-numpy.uint16(numpy.floor(filter_size/2.0)):c+numpy.uint16(numpy.ceil(filter_size/2.0))] #Element-wise multipliplication between the current region and the filter. curr_result = curr_region * conv_filter conv_sum = numpy.sum(curr_result) #Summing the result of multiplication. result[r, c] = conv_sum #Saving the summation in the convolution layer feature map. #Clipping the outliers of the result matrix. final_result = result[numpy.uint16(filter_size/2.0):result.shape[0]-numpy.uint16(filter_size/2.0), numpy.uint16(filter_size/2.0):result.shape[1]-numpy.uint16(filter_size/2.0)] return final_result
It iterates over the image and extracts regions of equal size to the filter according to this line:
curr_region = img[r-numpy.uint16(numpy.floor(filter_size/2.0)):r+numpy.uint16(numpy.ceil(filter_size/2.0)), c-numpy.uint16(numpy.floor(filter_size/2.0)):c+numpy.uint16(numpy.ceil(filter_size/2.0))]
Then it apply element-wise multiplication between the region and the filter and summing them to get a single value as the output according to these lines:
#Element-wise multipliplication between the current region and the filter. curr_result = curr_region * conv_filter conv_sum = numpy.sum(curr_result) #Summing the result of multiplication. result[r, c] = conv_sum #Saving the summation in the convolution layer feature map.
After convolving each filter by the input, the feature maps are returned by the conv function. Figure 2 shows the feature maps returned by such conv layer.
The output of such layer will be applied to the ReLU layer.
The ReLU layer applies the ReLU activation function over each feature map returned by the conv layer. It is called using the relu function according to the following line of code:
l1_feature_map_relu = relu(l1_feature_map)
The relu function is implemented as follows:
def relu(feature_map): #Preparing the output of the ReLU activation function. relu_out = numpy.zeros(feature_map.shape) for map_num in range(feature_map.shape[-1]): for r in numpy.arange(0,feature_map.shape[0]): for c in numpy.arange(0, feature_map.shape[1]): relu_out[r, c, map_num] = numpy.max([feature_map[r, c, map_num], 0]) return relu_out
It is very simple. Just loop though each element in the feature map and return the original value in the feature map if it is larger than 0. Otherwise, return 0. The outputs of the ReLU layer are shown in figure 3.
The output of the ReLU layer is applied to the max pooling layer.
The max pooling layer accepts the output of the ReLU layer and applies the max pooling operation according to the following line:
l1_feature_map_relu_pool = pooling(l1_feature_map_relu, 2, 2)
It is implemented using the pooling function as follows:
def pooling(feature_map, size=2, stride=2): #Preparing the output of the pooling operation. pool_out = numpy.zeros((numpy.uint16((feature_map.shape[0]-size+1)/stride), numpy.uint16((feature_map.shape[1]-size+1)/stride), feature_map.shape[-1])) for map_num in range(feature_map.shape[-1]): r2 = 0 for r in numpy.arange(0,feature_map.shape[0]-size-1, stride): c2 = 0 for c in numpy.arange(0, feature_map.shape[1]-size-1, stride): pool_out[r2, c2, map_num] = numpy.max([feature_map[r:r+size, c:c+size, map_num]]) c2 = c2 + 1 r2 = r2 +1 return pool_out
The function accepts three inputs which are the output of the ReLU layer, pooling mask size, and stride. It simply creates an empty array, as previous, that holds the output of such layer. The size of such array is specified according to the size and stride arguments as in such line:
pool_out = numpy.zeros((numpy.uint16((feature_map.shape[0]-size+1)/stride), numpy.uint16((feature_map.shape[1]-size+1)/stride), feature_map.shape[-1]))
Then it loops through the input, channel by channel according to the outer loop that uses the looping variable map_num. For each channel in the input, max pooling operation is applied. According to the stride and size used, the region is clipped and the max of it is returned in the output array according to this line:
pool_out[r2, c2, map_num] = numpy.max([feature_map[r:r+size, c:c+size, map_num]])
The outputs of such pooling layer are shown in the next figure. Note that the size of the pooling layer output is smaller than its input even if they seem identical in their graphs.
Up to this point, the CNN architecture with conv, ReLU, and max pooling layers is complete. There might be some other layers to be stacked in addition to the previous ones as below.
# Second conv layerl2_filter = numpy.random.rand(3, 5, 5, l1_feature_map_relu_pool.shape[-1])print("\n**Working with conv layer 2**")l2_feature_map = conv(l1_feature_map_relu_pool, l2_filter)print("\n**ReLU**")l2_feature_map_relu = relu(l2_feature_map)print("\n**Pooling**")l2_feature_map_relu_pool = pooling(l2_feature_map_relu, 2, 2)print("**End of conv layer 2**\n")
The previous conv layer uses 3 filters with their values generated randomly. That is why there will be 3 feature maps resulted from such conv layer. This is also the same for the successive ReLU and pooling layers. Outputs of such layers are shown in figure 5.
# Third conv layerl3_filter = numpy.random.rand(1, 7, 7, l2_feature_map_relu_pool.shape[-1])print("\n**Working with conv layer 3**")l3_feature_map = numpycnn.conv(l2_feature_map_relu_pool, l3_filter)print("\n**ReLU**")l3_feature_map_relu = numpycnn.relu(l3_feature_map)print("\n**Pooling**")l3_feature_map_relu_pool = numpycnn.pooling(l3_feature_map_relu, 2, 2)print("**End of conv layer 3**\n")
Figure 6 shows the outputs of the previous layers. The previous conv layer accepts just a single filter. That is why there is only one feature map as output.
But remember, the output of each previous layer is the input to the next layer. For example, such lines accepts the previous outputs as their inputs.
l2_feature_map = conv(l1_feature_map_relu_pool, l2_filter)l3_feature_map = conv(l2_feature_map_relu_pool, l3_filter)
The complete code is available in github (https://github.com/ahmedfgad/NumPyCNN). The code contains the visualization of the outputs from each layer using the Matplotlib library.
import skimage.dataimport numpyimport matplotlibimport sysdef conv_(img, conv_filter): filter_size = conv_filter.shape[1] result = numpy.zeros((img.shape)) #Looping through the image to apply the convolution operation. for r in numpy.uint16(numpy.arange(filter_size/2.0, img.shape[0]-filter_size/2.0+1)): for c in numpy.uint16(numpy.arange(filter_size/2.0, img.shape[1]-filter_size/2.0+1)): """ Getting the current region to get multiplied with the filter. How to loop through the image and get the region based on the image and filer sizes is the most tricky part of convolution. """ curr_region = img[r-numpy.uint16(numpy.floor(filter_size/2.0)):r+numpy.uint16(numpy.ceil(filter_size/2.0)), c-numpy.uint16(numpy.floor(filter_size/2.0)):c+numpy.uint16(numpy.ceil(filter_size/2.0))] #Element-wise multipliplication between the current region and the filter. curr_result = curr_region * conv_filter conv_sum = numpy.sum(curr_result) #Summing the result of multiplication. result[r, c] = conv_sum #Saving the summation in the convolution layer feature map. #Clipping the outliers of the result matrix. final_result = result[numpy.uint16(filter_size/2.0):result.shape[0]-numpy.uint16(filter_size/2.0), numpy.uint16(filter_size/2.0):result.shape[1]-numpy.uint16(filter_size/2.0)] return final_resultdef conv(img, conv_filter): if len(img.shape) > 2 or len(conv_filter.shape) > 3: # Check if number of image channels matches the filter depth. if img.shape[-1] != conv_filter.shape[-1]: print("Error: Number of channels in both image and filter must match.") sys.exit() if conv_filter.shape[1] != conv_filter.shape[2]: # Check if filter dimensions are equal. print('Error: Filter must be a square matrix. I.e. number of rows and columns must match.') sys.exit() if conv_filter.shape[1]%2==0: # Check if filter diemnsions are odd. print('Error: Filter must have an odd size. I.e. number of rows and columns must be odd.') sys.exit()# An empty feature map to hold the output of convolving the filter(s) with the image. feature_maps = numpy.zeros((img.shape[0]-conv_filter.shape[1]+1, img.shape[1]-conv_filter.shape[1]+1, conv_filter.shape[0]))# Convolving the image by the filter(s). for filter_num in range(conv_filter.shape[0]): print("Filter ", filter_num + 1) curr_filter = conv_filter[filter_num, :] # getting a filter from the bank. """ Checking if there are mutliple channels for the single filter. If so, then each channel will convolve the image. The result of all convolutions are summed to return a single feature map. """ if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) # Array holding the sum of all feature maps. for ch_num in range(1, curr_filter.shape[-1]): # Convolving each channel with the image and summing the results. conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: # There is just a single channel in the filter. conv_map = conv_(img, curr_filter) feature_maps[:, :, filter_num] = conv_map # Holding feature map with the current filter. return feature_maps # Returning all feature maps.def pooling(feature_map, size=2, stride=2): #Preparing the output of the pooling operation. pool_out = numpy.zeros((numpy.uint16((feature_map.shape[0]-size+1)/stride), numpy.uint16((feature_map.shape[1]-size+1)/stride), feature_map.shape[-1])) for map_num in range(feature_map.shape[-1]): r2 = 0 for r in numpy.arange(0,feature_map.shape[0]-size-1, stride): c2 = 0 for c in numpy.arange(0, feature_map.shape[1]-size-1, stride): pool_out[r2, c2, map_num] = numpy.max([feature_map[r:r+size, c:c+size, map_num]]) c2 = c2 + 1 r2 = r2 +1 return pool_outdef relu(feature_map): #Preparing the output of the ReLU activation function. relu_out = numpy.zeros(feature_map.shape) for map_num in range(feature_map.shape[-1]): for r in numpy.arange(0,feature_map.shape[0]): for c in numpy.arange(0, feature_map.shape[1]): relu_out[r, c, map_num] = numpy.max([feature_map[r, c, map_num], 0]) return relu_out# Reading the image#img = skimage.io.imread("fruits2.png")img = skimage.data.chelsea()# Converting the image into gray.img = skimage.color.rgb2gray(img)# First conv layer#l1_filter = numpy.random.rand(2,7,7)*20 # Preparing the filters randomly.l1_filter = numpy.zeros((2,3,3))l1_filter[0, :, :] = numpy.array([[[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]])l1_filter[1, :, :] = numpy.array([[[1, 1, 1], [0, 0, 0], [-1, -1, -1]]])print("\n**Working with conv layer 1**")l1_feature_map = conv(img, l1_filter)print("\n**ReLU**")l1_feature_map_relu = relu(l1_feature_map)print("\n**Pooling**")l1_feature_map_relu_pool = pooling(l1_feature_map_relu, 2, 2)print("**End of conv layer 1**\n")# Second conv layerl2_filter = numpy.random.rand(3, 5, 5, l1_feature_map_relu_pool.shape[-1])print("\n**Working with conv layer 2**")l2_feature_map = conv(l1_feature_map_relu_pool, l2_filter)print("\n**ReLU**")l2_feature_map_relu = relu(l2_feature_map)print("\n**Pooling**")l2_feature_map_relu_pool = pooling(l2_feature_map_relu, 2, 2)print("**End of conv layer 2**\n")# Third conv layerl3_filter = numpy.random.rand(1, 7, 7, l2_feature_map_relu_pool.shape[-1])print("\n**Working with conv layer 3**")l3_feature_map = conv(l2_feature_map_relu_pool, l3_filter)print("\n**ReLU**")l3_feature_map_relu = relu(l3_feature_map)print("\n**Pooling**")l3_feature_map_relu_pool = pooling(l3_feature_map_relu, 2, 2)print("**End of conv layer 3**\n")# Graphing resultsfig0, ax0 = matplotlib.pyplot.subplots(nrows=1, ncols=1)ax0.imshow(img).set_cmap("gray")ax0.set_title("Input Image")ax0.get_xaxis().set_ticks([])ax0.get_yaxis().set_ticks([])matplotlib.pyplot.savefig("in_img.png", bbox_inches="tight")matplotlib.pyplot.close(fig0)# Layer 1fig1, ax1 = matplotlib.pyplot.subplots(nrows=3, ncols=2)ax1[0, 0].imshow(l1_feature_map[:, :, 0]).set_cmap("gray")ax1[0, 0].get_xaxis().set_ticks([])ax1[0, 0].get_yaxis().set_ticks([])ax1[0, 0].set_title("L1-Map1")ax1[0, 1].imshow(l1_feature_map[:, :, 1]).set_cmap("gray")ax1[0, 1].get_xaxis().set_ticks([])ax1[0, 1].get_yaxis().set_ticks([])ax1[0, 1].set_title("L1-Map2")ax1[1, 0].imshow(l1_feature_map_relu[:, :, 0]).set_cmap("gray")ax1[1, 0].get_xaxis().set_ticks([])ax1[1, 0].get_yaxis().set_ticks([])ax1[1, 0].set_title("L1-Map1ReLU")ax1[1, 1].imshow(l1_feature_map_relu[:, :, 1]).set_cmap("gray")ax1[1, 1].get_xaxis().set_ticks([])ax1[1, 1].get_yaxis().set_ticks([])ax1[1, 1].set_title("L1-Map2ReLU")ax1[2, 0].imshow(l1_feature_map_relu_pool[:, :, 0]).set_cmap("gray")ax1[2, 0].get_xaxis().set_ticks([])ax1[2, 0].get_yaxis().set_ticks([])ax1[2, 0].set_title("L1-Map1ReLUPool")ax1[2, 1].imshow(l1_feature_map_relu_pool[:, :, 1]).set_cmap("gray")ax1[2, 0].get_xaxis().set_ticks([])ax1[2, 0].get_yaxis().set_ticks([])ax1[2, 1].set_title("L1-Map2ReLUPool")matplotlib.pyplot.savefig("L1.png", bbox_inches="tight")matplotlib.pyplot.close(fig1)# Layer 2fig2, ax2 = matplotlib.pyplot.subplots(nrows=3, ncols=3)ax2[0, 0].imshow(l2_feature_map[:, :, 0]).set_cmap("gray")ax2[0, 0].get_xaxis().set_ticks([])ax2[0, 0].get_yaxis().set_ticks([])ax2[0, 0].set_title("L2-Map1")ax2[0, 1].imshow(l2_feature_map[:, :, 1]).set_cmap("gray")ax2[0, 1].get_xaxis().set_ticks([])ax2[0, 1].get_yaxis().set_ticks([])ax2[0, 1].set_title("L2-Map2")ax2[0, 2].imshow(l2_feature_map[:, :, 2]).set_cmap("gray")ax2[0, 2].get_xaxis().set_ticks([])ax2[0, 2].get_yaxis().set_ticks([])ax2[0, 2].set_title("L2-Map3")ax2[1, 0].imshow(l2_feature_map_relu[:, :, 0]).set_cmap("gray")ax2[1, 0].get_xaxis().set_ticks([])ax2[1, 0].get_yaxis().set_ticks([])ax2[1, 0].set_title("L2-Map1ReLU")ax2[1, 1].imshow(l2_feature_map_relu[:, :, 1]).set_cmap("gray")ax2[1, 1].get_xaxis().set_ticks([])ax2[1, 1].get_yaxis().set_ticks([])ax2[1, 1].set_title("L2-Map2ReLU")ax2[1, 2].imshow(l2_feature_map_relu[:, :, 2]).set_cmap("gray")ax2[1, 2].get_xaxis().set_ticks([])ax2[1, 2].get_yaxis().set_ticks([])ax2[1, 2].set_title("L2-Map3ReLU")ax2[2, 0].imshow(l2_feature_map_relu_pool[:, :, 0]).set_cmap("gray")ax2[2, 0].get_xaxis().set_ticks([])ax2[2, 0].get_yaxis().set_ticks([])ax2[2, 0].set_title("L2-Map1ReLUPool")ax2[2, 1].imshow(l2_feature_map_relu_pool[:, :, 1]).set_cmap("gray")ax2[2, 1].get_xaxis().set_ticks([])ax2[2, 1].get_yaxis().set_ticks([])ax2[2, 1].set_title("L2-Map2ReLUPool")ax2[2, 2].imshow(l2_feature_map_relu_pool[:, :, 2]).set_cmap("gray")ax2[2, 2].get_xaxis().set_ticks([])ax2[2, 2].get_yaxis().set_ticks([])ax2[2, 2].set_title("L2-Map3ReLUPool")matplotlib.pyplot.savefig("L2.png", bbox_inches="tight")matplotlib.pyplot.close(fig2)# Layer 3fig3, ax3 = matplotlib.pyplot.subplots(nrows=1, ncols=3)ax3[0].imshow(l3_feature_map[:, :, 0]).set_cmap("gray")ax3[0].get_xaxis().set_ticks([])ax3[0].get_yaxis().set_ticks([])ax3[0].set_title("L3-Map1")ax3[1].imshow(l3_feature_map_relu[:, :, 0]).set_cmap("gray")ax3[1].get_xaxis().set_ticks([])ax3[1].get_yaxis().set_ticks([])ax3[1].set_title("L3-Map1ReLU")ax3[2].imshow(l3_feature_map_relu_pool[:, :, 0]).set_cmap("gray")ax3[2].get_xaxis().set_ticks([])ax3[2].get_yaxis().set_ticks([])ax3[2].set_title("L3-Map1ReLUPool")matplotlib.pyplot.savefig("L3.png", bbox_inches="tight")matplotlib.pyplot.close(fig3)
The original article is available at LinkedIn at this link:
www.linkedin.com
Ahmed Fawzy Gad | [
{
"code": null,
"e": 279,
"s": 47,
"text": "Using already existing models in ML/DL libraries might be helpful in some cases. But to have better control and understanding, you should try to implement them yourself. This article shows how a CNN is implemented just using NumPy."
},
{
"code": null,
"e": 1017,
"s": 279,
"text": "Convolutional neural network (CNN) is the state-of-art technique for analyzing multidimensional signals such as images. There are different libraries that already implements CNN such as TensorFlow and Keras. Such libraries isolates the developer from some details and just give an abstract API to make life easier and avoid complexity in the implementation. But in practice, such details might make a difference. Sometimes, the data scientist have to go through such details to enhance the performance. The solution in such situation is to build every piece of such model your own. This gives the highest possible level of control over the network. Also, it is recommended to implement such models to have better understanding over them."
},
{
"code": null,
"e": 1209,
"s": 1017,
"text": "In this article, CNN is created using only NumPy library. Just three layers are created which are convolution (conv for short), ReLU, and max pooling. The major steps involved are as follows:"
},
{
"code": null,
"e": 1237,
"s": 1209,
"text": "1. Reading the input image."
},
{
"code": null,
"e": 1259,
"s": 1237,
"text": "2. Preparing filters."
},
{
"code": null,
"e": 1319,
"s": 1259,
"text": "3. Conv layer: Convolving each filter with the input image."
},
{
"code": null,
"e": 1412,
"s": 1319,
"text": "4. ReLU layer: Applying ReLU activation function on the feature maps (output of conv layer)."
},
{
"code": null,
"e": 1494,
"s": 1412,
"text": "5. Max Pooling layer: Applying the pooling operation on the output of ReLU layer."
},
{
"code": null,
"e": 1542,
"s": 1494,
"text": "6. Stacking conv, ReLU, and max pooling layers."
},
{
"code": null,
"e": 1652,
"s": 1542,
"text": "The following code reads an already existing image from the skimage Python library and converts it into gray."
},
{
"code": null,
"e": 1785,
"s": 1652,
"text": "import skimage.data# Reading the imageimg = skimage.data.chelsea()# Converting the image into gray.img = skimage.color.rgb2gray(img)"
},
{
"code": null,
"e": 1920,
"s": 1785,
"text": "Reading image is the first step because next steps depend on the input size. The image after being converted into gray is shown below."
},
{
"code": null,
"e": 2006,
"s": 1920,
"text": "The following code prepares the filters bank for the first conv layer (l1 for short):"
},
{
"code": null,
"e": 2039,
"s": 2006,
"text": "l1_filter = numpy.zeros((2,3,3))"
},
{
"code": null,
"e": 2456,
"s": 2039,
"text": "A zero array is created according to the number of filters and the size of each filter. 2 filters of size 3x3 are created that is why the zero array is of size (2=num_filters, 3=num_rows_filter, 3=num_columns_filter). Size of the filter is selected to be 2D array without depth because the input image is gray and has no depth (i.e. 2D ). If the image is RGB with 3 channels, the filter size must be (3, 3, 3=depth)."
},
{
"code": null,
"e": 2655,
"s": 2456,
"text": "The size of the filters bank is specified by the above zero array but not the actual values of the filters. It is possible to override such values as follows to detect vertical and horizontal edges."
},
{
"code": null,
"e": 2942,
"s": 2655,
"text": "l1_filter[0, :, :] = numpy.array([[[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]])l1_filter[1, :, :] = numpy.array([[[1, 1, 1], [0, 0, 0], [-1, -1, -1]]])"
},
{
"code": null,
"e": 3102,
"s": 2942,
"text": "After preparing the filters, next is to convolve the input image by them. The next line convolves the image with the filters bank using a function called conv:"
},
{
"code": null,
"e": 3140,
"s": 3102,
"text": "l1_feature_map = conv(img, l1_filter)"
},
{
"code": null,
"e": 3252,
"s": 3140,
"text": "Such function accepts just two arguments which are the image and the filter bank which is implemented as below."
},
{
"code": null,
"e": 5327,
"s": 3252,
"text": "def conv(img, conv_filter): if len(img.shape) > 2 or len(conv_filter.shape) > 3: # Check if number of image channels matches the filter depth. if img.shape[-1] != conv_filter.shape[-1]: print(\"Error: Number of channels in both image and filter must match.\") sys.exit() if conv_filter.shape[1] != conv_filter.shape[2]: # Check if filter dimensions are equal. print('Error: Filter must be a square matrix. I.e. number of rows and columns must match.') sys.exit() if conv_filter.shape[1]%2==0: # Check if filter diemnsions are odd. print('Error: Filter must have an odd size. I.e. number of rows and columns must be odd.') sys.exit() # An empty feature map to hold the output of convolving the filter(s) with the image. feature_maps = numpy.zeros((img.shape[0]-conv_filter.shape[1]+1, img.shape[1]-conv_filter.shape[1]+1, conv_filter.shape[0])) # Convolving the image by the filter(s). for filter_num in range(conv_filter.shape[0]): print(\"Filter \", filter_num + 1) curr_filter = conv_filter[filter_num, :] # getting a filter from the bank. \"\"\" Checking if there are mutliple channels for the single filter. If so, then each channel will convolve the image. The result of all convolutions are summed to return a single feature map. \"\"\" if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) # Array holding the sum of all feature maps. for ch_num in range(1, curr_filter.shape[-1]): # Convolving each channel with the image and summing the results. conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: # There is just a single channel in the filter. conv_map = conv_(img, curr_filter) feature_maps[:, :, filter_num] = conv_map # Holding feature map with the current filter. return feature_maps # Returning all feature maps."
},
{
"code": null,
"e": 5633,
"s": 5327,
"text": "The function starts by ensuring that the depth of each filter is equal to the number of image channels. In the code below, the outer if checks if the channel and the filter have a depth. If a depth already exists, then the inner if checks their inequality. If there is no match, then the script will exit."
},
{
"code": null,
"e": 5903,
"s": 5633,
"text": "if len(img.shape) > 2 or len(conv_filter.shape) > 3: # Check if number of image channels matches the filter depth. if img.shape[-1] != conv_filter.shape[-1]: print(\"Error: Number of channels in both image and filter must match.\") sys.exit()"
},
{
"code": null,
"e": 6145,
"s": 5903,
"text": "Moreover, the size of the filter should be odd and filter dimensions are equal (i.e. number of rows and columns are odd and equal). This is checked according to the following two if blocks. If such conditions don’t met, the script will exit."
},
{
"code": null,
"e": 6538,
"s": 6145,
"text": "if conv_filter.shape[1] != conv_filter.shape[2]: # Check if filter dimensions are equal. print('Error: Filter must be a square matrix. I.e. number of rows and columns must match.') sys.exit() if conv_filter.shape[1]%2==0: # Check if filter diemnsions are odd. print('Error: Filter must have an odd size. I.e. number of rows and columns must be odd.') sys.exit()"
},
{
"code": null,
"e": 6859,
"s": 6538,
"text": "Not satisfying any of the conditions above is a proof that the filter depth is suitable with the image and convolution is ready to be applied. Convolving the image by the filter starts by initializing an array to hold the outputs of convolution (i.e. feature maps) by specifying its size according to the following code:"
},
{
"code": null,
"e": 7137,
"s": 6859,
"text": "# An empty feature map to hold the output of convolving the filter(s) with the image. feature_maps = numpy.zeros((img.shape[0]-conv_filter.shape[1]+1, img.shape[1]-conv_filter.shape[1]+1, conv_filter.shape[0]))"
},
{
"code": null,
"e": 7503,
"s": 7137,
"text": "Because there is no stride nor padding, the feature map size will be equal to (img_rows-filter_rows+1, image_columns-filter_columns+1, num_filters) as above in the code. Note that there is an output feature map for every filter in the bank. That is why the number of filters in the filter bank (conv_filter.shape[0]) is used to specify the size as a third argument."
},
{
"code": null,
"e": 7625,
"s": 7503,
"text": "After preparing the inputs and outputs of the convolution operation, next is to apply it according to the following code:"
},
{
"code": null,
"e": 8719,
"s": 7625,
"text": "# Convolving the image by the filter(s). for filter_num in range(conv_filter.shape[0]): print(\"Filter \", filter_num + 1) curr_filter = conv_filter[filter_num, :] # getting a filter from the bank. \"\"\" Checking if there are mutliple channels for the single filter. If so, then each channel will convolve the image. The result of all convolutions are summed to return a single feature map. \"\"\" if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) # Array holding the sum of all feature maps. for ch_num in range(1, curr_filter.shape[-1]): # Convolving each channel with the image and summing the results. conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: # There is just a single channel in the filter. conv_map = conv_(img, curr_filter) feature_maps[:, :, filter_num] = conv_map # Holding feature map with the current filter. return feature_maps # Returning all feature maps."
},
{
"code": null,
"e": 8836,
"s": 8719,
"text": "The outer loop iterates over each filter in the filter bank and returns it for further steps according to this line:"
},
{
"code": null,
"e": 8911,
"s": 8836,
"text": "curr_filter = conv_filter[filter_num, :] # getting a filter from the bank."
},
{
"code": null,
"e": 9350,
"s": 8911,
"text": "If the image to be convolved has more than one channel, then the filter must has a depth equal to such number of channels. Convolution in this case is done by convolving each image channel with its corresponding channel in the filter. Finally, the sum of the results will be the output feature map. If the image has just a single channel, then convolution will be straight forward. Determining such behavior is done in such if-else block:"
},
{
"code": null,
"e": 9844,
"s": 9350,
"text": "if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) # Array holding the sum of all feature maps. for ch_num in range(1, curr_filter.shape[-1]): # Convolving each channel with the image and summing the results. conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: # There is just a single channel in the filter. conv_map = conv_(img, curr_filter)"
},
{
"code": null,
"e": 10261,
"s": 9844,
"text": "You might notice that the convolution is applied by a function called conv_ which is different from the conv function. The function conv just accepts the input image and the filter bank but doesn’t apply convolution its own. It just passes each set of input-filter pairs to be convolved to the conv_ function. This is just for making the code simpler to investigate. Here is the implementation of the conv_ function:"
},
{
"code": null,
"e": 11775,
"s": 10261,
"text": "def conv_(img, conv_filter): filter_size = conv_filter.shape[1] result = numpy.zeros((img.shape)) #Looping through the image to apply the convolution operation. for r in numpy.uint16(numpy.arange(filter_size/2.0, img.shape[0]-filter_size/2.0+1)): for c in numpy.uint16(numpy.arange(filter_size/2.0, img.shape[1]-filter_size/2.0+1)): \"\"\" Getting the current region to get multiplied with the filter. How to loop through the image and get the region based on the image and filer sizes is the most tricky part of convolution. \"\"\" curr_region = img[r-numpy.uint16(numpy.floor(filter_size/2.0)):r+numpy.uint16(numpy.ceil(filter_size/2.0)), c-numpy.uint16(numpy.floor(filter_size/2.0)):c+numpy.uint16(numpy.ceil(filter_size/2.0))] #Element-wise multipliplication between the current region and the filter. curr_result = curr_region * conv_filter conv_sum = numpy.sum(curr_result) #Summing the result of multiplication. result[r, c] = conv_sum #Saving the summation in the convolution layer feature map. #Clipping the outliers of the result matrix. final_result = result[numpy.uint16(filter_size/2.0):result.shape[0]-numpy.uint16(filter_size/2.0), numpy.uint16(filter_size/2.0):result.shape[1]-numpy.uint16(filter_size/2.0)] return final_result"
},
{
"code": null,
"e": 11875,
"s": 11775,
"text": "It iterates over the image and extracts regions of equal size to the filter according to this line:"
},
{
"code": null,
"e": 12103,
"s": 11875,
"text": "curr_region = img[r-numpy.uint16(numpy.floor(filter_size/2.0)):r+numpy.uint16(numpy.ceil(filter_size/2.0)), c-numpy.uint16(numpy.floor(filter_size/2.0)):c+numpy.uint16(numpy.ceil(filter_size/2.0))]"
},
{
"code": null,
"e": 12258,
"s": 12103,
"text": "Then it apply element-wise multiplication between the region and the filter and summing them to get a single value as the output according to these lines:"
},
{
"code": null,
"e": 12563,
"s": 12258,
"text": "#Element-wise multipliplication between the current region and the filter. curr_result = curr_region * conv_filter conv_sum = numpy.sum(curr_result) #Summing the result of multiplication. result[r, c] = conv_sum #Saving the summation in the convolution layer feature map."
},
{
"code": null,
"e": 12719,
"s": 12563,
"text": "After convolving each filter by the input, the feature maps are returned by the conv function. Figure 2 shows the feature maps returned by such conv layer."
},
{
"code": null,
"e": 12779,
"s": 12719,
"text": "The output of such layer will be applied to the ReLU layer."
},
{
"code": null,
"e": 12959,
"s": 12779,
"text": "The ReLU layer applies the ReLU activation function over each feature map returned by the conv layer. It is called using the relu function according to the following line of code:"
},
{
"code": null,
"e": 13002,
"s": 12959,
"text": "l1_feature_map_relu = relu(l1_feature_map)"
},
{
"code": null,
"e": 13047,
"s": 13002,
"text": "The relu function is implemented as follows:"
},
{
"code": null,
"e": 13437,
"s": 13047,
"text": "def relu(feature_map): #Preparing the output of the ReLU activation function. relu_out = numpy.zeros(feature_map.shape) for map_num in range(feature_map.shape[-1]): for r in numpy.arange(0,feature_map.shape[0]): for c in numpy.arange(0, feature_map.shape[1]): relu_out[r, c, map_num] = numpy.max([feature_map[r, c, map_num], 0]) return relu_out"
},
{
"code": null,
"e": 13652,
"s": 13437,
"text": "It is very simple. Just loop though each element in the feature map and return the original value in the feature map if it is larger than 0. Otherwise, return 0. The outputs of the ReLU layer are shown in figure 3."
},
{
"code": null,
"e": 13718,
"s": 13652,
"text": "The output of the ReLU layer is applied to the max pooling layer."
},
{
"code": null,
"e": 13848,
"s": 13718,
"text": "The max pooling layer accepts the output of the ReLU layer and applies the max pooling operation according to the following line:"
},
{
"code": null,
"e": 13910,
"s": 13848,
"text": "l1_feature_map_relu_pool = pooling(l1_feature_map_relu, 2, 2)"
},
{
"code": null,
"e": 13967,
"s": 13910,
"text": "It is implemented using the pooling function as follows:"
},
{
"code": null,
"e": 14660,
"s": 13967,
"text": "def pooling(feature_map, size=2, stride=2): #Preparing the output of the pooling operation. pool_out = numpy.zeros((numpy.uint16((feature_map.shape[0]-size+1)/stride), numpy.uint16((feature_map.shape[1]-size+1)/stride), feature_map.shape[-1])) for map_num in range(feature_map.shape[-1]): r2 = 0 for r in numpy.arange(0,feature_map.shape[0]-size-1, stride): c2 = 0 for c in numpy.arange(0, feature_map.shape[1]-size-1, stride): pool_out[r2, c2, map_num] = numpy.max([feature_map[r:r+size, c:c+size, map_num]]) c2 = c2 + 1 r2 = r2 +1 return pool_out"
},
{
"code": null,
"e": 14945,
"s": 14660,
"text": "The function accepts three inputs which are the output of the ReLU layer, pooling mask size, and stride. It simply creates an empty array, as previous, that holds the output of such layer. The size of such array is specified according to the size and stride arguments as in such line:"
},
{
"code": null,
"e": 15151,
"s": 14945,
"text": "pool_out = numpy.zeros((numpy.uint16((feature_map.shape[0]-size+1)/stride), numpy.uint16((feature_map.shape[1]-size+1)/stride), feature_map.shape[-1]))"
},
{
"code": null,
"e": 15471,
"s": 15151,
"text": "Then it loops through the input, channel by channel according to the outer loop that uses the looping variable map_num. For each channel in the input, max pooling operation is applied. According to the stride and size used, the region is clipped and the max of it is returned in the output array according to this line:"
},
{
"code": null,
"e": 15554,
"s": 15471,
"text": "pool_out[r2, c2, map_num] = numpy.max([feature_map[r:r+size, c:c+size, map_num]])"
},
{
"code": null,
"e": 15736,
"s": 15554,
"text": "The outputs of such pooling layer are shown in the next figure. Note that the size of the pooling layer output is smaller than its input even if they seem identical in their graphs."
},
{
"code": null,
"e": 15918,
"s": 15736,
"text": "Up to this point, the CNN architecture with conv, ReLU, and max pooling layers is complete. There might be some other layers to be stacked in addition to the previous ones as below."
},
{
"code": null,
"e": 16288,
"s": 15918,
"text": "# Second conv layerl2_filter = numpy.random.rand(3, 5, 5, l1_feature_map_relu_pool.shape[-1])print(\"\\n**Working with conv layer 2**\")l2_feature_map = conv(l1_feature_map_relu_pool, l2_filter)print(\"\\n**ReLU**\")l2_feature_map_relu = relu(l2_feature_map)print(\"\\n**Pooling**\")l2_feature_map_relu_pool = pooling(l2_feature_map_relu, 2, 2)print(\"**End of conv layer 2**\\n\")"
},
{
"code": null,
"e": 16549,
"s": 16288,
"text": "The previous conv layer uses 3 filters with their values generated randomly. That is why there will be 3 feature maps resulted from such conv layer. This is also the same for the successive ReLU and pooling layers. Outputs of such layers are shown in figure 5."
},
{
"code": null,
"e": 16945,
"s": 16549,
"text": "# Third conv layerl3_filter = numpy.random.rand(1, 7, 7, l2_feature_map_relu_pool.shape[-1])print(\"\\n**Working with conv layer 3**\")l3_feature_map = numpycnn.conv(l2_feature_map_relu_pool, l3_filter)print(\"\\n**ReLU**\")l3_feature_map_relu = numpycnn.relu(l3_feature_map)print(\"\\n**Pooling**\")l3_feature_map_relu_pool = numpycnn.pooling(l3_feature_map_relu, 2, 2)print(\"**End of conv layer 3**\\n\")"
},
{
"code": null,
"e": 17103,
"s": 16945,
"text": "Figure 6 shows the outputs of the previous layers. The previous conv layer accepts just a single filter. That is why there is only one feature map as output."
},
{
"code": null,
"e": 17253,
"s": 17103,
"text": "But remember, the output of each previous layer is the input to the next layer. For example, such lines accepts the previous outputs as their inputs."
},
{
"code": null,
"e": 17370,
"s": 17253,
"text": "l2_feature_map = conv(l1_feature_map_relu_pool, l2_filter)l3_feature_map = conv(l2_feature_map_relu_pool, l3_filter)"
},
{
"code": null,
"e": 17549,
"s": 17370,
"text": "The complete code is available in github (https://github.com/ahmedfgad/NumPyCNN). The code contains the visualization of the outputs from each layer using the Matplotlib library."
},
{
"code": null,
"e": 27527,
"s": 17549,
"text": "import skimage.dataimport numpyimport matplotlibimport sysdef conv_(img, conv_filter): filter_size = conv_filter.shape[1] result = numpy.zeros((img.shape)) #Looping through the image to apply the convolution operation. for r in numpy.uint16(numpy.arange(filter_size/2.0, img.shape[0]-filter_size/2.0+1)): for c in numpy.uint16(numpy.arange(filter_size/2.0, img.shape[1]-filter_size/2.0+1)): \"\"\" Getting the current region to get multiplied with the filter. How to loop through the image and get the region based on the image and filer sizes is the most tricky part of convolution. \"\"\" curr_region = img[r-numpy.uint16(numpy.floor(filter_size/2.0)):r+numpy.uint16(numpy.ceil(filter_size/2.0)), c-numpy.uint16(numpy.floor(filter_size/2.0)):c+numpy.uint16(numpy.ceil(filter_size/2.0))] #Element-wise multipliplication between the current region and the filter. curr_result = curr_region * conv_filter conv_sum = numpy.sum(curr_result) #Summing the result of multiplication. result[r, c] = conv_sum #Saving the summation in the convolution layer feature map. #Clipping the outliers of the result matrix. final_result = result[numpy.uint16(filter_size/2.0):result.shape[0]-numpy.uint16(filter_size/2.0), numpy.uint16(filter_size/2.0):result.shape[1]-numpy.uint16(filter_size/2.0)] return final_resultdef conv(img, conv_filter): if len(img.shape) > 2 or len(conv_filter.shape) > 3: # Check if number of image channels matches the filter depth. if img.shape[-1] != conv_filter.shape[-1]: print(\"Error: Number of channels in both image and filter must match.\") sys.exit() if conv_filter.shape[1] != conv_filter.shape[2]: # Check if filter dimensions are equal. print('Error: Filter must be a square matrix. I.e. number of rows and columns must match.') sys.exit() if conv_filter.shape[1]%2==0: # Check if filter diemnsions are odd. print('Error: Filter must have an odd size. I.e. number of rows and columns must be odd.') sys.exit()# An empty feature map to hold the output of convolving the filter(s) with the image. feature_maps = numpy.zeros((img.shape[0]-conv_filter.shape[1]+1, img.shape[1]-conv_filter.shape[1]+1, conv_filter.shape[0]))# Convolving the image by the filter(s). for filter_num in range(conv_filter.shape[0]): print(\"Filter \", filter_num + 1) curr_filter = conv_filter[filter_num, :] # getting a filter from the bank. \"\"\" Checking if there are mutliple channels for the single filter. If so, then each channel will convolve the image. The result of all convolutions are summed to return a single feature map. \"\"\" if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) # Array holding the sum of all feature maps. for ch_num in range(1, curr_filter.shape[-1]): # Convolving each channel with the image and summing the results. conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: # There is just a single channel in the filter. conv_map = conv_(img, curr_filter) feature_maps[:, :, filter_num] = conv_map # Holding feature map with the current filter. return feature_maps # Returning all feature maps.def pooling(feature_map, size=2, stride=2): #Preparing the output of the pooling operation. pool_out = numpy.zeros((numpy.uint16((feature_map.shape[0]-size+1)/stride), numpy.uint16((feature_map.shape[1]-size+1)/stride), feature_map.shape[-1])) for map_num in range(feature_map.shape[-1]): r2 = 0 for r in numpy.arange(0,feature_map.shape[0]-size-1, stride): c2 = 0 for c in numpy.arange(0, feature_map.shape[1]-size-1, stride): pool_out[r2, c2, map_num] = numpy.max([feature_map[r:r+size, c:c+size, map_num]]) c2 = c2 + 1 r2 = r2 +1 return pool_outdef relu(feature_map): #Preparing the output of the ReLU activation function. relu_out = numpy.zeros(feature_map.shape) for map_num in range(feature_map.shape[-1]): for r in numpy.arange(0,feature_map.shape[0]): for c in numpy.arange(0, feature_map.shape[1]): relu_out[r, c, map_num] = numpy.max([feature_map[r, c, map_num], 0]) return relu_out# Reading the image#img = skimage.io.imread(\"fruits2.png\")img = skimage.data.chelsea()# Converting the image into gray.img = skimage.color.rgb2gray(img)# First conv layer#l1_filter = numpy.random.rand(2,7,7)*20 # Preparing the filters randomly.l1_filter = numpy.zeros((2,3,3))l1_filter[0, :, :] = numpy.array([[[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]])l1_filter[1, :, :] = numpy.array([[[1, 1, 1], [0, 0, 0], [-1, -1, -1]]])print(\"\\n**Working with conv layer 1**\")l1_feature_map = conv(img, l1_filter)print(\"\\n**ReLU**\")l1_feature_map_relu = relu(l1_feature_map)print(\"\\n**Pooling**\")l1_feature_map_relu_pool = pooling(l1_feature_map_relu, 2, 2)print(\"**End of conv layer 1**\\n\")# Second conv layerl2_filter = numpy.random.rand(3, 5, 5, l1_feature_map_relu_pool.shape[-1])print(\"\\n**Working with conv layer 2**\")l2_feature_map = conv(l1_feature_map_relu_pool, l2_filter)print(\"\\n**ReLU**\")l2_feature_map_relu = relu(l2_feature_map)print(\"\\n**Pooling**\")l2_feature_map_relu_pool = pooling(l2_feature_map_relu, 2, 2)print(\"**End of conv layer 2**\\n\")# Third conv layerl3_filter = numpy.random.rand(1, 7, 7, l2_feature_map_relu_pool.shape[-1])print(\"\\n**Working with conv layer 3**\")l3_feature_map = conv(l2_feature_map_relu_pool, l3_filter)print(\"\\n**ReLU**\")l3_feature_map_relu = relu(l3_feature_map)print(\"\\n**Pooling**\")l3_feature_map_relu_pool = pooling(l3_feature_map_relu, 2, 2)print(\"**End of conv layer 3**\\n\")# Graphing resultsfig0, ax0 = matplotlib.pyplot.subplots(nrows=1, ncols=1)ax0.imshow(img).set_cmap(\"gray\")ax0.set_title(\"Input Image\")ax0.get_xaxis().set_ticks([])ax0.get_yaxis().set_ticks([])matplotlib.pyplot.savefig(\"in_img.png\", bbox_inches=\"tight\")matplotlib.pyplot.close(fig0)# Layer 1fig1, ax1 = matplotlib.pyplot.subplots(nrows=3, ncols=2)ax1[0, 0].imshow(l1_feature_map[:, :, 0]).set_cmap(\"gray\")ax1[0, 0].get_xaxis().set_ticks([])ax1[0, 0].get_yaxis().set_ticks([])ax1[0, 0].set_title(\"L1-Map1\")ax1[0, 1].imshow(l1_feature_map[:, :, 1]).set_cmap(\"gray\")ax1[0, 1].get_xaxis().set_ticks([])ax1[0, 1].get_yaxis().set_ticks([])ax1[0, 1].set_title(\"L1-Map2\")ax1[1, 0].imshow(l1_feature_map_relu[:, :, 0]).set_cmap(\"gray\")ax1[1, 0].get_xaxis().set_ticks([])ax1[1, 0].get_yaxis().set_ticks([])ax1[1, 0].set_title(\"L1-Map1ReLU\")ax1[1, 1].imshow(l1_feature_map_relu[:, :, 1]).set_cmap(\"gray\")ax1[1, 1].get_xaxis().set_ticks([])ax1[1, 1].get_yaxis().set_ticks([])ax1[1, 1].set_title(\"L1-Map2ReLU\")ax1[2, 0].imshow(l1_feature_map_relu_pool[:, :, 0]).set_cmap(\"gray\")ax1[2, 0].get_xaxis().set_ticks([])ax1[2, 0].get_yaxis().set_ticks([])ax1[2, 0].set_title(\"L1-Map1ReLUPool\")ax1[2, 1].imshow(l1_feature_map_relu_pool[:, :, 1]).set_cmap(\"gray\")ax1[2, 0].get_xaxis().set_ticks([])ax1[2, 0].get_yaxis().set_ticks([])ax1[2, 1].set_title(\"L1-Map2ReLUPool\")matplotlib.pyplot.savefig(\"L1.png\", bbox_inches=\"tight\")matplotlib.pyplot.close(fig1)# Layer 2fig2, ax2 = matplotlib.pyplot.subplots(nrows=3, ncols=3)ax2[0, 0].imshow(l2_feature_map[:, :, 0]).set_cmap(\"gray\")ax2[0, 0].get_xaxis().set_ticks([])ax2[0, 0].get_yaxis().set_ticks([])ax2[0, 0].set_title(\"L2-Map1\")ax2[0, 1].imshow(l2_feature_map[:, :, 1]).set_cmap(\"gray\")ax2[0, 1].get_xaxis().set_ticks([])ax2[0, 1].get_yaxis().set_ticks([])ax2[0, 1].set_title(\"L2-Map2\")ax2[0, 2].imshow(l2_feature_map[:, :, 2]).set_cmap(\"gray\")ax2[0, 2].get_xaxis().set_ticks([])ax2[0, 2].get_yaxis().set_ticks([])ax2[0, 2].set_title(\"L2-Map3\")ax2[1, 0].imshow(l2_feature_map_relu[:, :, 0]).set_cmap(\"gray\")ax2[1, 0].get_xaxis().set_ticks([])ax2[1, 0].get_yaxis().set_ticks([])ax2[1, 0].set_title(\"L2-Map1ReLU\")ax2[1, 1].imshow(l2_feature_map_relu[:, :, 1]).set_cmap(\"gray\")ax2[1, 1].get_xaxis().set_ticks([])ax2[1, 1].get_yaxis().set_ticks([])ax2[1, 1].set_title(\"L2-Map2ReLU\")ax2[1, 2].imshow(l2_feature_map_relu[:, :, 2]).set_cmap(\"gray\")ax2[1, 2].get_xaxis().set_ticks([])ax2[1, 2].get_yaxis().set_ticks([])ax2[1, 2].set_title(\"L2-Map3ReLU\")ax2[2, 0].imshow(l2_feature_map_relu_pool[:, :, 0]).set_cmap(\"gray\")ax2[2, 0].get_xaxis().set_ticks([])ax2[2, 0].get_yaxis().set_ticks([])ax2[2, 0].set_title(\"L2-Map1ReLUPool\")ax2[2, 1].imshow(l2_feature_map_relu_pool[:, :, 1]).set_cmap(\"gray\")ax2[2, 1].get_xaxis().set_ticks([])ax2[2, 1].get_yaxis().set_ticks([])ax2[2, 1].set_title(\"L2-Map2ReLUPool\")ax2[2, 2].imshow(l2_feature_map_relu_pool[:, :, 2]).set_cmap(\"gray\")ax2[2, 2].get_xaxis().set_ticks([])ax2[2, 2].get_yaxis().set_ticks([])ax2[2, 2].set_title(\"L2-Map3ReLUPool\")matplotlib.pyplot.savefig(\"L2.png\", bbox_inches=\"tight\")matplotlib.pyplot.close(fig2)# Layer 3fig3, ax3 = matplotlib.pyplot.subplots(nrows=1, ncols=3)ax3[0].imshow(l3_feature_map[:, :, 0]).set_cmap(\"gray\")ax3[0].get_xaxis().set_ticks([])ax3[0].get_yaxis().set_ticks([])ax3[0].set_title(\"L3-Map1\")ax3[1].imshow(l3_feature_map_relu[:, :, 0]).set_cmap(\"gray\")ax3[1].get_xaxis().set_ticks([])ax3[1].get_yaxis().set_ticks([])ax3[1].set_title(\"L3-Map1ReLU\")ax3[2].imshow(l3_feature_map_relu_pool[:, :, 0]).set_cmap(\"gray\")ax3[2].get_xaxis().set_ticks([])ax3[2].get_yaxis().set_ticks([])ax3[2].set_title(\"L3-Map1ReLUPool\")matplotlib.pyplot.savefig(\"L3.png\", bbox_inches=\"tight\")matplotlib.pyplot.close(fig3)"
},
{
"code": null,
"e": 27587,
"s": 27527,
"text": "The original article is available at LinkedIn at this link:"
},
{
"code": null,
"e": 27604,
"s": 27587,
"text": "www.linkedin.com"
}
]
|
Matplotlib.colors.BoundaryNorm class in Python - GeeksforGeeks | 19 Oct, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.colors.BoundaryNorm class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap.The matplotlib.colors.BoundaryNorm class is used to create a colormap based on discrete intervals. BoundaryNorm maps values to integers, unlike Normalize or LogNorm which does mapping to the interval of 0 to 1. Piecewise linear interpolation can be used for mapping to the o- interval, however, using integers is simpler and leads to the reduction of the number of conversions back and forth among integer and floating points.Parameters:
boundaries: it is an array like object that monotonically increase sequence of boundaries ncolor: It accepts an integer value that represents a number of colors in the colormap that will be used. clip: It accepts a boolean value and is a optional parameter. If the clip is True, the values that are out of range and they are below the boundaries[0] are mapped to 0, whereas if they are above the boundaries[-1] they are mapped to ncolors-1. If the clip is set to False, the out of range values and they are below the boundaries[0] are mapped to -1, whereas if they are above boundaries[-1], they are mapped to ncolors. The Colormap.__call__() convert these into valid indices.
boundaries: it is an array like object that monotonically increase sequence of boundaries
ncolor: It accepts an integer value that represents a number of colors in the colormap that will be used.
clip: It accepts a boolean value and is a optional parameter. If the clip is True, the values that are out of range and they are below the boundaries[0] are mapped to 0, whereas if they are above the boundaries[-1] they are mapped to ncolors-1. If the clip is set to False, the out of range values and they are below the boundaries[0] are mapped to -1, whereas if they are above boundaries[-1], they are mapped to ncolors. The Colormap.__call__() convert these into valid indices.
Note: The edges of bins are defined by boundaries and the data falling within the bins are mapped to the same color index. If the ncolors are not equal to the number of bins, linear interpolation is used to choose color for them. Example 1:
Python3
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.collections import LineCollectionfrom matplotlib.colors import ListedColormap, BoundaryNorm a = np.linspace(0, 3 * np.pi, 500)b = np.sin(a)# this is the first derivativedbda = np.cos(0.5 * (a[:-1] + a[1:])) # Creating line segments so# to color them individuallypoints = np.array([a, b]).T.reshape(-1, 1, 2)set_of_segments = np.concatenate([points[:-1], points[1:]], axis = 1) figure, axes = plt.subplots(2, 1, sharex = True, sharey = True) # Mapping the data points with# continuous normcontinuous_norm = plt.Normalize(dbda.min(), dbda.max()) line_collection = LineCollection(set_of_segments, cmap ='viridis', norm = continuous_norm) # Set the values used for# colormappingline_collection.set_array(dbda)line_collection.set_linewidth(2)line = axes[0].add_collection(line_collection)figure.colorbar(line, ax = axes[0]) # Use a boundary norm insteadcmap = ListedColormap(['r', 'g', 'b'])boundary_norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N) line_collection = LineCollection(set_of_segments, cmap = cmap, norm = boundary_norm) line_collection.set_array(dbda)line_collection.set_linewidth(2)line = axes[1].add_collection(line_collection)figure.colorbar(line, ax = axes[1]) axes[0].set_xlim(a.min(), a.max())axes[0].set_ylim(-1.1, 1.1)plt.show()
Output:
Example 2:
Python3
import numpy as npimport matplotlib as mplimport matplotlib.pylab as plt # setup the plotfigure, axes = plt.subplots(1, 1, figsize=(6, 6)) # defining random datax = np.random.rand(20)y = np.random.rand(20) tag = np.random.randint(0, 20, 20)tag[10:12] = 0 # defining the colormapcmap = plt.cm.jet # extracting all colorscmaplist = [cmap(i) for i in range(cmap.N)] # making first color entry greycmaplist[0] = (.5, .5, .5, 1.0) # new mapcmap = mpl.colors.LinearSegmentedColormap.from_list( 'Custom cmap', cmaplist, cmap.N) # defining the bins and normsbounds = np.linspace(0, 20, 21)norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # the scatterscat = axes.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20), cmap=cmap, norm=norm) # axes for the colorbarax2 = figure.add_axes([0.95, 0.1, 0.03, 0.8]) axes.set_title(' discrete colors')
Output:
gabaa406
sweetyty
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 24114,
"s": 23901,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. "
},
{
"code": null,
"e": 24862,
"s": 24114,
"text": "The matplotlib.colors.BoundaryNorm class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap.The matplotlib.colors.BoundaryNorm class is used to create a colormap based on discrete intervals. BoundaryNorm maps values to integers, unlike Normalize or LogNorm which does mapping to the interval of 0 to 1. Piecewise linear interpolation can be used for mapping to the o- interval, however, using integers is simpler and leads to the reduction of the number of conversions back and forth among integer and floating points.Parameters: "
},
{
"code": null,
"e": 25541,
"s": 24862,
"text": "boundaries: it is an array like object that monotonically increase sequence of boundaries ncolor: It accepts an integer value that represents a number of colors in the colormap that will be used. clip: It accepts a boolean value and is a optional parameter. If the clip is True, the values that are out of range and they are below the boundaries[0] are mapped to 0, whereas if they are above the boundaries[-1] they are mapped to ncolors-1. If the clip is set to False, the out of range values and they are below the boundaries[0] are mapped to -1, whereas if they are above boundaries[-1], they are mapped to ncolors. The Colormap.__call__() convert these into valid indices. "
},
{
"code": null,
"e": 25632,
"s": 25541,
"text": "boundaries: it is an array like object that monotonically increase sequence of boundaries "
},
{
"code": null,
"e": 25739,
"s": 25632,
"text": "ncolor: It accepts an integer value that represents a number of colors in the colormap that will be used. "
},
{
"code": null,
"e": 26222,
"s": 25739,
"text": "clip: It accepts a boolean value and is a optional parameter. If the clip is True, the values that are out of range and they are below the boundaries[0] are mapped to 0, whereas if they are above the boundaries[-1] they are mapped to ncolors-1. If the clip is set to False, the out of range values and they are below the boundaries[0] are mapped to -1, whereas if they are above boundaries[-1], they are mapped to ncolors. The Colormap.__call__() convert these into valid indices. "
},
{
"code": null,
"e": 26465,
"s": 26222,
"text": "Note: The edges of bins are defined by boundaries and the data falling within the bins are mapped to the same color index. If the ncolors are not equal to the number of bins, linear interpolation is used to choose color for them. Example 1: "
},
{
"code": null,
"e": 26473,
"s": 26465,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.collections import LineCollectionfrom matplotlib.colors import ListedColormap, BoundaryNorm a = np.linspace(0, 3 * np.pi, 500)b = np.sin(a)# this is the first derivativedbda = np.cos(0.5 * (a[:-1] + a[1:])) # Creating line segments so# to color them individuallypoints = np.array([a, b]).T.reshape(-1, 1, 2)set_of_segments = np.concatenate([points[:-1], points[1:]], axis = 1) figure, axes = plt.subplots(2, 1, sharex = True, sharey = True) # Mapping the data points with# continuous normcontinuous_norm = plt.Normalize(dbda.min(), dbda.max()) line_collection = LineCollection(set_of_segments, cmap ='viridis', norm = continuous_norm) # Set the values used for# colormappingline_collection.set_array(dbda)line_collection.set_linewidth(2)line = axes[0].add_collection(line_collection)figure.colorbar(line, ax = axes[0]) # Use a boundary norm insteadcmap = ListedColormap(['r', 'g', 'b'])boundary_norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N) line_collection = LineCollection(set_of_segments, cmap = cmap, norm = boundary_norm) line_collection.set_array(dbda)line_collection.set_linewidth(2)line = axes[1].add_collection(line_collection)figure.colorbar(line, ax = axes[1]) axes[0].set_xlim(a.min(), a.max())axes[0].set_ylim(-1.1, 1.1)plt.show()",
"e": 28090,
"s": 26473,
"text": null
},
{
"code": null,
"e": 28100,
"s": 28090,
"text": "Output: "
},
{
"code": null,
"e": 28113,
"s": 28100,
"text": "Example 2: "
},
{
"code": null,
"e": 28121,
"s": 28113,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib as mplimport matplotlib.pylab as plt # setup the plotfigure, axes = plt.subplots(1, 1, figsize=(6, 6)) # defining random datax = np.random.rand(20)y = np.random.rand(20) tag = np.random.randint(0, 20, 20)tag[10:12] = 0 # defining the colormapcmap = plt.cm.jet # extracting all colorscmaplist = [cmap(i) for i in range(cmap.N)] # making first color entry greycmaplist[0] = (.5, .5, .5, 1.0) # new mapcmap = mpl.colors.LinearSegmentedColormap.from_list( 'Custom cmap', cmaplist, cmap.N) # defining the bins and normsbounds = np.linspace(0, 20, 21)norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # the scatterscat = axes.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20), cmap=cmap, norm=norm) # axes for the colorbarax2 = figure.add_axes([0.95, 0.1, 0.03, 0.8]) axes.set_title(' discrete colors')",
"e": 29157,
"s": 28121,
"text": null
},
{
"code": null,
"e": 29166,
"s": 29157,
"text": "Output: "
},
{
"code": null,
"e": 29177,
"s": 29168,
"text": "gabaa406"
},
{
"code": null,
"e": 29186,
"s": 29177,
"text": "sweetyty"
},
{
"code": null,
"e": 29204,
"s": 29186,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29211,
"s": 29204,
"text": "Python"
},
{
"code": null,
"e": 29227,
"s": 29211,
"text": "Write From Home"
},
{
"code": null,
"e": 29325,
"s": 29227,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29334,
"s": 29325,
"text": "Comments"
},
{
"code": null,
"e": 29347,
"s": 29334,
"text": "Old Comments"
},
{
"code": null,
"e": 29383,
"s": 29347,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 29406,
"s": 29383,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 29445,
"s": 29406,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29478,
"s": 29445,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 29527,
"s": 29478,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 29563,
"s": 29527,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 29579,
"s": 29563,
"text": "Python infinity"
},
{
"code": null,
"e": 29640,
"s": 29579,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29676,
"s": 29640,
"text": "Matplotlib.pyplot.title() in Python"
}
]
|
Check whether triangle is valid or not if sides are given - GeeksforGeeks | 19 Apr, 2022
Given three sides, check whether triangle is valid or not. Examples:
Input : a = 7, b = 10, c = 5
Output : Valid
Input : a = 1 b = 10 c = 12
Output : Invalid
Approach: A triangle is valid if sum of its two sides is greater than the third side. If three sides are a, b and c, then three conditions should be met.
1.a + b > c
2.a + c > b
3.b + c > a
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to check if three sides form a triangle or not#include <bits/stdc++.h>using namespace std; // function to check if three sider form a triangle or notbool checkValidity(int a, int b, int c){ // check condition if (a + b <= c || a + c <= b || b + c <= a) return false; else return true;} // Driver functionint main(){ int a = 7, b = 10, c = 5; if (checkValidity(a, b, c)) cout << "Valid"; else cout << "Invalid";} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to check if three sides form a triangle or not#include <stdio.h> // function to check if three sider form a triangle or notbool checkValidity(int a, int b, int c){ // check condition if (a + b <= c || a + c <= b || b + c <= a) return false; else return true;} // Driver functionint main(){ int a = 7, b = 10, c = 5; if (checkValidity(a, b, c)) printf("Valid"); else printf("Invalid");} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to check validity of any triangle public class GFG { // Function to calculate for validity public static int checkValidity(int a, int b, int c) { // check condition if (a + b <= c || a + c <= b || b + c <= a) return 0; else return 1; } // Driver function public static void main(String args[]) { int a = 7, b = 10, c = 5; // function calling and print output if ((checkValidity(a, b, c)) == 1) System.out.print("Valid"); else System.out.print("Invalid"); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to check if three# sides form a triangle or not # function to check if three sides# form a triangle or notdef checkValidity(a, b, c): # check condition if (a + b <= c) or (a + c <= b) or (b + c <= a) : return False else: return True # driver codea = 7b = 10c = 5if checkValidity(a, b, c): print("Valid")else: print("Invalid")
// C# program to check// validity of any triangleusing System; class GFG { // Function to calculate for validity public static int checkValidity(int a, int b, int c) { // check condition if (a + b <= c || a + c <= b || b + c <= a) return 0; else return 1; } // Driver code public static void Main() { int a = 7, b = 10, c = 5; // function calling and print output if ((checkValidity(a, b, c)) == 1) Console.Write("Valid"); else Console.Write("Invalid"); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to check if three// sides form a triangle or not // function to check if three sider// form a triangle or notfunction checkValidity($a, $b, $c){ // check condition if ($a + $b <= $c || $a + $c <= $b || $b + $c <= $a) return false; else return true;} // Driver Code $a = 7; $b = 10; $c = 5; if (checkValidity($a, $b, $c)) echo "Valid"; else echo "Invalid"; // This code is contributed by nitin mittal.?>
<script> // Javascript program to check if three// sides form a triangle or not // function to check if three sider// form a triangle or notfunction checkValidity(a, b, c){ // check condition if (a + b <= c || a + c <= b || b + c <= a) return false; else return true;} // Driver function let a = 7, b = 10, c = 5; if (checkValidity(a, b, c)) document.write("Valid"); else document.write("Invalid"); // This code is contributed by Mayank Tyagi </script>
Output :
Valid
Koushik Mondal
nitin mittal
mayanktyagi1709
gaurav4037
adityakumar129
triangle
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Given n line segments, find if any two segments intersect
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Closest Pair of Points | O(nlogn) Implementation
Polygon Clipping | Sutherland–Hodgman Algorithm
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24933,
"s": 24905,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 25004,
"s": 24933,
"text": "Given three sides, check whether triangle is valid or not. Examples: "
},
{
"code": null,
"e": 25097,
"s": 25004,
"text": "Input : a = 7, b = 10, c = 5 \nOutput : Valid\n\nInput : a = 1 b = 10 c = 12 \nOutput : Invalid"
},
{
"code": null,
"e": 25255,
"s": 25099,
"text": "Approach: A triangle is valid if sum of its two sides is greater than the third side. If three sides are a, b and c, then three conditions should be met. "
},
{
"code": null,
"e": 25295,
"s": 25255,
"text": "1.a + b > c \n2.a + c > b \n3.b + c > a "
},
{
"code": null,
"e": 25303,
"s": 25299,
"text": "C++"
},
{
"code": null,
"e": 25305,
"s": 25303,
"text": "C"
},
{
"code": null,
"e": 25310,
"s": 25305,
"text": "Java"
},
{
"code": null,
"e": 25318,
"s": 25310,
"text": "Python3"
},
{
"code": null,
"e": 25321,
"s": 25318,
"text": "C#"
},
{
"code": null,
"e": 25325,
"s": 25321,
"text": "PHP"
},
{
"code": null,
"e": 25336,
"s": 25325,
"text": "Javascript"
},
{
"code": "// C++ program to check if three sides form a triangle or not#include <bits/stdc++.h>using namespace std; // function to check if three sider form a triangle or notbool checkValidity(int a, int b, int c){ // check condition if (a + b <= c || a + c <= b || b + c <= a) return false; else return true;} // Driver functionint main(){ int a = 7, b = 10, c = 5; if (checkValidity(a, b, c)) cout << \"Valid\"; else cout << \"Invalid\";} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 25870,
"s": 25336,
"text": null
},
{
"code": "// C program to check if three sides form a triangle or not#include <stdio.h> // function to check if three sider form a triangle or notbool checkValidity(int a, int b, int c){ // check condition if (a + b <= c || a + c <= b || b + c <= a) return false; else return true;} // Driver functionint main(){ int a = 7, b = 10, c = 5; if (checkValidity(a, b, c)) printf(\"Valid\"); else printf(\"Invalid\");} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 26376,
"s": 25870,
"text": null
},
{
"code": "// Java program to check validity of any triangle public class GFG { // Function to calculate for validity public static int checkValidity(int a, int b, int c) { // check condition if (a + b <= c || a + c <= b || b + c <= a) return 0; else return 1; } // Driver function public static void main(String args[]) { int a = 7, b = 10, c = 5; // function calling and print output if ((checkValidity(a, b, c)) == 1) System.out.print(\"Valid\"); else System.out.print(\"Invalid\"); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 27029,
"s": 26376,
"text": null
},
{
"code": "# Python3 program to check if three# sides form a triangle or not # function to check if three sides# form a triangle or notdef checkValidity(a, b, c): # check condition if (a + b <= c) or (a + c <= b) or (b + c <= a) : return False else: return True # driver codea = 7b = 10c = 5if checkValidity(a, b, c): print(\"Valid\")else: print(\"Invalid\")",
"e": 27415,
"s": 27029,
"text": null
},
{
"code": "// C# program to check// validity of any triangleusing System; class GFG { // Function to calculate for validity public static int checkValidity(int a, int b, int c) { // check condition if (a + b <= c || a + c <= b || b + c <= a) return 0; else return 1; } // Driver code public static void Main() { int a = 7, b = 10, c = 5; // function calling and print output if ((checkValidity(a, b, c)) == 1) Console.Write(\"Valid\"); else Console.Write(\"Invalid\"); }} // This code is contributed by Nitin Mittal.",
"e": 28121,
"s": 27415,
"text": null
},
{
"code": "<?php// PHP program to check if three// sides form a triangle or not // function to check if three sider// form a triangle or notfunction checkValidity($a, $b, $c){ // check condition if ($a + $b <= $c || $a + $c <= $b || $b + $c <= $a) return false; else return true;} // Driver Code $a = 7; $b = 10; $c = 5; if (checkValidity($a, $b, $c)) echo \"Valid\"; else echo \"Invalid\"; // This code is contributed by nitin mittal.?>",
"e": 28632,
"s": 28121,
"text": null
},
{
"code": "<script> // Javascript program to check if three// sides form a triangle or not // function to check if three sider// form a triangle or notfunction checkValidity(a, b, c){ // check condition if (a + b <= c || a + c <= b || b + c <= a) return false; else return true;} // Driver function let a = 7, b = 10, c = 5; if (checkValidity(a, b, c)) document.write(\"Valid\"); else document.write(\"Invalid\"); // This code is contributed by Mayank Tyagi </script>",
"e": 29142,
"s": 28632,
"text": null
},
{
"code": null,
"e": 29153,
"s": 29142,
"text": "Output : "
},
{
"code": null,
"e": 29159,
"s": 29153,
"text": "Valid"
},
{
"code": null,
"e": 29176,
"s": 29161,
"text": "Koushik Mondal"
},
{
"code": null,
"e": 29189,
"s": 29176,
"text": "nitin mittal"
},
{
"code": null,
"e": 29205,
"s": 29189,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 29216,
"s": 29205,
"text": "gaurav4037"
},
{
"code": null,
"e": 29231,
"s": 29216,
"text": "adityakumar129"
},
{
"code": null,
"e": 29240,
"s": 29231,
"text": "triangle"
},
{
"code": null,
"e": 29250,
"s": 29240,
"text": "Geometric"
},
{
"code": null,
"e": 29269,
"s": 29250,
"text": "School Programming"
},
{
"code": null,
"e": 29279,
"s": 29269,
"text": "Geometric"
},
{
"code": null,
"e": 29377,
"s": 29279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29426,
"s": 29377,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 29484,
"s": 29426,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 29535,
"s": 29484,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 29584,
"s": 29535,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 29632,
"s": 29584,
"text": "Polygon Clipping | Sutherland–Hodgman Algorithm"
},
{
"code": null,
"e": 29650,
"s": 29632,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29666,
"s": 29650,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29685,
"s": 29666,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29710,
"s": 29685,
"text": "Reverse a string in Java"
}
]
|
Probability in a Weighted Coin-flip Game using Python and Numpy | by Michael Salmon | Towards Data Science | A short, fun one for this week:
Two players are playing a game where they flip a not necessarily fair coin, starting with Player 1. The first person to flip heads wins. The probability that a coin flipped lands on heads is p. What is the probability that Player 1 will win the game?
We can explore this problem with a simple function in python. Let’s write a function that takes in two arguments: 1.) the number of games to be played, and 2.) the probability that a coin flip will result in heads (set to a default of 0.5 or 50%).
Let’s call this function “P1_win_prob_weighted_coin_game”
We can simulate this game with the following code:
import numpy as npdef P1_win_prob_weighted_coin_game(num_games, prob_heads=.5): player_one_wins = 0 for n in range(0,num_games): num_flips = 0 win = 0 while win == 0: turn = np.random.uniform(0,1) num_flips += 1 if turn <= prob_heads: if num_flips % 2 != 0: player_one_wins += 1 win += 1 return float(player_one_wins)/float(num_games)
Now, let’s walk through this briefly step-by-step.
import numpy as npdef P1_win_prob_weighted_coin_game(num_games, prob_heads = 0.5): player_one_wins = 0
We begin by importing numpy, as we can utilize its random choice functionality to simulate the coin-flipping mechanism for this game.
We define the name of our function, and specify our two arguments. We’ll set a default probability of heads to 0.5, in case we simply want to specify a number of games using a fair coin to see what results. Obviously, we can enter custom probabilities here as we like.
We also set a global counter for the number of games won by Player 1, to begin at 0 for each round of simulations.
for n in range(0,num_games): num_flips = 0 win = 0 while win == 0: turn = np.random.uniform(0,1) num_flips += 1
Now, for every game in the specified number of simulations (e.g., range(0, num_games), we will count the number of coin flips starting from zero. This both keeps track of how the long the game has gone on, and will help us to determine who the winner is once a heads has been flipped.
We also specify a win condition “win” that will help us know when a game has been completed. While win remains equal to zero, the players continue to flip the coin. Each “turn” constitutes a flip of the coin, which is a randomly selected decimal value between 0 and 1. Each time a turn is taken, we add one to our num_flips counter.
if turn <= prob_heads: if num_flips % 2 != 0: player_one_wins += 1 win += 1
If the randomly chosen “turn” value is less than or equal to our set “prob_heads” value, we consider this a winning condition.
We can understand this in the following way: if the probability of flipping a heads is 0.6, than 60% of the values between 0 and 1 could be interpreted as a flip of heads (e.g., all of the values between 0.0 and 0.6).
Once the winning condition is met, we check how many times the coin has been flipped. Because player 1 always has the first flip, we know that an odd number of flips means that player 1 was the last player to go, and would therefore be the winner. If player 1 won the game, we add one to our player_one_wins counter at the top of the function. We also change the value of “win” to 1.0, which will break off the current game, and begin the next game in the preset number of simulations.
return float(player_one_wins)/float(num_games)
Once all simulations have been run, the function returns the number of games won by player 1 divided by the total number of games played. This will be expressed as a decimal win percentage.
Okay! Now that we have written our function, let’s play 50,000 games with a fair coin and see what results:
P1_win_prob_weighted_coin_game(50000)0.66848
Over 50,000 games, we see that player 1 has a distinct advantage by going first. In fact, player 1 has about a 2/3 chance of winning the game as a result of flipping first, even when using a fair coin.
What if we adjust the probability of the coin turning up heads? What if the coin has a 75% chance of coming up heads?
P1_win_prob_weighted_coin_game(50000, .75)0.80066
With a weighted coin coming up heads 75% of flips, player 1 would be expected to win about 80% of the time.
What if we really scale back the likelihood of a head appearing? Say, if heads only came up 1% of the time?
P1_win_prob_weighted_coin_game(50000, .01)0.50498
It’s only when we drastically cut back the likelihood of a heads turning up that both players have approximately the same chances of winning.
Fun stuff! Play around with the function as you like to see how different numbers of simulations and probabilities for heads effect the likelihood of player 1 winning.
Thanks for reading! | [
{
"code": null,
"e": 204,
"s": 172,
"text": "A short, fun one for this week:"
},
{
"code": null,
"e": 455,
"s": 204,
"text": "Two players are playing a game where they flip a not necessarily fair coin, starting with Player 1. The first person to flip heads wins. The probability that a coin flipped lands on heads is p. What is the probability that Player 1 will win the game?"
},
{
"code": null,
"e": 703,
"s": 455,
"text": "We can explore this problem with a simple function in python. Let’s write a function that takes in two arguments: 1.) the number of games to be played, and 2.) the probability that a coin flip will result in heads (set to a default of 0.5 or 50%)."
},
{
"code": null,
"e": 761,
"s": 703,
"text": "Let’s call this function “P1_win_prob_weighted_coin_game”"
},
{
"code": null,
"e": 812,
"s": 761,
"text": "We can simulate this game with the following code:"
},
{
"code": null,
"e": 1208,
"s": 812,
"text": "import numpy as npdef P1_win_prob_weighted_coin_game(num_games, prob_heads=.5): player_one_wins = 0 for n in range(0,num_games): num_flips = 0 win = 0 while win == 0: turn = np.random.uniform(0,1) num_flips += 1 if turn <= prob_heads: if num_flips % 2 != 0: player_one_wins += 1 win += 1 return float(player_one_wins)/float(num_games)"
},
{
"code": null,
"e": 1259,
"s": 1208,
"text": "Now, let’s walk through this briefly step-by-step."
},
{
"code": null,
"e": 1364,
"s": 1259,
"text": "import numpy as npdef P1_win_prob_weighted_coin_game(num_games, prob_heads = 0.5): player_one_wins = 0"
},
{
"code": null,
"e": 1498,
"s": 1364,
"text": "We begin by importing numpy, as we can utilize its random choice functionality to simulate the coin-flipping mechanism for this game."
},
{
"code": null,
"e": 1767,
"s": 1498,
"text": "We define the name of our function, and specify our two arguments. We’ll set a default probability of heads to 0.5, in case we simply want to specify a number of games using a fair coin to see what results. Obviously, we can enter custom probabilities here as we like."
},
{
"code": null,
"e": 1882,
"s": 1767,
"text": "We also set a global counter for the number of games won by Player 1, to begin at 0 for each round of simulations."
},
{
"code": null,
"e": 2029,
"s": 1882,
"text": " for n in range(0,num_games): num_flips = 0 win = 0 while win == 0: turn = np.random.uniform(0,1) num_flips += 1"
},
{
"code": null,
"e": 2314,
"s": 2029,
"text": "Now, for every game in the specified number of simulations (e.g., range(0, num_games), we will count the number of coin flips starting from zero. This both keeps track of how the long the game has gone on, and will help us to determine who the winner is once a heads has been flipped."
},
{
"code": null,
"e": 2647,
"s": 2314,
"text": "We also specify a win condition “win” that will help us know when a game has been completed. While win remains equal to zero, the players continue to flip the coin. Each “turn” constitutes a flip of the coin, which is a randomly selected decimal value between 0 and 1. Each time a turn is taken, we add one to our num_flips counter."
},
{
"code": null,
"e": 2763,
"s": 2647,
"text": " if turn <= prob_heads: if num_flips % 2 != 0: player_one_wins += 1 win += 1"
},
{
"code": null,
"e": 2890,
"s": 2763,
"text": "If the randomly chosen “turn” value is less than or equal to our set “prob_heads” value, we consider this a winning condition."
},
{
"code": null,
"e": 3108,
"s": 2890,
"text": "We can understand this in the following way: if the probability of flipping a heads is 0.6, than 60% of the values between 0 and 1 could be interpreted as a flip of heads (e.g., all of the values between 0.0 and 0.6)."
},
{
"code": null,
"e": 3594,
"s": 3108,
"text": "Once the winning condition is met, we check how many times the coin has been flipped. Because player 1 always has the first flip, we know that an odd number of flips means that player 1 was the last player to go, and would therefore be the winner. If player 1 won the game, we add one to our player_one_wins counter at the top of the function. We also change the value of “win” to 1.0, which will break off the current game, and begin the next game in the preset number of simulations."
},
{
"code": null,
"e": 3643,
"s": 3594,
"text": " return float(player_one_wins)/float(num_games)"
},
{
"code": null,
"e": 3833,
"s": 3643,
"text": "Once all simulations have been run, the function returns the number of games won by player 1 divided by the total number of games played. This will be expressed as a decimal win percentage."
},
{
"code": null,
"e": 3941,
"s": 3833,
"text": "Okay! Now that we have written our function, let’s play 50,000 games with a fair coin and see what results:"
},
{
"code": null,
"e": 3986,
"s": 3941,
"text": "P1_win_prob_weighted_coin_game(50000)0.66848"
},
{
"code": null,
"e": 4188,
"s": 3986,
"text": "Over 50,000 games, we see that player 1 has a distinct advantage by going first. In fact, player 1 has about a 2/3 chance of winning the game as a result of flipping first, even when using a fair coin."
},
{
"code": null,
"e": 4306,
"s": 4188,
"text": "What if we adjust the probability of the coin turning up heads? What if the coin has a 75% chance of coming up heads?"
},
{
"code": null,
"e": 4356,
"s": 4306,
"text": "P1_win_prob_weighted_coin_game(50000, .75)0.80066"
},
{
"code": null,
"e": 4464,
"s": 4356,
"text": "With a weighted coin coming up heads 75% of flips, player 1 would be expected to win about 80% of the time."
},
{
"code": null,
"e": 4572,
"s": 4464,
"text": "What if we really scale back the likelihood of a head appearing? Say, if heads only came up 1% of the time?"
},
{
"code": null,
"e": 4622,
"s": 4572,
"text": "P1_win_prob_weighted_coin_game(50000, .01)0.50498"
},
{
"code": null,
"e": 4764,
"s": 4622,
"text": "It’s only when we drastically cut back the likelihood of a heads turning up that both players have approximately the same chances of winning."
},
{
"code": null,
"e": 4932,
"s": 4764,
"text": "Fun stuff! Play around with the function as you like to see how different numbers of simulations and probabilities for heads effect the likelihood of player 1 winning."
}
]
|
Conda: Essential Concepts and Tips | by Giacomo Vianello | Towards Data Science | In this blog post, I will describe what conda is, and how to use it effectively, whether it is the first time you look at it or you are a seasoned user. While in the latter case many things will be known to you, you will still find some tricks you could use to improve your experience.
· Why conda· Entry-level examples· What is conda ∘ Conda and pip ∘ Conda Vs Anaconda Vs Miniconda· How to install conda ∘ Getting Miniconda· Installing packages, and environments ∘ The base environment ∘ Other environments ∘ The best way to use Jupyter and conda ∘ Removing environments ∘ Sharing an environment· Channels ∘ The conda-forge channel· Conda and pip· Conda is slow· Free up some disk space· Conda and docker· In-depth: RPATH and conda· Conclusions
Conda is for you if one or more of the following are true:
You spend way too much time installing and configuring software instead of focusing on the projects you need to work on
You invariably end up with a giant mess that you have to clear up and then restart from scratch
You want to be able to move your environments between machines
You need to install conflicting requirements for different projects on the same machine
You want a repeatable, trackable installation process that you can share across platforms and distributions, which could also include non-python packages
You just got a new machine (maybe with a GPU) and you want to get started quickly
You want to always experiment with the latest version of everything, but don’t want to deal with incompatibilities and figuring out which version goes with which version
You have multiple machines with different Linux distributions or even a mix of Linux/macOS/Windows, and you want the same environment across them
If any of this is true, conda is going to be very useful for you.
Let’s say you just got a new shiny machine with a GPU and you want to install the NVIDIA CUDA toolkit. Do you want to do this and spend the next 5–10 hours on the task, or you’d rather do this and be on your way?
> conda install -c conda-forge cudatoolkit=10.2
Do you want to install pytorch and jump on the Deep Learning bandwagon?
> conda install pytorch cudatoolkit=10.2 -c pytorch
Do you want to install Tensorflow and Pytorch in the same environment? It’s not madness, it’s just:
> conda install -c conda-forge -c pytorch python=3.8 cudatoolkit=10.2 pytorch pytorch tensorflow tensorboard
and much more. In general, most things are one conda install away. And, most importantly, if you mess up you just remove the environment and retry, no trace is left in your system.
I hope this gives you a hint of why conda is such an amazing tool. Let’s jump into it and learn (much) more about it.
Conda is a cross-platform, open-source package manager.
You are probably already using a package manager on your system. In Linux, you might have one or more of apt, yum or snap. In macOS you have homebrew or others. Conda is similar, but it is platform-independent. It is indeed available for Linux, Mac, and Windows and it works in the same way on all 3 platforms.
A common mistake is to compare conda with pip . They are similar, but also very different in a way: pip is a package manager centered around Python (after all the repository of pip packages is called the Python Package Index), while conda is language-agnostic. While pip packages do contain sometimes compiled libraries (for example, numpy, scipy, pandas...), in general, these are only supporting Python interfaces. Usingconda instead you can install C/C++ libraries, compilers, graphic libraries, full-fledged applications that have nothing to do with Python. You can even use conda to install GPU software like the NVIDIA CUDA toolkit, for example, or the go language, or npm, julia and so on. In other words, the conda ecosystem goes way beyond Python. Therefore conda is much more similar, as we said, to yum or homebrew than to pip. In fact, a typicalconda installation containspip as just another package, and you can install packages in your conda environment using pip (but see the caveats below before you do so).
As said above, conda is the package manager.
Anaconda is a collection of conda packages that contain most of the things that you are going to use on your daily job (including, of course, conda the package manager). Some people prefer it because it offers a nice graphical user interface to handle environments and packages instead of a command-line tool (CLI). I personally never use Anaconda, because I find it bloated and I don’t mind the CLI. I use instead Miniconda.
Miniconda is a barebone collection of packages: it contains python, the conda package manager as well as a few other packages (including pip). It does not have any Graphical User Interface, only the CLI. It is your starting point for building an environment that contains what you need, and nothing more. It is also super-useful for building Docker containers (see below). I personally only use Miniconda.
For this blog post, let’s focus on Miniconda and the CLI. This is by far the most common use case, but if you want to use Anaconda and its GUI, most of the things discussed apply there as well.
Go here and download the self-installing package appropriate for your system (Linux, Windows, or Mac). Save it somewhere.
Alternatively, run this command:
NOTE: all command line examples here will assume Linux and the bash shell. If you are on Mac and on bash, things will be identical. If you are using another shell there might be minimal changes. For example, in the following command, substitute Linux with MacOSX if you are on Mac. I won’t cover Windows, but it should be easy to translate the commands to the shell in Windows (or you can use the WSL
# Download Miniconda. You can also use wget or any other command # line download tool for this purpose> curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-installer.sh
Now go to wherever you downloaded the file, and install Miniconda by running:
# Add run permissions for current user> chmod u+x Miniconda3-installer.sh> ./Miniconda3-installer.sh -b -p ~/miniconda3
You can substitute -p ~/miniconda3 with any other prefix, however, it is generally a good idea to keep that prefix. For simplicity, the rest of the blog post will assume that path for Miniconda.
Congrats, you have installed Miniconda! Now let’s put it to use by adding it to the PATH environment variable and then activate it:
If you find conda useful, you might want to add these lines to your .bashrc file (or whatever your shell uses as init script) so you won’t have to do it for every new terminal.
> export PATH=${PATH}:~/miniconda3/bin# While you could use `conda activate` instead,# this way of activating is more portable> source ~/miniconda3/bin/activate
Note that we put the miniconda3 path at the end of the PATH env variable. This is a trick I use so that the presence of Miniconda is minimally invasive. For example, if now I run python when I did not activate conda, I will still get into the python interpreter installed in my system, and NOT the one that comes with Miniconda. If I had put the path at the beginning of the PATH env variable, I would instead get into the Miniconda python, whether I activate conda or not.
We are now ready to go, you should see something like:
(base) giacomo@fd4af0669a8:/#
The (base) part tells you that you are in the “base” environment and conda is ready for use.
WAIT! DO NOT install anything in the base environment. Read the next section first
Packages can be installed in two ways. One is obvious, i.e., using the command:
> conda install [name of the package]
In some cases, you need to add a channel specification (see the section about channels).
Another way is by creating environments and specifying packages during creation. Let’s look at that.
Environments are one of the most useful concepts in conda. They are self-contained installations: everything inside an environment only depends on things that are within that environment.
Well, not 100%, but 99.9%. You still depend on a few core libraries of your system likelibc on Linux, for example, but these are advanced details (described at the bottom). For all intent and purposes and for 99.9% of the users, the approximation I just said is a good way to think about environments.
Yes, they are conceptually similar to the virtual environments of python, but they can contain many more things than just python packages.
If you are interested in how this is achieved, look at the bottom of this post.
The documentation about environments contains all the details. Here I am summarizing the main points, as well as offering some tips and lessons learned.
The base environment gets created when you install Miniconda or Anaconda. It contains conda and packages that are needed for basic operations.
A typical beginner mistake is to install packages into the base environment. DO NOT DO THAT. Doing so will create conflicts with the other environments you are going to create.
The base environment should only contain conda, its dependencies, as well as conda-related things like conda-build or mamba (see below for what mamba is). Instead, you should always rely on other environments for any other software.
Since we don’t want to install anything in the base environment, the first thing is to create your go-to environment for day-to-day operations. For example, a standard data scientist environment could look like:
> conda create --name ds -c conda-forge python=3.8 matplotlib numpy scipy pandas jupyter jupyterlab seaborn
Conda will print a long list of packages, that are needed to make everything work. You can review the list, and then enter y to confirm. If you want to avoid that prompt, just add -y to the command line.
This will create a ds environment and will install packages at the same time.
TIP: if you already know that you are going to need some more packages, install them this way instead of relying on conda install later, so that conda will figure out the best combination of dependencies that fulfill your requirements upfront
As you might have guessed, you can add there whatever package you need, and chances are, you are going to find it in the conda-forge channel. We will get to what this means in a second.
You now need to activate this environment:
> conda activate ds
Since this is our go-to environment, you might want to add the line above to your .bashrc or whatever init script your shell runs, so that every time you open a shell you will find yourself in the ds environment.
From now on, if you run conda install [package] , the new package will be installed in the active environment.
You don’t need to stop here. Say you want to try the bleeding edge python 3.9 today, but you don’t want to disrupt your day-to-day operations. Easy enough, just create a different environment:
> conda deactivate> conda create --name py39 python=3.9 numpy scipy matplotlib> conda activate py39
The conda deactivate part deactivates the current environment and brings you back to the base environment, before creating and activating the next one. Here we also see how to specify explicit versions of packages, like in python=3.9.
TIP: always run conda deactivate before activating a new environment. This avoids weird problems for example with environment variables not being unset
Now, anything you install in the py39 environment is completely independent of what is inside the ds environment.
NOTE: after activating an environment, if you look at the $PATH environment variable (echo ${PATH}) you will see that conda activate prepend the path to the bin directory of the environment. That means that anything you install there have precedence on what is installed anywhere else on your system.
Similarly, you can use environments for installing say an older PyTorch version that you need to reproduce an old paper or to install the go language separately from your python environment, just to give a few examples.
At any moment, you can see a list of environments with:
> conda env list
If you use Jupyter in your day-to-day work (and who doesn’t?) there is an extension that you cannot miss: nb_conda_kernels. This simple extension allows you to control which environment to use for which notebook, from the Jupyter (notebook or lab) interface. You just need to install it in your default environment (what we called ds above) and then start Jupyter from your default environment:
> conda activate ds> conda install -c conda-forge jupyterlab nb_conda_kernels> jupyter lab
This is what you will get:
NOTE: you DO NOT need to install Jupyter in each environment, but you MUST install at least one kernel (for example, ipykernel for Python) in each environment. An environment without a kernel will not show up in the list of available environments in Jupyter.
If you want to delete an environment to free up some disk, or because you want to start from scratch, you can simply do:
> conda deactivate> conda uninstall --name py39 --all
This will completely remove the py39 environment and all its packages.
An environment can be replicated in multiple ways. It is important to understand the differences between them.
First, you need to activate your environment.
Then, if you are exporting to the same platform (say Linux to Linux), just do:
> conda env export > environment.yml
The environment.yml file is similar to a requirements.txt file for pip, if you know what I’m talking about. It contains every single package that is contained in your environment, including of course C/C++ libraries and the like. It can be used to recreate the environment on the same platform like this:
> conda env create -f environment.yml
A typical use case is to “develop” an environment on Linux and then export it this way to be recreated within a Linux Docker container. This gives you a guarantee of an exact replica, not only of the things you installed manually but also of all their dependencies. Some of these will be platform-dependent, which will make it difficult or impossible to replicate this environment on a different platform (say from Linux to macOS).
If instead, you want your environment to be replicable across platforms, export this way:
> conda env export --from-history > environment.yml
This version of the environment.yml file will only contain the packages that you explicitly installed during conda create or with conda install . When recreating the environment on a different platform (say, from Linux to Mac), conda will solve the dependencies of the packages listed in the environment file using what is available on the destination platform. Of course, you can use this environment file in the same way as before on the destination platform:
> conda env create -f environment.yml
A third option is a nuclear option: there is a way to package your entire environment in one binary file and unpack it at the destination (this of course only works within the same platform). This is very useful in some circumstances, most notably when using conda with PySpark. This is achieved using conda-pack, details here.
Conda packages are hosted remotely in channels, which are the equivalent of the repositories of yum or apt , for example. The default channels are used if you do not specify any -c parameter during conda install or conda create . Otherwise, the channels you specify are used. This means that conda will look for a certain package not only in the default channels but also in the one you specify. For example, a command like this:
> conda install -c pytorch torch
will look for the torch package in the pytorch channel as well as in the defaults channel. Then, the available versions will be compared with the rules explained here.
TIP: always turn on the strict channel policy. It makes conda faster, and helps to avoid conflicts. You can do it with conda config --set channel_priority strict
The conda-forge organization maintains a huge list of packages in the conda-forge channel. You can find the recipes to build these packages indexed on their website with links to GitHub. You can also easily contribute your own packages to conda-forge.
If you look around the net, there are lovers and haters of conda-forge. I am in the former category. However, you do need to know some important things to use it.
There are compatibility problems between conda-forge packages and packages contained in the default conda channels. Therefore, you should always set up channel_priority: strictas explained in the previous section and give priority to the conda-forge channel over the default channels when installing things or creating environments. There are two ways of doing that. Either you always specify conda install -c conda-forge or conda create -c conda-forge using always conda-forge as the first listed channel, OR, you create a .condarc file in your home with this content:
channels: - conda-forge - defaultschannel_priority: strict
An environment should either use conda-forge or not, from creation to destruction. Do not mix and match. If you created it without using the conda-forge channel, then do not add it to the mix halfway. In practice, I always create an environment with conda-forge unless in very specific cases where I found incompatibilities.
A third option is to define a bash function in your .bashrc like:
condaforge() { # $1 is the command, ${@:2} is every other parameter # Print the command before executing it echo "==>" conda "$1" -c conda-forge "${@:2}" conda "$1" -c conda-forge "${@:2}"}
and then use it to create environments and install packages:
> condaforge create --name test python=3.8
or
condaforge install numpy
This function will add the -c conda-forge channel to your conda installation commands.
TIP: sometimes it is hard to remember if a given environment was created using conda-forge. A simple trick is to always prepend cf to the environment name, like conda create --name cf_py39 -c conda-forge python=3.9 . Or, use conda list | grep pythonto see if python was installed from the conda-forge channel or not. In the former case, you will see something like:
python 3.8.5 h1103e12_7_cpython conda-forge
Conda and pip have been historically hard to combine. Things are much better these days, and in many cases, they just work out.
However, you should in general give precedence to one or the other. For example, normally you would give priority to conda, i.e., you try to install a package with conda first. If that’s not available, then use pip.
In some cases, you might want to do the opposite, by giving priority to pip. In that case, create an environment with just python+pip and nothing else, then use pip from that moment forward.
A compromise is to use conda to install the basics (numpy, scipy, matplotlib, jupyter...) as well as big dependencies with heavy compiled libraries like PyTorch, TensorFlow, the Cuda toolkit, OpenCV, or tricky and obscure packages like GDAL and rasterio. Install instead all python-only packages with pip. This is very unlikely to give you problems.
Note that if you are installing with pip a package that depends on say numpy, and you already installed numpy with conda, pip will recognize it and it will NOT install it again (unless there is a conflict of versions). This is why most of the time things just work.
Finally, notice that when you export an environment as explained above, the environment file does contain all the pip-installed packages as well as the conda-installed ones, so using pip in a conda environment does NOT prevent its sharing.
One of the most common complaints about conda is that the package solver is slow. This is unfortunately true, although it is getting better with time. A very cool alternative just came out, and it is called mamba (see here).
Mamba is a drop-in replacement for conda installation procedures, so you can use mamba installinstead of conda install and mamba create instead of conda create . You will get the same results in a much much faster way. Pretty cool!
You need to install mamba in your base environment:
> conda deactivate# Make sure your prompt says (base)> conda install mamba
After a while, you will notice that your miniconda directory starts to be very big. The main reason is that conda keeps archives of all the packages that you ever downloaded. You can easily and safely clean these up with:
conda clean --all
and free up some space.
You can use Miniconda to install an environment when building a Docker container (i.e., within the Dockerfile). There are a few good reasons as to why thighs might be a good idea in some situations:
You can use an environment file and replicate exactly your development environment. This is a quick and easy way to ensure that what you develop will find the same dependencies you used during developmentYou can install things from conda-forge, for example. This allows you to install things even when the distribution you are using in the container (the base image) does not have the package you needThere are readily-available images on Docker Hub that contain already conda pre-installed: https://hub.docker.com/r/continuumio/miniconda3, so using conda is very convenient and doesn’t add much complexityYou can install and run packages without having to be root , which sometimes is better from a security perspective, especially if these packages start web services, for example
You can use an environment file and replicate exactly your development environment. This is a quick and easy way to ensure that what you develop will find the same dependencies you used during development
You can install things from conda-forge, for example. This allows you to install things even when the distribution you are using in the container (the base image) does not have the package you need
There are readily-available images on Docker Hub that contain already conda pre-installed: https://hub.docker.com/r/continuumio/miniconda3, so using conda is very convenient and doesn’t add much complexity
You can install and run packages without having to be root , which sometimes is better from a security perspective, especially if these packages start web services, for example
Note that in your Dockerfile you should run conda clean --all -y at the end of your installation command to remove useless archives that would waste image space.
You absolutely don’t need to know this, but if you are curious as to how conda achieves independent environments even in the case of compiled libraries, here it is.
When you compile a C/C++ or a FORTRAN package or some other compiled library/executable you can link the libraries you depend on statically, or dynamically. Most modern applications are compiled with dynamic links. This means that at runtime the system needs to look into your executable or your library, understand what other libraries it depends on, and find them in your system (dynamic linking).
The system has some predefined places where it looks for these libraries, and it maintains a cache of those paths. For example, on Linux, these are places like /lib or /usr/lib and so on. You can see a list of all the libraries known to a Linux system with:
> ldconfig --verbose
macOS has a similar system. Now if we take an executable or a library, we can see which other libraries it depends on. For example, this prints the libraries that my system vimdepends on:
> ldd /usr/bin/vim linux-vdso.so.1 libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 libtinfo.so.6 => /lib/x86_64-linux-gnu/libtinfo.so.6 libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 libpython3.8.so.1.0 => /lib/x86_64-linux-gnu/libpython3.8.so.1.0 libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 /lib64/ld-linux-x86-64.so.2 libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1
As expected, these are all system libraries. If I do the same on a conda vim:
> conda install -c conda-forge -y vim> ldd ${CONDA_PREFIX}/bin/vim linux-vdso.so.1 libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 libtinfo.so.6 => /root/miniconda3/envs/py39/bin/../lib/libtinfo.so.6 libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 libpython3.9.so.1.0 => /root/miniconda3/envs/py39/bin/../lib/libpython3.9.so.1.0 libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 /lib64/ld-linux-x86-64.so.2 libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1
we can see that now the linker found libtinfo andlibpython in the conda environment instead, even though they are available in the system /lib . Why? Because vim in conda has been compiled using RPATH, i.e., the path is hardcoded in the executable and it points to the conda environment.
This means that the vim I installed in this particular environment only links to libraries in the same environment, so I can have a different vim in a different environment or in my system somewhere with incompatible versions and things work just fine, without any conflict.
You can also note however that we still depend on some basic system libraries like linux-vdso (an interface to some kernel functionalities), libc and so on. These cannot be shipped with conda. This is also why conda environments are not as independent from the system as Docker containers. However, these system libraries are guaranteed to be backward compatible, and they provide the same interface on any Linux distribution, so they are unlikely to cause any problem.
The same is true for macOS, even though the system libraries are different.
You can even see the RPATH setting that conda uses right there in your environment. Every time you do a conda activate and activate an environment, conda sets some environment variables:
CONDA_PREFIX: the path to the root of the active conda environmentLDFLAGS: this is a standard env variable that is read by the linker at compile time. If you look into it you will see the RPATH setting. For example, on my laptop I see:
CONDA_PREFIX: the path to the root of the active conda environment
LDFLAGS: this is a standard env variable that is read by the linker at compile time. If you look into it you will see the RPATH setting. For example, on my laptop I see:
(ds) giacomov@gr723gad9:~$ echo $LDFLAGS-Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -Wl,-rpath,/home/user/miniconda3/envs/ds/lib -Wl,-rpath-link,/home/user/miniconda3/envs/ds/lib -L/home/user/miniconda3/envs/ds/lib
The -rpath flag instructs the linker to hardcode that path as the RPATH in any executable. This means that you compile an executable or a library while an environment is active, it will have the RPATH setting in it. This is the basis of how conda-build works, but that’s for another day.
3. CXXFLAGS, CFLAGS: specific flags for C compilers, including the path to the headers in the conda environment
While there is certainly more to say, this post is long enough as it is. I hope you got useful information out of this, whether you are a beginner or not. Feel free to leave a comment and to ask questions. | [
{
"code": null,
"e": 458,
"s": 172,
"text": "In this blog post, I will describe what conda is, and how to use it effectively, whether it is the first time you look at it or you are a seasoned user. While in the latter case many things will be known to you, you will still find some tricks you could use to improve your experience."
},
{
"code": null,
"e": 919,
"s": 458,
"text": "· Why conda· Entry-level examples· What is conda ∘ Conda and pip ∘ Conda Vs Anaconda Vs Miniconda· How to install conda ∘ Getting Miniconda· Installing packages, and environments ∘ The base environment ∘ Other environments ∘ The best way to use Jupyter and conda ∘ Removing environments ∘ Sharing an environment· Channels ∘ The conda-forge channel· Conda and pip· Conda is slow· Free up some disk space· Conda and docker· In-depth: RPATH and conda· Conclusions"
},
{
"code": null,
"e": 978,
"s": 919,
"text": "Conda is for you if one or more of the following are true:"
},
{
"code": null,
"e": 1098,
"s": 978,
"text": "You spend way too much time installing and configuring software instead of focusing on the projects you need to work on"
},
{
"code": null,
"e": 1194,
"s": 1098,
"text": "You invariably end up with a giant mess that you have to clear up and then restart from scratch"
},
{
"code": null,
"e": 1257,
"s": 1194,
"text": "You want to be able to move your environments between machines"
},
{
"code": null,
"e": 1345,
"s": 1257,
"text": "You need to install conflicting requirements for different projects on the same machine"
},
{
"code": null,
"e": 1499,
"s": 1345,
"text": "You want a repeatable, trackable installation process that you can share across platforms and distributions, which could also include non-python packages"
},
{
"code": null,
"e": 1581,
"s": 1499,
"text": "You just got a new machine (maybe with a GPU) and you want to get started quickly"
},
{
"code": null,
"e": 1751,
"s": 1581,
"text": "You want to always experiment with the latest version of everything, but don’t want to deal with incompatibilities and figuring out which version goes with which version"
},
{
"code": null,
"e": 1897,
"s": 1751,
"text": "You have multiple machines with different Linux distributions or even a mix of Linux/macOS/Windows, and you want the same environment across them"
},
{
"code": null,
"e": 1963,
"s": 1897,
"text": "If any of this is true, conda is going to be very useful for you."
},
{
"code": null,
"e": 2176,
"s": 1963,
"text": "Let’s say you just got a new shiny machine with a GPU and you want to install the NVIDIA CUDA toolkit. Do you want to do this and spend the next 5–10 hours on the task, or you’d rather do this and be on your way?"
},
{
"code": null,
"e": 2224,
"s": 2176,
"text": "> conda install -c conda-forge cudatoolkit=10.2"
},
{
"code": null,
"e": 2296,
"s": 2224,
"text": "Do you want to install pytorch and jump on the Deep Learning bandwagon?"
},
{
"code": null,
"e": 2348,
"s": 2296,
"text": "> conda install pytorch cudatoolkit=10.2 -c pytorch"
},
{
"code": null,
"e": 2448,
"s": 2348,
"text": "Do you want to install Tensorflow and Pytorch in the same environment? It’s not madness, it’s just:"
},
{
"code": null,
"e": 2557,
"s": 2448,
"text": "> conda install -c conda-forge -c pytorch python=3.8 cudatoolkit=10.2 pytorch pytorch tensorflow tensorboard"
},
{
"code": null,
"e": 2738,
"s": 2557,
"text": "and much more. In general, most things are one conda install away. And, most importantly, if you mess up you just remove the environment and retry, no trace is left in your system."
},
{
"code": null,
"e": 2856,
"s": 2738,
"text": "I hope this gives you a hint of why conda is such an amazing tool. Let’s jump into it and learn (much) more about it."
},
{
"code": null,
"e": 2912,
"s": 2856,
"text": "Conda is a cross-platform, open-source package manager."
},
{
"code": null,
"e": 3223,
"s": 2912,
"text": "You are probably already using a package manager on your system. In Linux, you might have one or more of apt, yum or snap. In macOS you have homebrew or others. Conda is similar, but it is platform-independent. It is indeed available for Linux, Mac, and Windows and it works in the same way on all 3 platforms."
},
{
"code": null,
"e": 4247,
"s": 3223,
"text": "A common mistake is to compare conda with pip . They are similar, but also very different in a way: pip is a package manager centered around Python (after all the repository of pip packages is called the Python Package Index), while conda is language-agnostic. While pip packages do contain sometimes compiled libraries (for example, numpy, scipy, pandas...), in general, these are only supporting Python interfaces. Usingconda instead you can install C/C++ libraries, compilers, graphic libraries, full-fledged applications that have nothing to do with Python. You can even use conda to install GPU software like the NVIDIA CUDA toolkit, for example, or the go language, or npm, julia and so on. In other words, the conda ecosystem goes way beyond Python. Therefore conda is much more similar, as we said, to yum or homebrew than to pip. In fact, a typicalconda installation containspip as just another package, and you can install packages in your conda environment using pip (but see the caveats below before you do so)."
},
{
"code": null,
"e": 4292,
"s": 4247,
"text": "As said above, conda is the package manager."
},
{
"code": null,
"e": 4718,
"s": 4292,
"text": "Anaconda is a collection of conda packages that contain most of the things that you are going to use on your daily job (including, of course, conda the package manager). Some people prefer it because it offers a nice graphical user interface to handle environments and packages instead of a command-line tool (CLI). I personally never use Anaconda, because I find it bloated and I don’t mind the CLI. I use instead Miniconda."
},
{
"code": null,
"e": 5124,
"s": 4718,
"text": "Miniconda is a barebone collection of packages: it contains python, the conda package manager as well as a few other packages (including pip). It does not have any Graphical User Interface, only the CLI. It is your starting point for building an environment that contains what you need, and nothing more. It is also super-useful for building Docker containers (see below). I personally only use Miniconda."
},
{
"code": null,
"e": 5318,
"s": 5124,
"text": "For this blog post, let’s focus on Miniconda and the CLI. This is by far the most common use case, but if you want to use Anaconda and its GUI, most of the things discussed apply there as well."
},
{
"code": null,
"e": 5440,
"s": 5318,
"text": "Go here and download the self-installing package appropriate for your system (Linux, Windows, or Mac). Save it somewhere."
},
{
"code": null,
"e": 5473,
"s": 5440,
"text": "Alternatively, run this command:"
},
{
"code": null,
"e": 5874,
"s": 5473,
"text": "NOTE: all command line examples here will assume Linux and the bash shell. If you are on Mac and on bash, things will be identical. If you are using another shell there might be minimal changes. For example, in the following command, substitute Linux with MacOSX if you are on Mac. I won’t cover Windows, but it should be easy to translate the commands to the shell in Windows (or you can use the WSL"
},
{
"code": null,
"e": 6079,
"s": 5874,
"text": "# Download Miniconda. You can also use wget or any other command # line download tool for this purpose> curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-installer.sh"
},
{
"code": null,
"e": 6157,
"s": 6079,
"text": "Now go to wherever you downloaded the file, and install Miniconda by running:"
},
{
"code": null,
"e": 6277,
"s": 6157,
"text": "# Add run permissions for current user> chmod u+x Miniconda3-installer.sh> ./Miniconda3-installer.sh -b -p ~/miniconda3"
},
{
"code": null,
"e": 6472,
"s": 6277,
"text": "You can substitute -p ~/miniconda3 with any other prefix, however, it is generally a good idea to keep that prefix. For simplicity, the rest of the blog post will assume that path for Miniconda."
},
{
"code": null,
"e": 6604,
"s": 6472,
"text": "Congrats, you have installed Miniconda! Now let’s put it to use by adding it to the PATH environment variable and then activate it:"
},
{
"code": null,
"e": 6781,
"s": 6604,
"text": "If you find conda useful, you might want to add these lines to your .bashrc file (or whatever your shell uses as init script) so you won’t have to do it for every new terminal."
},
{
"code": null,
"e": 6942,
"s": 6781,
"text": "> export PATH=${PATH}:~/miniconda3/bin# While you could use `conda activate` instead,# this way of activating is more portable> source ~/miniconda3/bin/activate"
},
{
"code": null,
"e": 7416,
"s": 6942,
"text": "Note that we put the miniconda3 path at the end of the PATH env variable. This is a trick I use so that the presence of Miniconda is minimally invasive. For example, if now I run python when I did not activate conda, I will still get into the python interpreter installed in my system, and NOT the one that comes with Miniconda. If I had put the path at the beginning of the PATH env variable, I would instead get into the Miniconda python, whether I activate conda or not."
},
{
"code": null,
"e": 7471,
"s": 7416,
"text": "We are now ready to go, you should see something like:"
},
{
"code": null,
"e": 7501,
"s": 7471,
"text": "(base) giacomo@fd4af0669a8:/#"
},
{
"code": null,
"e": 7594,
"s": 7501,
"text": "The (base) part tells you that you are in the “base” environment and conda is ready for use."
},
{
"code": null,
"e": 7677,
"s": 7594,
"text": "WAIT! DO NOT install anything in the base environment. Read the next section first"
},
{
"code": null,
"e": 7757,
"s": 7677,
"text": "Packages can be installed in two ways. One is obvious, i.e., using the command:"
},
{
"code": null,
"e": 7795,
"s": 7757,
"text": "> conda install [name of the package]"
},
{
"code": null,
"e": 7884,
"s": 7795,
"text": "In some cases, you need to add a channel specification (see the section about channels)."
},
{
"code": null,
"e": 7985,
"s": 7884,
"text": "Another way is by creating environments and specifying packages during creation. Let’s look at that."
},
{
"code": null,
"e": 8173,
"s": 7985,
"text": "Environments are one of the most useful concepts in conda. They are self-contained installations: everything inside an environment only depends on things that are within that environment."
},
{
"code": null,
"e": 8475,
"s": 8173,
"text": "Well, not 100%, but 99.9%. You still depend on a few core libraries of your system likelibc on Linux, for example, but these are advanced details (described at the bottom). For all intent and purposes and for 99.9% of the users, the approximation I just said is a good way to think about environments."
},
{
"code": null,
"e": 8614,
"s": 8475,
"text": "Yes, they are conceptually similar to the virtual environments of python, but they can contain many more things than just python packages."
},
{
"code": null,
"e": 8694,
"s": 8614,
"text": "If you are interested in how this is achieved, look at the bottom of this post."
},
{
"code": null,
"e": 8847,
"s": 8694,
"text": "The documentation about environments contains all the details. Here I am summarizing the main points, as well as offering some tips and lessons learned."
},
{
"code": null,
"e": 8990,
"s": 8847,
"text": "The base environment gets created when you install Miniconda or Anaconda. It contains conda and packages that are needed for basic operations."
},
{
"code": null,
"e": 9167,
"s": 8990,
"text": "A typical beginner mistake is to install packages into the base environment. DO NOT DO THAT. Doing so will create conflicts with the other environments you are going to create."
},
{
"code": null,
"e": 9400,
"s": 9167,
"text": "The base environment should only contain conda, its dependencies, as well as conda-related things like conda-build or mamba (see below for what mamba is). Instead, you should always rely on other environments for any other software."
},
{
"code": null,
"e": 9612,
"s": 9400,
"text": "Since we don’t want to install anything in the base environment, the first thing is to create your go-to environment for day-to-day operations. For example, a standard data scientist environment could look like:"
},
{
"code": null,
"e": 9720,
"s": 9612,
"text": "> conda create --name ds -c conda-forge python=3.8 matplotlib numpy scipy pandas jupyter jupyterlab seaborn"
},
{
"code": null,
"e": 9924,
"s": 9720,
"text": "Conda will print a long list of packages, that are needed to make everything work. You can review the list, and then enter y to confirm. If you want to avoid that prompt, just add -y to the command line."
},
{
"code": null,
"e": 10002,
"s": 9924,
"text": "This will create a ds environment and will install packages at the same time."
},
{
"code": null,
"e": 10245,
"s": 10002,
"text": "TIP: if you already know that you are going to need some more packages, install them this way instead of relying on conda install later, so that conda will figure out the best combination of dependencies that fulfill your requirements upfront"
},
{
"code": null,
"e": 10431,
"s": 10245,
"text": "As you might have guessed, you can add there whatever package you need, and chances are, you are going to find it in the conda-forge channel. We will get to what this means in a second."
},
{
"code": null,
"e": 10474,
"s": 10431,
"text": "You now need to activate this environment:"
},
{
"code": null,
"e": 10494,
"s": 10474,
"text": "> conda activate ds"
},
{
"code": null,
"e": 10707,
"s": 10494,
"text": "Since this is our go-to environment, you might want to add the line above to your .bashrc or whatever init script your shell runs, so that every time you open a shell you will find yourself in the ds environment."
},
{
"code": null,
"e": 10818,
"s": 10707,
"text": "From now on, if you run conda install [package] , the new package will be installed in the active environment."
},
{
"code": null,
"e": 11011,
"s": 10818,
"text": "You don’t need to stop here. Say you want to try the bleeding edge python 3.9 today, but you don’t want to disrupt your day-to-day operations. Easy enough, just create a different environment:"
},
{
"code": null,
"e": 11111,
"s": 11011,
"text": "> conda deactivate> conda create --name py39 python=3.9 numpy scipy matplotlib> conda activate py39"
},
{
"code": null,
"e": 11346,
"s": 11111,
"text": "The conda deactivate part deactivates the current environment and brings you back to the base environment, before creating and activating the next one. Here we also see how to specify explicit versions of packages, like in python=3.9."
},
{
"code": null,
"e": 11498,
"s": 11346,
"text": "TIP: always run conda deactivate before activating a new environment. This avoids weird problems for example with environment variables not being unset"
},
{
"code": null,
"e": 11612,
"s": 11498,
"text": "Now, anything you install in the py39 environment is completely independent of what is inside the ds environment."
},
{
"code": null,
"e": 11913,
"s": 11612,
"text": "NOTE: after activating an environment, if you look at the $PATH environment variable (echo ${PATH}) you will see that conda activate prepend the path to the bin directory of the environment. That means that anything you install there have precedence on what is installed anywhere else on your system."
},
{
"code": null,
"e": 12133,
"s": 11913,
"text": "Similarly, you can use environments for installing say an older PyTorch version that you need to reproduce an old paper or to install the go language separately from your python environment, just to give a few examples."
},
{
"code": null,
"e": 12189,
"s": 12133,
"text": "At any moment, you can see a list of environments with:"
},
{
"code": null,
"e": 12206,
"s": 12189,
"text": "> conda env list"
},
{
"code": null,
"e": 12601,
"s": 12206,
"text": "If you use Jupyter in your day-to-day work (and who doesn’t?) there is an extension that you cannot miss: nb_conda_kernels. This simple extension allows you to control which environment to use for which notebook, from the Jupyter (notebook or lab) interface. You just need to install it in your default environment (what we called ds above) and then start Jupyter from your default environment:"
},
{
"code": null,
"e": 12692,
"s": 12601,
"text": "> conda activate ds> conda install -c conda-forge jupyterlab nb_conda_kernels> jupyter lab"
},
{
"code": null,
"e": 12719,
"s": 12692,
"text": "This is what you will get:"
},
{
"code": null,
"e": 12978,
"s": 12719,
"text": "NOTE: you DO NOT need to install Jupyter in each environment, but you MUST install at least one kernel (for example, ipykernel for Python) in each environment. An environment without a kernel will not show up in the list of available environments in Jupyter."
},
{
"code": null,
"e": 13099,
"s": 12978,
"text": "If you want to delete an environment to free up some disk, or because you want to start from scratch, you can simply do:"
},
{
"code": null,
"e": 13153,
"s": 13099,
"text": "> conda deactivate> conda uninstall --name py39 --all"
},
{
"code": null,
"e": 13224,
"s": 13153,
"text": "This will completely remove the py39 environment and all its packages."
},
{
"code": null,
"e": 13335,
"s": 13224,
"text": "An environment can be replicated in multiple ways. It is important to understand the differences between them."
},
{
"code": null,
"e": 13381,
"s": 13335,
"text": "First, you need to activate your environment."
},
{
"code": null,
"e": 13460,
"s": 13381,
"text": "Then, if you are exporting to the same platform (say Linux to Linux), just do:"
},
{
"code": null,
"e": 13497,
"s": 13460,
"text": "> conda env export > environment.yml"
},
{
"code": null,
"e": 13802,
"s": 13497,
"text": "The environment.yml file is similar to a requirements.txt file for pip, if you know what I’m talking about. It contains every single package that is contained in your environment, including of course C/C++ libraries and the like. It can be used to recreate the environment on the same platform like this:"
},
{
"code": null,
"e": 13840,
"s": 13802,
"text": "> conda env create -f environment.yml"
},
{
"code": null,
"e": 14272,
"s": 13840,
"text": "A typical use case is to “develop” an environment on Linux and then export it this way to be recreated within a Linux Docker container. This gives you a guarantee of an exact replica, not only of the things you installed manually but also of all their dependencies. Some of these will be platform-dependent, which will make it difficult or impossible to replicate this environment on a different platform (say from Linux to macOS)."
},
{
"code": null,
"e": 14362,
"s": 14272,
"text": "If instead, you want your environment to be replicable across platforms, export this way:"
},
{
"code": null,
"e": 14414,
"s": 14362,
"text": "> conda env export --from-history > environment.yml"
},
{
"code": null,
"e": 14876,
"s": 14414,
"text": "This version of the environment.yml file will only contain the packages that you explicitly installed during conda create or with conda install . When recreating the environment on a different platform (say, from Linux to Mac), conda will solve the dependencies of the packages listed in the environment file using what is available on the destination platform. Of course, you can use this environment file in the same way as before on the destination platform:"
},
{
"code": null,
"e": 14914,
"s": 14876,
"text": "> conda env create -f environment.yml"
},
{
"code": null,
"e": 15242,
"s": 14914,
"text": "A third option is a nuclear option: there is a way to package your entire environment in one binary file and unpack it at the destination (this of course only works within the same platform). This is very useful in some circumstances, most notably when using conda with PySpark. This is achieved using conda-pack, details here."
},
{
"code": null,
"e": 15672,
"s": 15242,
"text": "Conda packages are hosted remotely in channels, which are the equivalent of the repositories of yum or apt , for example. The default channels are used if you do not specify any -c parameter during conda install or conda create . Otherwise, the channels you specify are used. This means that conda will look for a certain package not only in the default channels but also in the one you specify. For example, a command like this:"
},
{
"code": null,
"e": 15705,
"s": 15672,
"text": "> conda install -c pytorch torch"
},
{
"code": null,
"e": 15873,
"s": 15705,
"text": "will look for the torch package in the pytorch channel as well as in the defaults channel. Then, the available versions will be compared with the rules explained here."
},
{
"code": null,
"e": 16035,
"s": 15873,
"text": "TIP: always turn on the strict channel policy. It makes conda faster, and helps to avoid conflicts. You can do it with conda config --set channel_priority strict"
},
{
"code": null,
"e": 16287,
"s": 16035,
"text": "The conda-forge organization maintains a huge list of packages in the conda-forge channel. You can find the recipes to build these packages indexed on their website with links to GitHub. You can also easily contribute your own packages to conda-forge."
},
{
"code": null,
"e": 16450,
"s": 16287,
"text": "If you look around the net, there are lovers and haters of conda-forge. I am in the former category. However, you do need to know some important things to use it."
},
{
"code": null,
"e": 17020,
"s": 16450,
"text": "There are compatibility problems between conda-forge packages and packages contained in the default conda channels. Therefore, you should always set up channel_priority: strictas explained in the previous section and give priority to the conda-forge channel over the default channels when installing things or creating environments. There are two ways of doing that. Either you always specify conda install -c conda-forge or conda create -c conda-forge using always conda-forge as the first listed channel, OR, you create a .condarc file in your home with this content:"
},
{
"code": null,
"e": 17081,
"s": 17020,
"text": "channels: - conda-forge - defaultschannel_priority: strict"
},
{
"code": null,
"e": 17406,
"s": 17081,
"text": "An environment should either use conda-forge or not, from creation to destruction. Do not mix and match. If you created it without using the conda-forge channel, then do not add it to the mix halfway. In practice, I always create an environment with conda-forge unless in very specific cases where I found incompatibilities."
},
{
"code": null,
"e": 17472,
"s": 17406,
"text": "A third option is to define a bash function in your .bashrc like:"
},
{
"code": null,
"e": 17678,
"s": 17472,
"text": "condaforge() { # $1 is the command, ${@:2} is every other parameter # Print the command before executing it echo \"==>\" conda \"$1\" -c conda-forge \"${@:2}\" conda \"$1\" -c conda-forge \"${@:2}\"}"
},
{
"code": null,
"e": 17739,
"s": 17678,
"text": "and then use it to create environments and install packages:"
},
{
"code": null,
"e": 17782,
"s": 17739,
"text": "> condaforge create --name test python=3.8"
},
{
"code": null,
"e": 17785,
"s": 17782,
"text": "or"
},
{
"code": null,
"e": 17810,
"s": 17785,
"text": "condaforge install numpy"
},
{
"code": null,
"e": 17897,
"s": 17810,
"text": "This function will add the -c conda-forge channel to your conda installation commands."
},
{
"code": null,
"e": 18263,
"s": 17897,
"text": "TIP: sometimes it is hard to remember if a given environment was created using conda-forge. A simple trick is to always prepend cf to the environment name, like conda create --name cf_py39 -c conda-forge python=3.9 . Or, use conda list | grep pythonto see if python was installed from the conda-forge channel or not. In the former case, you will see something like:"
},
{
"code": null,
"e": 18320,
"s": 18263,
"text": "python 3.8.5 h1103e12_7_cpython conda-forge"
},
{
"code": null,
"e": 18448,
"s": 18320,
"text": "Conda and pip have been historically hard to combine. Things are much better these days, and in many cases, they just work out."
},
{
"code": null,
"e": 18664,
"s": 18448,
"text": "However, you should in general give precedence to one or the other. For example, normally you would give priority to conda, i.e., you try to install a package with conda first. If that’s not available, then use pip."
},
{
"code": null,
"e": 18855,
"s": 18664,
"text": "In some cases, you might want to do the opposite, by giving priority to pip. In that case, create an environment with just python+pip and nothing else, then use pip from that moment forward."
},
{
"code": null,
"e": 19205,
"s": 18855,
"text": "A compromise is to use conda to install the basics (numpy, scipy, matplotlib, jupyter...) as well as big dependencies with heavy compiled libraries like PyTorch, TensorFlow, the Cuda toolkit, OpenCV, or tricky and obscure packages like GDAL and rasterio. Install instead all python-only packages with pip. This is very unlikely to give you problems."
},
{
"code": null,
"e": 19471,
"s": 19205,
"text": "Note that if you are installing with pip a package that depends on say numpy, and you already installed numpy with conda, pip will recognize it and it will NOT install it again (unless there is a conflict of versions). This is why most of the time things just work."
},
{
"code": null,
"e": 19711,
"s": 19471,
"text": "Finally, notice that when you export an environment as explained above, the environment file does contain all the pip-installed packages as well as the conda-installed ones, so using pip in a conda environment does NOT prevent its sharing."
},
{
"code": null,
"e": 19936,
"s": 19711,
"text": "One of the most common complaints about conda is that the package solver is slow. This is unfortunately true, although it is getting better with time. A very cool alternative just came out, and it is called mamba (see here)."
},
{
"code": null,
"e": 20168,
"s": 19936,
"text": "Mamba is a drop-in replacement for conda installation procedures, so you can use mamba installinstead of conda install and mamba create instead of conda create . You will get the same results in a much much faster way. Pretty cool!"
},
{
"code": null,
"e": 20220,
"s": 20168,
"text": "You need to install mamba in your base environment:"
},
{
"code": null,
"e": 20295,
"s": 20220,
"text": "> conda deactivate# Make sure your prompt says (base)> conda install mamba"
},
{
"code": null,
"e": 20517,
"s": 20295,
"text": "After a while, you will notice that your miniconda directory starts to be very big. The main reason is that conda keeps archives of all the packages that you ever downloaded. You can easily and safely clean these up with:"
},
{
"code": null,
"e": 20535,
"s": 20517,
"text": "conda clean --all"
},
{
"code": null,
"e": 20559,
"s": 20535,
"text": "and free up some space."
},
{
"code": null,
"e": 20758,
"s": 20559,
"text": "You can use Miniconda to install an environment when building a Docker container (i.e., within the Dockerfile). There are a few good reasons as to why thighs might be a good idea in some situations:"
},
{
"code": null,
"e": 21541,
"s": 20758,
"text": "You can use an environment file and replicate exactly your development environment. This is a quick and easy way to ensure that what you develop will find the same dependencies you used during developmentYou can install things from conda-forge, for example. This allows you to install things even when the distribution you are using in the container (the base image) does not have the package you needThere are readily-available images on Docker Hub that contain already conda pre-installed: https://hub.docker.com/r/continuumio/miniconda3, so using conda is very convenient and doesn’t add much complexityYou can install and run packages without having to be root , which sometimes is better from a security perspective, especially if these packages start web services, for example"
},
{
"code": null,
"e": 21746,
"s": 21541,
"text": "You can use an environment file and replicate exactly your development environment. This is a quick and easy way to ensure that what you develop will find the same dependencies you used during development"
},
{
"code": null,
"e": 21944,
"s": 21746,
"text": "You can install things from conda-forge, for example. This allows you to install things even when the distribution you are using in the container (the base image) does not have the package you need"
},
{
"code": null,
"e": 22150,
"s": 21944,
"text": "There are readily-available images on Docker Hub that contain already conda pre-installed: https://hub.docker.com/r/continuumio/miniconda3, so using conda is very convenient and doesn’t add much complexity"
},
{
"code": null,
"e": 22327,
"s": 22150,
"text": "You can install and run packages without having to be root , which sometimes is better from a security perspective, especially if these packages start web services, for example"
},
{
"code": null,
"e": 22489,
"s": 22327,
"text": "Note that in your Dockerfile you should run conda clean --all -y at the end of your installation command to remove useless archives that would waste image space."
},
{
"code": null,
"e": 22654,
"s": 22489,
"text": "You absolutely don’t need to know this, but if you are curious as to how conda achieves independent environments even in the case of compiled libraries, here it is."
},
{
"code": null,
"e": 23054,
"s": 22654,
"text": "When you compile a C/C++ or a FORTRAN package or some other compiled library/executable you can link the libraries you depend on statically, or dynamically. Most modern applications are compiled with dynamic links. This means that at runtime the system needs to look into your executable or your library, understand what other libraries it depends on, and find them in your system (dynamic linking)."
},
{
"code": null,
"e": 23312,
"s": 23054,
"text": "The system has some predefined places where it looks for these libraries, and it maintains a cache of those paths. For example, on Linux, these are places like /lib or /usr/lib and so on. You can see a list of all the libraries known to a Linux system with:"
},
{
"code": null,
"e": 23333,
"s": 23312,
"text": "> ldconfig --verbose"
},
{
"code": null,
"e": 23521,
"s": 23333,
"text": "macOS has a similar system. Now if we take an executable or a library, we can see which other libraries it depends on. For example, this prints the libraries that my system vimdepends on:"
},
{
"code": null,
"e": 23952,
"s": 23521,
"text": "> ldd /usr/bin/vim linux-vdso.so.1 libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 libtinfo.so.6 => /lib/x86_64-linux-gnu/libtinfo.so.6 libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 libpython3.8.so.1.0 => /lib/x86_64-linux-gnu/libpython3.8.so.1.0 libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 /lib64/ld-linux-x86-64.so.2 libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1 "
},
{
"code": null,
"e": 24030,
"s": 23952,
"text": "As expected, these are all system libraries. If I do the same on a conda vim:"
},
{
"code": null,
"e": 24540,
"s": 24030,
"text": "> conda install -c conda-forge -y vim> ldd ${CONDA_PREFIX}/bin/vim linux-vdso.so.1 libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 libtinfo.so.6 => /root/miniconda3/envs/py39/bin/../lib/libtinfo.so.6 libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 libpython3.9.so.1.0 => /root/miniconda3/envs/py39/bin/../lib/libpython3.9.so.1.0 libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 /lib64/ld-linux-x86-64.so.2 libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1 "
},
{
"code": null,
"e": 24828,
"s": 24540,
"text": "we can see that now the linker found libtinfo andlibpython in the conda environment instead, even though they are available in the system /lib . Why? Because vim in conda has been compiled using RPATH, i.e., the path is hardcoded in the executable and it points to the conda environment."
},
{
"code": null,
"e": 25103,
"s": 24828,
"text": "This means that the vim I installed in this particular environment only links to libraries in the same environment, so I can have a different vim in a different environment or in my system somewhere with incompatible versions and things work just fine, without any conflict."
},
{
"code": null,
"e": 25573,
"s": 25103,
"text": "You can also note however that we still depend on some basic system libraries like linux-vdso (an interface to some kernel functionalities), libc and so on. These cannot be shipped with conda. This is also why conda environments are not as independent from the system as Docker containers. However, these system libraries are guaranteed to be backward compatible, and they provide the same interface on any Linux distribution, so they are unlikely to cause any problem."
},
{
"code": null,
"e": 25649,
"s": 25573,
"text": "The same is true for macOS, even though the system libraries are different."
},
{
"code": null,
"e": 25836,
"s": 25649,
"text": "You can even see the RPATH setting that conda uses right there in your environment. Every time you do a conda activate and activate an environment, conda sets some environment variables:"
},
{
"code": null,
"e": 26072,
"s": 25836,
"text": "CONDA_PREFIX: the path to the root of the active conda environmentLDFLAGS: this is a standard env variable that is read by the linker at compile time. If you look into it you will see the RPATH setting. For example, on my laptop I see:"
},
{
"code": null,
"e": 26139,
"s": 26072,
"text": "CONDA_PREFIX: the path to the root of the active conda environment"
},
{
"code": null,
"e": 26309,
"s": 26139,
"text": "LDFLAGS: this is a standard env variable that is read by the linker at compile time. If you look into it you will see the RPATH setting. For example, on my laptop I see:"
},
{
"code": null,
"e": 26588,
"s": 26309,
"text": "(ds) giacomov@gr723gad9:~$ echo $LDFLAGS-Wl,-O2 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now -Wl,--disable-new-dtags -Wl,--gc-sections -Wl,-rpath,/home/user/miniconda3/envs/ds/lib -Wl,-rpath-link,/home/user/miniconda3/envs/ds/lib -L/home/user/miniconda3/envs/ds/lib"
},
{
"code": null,
"e": 26876,
"s": 26588,
"text": "The -rpath flag instructs the linker to hardcode that path as the RPATH in any executable. This means that you compile an executable or a library while an environment is active, it will have the RPATH setting in it. This is the basis of how conda-build works, but that’s for another day."
},
{
"code": null,
"e": 26988,
"s": 26876,
"text": "3. CXXFLAGS, CFLAGS: specific flags for C compilers, including the path to the headers in the conda environment"
}
]
|
Product Segmentation for Retail with Python | by Samir Saci | Towards Data Science | Product segmentation refers to the activity of grouping products that have similar characteristics and serve a similar market. It is usually related to marketing (Sales Categories) or manufacturing (Production Processes).
However, as a Logistics Manager, you rarely care about the product itself when managing goods flows; except for the dangerous and oversized products.
Your attention is mainly focused on the sales volumes distribution (fast/slow movers), demand variability and delivery lead time.
You want to put efforts into managing products that have:
The highest contribution to your total turnover: ABC Analysis
The most unstable demand: Demand Variability
In this article, we will introduce simple statistical tools to combine ABC Analysis and Demand Variability to perform products segmentation.
SUMMARYI. Scenario1. Problem Statement2. Scope Analysis3. ObjectiveII. SegmentationABC AnalysisDemand Stability: Coefficient of VariationNormality TestIII. Conclusion
You can find the full code in this Github repository: LinkMy portfolio with other projects: Samir Saci
You are the Operational Director of a local Distribution Center (DC) that delivers 10 Hypermarkets.
In your scope you the responsibility of
Preparation and delivery of replenishment orders from stores
Demand Planning and Inventory Management
This analysis will be based on the M5 Forecasting dataset of Walmart stores’ sales records (Link).
We suppose that we only have the first-year data (d_1 to d_365):
10 stores in 3 states (USA)
1,878 unique SKU
3 categories and 7 departments (sub-category)
Except for the warehouse layout, categories and departments have no impact on your ordering, picking or shipping processes.
Code — Data Processing
What does impact your logistic performance?
Products RotationWhat are the references that are driving most of your sales?
Very Fast Movers: top 5% (Class A)
The following 15% of fast movers (Class B)
The remaining 80% of very slow movers (Class C)
This classification will impact,
Warehouse Layout: Reduce Warehouse Space with the Pareto Principle using Python
www.samirsaci.com
Picking Process: Improve Warehouse Productivity using Order Batching with Python
www.samirsaci.com
Demand VariabilityHow stable is your customers’ demand?
Average Sales: μ
Standard Deviation:
Coefficient of Variation: CV = σ/μ
For SKUs with a high value of CV, you may face unstable customer demand that would lead to workload peaks, forecasting complexity and stock-outs.
Code
Filter on the first year of sales for HOBBIES Skus
Calculate Mean, Standard deviation and CV of sales
Sorting (Descending) and Cumulative sales calculation for ABC analysis
samirsaci.com
This analysis will be done for the SKU in the HOBBIES category.
What are the references that are driving most of your sales?
Class A: the top 5%- Number of SKU: 16- Turnover (%): 25%Class B: the following 15%- Number of SKU: 48 - Turnover (%): 31%Class C: the 80% slow movers- Number of SKU: 253 - Turnover (%): 43%
In this example, we cannot clearly observe the Pareto Law (20% of SKU making 80% of the turnover).
However, we still have 80% of our portfolio making less than 50% of the sales.
Code
How stable is your customers’ demand?
From the Logistics Manager's point of view, it is way more challenging to handle a peak of sales than a uniform distribution throughout the year.
In order to understand which products will bring planning and distribution challenges, we will compute the coefficient of variation of the yearly distribution of sales of each reference.
Class AFortunately, most of the A SKU have a quite stable demand; we won't be challenged by the most important SKUs.
Class BThe majority of SKUs are in the stable area; however we still spend effort on ensuring optimal planning for the few references that have a high CV.
Class CMost of the SKUs have a high value of CV;For this kind of reference a cause analysis would provide better results than a statistical approach for forecasting.
Code
Can we assume that the sales follow a normal distribution?
Most of the simple inventory management methods are based on the assumption that the demand follows a normal distribution.
Why? Because it’s easy.
Sanity CheckBefore starting to implement rules and perform forecasts it’s better to verify that this hypothesis cannot be refuted.
We’ll be using the Shapiro-Wilk test for normality; it can be implemented using the Scipy library. The null hypothesis will be (H0: the demand sales follows a normal distribution).
Bad NewsFor an alpha = 0.05, we can reject the null hypothesis for most of the SKUs. This will impact the complexity of inventory management assumptions.
Code
This operationally driven segmentation gives us a few insights on the challenges your operations will face for planning and managing the goods flows to meet your store's demand.
Have a look at my blog: https://samirsaci.com
[1] Scipy stats Shapiro Test documentation, Link | [
{
"code": null,
"e": 394,
"s": 172,
"text": "Product segmentation refers to the activity of grouping products that have similar characteristics and serve a similar market. It is usually related to marketing (Sales Categories) or manufacturing (Production Processes)."
},
{
"code": null,
"e": 544,
"s": 394,
"text": "However, as a Logistics Manager, you rarely care about the product itself when managing goods flows; except for the dangerous and oversized products."
},
{
"code": null,
"e": 674,
"s": 544,
"text": "Your attention is mainly focused on the sales volumes distribution (fast/slow movers), demand variability and delivery lead time."
},
{
"code": null,
"e": 732,
"s": 674,
"text": "You want to put efforts into managing products that have:"
},
{
"code": null,
"e": 794,
"s": 732,
"text": "The highest contribution to your total turnover: ABC Analysis"
},
{
"code": null,
"e": 839,
"s": 794,
"text": "The most unstable demand: Demand Variability"
},
{
"code": null,
"e": 980,
"s": 839,
"text": "In this article, we will introduce simple statistical tools to combine ABC Analysis and Demand Variability to perform products segmentation."
},
{
"code": null,
"e": 1147,
"s": 980,
"text": "SUMMARYI. Scenario1. Problem Statement2. Scope Analysis3. ObjectiveII. SegmentationABC AnalysisDemand Stability: Coefficient of VariationNormality TestIII. Conclusion"
},
{
"code": null,
"e": 1250,
"s": 1147,
"text": "You can find the full code in this Github repository: LinkMy portfolio with other projects: Samir Saci"
},
{
"code": null,
"e": 1350,
"s": 1250,
"text": "You are the Operational Director of a local Distribution Center (DC) that delivers 10 Hypermarkets."
},
{
"code": null,
"e": 1390,
"s": 1350,
"text": "In your scope you the responsibility of"
},
{
"code": null,
"e": 1451,
"s": 1390,
"text": "Preparation and delivery of replenishment orders from stores"
},
{
"code": null,
"e": 1492,
"s": 1451,
"text": "Demand Planning and Inventory Management"
},
{
"code": null,
"e": 1591,
"s": 1492,
"text": "This analysis will be based on the M5 Forecasting dataset of Walmart stores’ sales records (Link)."
},
{
"code": null,
"e": 1656,
"s": 1591,
"text": "We suppose that we only have the first-year data (d_1 to d_365):"
},
{
"code": null,
"e": 1684,
"s": 1656,
"text": "10 stores in 3 states (USA)"
},
{
"code": null,
"e": 1701,
"s": 1684,
"text": "1,878 unique SKU"
},
{
"code": null,
"e": 1747,
"s": 1701,
"text": "3 categories and 7 departments (sub-category)"
},
{
"code": null,
"e": 1871,
"s": 1747,
"text": "Except for the warehouse layout, categories and departments have no impact on your ordering, picking or shipping processes."
},
{
"code": null,
"e": 1894,
"s": 1871,
"text": "Code — Data Processing"
},
{
"code": null,
"e": 1938,
"s": 1894,
"text": "What does impact your logistic performance?"
},
{
"code": null,
"e": 2016,
"s": 1938,
"text": "Products RotationWhat are the references that are driving most of your sales?"
},
{
"code": null,
"e": 2051,
"s": 2016,
"text": "Very Fast Movers: top 5% (Class A)"
},
{
"code": null,
"e": 2094,
"s": 2051,
"text": "The following 15% of fast movers (Class B)"
},
{
"code": null,
"e": 2142,
"s": 2094,
"text": "The remaining 80% of very slow movers (Class C)"
},
{
"code": null,
"e": 2175,
"s": 2142,
"text": "This classification will impact,"
},
{
"code": null,
"e": 2255,
"s": 2175,
"text": "Warehouse Layout: Reduce Warehouse Space with the Pareto Principle using Python"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "www.samirsaci.com"
},
{
"code": null,
"e": 2354,
"s": 2273,
"text": "Picking Process: Improve Warehouse Productivity using Order Batching with Python"
},
{
"code": null,
"e": 2372,
"s": 2354,
"text": "www.samirsaci.com"
},
{
"code": null,
"e": 2428,
"s": 2372,
"text": "Demand VariabilityHow stable is your customers’ demand?"
},
{
"code": null,
"e": 2445,
"s": 2428,
"text": "Average Sales: μ"
},
{
"code": null,
"e": 2465,
"s": 2445,
"text": "Standard Deviation:"
},
{
"code": null,
"e": 2500,
"s": 2465,
"text": "Coefficient of Variation: CV = σ/μ"
},
{
"code": null,
"e": 2646,
"s": 2500,
"text": "For SKUs with a high value of CV, you may face unstable customer demand that would lead to workload peaks, forecasting complexity and stock-outs."
},
{
"code": null,
"e": 2651,
"s": 2646,
"text": "Code"
},
{
"code": null,
"e": 2702,
"s": 2651,
"text": "Filter on the first year of sales for HOBBIES Skus"
},
{
"code": null,
"e": 2753,
"s": 2702,
"text": "Calculate Mean, Standard deviation and CV of sales"
},
{
"code": null,
"e": 2824,
"s": 2753,
"text": "Sorting (Descending) and Cumulative sales calculation for ABC analysis"
},
{
"code": null,
"e": 2838,
"s": 2824,
"text": "samirsaci.com"
},
{
"code": null,
"e": 2902,
"s": 2838,
"text": "This analysis will be done for the SKU in the HOBBIES category."
},
{
"code": null,
"e": 2963,
"s": 2902,
"text": "What are the references that are driving most of your sales?"
},
{
"code": null,
"e": 3154,
"s": 2963,
"text": "Class A: the top 5%- Number of SKU: 16- Turnover (%): 25%Class B: the following 15%- Number of SKU: 48 - Turnover (%): 31%Class C: the 80% slow movers- Number of SKU: 253 - Turnover (%): 43%"
},
{
"code": null,
"e": 3253,
"s": 3154,
"text": "In this example, we cannot clearly observe the Pareto Law (20% of SKU making 80% of the turnover)."
},
{
"code": null,
"e": 3332,
"s": 3253,
"text": "However, we still have 80% of our portfolio making less than 50% of the sales."
},
{
"code": null,
"e": 3337,
"s": 3332,
"text": "Code"
},
{
"code": null,
"e": 3375,
"s": 3337,
"text": "How stable is your customers’ demand?"
},
{
"code": null,
"e": 3521,
"s": 3375,
"text": "From the Logistics Manager's point of view, it is way more challenging to handle a peak of sales than a uniform distribution throughout the year."
},
{
"code": null,
"e": 3708,
"s": 3521,
"text": "In order to understand which products will bring planning and distribution challenges, we will compute the coefficient of variation of the yearly distribution of sales of each reference."
},
{
"code": null,
"e": 3825,
"s": 3708,
"text": "Class AFortunately, most of the A SKU have a quite stable demand; we won't be challenged by the most important SKUs."
},
{
"code": null,
"e": 3980,
"s": 3825,
"text": "Class BThe majority of SKUs are in the stable area; however we still spend effort on ensuring optimal planning for the few references that have a high CV."
},
{
"code": null,
"e": 4146,
"s": 3980,
"text": "Class CMost of the SKUs have a high value of CV;For this kind of reference a cause analysis would provide better results than a statistical approach for forecasting."
},
{
"code": null,
"e": 4151,
"s": 4146,
"text": "Code"
},
{
"code": null,
"e": 4210,
"s": 4151,
"text": "Can we assume that the sales follow a normal distribution?"
},
{
"code": null,
"e": 4333,
"s": 4210,
"text": "Most of the simple inventory management methods are based on the assumption that the demand follows a normal distribution."
},
{
"code": null,
"e": 4357,
"s": 4333,
"text": "Why? Because it’s easy."
},
{
"code": null,
"e": 4488,
"s": 4357,
"text": "Sanity CheckBefore starting to implement rules and perform forecasts it’s better to verify that this hypothesis cannot be refuted."
},
{
"code": null,
"e": 4669,
"s": 4488,
"text": "We’ll be using the Shapiro-Wilk test for normality; it can be implemented using the Scipy library. The null hypothesis will be (H0: the demand sales follows a normal distribution)."
},
{
"code": null,
"e": 4823,
"s": 4669,
"text": "Bad NewsFor an alpha = 0.05, we can reject the null hypothesis for most of the SKUs. This will impact the complexity of inventory management assumptions."
},
{
"code": null,
"e": 4828,
"s": 4823,
"text": "Code"
},
{
"code": null,
"e": 5006,
"s": 4828,
"text": "This operationally driven segmentation gives us a few insights on the challenges your operations will face for planning and managing the goods flows to meet your store's demand."
},
{
"code": null,
"e": 5052,
"s": 5006,
"text": "Have a look at my blog: https://samirsaci.com"
}
]
|
How to check if a given array represents a Binary Heap? - GeeksforGeeks | 25 Mar, 2022
Given an array, how to check if the given array represents a Binary Max-Heap.Examples:
Input: arr[] = {90, 15, 10, 7, 12, 2}
Output: True
The given array represents below tree
90
/ \
15 10
/ \ /
7 12 2
The tree follows max-heap property as every
node is greater than all of its descendants.
Input: arr[] = {9, 15, 10, 7, 12, 11}
Output: False
The given array represents below tree
9
/ \
15 10
/ \ /
7 12 11
The tree doesn't follows max-heap property 9 is
smaller than 15 and 10, and 10 is smaller than 11.
A Simple Solution is to first check root if it’s greater than all of its descendants. Then check for children of the root. Time complexity of this solution is O(n2)An Efficient Solution is to compare root only with its children (not all descendants), if root is greater than its children and the same is true for all nodes, then tree is max-heap (This conclusion is based on transitive property of > operator, i.e., if x > y and y > z, then x > z).The last internal node is present at index (n-2)/2 assuming that indexing begins with 0.Below is the implementation of this solution.
C++
Java
Python3
C#
PHP
Javascript
// C program to check whether a given array// represents a max-heap or not#include <limits.h>#include <stdio.h> // Returns true if arr[i..n-1] represents a// max-heapbool isHeap(int arr[], int i, int n){ // If (2 * i) + 1 >= n, then leaf node, so return true if (i >= (n - 1) / 2) return true; // If an internal node and is // greater than its children, // and same is recursively // true for the children if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) return true; return false;} // Driver programint main(){ int arr[] = { 90, 15, 10, 7, 12, 2, 7, 3 }; int n = sizeof(arr) / sizeof(int) - 1; isHeap(arr, 0, n) ? printf("Yes") : printf("No"); return 0;}
// Java program to check whether a given array// represents a max-heap or notclass GFG{ // Returns true if arr[i..n-1] // represents a max-heap static boolean isHeap(int arr[], int i, int n) { // If (2 * i) + 1 >= n, then leaf node, so return true if (i >= (n - 1) / 2) { return true; } // If an internal node and // is greater than its // children, and same is // recursively true for the // children if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) { return true; } return false; } // Driver program public static void main(String[] args) { int arr[] = { 90, 15, 10, 7, 12, 2, 7, 3 }; int n = arr.length - 1; if (isHeap(arr, 0, n)) { System.out.println("Yes"); } else { System.out.println("No"); } }} // This code contributed by 29AjayKumar
# Python3 program to check whether a# given array represents a max-heap or not # Returns true if arr[i..n-1]# represents a max-heapdef isHeap(arr, i, n): # If (2 * i) + 1 >= n, then leaf node, so return true if i >= int((n - 1) / 2): return True # If an internal node and is greater # than its children, and same is # recursively true for the children if(arr[i] >= arr[2 * i + 1] and arr[i] >= arr[2 * i + 2] and isHeap(arr, 2 * i + 1, n) and isHeap(arr, 2 * i + 2, n)): return True return False # Driver Codeif __name__ == '__main__': arr = [90, 15, 10, 7, 12, 2, 7, 3] n = len(arr) - 1 if isHeap(arr, 0, n): print("Yes") else: print("No") # This code is contributed by PranchalK
// C# program to check whether a given // array represents a max-heap or notusing System; class GFG{ // Returns true if arr[i..n-1] represents a// max-heapstatic bool isHeap(int []arr, int i, int n){ // If (2 * i) + 1 >= n, then leaf node, so return true if (i >= (n - 1) / 2) { return true; } // If an internal node and is greater // than its children, and same is // recursively true for the children if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) { return true; } return false;} // Driver Codepublic static void Main(String[] args){ int []arr = {90, 15, 10, 7, 12, 2, 7, 3}; int n = arr.Length-1; if (isHeap(arr, 0, n)) { Console.Write("Yes"); } else { Console.Write("No"); }}}
<?php// PHP program to check whether a given// array represents a max-heap or not // Returns true if arr[i..n-1]// represents a max-heapfunction isHeap($arr, $i, $n){ // If (2 * i) + 1 >= n, then leaf node, so return trueif ($i >= ($n - 1) / 2) return true; // If an internal node and is greater// than its children, and same is// recursively true for the childrenif ($arr[$i] >= $arr[2 * $i + 1] && $arr[$i] >= $arr[2 * $i + 2] && isHeap($arr, 2 * $i + 1, $n) && isHeap($arr, 2 * $i + 2, $n)) return true; return false;} // Driver Code$arr = array(90, 15, 10, 7, 12, 2, 7, 3);$n = sizeof($arr); if(isHeap($arr, 0, $n)) echo "Yes";else echo "No"; // This code is contributed// by Akanksha Rai?>
<script>// Javascript program to check whether a given array// represents a max-heap or not // Returns true if arr[i..n-1] // represents a max-heapfunction isHeap(arr,i,n){ // If (2 * i) + 1 >= n, then leaf node, so return true if (i >= (n - 1) / 2) { return true; } // If an internal node and // is greater than its // children, and same is // recursively true for the // children if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) { return true; } return false;} // Driver programlet arr=[ 90, 15, 10, 7, 12, 2, 7, 3 ];let n = arr.length - 1;if (isHeap(arr, 0, n)) { document.write("Yes<br>");}else { document.write("No<br>");} // This code is contributed by rag2127</script>
Yes
Time complexity of this solution is O(n). The solution is similar to preorder traversal of Binary Tree.Thanks to Utkarsh Trivedi for suggesting the above solution.An Iterative Solution is to traverse all internal nodes and check id node is greater than its children or not.
C++
Java
Python3
C#
PHP
Javascript
// C program to check whether a given array// represents a max-heap or not#include <stdio.h>#include <limits.h> // Returns true if arr[i..n-1] represents a// max-heapbool isHeap(int arr[], int n){ // Start from root and go till the last internal // node for (int i=0; i<=(n-2)/2; i++) { // If left child is greater, return false if (arr[2*i +1] > arr[i]) return false; // If right child is greater, return false if (2*i+2 < n && arr[2*i+2] > arr[i]) return false; } return true;} // Driver programint main(){ int arr[] = {90, 15, 10, 7, 12, 2, 7, 3}; int n = sizeof(arr) / sizeof(int); isHeap(arr, n)? printf("Yes"): printf("No"); return 0;}
// Java program to check whether a given array// represents a max-heap or not class GFG { // Returns true if arr[i..n-1] represents a// max-heap static boolean isHeap(int arr[], int n) { // Start from root and go till the last internal // node for (int i = 0; i <= (n - 2) / 2; i++) { // If left child is greater, return false if (arr[2 * i + 1] > arr[i]) { return false; } // If right child is greater, return false if (2 * i + 2 < n && arr[2 * i + 2] > arr[i]) { return false; } } return true; } // Driver program public static void main(String[] args) { int arr[] = {90, 15, 10, 7, 12, 2, 7, 3}; int n = arr.length; if (isHeap(arr, n)) { System.out.println("Yes"); } else { System.out.println("No"); } }}// This code is contributed by 29AjayKumar
# Python3 program to check whether a# given array represents a max-heap or not # Returns true if arr[i..n-1]# represents a max-heapdef isHeap(arr, n): # Start from root and go till # the last internal node for i in range(int((n - 2) / 2) + 1): # If left child is greater, # return false if arr[2 * i + 1] > arr[i]: return False # If right child is greater, # return false if (2 * i + 2 < n and arr[2 * i + 2] > arr[i]): return False return True # Driver Codeif __name__ == '__main__': arr = [90, 15, 10, 7, 12, 2, 7, 3] n = len(arr) if isHeap(arr, n): print("Yes") else: print("No") # This code is contributed by PranchalK
// C# program to check whether a given array// represents a max-heap or notusing System; class GFG{ // Returns true if arr[i..n-1]// represents a max-heapstatic bool isHeap(int []arr, int n){ // Start from root and go till // the last internal node for (int i = 0; i <= (n - 2) / 2; i++) { // If left child is greater, // return false if (arr[2 * i + 1] > arr[i]) { return false; } // If right child is greater, // return false if (2 * i + 2 < n && arr[2 * i + 2] > arr[i]) { return false; } } return true;} // Driver Codepublic static void Main(){ int []arr = {90, 15, 10, 7, 12, 2, 7, 3}; int n = arr.Length; if (isHeap(arr, n)) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed// by 29AjayKumar
<?php// PHP program to check whether a// given array represents a max-heap or not // Returns true if arr[i..n-1]// represents a max-heapfunction isHeap($arr, $i, $n){ // Start from root and go till // the last internal node for ($i = 0; $i < (($n - 2) / 2) + 1; $i++) { // If left child is greater, // return false if($arr[2 * $i + 1] > $arr[$i]) return False; // If right child is greater, // return false if (2 * $i + 2 < $n && $arr[2 * $i + 2] > $arr[$i]) return False; return True; }} // Driver Code$arr = array(90, 15, 10, 7, 12, 2, 7, 3);$n = sizeof($arr); if(isHeap($arr, 0, $n)) echo "Yes";else echo "No"; // This code is contributed by Princi Singh?>
<script> // Javascript program to check// whether a given array// represents a max-heap or not // Returns true if arr[i..n-1]// represents a max-heapfunction isHeap( arr, n){ // Start from root and go till // the last internal node for (let i=0; i<=Math.floor((n-2)/2); i++) { // If left child is greater, // return false if (arr[2*i +1] > arr[i]) return false; // If right child is greater, // return false if (2*i+2 < n && arr[2*i+2] > arr[i]) return false; } return true;} // driver code let arr = [90, 15, 10, 7, 12, 2, 7, 3]; let n = arr.length; if (isHeap(arr, n)) { document.write("Yes"); } else { document.write("No"); } </script>
Yes
Thanks to Himanshu for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
anubhavtikku
29AjayKumar
princiraj1992
Akanksha_Rai
PranchalKatiyar
princi singh
Sheenam Yadav
sivajikondapalli
jana_sayantan
rag2127
arynkr
Cisco
Arrays
Binary Search Tree
Heap
Cisco
Arrays
Binary Search Tree
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Inorder Successor in Binary Search Tree | [
{
"code": null,
"e": 24722,
"s": 24694,
"text": "\n25 Mar, 2022"
},
{
"code": null,
"e": 24810,
"s": 24722,
"text": "Given an array, how to check if the given array represents a Binary Max-Heap.Examples: "
},
{
"code": null,
"e": 25307,
"s": 24810,
"text": "Input: arr[] = {90, 15, 10, 7, 12, 2} \nOutput: True\nThe given array represents below tree\n 90\n / \\\n 15 10\n / \\ /\n 7 12 2 \nThe tree follows max-heap property as every\nnode is greater than all of its descendants.\n\nInput: arr[] = {9, 15, 10, 7, 12, 11} \nOutput: False\nThe given array represents below tree\n 9\n / \\\n 15 10\n / \\ /\n 7 12 11\nThe tree doesn't follows max-heap property 9 is \nsmaller than 15 and 10, and 10 is smaller than 11. "
},
{
"code": null,
"e": 25890,
"s": 25307,
"text": "A Simple Solution is to first check root if it’s greater than all of its descendants. Then check for children of the root. Time complexity of this solution is O(n2)An Efficient Solution is to compare root only with its children (not all descendants), if root is greater than its children and the same is true for all nodes, then tree is max-heap (This conclusion is based on transitive property of > operator, i.e., if x > y and y > z, then x > z).The last internal node is present at index (n-2)/2 assuming that indexing begins with 0.Below is the implementation of this solution. "
},
{
"code": null,
"e": 25894,
"s": 25890,
"text": "C++"
},
{
"code": null,
"e": 25899,
"s": 25894,
"text": "Java"
},
{
"code": null,
"e": 25907,
"s": 25899,
"text": "Python3"
},
{
"code": null,
"e": 25910,
"s": 25907,
"text": "C#"
},
{
"code": null,
"e": 25914,
"s": 25910,
"text": "PHP"
},
{
"code": null,
"e": 25925,
"s": 25914,
"text": "Javascript"
},
{
"code": "// C program to check whether a given array// represents a max-heap or not#include <limits.h>#include <stdio.h> // Returns true if arr[i..n-1] represents a// max-heapbool isHeap(int arr[], int i, int n){ // If (2 * i) + 1 >= n, then leaf node, so return true if (i >= (n - 1) / 2) return true; // If an internal node and is // greater than its children, // and same is recursively // true for the children if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) return true; return false;} // Driver programint main(){ int arr[] = { 90, 15, 10, 7, 12, 2, 7, 3 }; int n = sizeof(arr) / sizeof(int) - 1; isHeap(arr, 0, n) ? printf(\"Yes\") : printf(\"No\"); return 0;}",
"e": 26723,
"s": 25925,
"text": null
},
{
"code": "// Java program to check whether a given array// represents a max-heap or notclass GFG{ // Returns true if arr[i..n-1] // represents a max-heap static boolean isHeap(int arr[], int i, int n) { // If (2 * i) + 1 >= n, then leaf node, so return true if (i >= (n - 1) / 2) { return true; } // If an internal node and // is greater than its // children, and same is // recursively true for the // children if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) { return true; } return false; } // Driver program public static void main(String[] args) { int arr[] = { 90, 15, 10, 7, 12, 2, 7, 3 }; int n = arr.length - 1; if (isHeap(arr, 0, n)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }} // This code contributed by 29AjayKumar",
"e": 27799,
"s": 26723,
"text": null
},
{
"code": "# Python3 program to check whether a# given array represents a max-heap or not # Returns true if arr[i..n-1]# represents a max-heapdef isHeap(arr, i, n): # If (2 * i) + 1 >= n, then leaf node, so return true if i >= int((n - 1) / 2): return True # If an internal node and is greater # than its children, and same is # recursively true for the children if(arr[i] >= arr[2 * i + 1] and arr[i] >= arr[2 * i + 2] and isHeap(arr, 2 * i + 1, n) and isHeap(arr, 2 * i + 2, n)): return True return False # Driver Codeif __name__ == '__main__': arr = [90, 15, 10, 7, 12, 2, 7, 3] n = len(arr) - 1 if isHeap(arr, 0, n): print(\"Yes\") else: print(\"No\") # This code is contributed by PranchalK",
"e": 28575,
"s": 27799,
"text": null
},
{
"code": "// C# program to check whether a given // array represents a max-heap or notusing System; class GFG{ // Returns true if arr[i..n-1] represents a// max-heapstatic bool isHeap(int []arr, int i, int n){ // If (2 * i) + 1 >= n, then leaf node, so return true if (i >= (n - 1) / 2) { return true; } // If an internal node and is greater // than its children, and same is // recursively true for the children if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) { return true; } return false;} // Driver Codepublic static void Main(String[] args){ int []arr = {90, 15, 10, 7, 12, 2, 7, 3}; int n = arr.Length-1; if (isHeap(arr, 0, n)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}}",
"e": 29438,
"s": 28575,
"text": null
},
{
"code": "<?php// PHP program to check whether a given// array represents a max-heap or not // Returns true if arr[i..n-1]// represents a max-heapfunction isHeap($arr, $i, $n){ // If (2 * i) + 1 >= n, then leaf node, so return trueif ($i >= ($n - 1) / 2) return true; // If an internal node and is greater// than its children, and same is// recursively true for the childrenif ($arr[$i] >= $arr[2 * $i + 1] && $arr[$i] >= $arr[2 * $i + 2] && isHeap($arr, 2 * $i + 1, $n) && isHeap($arr, 2 * $i + 2, $n)) return true; return false;} // Driver Code$arr = array(90, 15, 10, 7, 12, 2, 7, 3);$n = sizeof($arr); if(isHeap($arr, 0, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Akanksha Rai?>",
"e": 30158,
"s": 29438,
"text": null
},
{
"code": "<script>// Javascript program to check whether a given array// represents a max-heap or not // Returns true if arr[i..n-1] // represents a max-heapfunction isHeap(arr,i,n){ // If (2 * i) + 1 >= n, then leaf node, so return true if (i >= (n - 1) / 2) { return true; } // If an internal node and // is greater than its // children, and same is // recursively true for the // children if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) { return true; } return false;} // Driver programlet arr=[ 90, 15, 10, 7, 12, 2, 7, 3 ];let n = arr.length - 1;if (isHeap(arr, 0, n)) { document.write(\"Yes<br>\");}else { document.write(\"No<br>\");} // This code is contributed by rag2127</script>",
"e": 31057,
"s": 30158,
"text": null
},
{
"code": null,
"e": 31061,
"s": 31057,
"text": "Yes"
},
{
"code": null,
"e": 31336,
"s": 31061,
"text": "Time complexity of this solution is O(n). The solution is similar to preorder traversal of Binary Tree.Thanks to Utkarsh Trivedi for suggesting the above solution.An Iterative Solution is to traverse all internal nodes and check id node is greater than its children or not. "
},
{
"code": null,
"e": 31340,
"s": 31336,
"text": "C++"
},
{
"code": null,
"e": 31345,
"s": 31340,
"text": "Java"
},
{
"code": null,
"e": 31353,
"s": 31345,
"text": "Python3"
},
{
"code": null,
"e": 31356,
"s": 31353,
"text": "C#"
},
{
"code": null,
"e": 31360,
"s": 31356,
"text": "PHP"
},
{
"code": null,
"e": 31371,
"s": 31360,
"text": "Javascript"
},
{
"code": "// C program to check whether a given array// represents a max-heap or not#include <stdio.h>#include <limits.h> // Returns true if arr[i..n-1] represents a// max-heapbool isHeap(int arr[], int n){ // Start from root and go till the last internal // node for (int i=0; i<=(n-2)/2; i++) { // If left child is greater, return false if (arr[2*i +1] > arr[i]) return false; // If right child is greater, return false if (2*i+2 < n && arr[2*i+2] > arr[i]) return false; } return true;} // Driver programint main(){ int arr[] = {90, 15, 10, 7, 12, 2, 7, 3}; int n = sizeof(arr) / sizeof(int); isHeap(arr, n)? printf(\"Yes\"): printf(\"No\"); return 0;}",
"e": 32105,
"s": 31371,
"text": null
},
{
"code": "// Java program to check whether a given array// represents a max-heap or not class GFG { // Returns true if arr[i..n-1] represents a// max-heap static boolean isHeap(int arr[], int n) { // Start from root and go till the last internal // node for (int i = 0; i <= (n - 2) / 2; i++) { // If left child is greater, return false if (arr[2 * i + 1] > arr[i]) { return false; } // If right child is greater, return false if (2 * i + 2 < n && arr[2 * i + 2] > arr[i]) { return false; } } return true; } // Driver program public static void main(String[] args) { int arr[] = {90, 15, 10, 7, 12, 2, 7, 3}; int n = arr.length; if (isHeap(arr, n)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }}// This code is contributed by 29AjayKumar",
"e": 33056,
"s": 32105,
"text": null
},
{
"code": "# Python3 program to check whether a# given array represents a max-heap or not # Returns true if arr[i..n-1]# represents a max-heapdef isHeap(arr, n): # Start from root and go till # the last internal node for i in range(int((n - 2) / 2) + 1): # If left child is greater, # return false if arr[2 * i + 1] > arr[i]: return False # If right child is greater, # return false if (2 * i + 2 < n and arr[2 * i + 2] > arr[i]): return False return True # Driver Codeif __name__ == '__main__': arr = [90, 15, 10, 7, 12, 2, 7, 3] n = len(arr) if isHeap(arr, n): print(\"Yes\") else: print(\"No\") # This code is contributed by PranchalK",
"e": 33824,
"s": 33056,
"text": null
},
{
"code": "// C# program to check whether a given array// represents a max-heap or notusing System; class GFG{ // Returns true if arr[i..n-1]// represents a max-heapstatic bool isHeap(int []arr, int n){ // Start from root and go till // the last internal node for (int i = 0; i <= (n - 2) / 2; i++) { // If left child is greater, // return false if (arr[2 * i + 1] > arr[i]) { return false; } // If right child is greater, // return false if (2 * i + 2 < n && arr[2 * i + 2] > arr[i]) { return false; } } return true;} // Driver Codepublic static void Main(){ int []arr = {90, 15, 10, 7, 12, 2, 7, 3}; int n = arr.Length; if (isHeap(arr, n)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed// by 29AjayKumar",
"e": 34707,
"s": 33824,
"text": null
},
{
"code": "<?php// PHP program to check whether a// given array represents a max-heap or not // Returns true if arr[i..n-1]// represents a max-heapfunction isHeap($arr, $i, $n){ // Start from root and go till // the last internal node for ($i = 0; $i < (($n - 2) / 2) + 1; $i++) { // If left child is greater, // return false if($arr[2 * $i + 1] > $arr[$i]) return False; // If right child is greater, // return false if (2 * $i + 2 < $n && $arr[2 * $i + 2] > $arr[$i]) return False; return True; }} // Driver Code$arr = array(90, 15, 10, 7, 12, 2, 7, 3);$n = sizeof($arr); if(isHeap($arr, 0, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed by Princi Singh?>",
"e": 35488,
"s": 34707,
"text": null
},
{
"code": "<script> // Javascript program to check// whether a given array// represents a max-heap or not // Returns true if arr[i..n-1]// represents a max-heapfunction isHeap( arr, n){ // Start from root and go till // the last internal node for (let i=0; i<=Math.floor((n-2)/2); i++) { // If left child is greater, // return false if (arr[2*i +1] > arr[i]) return false; // If right child is greater, // return false if (2*i+2 < n && arr[2*i+2] > arr[i]) return false; } return true;} // driver code let arr = [90, 15, 10, 7, 12, 2, 7, 3]; let n = arr.length; if (isHeap(arr, n)) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>",
"e": 36270,
"s": 35488,
"text": null
},
{
"code": null,
"e": 36274,
"s": 36270,
"text": "Yes"
},
{
"code": null,
"e": 36446,
"s": 36274,
"text": "Thanks to Himanshu for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 36459,
"s": 36446,
"text": "anubhavtikku"
},
{
"code": null,
"e": 36471,
"s": 36459,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36485,
"s": 36471,
"text": "princiraj1992"
},
{
"code": null,
"e": 36498,
"s": 36485,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 36514,
"s": 36498,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 36527,
"s": 36514,
"text": "princi singh"
},
{
"code": null,
"e": 36541,
"s": 36527,
"text": "Sheenam Yadav"
},
{
"code": null,
"e": 36558,
"s": 36541,
"text": "sivajikondapalli"
},
{
"code": null,
"e": 36572,
"s": 36558,
"text": "jana_sayantan"
},
{
"code": null,
"e": 36580,
"s": 36572,
"text": "rag2127"
},
{
"code": null,
"e": 36587,
"s": 36580,
"text": "arynkr"
},
{
"code": null,
"e": 36593,
"s": 36587,
"text": "Cisco"
},
{
"code": null,
"e": 36600,
"s": 36593,
"text": "Arrays"
},
{
"code": null,
"e": 36619,
"s": 36600,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 36624,
"s": 36619,
"text": "Heap"
},
{
"code": null,
"e": 36630,
"s": 36624,
"text": "Cisco"
},
{
"code": null,
"e": 36637,
"s": 36630,
"text": "Arrays"
},
{
"code": null,
"e": 36656,
"s": 36637,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 36661,
"s": 36656,
"text": "Heap"
},
{
"code": null,
"e": 36759,
"s": 36661,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36768,
"s": 36759,
"text": "Comments"
},
{
"code": null,
"e": 36781,
"s": 36768,
"text": "Old Comments"
},
{
"code": null,
"e": 36825,
"s": 36781,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36848,
"s": 36825,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36862,
"s": 36848,
"text": "Linear Search"
},
{
"code": null,
"e": 36930,
"s": 36862,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36962,
"s": 36930,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37012,
"s": 36962,
"text": "Binary Search Tree | Set 1 (Search and Insertion)"
},
{
"code": null,
"e": 37041,
"s": 37012,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 37077,
"s": 37041,
"text": "Binary Search Tree | Set 2 (Delete)"
},
{
"code": null,
"e": 37127,
"s": 37077,
"text": "A program to check if a binary tree is BST or not"
}
]
|
How to remove the row names or column names from a matrix in R? | To remove the row names or column names from a matrix, we just need to set them to NULL, in this way all the names will be nullified. For example, if we have a matrix M that contain row names and column names then we can remove those names by using the command colnames(M)<-NULL for columns and rownames(M)<-NULL for rows.
Live Demo
M1<-matrix(1:100,ncol=10)
M1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
colnames(M1)<-LETTERS[1:10]
M1
A B C D E F G H I J
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 1 4 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
colnames(M1)<-NULL
M1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
rownames(M1)<-letters[1:10]
M1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
a 1 11 21 31 41 51 61 71 81 91
b 2 12 22 32 42 52 62 72 82 92
c 3 13 23 33 43 53 63 73 83 93
d 4 14 24 34 44 54 64 74 84 94
e 5 15 25 35 45 55 65 75 85 95
f 6 16 26 36 46 56 66 76 86 96
g 7 17 27 37 47 57 67 77 87 97
h 8 18 28 38 48 58 68 78 88 98
i 9 19 29 39 49 59 69 79 89 99
j 10 20 30 40 50 60 70 80 90 100
rownames(M1)<-NULL
M1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
Live Demo
M2<-matrix(rnorm(50),nrow=10)
M2
[,1] [,2] [,3] [,4] [,5]
[1,] 0.6802874 0.2144306 -1.4145804 0.62402960 -0.5938315
[2,] 0.4536187 0.5653905 0.6312822 2.56036083 0.7728485
[3,] 2.1096132 -0.7314662 0.3260058 -0.98057417 -0.3724911
[4,] -0.5953890 0.6637290 -1.6762956 -1.61804847 0.8662887
[5,] -0.7562208 -0.9417305 -1.7037116 0.60382315 -0.5236230
[6,] -1.2611174 -2.1865329 -0.2465629 -2.00149510 -1.0256434
[7,] 0.7827362 -0.8577172 1.1250864 -1.13954661 0.3187836
[8,] -0.8423010 -1.7105257 -0.2722357 -0.05741225 -0.9454204
[9,] -0.8249438 0.7572876 0.5679531 0.43816230 -1.5323482
[10,] 1.0914719 -0.9003930 0.7307768 -0.12886355 -1.5271211
colnames(M2)<-c("S1","S2","S3","S4","S5")
M2
S1 S2 S3 S4 S5
[1,] -0.21369037 -0.26807549 0.5780368 0.403231225 -0.3898034
[2,] -1.05153856 -0.91487726 -0.2038823 0.904563419 0.4286243
[3,] -0.10755935 0.36254026 -1.3386091 -0.218132138 0.3148615
[4,] 0.73045398 -0.09284451 -0.1476228 -1.196201762 1.3801728
[5,] 2.32148727 -1.51292926 1.7808169 -0.135465061 -0.8747653
[6,] 1.03602597 1.12718811 0.6376310 -0.009445365 -1.4074674
[7,] -0.05036301 -1.04252829 -0.8978156 -1.079780864 0.3735876
[8,] 1.01912253 1.28759140 0.1640043 -1.126854167 -0.2303916
[9,] 0.93337641 -1.24223632 0.6052778 -0.003241698 0.2684704
[10,] 0.30957289 -1.39528971 -0.7803917 0.946891126 -0.9375629
colnames(M2)<-NULL
M2
[,1] [,2] [,3] [,4] [,5]
[1,] -0.21369037 -0.26807549 0.5780368 0.403231225 -0.3898034
[2,] -1.05153856 -0.91487726 -0.2038823 0.904563419 0.4286243
[3,] -0.10755935 0.36254026 -1.3386091 -0.218132138 0.3148615
[4,] 0.73045398 - 0.09284451 -0.1476228 -1.196201762 1.3801728
[5,] 2.32148727 -1.51292926 1.7808169 -0.135465061 -0.8747653
[6,] 1.03602597 1.12718811 0.6376310 -0.009445365 -1.4074674
[7,] -0.05036301 -1.04252829 -0.8978156 -1.079780864 0.3735876
[8,] 1.01912253 1.28759140 0.1640043 -1.126854167 - 0.2303916
[9,] 0.93337641 - 1.24223632 0.6052778 -0.003241698 0.2684704
[10,] 0.30957289 -1.39528971 -0.780391 0.946891126 -0.9375629
rownames(M2)<-c("R1","R2","R3","R4","R5","R6","R7","R8","R9","R10")
M2
[,1] [,2] [,3] [,4] [,5]
R1 -0.21369037 - 0.26807549 0.5780368 0.403231225 -0.3898034
R2 -1.05153856 -0.91487726 -0.2038823 0.904563419 0.4286243
R3 -0.10755935 0.36254026 -1.3386091 -0.218132138 0.3148615
R4 0.73045398 -0.09284451 -0.1476228 -1.196201762 1.3801728
R5 2.32148727 -1.51292926 1.7808169 -0.135465061 -0.8747653
R6 1.03602597 1.12718811 0.6376310 -0.009445365 - 1.4074674
R7 -0.05036301 -1.04252829 -0.8978156 -1.079780864 0.3735876
R8 1.01912253 1.28759140 0.1640043 -1.126854167 -0.2303916
R9 0.93337641 -1.24223632 0.6052778 -0.003241698 0.2684704
R10 0.30957289 -1.39528971 -0.7803917 0.946891126 -0.9375629
rownames(M2)<-NULL
M2
[,1] [,2] [,3] [,4] [,5]
[1,] -0.21369037 -0.26807549 0.5780368 0.403231225 -0.3898034
[2,] -1.05153856 -0.91487726 -0.2038823 0.904563419 0.4286243
[3,] -0.10755935 0.36254026 -1.3386091 -0.218132138 0.3148615
[4,] 0.73045398 -0.09284451 -0.1476228 - 1.196201762 1.3801728
[5,] 2.32148727 -1.51292926 1.7808169 -0.135465061 -0.8747653
[6,] 1.03602597 1.12718811 0.6376310 -0.009445365 -1.4074674
[7,] -0.05036301 -1.04252829 -0.8978156 - 1.079780864 0.3735876
[8,] 1.01912253 1.28759140 0.1640043 -1.126854167 -0.2303916
[9,] 0.93337641 -1.24223632 0.6052778 -0.003241698 0.2684704
[10,] 0.30957289 -1.39528971 -0.7803917 0.946891126 -0.9375629 | [
{
"code": null,
"e": 1385,
"s": 1062,
"text": "To remove the row names or column names from a matrix, we just need to set them to NULL, in this way all the names will be nullified. For example, if we have a matrix M that contain row names and column names then we can remove those names by using the command colnames(M)<-NULL for columns and rownames(M)<-NULL for rows."
},
{
"code": null,
"e": 1396,
"s": 1385,
"text": " Live Demo"
},
{
"code": null,
"e": 1425,
"s": 1396,
"text": "M1<-matrix(1:100,ncol=10)\nM1"
},
{
"code": null,
"e": 1844,
"s": 1425,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 1875,
"s": 1844,
"text": "colnames(M1)<-LETTERS[1:10]\nM1"
},
{
"code": null,
"e": 2249,
"s": 1875,
"text": " A B C D E F G H I J\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n [3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 1 4 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2271,
"s": 2249,
"text": "colnames(M1)<-NULL\nM1"
},
{
"code": null,
"e": 2667,
"s": 2271,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 2698,
"s": 2667,
"text": "rownames(M1)<-letters[1:10]\nM1"
},
{
"code": null,
"e": 3062,
"s": 2698,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n a 1 11 21 31 41 51 61 71 81 91\nb 2 12 22 32 42 52 62 72 82 92\nc 3 13 23 33 43 53 63 73 83 93\nd 4 14 24 34 44 54 64 74 84 94\ne 5 15 25 35 45 55 65 75 85 95\nf 6 16 26 36 46 56 66 76 86 96\ng 7 17 27 37 47 57 67 77 87 97\nh 8 18 28 38 48 58 68 78 88 98\ni 9 19 29 39 49 59 69 79 89 99\nj 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 3084,
"s": 3062,
"text": "rownames(M1)<-NULL\nM1"
},
{
"code": null,
"e": 3480,
"s": 3084,
"text": " [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100"
},
{
"code": null,
"e": 3491,
"s": 3480,
"text": " Live Demo"
},
{
"code": null,
"e": 3524,
"s": 3491,
"text": "M2<-matrix(rnorm(50),nrow=10)\nM2"
},
{
"code": null,
"e": 4210,
"s": 3524,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] 0.6802874 0.2144306 -1.4145804 0.62402960 -0.5938315\n[2,] 0.4536187 0.5653905 0.6312822 2.56036083 0.7728485\n[3,] 2.1096132 -0.7314662 0.3260058 -0.98057417 -0.3724911\n[4,] -0.5953890 0.6637290 -1.6762956 -1.61804847 0.8662887\n[5,] -0.7562208 -0.9417305 -1.7037116 0.60382315 -0.5236230\n[6,] -1.2611174 -2.1865329 -0.2465629 -2.00149510 -1.0256434\n[7,] 0.7827362 -0.8577172 1.1250864 -1.13954661 0.3187836\n[8,] -0.8423010 -1.7105257 -0.2722357 -0.05741225 -0.9454204\n[9,] -0.8249438 0.7572876 0.5679531 0.43816230 -1.5323482\n[10,] 1.0914719 -0.9003930 0.7307768 -0.12886355 -1.5271211"
},
{
"code": null,
"e": 4255,
"s": 4210,
"text": "colnames(M2)<-c(\"S1\",\"S2\",\"S3\",\"S4\",\"S5\")\nM2"
},
{
"code": null,
"e": 4986,
"s": 4255,
"text": " S1 S2 S3 S4 S5\n[1,] -0.21369037 -0.26807549 0.5780368 0.403231225 -0.3898034\n[2,] -1.05153856 -0.91487726 -0.2038823 0.904563419 0.4286243\n[3,] -0.10755935 0.36254026 -1.3386091 -0.218132138 0.3148615\n[4,] 0.73045398 -0.09284451 -0.1476228 -1.196201762 1.3801728\n[5,] 2.32148727 -1.51292926 1.7808169 -0.135465061 -0.8747653\n[6,] 1.03602597 1.12718811 0.6376310 -0.009445365 -1.4074674\n[7,] -0.05036301 -1.04252829 -0.8978156 -1.079780864 0.3735876\n[8,] 1.01912253 1.28759140 0.1640043 -1.126854167 -0.2303916\n[9,] 0.93337641 -1.24223632 0.6052778 -0.003241698 0.2684704\n[10,] 0.30957289 -1.39528971 -0.7803917 0.946891126 -0.9375629"
},
{
"code": null,
"e": 5008,
"s": 4986,
"text": "colnames(M2)<-NULL\nM2"
},
{
"code": null,
"e": 5663,
"s": 5008,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] -0.21369037 -0.26807549 0.5780368 0.403231225 -0.3898034\n [2,] -1.05153856 -0.91487726 -0.2038823 0.904563419 0.4286243\n[3,] -0.10755935 0.36254026 -1.3386091 -0.218132138 0.3148615\n[4,] 0.73045398 - 0.09284451 -0.1476228 -1.196201762 1.3801728\n[5,] 2.32148727 -1.51292926 1.7808169 -0.135465061 -0.8747653\n[6,] 1.03602597 1.12718811 0.6376310 -0.009445365 -1.4074674\n[7,] -0.05036301 -1.04252829 -0.8978156 -1.079780864 0.3735876\n[8,] 1.01912253 1.28759140 0.1640043 -1.126854167 - 0.2303916\n[9,] 0.93337641 - 1.24223632 0.6052778 -0.003241698 0.2684704\n[10,] 0.30957289 -1.39528971 -0.780391 0.946891126 -0.9375629"
},
{
"code": null,
"e": 5734,
"s": 5663,
"text": "rownames(M2)<-c(\"R1\",\"R2\",\"R3\",\"R4\",\"R5\",\"R6\",\"R7\",\"R8\",\"R9\",\"R10\")\nM2"
},
{
"code": null,
"e": 6368,
"s": 5734,
"text": " [,1] [,2] [,3] [,4] [,5]\nR1 -0.21369037 - 0.26807549 0.5780368 0.403231225 -0.3898034\n R2 -1.05153856 -0.91487726 -0.2038823 0.904563419 0.4286243\n R3 -0.10755935 0.36254026 -1.3386091 -0.218132138 0.3148615\n R4 0.73045398 -0.09284451 -0.1476228 -1.196201762 1.3801728\nR5 2.32148727 -1.51292926 1.7808169 -0.135465061 -0.8747653\nR6 1.03602597 1.12718811 0.6376310 -0.009445365 - 1.4074674\nR7 -0.05036301 -1.04252829 -0.8978156 -1.079780864 0.3735876\n R8 1.01912253 1.28759140 0.1640043 -1.126854167 -0.2303916\nR9 0.93337641 -1.24223632 0.6052778 -0.003241698 0.2684704\nR10 0.30957289 -1.39528971 -0.7803917 0.946891126 -0.9375629"
},
{
"code": null,
"e": 6390,
"s": 6368,
"text": "rownames(M2)<-NULL\nM2"
},
{
"code": null,
"e": 7042,
"s": 6390,
"text": " [,1] [,2] [,3] [,4] [,5]\n[1,] -0.21369037 -0.26807549 0.5780368 0.403231225 -0.3898034\n[2,] -1.05153856 -0.91487726 -0.2038823 0.904563419 0.4286243\n[3,] -0.10755935 0.36254026 -1.3386091 -0.218132138 0.3148615\n[4,] 0.73045398 -0.09284451 -0.1476228 - 1.196201762 1.3801728\n[5,] 2.32148727 -1.51292926 1.7808169 -0.135465061 -0.8747653\n[6,] 1.03602597 1.12718811 0.6376310 -0.009445365 -1.4074674\n[7,] -0.05036301 -1.04252829 -0.8978156 - 1.079780864 0.3735876\n[8,] 1.01912253 1.28759140 0.1640043 -1.126854167 -0.2303916\n[9,] 0.93337641 -1.24223632 0.6052778 -0.003241698 0.2684704\n[10,] 0.30957289 -1.39528971 -0.7803917 0.946891126 -0.9375629"
}
]
|
Deploy a Machine Learning Model from a Jupyter Notebook | by Brandon Walker | Towards Data Science | To put it frankly, if you can’t get your machine learning models out of a notebook, it’s probably not going to get used. This article should help you create a deployment of your model as quickly as possible, so that you can infuse your models with business processes. This is an important skill to have since it means you won’t be relying on a software engineer/developer to assist you.
To do this we will use Watson Machine Learning, and a Jupyter Notebook. I will assume you already have Anaconda or another environment that can run notebooks. Here is an outline that we will follow, feel free to skip steps that you may have already completed:
Create an IBM Cloud account. (~2 minutes)Create a Watson Machine Learning (WML) instance. (~2 minutes)Obtain an API key. (~1 minute)Create a deployment space that can store models. (~1 minute)Create a machine learning model. (~1 minute, unless you are creating your own model)Deploy your model. (~4 minutes)Try sending your deployed model data. (~2 minutes)
Create an IBM Cloud account. (~2 minutes)
Create a Watson Machine Learning (WML) instance. (~2 minutes)
Obtain an API key. (~1 minute)
Create a deployment space that can store models. (~1 minute)
Create a machine learning model. (~1 minute, unless you are creating your own model)
Deploy your model. (~4 minutes)
Try sending your deployed model data. (~2 minutes)
Visit the registration page for IBM Cloud and follow the instructions there.
Once you’ve logged in, this should be the screen you are presented with. You can click the Catalog button in the banner at the top and scroll until you find Machine Learning, or use the search bar to find it.
After selecting Watson Machine Learning, create an free Lite instance by clicking the create button in the bottom right. Be sure to keep track of what region you have selected, for me that is Dallas.
As you see above, Watson Machine Learning comes with 20 free capacity units per month during which models can be trained, evaluated, deployed, and scored. If you are operating with a limited budget, I’d recommend training you model on your local environment, and saving your capacity units for scoring. For smaller models that won’t be called very frequently, this is probably enough.
To get a key visit the API key management page of your IBM Cloud Account. You can then click “Create an IBM Cloud API key” to make a new key, and supply a key name and description. I gave “wml-api-key” for my key’s name.
Once you’ve created your API key, copy it and paste it into your notebook so we can use it.
A Deployment Space is where you can store and manage all your deployed models. I’d recommend having one deployment space for each business purpose. Visit your deployment spaces page to create a new deployment.
From here on out, we will be writing python code in a notebook.
I’m going to keep this very simple and create a KNN model for the iris data set. While you should make something related to your business use case, this model is enough to demonstrate how to use WML. You can copy and paste the cell below if you aren’t making your own model.
import sklearnfrom sklearn.datasets import load_irisiris = load_iris()X = iris.dataY = iris.targetclf = sklearn.neighbors.KNeighborsClassifier()clf.fit(X, Y)
You will need to install the IBM Watson Machine Learning python SDK. You can do that by running pip install ibm-watson-machine-learning in the command line. You can also run this in it’s own cell in your notebook like this:!pip install ibm-watson-machine-learning.
You can start your code by importing the Watson Machine Learning package and supplying your API key and region. If you don’t know what value you should supply for location you should use check the city your instance is in. You take that city and find the region by consulting the locations page. Since my instance is in Dallas, I supplied “us-south” for the location variable below.
from ibm_watson_machine_learning import APIClientapi_key = "<your-key>"location = "<your-region>"
These can be supplied as credentials.
wml_credentials = { "apikey": api_key, "url": 'https://' + location + '.ml.cloud.ibm.com'}client = APIClient(wml_credentials)
We need to get the ID of your deployment space. You can do that by running the code below.
client.spaces.list()
From the output of the above you will get an ID for your deployment space. Set your APIClient to use your deployment space with the code below.
client.set.default_space("<ID>")
Before we deploy our model, we need to publish it. First we have to decide what version of python we want to use and set some metadata. If you need to figure out what version of python you are using run import sys then sys.version.
If you are also deploying a model based on sklearn, you will need to determine the version of that. You can run sklearn.__version__ to figure that out.
metadata = { client.repository.ModelMetaNames.NAME: 'Iris KNN Model', client.repository.ModelMetaNames.TYPE: 'scikit-learn_0.22', client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sofware_spec_uid}published_model = client.repository.store_model( model=clf, meta_props=metadata, training_data=iris.data, training_target=iris.feature_names)
You will need to get the ID of your published model. You can get that by running the following.
models_details = client.repository.list_models()
To deploy your model use your published model’s ID from the cell above and run the code below.
metadata = { client.deployments.ConfigurationMetaNames.NAME: "Deployment of Iris KNN Model", client.deployments.ConfigurationMetaNames.ONLINE: {}}created_deployment = client.deployments.create("<your-published-model-id>", meta_props=metadata)
Your model is now deployed and we can now send data to it and get a response. First we need to get the ID of the deployed model by running the code below.
client.deployments.list()
We can then use that ID and send observations in a list of lists.
scoring_payload = {"input_data": [{"values": [[5.1, 3.5, 1.4, 0.2]]}]}predictions = client.deployments.score("<your-deployment-id>", scoring_payload)
In the predictions variable we now have a stored a prediction of the class and probability of each class.
If your work is going to make a large impact it has to appear somewhere other than a PowerPoint. For many data scientists a notebook is the primary development environment for machine learning models, if you don’t want to burden yourself with packaging the model and its dependencies into something that can be run on both your computer and your production server, then this is the way to go. Besides the complications of all of that, this is the simplest workflow in terms of knowledge you have to acquire to make ML models work in production, which may be the fastest way to adopt AI in your business. | [
{
"code": null,
"e": 559,
"s": 172,
"text": "To put it frankly, if you can’t get your machine learning models out of a notebook, it’s probably not going to get used. This article should help you create a deployment of your model as quickly as possible, so that you can infuse your models with business processes. This is an important skill to have since it means you won’t be relying on a software engineer/developer to assist you."
},
{
"code": null,
"e": 819,
"s": 559,
"text": "To do this we will use Watson Machine Learning, and a Jupyter Notebook. I will assume you already have Anaconda or another environment that can run notebooks. Here is an outline that we will follow, feel free to skip steps that you may have already completed:"
},
{
"code": null,
"e": 1177,
"s": 819,
"text": "Create an IBM Cloud account. (~2 minutes)Create a Watson Machine Learning (WML) instance. (~2 minutes)Obtain an API key. (~1 minute)Create a deployment space that can store models. (~1 minute)Create a machine learning model. (~1 minute, unless you are creating your own model)Deploy your model. (~4 minutes)Try sending your deployed model data. (~2 minutes)"
},
{
"code": null,
"e": 1219,
"s": 1177,
"text": "Create an IBM Cloud account. (~2 minutes)"
},
{
"code": null,
"e": 1281,
"s": 1219,
"text": "Create a Watson Machine Learning (WML) instance. (~2 minutes)"
},
{
"code": null,
"e": 1312,
"s": 1281,
"text": "Obtain an API key. (~1 minute)"
},
{
"code": null,
"e": 1373,
"s": 1312,
"text": "Create a deployment space that can store models. (~1 minute)"
},
{
"code": null,
"e": 1458,
"s": 1373,
"text": "Create a machine learning model. (~1 minute, unless you are creating your own model)"
},
{
"code": null,
"e": 1490,
"s": 1458,
"text": "Deploy your model. (~4 minutes)"
},
{
"code": null,
"e": 1541,
"s": 1490,
"text": "Try sending your deployed model data. (~2 minutes)"
},
{
"code": null,
"e": 1618,
"s": 1541,
"text": "Visit the registration page for IBM Cloud and follow the instructions there."
},
{
"code": null,
"e": 1827,
"s": 1618,
"text": "Once you’ve logged in, this should be the screen you are presented with. You can click the Catalog button in the banner at the top and scroll until you find Machine Learning, or use the search bar to find it."
},
{
"code": null,
"e": 2027,
"s": 1827,
"text": "After selecting Watson Machine Learning, create an free Lite instance by clicking the create button in the bottom right. Be sure to keep track of what region you have selected, for me that is Dallas."
},
{
"code": null,
"e": 2412,
"s": 2027,
"text": "As you see above, Watson Machine Learning comes with 20 free capacity units per month during which models can be trained, evaluated, deployed, and scored. If you are operating with a limited budget, I’d recommend training you model on your local environment, and saving your capacity units for scoring. For smaller models that won’t be called very frequently, this is probably enough."
},
{
"code": null,
"e": 2633,
"s": 2412,
"text": "To get a key visit the API key management page of your IBM Cloud Account. You can then click “Create an IBM Cloud API key” to make a new key, and supply a key name and description. I gave “wml-api-key” for my key’s name."
},
{
"code": null,
"e": 2725,
"s": 2633,
"text": "Once you’ve created your API key, copy it and paste it into your notebook so we can use it."
},
{
"code": null,
"e": 2935,
"s": 2725,
"text": "A Deployment Space is where you can store and manage all your deployed models. I’d recommend having one deployment space for each business purpose. Visit your deployment spaces page to create a new deployment."
},
{
"code": null,
"e": 2999,
"s": 2935,
"text": "From here on out, we will be writing python code in a notebook."
},
{
"code": null,
"e": 3274,
"s": 2999,
"text": "I’m going to keep this very simple and create a KNN model for the iris data set. While you should make something related to your business use case, this model is enough to demonstrate how to use WML. You can copy and paste the cell below if you aren’t making your own model."
},
{
"code": null,
"e": 3432,
"s": 3274,
"text": "import sklearnfrom sklearn.datasets import load_irisiris = load_iris()X = iris.dataY = iris.targetclf = sklearn.neighbors.KNeighborsClassifier()clf.fit(X, Y)"
},
{
"code": null,
"e": 3697,
"s": 3432,
"text": "You will need to install the IBM Watson Machine Learning python SDK. You can do that by running pip install ibm-watson-machine-learning in the command line. You can also run this in it’s own cell in your notebook like this:!pip install ibm-watson-machine-learning."
},
{
"code": null,
"e": 4080,
"s": 3697,
"text": "You can start your code by importing the Watson Machine Learning package and supplying your API key and region. If you don’t know what value you should supply for location you should use check the city your instance is in. You take that city and find the region by consulting the locations page. Since my instance is in Dallas, I supplied “us-south” for the location variable below."
},
{
"code": null,
"e": 4178,
"s": 4080,
"text": "from ibm_watson_machine_learning import APIClientapi_key = \"<your-key>\"location = \"<your-region>\""
},
{
"code": null,
"e": 4216,
"s": 4178,
"text": "These can be supplied as credentials."
},
{
"code": null,
"e": 4348,
"s": 4216,
"text": "wml_credentials = { \"apikey\": api_key, \"url\": 'https://' + location + '.ml.cloud.ibm.com'}client = APIClient(wml_credentials)"
},
{
"code": null,
"e": 4439,
"s": 4348,
"text": "We need to get the ID of your deployment space. You can do that by running the code below."
},
{
"code": null,
"e": 4460,
"s": 4439,
"text": "client.spaces.list()"
},
{
"code": null,
"e": 4604,
"s": 4460,
"text": "From the output of the above you will get an ID for your deployment space. Set your APIClient to use your deployment space with the code below."
},
{
"code": null,
"e": 4637,
"s": 4604,
"text": "client.set.default_space(\"<ID>\")"
},
{
"code": null,
"e": 4869,
"s": 4637,
"text": "Before we deploy our model, we need to publish it. First we have to decide what version of python we want to use and set some metadata. If you need to figure out what version of python you are using run import sys then sys.version."
},
{
"code": null,
"e": 5021,
"s": 4869,
"text": "If you are also deploying a model based on sklearn, you will need to determine the version of that. You can run sklearn.__version__ to figure that out."
},
{
"code": null,
"e": 5383,
"s": 5021,
"text": "metadata = { client.repository.ModelMetaNames.NAME: 'Iris KNN Model', client.repository.ModelMetaNames.TYPE: 'scikit-learn_0.22', client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sofware_spec_uid}published_model = client.repository.store_model( model=clf, meta_props=metadata, training_data=iris.data, training_target=iris.feature_names)"
},
{
"code": null,
"e": 5479,
"s": 5383,
"text": "You will need to get the ID of your published model. You can get that by running the following."
},
{
"code": null,
"e": 5528,
"s": 5479,
"text": "models_details = client.repository.list_models()"
},
{
"code": null,
"e": 5623,
"s": 5528,
"text": "To deploy your model use your published model’s ID from the cell above and run the code below."
},
{
"code": null,
"e": 5872,
"s": 5623,
"text": "metadata = { client.deployments.ConfigurationMetaNames.NAME: \"Deployment of Iris KNN Model\", client.deployments.ConfigurationMetaNames.ONLINE: {}}created_deployment = client.deployments.create(\"<your-published-model-id>\", meta_props=metadata)"
},
{
"code": null,
"e": 6027,
"s": 5872,
"text": "Your model is now deployed and we can now send data to it and get a response. First we need to get the ID of the deployed model by running the code below."
},
{
"code": null,
"e": 6053,
"s": 6027,
"text": "client.deployments.list()"
},
{
"code": null,
"e": 6119,
"s": 6053,
"text": "We can then use that ID and send observations in a list of lists."
},
{
"code": null,
"e": 6269,
"s": 6119,
"text": "scoring_payload = {\"input_data\": [{\"values\": [[5.1, 3.5, 1.4, 0.2]]}]}predictions = client.deployments.score(\"<your-deployment-id>\", scoring_payload)"
},
{
"code": null,
"e": 6375,
"s": 6269,
"text": "In the predictions variable we now have a stored a prediction of the class and probability of each class."
}
]
|
Python - find_element_by_id() method in Selenium - GeeksforGeeks | 01 Jun, 2021
While performing any action on a web page using selenium, there is need of locators to perform specific tasks.Locators in web page are used to identify unique elements within a webpage. Web elements could be anything that the user sees on the page, such as title, table, links, buttons, toggle button, or any other HTML element.In order to find element by ID find_element_by_id() method is used. Id is basically unique attribute assigned to the elements of the web page such as buttons, image, heading etc.Syntax :
driver.find_element_by_id(ID)
Argument :
Takes ID in string format
Note :The first element with the ID attribute value matching the location will be returned. If no element has a matching ID attribute, a NoSuchElementException will be raised.Example 1 : – Consider the following page source :
Below is the code for finding the element i.e “geek_id”
Python3
#importing webdriver from seleniumfrom selenium import webdriver # Here Chrome will be useddriver=webdriver.Chrome() # Opening the websitedriver.get(url) # finds button using its idform = driver.find_element_by_id('geek_id')
The form element can be located like this.Example : Source code of https://www.geeksforgeeks.org/ is given below.
Below is the code for finding the scroll button with the help of its ID i.e scrollTopBtn.
Python3
#importing webdriver from seleniumfrom selenium import webdriver # Here Chrome will be useddriver=webdriver.Chrome() # URL of websiteurl = "https://www.geeksforgeeks.org/" # Opening the websitedriver.get(url) # finds button using its idbt = driver.find_element_by_id('scrollTopBtn')
With this code we can locate the scroll top button of this site.
clintra
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 24720,
"s": 24692,
"text": "\n01 Jun, 2021"
},
{
"code": null,
"e": 25237,
"s": 24720,
"text": "While performing any action on a web page using selenium, there is need of locators to perform specific tasks.Locators in web page are used to identify unique elements within a webpage. Web elements could be anything that the user sees on the page, such as title, table, links, buttons, toggle button, or any other HTML element.In order to find element by ID find_element_by_id() method is used. Id is basically unique attribute assigned to the elements of the web page such as buttons, image, heading etc.Syntax : "
},
{
"code": null,
"e": 25267,
"s": 25237,
"text": "driver.find_element_by_id(ID)"
},
{
"code": null,
"e": 25280,
"s": 25267,
"text": "Argument : "
},
{
"code": null,
"e": 25306,
"s": 25280,
"text": "Takes ID in string format"
},
{
"code": null,
"e": 25534,
"s": 25306,
"text": "Note :The first element with the ID attribute value matching the location will be returned. If no element has a matching ID attribute, a NoSuchElementException will be raised.Example 1 : – Consider the following page source : "
},
{
"code": null,
"e": 25592,
"s": 25534,
"text": "Below is the code for finding the element i.e “geek_id” "
},
{
"code": null,
"e": 25600,
"s": 25592,
"text": "Python3"
},
{
"code": "#importing webdriver from seleniumfrom selenium import webdriver # Here Chrome will be useddriver=webdriver.Chrome() # Opening the websitedriver.get(url) # finds button using its idform = driver.find_element_by_id('geek_id')",
"e": 25826,
"s": 25600,
"text": null
},
{
"code": null,
"e": 25942,
"s": 25826,
"text": "The form element can be located like this.Example : Source code of https://www.geeksforgeeks.org/ is given below. "
},
{
"code": null,
"e": 26034,
"s": 25942,
"text": "Below is the code for finding the scroll button with the help of its ID i.e scrollTopBtn. "
},
{
"code": null,
"e": 26042,
"s": 26034,
"text": "Python3"
},
{
"code": "#importing webdriver from seleniumfrom selenium import webdriver # Here Chrome will be useddriver=webdriver.Chrome() # URL of websiteurl = \"https://www.geeksforgeeks.org/\" # Opening the websitedriver.get(url) # finds button using its idbt = driver.find_element_by_id('scrollTopBtn')",
"e": 26326,
"s": 26042,
"text": null
},
{
"code": null,
"e": 26392,
"s": 26326,
"text": "With this code we can locate the scroll top button of this site. "
},
{
"code": null,
"e": 26400,
"s": 26392,
"text": "clintra"
},
{
"code": null,
"e": 26416,
"s": 26400,
"text": "Python-selenium"
},
{
"code": null,
"e": 26425,
"s": 26416,
"text": "selenium"
},
{
"code": null,
"e": 26432,
"s": 26425,
"text": "Python"
},
{
"code": null,
"e": 26530,
"s": 26432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26539,
"s": 26530,
"text": "Comments"
},
{
"code": null,
"e": 26552,
"s": 26539,
"text": "Old Comments"
},
{
"code": null,
"e": 26570,
"s": 26552,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26602,
"s": 26570,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26624,
"s": 26602,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26659,
"s": 26624,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26689,
"s": 26659,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26731,
"s": 26689,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26774,
"s": 26731,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26818,
"s": 26774,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26839,
"s": 26818,
"text": "Python OOPs Concepts"
}
]
|
Th3Inspector - OSINT Tool for Reconnaissance - GeeksforGeeks | 18 Jul, 2021
Th3 Inspector is an OSINT tool used for information gathering and reconnaissance which is available on Github. One can easily find a lot of information about the target, such as details about the server, whois info, target IP, mobile number, email, sub-domains, etc.
Open your terminal and type the following command to clone the tool.
git clone https://github.com/Moham3dRiahi/Th3inspector.git
To run this tool, we need to give the executable permissions to install.sh file, type the following command:
chmod +x install.sh && ./install.sh
Fig 1: Installation of Th3Inspector.
Now, let’s run this tool by typing this in the terminal.
perl Th3Inspector.pl
Fig 2: Options provided by Th3Inspector.
Let us examine all the options available.
Target: www.google.com
Result:
Fig 3: Website information.
As we can see, this tool has provided us with the info regarding how many visitors per day visit Google.com, its hosting country, and address, its IP address, etc.
Target: +4158586273
Result:
Fig 4: Phone number Information:
Target: github.com
Result:
Fig 5: Find IP address and Email Server.
Target: thehackernews.com
Result:
Fig 6: Domain Whois Lookup
Target: 104.215.148.63
Result:
Fig 7: IP address location.
Target: csfavorito.org
Result:
Fig 8: Bypass CLoudfare.
Target: youtube.com
Result:
Fig 9: Domain age checker.
Target: Mozilla/5.0 (x11; Ubuntu; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0
Result:
Fig 10: User agent info.
Target: goair.in
Result:
Fig 11: Check Active Services on Resources.
Target: 474201
Result:
Fig 12: Credit card Bin Checker
Target: microsoft.com
Result:
Fig 13: Microsoft subdomains
Target: [email protected]
Result:
Fig 14: Valid E-Mail address.
Target: rentcarwithdriver.ro
Result:
Fig 15: Content Management System Checker.
We can see from the above examples that the Th3Inspector tool can prove to be very useful in finding information about the target. Tools like Th3Inspector are the complete package and offer a lot of options ranging from finding domain age or whether an email address is valid or not.So, it is a very powerful tool and should be used with the utmost care.
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples | [
{
"code": null,
"e": 24040,
"s": 24012,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 24307,
"s": 24040,
"text": "Th3 Inspector is an OSINT tool used for information gathering and reconnaissance which is available on Github. One can easily find a lot of information about the target, such as details about the server, whois info, target IP, mobile number, email, sub-domains, etc."
},
{
"code": null,
"e": 24376,
"s": 24307,
"text": "Open your terminal and type the following command to clone the tool."
},
{
"code": null,
"e": 24435,
"s": 24376,
"text": "git clone https://github.com/Moham3dRiahi/Th3inspector.git"
},
{
"code": null,
"e": 24544,
"s": 24435,
"text": "To run this tool, we need to give the executable permissions to install.sh file, type the following command:"
},
{
"code": null,
"e": 24580,
"s": 24544,
"text": "chmod +x install.sh && ./install.sh"
},
{
"code": null,
"e": 24617,
"s": 24580,
"text": "Fig 1: Installation of Th3Inspector."
},
{
"code": null,
"e": 24675,
"s": 24617,
"text": " Now, let’s run this tool by typing this in the terminal."
},
{
"code": null,
"e": 24696,
"s": 24675,
"text": "perl Th3Inspector.pl"
},
{
"code": null,
"e": 24737,
"s": 24696,
"text": "Fig 2: Options provided by Th3Inspector."
},
{
"code": null,
"e": 24779,
"s": 24737,
"text": "Let us examine all the options available."
},
{
"code": null,
"e": 24802,
"s": 24779,
"text": "Target: www.google.com"
},
{
"code": null,
"e": 24810,
"s": 24802,
"text": "Result:"
},
{
"code": null,
"e": 24838,
"s": 24810,
"text": "Fig 3: Website information."
},
{
"code": null,
"e": 25002,
"s": 24838,
"text": "As we can see, this tool has provided us with the info regarding how many visitors per day visit Google.com, its hosting country, and address, its IP address, etc."
},
{
"code": null,
"e": 25022,
"s": 25002,
"text": "Target: +4158586273"
},
{
"code": null,
"e": 25030,
"s": 25022,
"text": "Result:"
},
{
"code": null,
"e": 25063,
"s": 25030,
"text": "Fig 4: Phone number Information:"
},
{
"code": null,
"e": 25082,
"s": 25063,
"text": "Target: github.com"
},
{
"code": null,
"e": 25090,
"s": 25082,
"text": "Result:"
},
{
"code": null,
"e": 25132,
"s": 25090,
"text": "Fig 5: Find IP address and Email Server."
},
{
"code": null,
"e": 25158,
"s": 25132,
"text": "Target: thehackernews.com"
},
{
"code": null,
"e": 25166,
"s": 25158,
"text": "Result:"
},
{
"code": null,
"e": 25193,
"s": 25166,
"text": "Fig 6: Domain Whois Lookup"
},
{
"code": null,
"e": 25216,
"s": 25193,
"text": "Target: 104.215.148.63"
},
{
"code": null,
"e": 25224,
"s": 25216,
"text": "Result:"
},
{
"code": null,
"e": 25252,
"s": 25224,
"text": "Fig 7: IP address location."
},
{
"code": null,
"e": 25275,
"s": 25252,
"text": "Target: csfavorito.org"
},
{
"code": null,
"e": 25283,
"s": 25275,
"text": "Result:"
},
{
"code": null,
"e": 25308,
"s": 25283,
"text": "Fig 8: Bypass CLoudfare."
},
{
"code": null,
"e": 25328,
"s": 25308,
"text": "Target: youtube.com"
},
{
"code": null,
"e": 25336,
"s": 25328,
"text": "Result:"
},
{
"code": null,
"e": 25363,
"s": 25336,
"text": "Fig 9: Domain age checker."
},
{
"code": null,
"e": 25449,
"s": 25363,
"text": "Target: Mozilla/5.0 (x11; Ubuntu; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"
},
{
"code": null,
"e": 25457,
"s": 25449,
"text": "Result:"
},
{
"code": null,
"e": 25482,
"s": 25457,
"text": "Fig 10: User agent info."
},
{
"code": null,
"e": 25499,
"s": 25482,
"text": "Target: goair.in"
},
{
"code": null,
"e": 25507,
"s": 25499,
"text": "Result:"
},
{
"code": null,
"e": 25551,
"s": 25507,
"text": "Fig 11: Check Active Services on Resources."
},
{
"code": null,
"e": 25566,
"s": 25551,
"text": "Target: 474201"
},
{
"code": null,
"e": 25574,
"s": 25566,
"text": "Result:"
},
{
"code": null,
"e": 25606,
"s": 25574,
"text": "Fig 12: Credit card Bin Checker"
},
{
"code": null,
"e": 25628,
"s": 25606,
"text": "Target: microsoft.com"
},
{
"code": null,
"e": 25636,
"s": 25628,
"text": "Result:"
},
{
"code": null,
"e": 25665,
"s": 25636,
"text": "Fig 13: Microsoft subdomains"
},
{
"code": null,
"e": 25699,
"s": 25665,
"text": "Target: [email protected]"
},
{
"code": null,
"e": 25707,
"s": 25699,
"text": "Result:"
},
{
"code": null,
"e": 25737,
"s": 25707,
"text": "Fig 14: Valid E-Mail address."
},
{
"code": null,
"e": 25766,
"s": 25737,
"text": "Target: rentcarwithdriver.ro"
},
{
"code": null,
"e": 25774,
"s": 25766,
"text": "Result:"
},
{
"code": null,
"e": 25817,
"s": 25774,
"text": "Fig 15: Content Management System Checker."
},
{
"code": null,
"e": 26172,
"s": 25817,
"text": "We can see from the above examples that the Th3Inspector tool can prove to be very useful in finding information about the target. Tools like Th3Inspector are the complete package and offer a lot of options ranging from finding domain age or whether an email address is valid or not.So, it is a very powerful tool and should be used with the utmost care."
},
{
"code": null,
"e": 26184,
"s": 26172,
"text": "Linux-Tools"
},
{
"code": null,
"e": 26195,
"s": 26184,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26293,
"s": 26195,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26302,
"s": 26293,
"text": "Comments"
},
{
"code": null,
"e": 26315,
"s": 26302,
"text": "Old Comments"
},
{
"code": null,
"e": 26350,
"s": 26315,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26387,
"s": 26350,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26421,
"s": 26387,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26447,
"s": 26421,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26473,
"s": 26447,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26510,
"s": 26473,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26550,
"s": 26510,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 26579,
"s": 26550,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26621,
"s": 26579,
"text": "Named Pipe or FIFO with example C program"
}
]
|
Java How To Add Two Numbers | Learn how to add two numbers in Java:
int x = 5;
int y = 6;
int sum = x + y;
System.out.println(sum); // Print the sum of x + y
Learn how to add two numbers with user input:
import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
int x, y, sum;
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Type a number:");
x = myObj.nextInt(); // Read user input
System.out.println("Type another number:");
y = myObj.nextInt(); // Read user input
sum = x + y; // Calculate the sum of x + y
System.out.println("Sum is: " + sum); // Print the sum
}
}
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": 38,
"s": 0,
"text": "Learn how to add two numbers in Java:"
},
{
"code": null,
"e": 128,
"s": 38,
"text": "int x = 5;\nint y = 6;\nint sum = x + y;\nSystem.out.println(sum); // Print the sum of x + y"
},
{
"code": null,
"e": 174,
"s": 128,
"text": "Learn how to add two numbers with user input:"
},
{
"code": null,
"e": 672,
"s": 174,
"text": "import java.util.Scanner; // Import the Scanner class\n\nclass MyClass {\n public static void main(String[] args) {\n int x, y, sum;\n Scanner myObj = new Scanner(System.in); // Create a Scanner object\n System.out.println(\"Type a number:\");\n x = myObj.nextInt(); // Read user input\n\n System.out.println(\"Type another number:\");\n y = myObj.nextInt(); // Read user input\n\n sum = x + y; // Calculate the sum of x + y\n System.out.println(\"Sum is: \" + sum); // Print the sum\n }\n} "
},
{
"code": null,
"e": 705,
"s": 672,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 747,
"s": 705,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 854,
"s": 747,
"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": 873,
"s": 854,
"text": "[email protected]"
}
]
|
Cleaning Text Data with Python | Towards Data Science | The data format is not always on tabular format. As we are getting into the big data era, the data comes with a pretty diverse format, including images, texts, graphs, and many more.
Because the format is pretty diverse, ranging from one data to another, it’s really essential to preprocess those data into a readable format to computers.
In this article, I want to show you on how to preprocess texts data using Python. As mention on the title, all you need is NLTK and re library.
To show you how this work, I will take a dataset from a Kaggle competition called Real or Not? NLP with Disaster Tweets.
I have created a Google Colab notebook if you want to follow along with me. To access, you can click on this link here
Before we are getting into processing our texts, it’s better to lowercase all of the characters first. The reason why we are doing this is to avoid any case-sensitive process.
Suppose we want to remove stop words from our string, and the technique that we use is to take the non-stop words and combine those as a sentence. If we are not lowercase those, the stop word cannot be detected, and it will result in the same string. That’s why lowering case on texts is essential.
To do this in Python is easy. The code looks like this,
# Examplex = "Watch This Airport Get Swallowed Up By A Sandstorm In Under A Minute http://t.co/TvYQczGJdy"# Lowercase the textx = x.lower()print(x)>>> watch this airport get swallowed up by a sandstorm in under a minute http://t.co/tvyqczgjdy
Some tweets could contain a Unicode character that is unreadable when we see it on an ASCII format. Mostly, those characters are used for emojis and non-ASCII characters. To remove this, we can use code like this one,
# Examplex = "Reddit Will Now QuarantineÛ_ http://t.co/pkUAMXw6pm #onlinecommunities #reddit #amageddon #freespeech #Business http://t.co/PAWvNJ4sAP"# Remove unicode charactersx = x.encode('ascii', 'ignore').decode()print(x)>>> Reddit Will Now Quarantine_ http://t.co/pkUAMXw6pm #onlinecommunities #reddit #amageddon #freespeech #Business http://t.co/PAWvNJ4sAP
After we do that, we can remove words that belong to stop words. Stop word is a type of word that has no significant contribution to the meaning of the text. Because of that, we can remove those words. To retrieve the stop words, we can download a corpus from the NLTK library. Here is the code on how to do this,
import nltknltk.download()# just download all-nltkstop_words = stopwords.words("english")# Examplex = "America like South Africa is a traumatised sick country - in different ways of course - but still messed up."# Remove stop wordsx = ' '.join([word for word in x.split(' ') if word not in stop_words])print(x)>>> America like South Africa traumatised sick country - different ways course - still messed up.
Besides we remove the Unicode and stop words, there are several terms that we should remove, including mentions, hashtags, links, punctuations, etc.
To remove those, it’s challenging if we rely only on a defined character. Therefore, we need patterns that can match terms that we desire by using something called Regular Expression (Regex).
Regex is a special string that contains a pattern that can match words associated with that pattern. By using it, we can search or remove those based on patterns using a Python library called re. To do this, we can implement it like this,
import re# Remove mentionsx = "@DDNewsLive @NitishKumar and @ArvindKejriwal can't survive without referring @@narendramodi . Without Mr Modi they are BIG ZEROS"x = re.sub("@\S+", " ", x)print(x)>>> and can't survive without referring . Without Mr Modi they are BIG ZEROS# Remove URLx = "Severe Thunderstorm pictures from across the Mid-South http://t.co/UZWLgJQzNS"x = re.sub("https*\S+", " ", x)print(x)>>> Severe Thunderstorm pictures from across the Mid-South# Remove Hashtagsx = "Are people not concerned that after #SLAB's obliteration in Scotland #Labour UK is ripping itself apart over #Labourleadership contest?"x = re.sub("#\S+", " ", x)print(x)>>> Are people not concerned that after obliteration in Scotland UK is ripping itself apart over contest?# Remove ticks and the next characterx = "Notley's tactful yet very direct response to Harper's attack on Alberta's gov't. Hell YEAH Premier! http://t.co/rzSUlzMOkX #ableg #cdnpoli"x = re.sub("\'\w+", '', x)print(x)>>> Notley tactful yet very direct response to Harper attack on Alberta gov. Hell YEAH Premier! http://t.co/rzSUlzMOkX #ableg #cdnpoli# Remove punctuationsx = "In 2014 I will only smoke crqck if I becyme a mayor. This includes Foursquare."x = re.sub('[%s]' % re.escape(string.punctuation), ' ', x)print(x)>>> In 2014 I will only smoke crqck if I becyme a mayor. This includes Foursquare.# Remove numbersx = "C-130 specially modified to land in a stadium and rescue hostages in Iran in 1980... http://t.co/tNI92fea3u http://t.co/czBaMzq3gL"x = re.sub(r'\w*\d+\w*', '', x)print(x)>>> C- specially modified to land in a stadium and rescue hostages in Iran in ... http://t.co/ http://t.co/# Replace the over spacesx = " and can't survive without referring . Without Mr Modi they are BIG ZEROS"x = re.sub('\s{2,}', " ", x)print(x)>>> and can't survive without referring . Without Mr Modi they are BIG ZEROS
After you know each step on preprocessing texts, Let’s apply this to a list. If you look closer at the steps in detail, you will see that each method is related to each other. Therefore, it’s essential to apply it on a function so we can process it all the same time sequentially. Before we apply the preprocessing steps, here are the preview of sampled texts,
Our Deeds are the Reason of this #earthquake May ALLAH Forgive us allForest fire near La Ronge Sask. CanadaAll residents asked to 'shelter in place' are being notified by officers. No other evacuation or shelter in place orders are expected13,000 people receive #wildfires evacuation orders in California Just got sent this photo from Ruby #Alaska as smoke from #wildfires pours into a school
There are several steps that we should do for preprocessing a list of texts. They are,
Create a function that contains all of the preprocessing steps, and it returns a preprocessed stringApply the function using a method called apply and chain the list with that method.
Create a function that contains all of the preprocessing steps, and it returns a preprocessed string
Apply the function using a method called apply and chain the list with that method.
The code will look like this,
# # In case of import errors# ! pip install nltk# ! pip install textblobimport numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport reimport nltkimport stringfrom nltk.corpus import stopwords# # In case of any corpus are missing # download all-nltknltk.download()df = pd.read_csv('train.csv')stop_words = stopwords.words("english")wordnet = WordNetLemmatizer()def text_preproc(x): x = x.lower() x = ' '.join([word for word in x.split(' ') if word not in stop_words]) x = x.encode('ascii', 'ignore').decode() x = re.sub(r'https*\S+', ' ', x) x = re.sub(r'@\S+', ' ', x) x = re.sub(r'#\S+', ' ', x) x = re.sub(r'\'\w+', '', x) x = re.sub('[%s]' % re.escape(string.punctuation), ' ', x) x = re.sub(r'\w*\d+\w*', '', x) x = re.sub(r'\s{2,}', ' ', x) return xdf['clean_text'] = df.text.apply(text_preproc)
And here is the result from it,
deeds reason may allah forgive usforest fire near la ronge sask canadaresidents asked place notified officers evacuation shelter place orders expected people receive evacuation orders california got sent photo ruby smoke pours school
That is how to preprocess texts using Python. I hope you can apply it to solve problems related to text data. If you have any thoughts, you can comment down below. Also, you can follow me on Medium so you can follow up to my articles. Thank you.
[1] https://docs.python.org/3/library/re.html[2] https://www.nltk.org/[3] https://www.kaggle.com/c/nlp-getting-started/overview | [
{
"code": null,
"e": 355,
"s": 172,
"text": "The data format is not always on tabular format. As we are getting into the big data era, the data comes with a pretty diverse format, including images, texts, graphs, and many more."
},
{
"code": null,
"e": 511,
"s": 355,
"text": "Because the format is pretty diverse, ranging from one data to another, it’s really essential to preprocess those data into a readable format to computers."
},
{
"code": null,
"e": 655,
"s": 511,
"text": "In this article, I want to show you on how to preprocess texts data using Python. As mention on the title, all you need is NLTK and re library."
},
{
"code": null,
"e": 776,
"s": 655,
"text": "To show you how this work, I will take a dataset from a Kaggle competition called Real or Not? NLP with Disaster Tweets."
},
{
"code": null,
"e": 895,
"s": 776,
"text": "I have created a Google Colab notebook if you want to follow along with me. To access, you can click on this link here"
},
{
"code": null,
"e": 1071,
"s": 895,
"text": "Before we are getting into processing our texts, it’s better to lowercase all of the characters first. The reason why we are doing this is to avoid any case-sensitive process."
},
{
"code": null,
"e": 1370,
"s": 1071,
"text": "Suppose we want to remove stop words from our string, and the technique that we use is to take the non-stop words and combine those as a sentence. If we are not lowercase those, the stop word cannot be detected, and it will result in the same string. That’s why lowering case on texts is essential."
},
{
"code": null,
"e": 1426,
"s": 1370,
"text": "To do this in Python is easy. The code looks like this,"
},
{
"code": null,
"e": 1669,
"s": 1426,
"text": "# Examplex = \"Watch This Airport Get Swallowed Up By A Sandstorm In Under A Minute http://t.co/TvYQczGJdy\"# Lowercase the textx = x.lower()print(x)>>> watch this airport get swallowed up by a sandstorm in under a minute http://t.co/tvyqczgjdy"
},
{
"code": null,
"e": 1887,
"s": 1669,
"text": "Some tweets could contain a Unicode character that is unreadable when we see it on an ASCII format. Mostly, those characters are used for emojis and non-ASCII characters. To remove this, we can use code like this one,"
},
{
"code": null,
"e": 2251,
"s": 1887,
"text": "# Examplex = \"Reddit Will Now QuarantineÛ_ http://t.co/pkUAMXw6pm #onlinecommunities #reddit #amageddon #freespeech #Business http://t.co/PAWvNJ4sAP\"# Remove unicode charactersx = x.encode('ascii', 'ignore').decode()print(x)>>> Reddit Will Now Quarantine_ http://t.co/pkUAMXw6pm #onlinecommunities #reddit #amageddon #freespeech #Business http://t.co/PAWvNJ4sAP"
},
{
"code": null,
"e": 2565,
"s": 2251,
"text": "After we do that, we can remove words that belong to stop words. Stop word is a type of word that has no significant contribution to the meaning of the text. Because of that, we can remove those words. To retrieve the stop words, we can download a corpus from the NLTK library. Here is the code on how to do this,"
},
{
"code": null,
"e": 2973,
"s": 2565,
"text": "import nltknltk.download()# just download all-nltkstop_words = stopwords.words(\"english\")# Examplex = \"America like South Africa is a traumatised sick country - in different ways of course - but still messed up.\"# Remove stop wordsx = ' '.join([word for word in x.split(' ') if word not in stop_words])print(x)>>> America like South Africa traumatised sick country - different ways course - still messed up."
},
{
"code": null,
"e": 3122,
"s": 2973,
"text": "Besides we remove the Unicode and stop words, there are several terms that we should remove, including mentions, hashtags, links, punctuations, etc."
},
{
"code": null,
"e": 3314,
"s": 3122,
"text": "To remove those, it’s challenging if we rely only on a defined character. Therefore, we need patterns that can match terms that we desire by using something called Regular Expression (Regex)."
},
{
"code": null,
"e": 3553,
"s": 3314,
"text": "Regex is a special string that contains a pattern that can match words associated with that pattern. By using it, we can search or remove those based on patterns using a Python library called re. To do this, we can implement it like this,"
},
{
"code": null,
"e": 5454,
"s": 3553,
"text": "import re# Remove mentionsx = \"@DDNewsLive @NitishKumar and @ArvindKejriwal can't survive without referring @@narendramodi . Without Mr Modi they are BIG ZEROS\"x = re.sub(\"@\\S+\", \" \", x)print(x)>>> and can't survive without referring . Without Mr Modi they are BIG ZEROS# Remove URLx = \"Severe Thunderstorm pictures from across the Mid-South http://t.co/UZWLgJQzNS\"x = re.sub(\"https*\\S+\", \" \", x)print(x)>>> Severe Thunderstorm pictures from across the Mid-South# Remove Hashtagsx = \"Are people not concerned that after #SLAB's obliteration in Scotland #Labour UK is ripping itself apart over #Labourleadership contest?\"x = re.sub(\"#\\S+\", \" \", x)print(x)>>> Are people not concerned that after obliteration in Scotland UK is ripping itself apart over contest?# Remove ticks and the next characterx = \"Notley's tactful yet very direct response to Harper's attack on Alberta's gov't. Hell YEAH Premier! http://t.co/rzSUlzMOkX #ableg #cdnpoli\"x = re.sub(\"\\'\\w+\", '', x)print(x)>>> Notley tactful yet very direct response to Harper attack on Alberta gov. Hell YEAH Premier! http://t.co/rzSUlzMOkX #ableg #cdnpoli# Remove punctuationsx = \"In 2014 I will only smoke crqck if I becyme a mayor. This includes Foursquare.\"x = re.sub('[%s]' % re.escape(string.punctuation), ' ', x)print(x)>>> In 2014 I will only smoke crqck if I becyme a mayor. This includes Foursquare.# Remove numbersx = \"C-130 specially modified to land in a stadium and rescue hostages in Iran in 1980... http://t.co/tNI92fea3u http://t.co/czBaMzq3gL\"x = re.sub(r'\\w*\\d+\\w*', '', x)print(x)>>> C- specially modified to land in a stadium and rescue hostages in Iran in ... http://t.co/ http://t.co/# Replace the over spacesx = \" and can't survive without referring . Without Mr Modi they are BIG ZEROS\"x = re.sub('\\s{2,}', \" \", x)print(x)>>> and can't survive without referring . Without Mr Modi they are BIG ZEROS"
},
{
"code": null,
"e": 5815,
"s": 5454,
"text": "After you know each step on preprocessing texts, Let’s apply this to a list. If you look closer at the steps in detail, you will see that each method is related to each other. Therefore, it’s essential to apply it on a function so we can process it all the same time sequentially. Before we apply the preprocessing steps, here are the preview of sampled texts,"
},
{
"code": null,
"e": 6208,
"s": 5815,
"text": "Our Deeds are the Reason of this #earthquake May ALLAH Forgive us allForest fire near La Ronge Sask. CanadaAll residents asked to 'shelter in place' are being notified by officers. No other evacuation or shelter in place orders are expected13,000 people receive #wildfires evacuation orders in California Just got sent this photo from Ruby #Alaska as smoke from #wildfires pours into a school"
},
{
"code": null,
"e": 6295,
"s": 6208,
"text": "There are several steps that we should do for preprocessing a list of texts. They are,"
},
{
"code": null,
"e": 6479,
"s": 6295,
"text": "Create a function that contains all of the preprocessing steps, and it returns a preprocessed stringApply the function using a method called apply and chain the list with that method."
},
{
"code": null,
"e": 6580,
"s": 6479,
"text": "Create a function that contains all of the preprocessing steps, and it returns a preprocessed string"
},
{
"code": null,
"e": 6664,
"s": 6580,
"text": "Apply the function using a method called apply and chain the list with that method."
},
{
"code": null,
"e": 6694,
"s": 6664,
"text": "The code will look like this,"
},
{
"code": null,
"e": 7521,
"s": 6694,
"text": "# # In case of import errors# ! pip install nltk# ! pip install textblobimport numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport reimport nltkimport stringfrom nltk.corpus import stopwords# # In case of any corpus are missing # download all-nltknltk.download()df = pd.read_csv('train.csv')stop_words = stopwords.words(\"english\")wordnet = WordNetLemmatizer()def text_preproc(x): x = x.lower() x = ' '.join([word for word in x.split(' ') if word not in stop_words]) x = x.encode('ascii', 'ignore').decode() x = re.sub(r'https*\\S+', ' ', x) x = re.sub(r'@\\S+', ' ', x) x = re.sub(r'#\\S+', ' ', x) x = re.sub(r'\\'\\w+', '', x) x = re.sub('[%s]' % re.escape(string.punctuation), ' ', x) x = re.sub(r'\\w*\\d+\\w*', '', x) x = re.sub(r'\\s{2,}', ' ', x) return xdf['clean_text'] = df.text.apply(text_preproc)"
},
{
"code": null,
"e": 7553,
"s": 7521,
"text": "And here is the result from it,"
},
{
"code": null,
"e": 7787,
"s": 7553,
"text": "deeds reason may allah forgive usforest fire near la ronge sask canadaresidents asked place notified officers evacuation shelter place orders expected people receive evacuation orders california got sent photo ruby smoke pours school"
},
{
"code": null,
"e": 8033,
"s": 7787,
"text": "That is how to preprocess texts using Python. I hope you can apply it to solve problems related to text data. If you have any thoughts, you can comment down below. Also, you can follow me on Medium so you can follow up to my articles. Thank you."
}
]
|
Most frequent element in an array in C++ | We are given a array and we need to find the most frequent element from it. Let's see an example.
Input
arr = [1, 2, 3, 3, 2, 2, 1, 1, 2, 3, 4]
Output
2
In the above array, 2 occurs 4 times which is most frequent than any other in the array.
Initialise the array.
Initialise the array.
Initialise a map to store the frequency of each element.
Initialise a map to store the frequency of each element.
Count the frequency of each element and store it in the map.
Count the frequency of each element and store it in the map.
Iterate over the map and find the element with most frequency.
Iterate over the map and find the element with most frequency.
Return the element.
Initialise the array.
Sort the given array.
Maintain the variables for max count, result and current element count.
Find the max count element by iterating over the array.
Same elements resides side by side.
Return the result.
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h>
using namespace std;
int getMostFrequentNumber(int arr[], int n) {
unordered_map<int, int> elements;
for (int i = 0; i < n; i++) {
elements[arr[i]]++;
}
int maxCount = 0, res = -1;
for (auto i : elements) {
if (maxCount < i.second) {
res = i.first;
maxCount = i.second;
}
}
return res;
}
int main() {
int arr[] = { 1, 2, 3, 3, 2, 2, 1, 1, 2, 3, 4 };
int n = 11;
cout << getMostFrequentNumber(arr, n) << endl;
return 0;
}
If you run the above code, then you will get the following result.
2 | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "We are given a array and we need to find the most frequent element from it. Let's see an example."
},
{
"code": null,
"e": 1166,
"s": 1160,
"text": "Input"
},
{
"code": null,
"e": 1206,
"s": 1166,
"text": "arr = [1, 2, 3, 3, 2, 2, 1, 1, 2, 3, 4]"
},
{
"code": null,
"e": 1213,
"s": 1206,
"text": "Output"
},
{
"code": null,
"e": 1215,
"s": 1213,
"text": "2"
},
{
"code": null,
"e": 1304,
"s": 1215,
"text": "In the above array, 2 occurs 4 times which is most frequent than any other in the array."
},
{
"code": null,
"e": 1326,
"s": 1304,
"text": "Initialise the array."
},
{
"code": null,
"e": 1348,
"s": 1326,
"text": "Initialise the array."
},
{
"code": null,
"e": 1405,
"s": 1348,
"text": "Initialise a map to store the frequency of each element."
},
{
"code": null,
"e": 1462,
"s": 1405,
"text": "Initialise a map to store the frequency of each element."
},
{
"code": null,
"e": 1523,
"s": 1462,
"text": "Count the frequency of each element and store it in the map."
},
{
"code": null,
"e": 1584,
"s": 1523,
"text": "Count the frequency of each element and store it in the map."
},
{
"code": null,
"e": 1647,
"s": 1584,
"text": "Iterate over the map and find the element with most frequency."
},
{
"code": null,
"e": 1710,
"s": 1647,
"text": "Iterate over the map and find the element with most frequency."
},
{
"code": null,
"e": 1730,
"s": 1710,
"text": "Return the element."
},
{
"code": null,
"e": 1752,
"s": 1730,
"text": "Initialise the array."
},
{
"code": null,
"e": 1774,
"s": 1752,
"text": "Sort the given array."
},
{
"code": null,
"e": 1846,
"s": 1774,
"text": "Maintain the variables for max count, result and current element count."
},
{
"code": null,
"e": 1902,
"s": 1846,
"text": "Find the max count element by iterating over the array."
},
{
"code": null,
"e": 1938,
"s": 1902,
"text": "Same elements resides side by side."
},
{
"code": null,
"e": 1957,
"s": 1938,
"text": "Return the result."
},
{
"code": null,
"e": 2019,
"s": 1957,
"text": "Following is the implementation of the above algorithm in C++"
},
{
"code": null,
"e": 2534,
"s": 2019,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint getMostFrequentNumber(int arr[], int n) {\n unordered_map<int, int> elements;\n for (int i = 0; i < n; i++) {\n elements[arr[i]]++;\n }\n int maxCount = 0, res = -1;\n for (auto i : elements) {\n if (maxCount < i.second) {\n res = i.first;\n maxCount = i.second;\n }\n }\n return res;\n}\nint main() {\n int arr[] = { 1, 2, 3, 3, 2, 2, 1, 1, 2, 3, 4 };\n int n = 11;\n cout << getMostFrequentNumber(arr, n) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2601,
"s": 2534,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 2603,
"s": 2601,
"text": "2"
}
]
|
Speech Recognition with Tensorflow.js | by Benson Ruan | Towards Data Science | Voice Assistants like Amazon Alexa and Google Home have become widely popular, they allow users to quickly get things done by using speech recognition.
Thanks to an improvement in speech recognition technology, Tensorflow.js released a JavaScript module that enables the recognition of spoken commands.
In this article, we will use a pre-trained Tensorflow.js model for transfer learning. Let’s build an application which can recognize your speech command.
Try it yourself in the link below :
bensonruan.com
Isn’t it amazing that we can now use our voice to control computer contactlessly? Tensorflow.js really bringing Artificial Intelligence to the browser. Let’s dive into the code and show you step by step how to build this speech recognition application with tensorflow.js.
Simply include the scripts for tfjs and speech-commands models in the <head> section of the html file.
<script src="https://unpkg.com/@tensorflow/tfjs"></script><script src="https://unpkg.com/@tensorflow-models/speech-commands"></script>
HTML — index.html
Add a <div> place holder in the html body
<div id="candidate-words"></div>
Add a checkbox to control turn on/off the Microphone, I had customized the checkbox to look like a mobile switch using pure css.
<label class="form-switch"><input type="checkbox" id="audio-switch"><i></i> Microphone</label>
Javascript — speech_command.js
The tfjs speech command library support 20 item vocabulary, consisting of: ‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’, ‘six’, ‘seven’, ‘eight’, ‘nine’, ‘up’, ‘down’, ‘left’, ‘right’, ‘go’, ‘stop’, ‘yes’, and ‘no’, in addition to ‘background_noise’ and ‘unknown’. When the page is loaded, append the words into the list.
wordList = ["zero","one","two","three","four","five","six","seven","eight","nine", "yes", "no", "up", "down", "left", "right", "stop", "go"];$.each(wordList, function( index, word ) { if (!word.startsWith('_')){ $("#candidate-words").append('<span id='word-${word}'>${word}</span>'); }});
When Microphone switch (checkbox) turn on (checked), first call function loadModel() to load the pre-trained model, then call function startListening() to start voice command recognition.
When Microphone switch (checkbox) turn off (unchecked), call function stopListening() to disconnect the Mic.
if(this.checked){ if(!modelLoaded){ loadModel(); }else{ startListening(); }}else { stopListening();}
function loadModel() to load the pre-trained speech command model, calling the API of speechCommands.create and recognizer.ensureModelLoaded. When calling the create function, you must provide the type of the audio input. The two available options are ‘BROWSER_FFT’ and ‘SOFT_FFT’. — BROWSER_FFT uses the browser’s native Fourier transform. — SOFT_FFT uses JavaScript implementations of Fourier transform (not implemented yet).
function loadModel(){ recognizer = speechCommands.create("BROWSER_FFT"); Promise.all([ recognizer.ensureModelLoaded() ]).then(function(){ words = recognizer.wordLabels(); modelLoaded = true; startListening(); })}
function startListening() to call the recognizer.listen API to start listening to voice command. The listen() function takes two arguments: 1. A callback function that is invoked anytime a word is recognized. 2. A configuration object with adjustable fields such a — includeSpectrogram — probabilityThreshold (The callback function will be invoked if and only if the maximum probability score of all the words is greater than this threshold) — includeEmbedding
The output of scores contains the probability scores that correspond to recognizer.wordLabels(). Below code turning scores into a list of (score,word) pairs.
Please note that Microphone can only be accessed via the https protocol
function startListening(){ recognizer.listen(({scores}) => { scores = Array.from(scores).map((s, i) => ({score: s, word: words[i]})); scores.sort((s1, s2) => s2.score - s1.score); $("#word-"+scores[0].word).addClass('candidate-word-active'); }, { probabilityThreshold: 0.70 });}
Finally, to turn off the Microphone, call the recognizer.stopListening API
function stopListening(){ recognizer.stopListening();}
You can download the complete code of the above demo in the link below:
github.com
Tensorflow.js in 2020 has become the bread and butter for all Machine Learning JavaScript projects due to its comprehensive linear algebra core and deep learning layers. From this article, I hope you have fun and I encourage you to discover more about this library.
Thank you for reading. If you like this article, please share on Facebook or Twitter. Let me know in the comment if you have any questions. Follow me on GitHub and Linkedin. | [
{
"code": null,
"e": 324,
"s": 172,
"text": "Voice Assistants like Amazon Alexa and Google Home have become widely popular, they allow users to quickly get things done by using speech recognition."
},
{
"code": null,
"e": 475,
"s": 324,
"text": "Thanks to an improvement in speech recognition technology, Tensorflow.js released a JavaScript module that enables the recognition of spoken commands."
},
{
"code": null,
"e": 629,
"s": 475,
"text": "In this article, we will use a pre-trained Tensorflow.js model for transfer learning. Let’s build an application which can recognize your speech command."
},
{
"code": null,
"e": 665,
"s": 629,
"text": "Try it yourself in the link below :"
},
{
"code": null,
"e": 680,
"s": 665,
"text": "bensonruan.com"
},
{
"code": null,
"e": 952,
"s": 680,
"text": "Isn’t it amazing that we can now use our voice to control computer contactlessly? Tensorflow.js really bringing Artificial Intelligence to the browser. Let’s dive into the code and show you step by step how to build this speech recognition application with tensorflow.js."
},
{
"code": null,
"e": 1055,
"s": 952,
"text": "Simply include the scripts for tfjs and speech-commands models in the <head> section of the html file."
},
{
"code": null,
"e": 1190,
"s": 1055,
"text": "<script src=\"https://unpkg.com/@tensorflow/tfjs\"></script><script src=\"https://unpkg.com/@tensorflow-models/speech-commands\"></script>"
},
{
"code": null,
"e": 1208,
"s": 1190,
"text": "HTML — index.html"
},
{
"code": null,
"e": 1250,
"s": 1208,
"text": "Add a <div> place holder in the html body"
},
{
"code": null,
"e": 1283,
"s": 1250,
"text": "<div id=\"candidate-words\"></div>"
},
{
"code": null,
"e": 1412,
"s": 1283,
"text": "Add a checkbox to control turn on/off the Microphone, I had customized the checkbox to look like a mobile switch using pure css."
},
{
"code": null,
"e": 1507,
"s": 1412,
"text": "<label class=\"form-switch\"><input type=\"checkbox\" id=\"audio-switch\"><i></i> Microphone</label>"
},
{
"code": null,
"e": 1538,
"s": 1507,
"text": "Javascript — speech_command.js"
},
{
"code": null,
"e": 1861,
"s": 1538,
"text": "The tfjs speech command library support 20 item vocabulary, consisting of: ‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’, ‘six’, ‘seven’, ‘eight’, ‘nine’, ‘up’, ‘down’, ‘left’, ‘right’, ‘go’, ‘stop’, ‘yes’, and ‘no’, in addition to ‘background_noise’ and ‘unknown’. When the page is loaded, append the words into the list."
},
{
"code": null,
"e": 2151,
"s": 1861,
"text": "wordList = [\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\", \"yes\", \"no\", \"up\", \"down\", \"left\", \"right\", \"stop\", \"go\"];$.each(wordList, function( index, word ) { if (!word.startsWith('_')){ $(\"#candidate-words\").append('<span id='word-${word}'>${word}</span>'); }});"
},
{
"code": null,
"e": 2339,
"s": 2151,
"text": "When Microphone switch (checkbox) turn on (checked), first call function loadModel() to load the pre-trained model, then call function startListening() to start voice command recognition."
},
{
"code": null,
"e": 2448,
"s": 2339,
"text": "When Microphone switch (checkbox) turn off (unchecked), call function stopListening() to disconnect the Mic."
},
{
"code": null,
"e": 2551,
"s": 2448,
"text": "if(this.checked){ if(!modelLoaded){ loadModel(); }else{ startListening(); }}else { stopListening();}"
},
{
"code": null,
"e": 2979,
"s": 2551,
"text": "function loadModel() to load the pre-trained speech command model, calling the API of speechCommands.create and recognizer.ensureModelLoaded. When calling the create function, you must provide the type of the audio input. The two available options are ‘BROWSER_FFT’ and ‘SOFT_FFT’. — BROWSER_FFT uses the browser’s native Fourier transform. — SOFT_FFT uses JavaScript implementations of Fourier transform (not implemented yet)."
},
{
"code": null,
"e": 3238,
"s": 2979,
"text": "function loadModel(){ recognizer = speechCommands.create(\"BROWSER_FFT\"); Promise.all([ recognizer.ensureModelLoaded() ]).then(function(){ words = recognizer.wordLabels(); modelLoaded = true; startListening(); })}"
},
{
"code": null,
"e": 3699,
"s": 3238,
"text": "function startListening() to call the recognizer.listen API to start listening to voice command. The listen() function takes two arguments: 1. A callback function that is invoked anytime a word is recognized. 2. A configuration object with adjustable fields such a — includeSpectrogram — probabilityThreshold (The callback function will be invoked if and only if the maximum probability score of all the words is greater than this threshold) — includeEmbedding"
},
{
"code": null,
"e": 3857,
"s": 3699,
"text": "The output of scores contains the probability scores that correspond to recognizer.wordLabels(). Below code turning scores into a list of (score,word) pairs."
},
{
"code": null,
"e": 3929,
"s": 3857,
"text": "Please note that Microphone can only be accessed via the https protocol"
},
{
"code": null,
"e": 4249,
"s": 3929,
"text": "function startListening(){ recognizer.listen(({scores}) => { scores = Array.from(scores).map((s, i) => ({score: s, word: words[i]})); scores.sort((s1, s2) => s2.score - s1.score); $(\"#word-\"+scores[0].word).addClass('candidate-word-active'); }, { probabilityThreshold: 0.70 });}"
},
{
"code": null,
"e": 4324,
"s": 4249,
"text": "Finally, to turn off the Microphone, call the recognizer.stopListening API"
},
{
"code": null,
"e": 4382,
"s": 4324,
"text": "function stopListening(){ recognizer.stopListening();}"
},
{
"code": null,
"e": 4454,
"s": 4382,
"text": "You can download the complete code of the above demo in the link below:"
},
{
"code": null,
"e": 4465,
"s": 4454,
"text": "github.com"
},
{
"code": null,
"e": 4731,
"s": 4465,
"text": "Tensorflow.js in 2020 has become the bread and butter for all Machine Learning JavaScript projects due to its comprehensive linear algebra core and deep learning layers. From this article, I hope you have fun and I encourage you to discover more about this library."
}
]
|
Data Preprocessing with Python Pandas — Part 5 Binning | by Angelica Lo Duca | Towards Data Science | Data binning (or bucketing) groups data in bins (or buckets), in the sense that it replaces values contained into a small interval with a single representative value for that interval. Sometimes binning improves accuracy in predictive models.
Data binning is a type of data preprocessing, a mechanism which includes also dealing with missing values, formatting, normalization and standardization.
Binning can be applied to convert numeric values to categorical or to sample (quantise) numeric values.
convert numeric to categorical includes binning by distance and binning by frequency
reduce numeric values includes quantisation (or sampling).
Binning is a technique for data smoothing. Data smoothing is employed to remove noise from data. Three techniques for data smoothing:
binning
regression
outlier analysis.
You can download the full code of this tutorial from my Github repository.
In this tutorial we exploit the cupcake.csv dataset, which contains the trend search of the word cupcake on Google Trends. Data are extracted from this link. We exploit the pandas library to import the dataset and we transform it into a dataframe through the read_csv() function.
import pandas as pddf = pd.read_csv('cupcake.csv')df.head(5)
In this case we define the edges of each bin. In Python pandas binning by distance is achieved by means of thecut() function.
We group values related to the column Cupcake into three groups: small, medium and big. In order to do it, we need to calculate the intervals within each group falls. We calculate the interval range as the difference between the maximum and minimum value and then we split this interval into three parts, one for each group. We exploit the functions min() and max() of dataframe to calculate the minimum value and the maximum value of the column Cupcake.
min_value = df['Cupcake'].min()max_value = df['Cupcake'].max()print(min_value)print(max_value)
which gives the following output
4100
Now we can calculate the range of each interval, i.e. the minimum and maximum value of each interval. Since we have 3 groups, we need 4 edges of intervals (bins):
small — (edge1, edge2)
medium — (edge2, edge3)
big — (edge3, edge4)
We can use the linspace() function of the numpy package to calculate the 4 bins, equally distributed.
import numpy as npbins = np.linspace(min_value,max_value,4)bins
which gives the following output:
array([ 4., 36., 68., 100.])
Now we define the labels:
labels = ['small', 'medium', 'big']
We can use the cut() function to convert the numeric values of the column Cupcake into the categorical values. We need to specify the bins and the labels. In addition, we set the parameter include_lowest to True in order to include also the minimum value.
df['bins'] = pd.cut(df['Cupcake'], bins=bins, labels=labels, include_lowest=True)
We can plot the distribution of values, by using the hist() function of the matplotlib package.
import matplotlib.pyplot as pltplt.hist(df['bins'], bins=3)
Alternatively, we can set the edges of each bin manually.
bins = [ 0, 10, 50, 100 ]df['bin_cut_manual'] = pd.cut(df['Cupcake'] , bins=bins, labels=labels, include_lowest=True)plt.hist(df['bin_cut_manual'], bins=3)plt.show()
Binning by frequency calculates the size of each bin so that each bin contains the (almost) same number of observations, but the bin range will vary. We can use the Python pandas qcut() function. We can set the precision parameter to define the number of decimal points.
df['bin_qcut'] = pd.qcut(df['Cupcake'], q=3, precision=1, labels=labels)
Sampling is another technique of data binning. It permits to reduce the number of samples, by grouping similar values or contiguous values. There are three approaches to perform sampling:
by bin means: each value in a bin is replaced by the mean value of the bin.
by bin median: each bin value is replaced by its bin median value.
by bin boundary: each bin value is replaced by the closest boundary value, i.e. maximum or minimum value of the bin.
In order to perform sampling, the binned_statistic() function of the scipy.stats package can be used. This function receives two arrays as input, x_data and y_data, as well as the statistics to be used (e.g. median or mean) and the number of bins to be created. The function returns the values of the bins as well as the edges of each bin.
from scipy.stats import binned_statisticx_data = np.arange(0, len(df))y_data = df['Cupcake']x_bins,bin_edges, misc = binned_statistic(y_data,x_data, statistic="median", bins=2)
Now we should approximate each value of the df['Cupcake'] column to the median value of the corresponding bin. Thus we convert the bin edges to an IntervalIndex, which receives as index the left and right edges of each interval. In our case, the left edges starts from the beginning of the bin edges and do not contain the last value of the bin edges. The right edges instead, start from the second value of the bin edges and last until the last value.
bin_intervals = pd.IntervalIndex.from_arrays(bin_edges[:-1], bin_edges[1:])
We can quantise the Cupcake column by defining a set_to_median() function which loops through the intervals and when it finds the correct interval, it returns the mid value.
def set_to_median(x, bin_intervals): for interval in bin_intervals: if x in interval: return interval.mid
We use the apply() function to apply the set_to_median() to the Cupcake column.
df['sampled_cupcake'] = df['Cupcake'].apply(lambda x: set_to_median(x, bin_intervals))
Now we can plot results. We note the loss of information.
plt.plot(df['Cupcake'], label='original')plt.plot(df['sampled_cupcake'], color='red', label='sampled')plt.legend()plt.show()
Finally, we can plot the median values. We can calculate the y values (y_bins) corresponding to the binned values (x_bins) as the values at the center of the bin range.
y_bins = (bin_edges[:-1]+bin_edges[1:])/2y_bins
Then we plot:
plt.plot(x_data,y_data)plt.xlabel("X"); plt.ylabel("Y")plt.scatter(x_bins, y_bins, color= 'red',linewidth=5)plt.show()
We can use the package jenkspy, which contains a single function, called jenks_breaks(), which calculates the natural breaks of an array, exploiting the Fisher-Jenks algorithm. We can install the package by running pip3 install jenkspy.
import jenkspybreaks = jenkspy.jenks_breaks(df['Cupcake'], nb_class=3)
Now we can use the cut() function to transform data in labels.
df['bin_cut_break'] = pd.cut(df['Cupcake'] , bins=breaks, labels=labels, include_lowest=True)
And we can plot the histogram.
plt.hist(df['bin_cut_break'], bins=3)plt.show()
In this tutorial I have illustrated how to perform data binning, which is a technique for data preprocessing. Two approaches can be followed. The first approach converts numeric data into categorical data, the second approach performs data sampling, by reducing the number of samples.
Data binning is very useful when discretization is needed.
If you wanted to learn how to perform data preprocessing using the scikit-learn library, stay tuned...
If you have come this far to read, for me it is already a lot for today. Thanks! You can read more about me in this article.
Chris Moffit. Binning Data with Pandas qcut and cut
Chris Moffit. Finding Natural Breaks in Data with the Fisher-Jenks Algorithm
2021/03/31 — added binning by distance and binning by frequency. Updated Sampling.
2021/04/01 — added calculate natural breaks in data and bibliography. | [
{
"code": null,
"e": 415,
"s": 172,
"text": "Data binning (or bucketing) groups data in bins (or buckets), in the sense that it replaces values contained into a small interval with a single representative value for that interval. Sometimes binning improves accuracy in predictive models."
},
{
"code": null,
"e": 569,
"s": 415,
"text": "Data binning is a type of data preprocessing, a mechanism which includes also dealing with missing values, formatting, normalization and standardization."
},
{
"code": null,
"e": 673,
"s": 569,
"text": "Binning can be applied to convert numeric values to categorical or to sample (quantise) numeric values."
},
{
"code": null,
"e": 758,
"s": 673,
"text": "convert numeric to categorical includes binning by distance and binning by frequency"
},
{
"code": null,
"e": 817,
"s": 758,
"text": "reduce numeric values includes quantisation (or sampling)."
},
{
"code": null,
"e": 951,
"s": 817,
"text": "Binning is a technique for data smoothing. Data smoothing is employed to remove noise from data. Three techniques for data smoothing:"
},
{
"code": null,
"e": 959,
"s": 951,
"text": "binning"
},
{
"code": null,
"e": 970,
"s": 959,
"text": "regression"
},
{
"code": null,
"e": 988,
"s": 970,
"text": "outlier analysis."
},
{
"code": null,
"e": 1063,
"s": 988,
"text": "You can download the full code of this tutorial from my Github repository."
},
{
"code": null,
"e": 1343,
"s": 1063,
"text": "In this tutorial we exploit the cupcake.csv dataset, which contains the trend search of the word cupcake on Google Trends. Data are extracted from this link. We exploit the pandas library to import the dataset and we transform it into a dataframe through the read_csv() function."
},
{
"code": null,
"e": 1404,
"s": 1343,
"text": "import pandas as pddf = pd.read_csv('cupcake.csv')df.head(5)"
},
{
"code": null,
"e": 1530,
"s": 1404,
"text": "In this case we define the edges of each bin. In Python pandas binning by distance is achieved by means of thecut() function."
},
{
"code": null,
"e": 1985,
"s": 1530,
"text": "We group values related to the column Cupcake into three groups: small, medium and big. In order to do it, we need to calculate the intervals within each group falls. We calculate the interval range as the difference between the maximum and minimum value and then we split this interval into three parts, one for each group. We exploit the functions min() and max() of dataframe to calculate the minimum value and the maximum value of the column Cupcake."
},
{
"code": null,
"e": 2080,
"s": 1985,
"text": "min_value = df['Cupcake'].min()max_value = df['Cupcake'].max()print(min_value)print(max_value)"
},
{
"code": null,
"e": 2113,
"s": 2080,
"text": "which gives the following output"
},
{
"code": null,
"e": 2118,
"s": 2113,
"text": "4100"
},
{
"code": null,
"e": 2281,
"s": 2118,
"text": "Now we can calculate the range of each interval, i.e. the minimum and maximum value of each interval. Since we have 3 groups, we need 4 edges of intervals (bins):"
},
{
"code": null,
"e": 2304,
"s": 2281,
"text": "small — (edge1, edge2)"
},
{
"code": null,
"e": 2328,
"s": 2304,
"text": "medium — (edge2, edge3)"
},
{
"code": null,
"e": 2349,
"s": 2328,
"text": "big — (edge3, edge4)"
},
{
"code": null,
"e": 2451,
"s": 2349,
"text": "We can use the linspace() function of the numpy package to calculate the 4 bins, equally distributed."
},
{
"code": null,
"e": 2515,
"s": 2451,
"text": "import numpy as npbins = np.linspace(min_value,max_value,4)bins"
},
{
"code": null,
"e": 2549,
"s": 2515,
"text": "which gives the following output:"
},
{
"code": null,
"e": 2581,
"s": 2549,
"text": "array([ 4., 36., 68., 100.])"
},
{
"code": null,
"e": 2607,
"s": 2581,
"text": "Now we define the labels:"
},
{
"code": null,
"e": 2643,
"s": 2607,
"text": "labels = ['small', 'medium', 'big']"
},
{
"code": null,
"e": 2899,
"s": 2643,
"text": "We can use the cut() function to convert the numeric values of the column Cupcake into the categorical values. We need to specify the bins and the labels. In addition, we set the parameter include_lowest to True in order to include also the minimum value."
},
{
"code": null,
"e": 2981,
"s": 2899,
"text": "df['bins'] = pd.cut(df['Cupcake'], bins=bins, labels=labels, include_lowest=True)"
},
{
"code": null,
"e": 3077,
"s": 2981,
"text": "We can plot the distribution of values, by using the hist() function of the matplotlib package."
},
{
"code": null,
"e": 3137,
"s": 3077,
"text": "import matplotlib.pyplot as pltplt.hist(df['bins'], bins=3)"
},
{
"code": null,
"e": 3195,
"s": 3137,
"text": "Alternatively, we can set the edges of each bin manually."
},
{
"code": null,
"e": 3361,
"s": 3195,
"text": "bins = [ 0, 10, 50, 100 ]df['bin_cut_manual'] = pd.cut(df['Cupcake'] , bins=bins, labels=labels, include_lowest=True)plt.hist(df['bin_cut_manual'], bins=3)plt.show()"
},
{
"code": null,
"e": 3632,
"s": 3361,
"text": "Binning by frequency calculates the size of each bin so that each bin contains the (almost) same number of observations, but the bin range will vary. We can use the Python pandas qcut() function. We can set the precision parameter to define the number of decimal points."
},
{
"code": null,
"e": 3705,
"s": 3632,
"text": "df['bin_qcut'] = pd.qcut(df['Cupcake'], q=3, precision=1, labels=labels)"
},
{
"code": null,
"e": 3893,
"s": 3705,
"text": "Sampling is another technique of data binning. It permits to reduce the number of samples, by grouping similar values or contiguous values. There are three approaches to perform sampling:"
},
{
"code": null,
"e": 3969,
"s": 3893,
"text": "by bin means: each value in a bin is replaced by the mean value of the bin."
},
{
"code": null,
"e": 4036,
"s": 3969,
"text": "by bin median: each bin value is replaced by its bin median value."
},
{
"code": null,
"e": 4153,
"s": 4036,
"text": "by bin boundary: each bin value is replaced by the closest boundary value, i.e. maximum or minimum value of the bin."
},
{
"code": null,
"e": 4493,
"s": 4153,
"text": "In order to perform sampling, the binned_statistic() function of the scipy.stats package can be used. This function receives two arrays as input, x_data and y_data, as well as the statistics to be used (e.g. median or mean) and the number of bins to be created. The function returns the values of the bins as well as the edges of each bin."
},
{
"code": null,
"e": 4670,
"s": 4493,
"text": "from scipy.stats import binned_statisticx_data = np.arange(0, len(df))y_data = df['Cupcake']x_bins,bin_edges, misc = binned_statistic(y_data,x_data, statistic=\"median\", bins=2)"
},
{
"code": null,
"e": 5123,
"s": 4670,
"text": "Now we should approximate each value of the df['Cupcake'] column to the median value of the corresponding bin. Thus we convert the bin edges to an IntervalIndex, which receives as index the left and right edges of each interval. In our case, the left edges starts from the beginning of the bin edges and do not contain the last value of the bin edges. The right edges instead, start from the second value of the bin edges and last until the last value."
},
{
"code": null,
"e": 5199,
"s": 5123,
"text": "bin_intervals = pd.IntervalIndex.from_arrays(bin_edges[:-1], bin_edges[1:])"
},
{
"code": null,
"e": 5373,
"s": 5199,
"text": "We can quantise the Cupcake column by defining a set_to_median() function which loops through the intervals and when it finds the correct interval, it returns the mid value."
},
{
"code": null,
"e": 5500,
"s": 5373,
"text": "def set_to_median(x, bin_intervals): for interval in bin_intervals: if x in interval: return interval.mid"
},
{
"code": null,
"e": 5580,
"s": 5500,
"text": "We use the apply() function to apply the set_to_median() to the Cupcake column."
},
{
"code": null,
"e": 5667,
"s": 5580,
"text": "df['sampled_cupcake'] = df['Cupcake'].apply(lambda x: set_to_median(x, bin_intervals))"
},
{
"code": null,
"e": 5725,
"s": 5667,
"text": "Now we can plot results. We note the loss of information."
},
{
"code": null,
"e": 5850,
"s": 5725,
"text": "plt.plot(df['Cupcake'], label='original')plt.plot(df['sampled_cupcake'], color='red', label='sampled')plt.legend()plt.show()"
},
{
"code": null,
"e": 6019,
"s": 5850,
"text": "Finally, we can plot the median values. We can calculate the y values (y_bins) corresponding to the binned values (x_bins) as the values at the center of the bin range."
},
{
"code": null,
"e": 6067,
"s": 6019,
"text": "y_bins = (bin_edges[:-1]+bin_edges[1:])/2y_bins"
},
{
"code": null,
"e": 6081,
"s": 6067,
"text": "Then we plot:"
},
{
"code": null,
"e": 6201,
"s": 6081,
"text": "plt.plot(x_data,y_data)plt.xlabel(\"X\"); plt.ylabel(\"Y\")plt.scatter(x_bins, y_bins, color= 'red',linewidth=5)plt.show()"
},
{
"code": null,
"e": 6438,
"s": 6201,
"text": "We can use the package jenkspy, which contains a single function, called jenks_breaks(), which calculates the natural breaks of an array, exploiting the Fisher-Jenks algorithm. We can install the package by running pip3 install jenkspy."
},
{
"code": null,
"e": 6509,
"s": 6438,
"text": "import jenkspybreaks = jenkspy.jenks_breaks(df['Cupcake'], nb_class=3)"
},
{
"code": null,
"e": 6572,
"s": 6509,
"text": "Now we can use the cut() function to transform data in labels."
},
{
"code": null,
"e": 6666,
"s": 6572,
"text": "df['bin_cut_break'] = pd.cut(df['Cupcake'] , bins=breaks, labels=labels, include_lowest=True)"
},
{
"code": null,
"e": 6697,
"s": 6666,
"text": "And we can plot the histogram."
},
{
"code": null,
"e": 6745,
"s": 6697,
"text": "plt.hist(df['bin_cut_break'], bins=3)plt.show()"
},
{
"code": null,
"e": 7030,
"s": 6745,
"text": "In this tutorial I have illustrated how to perform data binning, which is a technique for data preprocessing. Two approaches can be followed. The first approach converts numeric data into categorical data, the second approach performs data sampling, by reducing the number of samples."
},
{
"code": null,
"e": 7089,
"s": 7030,
"text": "Data binning is very useful when discretization is needed."
},
{
"code": null,
"e": 7192,
"s": 7089,
"text": "If you wanted to learn how to perform data preprocessing using the scikit-learn library, stay tuned..."
},
{
"code": null,
"e": 7317,
"s": 7192,
"text": "If you have come this far to read, for me it is already a lot for today. Thanks! You can read more about me in this article."
},
{
"code": null,
"e": 7369,
"s": 7317,
"text": "Chris Moffit. Binning Data with Pandas qcut and cut"
},
{
"code": null,
"e": 7446,
"s": 7369,
"text": "Chris Moffit. Finding Natural Breaks in Data with the Fisher-Jenks Algorithm"
},
{
"code": null,
"e": 7529,
"s": 7446,
"text": "2021/03/31 — added binning by distance and binning by frequency. Updated Sampling."
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.