title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
volatile Keyword in Java
The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null. public class MyRunnable implements Runnable { private volatile boolean active; public void run() { active = true; while (active) { } } public void stop() { active = false; } }
[ { "code": null, "e": 1240, "s": 1062, "text": "The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory." }, { "code": null, "e": 1472, "s": 1240, "text": "Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null." }, { "code": null, "e": 1687, "s": 1472, "text": "public class MyRunnable implements Runnable {\n private volatile boolean active;\n public void run() {\n active = true;\n while (active) {\n }\n }\n public void stop() {\n active = false;\n }\n}" } ]
DataFrame Operations in R - GeeksforGeeks
01 Apr, 2022 DataFrames are generic data objects of R which are used to store the tabular data. Data frames are considered to be the most popular data objects in R programming because it is more comfortable to analyze the data in the tabular form. Data frames can also be taught as mattresses where each column of a matrix can be of the different data types. DataFrame are made up of three principal components, the data, rows, and columns. Operations that can be performed on a DataFrame are: Creating a DataFrame Accessing rows and columns Selecting the subset of the data frame Editing dataframes Adding extra rows and columns to the data frame Add new variables to dataframe based on existing ones Delete rows and columns in a data frame In the real world, a DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and an Excel file. DataFrame can also be created from the vectors in R. Following are some of the various ways that can be used to create a DataFrame: Creating a data frame using Vectors: To create a data frame we use the data.frame() function in R. To create a data frame use data.frame() command and then pass each of the vectors you have created as arguments to the function. Example: Python3 # R program to illustrate dataframe # A vector which is a character vectorName = c("Amiya", "Raj", "Asish") # A vector which is a character vectorLanguage = c("R", "Python", "Java") # A vector which is a numeric vectorAge = c(22, 25, 45) # To create dataframe use data.frame command and# then pass each of the vectors# we have created as arguments# to the function data.frame()df = data.frame(Name, Language, Age) print(df) Output: Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 Creating a data frame using data from a file: Dataframes can also be created by importing the data from a file. For this, you have to use the function called ‘read.table()‘. Syntax: newDF = read.table(path="Path of the file") To create a dataframe from a CSV file in R: Syntax: newDF = read.csv("FileName.csv") The syntax for accessing rows and columns is given below, df[val1, val2] df = dataframe object val1 = rows of a data frame val2 = columns of a data frame So, this ‘val1‘ and ‘val2‘ can be an array of values such as “1:2” or “2:3” etc. If you specify only df[val2] this refers to the set of columns only, that you need to access from the data frame. Example: Row selection Python3 # R program to illustrate operations# on a data frame # Creating a dataframedf = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45))print(df) # Accessing first and second rowcat("Accessing first and second row\n")print(df[1:2, ]) Output: Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 Accessing first and second row Name Language Age 1 Amiya R 22 2 Raj Python 25 Example: Column selection Python3 # R program to illustrate operations# on a data frame # Creating a dataframedf = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45))print(df) # Accessing first and second columncat("Accessing first and second column\n")print(df[, 1:2]) Output: Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 Accessing first and second column Name Language 1 Amiya R 2 Raj Python 3 Asish Java A subset of a DataFrame can also be created based on certain conditions with the help of following syntax. newDF = subset(df, conditions)df = Original dataframe conditions = Certain conditions Example: Python3 # R program to illustrate operations# on a data frame # Creating a dataframedf = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45))print(df) # Selecting the subset of the data frame# where Name is equal to Amiya# OR age is greater than 30newDf = subset(df, Name =="Amiya"|Age>30) cat("After Selecting the subset of the data frame\n")print(newDf) Output: Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 After Selecting the subset of the data frame Name Language Age 1 Amiya R 22 3 Asish Java 45 In R, DataFrames can be edited in two ways:Editing data frames by direct assignments: Much like the list in R you can edit the data frames by a direct assignment. Example: Python3 # R program to illustrate operation on a data frame # Creating a dataframedf = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45))cat("Before editing the dataframe\n")print(df) # Editing dataframes by direct assignments# [[3]] accessing the top level components# Here Age in this case# [[3]][3] accessing inner level components# Here Age of Asish in this casedf[[3]][3] = 30 cat("After edited the dataframe\n")print(df) Output: Before editing the data frame Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 After edited the data frame Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 30 Editing dataframes using the edit() command: Follow the given steps to edit a DataFrame: Step 1: So, what you need to do for this is you have to create an instance of data frame, for example, you can see that here an instance of a data frame is created and named as “myTable” by using the command data.frame() and this creates an empty data frame. myTable = data.frame() Step 2: Next we will use the edit function to launch the viewer. Note that “myTable” data frame is passed back to the “myTable” object and this way the changes we make to this module will be saved to the original object. myTable = edit(myTable) So, when the above command is executed it will pop up a window like this, Step 3: Now, the table is completed with this small roster. Note that, change variable names by clicking on their labels and typing your changes. Variables can also be set as numeric or character. Once the data in the DataFrame looks like the above, close the table. Changes are saved automatically. Step 4: Check out the resulting data frame by printing it. > myTable Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 Adding extra rows: We can add extra row using the command rbind(). The syntax for this is given below, newDF = rbind(df, the entries for the new row you have to add )df = Original data frame Note that the entries for the new row you have to add you have to be careful when using rbind() because the data types in each column entry should be equal to the data types that are already existing rows. Example: Python3 # R program to illustrate operation on a data frame # Creating a dataframedf = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45))cat("Before adding row\n")print(df) # Add a new row using rbind()newDf = rbind(df, data.frame(Name = "Sandeep", Language = "C", Age = 23 ))cat("After Added a row\n")print(newDf) Output: Before adding row Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 After Added a row Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 4 Sandeep C 23 Adding extra columns: We can add extra column using the command cbind(). The syntax for this is given below, newDF = cbind(df, the entries for the new column you have to add )df = Original data frame Example: Python3 # R program to illustrate operation on a data frame # Creating a dataframedf = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45))cat("Before adding column\n")print(df) # Add a new column using cbind()newDf = cbind(df, Rank=c(3, 5, 1)) cat("After Added a column\n")print(newDf) Output: Before adding column Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 After Added a column Name Language Age Rank 1 Amiya R 22 3 2 Raj Python 25 5 3 Asish Java 45 1 In R, we can add new variables to a data frame based on existing ones. To do that we have to first call the dplyr library using the command library() . And then calling mutate() function will add extra variable columns based on existing ones. Syntax: library(dplyr) newDF = mutate(df, new_var=[existing_var])df = original data frame new_var = Name of the new variable existing_var = The modify action you are taking(e.g log value, multiply by 10) Example: Python3 # R program to illustrate operation on a data frame # Importing the dplyr librarylibrary(dplyr) # Creating a dataframedf = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45))cat("Original Dataframe\n")print(df) # Creating an extra variable column# "log_Age" which is log of variable column "Age"# Using mutate() commandnewDf = mutate(df, log_Age = log(Age)) cat("After creating extra variable column\n")print(newDf) Output: Original Dataframe Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 After creating extra variable column Name Language Age log_Age 1 Amiya R 22 3.091042 2 Raj Python 25 3.218876 3 Asish Java 45 3.806662 To delete a row or a column, first of all, you need to access that row or column and then insert a negative sign before that row or column. It indicates that you had to delete that row or column. Syntax: newDF = df[-rowNo, -colNo]df = original data frame Example: Python3 # R program to illustrate operation on a data frame # Creating a dataframedf = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" = c(22, 25, 45))cat("Before deleting the 3rd row and 2nd column\n")print(df) # delete the third row and the second columnnewDF = df[-3, -2] cat("After Deleted the 3rd row and 2nd column\n")print(newDF) Output: Before deleting the 3rd row and 2nd column Name Language Age 1 Amiya R 22 2 Raj Python 25 3 Asish Java 45 After Deleted the 3rd row and 2nd column Name Age 1 Amiya 22 2 Raj 25 sumitgumber28 saurabh1990aror Picked R-DataFrame Programming Language R Language Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Programming Languages to Learn in 2022 Advantages and Disadvantages of OOP Difference between Shallow and Deep copy of a class Java Swing | JComboBox with examples Prolog | An Introduction Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R
[ { "code": null, "e": 24680, "s": 24652, "text": "\n01 Apr, 2022" }, { "code": null, "e": 25109, "s": 24680, "text": "DataFrames are generic data objects of R which are used to store the tabular data. Data frames are considered to be the most popular data objects in R programming because it is more comfortable to analyze the data in the tabular form. Data frames can also be taught as mattresses where each column of a matrix can be of the different data types. DataFrame are made up of three principal components, the data, rows, and columns. " }, { "code": null, "e": 25164, "s": 25109, "text": "Operations that can be performed on a DataFrame are: " }, { "code": null, "e": 25185, "s": 25164, "text": "Creating a DataFrame" }, { "code": null, "e": 25212, "s": 25185, "text": "Accessing rows and columns" }, { "code": null, "e": 25251, "s": 25212, "text": "Selecting the subset of the data frame" }, { "code": null, "e": 25270, "s": 25251, "text": "Editing dataframes" }, { "code": null, "e": 25318, "s": 25270, "text": "Adding extra rows and columns to the data frame" }, { "code": null, "e": 25372, "s": 25318, "text": "Add new variables to dataframe based on existing ones" }, { "code": null, "e": 25412, "s": 25372, "text": "Delete rows and columns in a data frame" }, { "code": null, "e": 25696, "s": 25412, "text": "In the real world, a DataFrame will be created by loading the datasets from existing storage, storage can be SQL Database, CSV file, and an Excel file. DataFrame can also be created from the vectors in R. Following are some of the various ways that can be used to create a DataFrame:" }, { "code": null, "e": 25925, "s": 25696, "text": "Creating a data frame using Vectors: To create a data frame we use the data.frame() function in R. To create a data frame use data.frame() command and then pass each of the vectors you have created as arguments to the function. " }, { "code": null, "e": 25936, "s": 25925, "text": "Example: " }, { "code": null, "e": 25944, "s": 25936, "text": "Python3" }, { "code": "# R program to illustrate dataframe # A vector which is a character vectorName = c(\"Amiya\", \"Raj\", \"Asish\") # A vector which is a character vectorLanguage = c(\"R\", \"Python\", \"Java\") # A vector which is a numeric vectorAge = c(22, 25, 45) # To create dataframe use data.frame command and# then pass each of the vectors# we have created as arguments# to the function data.frame()df = data.frame(Name, Language, Age) print(df)", "e": 26368, "s": 25944, "text": null }, { "code": null, "e": 26377, "s": 26368, "text": "Output: " }, { "code": null, "e": 26462, "s": 26377, "text": " Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45" }, { "code": null, "e": 26636, "s": 26462, "text": "Creating a data frame using data from a file: Dataframes can also be created by importing the data from a file. For this, you have to use the function called ‘read.table()‘." }, { "code": null, "e": 26646, "s": 26636, "text": "Syntax: " }, { "code": null, "e": 26690, "s": 26646, "text": "newDF = read.table(path=\"Path of the file\")" }, { "code": null, "e": 26735, "s": 26690, "text": "To create a dataframe from a CSV file in R: " }, { "code": null, "e": 26745, "s": 26735, "text": "Syntax: " }, { "code": null, "e": 26778, "s": 26745, "text": "newDF = read.csv(\"FileName.csv\")" }, { "code": null, "e": 26838, "s": 26778, "text": "The syntax for accessing rows and columns is given below, " }, { "code": null, "e": 26935, "s": 26838, "text": "df[val1, val2]\n\ndf = dataframe object\nval1 = rows of a data frame\nval2 = columns of a data frame" }, { "code": null, "e": 27130, "s": 26935, "text": "So, this ‘val1‘ and ‘val2‘ can be an array of values such as “1:2” or “2:3” etc. If you specify only df[val2] this refers to the set of columns only, that you need to access from the data frame." }, { "code": null, "e": 27155, "s": 27130, "text": "Example: Row selection " }, { "code": null, "e": 27163, "s": 27155, "text": "Python3" }, { "code": "# R program to illustrate operations# on a data frame # Creating a dataframedf = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45))print(df) # Accessing first and second rowcat(\"Accessing first and second row\\n\")print(df[1:2, ])", "e": 27455, "s": 27163, "text": null }, { "code": null, "e": 27464, "s": 27455, "text": "Output: " }, { "code": null, "e": 27643, "s": 27464, "text": " Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\n\nAccessing first and second row\n Name Language Age\n1 Amiya R 22\n2 Raj Python 25" }, { "code": null, "e": 27670, "s": 27643, "text": "Example: Column selection " }, { "code": null, "e": 27678, "s": 27670, "text": "Python3" }, { "code": "# R program to illustrate operations# on a data frame # Creating a dataframedf = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45))print(df) # Accessing first and second columncat(\"Accessing first and second column\\n\")print(df[, 1:2])", "e": 27976, "s": 27678, "text": null }, { "code": null, "e": 27985, "s": 27976, "text": "Output: " }, { "code": null, "e": 28172, "s": 27985, "text": " Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\n\nAccessing first and second column\n Name Language\n1 Amiya R\n2 Raj Python\n3 Asish Java" }, { "code": null, "e": 28281, "s": 28172, "text": "A subset of a DataFrame can also be created based on certain conditions with the help of following syntax. " }, { "code": null, "e": 28369, "s": 28281, "text": "newDF = subset(df, conditions)df = Original dataframe conditions = Certain conditions " }, { "code": null, "e": 28380, "s": 28369, "text": "Example: " }, { "code": null, "e": 28388, "s": 28380, "text": "Python3" }, { "code": "# R program to illustrate operations# on a data frame # Creating a dataframedf = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45))print(df) # Selecting the subset of the data frame# where Name is equal to Amiya# OR age is greater than 30newDf = subset(df, Name ==\"Amiya\"|Age>30) cat(\"After Selecting the subset of the data frame\\n\")print(newDf)", "e": 28797, "s": 28388, "text": null }, { "code": null, "e": 28806, "s": 28797, "text": "Output: " }, { "code": null, "e": 28996, "s": 28806, "text": "Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\n\nAfter Selecting the subset of the data frame\n Name Language Age\n1 Amiya R 22\n3 Asish Java 45" }, { "code": null, "e": 29160, "s": 28996, "text": "In R, DataFrames can be edited in two ways:Editing data frames by direct assignments: Much like the list in R you can edit the data frames by a direct assignment. " }, { "code": null, "e": 29171, "s": 29160, "text": "Example: " }, { "code": null, "e": 29179, "s": 29171, "text": "Python3" }, { "code": "# R program to illustrate operation on a data frame # Creating a dataframedf = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45))cat(\"Before editing the dataframe\\n\")print(df) # Editing dataframes by direct assignments# [[3]] accessing the top level components# Here Age in this case# [[3]][3] accessing inner level components# Here Age of Asish in this casedf[[3]][3] = 30 cat(\"After edited the dataframe\\n\")print(df)", "e": 29661, "s": 29179, "text": null }, { "code": null, "e": 29670, "s": 29661, "text": "Output: " }, { "code": null, "e": 29897, "s": 29670, "text": "Before editing the data frame\n Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\n\nAfter edited the data frame\n Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 30" }, { "code": null, "e": 29986, "s": 29897, "text": "Editing dataframes using the edit() command: Follow the given steps to edit a DataFrame:" }, { "code": null, "e": 30246, "s": 29986, "text": "Step 1: So, what you need to do for this is you have to create an instance of data frame, for example, you can see that here an instance of a data frame is created and named as “myTable” by using the command data.frame() and this creates an empty data frame. " }, { "code": null, "e": 30271, "s": 30246, "text": "myTable = data.frame() " }, { "code": null, "e": 30493, "s": 30271, "text": "Step 2: Next we will use the edit function to launch the viewer. Note that “myTable” data frame is passed back to the “myTable” object and this way the changes we make to this module will be saved to the original object. " }, { "code": null, "e": 30519, "s": 30493, "text": "myTable = edit(myTable) " }, { "code": null, "e": 30594, "s": 30519, "text": "So, when the above command is executed it will pop up a window like this, " }, { "code": null, "e": 30656, "s": 30594, "text": "Step 3: Now, the table is completed with this small roster. " }, { "code": null, "e": 30896, "s": 30656, "text": "Note that, change variable names by clicking on their labels and typing your changes. Variables can also be set as numeric or character. Once the data in the DataFrame looks like the above, close the table. Changes are saved automatically." }, { "code": null, "e": 30957, "s": 30896, "text": "Step 4: Check out the resulting data frame by printing it. " }, { "code": null, "e": 30969, "s": 30957, "text": "> myTable " }, { "code": null, "e": 31054, "s": 30969, "text": " Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45 " }, { "code": null, "e": 31159, "s": 31054, "text": "Adding extra rows: We can add extra row using the command rbind(). The syntax for this is given below, " }, { "code": null, "e": 31249, "s": 31159, "text": "newDF = rbind(df, the entries for the new row you have to add )df = Original data frame " }, { "code": null, "e": 31456, "s": 31249, "text": "Note that the entries for the new row you have to add you have to be careful when using rbind() because the data types in each column entry should be equal to the data types that are already existing rows. " }, { "code": null, "e": 31467, "s": 31456, "text": "Example: " }, { "code": null, "e": 31475, "s": 31467, "text": "Python3" }, { "code": "# R program to illustrate operation on a data frame # Creating a dataframedf = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45))cat(\"Before adding row\\n\")print(df) # Add a new row using rbind()newDf = rbind(df, data.frame(Name = \"Sandeep\", Language = \"C\", Age = 23 ))cat(\"After Added a row\\n\")print(newDf)", "e": 31925, "s": 31475, "text": null }, { "code": null, "e": 31934, "s": 31925, "text": "Output: " }, { "code": null, "e": 32170, "s": 31934, "text": "Before adding row\n Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\n\nAfter Added a row\n Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\n4 Sandeep C 23" }, { "code": null, "e": 32281, "s": 32170, "text": "Adding extra columns: We can add extra column using the command cbind(). The syntax for this is given below, " }, { "code": null, "e": 32374, "s": 32281, "text": "newDF = cbind(df, the entries for the new column you have to add )df = Original data frame " }, { "code": null, "e": 32385, "s": 32374, "text": "Example: " }, { "code": null, "e": 32393, "s": 32385, "text": "Python3" }, { "code": "# R program to illustrate operation on a data frame # Creating a dataframedf = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45))cat(\"Before adding column\\n\")print(df) # Add a new column using cbind()newDf = cbind(df, Rank=c(3, 5, 1)) cat(\"After Added a column\\n\")print(newDf)", "e": 32733, "s": 32393, "text": null }, { "code": null, "e": 32742, "s": 32733, "text": "Output: " }, { "code": null, "e": 32973, "s": 32742, "text": "Before adding column\n Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\n\nAfter Added a column\n Name Language Age Rank\n1 Amiya R 22 3\n2 Raj Python 25 5\n3 Asish Java 45 1" }, { "code": null, "e": 33217, "s": 32973, "text": "In R, we can add new variables to a data frame based on existing ones. To do that we have to first call the dplyr library using the command library() . And then calling mutate() function will add extra variable columns based on existing ones. " }, { "code": null, "e": 33227, "s": 33217, "text": "Syntax: " }, { "code": null, "e": 33425, "s": 33227, "text": "library(dplyr) newDF = mutate(df, new_var=[existing_var])df = original data frame new_var = Name of the new variable existing_var = The modify action you are taking(e.g log value, multiply by 10) " }, { "code": null, "e": 33436, "s": 33425, "text": "Example: " }, { "code": null, "e": 33444, "s": 33436, "text": "Python3" }, { "code": "# R program to illustrate operation on a data frame # Importing the dplyr librarylibrary(dplyr) # Creating a dataframedf = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45))cat(\"Original Dataframe\\n\")print(df) # Creating an extra variable column# \"log_Age\" which is log of variable column \"Age\"# Using mutate() commandnewDf = mutate(df, log_Age = log(Age)) cat(\"After creating extra variable column\\n\")print(newDf)", "e": 33922, "s": 33444, "text": null }, { "code": null, "e": 33931, "s": 33922, "text": "Output: " }, { "code": null, "e": 34192, "s": 33931, "text": "Original Dataframe\n Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\n\nAfter creating extra variable column\n Name Language Age log_Age\n1 Amiya R 22 3.091042\n2 Raj Python 25 3.218876\n3 Asish Java 45 3.806662" }, { "code": null, "e": 34389, "s": 34192, "text": "To delete a row or a column, first of all, you need to access that row or column and then insert a negative sign before that row or column. It indicates that you had to delete that row or column. " }, { "code": null, "e": 34399, "s": 34389, "text": "Syntax: " }, { "code": null, "e": 34452, "s": 34399, "text": "newDF = df[-rowNo, -colNo]df = original data frame " }, { "code": null, "e": 34463, "s": 34452, "text": "Example: " }, { "code": null, "e": 34471, "s": 34463, "text": "Python3" }, { "code": "# R program to illustrate operation on a data frame # Creating a dataframedf = data.frame( \"Name\" = c(\"Amiya\", \"Raj\", \"Asish\"), \"Language\" = c(\"R\", \"Python\", \"Java\"), \"Age\" = c(22, 25, 45))cat(\"Before deleting the 3rd row and 2nd column\\n\")print(df) # delete the third row and the second columnnewDF = df[-3, -2] cat(\"After Deleted the 3rd row and 2nd column\\n\")print(newDF)", "e": 34849, "s": 34471, "text": null }, { "code": null, "e": 34858, "s": 34849, "text": "Output: " }, { "code": null, "e": 35062, "s": 34858, "text": "Before deleting the 3rd row and 2nd column\n Name Language Age\n1 Amiya R 22\n2 Raj Python 25\n3 Asish Java 45\nAfter Deleted the 3rd row and 2nd column\n Name Age\n1 Amiya 22\n2 Raj 25" }, { "code": null, "e": 35078, "s": 35064, "text": "sumitgumber28" }, { "code": null, "e": 35094, "s": 35078, "text": "saurabh1990aror" }, { "code": null, "e": 35101, "s": 35094, "text": "Picked" }, { "code": null, "e": 35113, "s": 35101, "text": "R-DataFrame" }, { "code": null, "e": 35134, "s": 35113, "text": "Programming Language" }, { "code": null, "e": 35145, "s": 35134, "text": "R Language" }, { "code": null, "e": 35161, "s": 35145, "text": "Write From Home" }, { "code": null, "e": 35259, "s": 35161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35268, "s": 35259, "text": "Comments" }, { "code": null, "e": 35281, "s": 35268, "text": "Old Comments" }, { "code": null, "e": 35327, "s": 35281, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 35363, "s": 35327, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 35415, "s": 35363, "text": "Difference between Shallow and Deep copy of a class" }, { "code": null, "e": 35452, "s": 35415, "text": "Java Swing | JComboBox with examples" }, { "code": null, "e": 35477, "s": 35452, "text": "Prolog | An Introduction" }, { "code": null, "e": 35522, "s": 35477, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 35580, "s": 35522, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 35612, "s": 35580, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 35664, "s": 35612, "text": "Filter data by multiple conditions in R using Dplyr" } ]
Python Pillow - Colors on an Image - GeeksforGeeks
12 Dec, 2021 In this article, we will learn Colors on an Image using the Pillow module in Python. Let’s discuss some concepts: A crucial class within the Python Imaging Library is that the Image class. It’s defined within the Image module and provides a PIL image on which manipulation operations are often administered. An instance of this class is often created in several ways: by loading images from a file, creating images from scratch, or as a result of processing other images. We’ll see all these in use. Any image consists of pixels, each pixel represents a dot in an image. A pixel contains three values and every value ranges between 0 and 255, representing the quantity of red, green, and blue components. The combination of those forms an actual color of the pixel. The ImageColor module contains color tables and converters from CSS3-style color specifiers to RGB tuples. This module is used by PIL.Image.Image.new() and the ImageDraw module, among others. ImageColor module that contains various formats of representing colors. These formats are as follows: String: Colors can also be represented as strings such as red, green, blue, yellow. They are case insensitive. Hexadecimal Color: It is represented as: #rgb or #rrggbb. For example- #ffff00 represents yellow where red is 255, green is 255 and blue is 0. RGB would be a tuple-(255,255,0) Cylindrical: It is represented as HSL where H-hue, S-saturation, and L-lightness of color. For example- #ffff00 represents yellow where hue is 0.63, saturation is 1.00 and also the lightness value is 0.50. Here, we will create Images with colors using Image.new() method. PIL.Image.new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band). We can also use color names. If the color argument is omitted, the image is filled with zero (this usually corresponds to black). If the color is None, the image is not initialized. This can be useful if you’re going to paste or draw things in the image. Syntax: PIL.Image.new(mode, size, color) Parameters: mode: The mode to use for the new image. (It could be RGB, RGBA) size: A 2-tuple containing (width, height) in pixels. color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes. Return Value: An Image object. Python3 from PIL import Image # color --> "red" or (255,0,0) or #ff0000img = Image.new('RGB',(200,200),(255,0,0))img.show() Output: Using the ImageColor module, we can also convert colors to RGB format(RGB tuple) as RGB is very convenient to perform different operations. To do this we will use ImageColor.getgrb() method. The ImageColor.getrgb() Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a ValueError exception. Syntax: PIL.ImageColor.getrgb(color) Parameters: color: A color string Returns: (red, green, blue[, alpha]) Python3 # importing modulefrom PIL import ImageColor # using getrgb for yellowimg1 = ImageColor.getrgb("yellow")print(img1) # using getrgb for redimg2 = ImageColor.getrgb("red")print(img2) Output: (255, 255, 0) (255, 0, 0) The ImageColor.getcolor() Same as getrgb(), but converts the RGB value to a grayscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a ValueError exception. Syntax: PIL.ImageColor.getcolor(color, mode) Parameters: color – A color string Returns: (graylevel [, alpha]) or (red, green, blue[, alpha]) Python3 # importing modulefrom PIL import ImageColor # using getrgb for yellowimg1 = ImageColor.getcolor("yellow",'L')print(img1) # using getrgb for redimg2 = ImageColor.getcolor("red",'L')print(img2) Output: 226 76 We can also change the color of an image to some other color. Input Image: Python3 from PIL import Image img = Image.open("flower.jpg")img = img.convert("RGB") d = img.getdata() new_image = []for item in d: # change all white (also shades of whites) # pixels to yellow if item[0] in list(range(200, 256)): new_image.append((255, 224, 100)) else: new_image.append(item) # update image dataimg.putdata(new_image_data) # save new imageimg.save("flower_image_altered.jpg") Output: gabaa406 Picked Python-pil 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25729, "s": 25701, "text": "\n12 Dec, 2021" }, { "code": null, "e": 25843, "s": 25729, "text": "In this article, we will learn Colors on an Image using the Pillow module in Python. Let’s discuss some concepts:" }, { "code": null, "e": 26229, "s": 25843, "text": "A crucial class within the Python Imaging Library is that the Image class. It’s defined within the Image module and provides a PIL image on which manipulation operations are often administered. An instance of this class is often created in several ways: by loading images from a file, creating images from scratch, or as a result of processing other images. We’ll see all these in use." }, { "code": null, "e": 26495, "s": 26229, "text": "Any image consists of pixels, each pixel represents a dot in an image. A pixel contains three values and every value ranges between 0 and 255, representing the quantity of red, green, and blue components. The combination of those forms an actual color of the pixel." }, { "code": null, "e": 26687, "s": 26495, "text": "The ImageColor module contains color tables and converters from CSS3-style color specifiers to RGB tuples. This module is used by PIL.Image.Image.new() and the ImageDraw module, among others." }, { "code": null, "e": 26789, "s": 26687, "text": "ImageColor module that contains various formats of representing colors. These formats are as follows:" }, { "code": null, "e": 26900, "s": 26789, "text": "String: Colors can also be represented as strings such as red, green, blue, yellow. They are case insensitive." }, { "code": null, "e": 27076, "s": 26900, "text": "Hexadecimal Color: It is represented as: #rgb or #rrggbb. For example- #ffff00 represents yellow where red is 255, green is 255 and blue is 0. RGB would be a tuple-(255,255,0)" }, { "code": null, "e": 27282, "s": 27076, "text": "Cylindrical: It is represented as HSL where H-hue, S-saturation, and L-lightness of color. For example- #ffff00 represents yellow where hue is 0.63, saturation is 1.00 and also the lightness value is 0.50." }, { "code": null, "e": 27348, "s": 27282, "text": "Here, we will create Images with colors using Image.new() method." }, { "code": null, "e": 27856, "s": 27348, "text": "PIL.Image.new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band). We can also use color names. If the color argument is omitted, the image is filled with zero (this usually corresponds to black). If the color is None, the image is not initialized. This can be useful if you’re going to paste or draw things in the image." }, { "code": null, "e": 27897, "s": 27856, "text": "Syntax: PIL.Image.new(mode, size, color)" }, { "code": null, "e": 27909, "s": 27897, "text": "Parameters:" }, { "code": null, "e": 27974, "s": 27909, "text": "mode: The mode to use for the new image. (It could be RGB, RGBA)" }, { "code": null, "e": 28028, "s": 27974, "text": "size: A 2-tuple containing (width, height) in pixels." }, { "code": null, "e": 28209, "s": 28028, "text": "color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes." }, { "code": null, "e": 28240, "s": 28209, "text": "Return Value: An Image object." }, { "code": null, "e": 28248, "s": 28240, "text": "Python3" }, { "code": "from PIL import Image # color --> \"red\" or (255,0,0) or #ff0000img = Image.new('RGB',(200,200),(255,0,0))img.show()", "e": 28364, "s": 28248, "text": null }, { "code": null, "e": 28372, "s": 28364, "text": "Output:" }, { "code": null, "e": 28704, "s": 28372, "text": "Using the ImageColor module, we can also convert colors to RGB format(RGB tuple) as RGB is very convenient to perform different operations. To do this we will use ImageColor.getgrb() method. The ImageColor.getrgb() Convert a color string to an RGB tuple. If the string cannot be parsed, this function raises a ValueError exception." }, { "code": null, "e": 28741, "s": 28704, "text": "Syntax: PIL.ImageColor.getrgb(color)" }, { "code": null, "e": 28753, "s": 28741, "text": "Parameters:" }, { "code": null, "e": 28775, "s": 28753, "text": "color: A color string" }, { "code": null, "e": 28812, "s": 28775, "text": "Returns: (red, green, blue[, alpha])" }, { "code": null, "e": 28820, "s": 28812, "text": "Python3" }, { "code": "# importing modulefrom PIL import ImageColor # using getrgb for yellowimg1 = ImageColor.getrgb(\"yellow\")print(img1) # using getrgb for redimg2 = ImageColor.getrgb(\"red\")print(img2)", "e": 29001, "s": 28820, "text": null }, { "code": null, "e": 29009, "s": 29001, "text": "Output:" }, { "code": null, "e": 29035, "s": 29009, "text": "(255, 255, 0)\n(255, 0, 0)" }, { "code": null, "e": 29249, "s": 29035, "text": "The ImageColor.getcolor() Same as getrgb(), but converts the RGB value to a grayscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a ValueError exception." }, { "code": null, "e": 29294, "s": 29249, "text": "Syntax: PIL.ImageColor.getcolor(color, mode)" }, { "code": null, "e": 29306, "s": 29294, "text": "Parameters:" }, { "code": null, "e": 29329, "s": 29306, "text": "color – A color string" }, { "code": null, "e": 29391, "s": 29329, "text": "Returns: (graylevel [, alpha]) or (red, green, blue[, alpha])" }, { "code": null, "e": 29399, "s": 29391, "text": "Python3" }, { "code": "# importing modulefrom PIL import ImageColor # using getrgb for yellowimg1 = ImageColor.getcolor(\"yellow\",'L')print(img1) # using getrgb for redimg2 = ImageColor.getcolor(\"red\",'L')print(img2)", "e": 29592, "s": 29399, "text": null }, { "code": null, "e": 29600, "s": 29592, "text": "Output:" }, { "code": null, "e": 29607, "s": 29600, "text": "226\n76" }, { "code": null, "e": 29669, "s": 29607, "text": "We can also change the color of an image to some other color." }, { "code": null, "e": 29682, "s": 29669, "text": "Input Image:" }, { "code": null, "e": 29692, "s": 29684, "text": "Python3" }, { "code": "from PIL import Image img = Image.open(\"flower.jpg\")img = img.convert(\"RGB\") d = img.getdata() new_image = []for item in d: # change all white (also shades of whites) # pixels to yellow if item[0] in list(range(200, 256)): new_image.append((255, 224, 100)) else: new_image.append(item) # update image dataimg.putdata(new_image_data) # save new imageimg.save(\"flower_image_altered.jpg\")", "e": 30116, "s": 29692, "text": null }, { "code": null, "e": 30124, "s": 30116, "text": "Output:" }, { "code": null, "e": 30133, "s": 30124, "text": "gabaa406" }, { "code": null, "e": 30140, "s": 30133, "text": "Picked" }, { "code": null, "e": 30151, "s": 30140, "text": "Python-pil" }, { "code": null, "e": 30158, "s": 30151, "text": "Python" }, { "code": null, "e": 30256, "s": 30158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30274, "s": 30256, "text": "Python Dictionary" }, { "code": null, "e": 30309, "s": 30274, "text": "Read a file line by line in Python" }, { "code": null, "e": 30341, "s": 30309, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30363, "s": 30341, "text": "Enumerate() in Python" }, { "code": null, "e": 30405, "s": 30363, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30435, "s": 30405, "text": "Iterate over a list in Python" }, { "code": null, "e": 30461, "s": 30435, "text": "Python String | replace()" }, { "code": null, "e": 30505, "s": 30461, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30534, "s": 30505, "text": "*args and **kwargs in Python" } ]
Count of elements not divisible by any other elements of Array - GeeksforGeeks
24 May, 2021 Given an array arr[], the task is to determine the number of elements of the array which are not divisible by any other element in the given array. Examples: Input: arr[] = {86, 45, 18, 4, 8, 28, 19, 33, 2} Output: 4 Explanation: The elements are {2, 19, 33, 45} are not divisible by any other array element. Input: arr[] = {3, 3, 3} Output: 0 Naive Approach: The naive approach is to iterate over the entire array and count the number of elements that are not divisible by any other elements in the given array and print the count. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>#define ll long long intusing namespace std; // Function to count the number of// elements of array which are not// divisible by any other element// in the array arr[]int count(int a[], int n){ int countElements = 0; // Iterate over the array for (int i = 0; i < n; i++) { bool flag = true; for (int j = 0; j < n; j++) { // Check if the element // is itself or not if (i == j) continue; // Check for divisibility if (a[i] % a[j] == 0) { flag = false; break; } } if (flag == true) ++countElements; } // Return the final result return countElements;} // Driver Codeint main(){ // Given array int arr[] = { 86, 45, 18, 4, 8, 28, 19, 33, 2 }; int n = sizeof(arr) / sizeof(int); // Function Call cout << count(arr, n); return 0;} // Java program for the above approachclass GFG{ // Function to count the number of// elements of array which are not// divisible by any other element// in the array arr[]static int count(int a[], int n){ int countElements = 0; // Iterate over the array for(int i = 0; i < n; i++) { boolean flag = true; for(int j = 0; j < n; j++) { // Check if the element // is itself or not if (i == j) continue; // Check for divisibility if (a[i] % a[j] == 0) { flag = false; break; } } if (flag == true) ++countElements; } // Return the final result return countElements;} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 86, 45, 18, 4, 8, 28, 19, 33, 2 }; int n = arr.length; // Function call System.out.print(count(arr, n));}} // This code is contributed by Amit Katiyar # Python3 program for# the above approach # Function to count the number of# elements of array which are not# divisible by any other element# in the array arr[]def count(a, n): countElements = 0 # Iterate over the array for i in range (n): flag = True for j in range (n): # Check if the element # is itself or not if (i == j): continue # Check for divisibility if (a[i] % a[j] == 0): flag = False break if (flag == True): countElements += 1 # Return the final result return countElements # Driver Codeif __name__ == "__main__": # Given array arr = [86, 45, 18, 4, 8, 28, 19, 33, 2] n = len(arr) # Function Call print( count(arr, n)) # This code is contributed by Chitranayal // C# program for the// above approachusing System;class GFG{ // Function to count the// number of elements of// array which are not// divisible by any other// element in the array []arrstatic int count(int []a, int n){ int countElements = 0; // Iterate over the array for(int i = 0; i < n; i++) { bool flag = true; for(int j = 0; j < n; j++) { // Check if the element // is itself or not if (i == j) continue; // Check for divisibility if (a[i] % a[j] == 0) { flag = false; break; } } if (flag == true) ++countElements; } // Return the readonly result return countElements;} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = {86, 45, 18, 4, 8, 28, 19, 33, 2}; int n = arr.Length; // Function call Console.Write(count(arr, n));}} // This code is contributed by Rajput-Ji <script>// Javascript program for the above approach // Function to count the number of// elements of array which are not// divisible by any other element// in the array arr[]function count(a, n){ let countElements = 0; // Iterate over the array for (let i = 0; i < n; i++) { let flag = true; for (let j = 0; j < n; j++) { // Check if the element // is itself or not if (i == j) continue; // Check for divisibility if (a[i] % a[j] == 0) { flag = false; break; } } if (flag == true) ++countElements; } // Return the final result return countElements;} // Driver Code // Given array let arr = [ 86, 45, 18, 4, 8, 28, 19, 33, 2 ]; let n = arr.length; // Function Call document.write(count(arr, n)); </script> 4 Time Complexity: O(N2) Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, we will use the concept of Sieve of Eratosthenes. Below are the steps: Initialize a boolean array(say v[]) of size equal to the maximum element present in the array + 1 with true at every index.Traverse the given array arr[] and change the value at the index of multiple of current elements as false in the array v[].Create a Hashmap and store the frequency of each element in it.For each element(say current_element) in the array, if v[current_element] is true then that element is not divisible by any other element in the given array and increment the count for the current element.Print the final value of count after the above steps. Initialize a boolean array(say v[]) of size equal to the maximum element present in the array + 1 with true at every index. Traverse the given array arr[] and change the value at the index of multiple of current elements as false in the array v[]. Create a Hashmap and store the frequency of each element in it. For each element(say current_element) in the array, if v[current_element] is true then that element is not divisible by any other element in the given array and increment the count for the current element. Print the final value of count after the above steps. 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 count the number of// elements of array which are not// divisible by any other element// of same arrayint countEle(int a[], int n){ // Length for boolean array int len = 0; // Hash map for storing the // element and it's frequency unordered_map<int, int> hmap; for (int i = 0; i < n; i++) { // Update the maximum element len = max(len, a[i]); hmap[a[i]]++; } // Boolean array of size // of the max element + 1 bool v[len + 1]; for (int i = 0; i <= len; i++) { v[i] = true; } // Marking the multiples as false for (int i = 0; i < n; i++) { if (v[a[i]] == false) continue; for (int j = 2 * a[i]; j <= len; j += a[i]) { v[j] = false; } } // To store the final count int count = 0; // Traverse boolean array for (int i = 1; i <= len; i++) { // Check if i is not divisible by // any other array elements and // appears in the array only once if (v[i] == true && hmap.count(i) == 1 && hmap[i] == 1) { count += 1; } } // Return the final Count return count;} // Driver Codeint main(){ // Given array int arr[] = { 86, 45, 18, 4, 8, 28, 19, 33, 2 }; int n = sizeof(arr) / sizeof(int); // Function Call cout << countEle(arr, n); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ // Function to count the// number of elements of// array which are not// divisible by any other// element of same arraystatic int countEle(int a[], int n){ // Length for boolean array int len = 0; // Hash map for storing the // element and it's frequency HashMap<Integer, Integer> hmap = new HashMap<>(); for (int i = 0; i < n; i++) { // Update the maximum element len = Math.max(len, a[i]); if(hmap.containsKey(a[i])) { hmap.put(a[i], hmap.get(a[i]) + 1); } else { hmap.put(a[i], 1); } } // Boolean array of size // of the max element + 1 boolean []v = new boolean[len + 1]; for (int i = 0; i <= len; i++) { v[i] = true; } // Marking the multiples // as false for (int i = 0; i < n; i++) { if (v[a[i]] == false) continue; for (int j = 2 * a[i]; j <= len; j += a[i]) { v[j] = false; } } // To store the // final count int count = 0; // Traverse boolean array for (int i = 1; i <= len; i++) { // Check if i is not divisible by // any other array elements and // appears in the array only once if (v[i] == true && hmap.containsKey(i) && hmap.get(i) == 1 && hmap.get(i) == 1) { count += 1; } } // Return the final // Count return count;} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = {86, 45, 18, 4, 8, 28, 19, 33, 2}; int n = arr.length; // Function Call System.out.print(countEle(arr, n));}} // This code is contributed by Princi Singh # Python3 program for the above approach # Function to count the number of# elements of array which are not# divisible by any other element# of same arraydef countEle(a, n): # Length for boolean array len = 0 # Hash map for storing the # element and it's frequency hmap = {} for i in range(n): # Update the maximum element len = max(len, a[i]) hmap[a[i]] = hmap.get(a[i], 0) + 1 # Boolean array of size # of the max element + 1 v = [True for i in range(len + 1)] # Marking the multiples as false for i in range(n): if (v[a[i]] == False): continue for j in range(2 * a[i], len + 1, a[i]): v[j] = False # To store the final count count = 0 # Traverse boolean array for i in range(1, len + 1): # Check if i is not divisible by # any other array elements and # appears in the array only once if (v[i] == True and (i in hmap) and hmap[i] == 1): count += 1 # Return the final Count return count # Driver Codeif __name__ == '__main__': # Given array arr = [86, 45, 18, 4, 8, 28, 19, 33, 2] n = len(arr) # Function Call print(countEle(arr, n)) # This code is contributed by mohit kumar 29 // C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to count the// number of elements of// array which are not// divisible by any other// element of same arraystatic int countEle(int []a, int n){ // Length for bool array int len = 0; // Hash map for storing the // element and it's frequency Dictionary<int, int> hmap = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { // Update the maximum // element len = Math.Max(len, a[i]); if(hmap.ContainsKey(a[i])) { hmap[a[i]]++; } else { hmap.Add(a[i], 1); } } // Boolean array of size // of the max element + 1 bool []v = new bool[len + 1]; for (int i = 0; i <= len; i++) { v[i] = true; } // Marking the multiples // as false for (int i = 0; i < n; i++) { if (v[a[i]] == false) continue; for (int j = 2 * a[i]; j <= len; j += a[i]) { v[j] = false; } } // To store the // readonly count int count = 0; // Traverse bool array for (int i = 1; i <= len; i++) { // Check if i is not divisible by // any other array elements and // appears in the array only once if (v[i] == true && hmap.ContainsKey(i) && hmap[i] == 1 && hmap[i] == 1) { count += 1; } } // Return the readonly // Count return count;} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = {86, 45, 18, 4, 8, 28, 19, 33, 2}; int n = arr.Length; // Function Call Console.Write(countEle(arr, n));}} // This code is contributed by gauravrajput1 <script> // Javascript program for// the above approach // Function to count the// number of elements of// array which are not// divisible by any other// element of same arrayfunction countEle(a, n){ // Length for boolean array let len = 0; // Hash map for storing the // element and it's frequency let hmap = new Map(); for (let i = 0; i < n; i++) { // Update the maximum element len = Math.max(len, a[i]); if(hmap.has(a[i])) { hmap.set(a[i], hmap.get(a[i]) + 1); } else { hmap.set(a[i], 1); } } // Boolean array of size // of the max element + 1 let v = Array.from({length: len + 1}, (_, i) => 0); for (let i = 0; i <= len; i++) { v[i] = true; } // Marking the multiples // as false for (let i = 0; i < n; i++) { if (v[a[i]] == false) continue; for (let j = 2 * a[i]; j <= len; j += a[i]) { v[j] = false; } } // To store the // final count let count = 0; // Traverse boolean array for (let i = 1; i <= len; i++) { // Check if i is not divisible by // any other array elements and // appears in the array only once if (v[i] == true && hmap.has(i) && hmap.get(i) == 1 && hmap.get(i) == 1) { count += 1; } } // Return the final // Count return count;} // Driver code // Given array let arr = [86, 45, 18, 4, 8, 28, 19, 33, 2]; let n = arr.length; // Function Call document.write(countEle(arr, n)); // This code is contributed by souravghosh0416.</script> 4 Time Complexity: O(N*log(M)) where N is the number of elements in the given array and M is the maximum element in the given array. Auxiliary Space: O(M + N) where N is the number of elements in the given array and M is the maximum element in the given array. mansimar_anand ukasp amit143katiyar Rajput-Ji princi singh GauravRajput1 mohit kumar 29 subham348 souravghosh0416 cpp-map divisibility frequency-counting Arrays Hash Mathematical Arrays Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Trapping Rain Water Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining) Count pairs with given sum
[ { "code": null, "e": 24740, "s": 24712, "text": "\n24 May, 2021" }, { "code": null, "e": 24899, "s": 24740, "text": "Given an array arr[], the task is to determine the number of elements of the array which are not divisible by any other element in the given array. Examples: " }, { "code": null, "e": 25050, "s": 24899, "text": "Input: arr[] = {86, 45, 18, 4, 8, 28, 19, 33, 2} Output: 4 Explanation: The elements are {2, 19, 33, 45} are not divisible by any other array element." }, { "code": null, "e": 25087, "s": 25050, "text": "Input: arr[] = {3, 3, 3} Output: 0 " }, { "code": null, "e": 25276, "s": 25087, "text": "Naive Approach: The naive approach is to iterate over the entire array and count the number of elements that are not divisible by any other elements in the given array and print the count." }, { "code": null, "e": 25328, "s": 25276, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25332, "s": 25328, "text": "C++" }, { "code": null, "e": 25337, "s": 25332, "text": "Java" }, { "code": null, "e": 25345, "s": 25337, "text": "Python3" }, { "code": null, "e": 25348, "s": 25345, "text": "C#" }, { "code": null, "e": 25359, "s": 25348, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>#define ll long long intusing namespace std; // Function to count the number of// elements of array which are not// divisible by any other element// in the array arr[]int count(int a[], int n){ int countElements = 0; // Iterate over the array for (int i = 0; i < n; i++) { bool flag = true; for (int j = 0; j < n; j++) { // Check if the element // is itself or not if (i == j) continue; // Check for divisibility if (a[i] % a[j] == 0) { flag = false; break; } } if (flag == true) ++countElements; } // Return the final result return countElements;} // Driver Codeint main(){ // Given array int arr[] = { 86, 45, 18, 4, 8, 28, 19, 33, 2 }; int n = sizeof(arr) / sizeof(int); // Function Call cout << count(arr, n); return 0;}", "e": 26355, "s": 25359, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function to count the number of// elements of array which are not// divisible by any other element// in the array arr[]static int count(int a[], int n){ int countElements = 0; // Iterate over the array for(int i = 0; i < n; i++) { boolean flag = true; for(int j = 0; j < n; j++) { // Check if the element // is itself or not if (i == j) continue; // Check for divisibility if (a[i] % a[j] == 0) { flag = false; break; } } if (flag == true) ++countElements; } // Return the final result return countElements;} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 86, 45, 18, 4, 8, 28, 19, 33, 2 }; int n = arr.length; // Function call System.out.print(count(arr, n));}} // This code is contributed by Amit Katiyar", "e": 27401, "s": 26355, "text": null }, { "code": "# Python3 program for# the above approach # Function to count the number of# elements of array which are not# divisible by any other element# in the array arr[]def count(a, n): countElements = 0 # Iterate over the array for i in range (n): flag = True for j in range (n): # Check if the element # is itself or not if (i == j): continue # Check for divisibility if (a[i] % a[j] == 0): flag = False break if (flag == True): countElements += 1 # Return the final result return countElements # Driver Codeif __name__ == \"__main__\": # Given array arr = [86, 45, 18, 4, 8, 28, 19, 33, 2] n = len(arr) # Function Call print( count(arr, n)) # This code is contributed by Chitranayal", "e": 28271, "s": 27401, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ // Function to count the// number of elements of// array which are not// divisible by any other// element in the array []arrstatic int count(int []a, int n){ int countElements = 0; // Iterate over the array for(int i = 0; i < n; i++) { bool flag = true; for(int j = 0; j < n; j++) { // Check if the element // is itself or not if (i == j) continue; // Check for divisibility if (a[i] % a[j] == 0) { flag = false; break; } } if (flag == true) ++countElements; } // Return the readonly result return countElements;} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = {86, 45, 18, 4, 8, 28, 19, 33, 2}; int n = arr.Length; // Function call Console.Write(count(arr, n));}} // This code is contributed by Rajput-Ji", "e": 29197, "s": 28271, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to count the number of// elements of array which are not// divisible by any other element// in the array arr[]function count(a, n){ let countElements = 0; // Iterate over the array for (let i = 0; i < n; i++) { let flag = true; for (let j = 0; j < n; j++) { // Check if the element // is itself or not if (i == j) continue; // Check for divisibility if (a[i] % a[j] == 0) { flag = false; break; } } if (flag == true) ++countElements; } // Return the final result return countElements;} // Driver Code // Given array let arr = [ 86, 45, 18, 4, 8, 28, 19, 33, 2 ]; let n = arr.length; // Function Call document.write(count(arr, n)); </script>", "e": 30110, "s": 29197, "text": null }, { "code": null, "e": 30112, "s": 30110, "text": "4" }, { "code": null, "e": 30157, "s": 30112, "text": "Time Complexity: O(N2) Auxiliary Space: O(1)" }, { "code": null, "e": 30281, "s": 30157, "text": "Efficient Approach: To optimize the above approach, we will use the concept of Sieve of Eratosthenes. Below are the steps: " }, { "code": null, "e": 30849, "s": 30281, "text": "Initialize a boolean array(say v[]) of size equal to the maximum element present in the array + 1 with true at every index.Traverse the given array arr[] and change the value at the index of multiple of current elements as false in the array v[].Create a Hashmap and store the frequency of each element in it.For each element(say current_element) in the array, if v[current_element] is true then that element is not divisible by any other element in the given array and increment the count for the current element.Print the final value of count after the above steps." }, { "code": null, "e": 30973, "s": 30849, "text": "Initialize a boolean array(say v[]) of size equal to the maximum element present in the array + 1 with true at every index." }, { "code": null, "e": 31097, "s": 30973, "text": "Traverse the given array arr[] and change the value at the index of multiple of current elements as false in the array v[]." }, { "code": null, "e": 31161, "s": 31097, "text": "Create a Hashmap and store the frequency of each element in it." }, { "code": null, "e": 31367, "s": 31161, "text": "For each element(say current_element) in the array, if v[current_element] is true then that element is not divisible by any other element in the given array and increment the count for the current element." }, { "code": null, "e": 31421, "s": 31367, "text": "Print the final value of count after the above steps." }, { "code": null, "e": 31472, "s": 31421, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 31476, "s": 31472, "text": "C++" }, { "code": null, "e": 31481, "s": 31476, "text": "Java" }, { "code": null, "e": 31489, "s": 31481, "text": "Python3" }, { "code": null, "e": 31492, "s": 31489, "text": "C#" }, { "code": null, "e": 31503, "s": 31492, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the number of// elements of array which are not// divisible by any other element// of same arrayint countEle(int a[], int n){ // Length for boolean array int len = 0; // Hash map for storing the // element and it's frequency unordered_map<int, int> hmap; for (int i = 0; i < n; i++) { // Update the maximum element len = max(len, a[i]); hmap[a[i]]++; } // Boolean array of size // of the max element + 1 bool v[len + 1]; for (int i = 0; i <= len; i++) { v[i] = true; } // Marking the multiples as false for (int i = 0; i < n; i++) { if (v[a[i]] == false) continue; for (int j = 2 * a[i]; j <= len; j += a[i]) { v[j] = false; } } // To store the final count int count = 0; // Traverse boolean array for (int i = 1; i <= len; i++) { // Check if i is not divisible by // any other array elements and // appears in the array only once if (v[i] == true && hmap.count(i) == 1 && hmap[i] == 1) { count += 1; } } // Return the final Count return count;} // Driver Codeint main(){ // Given array int arr[] = { 86, 45, 18, 4, 8, 28, 19, 33, 2 }; int n = sizeof(arr) / sizeof(int); // Function Call cout << countEle(arr, n); return 0;}", "e": 32996, "s": 31503, "text": null }, { "code": "// Java program for// the above approachimport java.util.*;class GFG{ // Function to count the// number of elements of// array which are not// divisible by any other// element of same arraystatic int countEle(int a[], int n){ // Length for boolean array int len = 0; // Hash map for storing the // element and it's frequency HashMap<Integer, Integer> hmap = new HashMap<>(); for (int i = 0; i < n; i++) { // Update the maximum element len = Math.max(len, a[i]); if(hmap.containsKey(a[i])) { hmap.put(a[i], hmap.get(a[i]) + 1); } else { hmap.put(a[i], 1); } } // Boolean array of size // of the max element + 1 boolean []v = new boolean[len + 1]; for (int i = 0; i <= len; i++) { v[i] = true; } // Marking the multiples // as false for (int i = 0; i < n; i++) { if (v[a[i]] == false) continue; for (int j = 2 * a[i]; j <= len; j += a[i]) { v[j] = false; } } // To store the // final count int count = 0; // Traverse boolean array for (int i = 1; i <= len; i++) { // Check if i is not divisible by // any other array elements and // appears in the array only once if (v[i] == true && hmap.containsKey(i) && hmap.get(i) == 1 && hmap.get(i) == 1) { count += 1; } } // Return the final // Count return count;} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = {86, 45, 18, 4, 8, 28, 19, 33, 2}; int n = arr.length; // Function Call System.out.print(countEle(arr, n));}} // This code is contributed by Princi Singh", "e": 34649, "s": 32996, "text": null }, { "code": "# Python3 program for the above approach # Function to count the number of# elements of array which are not# divisible by any other element# of same arraydef countEle(a, n): # Length for boolean array len = 0 # Hash map for storing the # element and it's frequency hmap = {} for i in range(n): # Update the maximum element len = max(len, a[i]) hmap[a[i]] = hmap.get(a[i], 0) + 1 # Boolean array of size # of the max element + 1 v = [True for i in range(len + 1)] # Marking the multiples as false for i in range(n): if (v[a[i]] == False): continue for j in range(2 * a[i], len + 1, a[i]): v[j] = False # To store the final count count = 0 # Traverse boolean array for i in range(1, len + 1): # Check if i is not divisible by # any other array elements and # appears in the array only once if (v[i] == True and (i in hmap) and hmap[i] == 1): count += 1 # Return the final Count return count # Driver Codeif __name__ == '__main__': # Given array arr = [86, 45, 18, 4, 8, 28, 19, 33, 2] n = len(arr) # Function Call print(countEle(arr, n)) # This code is contributed by mohit kumar 29", "e": 35923, "s": 34649, "text": null }, { "code": "// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to count the// number of elements of// array which are not// divisible by any other// element of same arraystatic int countEle(int []a, int n){ // Length for bool array int len = 0; // Hash map for storing the // element and it's frequency Dictionary<int, int> hmap = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { // Update the maximum // element len = Math.Max(len, a[i]); if(hmap.ContainsKey(a[i])) { hmap[a[i]]++; } else { hmap.Add(a[i], 1); } } // Boolean array of size // of the max element + 1 bool []v = new bool[len + 1]; for (int i = 0; i <= len; i++) { v[i] = true; } // Marking the multiples // as false for (int i = 0; i < n; i++) { if (v[a[i]] == false) continue; for (int j = 2 * a[i]; j <= len; j += a[i]) { v[j] = false; } } // To store the // readonly count int count = 0; // Traverse bool array for (int i = 1; i <= len; i++) { // Check if i is not divisible by // any other array elements and // appears in the array only once if (v[i] == true && hmap.ContainsKey(i) && hmap[i] == 1 && hmap[i] == 1) { count += 1; } } // Return the readonly // Count return count;} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = {86, 45, 18, 4, 8, 28, 19, 33, 2}; int n = arr.Length; // Function Call Console.Write(countEle(arr, n));}} // This code is contributed by gauravrajput1", "e": 37612, "s": 35923, "text": null }, { "code": "<script> // Javascript program for// the above approach // Function to count the// number of elements of// array which are not// divisible by any other// element of same arrayfunction countEle(a, n){ // Length for boolean array let len = 0; // Hash map for storing the // element and it's frequency let hmap = new Map(); for (let i = 0; i < n; i++) { // Update the maximum element len = Math.max(len, a[i]); if(hmap.has(a[i])) { hmap.set(a[i], hmap.get(a[i]) + 1); } else { hmap.set(a[i], 1); } } // Boolean array of size // of the max element + 1 let v = Array.from({length: len + 1}, (_, i) => 0); for (let i = 0; i <= len; i++) { v[i] = true; } // Marking the multiples // as false for (let i = 0; i < n; i++) { if (v[a[i]] == false) continue; for (let j = 2 * a[i]; j <= len; j += a[i]) { v[j] = false; } } // To store the // final count let count = 0; // Traverse boolean array for (let i = 1; i <= len; i++) { // Check if i is not divisible by // any other array elements and // appears in the array only once if (v[i] == true && hmap.has(i) && hmap.get(i) == 1 && hmap.get(i) == 1) { count += 1; } } // Return the final // Count return count;} // Driver code // Given array let arr = [86, 45, 18, 4, 8, 28, 19, 33, 2]; let n = arr.length; // Function Call document.write(countEle(arr, n)); // This code is contributed by souravghosh0416.</script>", "e": 39167, "s": 37612, "text": null }, { "code": null, "e": 39169, "s": 39167, "text": "4" }, { "code": null, "e": 39428, "s": 39169, "text": "Time Complexity: O(N*log(M)) where N is the number of elements in the given array and M is the maximum element in the given array. Auxiliary Space: O(M + N) where N is the number of elements in the given array and M is the maximum element in the given array." }, { "code": null, "e": 39443, "s": 39428, "text": "mansimar_anand" }, { "code": null, "e": 39449, "s": 39443, "text": "ukasp" }, { "code": null, "e": 39464, "s": 39449, "text": "amit143katiyar" }, { "code": null, "e": 39474, "s": 39464, "text": "Rajput-Ji" }, { "code": null, "e": 39487, "s": 39474, "text": "princi singh" }, { "code": null, "e": 39501, "s": 39487, "text": "GauravRajput1" }, { "code": null, "e": 39516, "s": 39501, "text": "mohit kumar 29" }, { "code": null, "e": 39526, "s": 39516, "text": "subham348" }, { "code": null, "e": 39542, "s": 39526, "text": "souravghosh0416" }, { "code": null, "e": 39550, "s": 39542, "text": "cpp-map" }, { "code": null, "e": 39563, "s": 39550, "text": "divisibility" }, { "code": null, "e": 39582, "s": 39563, "text": "frequency-counting" }, { "code": null, "e": 39589, "s": 39582, "text": "Arrays" }, { "code": null, "e": 39594, "s": 39589, "text": "Hash" }, { "code": null, "e": 39607, "s": 39594, "text": "Mathematical" }, { "code": null, "e": 39614, "s": 39607, "text": "Arrays" }, { "code": null, "e": 39619, "s": 39614, "text": "Hash" }, { "code": null, "e": 39632, "s": 39619, "text": "Mathematical" }, { "code": null, "e": 39730, "s": 39632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39739, "s": 39730, "text": "Comments" }, { "code": null, "e": 39752, "s": 39739, "text": "Old Comments" }, { "code": null, "e": 39777, "s": 39752, "text": "Window Sliding Technique" }, { "code": null, "e": 39826, "s": 39777, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 39864, "s": 39826, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 39922, "s": 39864, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 39942, "s": 39922, "text": "Trapping Rain Water" }, { "code": null, "e": 39978, "s": 39942, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 40009, "s": 39978, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 40043, "s": 40009, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 40079, "s": 40043, "text": "Hashing | Set 2 (Separate Chaining)" } ]
Transform to Sum Tree | Practice | GeeksforGeeks
Given a Binary Tree of size N , where each node can have positive or negative values. Convert this to a tree where each node contains the sum of the left and right sub trees of the original tree. The values of leaf nodes are changed to 0. Example 1: Input: 10 / \ -2 6 / \ / \ 8 -4 7 5 Output: 20 / \ 4 12 / \ / \ 0 0 0 0 Explanation: (4-2+12+6) / \ (8-4) (7+5) / \ / \ 0 0 0 0 Your Task: You dont need to read input or print anything. Complete the function toSumTree() which takes root node as input parameter and modifies the given tree in-place. Note: If you click on Compile and Test the output will be the in-order traversal of the modified tree. Expected Time Complexity: O(N) Expected Auxiliary Space: O(height of tree) Constraints: 1 ≤ N ≤ 104 +1 goelyash3 weeks ago int solve(Node* root){ if(!root)return 0; int x =root->data; int l=solve(root->left); int r = solve(root->right); root->data = l+r; return l+r+x; } void toSumTree(Node *node) { int x=solve(node); } 0 keshavkjha19993 weeks ago Nice and Easy C++ int sumTree(Node *node){ int sumLeft, sumRight; if(!node->left&&!node->right){ sumLeft = 0; sumRight = 0; } else if(!node->right){ sumLeft = node->left->data + sumTree(node->left); sumRight = 0; } else if(!node->left){ sumLeft = 0; sumRight = node->right->data + sumTree(node->right); } else { sumLeft = node->left->data + sumTree(node->left); sumRight = node->right->data + sumTree(node->right); } return sumLeft + sumRight; } void toSumTree(Node *node){ // Your code here queue<Node *> q; q.push(node); int sum; while(!q.empty()){ Node* currentNode = q.front(); q.pop(); sum = sumTree(currentNode); currentNode->data = sum; if(currentNode->left){ q.push(currentNode->left); } if(currentNode->right){ q.push(currentNode->right); } } } +1 jaydhurat1 month ago class Solution{ public void toSumTree(Node root){ sum(root); } public int sum(Node root) { if(root==null) { return 0; } int x=sum(root.left); int y=sum(root.right); int data=root.data; root.data=x+y; return x+y+data; }} 0 badgujarsachin831 month ago int cheak(Node* node){ if(node==NULL){ return 0; } int a=cheak(node->left); int b=cheak(node->right); int x=node->data; node->data=a+b; return a+b+x; } // Convert a given tree to a tree where every node contains sum of values of // nodes in left and right subtrees in the original tree void toSumTree(Node *node) { // Your code here cheak(node); } 0 sfazal0002 months ago int solve(node* root){ // base case if(root == NULL) { return 0; } // hypothesis int l= solve(root->left); int r = solve(root->right); // induction int x = root->data; root->data = l+r; return l+r+x;} void binaryTreeToSumTree(node* root){ solve(root); } 0 tejasbhagat542 months ago Simple Java Solution : class Solution{ public int solve(Node root) { if(root==null)return 0; int a=solve(root.left); int b=solve(root.right); int x=root.data; root.data=a+b; return a+b+x; } public void toSumTree(Node root) { solve(root); }} 0 vrajeshmodi992 months ago int helper(Node*root) { if(!root)return 0; int nl = helper(root->left); int nr = helper(root->right); int sum = root->data; root->data = nl+nr; return (root->data+sum); } void toSumTree(Node *node) { helper(node); } 0 ritikshrivastava6645 This comment was deleted. +1 wolfofsv2 months ago Simple traversal int sum_util(Node* node){ if(node){ int child = sum_util(node -> left) + sum_util(node -> right); int store = node -> data; node -> data = child; return child + store; } return 0; } void toSumTree(Node *node) { // Your code here sum_util(node); } }; 0 hamidnourashraf2 months ago class Solution: def rec_sum(self, root): if root is None: return 0 elif root.left is None and root.right is None: val = root.data root.data = 0 return val else: val1 = self.rec_sum(root.left) val2 = self.rec_sum(root.right) val = val1+val2+root.data root.data = val1+val2 return val def toSumTree(self, root) : self.rec_sum(root) return root 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": 477, "s": 238, "text": "Given a Binary Tree of size N , where each node can have positive or negative values. Convert this to a tree where each node contains the sum of the left and right sub trees of the original tree. The values of leaf nodes are changed to 0." }, { "code": null, "e": 488, "s": 477, "text": "Example 1:" }, { "code": null, "e": 840, "s": 488, "text": "Input:\n 10\n / \\\n -2 6\n / \\ / \\\n 8 -4 7 5\n\nOutput:\n 20\n / \\\n 4 12\n / \\ / \\\n 0 0 0 0\n\nExplanation:\n\n (4-2+12+6)\n / \\\n (8-4) (7+5)\n / \\ / \\\n 0 0 0 0" }, { "code": null, "e": 1015, "s": 842, "text": "Your Task: \nYou dont need to read input or print anything. Complete the function toSumTree() which takes root node as input parameter and modifies the given tree in-place." }, { "code": null, "e": 1118, "s": 1015, "text": "Note: If you click on Compile and Test the output will be the in-order traversal of the modified tree." }, { "code": null, "e": 1196, "s": 1118, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(height of tree)\n " }, { "code": null, "e": 1221, "s": 1196, "text": "Constraints:\n1 ≤ N ≤ 104" }, { "code": null, "e": 1224, "s": 1221, "text": "+1" }, { "code": null, "e": 1244, "s": 1224, "text": "goelyash3 weeks ago" }, { "code": null, "e": 1518, "s": 1244, "text": " int solve(Node* root){\n if(!root)return 0;\n int x =root->data;\n int l=solve(root->left);\n int r = solve(root->right);\n root->data = l+r;\n return l+r+x;\n }\n void toSumTree(Node *node)\n {\n int x=solve(node);\n }" }, { "code": null, "e": 1520, "s": 1518, "text": "0" }, { "code": null, "e": 1546, "s": 1520, "text": "keshavkjha19993 weeks ago" }, { "code": null, "e": 1564, "s": 1546, "text": "Nice and Easy C++" }, { "code": null, "e": 2645, "s": 1564, "text": "int sumTree(Node *node){\n int sumLeft, sumRight;\n if(!node->left&&!node->right){\n sumLeft = 0;\n sumRight = 0;\n } else if(!node->right){\n sumLeft = node->left->data + sumTree(node->left);\n sumRight = 0;\n } else if(!node->left){\n sumLeft = 0;\n sumRight = node->right->data + sumTree(node->right);\n } else {\n sumLeft = node->left->data + sumTree(node->left);\n sumRight = node->right->data + sumTree(node->right);\n }\n return sumLeft + sumRight;\n }\n \n void toSumTree(Node *node){\n // Your code here\n queue<Node *> q;\n q.push(node);\n int sum;\n while(!q.empty()){\n Node* currentNode = q.front();\n q.pop();\n sum = sumTree(currentNode);\n currentNode->data = sum;\n if(currentNode->left){\n q.push(currentNode->left);\n }\n if(currentNode->right){\n q.push(currentNode->right);\n }\n }\n }" }, { "code": null, "e": 2648, "s": 2645, "text": "+1" }, { "code": null, "e": 2669, "s": 2648, "text": "jaydhurat1 month ago" }, { "code": null, "e": 2965, "s": 2669, "text": "class Solution{ public void toSumTree(Node root){ sum(root); } public int sum(Node root) { if(root==null) { return 0; } int x=sum(root.left); int y=sum(root.right); int data=root.data; root.data=x+y; return x+y+data; }}" }, { "code": null, "e": 2969, "s": 2967, "text": "0" }, { "code": null, "e": 2997, "s": 2969, "text": "badgujarsachin831 month ago" }, { "code": null, "e": 3453, "s": 2997, "text": "int cheak(Node* node){\n if(node==NULL){\n return 0;\n }\n int a=cheak(node->left);\n int b=cheak(node->right);\n int x=node->data;\n node->data=a+b;\n return a+b+x;\n }\n // Convert a given tree to a tree where every node contains sum of values of\n // nodes in left and right subtrees in the original tree\n void toSumTree(Node *node)\n {\n // Your code here\n cheak(node);\n }" }, { "code": null, "e": 3455, "s": 3453, "text": "0" }, { "code": null, "e": 3477, "s": 3455, "text": "sfazal0002 months ago" }, { "code": null, "e": 3718, "s": 3477, "text": "int solve(node* root){ // base case if(root == NULL) { return 0; } // hypothesis int l= solve(root->left); int r = solve(root->right); // induction int x = root->data; root->data = l+r; return l+r+x;}" }, { "code": null, "e": 3780, "s": 3720, "text": "void binaryTreeToSumTree(node* root){ solve(root); }" }, { "code": null, "e": 3782, "s": 3780, "text": "0" }, { "code": null, "e": 3808, "s": 3782, "text": "tejasbhagat542 months ago" }, { "code": null, "e": 3831, "s": 3808, "text": "Simple Java Solution :" }, { "code": null, "e": 4103, "s": 3831, "text": "class Solution{ public int solve(Node root) { if(root==null)return 0; int a=solve(root.left); int b=solve(root.right); int x=root.data; root.data=a+b; return a+b+x; } public void toSumTree(Node root) { solve(root); }}" }, { "code": null, "e": 4105, "s": 4103, "text": "0" }, { "code": null, "e": 4131, "s": 4105, "text": "vrajeshmodi992 months ago" }, { "code": null, "e": 4455, "s": 4131, "text": "int helper(Node*root)\n {\n if(!root)return 0;\n \n int nl = helper(root->left);\n int nr = helper(root->right);\n \n int sum = root->data;\n root->data = nl+nr;\n \n return (root->data+sum);\n }\n \n void toSumTree(Node *node)\n {\n helper(node);\n }" }, { "code": null, "e": 4457, "s": 4455, "text": "0" }, { "code": null, "e": 4478, "s": 4457, "text": "ritikshrivastava6645" }, { "code": null, "e": 4504, "s": 4478, "text": "This comment was deleted." }, { "code": null, "e": 4507, "s": 4504, "text": "+1" }, { "code": null, "e": 4528, "s": 4507, "text": "wolfofsv2 months ago" }, { "code": null, "e": 4546, "s": 4528, "text": "Simple traversal " }, { "code": null, "e": 4907, "s": 4546, "text": " int sum_util(Node* node){\n if(node){\n int child = sum_util(node -> left) + sum_util(node -> right);\n int store = node -> data;\n node -> data = child;\n return child + store;\n }\n return 0;\n }\n \n void toSumTree(Node *node)\n {\n // Your code here\n sum_util(node);\n }\n};" }, { "code": null, "e": 4909, "s": 4907, "text": "0" }, { "code": null, "e": 4937, "s": 4909, "text": "hamidnourashraf2 months ago" }, { "code": null, "e": 5436, "s": 4937, "text": "class Solution:\n def rec_sum(self, root):\n if root is None:\n return 0\n elif root.left is None and root.right is None:\n val = root.data\n root.data = 0\n return val\n else:\n val1 = self.rec_sum(root.left) \n val2 = self.rec_sum(root.right)\n val = val1+val2+root.data\n root.data = val1+val2\n return val\n def toSumTree(self, root) :\n self.rec_sum(root)\n return root" }, { "code": null, "e": 5582, "s": 5436, "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": 5618, "s": 5582, "text": " Login to access your submissions. " }, { "code": null, "e": 5628, "s": 5618, "text": "\nProblem\n" }, { "code": null, "e": 5638, "s": 5628, "text": "\nContest\n" }, { "code": null, "e": 5701, "s": 5638, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5849, "s": 5701, "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": 6057, "s": 5849, "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": 6163, "s": 6057, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C++ String Library - rfind
It searches the string for the last occurrence of the sequence specified by its arguments. Following is the declaration for std::string::rfind. size_t rfind (const string& str, size_t pos = npos) const; size_t rfind (const string& str, size_t pos = npos) const noexcept; size_t rfind (const string& str, size_t pos = npos) const noexcept; str − It is a string object. str − It is a string object. len − It is used to copy the characters. len − It is used to copy the characters. pos − Position of the first character to be copied. pos − Position of the first character to be copied. none if an exception is thrown, there are no changes in the string. In below example for std::string::rfind. #include <iostream> #include <string> #include <cstddef> int main () { std::string str ("sairamkrishna mammahe is a one of the tech person in tutorialspoint.com"); std::string key ("mammahe"); std::size_t found = str.rfind(key); if (found!=std::string::npos) str.replace (found,key.length(),"tech"); std::cout << str << '\n'; return 0; } The sample output should be like this − sairamkrishna tech is a one of the tech person in tutorialspoint.com Print Add Notes Bookmark this page
[ { "code": null, "e": 2694, "s": 2603, "text": "It searches the string for the last occurrence of the sequence specified by its arguments." }, { "code": null, "e": 2747, "s": 2694, "text": "Following is the declaration for std::string::rfind." }, { "code": null, "e": 2806, "s": 2747, "text": "size_t rfind (const string& str, size_t pos = npos) const;" }, { "code": null, "e": 2874, "s": 2806, "text": "size_t rfind (const string& str, size_t pos = npos) const noexcept;" }, { "code": null, "e": 2942, "s": 2874, "text": "size_t rfind (const string& str, size_t pos = npos) const noexcept;" }, { "code": null, "e": 2971, "s": 2942, "text": "str − It is a string object." }, { "code": null, "e": 3000, "s": 2971, "text": "str − It is a string object." }, { "code": null, "e": 3041, "s": 3000, "text": "len − It is used to copy the characters." }, { "code": null, "e": 3082, "s": 3041, "text": "len − It is used to copy the characters." }, { "code": null, "e": 3134, "s": 3082, "text": "pos − Position of the first character to be copied." }, { "code": null, "e": 3186, "s": 3134, "text": "pos − Position of the first character to be copied." }, { "code": null, "e": 3191, "s": 3186, "text": "none" }, { "code": null, "e": 3254, "s": 3191, "text": "if an exception is thrown, there are no changes in the string." }, { "code": null, "e": 3295, "s": 3254, "text": "In below example for std::string::rfind." }, { "code": null, "e": 3661, "s": 3295, "text": "#include <iostream>\n#include <string>\n#include <cstddef>\n\nint main () {\n std::string str (\"sairamkrishna mammahe is a one of the tech person in tutorialspoint.com\");\n std::string key (\"mammahe\");\n\n std::size_t found = str.rfind(key);\n if (found!=std::string::npos)\n str.replace (found,key.length(),\"tech\");\n\n std::cout << str << '\\n';\n\n return 0;\n}" }, { "code": null, "e": 3701, "s": 3661, "text": "The sample output should be like this −" }, { "code": null, "e": 3771, "s": 3701, "text": "sairamkrishna tech is a one of the tech person in tutorialspoint.com\n" }, { "code": null, "e": 3778, "s": 3771, "text": " Print" }, { "code": null, "e": 3789, "s": 3778, "text": " Add Notes" } ]
How to create canvas line using Fabric.js ? - GeeksforGeeks
16 Jul, 2021 In this article, we are going to see how to create a canvas line using FabricJS. The canvas line means the line is movable and can be stretched according to your requirements. Further, the line can be customized when it comes to initial stroke color and its starting and ending coordinates.Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain our line. After this, we will initialize instances of Canvas and Line provided by FabricJS and render the Line instance on the Canvas instance as given in the example below.Syntax: fabric.Line(points, options); Parameters: This function accepts two parameters as mentioned above and described below: points: It specifies the starting and ending coordinates of the line which are in the sequence like start x-coordinate, start y-coordinate, end x-coordinate and end y-coordinate. options: It specifies the additional options to be applied. Example: We can use FabricJS to create simple editable canvas line. html <!DOCTYPE html><html> <head> <title> How to create canvas line using Fabric.js? </title> <!-- Loading the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <canvas id="canvas" width="600" height="200" style="border:1px solid #000000;"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas("canvas"); // Initiate a line instance var line = new fabric.Line([50, 10, 200, 150], { stroke: 'green' }); // Render the rectangle in canvas canvas.add(line); </script></body> </html> sagar0719kumar Fabric.js JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24868, "s": 24840, "text": "\n16 Jul, 2021" }, { "code": null, "e": 25524, "s": 24868, "text": "In this article, we are going to see how to create a canvas line using FabricJS. The canvas line means the line is movable and can be stretched according to your requirements. Further, the line can be customized when it comes to initial stroke color and its starting and ending coordinates.Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain our line. After this, we will initialize instances of Canvas and Line provided by FabricJS and render the Line instance on the Canvas instance as given in the example below.Syntax: " }, { "code": null, "e": 25555, "s": 25524, "text": "fabric.Line(points, options); " }, { "code": null, "e": 25646, "s": 25555, "text": "Parameters: This function accepts two parameters as mentioned above and described below: " }, { "code": null, "e": 25825, "s": 25646, "text": "points: It specifies the starting and ending coordinates of the line which are in the sequence like start x-coordinate, start y-coordinate, end x-coordinate and end y-coordinate." }, { "code": null, "e": 25885, "s": 25825, "text": "options: It specifies the additional options to be applied." }, { "code": null, "e": 25954, "s": 25885, "text": "Example: We can use FabricJS to create simple editable canvas line. " }, { "code": null, "e": 25959, "s": 25954, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to create canvas line using Fabric.js? </title> <!-- Loading the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <canvas id=\"canvas\" width=\"600\" height=\"200\" style=\"border:1px solid #000000;\"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas(\"canvas\"); // Initiate a line instance var line = new fabric.Line([50, 10, 200, 150], { stroke: 'green' }); // Render the rectangle in canvas canvas.add(line); </script></body> </html>", "e": 26672, "s": 25959, "text": null }, { "code": null, "e": 26687, "s": 26672, "text": "sagar0719kumar" }, { "code": null, "e": 26697, "s": 26687, "text": "Fabric.js" }, { "code": null, "e": 26713, "s": 26697, "text": "JavaScript-Misc" }, { "code": null, "e": 26724, "s": 26713, "text": "JavaScript" }, { "code": null, "e": 26741, "s": 26724, "text": "Web Technologies" }, { "code": null, "e": 26768, "s": 26741, "text": "Web technologies Questions" }, { "code": null, "e": 26866, "s": 26768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26911, "s": 26866, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26972, "s": 26911, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27044, "s": 26972, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27090, "s": 27044, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27131, "s": 27090, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27173, "s": 27131, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27206, "s": 27173, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27249, "s": 27206, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27311, "s": 27249, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
JSF - Custom Converter
We can create our own Custom convertor in JSF. Defining a custom converter in JSF is a three-step process. public class UrlConverter implements Converter { ... } Create a simple class to store data: UrlData. This class will store a URL string. public class UrlData { private String url; public UrlData(String url) { this.url = url; } ... } Use UrlData in getAsObject method. public class UrlConverter implements Converter { @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { ... UrlData urlData = new UrlData(url.toString()); return urlData; } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object value) { return value.toString(); } } @FacesConverter("com.tutorialspoint.test.UrlConverter") public class UrlConverter implements Converter { } <h:inputText id = "urlInput" value = "#{userData.data}" label = "URL" > <f:converter converterId = "com.tutorialspoint.test.UrlConverter" /> </h:inputText> Let us create a test JSF application to test the above tag. package com.tutorialspoint.test; public class UrlData { private String url; public UrlData(String url) { this.url = url; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String toString() { return url; } } package com.tutorialspoint.test; import java.net.URI; import java.net.URISyntaxException; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; @FacesConverter("com.tutorialspoint.test.UrlConverter") public class UrlConverter implements Converter { @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { StringBuilder url = new StringBuilder(); if(!value.startsWith("http://", 0)) { url.append("http://"); } url.append(value); try { new URI(url.toString()); } catch (URISyntaxException e) { FacesMessage msg = new FacesMessage("Error converting URL", "Invalid URL format"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ConverterException(msg); } UrlData urlData = new UrlData(url.toString()); return urlData; } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object value) { return value.toString(); } } package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; public UrlData data; public UrlData getData() { return data; } public void setData(UrlData data) { this.data = data; } } <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h2>Custom Converter Example</h2> <h:form> <h:inputText id = "urlInput" value = "#{userData.data}" label = "URL" > <f:converter converterId = "com.tutorialspoint.test.UrlConverter" /> </h:inputText> <h:commandButton value = "submit" action = "result"/> <h:message for = "urlInput" style = "color:red" /> </h:form> </h:body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:body> <h2>Result</h2> <hr /> #{userData.data} </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. Enter any invalid value and press Submit button. See the following error message. Enter any valid value and press Submit button. See the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 1999, "s": 1952, "text": "We can create our own Custom convertor in JSF." }, { "code": null, "e": 2059, "s": 1999, "text": "Defining a custom converter in JSF is a three-step process." }, { "code": null, "e": 2114, "s": 2059, "text": "public class UrlConverter implements Converter {\n...\n}" }, { "code": null, "e": 2196, "s": 2114, "text": "Create a simple class to store data: UrlData. This class will store a URL string." }, { "code": null, "e": 2311, "s": 2196, "text": "public class UrlData {\n private String url;\n\n public UrlData(String url) {\n this.url = url;\n }\n ...\n}" }, { "code": null, "e": 2346, "s": 2311, "text": "Use UrlData in getAsObject method." }, { "code": null, "e": 2758, "s": 2346, "text": "public class UrlConverter implements Converter {\n \n @Override\n public Object getAsObject(FacesContext facesContext,\n UIComponent component, String value) {\n ...\n UrlData urlData = new UrlData(url.toString()); \n return urlData;\n }\n\n @Override\n public String getAsString(FacesContext facesContext, \n UIComponent component, Object value) {\n return value.toString();\n }\n}" }, { "code": null, "e": 2865, "s": 2758, "text": "@FacesConverter(\"com.tutorialspoint.test.UrlConverter\")\npublic class UrlConverter implements Converter {\n}" }, { "code": null, "e": 3024, "s": 2865, "text": "<h:inputText id = \"urlInput\" value = \"#{userData.data}\" label = \"URL\" >\n <f:converter converterId = \"com.tutorialspoint.test.UrlConverter\" />\n</h:inputText>" }, { "code": null, "e": 3084, "s": 3024, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 3405, "s": 3084, "text": "package com.tutorialspoint.test;\n\npublic class UrlData {\n private String url;\n \n public UrlData(String url) {\n this.url = url;\n }\n \n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n \n public String toString() {\n return url;\n }\n}" }, { "code": null, "e": 4676, "s": 3405, "text": "package com.tutorialspoint.test;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\nimport javax.faces.application.FacesMessage;\nimport javax.faces.component.UIComponent;\nimport javax.faces.context.FacesContext;\nimport javax.faces.convert.Converter;\nimport javax.faces.convert.ConverterException;\nimport javax.faces.convert.FacesConverter;\n\n@FacesConverter(\"com.tutorialspoint.test.UrlConverter\")\npublic class UrlConverter implements Converter {\n\n @Override\n public Object getAsObject(FacesContext facesContext, \n UIComponent component, String value) {\n StringBuilder url = new StringBuilder();\n\n if(!value.startsWith(\"http://\", 0)) {\n url.append(\"http://\");\n }\n url.append(value);\n\n try {\n new URI(url.toString());\t \n } catch (URISyntaxException e) {\n FacesMessage msg = new FacesMessage(\"Error converting URL\",\n \"Invalid URL format\");\n msg.setSeverity(FacesMessage.SEVERITY_ERROR);\n throw new ConverterException(msg);\n }\n\n UrlData urlData = new UrlData(url.toString()); \n return urlData;\n }\n\n @Override\n public String getAsString(FacesContext facesContext,\n UIComponent component, Object value) {\n return value.toString();\n }\n}" }, { "code": null, "e": 5130, "s": 4676, "text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n\n private static final long serialVersionUID = 1L;\n public UrlData data;\n\n public UrlData getData() {\n return data;\n }\n\n public void setData(UrlData data) {\n this.data = data;\n }\t\n}" }, { "code": null, "e": 5940, "s": 5130, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:f = \"http://java.sun.com/jsf/core\">\n <h:head>\n <title>JSF tutorial</title>\t\t\t\n </h:head>\n \n <h:body>\n <h2>Custom Converter Example</h2>\n \n <h:form>\n <h:inputText id = \"urlInput\" value = \"#{userData.data}\" \n label = \"URL\" >\n <f:converter converterId = \"com.tutorialspoint.test.UrlConverter\" />\n </h:inputText>\t\t \n <h:commandButton value = \"submit\" action = \"result\"/>\n <h:message for = \"urlInput\" style = \"color:red\" />\n </h:form>\n \n </h:body>\n</html>" }, { "code": null, "e": 6394, "s": 5940, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <h:body>\n <h2>Result</h2>\n <hr />\n #{userData.data} \t\n </h:body>\n</html> " }, { "code": null, "e": 6610, "s": 6394, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 6692, "s": 6610, "text": "Enter any invalid value and press Submit button. See the following error message." }, { "code": null, "e": 6765, "s": 6692, "text": "Enter any valid value and press Submit button. See the following result." }, { "code": null, "e": 6800, "s": 6765, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6815, "s": 6800, "text": " Chaand Sheikh" }, { "code": null, "e": 6822, "s": 6815, "text": " Print" }, { "code": null, "e": 6833, "s": 6822, "text": " Add Notes" } ]
How to convert LinkedList to Array in Java? - GeeksforGeeks
11 Dec, 2018 Given a Linked List in Java, the task is to convert this LinkedList to Array. Examples: Input: LinkedList: ['G', 'e', 'e', 'k', 's'] Output: Array: ['G', 'e', 'e', 'k', 's'] Input: LinkedList: [1, 2, 3, 4, 5] Output: Array: [1, 2, 3, 4, 5] Approach: Get the LinkedListConvert the LinkedList to Object array using toArray() method.Convert the Object array to desired type array using Arrays.copyOf() method.Return the print the Array Get the LinkedList Convert the LinkedList to Object array using toArray() method. Convert the Object array to desired type array using Arrays.copyOf() method. Return the print the Array Below is the implementation of the above approach: // Java program to convert// LinkedList to Array import java.util.*; public class GFG { // Function to convert LinkedList to Array public static <T> Object[] convertLinkedListToArray(LinkedList<T> linkedList) { // Converting LinkedList to Array Object[] array = linkedList.toArray(); return array; } public static void main(String args[]) { // Creating linked list LinkedList<String> linkedList = new LinkedList<String>(); // Adding elements to the linked list linkedList.add("G"); linkedList.add("e"); linkedList.add("e"); linkedList.add("k"); linkedList.add("s"); // Print the LinkedList System.out.println("Linked list: " + linkedList); // Converting LinkedList to Object Array Object[] objArray = convertLinkedListToArray(linkedList); // Convert Object[] to String[] String[] array = Arrays.copyOf(objArray, objArray.length, String[].class); // Print the String Array System.out.println("Array: " + Arrays.toString(array)); }} Linked list: [G, e, e, k, s] Array: [G, e, e, k, s] Java-Array-Programs Java-Arrays Java-Collections java-LinkedList Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 HashMap in Java with Examples Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 23866, "s": 23838, "text": "\n11 Dec, 2018" }, { "code": null, "e": 23944, "s": 23866, "text": "Given a Linked List in Java, the task is to convert this LinkedList to Array." }, { "code": null, "e": 23954, "s": 23944, "text": "Examples:" }, { "code": null, "e": 24111, "s": 23954, "text": "Input: LinkedList: ['G', 'e', 'e', 'k', 's'] \nOutput: Array: ['G', 'e', 'e', 'k', 's'] \n\nInput: LinkedList: [1, 2, 3, 4, 5]\nOutput: Array: [1, 2, 3, 4, 5] \n" }, { "code": null, "e": 24121, "s": 24111, "text": "Approach:" }, { "code": null, "e": 24304, "s": 24121, "text": "Get the LinkedListConvert the LinkedList to Object array using toArray() method.Convert the Object array to desired type array using Arrays.copyOf() method.Return the print the Array" }, { "code": null, "e": 24323, "s": 24304, "text": "Get the LinkedList" }, { "code": null, "e": 24386, "s": 24323, "text": "Convert the LinkedList to Object array using toArray() method." }, { "code": null, "e": 24463, "s": 24386, "text": "Convert the Object array to desired type array using Arrays.copyOf() method." }, { "code": null, "e": 24490, "s": 24463, "text": "Return the print the Array" }, { "code": null, "e": 24541, "s": 24490, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to convert// LinkedList to Array import java.util.*; public class GFG { // Function to convert LinkedList to Array public static <T> Object[] convertLinkedListToArray(LinkedList<T> linkedList) { // Converting LinkedList to Array Object[] array = linkedList.toArray(); return array; } public static void main(String args[]) { // Creating linked list LinkedList<String> linkedList = new LinkedList<String>(); // Adding elements to the linked list linkedList.add(\"G\"); linkedList.add(\"e\"); linkedList.add(\"e\"); linkedList.add(\"k\"); linkedList.add(\"s\"); // Print the LinkedList System.out.println(\"Linked list: \" + linkedList); // Converting LinkedList to Object Array Object[] objArray = convertLinkedListToArray(linkedList); // Convert Object[] to String[] String[] array = Arrays.copyOf(objArray, objArray.length, String[].class); // Print the String Array System.out.println(\"Array: \" + Arrays.toString(array)); }}", "e": 25783, "s": 24541, "text": null }, { "code": null, "e": 25836, "s": 25783, "text": "Linked list: [G, e, e, k, s]\nArray: [G, e, e, k, s]\n" }, { "code": null, "e": 25856, "s": 25836, "text": "Java-Array-Programs" }, { "code": null, "e": 25868, "s": 25856, "text": "Java-Arrays" }, { "code": null, "e": 25885, "s": 25868, "text": "Java-Collections" }, { "code": null, "e": 25901, "s": 25885, "text": "java-LinkedList" }, { "code": null, "e": 25920, "s": 25901, "text": "Java-List-Programs" }, { "code": null, "e": 25925, "s": 25920, "text": "Java" }, { "code": null, "e": 25930, "s": 25925, "text": "Java" }, { "code": null, "e": 25947, "s": 25930, "text": "Java-Collections" }, { "code": null, "e": 26045, "s": 25947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26054, "s": 26045, "text": "Comments" }, { "code": null, "e": 26067, "s": 26054, "text": "Old Comments" }, { "code": null, "e": 26082, "s": 26067, "text": "Arrays in Java" }, { "code": null, "e": 26126, "s": 26082, "text": "Split() String method in Java with examples" }, { "code": null, "e": 26148, "s": 26126, "text": "For-each loop in Java" }, { "code": null, "e": 26184, "s": 26148, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 26209, "s": 26184, "text": "Reverse a string in Java" }, { "code": null, "e": 26239, "s": 26209, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26271, "s": 26239, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26322, "s": 26271, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26341, "s": 26322, "text": "Interfaces in Java" } ]
What are recursive stored procedures and why MySQL limits the recursion?
A stored procedure is called recursive if it calls itself. Basically, this concept is called recursion. MySQL limits the recursion so the errors will be less rigorous. We can check this limit with the help of the following query − mysql> Show variables LIKE '%recur%'; +------------------------+-------+ | Variable_name | Value | +------------------------+-------+ | max_sp_recursion_depth | 0 | +------------------------+-------+ 1 row in set (0.01 sec) We can change this value up to 255 with the help of the following query − mysql> SET @@GLOBAL.max_sp_recursion_depth = 255// Query OK, 0 rows affected (0.00 sec) mysql> Show variables LIKE '%recur%'// +------------------------+-------+ | Variable_name | Value | +------------------------+-------+ | max_sp_recursion_depth | 255 | +------------------------+-------+ 1 row in set (0.01 sec) The limit can be extended while writing the procedure also.
[ { "code": null, "e": 1293, "s": 1062, "text": "A stored procedure is called recursive if it calls itself. Basically, this concept is called recursion. MySQL limits the recursion so the errors will be less rigorous. We can check this limit with the help of the following query −" }, { "code": null, "e": 1530, "s": 1293, "text": "mysql> Show variables LIKE '%recur%';\n+------------------------+-------+\n| Variable_name | Value |\n+------------------------+-------+\n| max_sp_recursion_depth | 0 |\n+------------------------+-------+\n1 row in set (0.01 sec)" }, { "code": null, "e": 1604, "s": 1530, "text": "We can change this value up to 255 with the help of the following query −" }, { "code": null, "e": 1931, "s": 1604, "text": "mysql> SET @@GLOBAL.max_sp_recursion_depth = 255//\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Show variables LIKE '%recur%'//\n+------------------------+-------+\n| Variable_name | Value |\n+------------------------+-------+\n| max_sp_recursion_depth | 255 |\n+------------------------+-------+\n1 row in set (0.01 sec)" }, { "code": null, "e": 1991, "s": 1931, "text": "The limit can be extended while writing the procedure also." } ]
How to clear screen using C#?
Use the Console.Clear() method to clear screen and the console buffer. When the Clear method is called, the cursor automatically scrolls to the top-left corner of the window. Here, we have cleared the screen and then set the ForegroundColor and BackgroundColor − ConsoleColor newForeColor = ConsoleColor.Blue; ConsoleColor newBackColor = ConsoleColor.Yellow; The following is the complete code − Live Demo using System; using System.Collections.Generic; class Program { static void Main() { ConsoleColor foreColor = Console.ForegroundColor; ConsoleColor backColor = Console.BackgroundColor; Console.WriteLine("Clearing the screen!"); Console.Clear(); ConsoleColor newForeColor = ConsoleColor.Blue; ConsoleColor newBackColor = ConsoleColor.Yellow; } } Clearing the screen!
[ { "code": null, "e": 1362, "s": 1187, "text": "Use the Console.Clear() method to clear screen and the console buffer. When the Clear method is called, the cursor automatically scrolls to the top-left corner of the window." }, { "code": null, "e": 1450, "s": 1362, "text": "Here, we have cleared the screen and then set the ForegroundColor and BackgroundColor −" }, { "code": null, "e": 1546, "s": 1450, "text": "ConsoleColor newForeColor = ConsoleColor.Blue;\nConsoleColor newBackColor = ConsoleColor.Yellow;" }, { "code": null, "e": 1583, "s": 1546, "text": "The following is the complete code −" }, { "code": null, "e": 1594, "s": 1583, "text": " Live Demo" }, { "code": null, "e": 1982, "s": 1594, "text": "using System;\nusing System.Collections.Generic;\n\nclass Program {\n static void Main() {\n ConsoleColor foreColor = Console.ForegroundColor;\n ConsoleColor backColor = Console.BackgroundColor;\n Console.WriteLine(\"Clearing the screen!\");\n Console.Clear();\n ConsoleColor newForeColor = ConsoleColor.Blue;\n ConsoleColor newBackColor = ConsoleColor.Yellow;\n }\n}" }, { "code": null, "e": 2003, "s": 1982, "text": "Clearing the screen!" } ]
Python | Pandas Timestamp.now
14 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.now() function return the current time in the local timezone. It is Equivalent to datetime.now([tz]). Syntax :Timestamp.now() Parameters : None Return : Timestamp Example #1: Use Timestamp.now() function to return the current time in the local timezone. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.now() function to find the current time in the local timezone. # return the current timets.now() Output : As we can see in the output, the Timestamp.now() function has returned the current time in the local timezone. It auto detects the local timezone. Example #2: Use Timestamp.now() function to return the current time in the local timezone. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.now() function to find the current time in the local timezone. # return the current timets.now() Output : As we can see in the output, the Timestamp.now() function has returned the current time in the local timezone. It auto detects the local timezone. Python Pandas-Timestamp Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 361, "s": 242, "text": "Pandas Timestamp.now() function return the current time in the local timezone. It is Equivalent to datetime.now([tz])." }, { "code": null, "e": 385, "s": 361, "text": "Syntax :Timestamp.now()" }, { "code": null, "e": 403, "s": 385, "text": "Parameters : None" }, { "code": null, "e": 422, "s": 403, "text": "Return : Timestamp" }, { "code": null, "e": 513, "s": 422, "text": "Example #1: Use Timestamp.now() function to return the current time in the local timezone." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)", "e": 733, "s": 513, "text": null }, { "code": null, "e": 742, "s": 733, "text": "Output :" }, { "code": null, "e": 835, "s": 742, "text": "Now we will use the Timestamp.now() function to find the current time in the local timezone." }, { "code": "# return the current timets.now()", "e": 869, "s": 835, "text": null }, { "code": null, "e": 878, "s": 869, "text": "Output :" }, { "code": null, "e": 1116, "s": 878, "text": "As we can see in the output, the Timestamp.now() function has returned the current time in the local timezone. It auto detects the local timezone. Example #2: Use Timestamp.now() function to return the current time in the local timezone." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)", "e": 1332, "s": 1116, "text": null }, { "code": null, "e": 1341, "s": 1332, "text": "Output :" }, { "code": null, "e": 1434, "s": 1341, "text": "Now we will use the Timestamp.now() function to find the current time in the local timezone." }, { "code": "# return the current timets.now()", "e": 1468, "s": 1434, "text": null }, { "code": null, "e": 1477, "s": 1468, "text": "Output :" }, { "code": null, "e": 1624, "s": 1477, "text": "As we can see in the output, the Timestamp.now() function has returned the current time in the local timezone. It auto detects the local timezone." }, { "code": null, "e": 1648, "s": 1624, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 1662, "s": 1648, "text": "Python-pandas" }, { "code": null, "e": 1669, "s": 1662, "text": "Python" } ]
How to scrape Comment using Beautifulsoup in Python?
29 Dec, 2020 Comments are provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The Comment object is just a special type of NavigableString and is used to make the codebase more readable. Syntax: <!-- COMMENT --> Below given examples explain the concept of comments in Beautiful Soup. Example 1: In this example, we are going to create a comment. Python3 # Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentdoc = "<b><!-- COMMENT --></b>" # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser") # Get the whole comment inside b tagcomment = soup.b # Print the commentprint(comment) Output: <b><!-- COMMENT --></b> Example 2: In this example, we are going to create a comment and see its type. Python3 # Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentdoc = "<b><!-- COMMENT --></b>" # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser") # Get the whole comment inside b tagcomment = soup.b.string # Print the type of the commentprint(type(comment)) Output: <class 'bs4.element.Comment'> Python web-scraping-exercises Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2020" }, { "code": null, "e": 337, "s": 28, "text": "Comments are provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The Comment object is just a special type of NavigableString and is used to make the codebase more readable." }, { "code": null, "e": 346, "s": 337, "text": "Syntax: " }, { "code": null, "e": 365, "s": 346, "text": "<!-- COMMENT --> \n" }, { "code": null, "e": 499, "s": 365, "text": "Below given examples explain the concept of comments in Beautiful Soup. Example 1: In this example, we are going to create a comment." }, { "code": null, "e": 507, "s": 499, "text": "Python3" }, { "code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentdoc = \"<b><!-- COMMENT --></b>\" # Initialize the object with the documentsoup = BeautifulSoup(doc, \"html.parser\") # Get the whole comment inside b tagcomment = soup.b # Print the commentprint(comment)", "e": 786, "s": 507, "text": null }, { "code": null, "e": 795, "s": 786, "text": "Output: " }, { "code": null, "e": 820, "s": 795, "text": "<b><!-- COMMENT --></b>\n" }, { "code": null, "e": 899, "s": 820, "text": "Example 2: In this example, we are going to create a comment and see its type." }, { "code": null, "e": 907, "s": 899, "text": "Python3" }, { "code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Create the documentdoc = \"<b><!-- COMMENT --></b>\" # Initialize the object with the documentsoup = BeautifulSoup(doc, \"html.parser\") # Get the whole comment inside b tagcomment = soup.b.string # Print the type of the commentprint(type(comment))", "e": 1211, "s": 907, "text": null }, { "code": null, "e": 1220, "s": 1211, "text": "Output: " }, { "code": null, "e": 1252, "s": 1220, "text": "<class 'bs4.element.Comment'> \n" }, { "code": null, "e": 1282, "s": 1252, "text": "Python web-scraping-exercises" }, { "code": null, "e": 1295, "s": 1282, "text": "Web-scraping" }, { "code": null, "e": 1302, "s": 1295, "text": "Python" } ]
Minimum characters to be added at front to make string palindrome
16 Jun, 2022 Given a string str we need to tell minimum characters to be added at front of string to make string palindrome.Examples: Input : str = "ABC" Output : 2 We can make above string palindrome as "CBABC" by adding 'B' and 'C' at front. Input : str = "AACECAAAA"; Output : 2 We can make above string palindrome as AAAACECAAAA by adding two A's at front of string. Naive approach: Start checking the string each time if it is a palindrome and if not, then delete the last character and check again. When the string gets reduced to wither a palindrome or empty then the number of characters deleted from the end till now will be the answer as those characters could have been inserted at the beginning of the original string in the order which will make the string a palindrome.Below is the implementation of the above approach: C++ Java Python 3 C# Javascript // C++ program for getting minimum character to be// added at front to make string palindrome#include<bits/stdc++.h>using namespace std; // function for checking string is palindrome or notbool ispalindrome(string s){ int l = s.length(); int j; for(int i = 0, j = l - 1; i <= j; i++, j--) { if(s[i] != s[j]) return false; } return true;} // Driver codeint main(){ string s = "BABABAA"; int cnt = 0; int flag = 0; while(s.length()>0) { // if string becomes palindrome then break if(ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s.erase(s.begin() + s.length() - 1); } } // print the number of insertion at front if(flag) cout << cnt;} // Java program for getting minimum character to be// added at front to make string palindrome class GFG { // function for checking string is palindrome or not static boolean ispalindrome(String s) { int l = s.length(); for (int i = 0, j = l - 1; i <= j; i++, j--) { if (s.charAt(i) != s.charAt(j)) { return false; } } return true; } // Driver code public static void main(String[] args) { String s = "BABABAA"; int cnt = 0; int flag = 0; while (s.length() > 0) { // if string becomes palindrome then break if (ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s = s.substring(0, s.length() - 1); //s.erase(s.begin() + s.length() - 1); } } // print the number of insertion at front if (flag == 1) { System.out.println(cnt); } }} // This code is contributed by 29AjayKumar # Python 3 program for getting minimum character# to be added at front to make string palindrome # function for checking string is# palindrome or notdef ispalindrome(s): l = len(s) i = 0 j = l - 1 while i <= j: if(s[i] != s[j]): return False i += 1 j -= 1 return True # Driver codeif __name__ == "__main__": s = "BABABAA" cnt = 0 flag = 0 while(len(s) > 0): # if string becomes palindrome then break if(ispalindrome(s)): flag = 1 break else: cnt += 1 # erase the last element of the string s = s[:-1] # print the number of insertion at front if(flag): print(cnt) # This code is contributed by ita_c // C# program for getting minimum character to be// added at front to make string palindrome using System;public class GFG { // function for checking string is palindrome or not static bool ispalindrome(String s) { int l = s.Length; for (int i = 0, j = l - 1; i <= j; i++, j--) { if (s[i] != s[j]) { return false; } } return true; } // Driver code public static void Main() { String s = "BABABAA"; int cnt = 0; int flag = 0; while (s.Length > 0) { // if string becomes palindrome then break if (ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s = s.Substring(0, s.Length - 1); //s.erase(s.begin() + s.length() - 1); } } // print the number of insertion at front if (flag == 1) { Console.WriteLine(cnt); } }} // This code is contributed by PrinciRaj1992 <script> // JavaScript Program to implement // the above approach // function for checking string is palindrome or not function ispalindrome(s) { let l = s.length; let j; for (let i = 0, j = l - 1; i <= j; i++, j--) { if (s[i] != s[j]) return false; } return true; } // Driver code let s = "BABABAA"; let cnt = 0; let flag = 0; while (s.length > 0) { // if string becomes palindrome then break if (ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s = s.substring(0, s.length - 1); } } // print the number of insertion at front if (flag) document.write(cnt); // This code is contributed by Potta Lokesh </script> Output: 2 Time complexity: O(n2) Auxiliary Space: O(1) Thank you Sanny Kumar for suggesting this approach.Efficient approach: We can solve this problem efficiently in O(n) time using lps array of KMP algorithm. First we concat string by concatenating given string, a special character and reverse of given string then we will get lps array for this concatenated string, recall that each index of lps array represent longest proper prefix which is also suffix. We can use this lps array for solving the problem. For string = AACECAAAA Concatenated String = AACECAAAA$AAAACECAA LPS array will be {0, 1, 0, 0, 0, 1, 2, 2, 2, 0, 1, 2, 2, 2, 3, 4, 5, 6, 7} Here we are only interested in the last value of this lps array because it shows us the largest suffix of the reversed string that matches the prefix of the original string i.e these many characters already satisfy the palindrome property. Finally minimum number of character needed to make the string a palindrome is length of the input string minus last entry of our lps array. Please see below code for better understanding C++ Java Python3 C# Javascript // C++ program for getting minimum character to be// added at front to make string palindrome#include <bits/stdc++.h>using namespace std; // returns vector lps for given string strvector<int> computeLPSArray(string str){ int M = str.length(); vector<int> lps(M); int len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (str[i] != str[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } } return lps;} // Method returns minimum character to be added at// front to make string palindromeint getMinCharToAddedToMakeStringPalin(string str){ string revStr = str; reverse(revStr.begin(), revStr.end()); // Get concatenation of string, special character // and reverse string string concat = str + "$" + revStr; // Get LPS array of this concatenated string vector<int> lps = computeLPSArray(concat); // By subtracting last entry of lps vector from // string length, we will get our result return (str.length() - lps.back());} // Driver program to test above functionsint main(){ string str = "AACECAAAA"; cout << getMinCharToAddedToMakeStringPalin(str); return 0;} // Java program for getting minimum character to be// added at front to make string palindromeimport java.util.*;class GFG{ // returns vector lps for given string strpublic static int[] computeLPSArray(String str){ int n = str.length(); int lps[] = new int[n]; int i = 1, len = 0; lps[0] = 0; // lps[0] is always 0 while (i < n) { if (str.charAt(i) == str.charAt(len)) { len++; lps[i] = len; i++; } else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else { lps[i] = 0; i++; } } } return lps;} // Method returns minimum character to be added at// front to make string palindromestatic int getMinCharToAddedToMakeStringPalin(String str){ StringBuilder s = new StringBuilder(); s.append(str); // Get concatenation of string, special character // and reverse string String rev = s.reverse().toString(); s.reverse().append("$").append(rev); // Get LPS array of this concatenated string int lps[] = computeLPSArray(s.toString()); return str.length() - lps[s.length() - 1];} // Driver Codepublic static void main(String args[]){ String str = "AACECAAAA"; System.out.println(getMinCharToAddedToMakeStringPalin(str));}} // This code is contributed by Sparsh Singhal # Python3 program for getting minimum# character to be added at the front# to make string palindrome # Returns vector lps for given string strdef computeLPSArray(string): M = len(string) lps = [None] * M length = 0 lps[0] = 0 # lps[0] is always 0 # the loop calculates lps[i] # for i = 1 to M-1 i = 1 while i < M: if string[i] == string[length]: length += 1 lps[i] = length i += 1 else: # (str[i] != str[len]) # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is # similar to search step. if length != 0: length = lps[length - 1] # Also, note that we do not # increment i here else: # if (len == 0) lps[i] = 0 i += 1 return lps # Method returns minimum character# to be added at front to make# string palindromedef getMinCharToAddedToMakeStringPalin(string): revStr = string[::-1] # Get concatenation of string, # special character and reverse string concat = string + "$" + revStr # Get LPS array of this # concatenated string lps = computeLPSArray(concat) # By subtracting last entry of lps # vector from string length, we # will get our result return len(string) - lps[-1] # Driver Codeif __name__ == "__main__": string = "AACECAAAA" print(getMinCharToAddedToMakeStringPalin(string)) # This code is contributed by Rituraj Jain // C# program for getting minimum character to be // added at front to make string palindrome using System;using System.Text; public class GFG{ // returns vector lps for given string str public static int[] computeLPSArray(string str) { int n = str.Length; int[] lps = new int[n]; int i = 1, len = 0; lps[0] = 0; // lps[0] is always 0 while (i < n) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else { lps[i] = 0; i++; } } } return lps; } // Method returns minimum character to be added at // front to make string palindrome static int getMinCharToAddedToMakeStringPalin(string str) { char[] s = str.ToCharArray(); // Get concatenation of string, special character // and reverse string Array.Reverse( s ); string rev = new string(s); string concat= str + "$" + rev; // Get LPS array of this concatenated string int[] lps = computeLPSArray(concat); return str.Length - lps[concat.Length - 1]; } // Driver Code static public void Main (){ string str = "AACECAAAA"; Console.WriteLine(getMinCharToAddedToMakeStringPalin(str)); }} // This code is contributed by avanitrachhadiya2155 <script> // JavaScript program for getting minimum character to be// added at front to make string palindrome // returns vector lps for given string strfunction computeLPSArray(str){ let M = str.length; let lps = new Array(M); let len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 let i = 1; while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (str[i] != str[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } } return lps;} // Method returns minimum character to be added at// front to make string palindromefunction getMinCharToAddedToMakeStringPalin(str){ let revStr = str.split('').reverse().join(''); // Get concatenation of string, special character // and reverse string let concat = str + "$" + revStr; // Get LPS array of this concatenated string let lps = computeLPSArray(concat); // By subtracting last entry of lps vector from // string length, we will get our result return (str.length - lps[lps.length-1]);} // Driver program to test above functionslet str = "AACECAAAA";document.write(getMinCharToAddedToMakeStringPalin(str)); // This code is contributed by shinjanpatra </script> Output: 2 Time complexity: O(n) Auxiliary Space: O(n) This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar princiraj1992 ukasp rituraj_jain hemant_dhanuka sparsh singhal avanitrachhadiya2155 lokeshpotta20 kk9826225 shinjanpatra simmytarika5 riya55 palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Length of the longest substring without repeating characters Convert string to char array in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 175, "s": 52, "text": "Given a string str we need to tell minimum characters to be added at front of string to make string palindrome.Examples: " }, { "code": null, "e": 415, "s": 175, "text": "Input : str = \"ABC\"\nOutput : 2\nWe can make above string palindrome as \"CBABC\"\nby adding 'B' and 'C' at front.\n\nInput : str = \"AACECAAAA\";\nOutput : 2\nWe can make above string palindrome as AAAACECAAAA\nby adding two A's at front of string." }, { "code": null, "e": 882, "s": 417, "text": "Naive approach: Start checking the string each time if it is a palindrome and if not, then delete the last character and check again. When the string gets reduced to wither a palindrome or empty then the number of characters deleted from the end till now will be the answer as those characters could have been inserted at the beginning of the original string in the order which will make the string a palindrome.Below is the implementation of the above approach: " }, { "code": null, "e": 886, "s": 882, "text": "C++" }, { "code": null, "e": 891, "s": 886, "text": "Java" }, { "code": null, "e": 900, "s": 891, "text": "Python 3" }, { "code": null, "e": 903, "s": 900, "text": "C#" }, { "code": null, "e": 914, "s": 903, "text": "Javascript" }, { "code": "// C++ program for getting minimum character to be// added at front to make string palindrome#include<bits/stdc++.h>using namespace std; // function for checking string is palindrome or notbool ispalindrome(string s){ int l = s.length(); int j; for(int i = 0, j = l - 1; i <= j; i++, j--) { if(s[i] != s[j]) return false; } return true;} // Driver codeint main(){ string s = \"BABABAA\"; int cnt = 0; int flag = 0; while(s.length()>0) { // if string becomes palindrome then break if(ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s.erase(s.begin() + s.length() - 1); } } // print the number of insertion at front if(flag) cout << cnt;}", "e": 1777, "s": 914, "text": null }, { "code": "// Java program for getting minimum character to be// added at front to make string palindrome class GFG { // function for checking string is palindrome or not static boolean ispalindrome(String s) { int l = s.length(); for (int i = 0, j = l - 1; i <= j; i++, j--) { if (s.charAt(i) != s.charAt(j)) { return false; } } return true; } // Driver code public static void main(String[] args) { String s = \"BABABAA\"; int cnt = 0; int flag = 0; while (s.length() > 0) { // if string becomes palindrome then break if (ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s = s.substring(0, s.length() - 1); //s.erase(s.begin() + s.length() - 1); } } // print the number of insertion at front if (flag == 1) { System.out.println(cnt); } }} // This code is contributed by 29AjayKumar", "e": 2873, "s": 1777, "text": null }, { "code": "# Python 3 program for getting minimum character# to be added at front to make string palindrome # function for checking string is# palindrome or notdef ispalindrome(s): l = len(s) i = 0 j = l - 1 while i <= j: if(s[i] != s[j]): return False i += 1 j -= 1 return True # Driver codeif __name__ == \"__main__\": s = \"BABABAA\" cnt = 0 flag = 0 while(len(s) > 0): # if string becomes palindrome then break if(ispalindrome(s)): flag = 1 break else: cnt += 1 # erase the last element of the string s = s[:-1] # print the number of insertion at front if(flag): print(cnt) # This code is contributed by ita_c", "e": 3674, "s": 2873, "text": null }, { "code": "// C# program for getting minimum character to be// added at front to make string palindrome using System;public class GFG { // function for checking string is palindrome or not static bool ispalindrome(String s) { int l = s.Length; for (int i = 0, j = l - 1; i <= j; i++, j--) { if (s[i] != s[j]) { return false; } } return true; } // Driver code public static void Main() { String s = \"BABABAA\"; int cnt = 0; int flag = 0; while (s.Length > 0) { // if string becomes palindrome then break if (ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s = s.Substring(0, s.Length - 1); //s.erase(s.begin() + s.length() - 1); } } // print the number of insertion at front if (flag == 1) { Console.WriteLine(cnt); } }} // This code is contributed by PrinciRaj1992", "e": 4753, "s": 3674, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // function for checking string is palindrome or not function ispalindrome(s) { let l = s.length; let j; for (let i = 0, j = l - 1; i <= j; i++, j--) { if (s[i] != s[j]) return false; } return true; } // Driver code let s = \"BABABAA\"; let cnt = 0; let flag = 0; while (s.length > 0) { // if string becomes palindrome then break if (ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s = s.substring(0, s.length - 1); } } // print the number of insertion at front if (flag) document.write(cnt); // This code is contributed by Potta Lokesh </script>", "e": 5760, "s": 4753, "text": null }, { "code": null, "e": 5770, "s": 5760, "text": "Output: " }, { "code": null, "e": 5772, "s": 5770, "text": "2" }, { "code": null, "e": 5795, "s": 5772, "text": "Time complexity: O(n2)" }, { "code": null, "e": 5817, "s": 5795, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6275, "s": 5817, "text": "Thank you Sanny Kumar for suggesting this approach.Efficient approach: We can solve this problem efficiently in O(n) time using lps array of KMP algorithm. First we concat string by concatenating given string, a special character and reverse of given string then we will get lps array for this concatenated string, recall that each index of lps array represent longest proper prefix which is also suffix. We can use this lps array for solving the problem. " }, { "code": null, "e": 6436, "s": 6275, "text": "For string = AACECAAAA\nConcatenated String = AACECAAAA$AAAACECAA\nLPS array will be {0, 1, 0, 0, 0, 1, 2, 2, 2, \n 0, 1, 2, 2, 2, 3, 4, 5, 6, 7}" }, { "code": null, "e": 6864, "s": 6436, "text": "Here we are only interested in the last value of this lps array because it shows us the largest suffix of the reversed string that matches the prefix of the original string i.e these many characters already satisfy the palindrome property. Finally minimum number of character needed to make the string a palindrome is length of the input string minus last entry of our lps array. Please see below code for better understanding " }, { "code": null, "e": 6868, "s": 6864, "text": "C++" }, { "code": null, "e": 6873, "s": 6868, "text": "Java" }, { "code": null, "e": 6881, "s": 6873, "text": "Python3" }, { "code": null, "e": 6884, "s": 6881, "text": "C#" }, { "code": null, "e": 6895, "s": 6884, "text": "Javascript" }, { "code": "// C++ program for getting minimum character to be// added at front to make string palindrome#include <bits/stdc++.h>using namespace std; // returns vector lps for given string strvector<int> computeLPSArray(string str){ int M = str.length(); vector<int> lps(M); int len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (str[i] != str[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } } return lps;} // Method returns minimum character to be added at// front to make string palindromeint getMinCharToAddedToMakeStringPalin(string str){ string revStr = str; reverse(revStr.begin(), revStr.end()); // Get concatenation of string, special character // and reverse string string concat = str + \"$\" + revStr; // Get LPS array of this concatenated string vector<int> lps = computeLPSArray(concat); // By subtracting last entry of lps vector from // string length, we will get our result return (str.length() - lps.back());} // Driver program to test above functionsint main(){ string str = \"AACECAAAA\"; cout << getMinCharToAddedToMakeStringPalin(str); return 0;}", "e": 8594, "s": 6895, "text": null }, { "code": "// Java program for getting minimum character to be// added at front to make string palindromeimport java.util.*;class GFG{ // returns vector lps for given string strpublic static int[] computeLPSArray(String str){ int n = str.length(); int lps[] = new int[n]; int i = 1, len = 0; lps[0] = 0; // lps[0] is always 0 while (i < n) { if (str.charAt(i) == str.charAt(len)) { len++; lps[i] = len; i++; } else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else { lps[i] = 0; i++; } } } return lps;} // Method returns minimum character to be added at// front to make string palindromestatic int getMinCharToAddedToMakeStringPalin(String str){ StringBuilder s = new StringBuilder(); s.append(str); // Get concatenation of string, special character // and reverse string String rev = s.reverse().toString(); s.reverse().append(\"$\").append(rev); // Get LPS array of this concatenated string int lps[] = computeLPSArray(s.toString()); return str.length() - lps[s.length() - 1];} // Driver Codepublic static void main(String args[]){ String str = \"AACECAAAA\"; System.out.println(getMinCharToAddedToMakeStringPalin(str));}} // This code is contributed by Sparsh Singhal", "e": 10235, "s": 8594, "text": null }, { "code": "# Python3 program for getting minimum# character to be added at the front# to make string palindrome # Returns vector lps for given string strdef computeLPSArray(string): M = len(string) lps = [None] * M length = 0 lps[0] = 0 # lps[0] is always 0 # the loop calculates lps[i] # for i = 1 to M-1 i = 1 while i < M: if string[i] == string[length]: length += 1 lps[i] = length i += 1 else: # (str[i] != str[len]) # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is # similar to search step. if length != 0: length = lps[length - 1] # Also, note that we do not # increment i here else: # if (len == 0) lps[i] = 0 i += 1 return lps # Method returns minimum character# to be added at front to make# string palindromedef getMinCharToAddedToMakeStringPalin(string): revStr = string[::-1] # Get concatenation of string, # special character and reverse string concat = string + \"$\" + revStr # Get LPS array of this # concatenated string lps = computeLPSArray(concat) # By subtracting last entry of lps # vector from string length, we # will get our result return len(string) - lps[-1] # Driver Codeif __name__ == \"__main__\": string = \"AACECAAAA\" print(getMinCharToAddedToMakeStringPalin(string)) # This code is contributed by Rituraj Jain", "e": 11814, "s": 10235, "text": null }, { "code": "// C# program for getting minimum character to be // added at front to make string palindrome using System;using System.Text; public class GFG{ // returns vector lps for given string str public static int[] computeLPSArray(string str) { int n = str.Length; int[] lps = new int[n]; int i = 1, len = 0; lps[0] = 0; // lps[0] is always 0 while (i < n) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else { lps[i] = 0; i++; } } } return lps; } // Method returns minimum character to be added at // front to make string palindrome static int getMinCharToAddedToMakeStringPalin(string str) { char[] s = str.ToCharArray(); // Get concatenation of string, special character // and reverse string Array.Reverse( s ); string rev = new string(s); string concat= str + \"$\" + rev; // Get LPS array of this concatenated string int[] lps = computeLPSArray(concat); return str.Length - lps[concat.Length - 1]; } // Driver Code static public void Main (){ string str = \"AACECAAAA\"; Console.WriteLine(getMinCharToAddedToMakeStringPalin(str)); }} // This code is contributed by avanitrachhadiya2155", "e": 13353, "s": 11814, "text": null }, { "code": "<script> // JavaScript program for getting minimum character to be// added at front to make string palindrome // returns vector lps for given string strfunction computeLPSArray(str){ let M = str.length; let lps = new Array(M); let len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 let i = 1; while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (str[i] != str[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } } return lps;} // Method returns minimum character to be added at// front to make string palindromefunction getMinCharToAddedToMakeStringPalin(str){ let revStr = str.split('').reverse().join(''); // Get concatenation of string, special character // and reverse string let concat = str + \"$\" + revStr; // Get LPS array of this concatenated string let lps = computeLPSArray(concat); // By subtracting last entry of lps vector from // string length, we will get our result return (str.length - lps[lps.length-1]);} // Driver program to test above functionslet str = \"AACECAAAA\";document.write(getMinCharToAddedToMakeStringPalin(str)); // This code is contributed by shinjanpatra </script>", "e": 15017, "s": 13353, "text": null }, { "code": null, "e": 15027, "s": 15017, "text": "Output: " }, { "code": null, "e": 15029, "s": 15027, "text": "2" }, { "code": null, "e": 15051, "s": 15029, "text": "Time complexity: O(n)" }, { "code": null, "e": 15073, "s": 15051, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 15497, "s": 15073, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 15509, "s": 15497, "text": "29AjayKumar" }, { "code": null, "e": 15523, "s": 15509, "text": "princiraj1992" }, { "code": null, "e": 15529, "s": 15523, "text": "ukasp" }, { "code": null, "e": 15542, "s": 15529, "text": "rituraj_jain" }, { "code": null, "e": 15557, "s": 15542, "text": "hemant_dhanuka" }, { "code": null, "e": 15572, "s": 15557, "text": "sparsh singhal" }, { "code": null, "e": 15593, "s": 15572, "text": "avanitrachhadiya2155" }, { "code": null, "e": 15607, "s": 15593, "text": "lokeshpotta20" }, { "code": null, "e": 15617, "s": 15607, "text": "kk9826225" }, { "code": null, "e": 15630, "s": 15617, "text": "shinjanpatra" }, { "code": null, "e": 15643, "s": 15630, "text": "simmytarika5" }, { "code": null, "e": 15650, "s": 15643, "text": "riya55" }, { "code": null, "e": 15661, "s": 15650, "text": "palindrome" }, { "code": null, "e": 15669, "s": 15661, "text": "Strings" }, { "code": null, "e": 15677, "s": 15669, "text": "Strings" }, { "code": null, "e": 15688, "s": 15677, "text": "palindrome" }, { "code": null, "e": 15786, "s": 15688, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15832, "s": 15786, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 15857, "s": 15832, "text": "Reverse a string in Java" }, { "code": null, "e": 15917, "s": 15857, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 15932, "s": 15917, "text": "C++ Data Types" }, { "code": null, "e": 15977, "s": 15932, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 16034, "s": 15977, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 16068, "s": 16034, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 16143, "s": 16068, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 16204, "s": 16143, "text": "Length of the longest substring without repeating characters" } ]
How to check which Button was clicked in Tkinter ?
25 Jan, 2022 Are you using various buttons in your app, and you are being confused about which button is being pressed? Don’t know how to get rid of this solution!! Don’t worry, just go through the article. In this article, we will explain in detail the procedure to know which button was pressed. Step 1: First, import the library Tkinter. from tkinter import * Step 2: Now, create a GUI app using Tkinter. app = Tk() Step 3: Then, create a function with one parameter, i.e., of the text you want to show when a button is clicked def which_button(button_press): print (button_press) Step 4: Further, create and display the first button by calling the which_button function you declared in step 3. b1 = Button(app, text="#Text you want to show in button b1", command=lambda m="#Text you want to show when\ b1 is clicked": which_button(m)) b1.grid(padx=10, pady=10) Step 5: Moreover, create and display the second button by calling the which_button function you declared in step 3. b2 = Button(app, text="#Text you want to show in button b2", command=lambda m="#Text you want to show when \ b2 is clicked": which_button(m)) b2.grid(padx=10, pady=10) Step 6: Next, keep on repeating steps 4 and 5 for n number of buttons by replacing n with the number of buttons you want it to display on the app. Don’t forget to call the which_button function you declared in step 3. bn = Button(app, text="#Text you want to show in button bn", command=lambda m="#Text you want to show when \ bn is clicked": which_button(m)) bn.grid(padx=10, pady=10) Step 7: Finally, create an infinite loop for displaying the app on the screen. app.mainloop() Example: In this example, if the text ‘It is an apple‘ is printed on the screen, we get to know ‘Apple‘ button is pressed, else when ‘It is a banana‘ is printed on the screen, we get to know ‘Banana‘ button is pressed. Python # Python program to determine which# button was pressed in tkinter # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Create a function with one parameter, i.e., of# the text you want to show when button is clickeddef which_button(button_press): # Printing the text when a button is clicked print(button_press) # Creating and displaying of button b1b1 = Button(app, text="Apple", command=lambda m="It is an apple": which_button(m)) b1.grid(padx=10, pady=10) # Creating and displaying of button b2b2 = Button(app, text="Banana", command=lambda m="It is a banana": which_button(m))b2.grid(padx=10, pady=10) # Make the infinite loop for displaying the appapp.mainloop() Output: adnanirshad158 Picked Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jan, 2022" }, { "code": null, "e": 339, "s": 54, "text": "Are you using various buttons in your app, and you are being confused about which button is being pressed? Don’t know how to get rid of this solution!! Don’t worry, just go through the article. In this article, we will explain in detail the procedure to know which button was pressed." }, { "code": null, "e": 382, "s": 339, "text": "Step 1: First, import the library Tkinter." }, { "code": null, "e": 404, "s": 382, "text": "from tkinter import *" }, { "code": null, "e": 449, "s": 404, "text": "Step 2: Now, create a GUI app using Tkinter." }, { "code": null, "e": 460, "s": 449, "text": "app = Tk()" }, { "code": null, "e": 572, "s": 460, "text": "Step 3: Then, create a function with one parameter, i.e., of the text you want to show when a button is clicked" }, { "code": null, "e": 628, "s": 572, "text": "def which_button(button_press):\n print (button_press)" }, { "code": null, "e": 742, "s": 628, "text": "Step 4: Further, create and display the first button by calling the which_button function you declared in step 3." }, { "code": null, "e": 946, "s": 742, "text": "b1 = Button(app, text=\"#Text you want to show in button b1\",\n command=lambda m=\"#Text you want to show when\\\n b1 is clicked\": which_button(m))\n \nb1.grid(padx=10, pady=10)" }, { "code": null, "e": 1062, "s": 946, "text": "Step 5: Moreover, create and display the second button by calling the which_button function you declared in step 3." }, { "code": null, "e": 1267, "s": 1062, "text": "b2 = Button(app, text=\"#Text you want to show in button b2\",\n command=lambda m=\"#Text you want to show when \\\n b2 is clicked\": which_button(m))\n \nb2.grid(padx=10, pady=10)" }, { "code": null, "e": 1485, "s": 1267, "text": "Step 6: Next, keep on repeating steps 4 and 5 for n number of buttons by replacing n with the number of buttons you want it to display on the app. Don’t forget to call the which_button function you declared in step 3." }, { "code": null, "e": 1690, "s": 1485, "text": "bn = Button(app, text=\"#Text you want to show in button bn\",\n command=lambda m=\"#Text you want to show when \\\n bn is clicked\": which_button(m))\n \nbn.grid(padx=10, pady=10)" }, { "code": null, "e": 1769, "s": 1690, "text": "Step 7: Finally, create an infinite loop for displaying the app on the screen." }, { "code": null, "e": 1784, "s": 1769, "text": "app.mainloop()" }, { "code": null, "e": 1794, "s": 1784, "text": "Example: " }, { "code": null, "e": 2004, "s": 1794, "text": "In this example, if the text ‘It is an apple‘ is printed on the screen, we get to know ‘Apple‘ button is pressed, else when ‘It is a banana‘ is printed on the screen, we get to know ‘Banana‘ button is pressed." }, { "code": null, "e": 2011, "s": 2004, "text": "Python" }, { "code": "# Python program to determine which# button was pressed in tkinter # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Create a function with one parameter, i.e., of# the text you want to show when button is clickeddef which_button(button_press): # Printing the text when a button is clicked print(button_press) # Creating and displaying of button b1b1 = Button(app, text=\"Apple\", command=lambda m=\"It is an apple\": which_button(m)) b1.grid(padx=10, pady=10) # Creating and displaying of button b2b2 = Button(app, text=\"Banana\", command=lambda m=\"It is a banana\": which_button(m))b2.grid(padx=10, pady=10) # Make the infinite loop for displaying the appapp.mainloop()", "e": 2737, "s": 2011, "text": null }, { "code": null, "e": 2745, "s": 2737, "text": "Output:" }, { "code": null, "e": 2760, "s": 2745, "text": "adnanirshad158" }, { "code": null, "e": 2767, "s": 2760, "text": "Picked" }, { "code": null, "e": 2792, "s": 2767, "text": "Python Tkinter-exercises" }, { "code": null, "e": 2807, "s": 2792, "text": "Python-tkinter" }, { "code": null, "e": 2814, "s": 2807, "text": "Python" }, { "code": null, "e": 2912, "s": 2814, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2944, "s": 2912, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2971, "s": 2944, "text": "Python Classes and Objects" }, { "code": null, "e": 2992, "s": 2971, "text": "Python OOPs Concepts" }, { "code": null, "e": 3015, "s": 2992, "text": "Introduction To PYTHON" }, { "code": null, "e": 3071, "s": 3015, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3102, "s": 3071, "text": "Python | os.path.join() method" }, { "code": null, "e": 3144, "s": 3102, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3186, "s": 3144, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3225, "s": 3186, "text": "Python | datetime.timedelta() function" } ]
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
02 Dec, 2021 Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt from scratch, it provides world-class support for developing Spring-based enterprise applications, whether you prefer Eclipse, Visual Studio Code, or Theia IDE. Prerequisite: Make sure you have installed Java Development Kit (JDK) version 8 or newer. To check simply go to the terminal and enter the below command to check if it is present or not. javac -version Procedure: These are steps to be followed sequentially which are discussed further with visual aids as listed: Download SpringToolSuite as per the operating system to the local machine.Move the downloaded JAR file to the corresponding folder.Unzip this JAR file and open the corresponding folder.Click on the SpringToolSuite4 Application fileSelect the directory representing workspace and press the ‘LAUNCH’ button. Download SpringToolSuite as per the operating system to the local machine. Move the downloaded JAR file to the corresponding folder. Unzip this JAR file and open the corresponding folder. Click on the SpringToolSuite4 Application file Select the directory representing workspace and press the ‘LAUNCH’ button. Step 1: Go to their website and in Spring Tools 4 for the Eclipse section in order to download. choose your corresponding file according to your OS. Here we are going with Windows operating systems so do we have chosen Windows option as seen in the below image. Step 2: After clicking on the button a Jar file will be downloaded to your local system. Now create a folder and move this Jar file to that folder. And double-click on that Jar file. A pop-up window will appear like this. Step 3: After successfully Unpacking a new folder will create as shown in the below image. Now open the folder. Step 4: In this folder now click on the SpringToolSuite4 Application file as shown in the below image. Step 5: Now select your directory as workspace by clicking on the Browse button and then click on the Launch button. And you are done. This is the Home screen for Spring Tool Suite (Spring Tools 4 for Eclipse) IDE sweetyty Java-Spring 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": 52, "s": 24, "text": "\n02 Dec, 2021" }, { "code": null, "e": 563, "s": 52, "text": "Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt from scratch, it provides world-class support for developing Spring-based enterprise applications, whether you prefer Eclipse, Visual Studio Code, or Theia IDE." }, { "code": null, "e": 750, "s": 563, "text": "Prerequisite: Make sure you have installed Java Development Kit (JDK) version 8 or newer. To check simply go to the terminal and enter the below command to check if it is present or not." }, { "code": null, "e": 765, "s": 750, "text": "javac -version" }, { "code": null, "e": 876, "s": 765, "text": "Procedure: These are steps to be followed sequentially which are discussed further with visual aids as listed:" }, { "code": null, "e": 1182, "s": 876, "text": "Download SpringToolSuite as per the operating system to the local machine.Move the downloaded JAR file to the corresponding folder.Unzip this JAR file and open the corresponding folder.Click on the SpringToolSuite4 Application fileSelect the directory representing workspace and press the ‘LAUNCH’ button." }, { "code": null, "e": 1257, "s": 1182, "text": "Download SpringToolSuite as per the operating system to the local machine." }, { "code": null, "e": 1315, "s": 1257, "text": "Move the downloaded JAR file to the corresponding folder." }, { "code": null, "e": 1370, "s": 1315, "text": "Unzip this JAR file and open the corresponding folder." }, { "code": null, "e": 1417, "s": 1370, "text": "Click on the SpringToolSuite4 Application file" }, { "code": null, "e": 1492, "s": 1417, "text": "Select the directory representing workspace and press the ‘LAUNCH’ button." }, { "code": null, "e": 1642, "s": 1492, "text": "Step 1: Go to their website and in Spring Tools 4 for the Eclipse section in order to download. choose your corresponding file according to your OS. " }, { "code": null, "e": 1756, "s": 1642, "text": "Here we are going with Windows operating systems so do we have chosen Windows option as seen in the below image. " }, { "code": null, "e": 1979, "s": 1756, "text": "Step 2: After clicking on the button a Jar file will be downloaded to your local system. Now create a folder and move this Jar file to that folder. And double-click on that Jar file. A pop-up window will appear like this. " }, { "code": null, "e": 2092, "s": 1979, "text": "Step 3: After successfully Unpacking a new folder will create as shown in the below image. Now open the folder. " }, { "code": null, "e": 2196, "s": 2092, "text": "Step 4: In this folder now click on the SpringToolSuite4 Application file as shown in the below image. " }, { "code": null, "e": 2332, "s": 2196, "text": "Step 5: Now select your directory as workspace by clicking on the Browse button and then click on the Launch button. And you are done. " }, { "code": null, "e": 2411, "s": 2332, "text": "This is the Home screen for Spring Tool Suite (Spring Tools 4 for Eclipse) IDE" }, { "code": null, "e": 2420, "s": 2411, "text": "sweetyty" }, { "code": null, "e": 2432, "s": 2420, "text": "Java-Spring" }, { "code": null, "e": 2437, "s": 2432, "text": "Java" }, { "code": null, "e": 2442, "s": 2437, "text": "Java" }, { "code": null, "e": 2540, "s": 2442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2555, "s": 2540, "text": "Stream In Java" }, { "code": null, "e": 2576, "s": 2555, "text": "Introduction to Java" }, { "code": null, "e": 2597, "s": 2576, "text": "Constructors in Java" }, { "code": null, "e": 2616, "s": 2597, "text": "Exceptions in Java" }, { "code": null, "e": 2633, "s": 2616, "text": "Generics in Java" }, { "code": null, "e": 2663, "s": 2633, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2689, "s": 2663, "text": "Java Programming Examples" }, { "code": null, "e": 2705, "s": 2689, "text": "Strings in Java" }, { "code": null, "e": 2742, "s": 2705, "text": "Differences between JDK, JRE and JVM" } ]
Noiseless Channel Protocol
18 Feb, 2022 Introduction :A protocol is a set of rules used by two devices to communicate. These sets of rules are usually decided by headers (fixed headers determined by the protocol). These headers specify the content of the message and the way this message is processed. To detect the error, the header must be the address of the destination, the address of the source, the checksum of the message. Categorization of protocol :The exploration of protocols is split into those that can be applied for noiseless(error-free) channels and those that can be used for noisy(error-causing) channels. The first category of protocols cannot be used in actual life, but they serve as a basis for protocols for noise channels. Noiseless Channel :An idealistic channel in which no frames are lost, corrupted or duplicated. The protocol does not implement error control in this category. There are two protocols for the noiseless channel as follows. Simplest Protocol – We consider here that the receiver can maintain any frame received with insignificant processing time. The receiver’s data link layer immediately removes the header from the frame and assigns the data packet to its network layer, which can also accept the packet immediately. That is to say, the receiver can never be overwhelmed with forthcoming frames. Design :The data link layer at the sender site gets data from its network layer, makes a frame out of the data, and sends it. The data link layer(receiver site) receives a frame from its physical layer, extracts data from the frame, and convey the data to its network layer. The data link layers of the sender and receiver provide communication/transmission services for their network layers. The data link layers utilization the services provided by their physical layers for the physical transmission of bits. Design of Simplest Protocol with no error control or flow Sender-site and Receivers algorithms :Sender-site algorithm – while(true) //Repeat forever { waitForEvent(); //sleep until an event occur if (Event(RequestToSend)) //there is a packet to send { GetData(); MakeFrame(); SendFrame(); //send the frame } } Receivers algorithm – while(true) //Repeat forever { waitForEvent(); //sleep until an event occur if (Event(ArrivalNotification)) //data frame arrived { ReceiveFrame(); ExtractData(); DeliverData(); //Deliver data to network layer } } Flow Diagram :This Flow Diagram shows an example of communication using the simplest protocol. It is very straightforward. The sender sends a series of frames without further consideration about the receiver. Let’s take an example, three frames will send from the sender, and three frames received by receivers. Bear in mind the data frames are shown by tilted boxes; the height of the box defines the transmission time difference between the first bit and the last bit in the frame. Diagram – Flow Diagram for Simplest Protocol Stop and Wait Protocol – If data frame receivers arrive at the site faster than they can be processed, then frames must be stored until their use. Generally, the receiver does not have enough storage space, especially if it is receiving data from multiple sources. Design :On Comparing the stop-and-wait protocol design model with the Simplest protocol design model, we can see the traffic on the front/forward channel (from sender to receiver) and the back/reverse channel. Anytime, there is either one data frame on the forward channel or one ACK frame on the reverse channel. We hereupon require a half-duplex link. Design of Stop-and-Wait Protocol Sender-site and Receivers algorithms :Sender-site algorithm – while(true) //Repeat forever canSend = true // Allow the first frame to go { waitForEvent(); //sleep until an event occur if (Event(RequestToSend)AND canSend) //there is a packet to send { GetData(); MakeFrame(); SendFrame(); //send the data frame canSend = false; //cannot send until ACK arrives } WaitForEvent(); //sleep until an event occurs if(Event(ArrivalNotification)) //An ACK has arrived { ReceiveFrame(); //Receive the ACK frame CanSend = true; } Receivers algorithm – while(true) //Repeat forever { waitForEvent(); //sleep until an event occur if (Event(ArrivalNotification) //data frame arrives { ReceiveFrame(); ExtractData(); DeliverData(); //Deliver data to network layer SendFrame(); //Send an ACK frame } } Flow Diagram : This figure shows an example of communication using the Stop-and-wait protocol. It is still straightforward. The sender sends a frame and waits for a response from the receiver. When ACK(acknowledged) will arrival from the receiver side then send the next frame and so on. Keep it in mind when two frames will be there sender will involve in four event and the receivers will involve in two events. Flow diagram for Stop & Wait Protocol tanushree7252 germanshephered48 kk773572498 Technical Scripter 2020 Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Feb, 2022" }, { "code": null, "e": 442, "s": 52, "text": "Introduction :A protocol is a set of rules used by two devices to communicate. These sets of rules are usually decided by headers (fixed headers determined by the protocol). These headers specify the content of the message and the way this message is processed. To detect the error, the header must be the address of the destination, the address of the source, the checksum of the message." }, { "code": null, "e": 759, "s": 442, "text": "Categorization of protocol :The exploration of protocols is split into those that can be applied for noiseless(error-free) channels and those that can be used for noisy(error-causing) channels. The first category of protocols cannot be used in actual life, but they serve as a basis for protocols for noise channels." }, { "code": null, "e": 980, "s": 759, "text": "Noiseless Channel :An idealistic channel in which no frames are lost, corrupted or duplicated. The protocol does not implement error control in this category. There are two protocols for the noiseless channel as follows." }, { "code": null, "e": 1355, "s": 980, "text": "Simplest Protocol – We consider here that the receiver can maintain any frame received with insignificant processing time. The receiver’s data link layer immediately removes the header from the frame and assigns the data packet to its network layer, which can also accept the packet immediately. That is to say, the receiver can never be overwhelmed with forthcoming frames." }, { "code": null, "e": 1867, "s": 1355, "text": "Design :The data link layer at the sender site gets data from its network layer, makes a frame out of the data, and sends it. The data link layer(receiver site) receives a frame from its physical layer, extracts data from the frame, and convey the data to its network layer. The data link layers of the sender and receiver provide communication/transmission services for their network layers. The data link layers utilization the services provided by their physical layers for the physical transmission of bits." }, { "code": null, "e": 1925, "s": 1867, "text": "Design of Simplest Protocol with no error control or flow" }, { "code": null, "e": 1987, "s": 1925, "text": "Sender-site and Receivers algorithms :Sender-site algorithm –" }, { "code": null, "e": 2265, "s": 1987, "text": "while(true) //Repeat forever\n{ \n waitForEvent(); //sleep until an event occur\n if (Event(RequestToSend)) //there is a packet to send\n {\n GetData();\n MakeFrame();\n SendFrame(); //send the frame\n }\n}" }, { "code": null, "e": 2287, "s": 2265, "text": "Receivers algorithm –" }, { "code": null, "e": 2603, "s": 2287, "text": "while(true) //Repeat forever\n{ \n waitForEvent(); //sleep until an event occur\n if (Event(ArrivalNotification)) //data frame arrived\n {\n ReceiveFrame();\n ExtractData();\n DeliverData(); //Deliver data to network layer\n }\n}" }, { "code": null, "e": 3087, "s": 2603, "text": "Flow Diagram :This Flow Diagram shows an example of communication using the simplest protocol. It is very straightforward. The sender sends a series of frames without further consideration about the receiver. Let’s take an example, three frames will send from the sender, and three frames received by receivers. Bear in mind the data frames are shown by tilted boxes; the height of the box defines the transmission time difference between the first bit and the last bit in the frame." }, { "code": null, "e": 3097, "s": 3087, "text": "Diagram –" }, { "code": null, "e": 3132, "s": 3097, "text": "Flow Diagram for Simplest Protocol" }, { "code": null, "e": 3397, "s": 3132, "text": "Stop and Wait Protocol – If data frame receivers arrive at the site faster than they can be processed, then frames must be stored until their use. Generally, the receiver does not have enough storage space, especially if it is receiving data from multiple sources." }, { "code": null, "e": 3751, "s": 3397, "text": "Design :On Comparing the stop-and-wait protocol design model with the Simplest protocol design model, we can see the traffic on the front/forward channel (from sender to receiver) and the back/reverse channel. Anytime, there is either one data frame on the forward channel or one ACK frame on the reverse channel. We hereupon require a half-duplex link." }, { "code": null, "e": 3784, "s": 3751, "text": "Design of Stop-and-Wait Protocol" }, { "code": null, "e": 3846, "s": 3784, "text": "Sender-site and Receivers algorithms :Sender-site algorithm –" }, { "code": null, "e": 4561, "s": 3846, "text": "while(true) //Repeat forever\ncanSend = true // Allow the first frame to go\n{ \n waitForEvent(); //sleep until an event occur\n if (Event(RequestToSend)AND canSend) //there is a packet to send\n {\n GetData();\n MakeFrame();\n SendFrame(); //send the data frame\n canSend = false; //cannot send until ACK arrives\n }\n WaitForEvent(); //sleep until an event occurs\n if(Event(ArrivalNotification)) //An ACK has arrived\n {\n ReceiveFrame(); //Receive the ACK frame\n CanSend = true;\n} " }, { "code": null, "e": 4583, "s": 4561, "text": "Receivers algorithm –" }, { "code": null, "e": 4974, "s": 4583, "text": "while(true) //Repeat forever\n\n{ \n waitForEvent(); //sleep until an event occur\n if (Event(ArrivalNotification) //data frame arrives\n {\n ReceiveFrame();\n ExtractData();\n DeliverData(); //Deliver data to network layer\n SendFrame(); //Send an ACK frame\n }\n }" }, { "code": null, "e": 5388, "s": 4974, "text": "Flow Diagram : This figure shows an example of communication using the Stop-and-wait protocol. It is still straightforward. The sender sends a frame and waits for a response from the receiver. When ACK(acknowledged) will arrival from the receiver side then send the next frame and so on. Keep it in mind when two frames will be there sender will involve in four event and the receivers will involve in two events." }, { "code": null, "e": 5426, "s": 5388, "text": "Flow diagram for Stop & Wait Protocol" }, { "code": null, "e": 5440, "s": 5426, "text": "tanushree7252" }, { "code": null, "e": 5458, "s": 5440, "text": "germanshephered48" }, { "code": null, "e": 5470, "s": 5458, "text": "kk773572498" }, { "code": null, "e": 5494, "s": 5470, "text": "Technical Scripter 2020" }, { "code": null, "e": 5512, "s": 5494, "text": "Computer Networks" }, { "code": null, "e": 5520, "s": 5512, "text": "GATE CS" }, { "code": null, "e": 5538, "s": 5520, "text": "Computer Networks" } ]
Flutter – Auto size text
11 Apr, 2022 An adaptive UI is an integral part of any application. As applications nowadays have to function on a wide range of devices ranging from tablets, PCs, and mobile with varying screen sizes. This is where the application needs to adjust itself according to the size of the screen irrespective of the size of the content of the application. Flutter provides with an auto_size_text dependency that adapts the screen according to the screen size and manipulates itself to provide with adaptive user experience. The above dependency adjusts the size of the text in the application. In this article, we will explore the same dependency in detail by building a simple application. To build the application follow the below steps: Add the dependency to the pubspec.yaml file. Import the dependency into the main.dart file. Create a StatelessWidget to give the app a structure Add a sample text to adapt Now, let’s discuss the above steps in detail. To add the dependency to the pubspec.yaml file, add the auto_size_text to the flutter dependency as shown below: The dependency can be imported into the main.dart file as follows: import 'package:auto_size_text/auto_size_text.dart'; Use the StatelessWidget to give a simple structure to the app as shown below: Dart class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(title: Text('GeeksForGeeks'), backgroundColor: Colors.green,), ), ), ); }} A text inside the body of the application can be added inside a sizedBox as shown below: Dart child: SizedBox( width: 200.0, height: 140.0, child: AutoSizeText( 'Hello Geeks!. We will break this line into 3 lines !!', style: TextStyle(fontSize: 30.0), maxLines: 3, ),), Complete Source Code: Dart import 'package:auto_size_text/auto_size_text.dart';import 'package:flutter/material.dart'; void main() { runApp(App());} class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(title: Text('GeeksForGeeks'), backgroundColor: Colors.green,), body: Center( child: SizedBox( width: 200.0, height: 140.0, child: AutoSizeText( 'Hello Geeks!. We will break this line into 3 lines !!', style: TextStyle(fontSize: 30.0), maxLines: 3, ), ), ), ), ); }} Output: If you wish to make the text fit in 2 lines instead of 3 line, make the below changes to the code: Dart import 'package:auto_size_text/auto_size_text.dart';import 'package:flutter/material.dart'; void main() { runApp(App());} class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(title: Text('GeeksForGeeks'), backgroundColor: Colors.green,), body: Center( child: SizedBox( width: 200.0, height: 140.0, child: AutoSizeText( 'Hello Geeks! We will break this line into 3 lines !!', style: TextStyle(fontSize: 30.0), maxLines: 2, ), ), ), ), ); }} Output: sumitgumber28 akshaysingh98088 sooda367 saurabh1990aror kalrap615 simranarora5sos android Flutter Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Apr, 2022" }, { "code": null, "e": 366, "s": 28, "text": "An adaptive UI is an integral part of any application. As applications nowadays have to function on a wide range of devices ranging from tablets, PCs, and mobile with varying screen sizes. This is where the application needs to adjust itself according to the size of the screen irrespective of the size of the content of the application." }, { "code": null, "e": 701, "s": 366, "text": "Flutter provides with an auto_size_text dependency that adapts the screen according to the screen size and manipulates itself to provide with adaptive user experience. The above dependency adjusts the size of the text in the application. In this article, we will explore the same dependency in detail by building a simple application." }, { "code": null, "e": 750, "s": 701, "text": "To build the application follow the below steps:" }, { "code": null, "e": 795, "s": 750, "text": "Add the dependency to the pubspec.yaml file." }, { "code": null, "e": 842, "s": 795, "text": "Import the dependency into the main.dart file." }, { "code": null, "e": 895, "s": 842, "text": "Create a StatelessWidget to give the app a structure" }, { "code": null, "e": 922, "s": 895, "text": "Add a sample text to adapt" }, { "code": null, "e": 968, "s": 922, "text": "Now, let’s discuss the above steps in detail." }, { "code": null, "e": 1082, "s": 968, "text": "To add the dependency to the pubspec.yaml file, add the auto_size_text to the flutter dependency as shown below:" }, { "code": null, "e": 1149, "s": 1082, "text": "The dependency can be imported into the main.dart file as follows:" }, { "code": null, "e": 1202, "s": 1149, "text": "import 'package:auto_size_text/auto_size_text.dart';" }, { "code": null, "e": 1280, "s": 1202, "text": "Use the StatelessWidget to give a simple structure to the app as shown below:" }, { "code": null, "e": 1285, "s": 1280, "text": "Dart" }, { "code": "class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(title: Text('GeeksForGeeks'), backgroundColor: Colors.green,), ), ), ); }}", "e": 1535, "s": 1285, "text": null }, { "code": null, "e": 1624, "s": 1535, "text": "A text inside the body of the application can be added inside a sizedBox as shown below:" }, { "code": null, "e": 1629, "s": 1624, "text": "Dart" }, { "code": "child: SizedBox( width: 200.0, height: 140.0, child: AutoSizeText( 'Hello Geeks!. We will break this line into 3 lines !!', style: TextStyle(fontSize: 30.0), maxLines: 3, ),),", "e": 1818, "s": 1629, "text": null }, { "code": null, "e": 1843, "s": 1821, "text": "Complete Source Code:" }, { "code": null, "e": 1850, "s": 1845, "text": "Dart" }, { "code": "import 'package:auto_size_text/auto_size_text.dart';import 'package:flutter/material.dart'; void main() { runApp(App());} class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(title: Text('GeeksForGeeks'), backgroundColor: Colors.green,), body: Center( child: SizedBox( width: 200.0, height: 140.0, child: AutoSizeText( 'Hello Geeks!. We will break this line into 3 lines !!', style: TextStyle(fontSize: 30.0), maxLines: 3, ), ), ), ), ); }}", "e": 2522, "s": 1850, "text": null }, { "code": null, "e": 2530, "s": 2522, "text": "Output:" }, { "code": null, "e": 2629, "s": 2530, "text": "If you wish to make the text fit in 2 lines instead of 3 line, make the below changes to the code:" }, { "code": null, "e": 2634, "s": 2629, "text": "Dart" }, { "code": "import 'package:auto_size_text/auto_size_text.dart';import 'package:flutter/material.dart'; void main() { runApp(App());} class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(title: Text('GeeksForGeeks'), backgroundColor: Colors.green,), body: Center( child: SizedBox( width: 200.0, height: 140.0, child: AutoSizeText( 'Hello Geeks! We will break this line into 3 lines !!', style: TextStyle(fontSize: 30.0), maxLines: 2, ), ), ), ), ); }}", "e": 3305, "s": 2634, "text": null }, { "code": null, "e": 3313, "s": 3305, "text": "Output:" }, { "code": null, "e": 3327, "s": 3313, "text": "sumitgumber28" }, { "code": null, "e": 3344, "s": 3327, "text": "akshaysingh98088" }, { "code": null, "e": 3353, "s": 3344, "text": "sooda367" }, { "code": null, "e": 3369, "s": 3353, "text": "saurabh1990aror" }, { "code": null, "e": 3379, "s": 3369, "text": "kalrap615" }, { "code": null, "e": 3395, "s": 3379, "text": "simranarora5sos" }, { "code": null, "e": 3403, "s": 3395, "text": "android" }, { "code": null, "e": 3411, "s": 3403, "text": "Flutter" }, { "code": null, "e": 3416, "s": 3411, "text": "Dart" }, { "code": null, "e": 3424, "s": 3416, "text": "Flutter" } ]
Matplotlib.axes.Axes.set_yscale() in Python
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.set_yscale() function in axes module of matplotlib library is used to set the y-axis scale. Syntax: Axes.set_xscale(self, value, **kwargs) Parameters: This method accepts the following parameters. value : This parameter is the axis scale type to apply. **kwargs: There are different keyword arguments which are accepted and its depend on the scale. Below examples illustrate the matplotlib.axes.Axes.set_yscale() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_yscale("log")ax.set_adjustable("datalim")ax.plot([1, 3, 10], [1, 9, 100], "o-", color ="green") ax.set_ylim(1e-1, 1e3)ax.set_aspect(1)fig.suptitle('matplotlib.axes.Axes.set_yscale()\ function Example\n', fontweight ="bold")plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax4 = plt.subplots() x = 10.0**np.linspace(0.0, 2.0, 15)y = x**2.0ax4.set_xscale("log", nonposx ='clip')ax4.set_yscale("log", nonposy ='clip') ax4.errorbar(x, y, xerr = 0.1 * x, yerr = 2.0 + 1.75 * y, color ="green") ax4.set_ylim(bottom = 0.1) fig.suptitle('matplotlib.axes.Axes.set_yscale() \function Example\n', fontweight ="bold") 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 ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 429, "s": 328, "text": "The Axes.set_yscale() function in axes module of matplotlib library is used to set the y-axis scale." }, { "code": null, "e": 476, "s": 429, "text": "Syntax: Axes.set_xscale(self, value, **kwargs)" }, { "code": null, "e": 534, "s": 476, "text": "Parameters: This method accepts the following parameters." }, { "code": null, "e": 590, "s": 534, "text": "value : This parameter is the axis scale type to apply." }, { "code": null, "e": 686, "s": 590, "text": "**kwargs: There are different keyword arguments which are accepted and its depend on the scale." }, { "code": null, "e": 779, "s": 686, "text": "Below examples illustrate the matplotlib.axes.Axes.set_yscale() function in matplotlib.axes:" }, { "code": null, "e": 790, "s": 779, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_yscale(\"log\")ax.set_adjustable(\"datalim\")ax.plot([1, 3, 10], [1, 9, 100], \"o-\", color =\"green\") ax.set_ylim(1e-1, 1e3)ax.set_aspect(1)fig.suptitle('matplotlib.axes.Axes.set_yscale()\\ function Example\\n', fontweight =\"bold\")plt.show()", "e": 1137, "s": 790, "text": null }, { "code": null, "e": 1145, "s": 1137, "text": "Output:" }, { "code": null, "e": 1156, "s": 1145, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt fig, ax4 = plt.subplots() x = 10.0**np.linspace(0.0, 2.0, 15)y = x**2.0ax4.set_xscale(\"log\", nonposx ='clip')ax4.set_yscale(\"log\", nonposy ='clip') ax4.errorbar(x, y, xerr = 0.1 * x, yerr = 2.0 + 1.75 * y, color =\"green\") ax4.set_ylim(bottom = 0.1) fig.suptitle('matplotlib.axes.Axes.set_yscale() \\function Example\\n', fontweight =\"bold\") plt.show()", "e": 1627, "s": 1156, "text": null }, { "code": null, "e": 1635, "s": 1627, "text": "Output:" }, { "code": null, "e": 1653, "s": 1635, "text": "Python-matplotlib" }, { "code": null, "e": 1660, "s": 1653, "text": "Python" }, { "code": null, "e": 1758, "s": 1660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1790, "s": 1758, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1817, "s": 1790, "text": "Python Classes and Objects" }, { "code": null, "e": 1838, "s": 1817, "text": "Python OOPs Concepts" }, { "code": null, "e": 1869, "s": 1838, "text": "Python | os.path.join() method" }, { "code": null, "e": 1925, "s": 1869, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1948, "s": 1925, "text": "Introduction To PYTHON" }, { "code": null, "e": 1990, "s": 1948, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2032, "s": 1990, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2071, "s": 2032, "text": "Python | datetime.timedelta() function" } ]
SweetAlert Library Introduction and Installation with the Example
07 Jan, 2022 When building JavaScript-driven websites we often have the need to provide feedback to our users to let them know if the action they have performed has been successful or not. In the early days of the web, developers used to create messages using the window.alert() function. While alert() works in practice and it’s also consistent across browsers, it’s not very flexible and, to be honest, its look and feel are terrible. Today there are several approaches adopted that range from modals to inline messages. In this article, I’ll introduce you to sweetAlert, a library that acts as a replacement for JavaScript’s alert() function. SweetAlert CDN Library: The sweetAlert is a replacement for JavaScript’s window.alert() function that shows very pretty modal windows. It’s a standalone library that has no dependencies, and it’s made from a JavaScript file plus a CSS file. Sweet Alert is used to make an alert box more attractive and easier to design. The sweet JS Provide easy methods to design and add a lot of functionality to the alert box of the website by just calling the function of sweet alert (in short SWAL()). A beautiful replacement for JavaScript confirms the message! It will replace the ugly confirmation message with a beautiful customizable and fully functional modal. Sweet Alert is a way to customize alerts in your games and websites. It allows you to change from a standard JavaScript button. We can add buttons, change the color text, and even add additional alerts that change depending on user click. We can also put icons with our alerts. We can also use JavaScript setTimeout function to set the time of alert display Installation: Using NPM: npm install sweetalert --save CDN Link: https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js Syntax: swal("add title Text","Add simple text","add icon", {Json Format To add other swal function}) Note: The swal() accept title text (it is bold and larger in font Size then simple text), simple text, and icon as default parameter You can use JSON to use Any other Function of Sweetalert. If Only one text is given inside swal() then it will be Simple text. If two text is there then first will be title text and second will be simple text The below examples illustrate the working of SweetAlert. Example 1: html <!DOCTYPE html><html><head> <title>GeeksForGeeks Sweet alert</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"> </script> </head><body> <script> swal("Here's a title", "Here's some text", "success", { button: "I am new button", }); </script></body></html> Output: Example 2: HTML <!DOCTYPE html><html><head> <title>GeeksForGeeks Sweet alert</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"> </script> </head><body> <script> swal("Are You want To Delete", { dangerMode: true, buttons: true, } ); </script></body></html> Output: Title: It Is used to write title inside the alert box if the title is given as a first parameter in Swal() then JSON attribute title will overwrite that target valueText: This Attribute Use For writing Text inside the alert box. If Swal() contains simple text outside the JSON attribute then it will overwrite those text.Icons: This Is Use for Displaying Icon. SweetAlert comes with 4 built-in icons that you can use: warningerrorsuccessinfo Title: It Is used to write title inside the alert box if the title is given as a first parameter in Swal() then JSON attribute title will overwrite that target value Text: This Attribute Use For writing Text inside the alert box. If Swal() contains simple text outside the JSON attribute then it will overwrite those text. Icons: This Is Use for Displaying Icon. SweetAlert comes with 4 built-in icons that you can use: warningerrorsuccessinfo warning error success info Example 3: But You Can Add Image Of icons by putting image address inside quote like: HTML <!DOCTYPE html><html><head> <title>GeeksForGeeks Sweet alert</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"> </script> </head><body> <script> swal("Here's a title!", "Here's some text","success",{ title:"i am New title", text:"I am New Text", icon:'https://dl.dropbox.com/s/qe98k2xvmqivxwz/google_apps.png', }); </script></body></html> Output: Button And Buttons: Button is used for creating a single button whereas buttons are used for creating more than 1 button. By default, buttons have two buttons “cancel” and “ok” with the default configuration. Example 4: You Can Add className attribute to both button and swal to change the style of button and dialogbox as shown in the figure below: HTML <!DOCTYPE html><html> <head> <title>GeeksForGeeks Sweet alert</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"> </script> <style> .buttonstyle { color: Yellow; background-color: black; } .boxstyle { background: rgba(256, 10, 20, 0.5); } </style> </head> <body> <script> swal("Here's a title", "Here's some text", "success", { className: "boxstyle", buttons: { cancel: true, New: { text: "I am new button", value: "new button data", visible: true, }, New2: { text: " styleButton", value: "new button data", visible: true, className: "buttonstyle", }, }, }); </script> </body></html> Output: Example 5: HTML <!DOCTYPE html><html> <head> <title>GeeksFor Geeks Sweet alert</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"> </script> <style> .p { background-color: red; width: 190px; margin: auto; text-align: center; font-size: 22px; } </style> </head> <body> <script> swal("Button in Danger Mode", "ESC and click outside is disable,and time=5sec", "warning", { dangerMode: true, buttons: true, closeOnClickOutside: false, timer: 5000, }); </script> </body></html> Output: content: This is used for adding any element like P element, H1 element, Button, Textarea, Input, Div, etc. The content attribute contains Two thing element names and its attribute, Attribute means inside properties of an element like inline style, width, height, placeholder, className, etc, Following Are Example Code of Input element. swal({ content: { element: "input", attributes: { placeholder: "Enter any Number", // Type can be range,can be // password and can be text type: "number", }, }, }); Creating Paragraph Element: swal({ content: { element: "p", attributes: { innerText:"hello", style:"color:blue;", className:"p", }, }, }); Example 6: Creating Paragraph Element. HTML <!DOCTYPE html><html> <head> <title>GeeksFor Geeks Sweet alert</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"> </script> <style> h1{ color: green; text-align: center; } .p { width: 100%; margin: auto; text-align: center; font-size: 22px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <script> swal({ content: { element: "p", attributes: { innerText: "A Computer Science Portal for Geeks", style: "color: black;", className: "p", }, }, }); </script> </body></html> Output: Reference: https://sweetalert.js.org/ kashishsoda varshagumber28 abhishek0719kadiyan HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Angular File Upload Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2022" }, { "code": null, "e": 661, "s": 28, "text": "When building JavaScript-driven websites we often have the need to provide feedback to our users to let them know if the action they have performed has been successful or not. In the early days of the web, developers used to create messages using the window.alert() function. While alert() works in practice and it’s also consistent across browsers, it’s not very flexible and, to be honest, its look and feel are terrible. Today there are several approaches adopted that range from modals to inline messages. In this article, I’ll introduce you to sweetAlert, a library that acts as a replacement for JavaScript’s alert() function." }, { "code": null, "e": 902, "s": 661, "text": "SweetAlert CDN Library: The sweetAlert is a replacement for JavaScript’s window.alert() function that shows very pretty modal windows. It’s a standalone library that has no dependencies, and it’s made from a JavaScript file plus a CSS file." }, { "code": null, "e": 1151, "s": 902, "text": "Sweet Alert is used to make an alert box more attractive and easier to design. The sweet JS Provide easy methods to design and add a lot of functionality to the alert box of the website by just calling the function of sweet alert (in short SWAL())." }, { "code": null, "e": 1316, "s": 1151, "text": "A beautiful replacement for JavaScript confirms the message! It will replace the ugly confirmation message with a beautiful customizable and fully functional modal." }, { "code": null, "e": 1674, "s": 1316, "text": "Sweet Alert is a way to customize alerts in your games and websites. It allows you to change from a standard JavaScript button. We can add buttons, change the color text, and even add additional alerts that change depending on user click. We can also put icons with our alerts. We can also use JavaScript setTimeout function to set the time of alert display" }, { "code": null, "e": 1688, "s": 1674, "text": "Installation:" }, { "code": null, "e": 1699, "s": 1688, "text": "Using NPM:" }, { "code": null, "e": 1729, "s": 1699, "text": "npm install sweetalert --save" }, { "code": null, "e": 1739, "s": 1729, "text": "CDN Link:" }, { "code": null, "e": 1813, "s": 1739, "text": "https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js" }, { "code": null, "e": 1821, "s": 1813, "text": "Syntax:" }, { "code": null, "e": 1922, "s": 1821, "text": "swal(\"add title Text\",\"Add simple text\",\"add icon\",\n {Json Format To add other swal function})" }, { "code": null, "e": 2265, "s": 1922, "text": "Note: The swal() accept title text (it is bold and larger in font Size then simple text), simple text, and icon as default parameter You can use JSON to use Any other Function of Sweetalert. If Only one text is given inside swal() then it will be Simple text. If two text is there then first will be title text and second will be simple text " }, { "code": null, "e": 2322, "s": 2265, "text": "The below examples illustrate the working of SweetAlert." }, { "code": null, "e": 2333, "s": 2322, "text": "Example 1:" }, { "code": null, "e": 2338, "s": 2333, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>GeeksForGeeks Sweet alert</title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js\"> </script> </head><body> <script> swal(\"Here's a title\", \"Here's some text\", \"success\", { button: \"I am new button\", }); </script></body></html>", "e": 2657, "s": 2338, "text": null }, { "code": null, "e": 2665, "s": 2657, "text": "Output:" }, { "code": null, "e": 2676, "s": 2665, "text": "Example 2:" }, { "code": null, "e": 2681, "s": 2676, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>GeeksForGeeks Sweet alert</title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js\"> </script> </head><body> <script> swal(\"Are You want To Delete\", { dangerMode: true, buttons: true, } ); </script></body></html>", "e": 2991, "s": 2681, "text": null }, { "code": null, "e": 3000, "s": 2991, "text": "Output: " }, { "code": null, "e": 3442, "s": 3000, "text": "Title: It Is used to write title inside the alert box if the title is given as a first parameter in Swal() then JSON attribute title will overwrite that target valueText: This Attribute Use For writing Text inside the alert box. If Swal() contains simple text outside the JSON attribute then it will overwrite those text.Icons: This Is Use for Displaying Icon. SweetAlert comes with 4 built-in icons that you can use: warningerrorsuccessinfo" }, { "code": null, "e": 3608, "s": 3442, "text": "Title: It Is used to write title inside the alert box if the title is given as a first parameter in Swal() then JSON attribute title will overwrite that target value" }, { "code": null, "e": 3765, "s": 3608, "text": "Text: This Attribute Use For writing Text inside the alert box. If Swal() contains simple text outside the JSON attribute then it will overwrite those text." }, { "code": null, "e": 3886, "s": 3765, "text": "Icons: This Is Use for Displaying Icon. SweetAlert comes with 4 built-in icons that you can use: warningerrorsuccessinfo" }, { "code": null, "e": 3894, "s": 3886, "text": "warning" }, { "code": null, "e": 3900, "s": 3894, "text": "error" }, { "code": null, "e": 3908, "s": 3900, "text": "success" }, { "code": null, "e": 3913, "s": 3908, "text": "info" }, { "code": null, "e": 3999, "s": 3913, "text": "Example 3: But You Can Add Image Of icons by putting image address inside quote like:" }, { "code": null, "e": 4004, "s": 3999, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>GeeksForGeeks Sweet alert</title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js\"> </script> </head><body> <script> swal(\"Here's a title!\", \"Here's some text\",\"success\",{ title:\"i am New title\", text:\"I am New Text\", icon:'https://dl.dropbox.com/s/qe98k2xvmqivxwz/google_apps.png', }); </script></body></html>", "e": 4417, "s": 4004, "text": null }, { "code": null, "e": 4425, "s": 4417, "text": "Output:" }, { "code": null, "e": 4634, "s": 4425, "text": "Button And Buttons: Button is used for creating a single button whereas buttons are used for creating more than 1 button. By default, buttons have two buttons “cancel” and “ok” with the default configuration." }, { "code": null, "e": 4775, "s": 4634, "text": "Example 4: You Can Add className attribute to both button and swal to change the style of button and dialogbox as shown in the figure below:" }, { "code": null, "e": 4780, "s": 4775, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksForGeeks Sweet alert</title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js\"> </script> <style> .buttonstyle { color: Yellow; background-color: black; } .boxstyle { background: rgba(256, 10, 20, 0.5); } </style> </head> <body> <script> swal(\"Here's a title\", \"Here's some text\", \"success\", { className: \"boxstyle\", buttons: { cancel: true, New: { text: \"I am new button\", value: \"new button data\", visible: true, }, New2: { text: \" styleButton\", value: \"new button data\", visible: true, className: \"buttonstyle\", }, }, }); </script> </body></html>", "e": 5892, "s": 4780, "text": null }, { "code": null, "e": 5900, "s": 5892, "text": "Output:" }, { "code": null, "e": 5911, "s": 5900, "text": "Example 5:" }, { "code": null, "e": 5916, "s": 5911, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksFor Geeks Sweet alert</title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js\"> </script> <style> .p { background-color: red; width: 190px; margin: auto; text-align: center; font-size: 22px; } </style> </head> <body> <script> swal(\"Button in Danger Mode\", \"ESC and click outside is disable,and time=5sec\", \"warning\", { dangerMode: true, buttons: true, closeOnClickOutside: false, timer: 5000, }); </script> </body></html>", "e": 6691, "s": 5916, "text": null }, { "code": null, "e": 6699, "s": 6691, "text": "Output:" }, { "code": null, "e": 7037, "s": 6699, "text": "content: This is used for adding any element like P element, H1 element, Button, Textarea, Input, Div, etc. The content attribute contains Two thing element names and its attribute, Attribute means inside properties of an element like inline style, width, height, placeholder, className, etc, Following Are Example Code of Input element." }, { "code": null, "e": 7245, "s": 7037, "text": "swal({\n content: {\n element: \"input\",\n attributes: {\n placeholder: \"Enter any Number\",\n // Type can be range,can be \n // password and can be text\n type: \"number\", \n },\n },\n});" }, { "code": null, "e": 7273, "s": 7245, "text": "Creating Paragraph Element:" }, { "code": null, "e": 7420, "s": 7273, "text": "swal({\n content: {\n element: \"p\",\n attributes: {\n innerText:\"hello\",\n style:\"color:blue;\",\n className:\"p\",\n \n },\n },\n});" }, { "code": null, "e": 7459, "s": 7420, "text": "Example 6: Creating Paragraph Element." }, { "code": null, "e": 7464, "s": 7459, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>GeeksFor Geeks Sweet alert</title> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js\"> </script> <style> h1{ color: green; text-align: center; } .p { width: 100%; margin: auto; text-align: center; font-size: 22px; } </style> </head> <body> <h1>GeeksforGeeks</h1> <script> swal({ content: { element: \"p\", attributes: { innerText: \"A Computer Science Portal for Geeks\", style: \"color: black;\", className: \"p\", }, }, }); </script> </body></html>", "e": 8365, "s": 7464, "text": null }, { "code": null, "e": 8373, "s": 8365, "text": "Output:" }, { "code": null, "e": 8411, "s": 8373, "text": "Reference: https://sweetalert.js.org/" }, { "code": null, "e": 8423, "s": 8411, "text": "kashishsoda" }, { "code": null, "e": 8438, "s": 8423, "text": "varshagumber28" }, { "code": null, "e": 8458, "s": 8438, "text": "abhishek0719kadiyan" }, { "code": null, "e": 8463, "s": 8458, "text": "HTML" }, { "code": null, "e": 8474, "s": 8463, "text": "JavaScript" }, { "code": null, "e": 8491, "s": 8474, "text": "Web Technologies" }, { "code": null, "e": 8496, "s": 8491, "text": "HTML" }, { "code": null, "e": 8594, "s": 8496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8618, "s": 8594, "text": "REST API (Introduction)" }, { "code": null, "e": 8657, "s": 8618, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 8696, "s": 8657, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 8733, "s": 8696, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 8753, "s": 8733, "text": "Angular File Upload" }, { "code": null, "e": 8814, "s": 8753, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8886, "s": 8814, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 8926, "s": 8886, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 8978, "s": 8926, "text": "How to append HTML code to a div using JavaScript ?" } ]
Given number of matches played, find number of teams in tournament
22 Jun, 2022 Given an integer M which is the number of matches played in a tournament and each participating team has played a match with all the other teams. The task is to find how many teams are there in the tournament.Examples: Input: M = 3 Output: 3 If there are 3 teams A, B and C then A will play a match with B and C B will play a match with C (B has already played a match with A) C has already played matches with team A and B Total matches played are 3Input: M = 45 Output: 10 Approach: Since each match is played between two teams. So this problem is similar to selecting 2 objects from Given N objects. Therefore the total number of matches will be C(N, 2), where N is the number of participating teams. Therefore, M = C(N, 2) M = (N * (N – 1)) / 2 N2 – N – 2 * M = 0 This is a quadratic equation of type ax2 + bx + c = 0. Here a = 1, b = -1, c = 2 * M. Therefore, applying formula x = (-b + sqrt(b2 – 4ac)) / 2a and x = (-b – sqrt(b2 – 4ac)) / 2a N = [(-1 * -1) + sqrt((-1 * -1) – (4 * 1 * (-2 * M)))] / 2 N = (1 + sqrt(1 + (8 * M))) / 2 and N = (1 – sqrt(1 + (8 * M))) / 2 After solving the above two equations, we’ll get two values of N. One value will be positive and one negative. Ignore the negative value. Therefore, the number of teams will be the positive root of the above equation.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <cmath>#include <iostream>using namespace std; // Function to return the number of teamsint number_of_teams(int M){ // To store both roots of the equation int N1, N2, sqr; // sqrt(b^2 - 4ac) sqr = sqrt(1 + (8 * M)); // First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2; // Return the positive root if (N1 > 0) return N1; return N2;} // Driver codeint main(){ int M = 45; cout << number_of_teams(M); return 0;} // Java implementation of the approachimport java.io.*; class GFG{ // Function to return the number of teamsstatic int number_of_teams(int M){ // To store both roots of the equation int N1, N2, sqr; // sqrt(b^2 - 4ac) sqr = (int)Math.sqrt(1 + (8 * M)); // First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2; // Return the positive root if (N1 > 0) return N1; return N2;} // Driver code public static void main (String[] args) { int M = 45; System.out.println( number_of_teams(M)); }} // this code is contributed by vt_m.. # Python implementation of the approachimport math # Function to return the number of teamsdef number_of_teams(M): # To store both roots of the equation N1, N2, sqr = 0,0,0 # sqrt(b^2 - 4ac) sqr = math.sqrt(1 + (8 * M)) # First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2 # Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2 # Return the positive root if (N1 > 0): return int(N1) return int(N2) # Driver codedef main(): M = 45 print(number_of_teams(M))if __name__ == '__main__': main() # This code has been contributed by 29AjayKumar // C# implementation of the approachusing System; class GFG{ // Function to return the number of teams static int number_of_teams(int M) { // To store both roots of the equation int N1, N2, sqr; // sqrt(b^2 - 4ac) sqr = (int)Math.Sqrt(1 + (8 * M)); // First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2; // Return the positive root if (N1 > 0) return N1; return N2; } // Driver code public static void Main() { int M = 45; Console.WriteLine( number_of_teams(M)); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Function to return the number of teamsfunction number_of_teams($M){ // To store both roots of the equation // sqrt(b^2 - 4ac) $sqr = sqrt(1 + (8 * $M)); // First root (-b + sqrt(b^2 - 4ac)) / 2a $N1 = (1 + $sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a $N2 = (1 - $sqr) / 2; // Return the positive root if ($N1 > 0) return $N1; return $N2;} // Driver code$M = 45;echo number_of_teams($M); // This code is contributed// by chandan_jnu?> <script>// javascript implementation of the approach // Function to return the number of teams function number_of_teams(M) { // To store both roots of the equation var N1, N2, sqr; // sqrt(b^2 - 4ac) sqr = parseInt( Math.sqrt(1 + (8 * M))); // First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2; // Return the positive root if (N1 > 0) return N1; return N2; } // Driver code var M = 45; document.write(number_of_teams(M)); // This code contributed by gauravrajput1</script> 10 Time Complexity: O(logn)Auxiliary Space: O(1) vt_m ankthon 29AjayKumar Chandan_Kumar GauravRajput1 subham348 Combinatorial Mathematical School Programming Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Find the K-th Permutation Sequence of first N natural numbers Count Derangements (Permutation such that no element appears in its original position) Print all possible strings of length k that can be formed from a set of n characters Permutations of a given string using STL Program for Fibonacci numbers Set in C++ Standard Template Library (STL) C++ Data Types Merge two sorted arrays Coin Change | DP-7
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 249, "s": 28, "text": "Given an integer M which is the number of matches played in a tournament and each participating team has played a match with all the other teams. The task is to find how many teams are there in the tournament.Examples: " }, { "code": null, "e": 507, "s": 249, "text": "Input: M = 3 Output: 3 If there are 3 teams A, B and C then A will play a match with B and C B will play a match with C (B has already played a match with A) C has already played matches with team A and B Total matches played are 3Input: M = 45 Output: 10 " }, { "code": null, "e": 751, "s": 509, "text": "Approach: Since each match is played between two teams. So this problem is similar to selecting 2 objects from Given N objects. Therefore the total number of matches will be C(N, 2), where N is the number of participating teams. Therefore, " }, { "code": null, "e": 1113, "s": 751, "text": "M = C(N, 2) M = (N * (N – 1)) / 2 N2 – N – 2 * M = 0 This is a quadratic equation of type ax2 + bx + c = 0. Here a = 1, b = -1, c = 2 * M. Therefore, applying formula x = (-b + sqrt(b2 – 4ac)) / 2a and x = (-b – sqrt(b2 – 4ac)) / 2a N = [(-1 * -1) + sqrt((-1 * -1) – (4 * 1 * (-2 * M)))] / 2 N = (1 + sqrt(1 + (8 * M))) / 2 and N = (1 – sqrt(1 + (8 * M))) / 2 " }, { "code": null, "e": 1383, "s": 1113, "text": "After solving the above two equations, we’ll get two values of N. One value will be positive and one negative. Ignore the negative value. Therefore, the number of teams will be the positive root of the above equation.Below is the implementation of the above approach: " }, { "code": null, "e": 1387, "s": 1383, "text": "C++" }, { "code": null, "e": 1392, "s": 1387, "text": "Java" }, { "code": null, "e": 1400, "s": 1392, "text": "Python3" }, { "code": null, "e": 1403, "s": 1400, "text": "C#" }, { "code": null, "e": 1407, "s": 1403, "text": "PHP" }, { "code": null, "e": 1418, "s": 1407, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <cmath>#include <iostream>using namespace std; // Function to return the number of teamsint number_of_teams(int M){ // To store both roots of the equation int N1, N2, sqr; // sqrt(b^2 - 4ac) sqr = sqrt(1 + (8 * M)); // First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2; // Return the positive root if (N1 > 0) return N1; return N2;} // Driver codeint main(){ int M = 45; cout << number_of_teams(M); return 0;}", "e": 1999, "s": 1418, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function to return the number of teamsstatic int number_of_teams(int M){ // To store both roots of the equation int N1, N2, sqr; // sqrt(b^2 - 4ac) sqr = (int)Math.sqrt(1 + (8 * M)); // First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2; // Return the positive root if (N1 > 0) return N1; return N2;} // Driver code public static void main (String[] args) { int M = 45; System.out.println( number_of_teams(M)); }} // this code is contributed by vt_m..", "e": 2662, "s": 1999, "text": null }, { "code": "# Python implementation of the approachimport math # Function to return the number of teamsdef number_of_teams(M): # To store both roots of the equation N1, N2, sqr = 0,0,0 # sqrt(b^2 - 4ac) sqr = math.sqrt(1 + (8 * M)) # First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2 # Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2 # Return the positive root if (N1 > 0): return int(N1) return int(N2) # Driver codedef main(): M = 45 print(number_of_teams(M))if __name__ == '__main__': main() # This code has been contributed by 29AjayKumar", "e": 3274, "s": 2662, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the number of teams static int number_of_teams(int M) { // To store both roots of the equation int N1, N2, sqr; // sqrt(b^2 - 4ac) sqr = (int)Math.Sqrt(1 + (8 * M)); // First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2; // Return the positive root if (N1 > 0) return N1; return N2; } // Driver code public static void Main() { int M = 45; Console.WriteLine( number_of_teams(M)); }} // This code is contributed by Ryuga", "e": 3999, "s": 3274, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the number of teamsfunction number_of_teams($M){ // To store both roots of the equation // sqrt(b^2 - 4ac) $sqr = sqrt(1 + (8 * $M)); // First root (-b + sqrt(b^2 - 4ac)) / 2a $N1 = (1 + $sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a $N2 = (1 - $sqr) / 2; // Return the positive root if ($N1 > 0) return $N1; return $N2;} // Driver code$M = 45;echo number_of_teams($M); // This code is contributed// by chandan_jnu?>", "e": 4529, "s": 3999, "text": null }, { "code": "<script>// javascript implementation of the approach // Function to return the number of teams function number_of_teams(M) { // To store both roots of the equation var N1, N2, sqr; // sqrt(b^2 - 4ac) sqr = parseInt( Math.sqrt(1 + (8 * M))); // First root (-b + sqrt(b^2 - 4ac)) / 2a N1 = (1 + sqr) / 2; // Second root (-b - sqrt(b^2 - 4ac)) / 2a N2 = (1 - sqr) / 2; // Return the positive root if (N1 > 0) return N1; return N2; } // Driver code var M = 45; document.write(number_of_teams(M)); // This code contributed by gauravrajput1</script>", "e": 5198, "s": 4529, "text": null }, { "code": null, "e": 5201, "s": 5198, "text": "10" }, { "code": null, "e": 5251, "s": 5203, "text": " Time Complexity: O(logn)Auxiliary Space: O(1) " }, { "code": null, "e": 5256, "s": 5251, "text": "vt_m" }, { "code": null, "e": 5264, "s": 5256, "text": "ankthon" }, { "code": null, "e": 5276, "s": 5264, "text": "29AjayKumar" }, { "code": null, "e": 5290, "s": 5276, "text": "Chandan_Kumar" }, { "code": null, "e": 5304, "s": 5290, "text": "GauravRajput1" }, { "code": null, "e": 5314, "s": 5304, "text": "subham348" }, { "code": null, "e": 5328, "s": 5314, "text": "Combinatorial" }, { "code": null, "e": 5341, "s": 5328, "text": "Mathematical" }, { "code": null, "e": 5360, "s": 5341, "text": "School Programming" }, { "code": null, "e": 5373, "s": 5360, "text": "Mathematical" }, { "code": null, "e": 5387, "s": 5373, "text": "Combinatorial" }, { "code": null, "e": 5485, "s": 5387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5522, "s": 5485, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 5584, "s": 5522, "text": "Find the K-th Permutation Sequence of first N natural numbers" }, { "code": null, "e": 5671, "s": 5584, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 5756, "s": 5671, "text": "Print all possible strings of length k that can be formed from a set of n characters" }, { "code": null, "e": 5797, "s": 5756, "text": "Permutations of a given string using STL" }, { "code": null, "e": 5827, "s": 5797, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 5870, "s": 5827, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5885, "s": 5870, "text": "C++ Data Types" }, { "code": null, "e": 5909, "s": 5885, "text": "Merge two sorted arrays" } ]
pkg-config - Unix, Linux Command
pkg-config [--modversion] [--help] [--print-errors] [--silence-errors] [--cflags] [--libs] [--libs-only-L] [--libs-only-l] [--cflags-only-I] [--variable=VARIABLENAME] [--define-variable=VARIABLENAME=VARIABLEVALUE] [--uninstalled] [--exists] [--atleast-version=VERSION] [--exact-version=VERSION] [--max-version=VERSION] [LIBRARIES...] The pkg-config program is used to retrieve information about installed libraries in the system. It is typically used to compile and link against one or more libraries. Here is a typical usage scenario in a Makefile: program: program.c cc program.c ‘pkg-config --cflags --libs gnomeui‘ pkg-config retrieves information about packages from special metadata files. These files are named after the package, with the extension .pc. By default, pkg-config looks in the directory prefix/lib/pkgconfig for these files; it will also look in the colon-separated (on Windows, semicolon-separated) list of directories specified by the PKG_CONFIG_PATH environment variable. The package name specified on the pkg-config command line is defined to be the name of the metadata file, minus the .pc extension. If a library can install multiple versions simultaneously, it must give each version its own name (for example, GTK 1.2 might have the package name "gtk+" while GTK 2.0 has "gtk+-2.0"). $ pkg-config --variable=prefix glib-2.0 /usr/ $ pkg-config --print-errors --define-variable=prefix=/foo \ --variable=prefix glib-2.0 /foo Rather than using the version-test options, you can simply give a version constraint after each package name, for example: $ pkg-config --exists ’glib-2.0 >= 1.3.4 libxml = 1.8.3’ In addition to the PKG_CONFIG_PATH environment variable, the Registry keys HKEY_CURRENT_USER\Software\pkgconfig\PKG_CONFIG_PATH and HKEY_LOCAL_MACHINE\Software\pkgconfig\PKG_CONFIG_PATH can be used to specify directories to search for .pc files. Each (string) value in these keys is treated as a directory where to look for .pc files. The macro PKG_CHECK_MODULES can be used in configure.ac to check whether modules exist. A typical usage would be: PKG_CHECK_MODULES([MYSTUFF], [gtk+-2.0 >= 1.3.5 libxml = 1.8.4]) This would result in MYSTUFF_LIBS and MYSTUFF_CFLAGS substitution variables, set to the libs and cflags for the given module list. If a module is missing or has the wrong version, by default configure will abort with a message. To replace the default action, specify an ACTION-IF-NOT-FOUND. PKG_CHECK_MODULES will not print any error messages if you specify your own ACTION-IF-NOT-FOUND. However, it will set the variable MYSTUFF_PKG_ERRORS, which you can use to display what went wrong. Note that if there is a possibility the first call to PKG_CHECK_MODULES might not happen, you should be sure to include an explicit call to PKG_PROG_PKG_CONFIG in your configure.ac PKG_PROG_PKG_CONFIG([MIN-VERSION]) Defines the PKG_CONFIG variable to the best pkg-config available, useful if you need pkg-config but don’t want to use PKG_CHECK_MODULES. PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) Check to see whether a particular set of modules exists. Similar to PKG_CHECK_MODULES(), but does not set variables or print errors. Similar to PKG_CHECK_MODULES, make sure that the first instance of this or PKG_CHECK_MODULES is called, or make sure to call PKG_CHECK_EXISTS manually Here is an example file: # This is a comment prefix=/home/hp/unst # this defines a variable exec_prefix=${prefix} # defining another variable in terms of the first libdir=${exec_prefix}/lib includedir=${prefix}/include Name: GObject # human-readable name Description: Object/type system for GLib # human-readable description Version: 1.3.1 URL: http://www.gtk.org Requires: glib-2.0 = 1.3.1 Conflicts: foobar <= 4.5 Libs: -L${libdir} -lgobject-1.3 Libs.private: -lm Cflags: -I${includedir}/glib-2.0 -I${libdir}/glib/include Name: GObject # human-readable name Description: Object/type system for GLib # human-readable description Version: 1.3.1 URL: http://www.gtk.org Requires: glib-2.0 = 1.3.1 Conflicts: foobar <= 4.5 Libs: -L${libdir} -lgobject-1.3 Libs.private: -lm Cflags: -I${includedir}/glib-2.0 -I${libdir}/glib/include You would normally generate the file using configure, of course, so that the prefix, etc. are set to the proper values. Files have two kinds of line: keyword lines start with a keyword plus a colon, and variable definitions start with an alphanumeric string plus an equals sign. Keywords are defined in advance and have special meaning to pkg-config; variables do not, you can have any variables that you wish (however, users may expect to retrieve the usual directory name variables). Note that variable references are written "${foo}"; you can escape literal "${" as "$${". pkg-config was written by James Henstridge, rewritten by Martijn van Beers, and rewritten again by Havoc Pennington. Tim Janik, Owen Taylor, and Raja Harinath submitted suggestions and some code. gnome-config was written by Miguel de Icaza, Raja Harinath and various hackers in the GNOME team. It was inspired by Owen Taylor’s gtk-config program. pkg-config does not handle mixing of parameters with and without = well. Stick with one.
[ { "code": null, "e": 11051, "s": 10715, "text": "\npkg-config [--modversion] [--help] [--print-errors] [--silence-errors]\n[--cflags] [--libs] [--libs-only-L]\n[--libs-only-l] [--cflags-only-I]\n[--variable=VARIABLENAME]\n[--define-variable=VARIABLENAME=VARIABLEVALUE]\n[--uninstalled]\n[--exists] [--atleast-version=VERSION] [--exact-version=VERSION]\n[--max-version=VERSION] [LIBRARIES...]\n" }, { "code": null, "e": 11271, "s": 11051, "text": "\nThe pkg-config program is used to retrieve information about\ninstalled libraries in the system. It is typically used to compile\nand link against one or more libraries. Here is a typical usage\nscenario in a Makefile:\n" }, { "code": null, "e": 11351, "s": 11273, "text": "program: program.c\n cc program.c ‘pkg-config --cflags --libs gnomeui‘\n" }, { "code": null, "e": 11733, "s": 11355, "text": "\npkg-config retrieves information about packages from\nspecial metadata files. These files are named after the package,\nwith the extension .pc. By default, pkg-config looks in\nthe directory prefix/lib/pkgconfig for these files; it will also\nlook in the colon-separated (on Windows, semicolon-separated)\nlist of directories specified by the\nPKG_CONFIG_PATH environment variable.\n" }, { "code": null, "e": 12054, "s": 11735, "text": "\nThe package name specified on the pkg-config command line is\ndefined to be the name of the metadata file, minus the .pc\nextension. If a library can install multiple versions simultaneously,\nit must give each version its own name (for example, GTK 1.2 might\nhave the package name \"gtk+\" while GTK 2.0 has \"gtk+-2.0\").\n" }, { "code": null, "e": 12117, "s": 12066, "text": " $ pkg-config --variable=prefix glib-2.0\n /usr/\n" }, { "code": null, "e": 12229, "s": 12117, "text": " $ pkg-config --print-errors --define-variable=prefix=/foo \\\n --variable=prefix glib-2.0\n /foo\n" }, { "code": null, "e": 12358, "s": 12233, "text": "\nRather than using the version-test options, you can simply give a version\nconstraint after each package name, for example:\n" }, { "code": null, "e": 12418, "s": 12358, "text": " $ pkg-config --exists ’glib-2.0 >= 1.3.4 libxml = 1.8.3’\n" }, { "code": null, "e": 12783, "s": 12444, "text": "\nIn addition to the PKG_CONFIG_PATH environment variable, the\nRegistry keys\n\nHKEY_CURRENT_USER\\Software\\pkgconfig\\PKG_CONFIG_PATH and\n\nHKEY_LOCAL_MACHINE\\Software\\pkgconfig\\PKG_CONFIG_PATH can be\nused to specify directories to search for .pc files. Each (string)\nvalue in these keys is treated as a directory where to look for .pc\nfiles.\n" }, { "code": null, "e": 12903, "s": 12787, "text": "\nThe macro PKG_CHECK_MODULES can be used in configure.ac to\ncheck whether modules exist. A typical usage would be:\n" }, { "code": null, "e": 12970, "s": 12903, "text": " PKG_CHECK_MODULES([MYSTUFF], [gtk+-2.0 >= 1.3.5 libxml = 1.8.4])\n" }, { "code": null, "e": 13460, "s": 12970, "text": "\nThis would result in MYSTUFF_LIBS and MYSTUFF_CFLAGS substitution\nvariables, set to the libs and cflags for the given module list.\nIf a module is missing or has the wrong version, by default configure\nwill abort with a message. To replace the default action,\nspecify an ACTION-IF-NOT-FOUND. PKG_CHECK_MODULES will not print any\nerror messages if you specify your own ACTION-IF-NOT-FOUND.\nHowever, it will set the variable MYSTUFF_PKG_ERRORS, which you can\nuse to display what went wrong.\n" }, { "code": null, "e": 13643, "s": 13460, "text": "\nNote that if there is a possibility the first call to\nPKG_CHECK_MODULES might not happen, you should be sure to include an\nexplicit call to PKG_PROG_PKG_CONFIG in your configure.ac\n" }, { "code": null, "e": 13680, "s": 13643, "text": "\nPKG_PROG_PKG_CONFIG([MIN-VERSION]) " }, { "code": null, "e": 13819, "s": 13680, "text": "\nDefines the PKG_CONFIG variable to the best pkg-config available,\nuseful if you need pkg-config but don’t want to use PKG_CHECK_MODULES.\n" }, { "code": null, "e": 13889, "s": 13819, "text": "\nPKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) " }, { "code": null, "e": 14025, "s": 13889, "text": "\nCheck to see whether a particular set of modules exists. Similar\nto PKG_CHECK_MODULES(), but does not set variables or print errors.\n" }, { "code": null, "e": 14178, "s": 14025, "text": "\nSimilar to PKG_CHECK_MODULES, make sure that the first instance of\nthis or PKG_CHECK_MODULES is called, or make sure to call\nPKG_CHECK_EXISTS manually\n" }, { "code": null, "e": 14209, "s": 14182, "text": "\nHere is an example file:\n" }, { "code": null, "e": 14740, "s": 14209, "text": "# This is a comment\nprefix=/home/hp/unst # this defines a variable\nexec_prefix=${prefix} # defining another variable in terms of the first\nlibdir=${exec_prefix}/lib\nincludedir=${prefix}/include\n\nName: GObject # human-readable name\nDescription: Object/type system for GLib # human-readable description\nVersion: 1.3.1\nURL: http://www.gtk.org\nRequires: glib-2.0 = 1.3.1\nConflicts: foobar <= 4.5\nLibs: -L${libdir} -lgobject-1.3\nLibs.private: -lm\nCflags: -I${includedir}/glib-2.0 -I${libdir}/glib/include\n" }, { "code": null, "e": 15074, "s": 14740, "text": "\nName: GObject # human-readable name\nDescription: Object/type system for GLib # human-readable description\nVersion: 1.3.1\nURL: http://www.gtk.org\nRequires: glib-2.0 = 1.3.1\nConflicts: foobar <= 4.5\nLibs: -L${libdir} -lgobject-1.3\nLibs.private: -lm\nCflags: -I${includedir}/glib-2.0 -I${libdir}/glib/include\n" }, { "code": null, "e": 15198, "s": 15076, "text": "\nYou would normally generate the file using configure, of course, so\nthat the prefix, etc. are set to the proper values.\n" }, { "code": null, "e": 15568, "s": 15200, "text": "\nFiles have two kinds of line: keyword lines start with a keyword plus\na colon, and variable definitions start with an alphanumeric string\nplus an equals sign. Keywords are defined in advance and have special\nmeaning to pkg-config; variables do not, you can have any\nvariables that you wish (however, users may expect to retrieve the\nusual directory name variables).\n" }, { "code": null, "e": 15662, "s": 15570, "text": "\nNote that variable references are written \"${foo}\"; you can escape\nliteral \"${\" as \"$${\".\n" }, { "code": null, "e": 16020, "s": 15670, "text": "\npkg-config was written by James Henstridge, rewritten by Martijn\nvan Beers, and rewritten again by Havoc Pennington. Tim Janik, Owen\nTaylor, and Raja Harinath submitted suggestions and some code.\ngnome-config was written by Miguel de Icaza, Raja Harinath and\nvarious hackers in the GNOME team. It was inspired by Owen Taylor’s\ngtk-config program.\n" } ]
Java String length() Method with Examples
22 Dec, 2021 Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well. The String class of Java comprises a lot of methods to execute various operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring() etc. Out of these methods, we will be focusing on the length() method. The length or size of a string means the total number of characters present in it. For Example: The string “Geeks For Geeks” has 15 characters (including spaces also). The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays. The length() method can also be used for StringBuilder and StringBuffer classes. The length() method is a public member method. Any object of the String class, StringBuilder class, and StringBuffer class can access the length() method using the . (dot) operator. Method Signature: The method signature of the length() method is as follows – public int length() Return Type: The return type of the length() method is int. Below are the examples of how to get the length of String in Java using the length() method: Example 1: Java program to demonstrate how to get the length of String in Java using the length() method Java // Java program to illustrate// how to get the length of String// in Java using length() method public class Test { public static void main(String[] args) { // Here str is a string object String str = "GeeksforGeeks"; System.out.println( "The size of " + "the String is " + str.length()); }} The size of the String is 13 Example 2: Java program to illustrate how to check whether the length of two strings is equal or not using the length() method. Java // Java program to illustrate how to check// whether the length of two strings is// equal or not using the length() method. import java.io.*; class GFG { public static void main(String[] args) { String s1 = "abc"; String s2 = "xyz"; // storing the length of both the // strings in int variables int len1 = s1.length(); int len2 = s2.length(); // checking whether the length of // the strings is equal or not if (len1 == len2) { System.out.println( "The length of both the strings are equal and is " + len1); } else { System.out.println( "The length of both the strings are not equal"); } }} The length of both the strings are equal and is 3 nishkarshgandhi Java-String-Programs Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Dec, 2021" }, { "code": null, "e": 271, "s": 53, "text": "Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well. " }, { "code": null, "e": 530, "s": 271, "text": "The String class of Java comprises a lot of methods to execute various operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring() etc. Out of these methods, we will be focusing on the length() method. " }, { "code": null, "e": 614, "s": 530, "text": "The length or size of a string means the total number of characters present in it. " }, { "code": null, "e": 699, "s": 614, "text": "For Example: The string “Geeks For Geeks” has 15 characters (including spaces also)." }, { "code": null, "e": 926, "s": 699, "text": "The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays. " }, { "code": null, "e": 1189, "s": 926, "text": "The length() method can also be used for StringBuilder and StringBuffer classes. The length() method is a public member method. Any object of the String class, StringBuilder class, and StringBuffer class can access the length() method using the . (dot) operator." }, { "code": null, "e": 1267, "s": 1189, "text": "Method Signature: The method signature of the length() method is as follows –" }, { "code": null, "e": 1289, "s": 1267, "text": "public int length() " }, { "code": null, "e": 1349, "s": 1289, "text": "Return Type: The return type of the length() method is int." }, { "code": null, "e": 1442, "s": 1349, "text": "Below are the examples of how to get the length of String in Java using the length() method:" }, { "code": null, "e": 1547, "s": 1442, "text": "Example 1: Java program to demonstrate how to get the length of String in Java using the length() method" }, { "code": null, "e": 1552, "s": 1547, "text": "Java" }, { "code": "// Java program to illustrate// how to get the length of String// in Java using length() method public class Test { public static void main(String[] args) { // Here str is a string object String str = \"GeeksforGeeks\"; System.out.println( \"The size of \" + \"the String is \" + str.length()); }}", "e": 1910, "s": 1552, "text": null }, { "code": null, "e": 1939, "s": 1910, "text": "The size of the String is 13" }, { "code": null, "e": 2067, "s": 1939, "text": "Example 2: Java program to illustrate how to check whether the length of two strings is equal or not using the length() method." }, { "code": null, "e": 2072, "s": 2067, "text": "Java" }, { "code": "// Java program to illustrate how to check// whether the length of two strings is// equal or not using the length() method. import java.io.*; class GFG { public static void main(String[] args) { String s1 = \"abc\"; String s2 = \"xyz\"; // storing the length of both the // strings in int variables int len1 = s1.length(); int len2 = s2.length(); // checking whether the length of // the strings is equal or not if (len1 == len2) { System.out.println( \"The length of both the strings are equal and is \" + len1); } else { System.out.println( \"The length of both the strings are not equal\"); } }}", "e": 2841, "s": 2072, "text": null }, { "code": null, "e": 2891, "s": 2841, "text": "The length of both the strings are equal and is 3" }, { "code": null, "e": 2907, "s": 2891, "text": "nishkarshgandhi" }, { "code": null, "e": 2928, "s": 2907, "text": "Java-String-Programs" }, { "code": null, "e": 2933, "s": 2928, "text": "Java" }, { "code": null, "e": 2938, "s": 2933, "text": "Java" }, { "code": null, "e": 3036, "s": 2938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3087, "s": 3036, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3118, "s": 3087, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3137, "s": 3118, "text": "Interfaces in Java" }, { "code": null, "e": 3167, "s": 3137, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3182, "s": 3167, "text": "Stream In Java" }, { "code": null, "e": 3200, "s": 3182, "text": "ArrayList in Java" }, { "code": null, "e": 3220, "s": 3200, "text": "Collections in Java" }, { "code": null, "e": 3244, "s": 3220, "text": "Singleton Class in Java" }, { "code": null, "e": 3276, "s": 3244, "text": "Multidimensional Arrays in Java" } ]
How to shuffle a dataframe in R by rows
14 Sep, 2021 In this article, we will discuss how to shuffle a dataframe by rows in the R programming language. Shuffling means reordering or rearranging the data. We can shuffle the rows in the dataframe by using sample() function. By providing indexing to the dataframe the required task can be easily achieved. Syntax: dataframe[sample(1:nrow(dataframe)), ] Where. dataframe is the input dataframe sample() function is used to shuffle the rows that takes a parameter with a function called nrow() with a slice operator to get all rows shuffled. nrow() is sued to get all rows by taking the input parameter as a dataframe Example: R program to create a dataframe with 3 columns and 6 rows and shuffle the dataframe by rows R # create a dataframe of students with id,name and marksdata=data.frame(id=c(1,2,3,4,5,6), name=c("sravan","bobby","ojaswi","gnanesh", "rohith","satwik"), marks=c(89,90,98,78,98,78)) # display dataframeprint(data)print("_______________________________________________________") # shuffle the dataframe by rowsshuffled_data= data[sample(1:nrow(data)), ] # displayprint(shuffled_data) Output: Example: R program to create a student dataframe with 2 columns and 3 rows R # create a dataframe of students with id,namedata = data.frame(id=c(1, 2, 3), name=c( "sravan", "bobby", "ojaswi")) # display dataframeprint(data)print("_______________________________________________________") # shuffle the dataframe by rowsshuffled_data = data[sample(1:nrow(data)), ] # displayprint(shuffled_data) 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 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? How to filter R DataFrame by values in a column? 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": "\n14 Sep, 2021" }, { "code": null, "e": 127, "s": 28, "text": "In this article, we will discuss how to shuffle a dataframe by rows in the R programming language." }, { "code": null, "e": 329, "s": 127, "text": "Shuffling means reordering or rearranging the data. We can shuffle the rows in the dataframe by using sample() function. By providing indexing to the dataframe the required task can be easily achieved." }, { "code": null, "e": 337, "s": 329, "text": "Syntax:" }, { "code": null, "e": 377, "s": 337, "text": " dataframe[sample(1:nrow(dataframe)), ]" }, { "code": null, "e": 384, "s": 377, "text": "Where." }, { "code": null, "e": 417, "s": 384, "text": "dataframe is the input dataframe" }, { "code": null, "e": 564, "s": 417, "text": "sample() function is used to shuffle the rows that takes a parameter with a function called nrow() with a slice operator to get all rows shuffled." }, { "code": null, "e": 640, "s": 564, "text": "nrow() is sued to get all rows by taking the input parameter as a dataframe" }, { "code": null, "e": 741, "s": 640, "text": "Example: R program to create a dataframe with 3 columns and 6 rows and shuffle the dataframe by rows" }, { "code": null, "e": 743, "s": 741, "text": "R" }, { "code": "# create a dataframe of students with id,name and marksdata=data.frame(id=c(1,2,3,4,5,6), name=c(\"sravan\",\"bobby\",\"ojaswi\",\"gnanesh\", \"rohith\",\"satwik\"), marks=c(89,90,98,78,98,78)) # display dataframeprint(data)print(\"_______________________________________________________\") # shuffle the dataframe by rowsshuffled_data= data[sample(1:nrow(data)), ] # displayprint(shuffled_data)", "e": 1180, "s": 743, "text": null }, { "code": null, "e": 1188, "s": 1180, "text": "Output:" }, { "code": null, "e": 1263, "s": 1188, "text": "Example: R program to create a student dataframe with 2 columns and 3 rows" }, { "code": null, "e": 1265, "s": 1263, "text": "R" }, { "code": "# create a dataframe of students with id,namedata = data.frame(id=c(1, 2, 3), name=c( \"sravan\", \"bobby\", \"ojaswi\")) # display dataframeprint(data)print(\"_______________________________________________________\") # shuffle the dataframe by rowsshuffled_data = data[sample(1:nrow(data)), ] # displayprint(shuffled_data)", "e": 1586, "s": 1265, "text": null }, { "code": null, "e": 1594, "s": 1586, "text": "Output:" }, { "code": null, "e": 1601, "s": 1594, "text": "Picked" }, { "code": null, "e": 1622, "s": 1601, "text": "R DataFrame-Programs" }, { "code": null, "e": 1634, "s": 1622, "text": "R-DataFrame" }, { "code": null, "e": 1645, "s": 1634, "text": "R Language" }, { "code": null, "e": 1656, "s": 1645, "text": "R Programs" }, { "code": null, "e": 1754, "s": 1656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1806, "s": 1754, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1864, "s": 1806, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1899, "s": 1864, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1937, "s": 1899, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1986, "s": 1937, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2044, "s": 1986, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2093, "s": 2044, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2136, "s": 2093, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2174, "s": 2136, "text": "Merge DataFrames by Column Names in R" } ]
Sopra Steria Interview Experience
21 May, 2019 Today, I was called for interview in Sopra Steria. Approximate 100 persons were present during the interview process. First round as technical test which consists of 2 complex questions from hackersearth websites. Though I failed in first round itself. One question I tries to solve and I solved that 80% but could not make to 2nd round. Question which I attempted is given below along with solution so that you can post and anybody can get help. Q. 1 You have to take input from input device with the below sysntax : Line 1 : T No of test cases to be checked. Line 2 : Array Count. Line 3 : No of elements of the array. Line 4 : Kth largest element to be found. If not found return -1. Line 2, 3 and 4 will get repeated accordingly what we have entered in line 1. Rule : We need to find the differences of ant 2 numbers, if it is not present then we should add this to given array. So we would have all numbers difference present in array in last. For Example : INPUT :151 3 5 6 72112 Input : Line 1 is : we want to pass 2 test cases.Line 2 : Array size of First Array.Line 3 : Array Elements separated by SPACELine 4 : Need to find out 2nd Largest elements.Line 5 : Array Size of Second array for test case 2.Line 6 : Array ElementsLine 7 : 2nd largest elements to be found Output :6-1 Solutions : package soptasteria; import java.io.IOException;import java.util.Arrays;import java.util.Scanner; public class Test { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int testCasesCount = sc.nextInt(); int[] result = new int[testCasesCount]; for (int i = 0; i < testCasesCount; i++) { int arraySize = sc.nextInt(); // System.err.println("Enter arr element after arr size"); // System.err.println("Array Entered : "+sc.nextLine()); sc.nextLine(); String[] strArr = sc.nextLine().split(" "); int[] array = makeArrayOfInteger(strArr); // System.out.println("Printing integer array"); int kth = sc.nextInt(); // System.out.println("Array Entered : "); printArray(array, arraySize); result[i] = goForBusiness(array, arraySize, kth); // System.out.println("Result : "+result[i]); } System.out.println("Output : "); for (int i = 0; i < testCasesCount; i++) { System.out.println(result[i]); } } private static int goForBusiness(int arr[], int len, int kthLargest) { int lastIndex = len; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { int d = Math.abs(arr[i] - arr[j]); // System.out.println("Checked "+i+"th and "+j+"th element with differnece : "+d); if (!searchInArray(arr, lastIndex, d)) { arr[lastIndex++] = d; } } } Arrays.sort(arr, 0, lastIndex); // System.out.print("After Sort : "); // printArray(arr, lastIndex); if (kthLargest > lastIndex) return -1; return arr[lastIndex - kthLargest]; } private static int[] makeArrayOfInteger(String[] str) { int[] arr = new int[str.length * 4]; for (int i = 0; i < str.length; i++) arr[i] = Integer.parseInt(str[i]); return arr; } private static boolean searchInArray(int arr[], int len, int ele) { for (int i = 0; i < len; i++) if (arr[i] == ele) return true; return false; } private static void printArray(int arr[], int len) { for (int i = 0; i < len; i++) System.out.print(" " + arr[i]); System.out.println(""); }} Sopra Steria Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE 1 TCS Digital Interview Questions Google Interview Questions Amazon Interview Experience SDE-2 (3 Years Experienced) TCS Ninja Interview Experience (2020 batch) Write It Up: Share Your Interview Experiences Samsung RnD Coding Round Questions Nagarro Interview Experience
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2019" }, { "code": null, "e": 475, "s": 28, "text": "Today, I was called for interview in Sopra Steria. Approximate 100 persons were present during the interview process. First round as technical test which consists of 2 complex questions from hackersearth websites. Though I failed in first round itself. One question I tries to solve and I solved that 80% but could not make to 2nd round. Question which I attempted is given below along with solution so that you can post and anybody can get help." }, { "code": null, "e": 546, "s": 475, "text": "Q. 1 You have to take input from input device with the below sysntax :" }, { "code": null, "e": 589, "s": 546, "text": "Line 1 : T No of test cases to be checked." }, { "code": null, "e": 611, "s": 589, "text": "Line 2 : Array Count." }, { "code": null, "e": 649, "s": 611, "text": "Line 3 : No of elements of the array." }, { "code": null, "e": 715, "s": 649, "text": "Line 4 : Kth largest element to be found. If not found return -1." }, { "code": null, "e": 793, "s": 715, "text": "Line 2, 3 and 4 will get repeated accordingly what we have entered in line 1." }, { "code": null, "e": 977, "s": 793, "text": "Rule : We need to find the differences of ant 2 numbers, if it is not present then we should add this to given array. So we would have all numbers difference present in array in last." }, { "code": null, "e": 1014, "s": 977, "text": "For Example : INPUT :151 3 5 6 72112" }, { "code": null, "e": 1304, "s": 1014, "text": "Input : Line 1 is : we want to pass 2 test cases.Line 2 : Array size of First Array.Line 3 : Array Elements separated by SPACELine 4 : Need to find out 2nd Largest elements.Line 5 : Array Size of Second array for test case 2.Line 6 : Array ElementsLine 7 : 2nd largest elements to be found" }, { "code": null, "e": 1316, "s": 1304, "text": "Output :6-1" }, { "code": null, "e": 1328, "s": 1316, "text": "Solutions :" }, { "code": "package soptasteria; import java.io.IOException;import java.util.Arrays;import java.util.Scanner; public class Test { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int testCasesCount = sc.nextInt(); int[] result = new int[testCasesCount]; for (int i = 0; i < testCasesCount; i++) { int arraySize = sc.nextInt(); // System.err.println(\"Enter arr element after arr size\"); // System.err.println(\"Array Entered : \"+sc.nextLine()); sc.nextLine(); String[] strArr = sc.nextLine().split(\" \"); int[] array = makeArrayOfInteger(strArr); // System.out.println(\"Printing integer array\"); int kth = sc.nextInt(); // System.out.println(\"Array Entered : \"); printArray(array, arraySize); result[i] = goForBusiness(array, arraySize, kth); // System.out.println(\"Result : \"+result[i]); } System.out.println(\"Output : \"); for (int i = 0; i < testCasesCount; i++) { System.out.println(result[i]); } } private static int goForBusiness(int arr[], int len, int kthLargest) { int lastIndex = len; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { int d = Math.abs(arr[i] - arr[j]); // System.out.println(\"Checked \"+i+\"th and \"+j+\"th element with differnece : \"+d); if (!searchInArray(arr, lastIndex, d)) { arr[lastIndex++] = d; } } } Arrays.sort(arr, 0, lastIndex); // System.out.print(\"After Sort : \"); // printArray(arr, lastIndex); if (kthLargest > lastIndex) return -1; return arr[lastIndex - kthLargest]; } private static int[] makeArrayOfInteger(String[] str) { int[] arr = new int[str.length * 4]; for (int i = 0; i < str.length; i++) arr[i] = Integer.parseInt(str[i]); return arr; } private static boolean searchInArray(int arr[], int len, int ele) { for (int i = 0; i < len; i++) if (arr[i] == ele) return true; return false; } private static void printArray(int arr[], int len) { for (int i = 0; i < len; i++) System.out.print(\" \" + arr[i]); System.out.println(\"\"); }}", "e": 3810, "s": 1328, "text": null }, { "code": null, "e": 3823, "s": 3810, "text": "Sopra Steria" }, { "code": null, "e": 3845, "s": 3823, "text": "Interview Experiences" }, { "code": null, "e": 3943, "s": 3845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4013, "s": 3943, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 4086, "s": 4013, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 4124, "s": 4086, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 4156, "s": 4124, "text": "TCS Digital Interview Questions" }, { "code": null, "e": 4183, "s": 4156, "text": "Google Interview Questions" }, { "code": null, "e": 4239, "s": 4183, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 4283, "s": 4239, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 4329, "s": 4283, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 4364, "s": 4329, "text": "Samsung RnD Coding Round Questions" } ]
How to fetch single and multiple documents from MongoDb using Node.js ?
20 Nov, 2020 MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format). Refer (this) article. MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() method is used for connecting the MongoDB database which is running on a particular server on your machine. (Refer to this article). We can also use promises, in this method in resolve the object contains all the methods and properties required for collection manipulation and in reject the error occurs during connection. Installing module: node install mongodb Project Structure: Running the server on Local IP: data is folder name mongod --dbpath=data --bind_ip 127.0.0.1 MongoDB Database: Database:GFG Collection:GFGcollections Index.js 1. Fetching single document of GFGcollections Javascript const MongoClient = require("mongodb");const url = 'mongodb://localhost:27017/';const databasename = "GFG"; // Database nameMongoClient.connect(url).then((client) => { const connect = client.db(databasename); // Connect to collection const collection = connect .collection("GFGcollections"); // Fetching the records having // name as saini collection.find({ "name": "saini" }) .toArray().then((ans) => { console.log(ans); });}).catch((err) => { // Printing the error message console.log(err.Message);}) Output: 2. Fetching all documents of the GFGcollections Javascript const MongoClient = require("mongodb");const url = 'mongodb://localhost:27017/';const databasename = "GFG"; // Database nameMongoClient.connect(url).then((client) => { const connect = client.db(databasename); // Connect to collection const collection = connect .collection("GFGcollections"); collection.find({}).toArray().then((ans) => { console.log(ans); });}).catch((err) => { // Printing the error message console.log(err.Message);}) Output: Node.js-Misc Technical Scripter 2020 MongoDB Node.js Technical Scripter Web Technologies Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Nov, 2020" }, { "code": null, "e": 408, "s": 28, "text": "MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format). Refer (this) article." }, { "code": null, "e": 911, "s": 408, "text": "MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() method is used for connecting the MongoDB database which is running on a particular server on your machine. (Refer to this article). We can also use promises, in this method in resolve the object contains all the methods and properties required for collection manipulation and in reject the error occurs during connection." }, { "code": null, "e": 930, "s": 911, "text": "Installing module:" }, { "code": null, "e": 952, "s": 930, "text": "node install mongodb\n" }, { "code": null, "e": 971, "s": 952, "text": "Project Structure:" }, { "code": null, "e": 1023, "s": 971, "text": "Running the server on Local IP: data is folder name" }, { "code": null, "e": 1065, "s": 1023, "text": "mongod --dbpath=data --bind_ip 127.0.0.1\n" }, { "code": null, "e": 1083, "s": 1065, "text": "MongoDB Database:" }, { "code": null, "e": 1123, "s": 1083, "text": "Database:GFG\nCollection:GFGcollections\n" }, { "code": null, "e": 1132, "s": 1123, "text": "Index.js" }, { "code": null, "e": 1178, "s": 1132, "text": "1. Fetching single document of GFGcollections" }, { "code": null, "e": 1189, "s": 1178, "text": "Javascript" }, { "code": "const MongoClient = require(\"mongodb\");const url = 'mongodb://localhost:27017/';const databasename = \"GFG\"; // Database nameMongoClient.connect(url).then((client) => { const connect = client.db(databasename); // Connect to collection const collection = connect .collection(\"GFGcollections\"); // Fetching the records having // name as saini collection.find({ \"name\": \"saini\" }) .toArray().then((ans) => { console.log(ans); });}).catch((err) => { // Printing the error message console.log(err.Message);})", "e": 1762, "s": 1189, "text": null }, { "code": null, "e": 1770, "s": 1762, "text": "Output:" }, { "code": null, "e": 1818, "s": 1770, "text": "2. Fetching all documents of the GFGcollections" }, { "code": null, "e": 1829, "s": 1818, "text": "Javascript" }, { "code": "const MongoClient = require(\"mongodb\");const url = 'mongodb://localhost:27017/';const databasename = \"GFG\"; // Database nameMongoClient.connect(url).then((client) => { const connect = client.db(databasename); // Connect to collection const collection = connect .collection(\"GFGcollections\"); collection.find({}).toArray().then((ans) => { console.log(ans); });}).catch((err) => { // Printing the error message console.log(err.Message);})", "e": 2310, "s": 1829, "text": null }, { "code": null, "e": 2318, "s": 2310, "text": "Output:" }, { "code": null, "e": 2331, "s": 2318, "text": "Node.js-Misc" }, { "code": null, "e": 2355, "s": 2331, "text": "Technical Scripter 2020" }, { "code": null, "e": 2363, "s": 2355, "text": "MongoDB" }, { "code": null, "e": 2371, "s": 2363, "text": "Node.js" }, { "code": null, "e": 2390, "s": 2371, "text": "Technical Scripter" }, { "code": null, "e": 2407, "s": 2390, "text": "Web Technologies" }, { "code": null, "e": 2423, "s": 2407, "text": "Write From Home" } ]
Autosizing TextView in Android - GeeksforGeeks
18 Feb, 2021 If the user is giving the input and the input needs to be shown as TextView and if the user inputs the stuff which can go out of the screen, then in this case the font TextView should be decreased gradually. So, in this article its been discussed how the developer can reduce the size of TextView gradually as the user gives the data. One can have a look at the following GIF to understand it better, what we are going to build at the end of this article. Note that we are going to implement this project using the Java language. In this article, the dial pad is taken as an example. This method can be used in building the calculator and can be used in many other scenarios where the TextView resize is required. Step 1: Create an android studio project with an empty activity You may refer to this Android | How to Create/Start a New Project in Android Studio on how to create an empty activity android studio project. Rename the application name as Auto resize TextView, and let the name of the layout be activity_main.xml And select Java as Language. Step 2: Building an appropriate layout by working with the activity_main.xml file As we have taken the dial pad as an example to demonstrate the auto-resizing of the TextView, so invoke the following code in the activity_main.xml file to make the UI like a dial pad. XML <?xml version="1.0" encoding="utf-8"?> <!--the attributes further invoked for the TextView are the part of Android Jetpac so we need to include xmlns:app="http://schemas.android.com/apk/res-auto" as you can see below--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--One needs to hardcode the height of the TextView--> <!--so that it can decrease its height automatically within--> <!--the given height and it doesn't disturbs the other widgets--> <!--one can set the maxLines of the TextViews upto which--> <!--the lines of the TextViews must be visible in this case its 2--> <TextView android:id="@+id/primaryTextView" android:layout_width="match_parent" android:layout_height="100dp" android:hint="0" android:maxLines="2" app:autoSizeMaxTextSize="80sp" app:autoSizeMinTextSize="10sp" app:autoSizeStepGranularity="2sp" app:autoSizeTextType="uniform" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal" android:weightSum="3"> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedOne" android:text="1" android:textSize="24sp" /> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedTwo" android:text="2" android:textSize="24sp" /> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedThree" android:text="3" android:textSize="24sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal" android:weightSum="3"> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedFour" android:text="4" android:textSize="24sp" /> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedFive" android:text="5" android:textSize="24sp" /> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedSix" android:text="6" android:textSize="24sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal" android:weightSum="3"> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedSeven" android:text="7" android:textSize="24sp" /> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedEight" android:text="8" android:textSize="24sp" /> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_margin="8dp" android:onClick="clickedNine" android:text="9" android:textSize="24sp" /> </LinearLayout> <Button android:layout_width="68dp" android:layout_height="68dp" android:layout_gravity="center" android:layout_marginTop="8dp" android:onClick="clickedZero" android:text="0" android:textSize="24sp" /> </LinearLayout> One can see attributes of TextView in above code app:autoSizeMaxTextSize=”80sp”, this is the initial sizes of TextView. app:autoSizeMinTextSize=”10sp” using this attribute the TextView will be resized up to the size of 10sp and app:autoSizeStepGranularity=”2sp” using this attribute we are uniformly reducing the size of the TextView as 2sp when it goes out of the screen. app:autoSizeTextType=”uniform” by using this attribute we are simply resizing the TextView uniformly. One thing to remember is one shouldn’t set the height and width of the TextView as wrap_content. To disable the resizing of the TextView, can set this attribute to none. As you can see below. app:autoSizeTextType=”none” The following Output UI is produced: Step 3: Now handling each Button separately, using the onClick XML attribute Now in the MainActivity.java file, we will handle all the onClick functions of each Button separately, and set the TextView to the appropriate number when pressed. So, now invoke the following code: Java import androidx.appcompat.app.AppCompatActivity;import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView primaryTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the button using appropriate ID of the TextView primaryTextView = findViewById(R.id.primaryTextView); } // handle the button 1 and append the 1 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedOne(View view) { primaryTextView.setText(primaryTextView.getText() + "1"); } // handle the button 2 and append the 2 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedTwo(View view) { primaryTextView.setText(primaryTextView.getText() + "2"); } // handle the button 3 and append the 3 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedThree(View view) { primaryTextView.setText(primaryTextView.getText() + "3"); } // handle the button 4 and append the 4 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedFour(View view) { primaryTextView.setText(primaryTextView.getText() + "4"); } // handle the button 5 and append the 5 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedFive(View view) { primaryTextView.setText(primaryTextView.getText() + "5"); } // handle the button 6 and append the 6 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedSix(View view) { primaryTextView.setText(primaryTextView.getText() + "6"); } // handle the button 7 and append the 7 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedSeven(View view) { primaryTextView.setText(primaryTextView.getText() + "7"); } // handle the button 8 and append the 8 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedEight(View view) { primaryTextView.setText(primaryTextView.getText() + "8"); } // handle the button 9 and append the 9 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedNine(View view) { primaryTextView.setText(primaryTextView.getText() + "9"); } // handle the button 0 and append the 0 to the end of the TextView @SuppressLint("SetTextI18n") public void clickedZero(View view) { primaryTextView.setText(primaryTextView.getText() + "0"); }} adityamshidlyali android Android-View Android Java 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 How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24725, "s": 24697, "text": "\n18 Feb, 2021" }, { "code": null, "e": 25255, "s": 24725, "text": "If the user is giving the input and the input needs to be shown as TextView and if the user inputs the stuff which can go out of the screen, then in this case the font TextView should be decreased gradually. So, in this article its been discussed how the developer can reduce the size of TextView gradually as the user gives the data. One can have a look at the following GIF to understand it better, what we are going to build at the end of this article. Note that we are going to implement this project using the Java language." }, { "code": null, "e": 25439, "s": 25255, "text": "In this article, the dial pad is taken as an example. This method can be used in building the calculator and can be used in many other scenarios where the TextView resize is required." }, { "code": null, "e": 25503, "s": 25439, "text": "Step 1: Create an android studio project with an empty activity" }, { "code": null, "e": 25646, "s": 25503, "text": "You may refer to this Android | How to Create/Start a New Project in Android Studio on how to create an empty activity android studio project." }, { "code": null, "e": 25751, "s": 25646, "text": "Rename the application name as Auto resize TextView, and let the name of the layout be activity_main.xml" }, { "code": null, "e": 25780, "s": 25751, "text": "And select Java as Language." }, { "code": null, "e": 25862, "s": 25780, "text": "Step 2: Building an appropriate layout by working with the activity_main.xml file" }, { "code": null, "e": 26047, "s": 25862, "text": "As we have taken the dial pad as an example to demonstrate the auto-resizing of the TextView, so invoke the following code in the activity_main.xml file to make the UI like a dial pad." }, { "code": null, "e": 26051, "s": 26047, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!--the attributes further invoked for the TextView are the part of Android Jetpac so we need to include xmlns:app=\"http://schemas.android.com/apk/res-auto\" as you can see below--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--One needs to hardcode the height of the TextView--> <!--so that it can decrease its height automatically within--> <!--the given height and it doesn't disturbs the other widgets--> <!--one can set the maxLines of the TextViews upto which--> <!--the lines of the TextViews must be visible in this case its 2--> <TextView android:id=\"@+id/primaryTextView\" android:layout_width=\"match_parent\" android:layout_height=\"100dp\" android:hint=\"0\" android:maxLines=\"2\" app:autoSizeMaxTextSize=\"80sp\" app:autoSizeMinTextSize=\"10sp\" app:autoSizeStepGranularity=\"2sp\" app:autoSizeTextType=\"uniform\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:orientation=\"horizontal\" android:weightSum=\"3\"> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedOne\" android:text=\"1\" android:textSize=\"24sp\" /> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedTwo\" android:text=\"2\" android:textSize=\"24sp\" /> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedThree\" android:text=\"3\" android:textSize=\"24sp\" /> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:orientation=\"horizontal\" android:weightSum=\"3\"> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedFour\" android:text=\"4\" android:textSize=\"24sp\" /> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedFive\" android:text=\"5\" android:textSize=\"24sp\" /> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedSix\" android:text=\"6\" android:textSize=\"24sp\" /> </LinearLayout> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:orientation=\"horizontal\" android:weightSum=\"3\"> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedSeven\" android:text=\"7\" android:textSize=\"24sp\" /> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedEight\" android:text=\"8\" android:textSize=\"24sp\" /> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_margin=\"8dp\" android:onClick=\"clickedNine\" android:text=\"9\" android:textSize=\"24sp\" /> </LinearLayout> <Button android:layout_width=\"68dp\" android:layout_height=\"68dp\" android:layout_gravity=\"center\" android:layout_marginTop=\"8dp\" android:onClick=\"clickedZero\" android:text=\"0\" android:textSize=\"24sp\" /> </LinearLayout>", "e": 30491, "s": 26051, "text": null }, { "code": null, "e": 30611, "s": 30491, "text": "One can see attributes of TextView in above code app:autoSizeMaxTextSize=”80sp”, this is the initial sizes of TextView." }, { "code": null, "e": 30864, "s": 30611, "text": "app:autoSizeMinTextSize=”10sp” using this attribute the TextView will be resized up to the size of 10sp and app:autoSizeStepGranularity=”2sp” using this attribute we are uniformly reducing the size of the TextView as 2sp when it goes out of the screen." }, { "code": null, "e": 30966, "s": 30864, "text": "app:autoSizeTextType=”uniform” by using this attribute we are simply resizing the TextView uniformly." }, { "code": null, "e": 31063, "s": 30966, "text": "One thing to remember is one shouldn’t set the height and width of the TextView as wrap_content." }, { "code": null, "e": 31158, "s": 31063, "text": "To disable the resizing of the TextView, can set this attribute to none. As you can see below." }, { "code": null, "e": 31186, "s": 31158, "text": "app:autoSizeTextType=”none”" }, { "code": null, "e": 31224, "s": 31186, "text": "The following Output UI is produced: " }, { "code": null, "e": 31302, "s": 31224, "text": "Step 3: Now handling each Button separately, using the onClick XML attribute " }, { "code": null, "e": 31501, "s": 31302, "text": "Now in the MainActivity.java file, we will handle all the onClick functions of each Button separately, and set the TextView to the appropriate number when pressed. So, now invoke the following code:" }, { "code": null, "e": 31506, "s": 31501, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.annotation.SuppressLint;import android.os.Bundle;import android.view.View;import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView primaryTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the button using appropriate ID of the TextView primaryTextView = findViewById(R.id.primaryTextView); } // handle the button 1 and append the 1 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedOne(View view) { primaryTextView.setText(primaryTextView.getText() + \"1\"); } // handle the button 2 and append the 2 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedTwo(View view) { primaryTextView.setText(primaryTextView.getText() + \"2\"); } // handle the button 3 and append the 3 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedThree(View view) { primaryTextView.setText(primaryTextView.getText() + \"3\"); } // handle the button 4 and append the 4 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedFour(View view) { primaryTextView.setText(primaryTextView.getText() + \"4\"); } // handle the button 5 and append the 5 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedFive(View view) { primaryTextView.setText(primaryTextView.getText() + \"5\"); } // handle the button 6 and append the 6 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedSix(View view) { primaryTextView.setText(primaryTextView.getText() + \"6\"); } // handle the button 7 and append the 7 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedSeven(View view) { primaryTextView.setText(primaryTextView.getText() + \"7\"); } // handle the button 8 and append the 8 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedEight(View view) { primaryTextView.setText(primaryTextView.getText() + \"8\"); } // handle the button 9 and append the 9 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedNine(View view) { primaryTextView.setText(primaryTextView.getText() + \"9\"); } // handle the button 0 and append the 0 to the end of the TextView @SuppressLint(\"SetTextI18n\") public void clickedZero(View view) { primaryTextView.setText(primaryTextView.getText() + \"0\"); }}", "e": 34198, "s": 31506, "text": null }, { "code": null, "e": 34215, "s": 34198, "text": "adityamshidlyali" }, { "code": null, "e": 34223, "s": 34215, "text": "android" }, { "code": null, "e": 34236, "s": 34223, "text": "Android-View" }, { "code": null, "e": 34244, "s": 34236, "text": "Android" }, { "code": null, "e": 34249, "s": 34244, "text": "Java" }, { "code": null, "e": 34254, "s": 34249, "text": "Java" }, { "code": null, "e": 34262, "s": 34254, "text": "Android" }, { "code": null, "e": 34360, "s": 34262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34369, "s": 34360, "text": "Comments" }, { "code": null, "e": 34382, "s": 34369, "text": "Old Comments" }, { "code": null, "e": 34421, "s": 34382, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 34471, "s": 34421, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 34522, "s": 34471, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 34560, "s": 34522, "text": "Android Listview in Java with Example" }, { "code": null, "e": 34602, "s": 34560, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 34617, "s": 34602, "text": "Arrays in Java" }, { "code": null, "e": 34661, "s": 34617, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34683, "s": 34661, "text": "For-each loop in Java" }, { "code": null, "e": 34708, "s": 34683, "text": "Reverse a string in Java" } ]
C++ Program to Construct Transitive Closure Using Warshall’s Algorithm
If a directed graph is given, determine if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph. Reachable mean that there is a path from vertex i to j. This reach-ability matrix is called transitive closure of a graph. Warshall algorithm is commonly used to find the Transitive Closure of a given graph G. Here is a C++ program to implement this algorithm. Begin 1.Take maximum number of nodes as input. 2.For Label the nodes as a, b, c ..... 3.To check if there any edge present between the nodes make a for loop: for i = 97 to less than 97 + number of nodes for j = 97 to less than 97 + number of nodes if edge is present do, adj[i - 97][j - 97] = 1 else adj[i - 97][j - 97] = 0 end loop end loop. 4.To print the transitive closure of graph: for i = 0 to number of nodes c = 97 + i end loop. for i = 0 to number of nodes c = 97 + i; for j = 0 to n_nodes print adj[I][j] end loop end loop End #include<iostream> using namespace std; const int n_nodes = 20; int main() { int n_nodes, k, n; char i, j, res, c; int adj[10][10], path[10][10]; cout << "\n\tMaximum number of nodes in the graph :"; cin >>n; n_nodes = n; cout << "\nEnter 'y' for 'YES' and 'n' for 'NO' \n"; for (i = 97; i < 97 + n_nodes; i++) for (j = 97; j < 97 + n_nodes; j++) { cout << "\n\tIs there an edge from " << i << " to " << j << " ? "; cin >>res; if (res == 'y') adj[i - 97][j - 97] = 1; else adj[i - 97][j - 97] = 0; } cout << "\nTransitive Closure of the Graph:\n"; cout << "\n\t\t\t "; for (i = 0; i < n_nodes; i++) { c = 97 + i; cout << c << " "; } cout << "\n\n"; for (int i = 0; i < n_nodes; i++) { c = 97 + i; cout << "\t\t\t" << c << " "; for (int j = 0; j < n_nodes; j++) cout << adj[i][j] << " "; cout << "\n"; } return 0; } Maximum number of nodes in the graph :4 Enter 'y' for 'YES' and 'n' for 'NO' Is there an edge from a to a ? y Is there an edge from a to b ?y Is there an edge from a to c ? n Is there an edge from a to d ? n Is there an edge from b to a ? y Is there an edge from b to b ? n Is there an edge from b to c ? y Is there an edge from b to d ? n Is there an edge from c to a ? y Is there an edge from c to b ? n Is there an edge from c to c ? n Is there an edge from c to d ? n Is there an edge from d to a ? y Is there an edge from d to b ? n Is there an edge from d to c ? y Is there an edge from d to d ? n Transitive Closure of the Graph: a b c d a 1 1 0 0 b 1 0 1 0 c 1 0 0 0 d 1 0 1 0
[ { "code": null, "e": 1460, "s": 1062, "text": "If a directed graph is given, determine if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the given graph. Reachable mean that there is a path from vertex i to j. This reach-ability matrix is called transitive closure of a graph. Warshall algorithm is commonly used to find the Transitive Closure of a given graph G. Here is a C++ program to implement this algorithm." }, { "code": null, "e": 2156, "s": 1460, "text": "Begin\n 1.Take maximum number of nodes as input.\n 2.For Label the nodes as a, b, c .....\n 3.To check if there any edge present between the nodes make a for loop:\n for i = 97 to less than 97 + number of nodes\n for j = 97 to less than 97 + number of nodes\n if edge is present do,\n adj[i - 97][j - 97] = 1\n else\n adj[i - 97][j - 97] = 0\n end loop\n end loop.\n 4.To print the transitive closure of graph:\n for i = 0 to number of nodes\n c = 97 + i\n end loop.\n for i = 0 to number of nodes\n c = 97 + i;\n for j = 0 to n_nodes\n print adj[I][j]\n end loop\n end loop\nEnd" }, { "code": null, "e": 3184, "s": 2156, "text": "#include<iostream>\nusing namespace std;\nconst int n_nodes = 20;\nint main() {\n int n_nodes, k, n;\n char i, j, res, c;\n int adj[10][10], path[10][10];\n cout << \"\\n\\tMaximum number of nodes in the graph :\";\n cin >>n;\n n_nodes = n;\n cout << \"\\nEnter 'y' for 'YES' and 'n' for 'NO' \\n\";\n for (i = 97; i < 97 + n_nodes; i++)\n for (j = 97; j < 97 + n_nodes; j++) {\n cout << \"\\n\\tIs there an edge from \" << i << \" to \" << j << \" ? \";\n cin >>res;\n if (res == 'y')\n adj[i - 97][j - 97] = 1;\n else\n adj[i - 97][j - 97] = 0;\n }\n cout << \"\\nTransitive Closure of the Graph:\\n\";\n cout << \"\\n\\t\\t\\t \";\n for (i = 0; i < n_nodes; i++) {\n c = 97 + i;\n cout << c << \" \";\n }\n cout << \"\\n\\n\";\n for (int i = 0; i < n_nodes; i++) {\n c = 97 + i;\n cout << \"\\t\\t\\t\" << c << \" \";\n for (int j = 0; j < n_nodes; j++)\n cout << adj[i][j] << \" \";\n cout << \"\\n\";\n }\n return 0;\n}" }, { "code": null, "e": 3872, "s": 3184, "text": "Maximum number of nodes in the graph :4\nEnter 'y' for 'YES' and 'n' for 'NO'\n\nIs there an edge from a to a ? y\nIs there an edge from a to b ?y\nIs there an edge from a to c ? n\nIs there an edge from a to d ? n\nIs there an edge from b to a ? y\nIs there an edge from b to b ? n\nIs there an edge from b to c ? y\nIs there an edge from b to d ? n\nIs there an edge from c to a ? y\nIs there an edge from c to b ? n\nIs there an edge from c to c ? n\nIs there an edge from c to d ? n\nIs there an edge from d to a ? y\nIs there an edge from d to b ? n\nIs there an edge from d to c ? y\nIs there an edge from d to d ? n\nTransitive Closure of the Graph:\n\na b c d\n\na 1 1 0 0\nb 1 0 1 0\nc 1 0 0 0\nd 1 0 1 0" } ]
How to build a Deep Learning model in 10 lines | by Jordi TORRES.AI | Towards Data Science
This post will introduce the reader to the basics of neural networks through a case study that using only 10 lines of Python code creates and trains a neural network that recognises handwritten digits in 3 basic steps: 1- Load and Preprocess the Data 2- Define the Model 3- Train the Model To do this, we will use the TensorFlow Keras API, the most popular library currently in the Deep Learning community. Let’s go for it! As a case study, we will create a model that allows us to identify handwritten digits such as te following ones: The goal is to create a mathematical model that, given an image, the model identify the number it represents. For example, if we feed to the model the first image, we would expect it to answer that it is a 5. The next one a 0, next one a 4, an so on. Actually, we are dealing with a classification problem, which given an image, the model classifies it between 0 and 9. But sometimes, even we can find ourselves with certain doubts, for example, the first image represents a 5 or a 3? For this purpose, the neural network that we will create returns a vector with 10 positions indicating the likelihood of each of the ten possible digits: Yes, in just 10 lines of python code you can create and train a neural network model that classify handwritten digits: 1: import tensorflow as tf2: from tensorflow.keras.utils import to_categorical3:(x_train, y_train), _ = tf.keras.datasets.mnist.load_data()4: x_train = x_train.reshape(60000, 784).astype('float32')/2555: y_train = to_categorical(y_train, num_classes=10)6: model = tf.keras.Sequential()7: model.add(tf.keras.layers.Dense(10, activation='sigmoid', input_shape=(784,)))8: model.add(tf.keras.layers.Dense(10, activation='softmax'))9: model.compile(loss="categorical_crossentropy", optimizer="sgd", metrics = ['accuracy'])10: model.fit(x_train, y_train, epochs=10, verbose=0) We used the API Keras of TensorFlow. It is the recommended library for beginners, since its learning curve is very smooth compared to others, and at the moment it is one of the popular middleware to implement neural networks. Keras was developed and maintained by François Chollet, an engineer from Google, and it is currently included in Tensorflow library. I suggest to use the Colaboratory offered by Google if you want to execute the code described in this post. It is a Google research project created to help to disseminate Machine Learning education and research. It is a Jupyter notebook environment that requires no configuration and runs completely in the Cloud allowing the use different Deep Learning libraries as TensorFlow and PyTorch. The most important feature that distinguishes Colab from other free cloud services is; Colab provides GPU (or TPU) and is totally free. Detailed information about the service can be found on the faq page. By default, Colab notebooks run on CPU. You can switch your notebook to run with GPU (or TPU). In order to obtain access to one GPU we need to choose the tab Runtime and then select “Change runtime type” as shown in the following figure: When a pop-up window appears select GPU. Ensure “Hardware accelerator” is set to GPU (the default is CPU). Afterwards, ensure that you are connected to the runtime (there is a green check next to “connected” in the menu ribbon): Now you are able to run the code presented in this post. I suggest to copy & paste the code of this post in a colab notebook in order to see the execution meanwhile you are reading this post. Ready? Let’s do it! Code for this post available at GitHub First of all we need to import some Python libraries that we need in order to program our neural network in TensorFlow: import tensorflow as tffrom tensorflow.keras.utils import to_categorical Next step is to loading data that will be used to train our neural network. We will use the MNIST dataset, which can be downloaded from The MNIST database page. This dataset contains 60,000 images of hand-made digits to train the model and it is ideal for entering pattern recognition techniques for the first time without having to spend much time preprocessing and formatting data, both very important and expensive steps in the analysis of data and of special complexity when working with images. With TensorFlow this can be done using this line of code (line 3): (x_train, y_train), _ = tf.keras.datasets.mnist.load_data() Optional step: If you want, you can verify the data loaded using this code: import numpy as npimport matplotlib.pyplot as pltfig = plt.figure(figsize=(25, 4))for idx in np.arange(20): ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(x_train[idx], cmap=plt.cm.binary) ax.set_title(str(y_train[idx])) This dataset of black and white images (images contain gray levels) has been normalized to 20×20 pixels while retaining their aspect ratio. Subsequently, the images were centered, calculating the center of mass of these and moving the image in order to position this point in the center of the 28×28 field. These MNIST images of 28×28 pixels are represented as an array of numbers whose values range from [0, 255] of type uint8. But it is usual to scale the input values of neural networks to certain ranges. In the example of this post the input values should be scaled to values of type float32 within the interval [0, 1]. On the other hand, to facilitate the entry of data into our neural network we must make a transformation of the input (image) from 2 dimensions (2D) to a vector of 1 dimension (1D). That is, the matrix of 28×28 numbers can be represented by a vector (array) of 784 numbers (concatenating row by row), which is the format that accepts as input a densely connected neural network like the one we will see in this post. We can achieve these transformations with the following line of code (line 4): x_train = x_train.reshape(60000, 784).astype('float32')/255 Furthermore, the dataset has a label for each of the images that indicates what digit it represents (downloaded in y_train). In our case are numbers between 0 and 9 that indicate which digit the image represents,that is, to which class it is associated. We need to represent each label with a vector of 10 positions as we presented before, where the position corresponding to the digit that represents the image contains a 1 and the rest contains 0s. This process of transforming the labels into a vector of as many zeros as the number of different labels, and putting a 1 in the index corresponding to the label, is known as one-hot encoding. For example, the number 7 will be encoded as: We can achieve this transformations with the following line of code (line 5): y_train = to_categorical(y_train, num_classes=10) In order to define the model with the Keras’s API we only need these code lines (lines 6–8): model = tf.keras.Sequential()model.add(tf.keras.layers.Dense(10,activation='sigmoid', input_shape=(784,)))model.add(tf.keras.layers.Dense(10,activation='softmax')) However, before to explain these code lines, let me introduce some basic neural network concepts. In order to show how a basic neuronal is, let’s suppose a simple example where we have a set of points in a two-dimensional plane and each point is already labeled “square” or “circle”: Given a new point “X“, we want to know what label corresponds to it: A common approach is to draw a line that separates the two groups and use this line as a classifier: In this case, the input data will be represented by vectors of the form (x1, x2) that indicate their coordinates in this two-dimensional space, and our function will return ‘0’ or ‘1’ (above or below the line) to know if it should be classified as “square” or “circle”. It can be defined by: More generally, we can express the line as: To classify input elements X, which in our case are two-dimensional, we must learn a vector of weight W of the same dimension as the input vectors,that is, the vector (w1, w2) and a b bias. With these calculated values, we can now construct an artificial neuron to classify a new element X. Basically, the neuron applies this vector W of calculated weights on the values in each dimension of the input element X, and at the end adds the bias b. The result of this will be passed through a non-linear “activation” function to produce a result of ‘0’ or ‘1’. The function of this artificial neuron that we have just defined can be expressed in a more formal way such as: Now, we will need a function that applies a transformation to variable z so that it becomes ‘0’ or ‘1’. Although there are several functions ( “activation functions”), for this example we will use one known as a sigmoid function that returns an actual output value between 0 and 1 for any input value: If we analyze the previous formula, we can see that it always tends to give values close to 0 or 1. If the input z is reasonably large and positive, “e” at minus z is zero and, therefore, the y takes the value of 1. If z has a large and negative value, it turns out that for “e” raised to a large positive number, the denominator of the formula will turn out to be a large number and therefore the value of y will be close to 0. Graphically, the sigmoid function presents this form: So far we have presented how to define an artificial neuron, the simplest architecture that a neural network can have. In particular this architecture is named in the literature of the subject as Perceptron (also called linear threshold unit (LTU)), invented in 1957 by Frank Rosenblatt, and visually summarized in a general way with the following scheme: But before moving forward with the example, we will briefly introduce the form that neural networks usually take when they are constructed from perceptrons like the one we have just presented. In the literature of the area we refer to a Multi-Layer Perceptron (MLP) when we find neural networks that have an input layer, one or more layers composed of perceptrons, called hidden layers and a final layer with several perceptrons called the output layer. In general we refer to Deep Learning when the model based on neural networks is composed of multiple hidden layers. Visually it can be presented with the following scheme: MLPs are often used for classification, and specifically when classes are exclusive, as in the case of the classification of digit images (in classes from 0 to 9). In this case, the output layer returns the probability of belonging to each one of the classes, thanks to a function called softmax. Visually we could represent it in the following way: As we mentioned, there are several activation functions in addition to the sigmoid, each with different properties. One of them is the one we just mentioned, the softmax activation function, which will be useful to present an example of simple neural network to classify in more than two classes. For the moment we can consider the softmax function as a generalization of the sigmoid function that allows us to classify more than two classes. We will solve the problem in a way that, given an input image, we will obtain the probabilities that it is each of the 10 possible digits. In this way, we will have a model that, for example, could predict a five in an image, but only being sure in 70% that it is a five. Due to the stroke of the upper part of the number in this image, it seems that it could become an three in a 20% chance and it could even give a certain probability to any other number. Although in this particular case we will consider that the prediction of our model is a five since it is the one with the highest probability, this approach of using a probability distribution can give us a better idea of how confident we are of our prediction. This is good in this case, where the numbers are made by hand, and surely in many of them, we cannot recognize the digits with 100% certainty. Therefore, for this example of classification we will obtain, for each input example, an output vector with the probability distribution over a set of mutually exclusive labels. That is, a vector of 10 probabilities each corresponding to a digit and also the sum of all these 10 probabilities results in the value of 1 (the probabilities will be expressed between 0 and 1). As we have already advanced, this is achieved through the use of an output layer in our neural network with the softmax activation function, in which each neuron in this softmax layer depends on the outputs of all the other neurons in the layer, since that the sum of the output of all of them must be 1. But how does the softmax activation function work? The softmax function is based on calculating “the evidence” that a certain image belongs to a particular class and then these evidences are converted into probabilities that it belongs to each of the possible classes. An approach to measure the evidence that a certain image belongs to a particular class is to make a weighted sum of the evidence of belonging to each of its pixels to that class. To explain the idea I will use a visual example. Let’s suppose that we already have the model learned for the number zero. For the moment, we can consider a model as “something” that contains information to know if a number is of a certain class. In this case, for the number zero, suppose we have a model like the one presented below: In this case, with a matrix of 28×28 pixels, where the pixels in red represent negative weights (i.e., reduce the evidence that it belongs), while that the pixels in blue represent positive weights (the evidence of which is greater increases). The white color represents the neutral value. Let’s imagine that we trace a zero over it. In general, the trace of our zero would fall on the blue zone (remember that we are talking about images that have been normalized to 20×20 pixels and later centered on a 28×28 image). It is quite evident that if our stroke goes over the red zone, it is most likely that we are not writing a zero; therefore, using a metric based on adding if we pass through the blue zone and subtracting if we pass through the red zone seems reasonable. To confirm that it is a good metric, let’s imagine now that we draw a three; it is clear that the red zone of the center of the previous model that we used for the zero will penalize the aforementioned metric since, as we can see in the left part of the following figure, when writing a three we pass over: But on the other hand, if the reference model is the one corresponding to number 3 as shown in the right part of the previous figure, we can see that, in general, the different possible traces that represent a three are mostly maintained in the blue zone. I hope that the reader, seeing this visual example, already intuits how the approximation of the weights indicated above allows us to estimate what number it is. Once the evidence of belonging to each of the 10 classes has been calculated, these must be converted into probabilities whose sum of all their components add 1. For this, softmax uses the exponential value of the calculated evidence and then normalizes them so that the sum equates to one, forming a probability distribution. The probability of belonging to class i is: Intuitively, the effect obtained with the use of exponentials is that one more unit of evidence has a multiplier effect and one unit less has the inverse effect. The interesting thing about this function is that a good prediction will have a single entry in the vector with a value close to 1, while the remaining entries will be close to 0. In a weak prediction, there will be several possible labels, which will have more or less the same probability. The main data structure in Keras is the Sequential class, which allows the creation of a basic neural network. Keras also offers an API that allows implementing more complex models in the form of a graph that can have multiple inputs, multiple outputs, with arbitrary connections in between, but it is beyond the scope of this post. The Sequential class of the Keras library is a wrapper for the sequential neural network model that Keras offers and can be created in the following way: model = tf.keras.Sequential()model.add(tf.keras.layers.Dense(10,activation='sigmoid', input_shape=(784,)))model.add(tf.keras.layers.Dense(10,activation='softmax')) In this case, the model in Keras is considered as a sequence of layers and each of them gradually “distills” the input data to obtain the desired output.In Keras we can find all the required types of layers that can be easily added to the model through the add() method. Here, the neural network has been defined as a sequence of two layers that are densely connected (or fully connected), meaning that all the neurons in each layer are connected to all the neurons in the next layer. Visually we could represent it in the following way: In the previous code we explicitly express in the input_shape argument of the first layer what the input data is like: a tensor that indicates that we have 784 features of the model. A very interesting characteristic of the Keras library is that it will automatically deduce the shape of the tensors between layers after the first one. This means that the programmer only has to establish this information for the first of them. Also, for each layer we indicate the number of nodes that it has and the activation function that we will apply in it (in this example, sigmoid). The second layer in this example is a softmax layer of 10 neurons, which means that it will return a matrix of 10 probability values representing the 10 possible digits (in general, the output layer of a classification network will have as many neurons as classes, except in a binary classification, where only one neuron is needed). Each value will be the probability that the image of the current digit belongs to each one of them. Optional step: A very useful method that Keras provides to check the architecture of our model is summary(): model.summary()_________________________________________________________________Layer (type) Output Shape Param #=================================================================dense_1 (Dense) (None, 10) 7850_________________________________________________________________dense_2 (Dense) (None, 10) 110=================================================================Total params: 7,960Trainable params: 7,960Non-trainable params: 0 For our simple example, we see that it indicates that 7,960 parameters are required (column Param #), which correspond to 7,850 parameters to the first layer and 110 to the second. In the first layer, for each neuron i (between 0 and 9) we require 784 parameters for the weights wij and therefore 10×784 parameters to store the weights of the 10 neurons. In addition to the 10 additional parameters for the 10 bj biases corresponding to each one of them. In the second layer, being a softmax function, it is required to connect all 10 neurons with the 10 neurons of the previous layer. Therefore 10×10 wi parameters are required and in addition 10 bj biases corresponding to each node. The details of the arguments that we can indicate for the dense layer can be found in the Keras manual. In our example, the most relevant ones appear in the example. The first argument indicates the number of neurons in the layer; the following is the activation function that we will use in it. In this post we discuss in more detail other possible activation functions beyond the two presented here: sigmoid and softmax. We’re almost done, we just have to explain the last two lines of code: model.compile(loss="categorical_crossentropy", optimizer="sgd", metrics = ['accuracy'])model.fit(x_train, y_train, epochs=10, verbose=0) The way how the neural network can learn the weights W and the biases b of the neurons is an iterative process for all the known labeled input examples, comparing the value of its label estimated through the model, with the expected value of the label of each element. After each iteration, the parameter values are adjusted in such a way that the discordance (error) between the estimated value for the image and the actual value, is becoming smaller. The following scheme wants to visually summarize the learning process of one perceptron in a general way: We can configure how this learning process will be with the compile() method, with which we can specify some properties through method arguments. The first of these arguments is the loss function that we will use to evaluate the degree of error between calculated outputs and the desired outputs of the training data. On the other hand, we specify an optimizer that is the way we have to specify the optimization algorithm that allows the neural network to calculate the weights of the parameters from the input data and the defined loss function. And finally we must indicate the metric that we will use to monitor the learning process of our neural network. In this first example we will only consider the accuracy (fraction of images that are correctly classified). For example, in our case we can specify the following arguments in compile() method to test it: model.compile(loss="categorical_crossentropy", optimizer="sgd", metrics = ['accuracy']) In this example we specify that the loss function is categorical_crossentropy, the optimizer used is the stocastic gradient descent (sgd) and the metric is accuracy, with which we will evaluate the percentage of correct guesses.ç In a new post the reader could enter in more detail about the learning process. Once our model has been defined and the learning method configured, it is ready to be trained. For this we can train or “adjust” the model to the training data available by invoking the fit() method of the model: model.fit(x_train, y_train, epochs=10, verbose=0) In the first two arguments we have indicated the data with which we will train the model in the form of Numpy arrays. The batch_size argument indicates the number of data that we will use for each update of the model parameters and with epochs we are indicating the number of times we will use all the data in the learning process. This method finds the value of the parameters of the network through the iterative training algorithm that we mentioned. Roughly, in each iteration of this algorithm, this algorith takes training data from x_train, passes them through the neural network (with the values that their parameters have at that moment), compares the obtained result with the expected one(indicated in y_train) and calculates the loss to guide the adjustment process of the model parameters, which intuitively consists of applying the optimizer specified above in the compile() method to calculate a new value of each one of the model parameters (weights and biases)in each iteration in such a way that the loss is reduced. This is the method that, as we will see, may take longer and Keras allows us to see its progress using the verbose argument (by default, equal to 1), in addition to indicating an estimate of how long each epoch takes: Epoch 1/560000/60000 [========] — 1s 15us/step — loss: 2.1822 — acc: 0.2916Epoch 2/560000/60000 [========] — 1s 12us/step — loss: 1.9180 — acc: 0.5283Epoch 3/560000/60000 [========] — 1s 13us/step — loss: 1.6978 — acc: 0.5937Epoch 4/560000/60000 [========] — 1s 14us/step — loss: 1.5102 — acc: 0.6537Epoch 5/560000/60000 [========] — 1s 13us/step — loss: 1.3526 — acc: 0.703410000/10000 [========] — 0s 22us/step In order to use the model we can download another set of images (different o the training images) with the following code: _, (x_test_, y_test_)= tf.keras.datasets.mnist.load_data()x_test = x_test_.reshape(10000, 784).astype('float32')/255y_test = to_categorical(y_test_, num_classes=10) At this point, the neural network has been trained and its behavior with new test data can now be evaluated using the evaluation() method. This method returns two values: test_loss, test_acc = model.evaluate(x_test, y_test) These values indicate how well or badly our model behaves with new data that it has never seen. These data have been stored in x_test and y_test when we have performed the mnist.load_data() and we pass them to the method as arguments. In the scope of this post we will only look at one of them, the accuracy: print(‘Test accuracy:’, test_acc)Test accuracy: 0.9018 The accuracy is telling us that the model we have created in this post, applied to data that the model has never seen before, classifies 90% of them correctly. Finally, readers need to know how we can use the model trained in the previous section to make predictions. In our example, it consists in predict which digit represents an image. In order to do this, Keras supply the predict() method. Let’s choose one image (and plot it) in order to predict the number: image = 5_ = plt.imshow(x_test_[image], cmap=plt.cm.binary) and in order to predict the number we can use the following code: import numpy as npprediction = model.predict(x_test_)print("Model prediction: ", np.argmax(prediction[image]) ) And that’s all! Now you are ready for learning how to program a more advanced neural networks (in this post): Convolutional Neural Networks. Ready? towardsdatascience.com Code for this post available at GitHub Originally published in spanish at https://torres.ai on May 02, 2020.
[ { "code": null, "e": 390, "s": 171, "text": "This post will introduce the reader to the basics of neural networks through a case study that using only 10 lines of Python code creates and trains a neural network that recognises handwritten digits in 3 basic steps:" }, { "code": null, "e": 422, "s": 390, "text": "1- Load and Preprocess the Data" }, { "code": null, "e": 442, "s": 422, "text": "2- Define the Model" }, { "code": null, "e": 461, "s": 442, "text": "3- Train the Model" }, { "code": null, "e": 595, "s": 461, "text": "To do this, we will use the TensorFlow Keras API, the most popular library currently in the Deep Learning community. Let’s go for it!" }, { "code": null, "e": 708, "s": 595, "text": "As a case study, we will create a model that allows us to identify handwritten digits such as te following ones:" }, { "code": null, "e": 959, "s": 708, "text": "The goal is to create a mathematical model that, given an image, the model identify the number it represents. For example, if we feed to the model the first image, we would expect it to answer that it is a 5. The next one a 0, next one a 4, an so on." }, { "code": null, "e": 1193, "s": 959, "text": "Actually, we are dealing with a classification problem, which given an image, the model classifies it between 0 and 9. But sometimes, even we can find ourselves with certain doubts, for example, the first image represents a 5 or a 3?" }, { "code": null, "e": 1347, "s": 1193, "text": "For this purpose, the neural network that we will create returns a vector with 10 positions indicating the likelihood of each of the ten possible digits:" }, { "code": null, "e": 1466, "s": 1347, "text": "Yes, in just 10 lines of python code you can create and train a neural network model that classify handwritten digits:" }, { "code": null, "e": 2066, "s": 1466, "text": "1: import tensorflow as tf2: from tensorflow.keras.utils import to_categorical3:(x_train, y_train), _ = tf.keras.datasets.mnist.load_data()4: x_train = x_train.reshape(60000, 784).astype('float32')/2555: y_train = to_categorical(y_train, num_classes=10)6: model = tf.keras.Sequential()7: model.add(tf.keras.layers.Dense(10, activation='sigmoid', input_shape=(784,)))8: model.add(tf.keras.layers.Dense(10, activation='softmax'))9: model.compile(loss=\"categorical_crossentropy\", optimizer=\"sgd\", metrics = ['accuracy'])10: model.fit(x_train, y_train, epochs=10, verbose=0)" }, { "code": null, "e": 2426, "s": 2066, "text": "We used the API Keras of TensorFlow. It is the recommended library for beginners, since its learning curve is very smooth compared to others, and at the moment it is one of the popular middleware to implement neural networks. Keras was developed and maintained by François Chollet, an engineer from Google, and it is currently included in Tensorflow library." }, { "code": null, "e": 2534, "s": 2426, "text": "I suggest to use the Colaboratory offered by Google if you want to execute the code described in this post." }, { "code": null, "e": 3022, "s": 2534, "text": "It is a Google research project created to help to disseminate Machine Learning education and research. It is a Jupyter notebook environment that requires no configuration and runs completely in the Cloud allowing the use different Deep Learning libraries as TensorFlow and PyTorch. The most important feature that distinguishes Colab from other free cloud services is; Colab provides GPU (or TPU) and is totally free. Detailed information about the service can be found on the faq page." }, { "code": null, "e": 3260, "s": 3022, "text": "By default, Colab notebooks run on CPU. You can switch your notebook to run with GPU (or TPU). In order to obtain access to one GPU we need to choose the tab Runtime and then select “Change runtime type” as shown in the following figure:" }, { "code": null, "e": 3367, "s": 3260, "text": "When a pop-up window appears select GPU. Ensure “Hardware accelerator” is set to GPU (the default is CPU)." }, { "code": null, "e": 3489, "s": 3367, "text": "Afterwards, ensure that you are connected to the runtime (there is a green check next to “connected” in the menu ribbon):" }, { "code": null, "e": 3681, "s": 3489, "text": "Now you are able to run the code presented in this post. I suggest to copy & paste the code of this post in a colab notebook in order to see the execution meanwhile you are reading this post." }, { "code": null, "e": 3701, "s": 3681, "text": "Ready? Let’s do it!" }, { "code": null, "e": 3740, "s": 3701, "text": "Code for this post available at GitHub" }, { "code": null, "e": 3860, "s": 3740, "text": "First of all we need to import some Python libraries that we need in order to program our neural network in TensorFlow:" }, { "code": null, "e": 3933, "s": 3860, "text": "import tensorflow as tffrom tensorflow.keras.utils import to_categorical" }, { "code": null, "e": 4433, "s": 3933, "text": "Next step is to loading data that will be used to train our neural network. We will use the MNIST dataset, which can be downloaded from The MNIST database page. This dataset contains 60,000 images of hand-made digits to train the model and it is ideal for entering pattern recognition techniques for the first time without having to spend much time preprocessing and formatting data, both very important and expensive steps in the analysis of data and of special complexity when working with images." }, { "code": null, "e": 4500, "s": 4433, "text": "With TensorFlow this can be done using this line of code (line 3):" }, { "code": null, "e": 4560, "s": 4500, "text": "(x_train, y_train), _ = tf.keras.datasets.mnist.load_data()" }, { "code": null, "e": 4636, "s": 4560, "text": "Optional step: If you want, you can verify the data loaded using this code:" }, { "code": null, "e": 4885, "s": 4636, "text": "import numpy as npimport matplotlib.pyplot as pltfig = plt.figure(figsize=(25, 4))for idx in np.arange(20): ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[]) ax.imshow(x_train[idx], cmap=plt.cm.binary) ax.set_title(str(y_train[idx]))" }, { "code": null, "e": 5192, "s": 4885, "text": "This dataset of black and white images (images contain gray levels) has been normalized to 20×20 pixels while retaining their aspect ratio. Subsequently, the images were centered, calculating the center of mass of these and moving the image in order to position this point in the center of the 28×28 field." }, { "code": null, "e": 5510, "s": 5192, "text": "These MNIST images of 28×28 pixels are represented as an array of numbers whose values range from [0, 255] of type uint8. But it is usual to scale the input values of neural networks to certain ranges. In the example of this post the input values should be scaled to values of type float32 within the interval [0, 1]." }, { "code": null, "e": 5927, "s": 5510, "text": "On the other hand, to facilitate the entry of data into our neural network we must make a transformation of the input (image) from 2 dimensions (2D) to a vector of 1 dimension (1D). That is, the matrix of 28×28 numbers can be represented by a vector (array) of 784 numbers (concatenating row by row), which is the format that accepts as input a densely connected neural network like the one we will see in this post." }, { "code": null, "e": 6006, "s": 5927, "text": "We can achieve these transformations with the following line of code (line 4):" }, { "code": null, "e": 6066, "s": 6006, "text": "x_train = x_train.reshape(60000, 784).astype('float32')/255" }, { "code": null, "e": 6320, "s": 6066, "text": "Furthermore, the dataset has a label for each of the images that indicates what digit it represents (downloaded in y_train). In our case are numbers between 0 and 9 that indicate which digit the image represents,that is, to which class it is associated." }, { "code": null, "e": 6756, "s": 6320, "text": "We need to represent each label with a vector of 10 positions as we presented before, where the position corresponding to the digit that represents the image contains a 1 and the rest contains 0s. This process of transforming the labels into a vector of as many zeros as the number of different labels, and putting a 1 in the index corresponding to the label, is known as one-hot encoding. For example, the number 7 will be encoded as:" }, { "code": null, "e": 6834, "s": 6756, "text": "We can achieve this transformations with the following line of code (line 5):" }, { "code": null, "e": 6884, "s": 6834, "text": "y_train = to_categorical(y_train, num_classes=10)" }, { "code": null, "e": 6977, "s": 6884, "text": "In order to define the model with the Keras’s API we only need these code lines (lines 6–8):" }, { "code": null, "e": 7150, "s": 6977, "text": "model = tf.keras.Sequential()model.add(tf.keras.layers.Dense(10,activation='sigmoid', input_shape=(784,)))model.add(tf.keras.layers.Dense(10,activation='softmax'))" }, { "code": null, "e": 7248, "s": 7150, "text": "However, before to explain these code lines, let me introduce some basic neural network concepts." }, { "code": null, "e": 7434, "s": 7248, "text": "In order to show how a basic neuronal is, let’s suppose a simple example where we have a set of points in a two-dimensional plane and each point is already labeled “square” or “circle”:" }, { "code": null, "e": 7503, "s": 7434, "text": "Given a new point “X“, we want to know what label corresponds to it:" }, { "code": null, "e": 7604, "s": 7503, "text": "A common approach is to draw a line that separates the two groups and use this line as a classifier:" }, { "code": null, "e": 7896, "s": 7604, "text": "In this case, the input data will be represented by vectors of the form (x1, x2) that indicate their coordinates in this two-dimensional space, and our function will return ‘0’ or ‘1’ (above or below the line) to know if it should be classified as “square” or “circle”. It can be defined by:" }, { "code": null, "e": 7940, "s": 7896, "text": "More generally, we can express the line as:" }, { "code": null, "e": 8130, "s": 7940, "text": "To classify input elements X, which in our case are two-dimensional, we must learn a vector of weight W of the same dimension as the input vectors,that is, the vector (w1, w2) and a b bias." }, { "code": null, "e": 8609, "s": 8130, "text": "With these calculated values, we can now construct an artificial neuron to classify a new element X. Basically, the neuron applies this vector W of calculated weights on the values in each dimension of the input element X, and at the end adds the bias b. The result of this will be passed through a non-linear “activation” function to produce a result of ‘0’ or ‘1’. The function of this artificial neuron that we have just defined can be expressed in a more formal way such as:" }, { "code": null, "e": 8911, "s": 8609, "text": "Now, we will need a function that applies a transformation to variable z so that it becomes ‘0’ or ‘1’. Although there are several functions ( “activation functions”), for this example we will use one known as a sigmoid function that returns an actual output value between 0 and 1 for any input value:" }, { "code": null, "e": 9394, "s": 8911, "text": "If we analyze the previous formula, we can see that it always tends to give values close to 0 or 1. If the input z is reasonably large and positive, “e” at minus z is zero and, therefore, the y takes the value of 1. If z has a large and negative value, it turns out that for “e” raised to a large positive number, the denominator of the formula will turn out to be a large number and therefore the value of y will be close to 0. Graphically, the sigmoid function presents this form:" }, { "code": null, "e": 9750, "s": 9394, "text": "So far we have presented how to define an artificial neuron, the simplest architecture that a neural network can have. In particular this architecture is named in the literature of the subject as Perceptron (also called linear threshold unit (LTU)), invented in 1957 by Frank Rosenblatt, and visually summarized in a general way with the following scheme:" }, { "code": null, "e": 9943, "s": 9750, "text": "But before moving forward with the example, we will briefly introduce the form that neural networks usually take when they are constructed from perceptrons like the one we have just presented." }, { "code": null, "e": 10376, "s": 9943, "text": "In the literature of the area we refer to a Multi-Layer Perceptron (MLP) when we find neural networks that have an input layer, one or more layers composed of perceptrons, called hidden layers and a final layer with several perceptrons called the output layer. In general we refer to Deep Learning when the model based on neural networks is composed of multiple hidden layers. Visually it can be presented with the following scheme:" }, { "code": null, "e": 10726, "s": 10376, "text": "MLPs are often used for classification, and specifically when classes are exclusive, as in the case of the classification of digit images (in classes from 0 to 9). In this case, the output layer returns the probability of belonging to each one of the classes, thanks to a function called softmax. Visually we could represent it in the following way:" }, { "code": null, "e": 11169, "s": 10726, "text": "As we mentioned, there are several activation functions in addition to the sigmoid, each with different properties. One of them is the one we just mentioned, the softmax activation function, which will be useful to present an example of simple neural network to classify in more than two classes. For the moment we can consider the softmax function as a generalization of the sigmoid function that allows us to classify more than two classes." }, { "code": null, "e": 12032, "s": 11169, "text": "We will solve the problem in a way that, given an input image, we will obtain the probabilities that it is each of the 10 possible digits. In this way, we will have a model that, for example, could predict a five in an image, but only being sure in 70% that it is a five. Due to the stroke of the upper part of the number in this image, it seems that it could become an three in a 20% chance and it could even give a certain probability to any other number. Although in this particular case we will consider that the prediction of our model is a five since it is the one with the highest probability, this approach of using a probability distribution can give us a better idea of how confident we are of our prediction. This is good in this case, where the numbers are made by hand, and surely in many of them, we cannot recognize the digits with 100% certainty." }, { "code": null, "e": 12406, "s": 12032, "text": "Therefore, for this example of classification we will obtain, for each input example, an output vector with the probability distribution over a set of mutually exclusive labels. That is, a vector of 10 probabilities each corresponding to a digit and also the sum of all these 10 probabilities results in the value of 1 (the probabilities will be expressed between 0 and 1)." }, { "code": null, "e": 12711, "s": 12406, "text": "As we have already advanced, this is achieved through the use of an output layer in our neural network with the softmax activation function, in which each neuron in this softmax layer depends on the outputs of all the other neurons in the layer, since that the sum of the output of all of them must be 1." }, { "code": null, "e": 12980, "s": 12711, "text": "But how does the softmax activation function work? The softmax function is based on calculating “the evidence” that a certain image belongs to a particular class and then these evidences are converted into probabilities that it belongs to each of the possible classes." }, { "code": null, "e": 13208, "s": 12980, "text": "An approach to measure the evidence that a certain image belongs to a particular class is to make a weighted sum of the evidence of belonging to each of its pixels to that class. To explain the idea I will use a visual example." }, { "code": null, "e": 13495, "s": 13208, "text": "Let’s suppose that we already have the model learned for the number zero. For the moment, we can consider a model as “something” that contains information to know if a number is of a certain class. In this case, for the number zero, suppose we have a model like the one presented below:" }, { "code": null, "e": 13785, "s": 13495, "text": "In this case, with a matrix of 28×28 pixels, where the pixels in red represent negative weights (i.e., reduce the evidence that it belongs), while that the pixels in blue represent positive weights (the evidence of which is greater increases). The white color represents the neutral value." }, { "code": null, "e": 14268, "s": 13785, "text": "Let’s imagine that we trace a zero over it. In general, the trace of our zero would fall on the blue zone (remember that we are talking about images that have been normalized to 20×20 pixels and later centered on a 28×28 image). It is quite evident that if our stroke goes over the red zone, it is most likely that we are not writing a zero; therefore, using a metric based on adding if we pass through the blue zone and subtracting if we pass through the red zone seems reasonable." }, { "code": null, "e": 14575, "s": 14268, "text": "To confirm that it is a good metric, let’s imagine now that we draw a three; it is clear that the red zone of the center of the previous model that we used for the zero will penalize the aforementioned metric since, as we can see in the left part of the following figure, when writing a three we pass over:" }, { "code": null, "e": 14831, "s": 14575, "text": "But on the other hand, if the reference model is the one corresponding to number 3 as shown in the right part of the previous figure, we can see that, in general, the different possible traces that represent a three are mostly maintained in the blue zone." }, { "code": null, "e": 14993, "s": 14831, "text": "I hope that the reader, seeing this visual example, already intuits how the approximation of the weights indicated above allows us to estimate what number it is." }, { "code": null, "e": 15364, "s": 14993, "text": "Once the evidence of belonging to each of the 10 classes has been calculated, these must be converted into probabilities whose sum of all their components add 1. For this, softmax uses the exponential value of the calculated evidence and then normalizes them so that the sum equates to one, forming a probability distribution. The probability of belonging to class i is:" }, { "code": null, "e": 15818, "s": 15364, "text": "Intuitively, the effect obtained with the use of exponentials is that one more unit of evidence has a multiplier effect and one unit less has the inverse effect. The interesting thing about this function is that a good prediction will have a single entry in the vector with a value close to 1, while the remaining entries will be close to 0. In a weak prediction, there will be several possible labels, which will have more or less the same probability." }, { "code": null, "e": 16151, "s": 15818, "text": "The main data structure in Keras is the Sequential class, which allows the creation of a basic neural network. Keras also offers an API that allows implementing more complex models in the form of a graph that can have multiple inputs, multiple outputs, with arbitrary connections in between, but it is beyond the scope of this post." }, { "code": null, "e": 16305, "s": 16151, "text": "The Sequential class of the Keras library is a wrapper for the sequential neural network model that Keras offers and can be created in the following way:" }, { "code": null, "e": 16478, "s": 16305, "text": "model = tf.keras.Sequential()model.add(tf.keras.layers.Dense(10,activation='sigmoid', input_shape=(784,)))model.add(tf.keras.layers.Dense(10,activation='softmax'))" }, { "code": null, "e": 16749, "s": 16478, "text": "In this case, the model in Keras is considered as a sequence of layers and each of them gradually “distills” the input data to obtain the desired output.In Keras we can find all the required types of layers that can be easily added to the model through the add() method." }, { "code": null, "e": 17016, "s": 16749, "text": "Here, the neural network has been defined as a sequence of two layers that are densely connected (or fully connected), meaning that all the neurons in each layer are connected to all the neurons in the next layer. Visually we could represent it in the following way:" }, { "code": null, "e": 17199, "s": 17016, "text": "In the previous code we explicitly express in the input_shape argument of the first layer what the input data is like: a tensor that indicates that we have 784 features of the model." }, { "code": null, "e": 17591, "s": 17199, "text": "A very interesting characteristic of the Keras library is that it will automatically deduce the shape of the tensors between layers after the first one. This means that the programmer only has to establish this information for the first of them. Also, for each layer we indicate the number of nodes that it has and the activation function that we will apply in it (in this example, sigmoid)." }, { "code": null, "e": 18025, "s": 17591, "text": "The second layer in this example is a softmax layer of 10 neurons, which means that it will return a matrix of 10 probability values representing the 10 possible digits (in general, the output layer of a classification network will have as many neurons as classes, except in a binary classification, where only one neuron is needed). Each value will be the probability that the image of the current digit belongs to each one of them." }, { "code": null, "e": 18134, "s": 18025, "text": "Optional step: A very useful method that Keras provides to check the architecture of our model is summary():" }, { "code": null, "e": 18569, "s": 18134, "text": "model.summary()_________________________________________________________________Layer (type) Output Shape Param #=================================================================dense_1 (Dense) (None, 10) 7850_________________________________________________________________dense_2 (Dense) (None, 10) 110=================================================================Total params: 7,960Trainable params: 7,960Non-trainable params: 0" }, { "code": null, "e": 18750, "s": 18569, "text": "For our simple example, we see that it indicates that 7,960 parameters are required (column Param #), which correspond to 7,850 parameters to the first layer and 110 to the second." }, { "code": null, "e": 19255, "s": 18750, "text": "In the first layer, for each neuron i (between 0 and 9) we require 784 parameters for the weights wij and therefore 10×784 parameters to store the weights of the 10 neurons. In addition to the 10 additional parameters for the 10 bj biases corresponding to each one of them. In the second layer, being a softmax function, it is required to connect all 10 neurons with the 10 neurons of the previous layer. Therefore 10×10 wi parameters are required and in addition 10 bj biases corresponding to each node." }, { "code": null, "e": 19678, "s": 19255, "text": "The details of the arguments that we can indicate for the dense layer can be found in the Keras manual. In our example, the most relevant ones appear in the example. The first argument indicates the number of neurons in the layer; the following is the activation function that we will use in it. In this post we discuss in more detail other possible activation functions beyond the two presented here: sigmoid and softmax." }, { "code": null, "e": 19749, "s": 19678, "text": "We’re almost done, we just have to explain the last two lines of code:" }, { "code": null, "e": 19903, "s": 19749, "text": "model.compile(loss=\"categorical_crossentropy\", optimizer=\"sgd\", metrics = ['accuracy'])model.fit(x_train, y_train, epochs=10, verbose=0)" }, { "code": null, "e": 20462, "s": 19903, "text": "The way how the neural network can learn the weights W and the biases b of the neurons is an iterative process for all the known labeled input examples, comparing the value of its label estimated through the model, with the expected value of the label of each element. After each iteration, the parameter values are adjusted in such a way that the discordance (error) between the estimated value for the image and the actual value, is becoming smaller. The following scheme wants to visually summarize the learning process of one perceptron in a general way:" }, { "code": null, "e": 20608, "s": 20462, "text": "We can configure how this learning process will be with the compile() method, with which we can specify some properties through method arguments." }, { "code": null, "e": 21010, "s": 20608, "text": "The first of these arguments is the loss function that we will use to evaluate the degree of error between calculated outputs and the desired outputs of the training data. On the other hand, we specify an optimizer that is the way we have to specify the optimization algorithm that allows the neural network to calculate the weights of the parameters from the input data and the defined loss function." }, { "code": null, "e": 21327, "s": 21010, "text": "And finally we must indicate the metric that we will use to monitor the learning process of our neural network. In this first example we will only consider the accuracy (fraction of images that are correctly classified). For example, in our case we can specify the following arguments in compile() method to test it:" }, { "code": null, "e": 21443, "s": 21327, "text": "model.compile(loss=\"categorical_crossentropy\", optimizer=\"sgd\", metrics = ['accuracy'])" }, { "code": null, "e": 21674, "s": 21443, "text": "In this example we specify that the loss function is categorical_crossentropy, the optimizer used is the stocastic gradient descent (sgd) and the metric is accuracy, with which we will evaluate the percentage of correct guesses.ç" }, { "code": null, "e": 21754, "s": 21674, "text": "In a new post the reader could enter in more detail about the learning process." }, { "code": null, "e": 21967, "s": 21754, "text": "Once our model has been defined and the learning method configured, it is ready to be trained. For this we can train or “adjust” the model to the training data available by invoking the fit() method of the model:" }, { "code": null, "e": 22017, "s": 21967, "text": "model.fit(x_train, y_train, epochs=10, verbose=0)" }, { "code": null, "e": 22349, "s": 22017, "text": "In the first two arguments we have indicated the data with which we will train the model in the form of Numpy arrays. The batch_size argument indicates the number of data that we will use for each update of the model parameters and with epochs we are indicating the number of times we will use all the data in the learning process." }, { "code": null, "e": 23050, "s": 22349, "text": "This method finds the value of the parameters of the network through the iterative training algorithm that we mentioned. Roughly, in each iteration of this algorithm, this algorith takes training data from x_train, passes them through the neural network (with the values that their parameters have at that moment), compares the obtained result with the expected one(indicated in y_train) and calculates the loss to guide the adjustment process of the model parameters, which intuitively consists of applying the optimizer specified above in the compile() method to calculate a new value of each one of the model parameters (weights and biases)in each iteration in such a way that the loss is reduced." }, { "code": null, "e": 23268, "s": 23050, "text": "This is the method that, as we will see, may take longer and Keras allows us to see its progress using the verbose argument (by default, equal to 1), in addition to indicating an estimate of how long each epoch takes:" }, { "code": null, "e": 23681, "s": 23268, "text": "Epoch 1/560000/60000 [========] — 1s 15us/step — loss: 2.1822 — acc: 0.2916Epoch 2/560000/60000 [========] — 1s 12us/step — loss: 1.9180 — acc: 0.5283Epoch 3/560000/60000 [========] — 1s 13us/step — loss: 1.6978 — acc: 0.5937Epoch 4/560000/60000 [========] — 1s 14us/step — loss: 1.5102 — acc: 0.6537Epoch 5/560000/60000 [========] — 1s 13us/step — loss: 1.3526 — acc: 0.703410000/10000 [========] — 0s 22us/step" }, { "code": null, "e": 23804, "s": 23681, "text": "In order to use the model we can download another set of images (different o the training images) with the following code:" }, { "code": null, "e": 23969, "s": 23804, "text": "_, (x_test_, y_test_)= tf.keras.datasets.mnist.load_data()x_test = x_test_.reshape(10000, 784).astype('float32')/255y_test = to_categorical(y_test_, num_classes=10)" }, { "code": null, "e": 24140, "s": 23969, "text": "At this point, the neural network has been trained and its behavior with new test data can now be evaluated using the evaluation() method. This method returns two values:" }, { "code": null, "e": 24193, "s": 24140, "text": "test_loss, test_acc = model.evaluate(x_test, y_test)" }, { "code": null, "e": 24502, "s": 24193, "text": "These values indicate how well or badly our model behaves with new data that it has never seen. These data have been stored in x_test and y_test when we have performed the mnist.load_data() and we pass them to the method as arguments. In the scope of this post we will only look at one of them, the accuracy:" }, { "code": null, "e": 24557, "s": 24502, "text": "print(‘Test accuracy:’, test_acc)Test accuracy: 0.9018" }, { "code": null, "e": 24717, "s": 24557, "text": "The accuracy is telling us that the model we have created in this post, applied to data that the model has never seen before, classifies 90% of them correctly." }, { "code": null, "e": 24953, "s": 24717, "text": "Finally, readers need to know how we can use the model trained in the previous section to make predictions. In our example, it consists in predict which digit represents an image. In order to do this, Keras supply the predict() method." }, { "code": null, "e": 25022, "s": 24953, "text": "Let’s choose one image (and plot it) in order to predict the number:" }, { "code": null, "e": 25082, "s": 25022, "text": "image = 5_ = plt.imshow(x_test_[image], cmap=plt.cm.binary)" }, { "code": null, "e": 25148, "s": 25082, "text": "and in order to predict the number we can use the following code:" }, { "code": null, "e": 25260, "s": 25148, "text": "import numpy as npprediction = model.predict(x_test_)print(\"Model prediction: \", np.argmax(prediction[image]) )" }, { "code": null, "e": 25276, "s": 25260, "text": "And that’s all!" }, { "code": null, "e": 25408, "s": 25276, "text": "Now you are ready for learning how to program a more advanced neural networks (in this post): Convolutional Neural Networks. Ready?" }, { "code": null, "e": 25431, "s": 25408, "text": "towardsdatascience.com" }, { "code": null, "e": 25470, "s": 25431, "text": "Code for this post available at GitHub" } ]
Creating A Chess AI using Deep Learning | by Victor Sim | Towards Data Science
When Gary Kasparov was dethroned by IBM’s Deep Blue chess algorithm, the algorithm did not use Machine Learning, or at least in the way that we define Machine Learning today. This article aims to use Neural Networks to create a successful chess AI, by using Neural Networks, a newer form of machine learning algorithms. Using a chess dataset with over 20,000 instances (contact at victorwtsim@gmail.com for dataset), the Neural Network should output a move, when given a chess-board. Here is the github repo (ads) for the code: import osimport chessimport numpy as npimport pandas as pdfrom tensorflow import kerasfrom tensorflow.keras import layers These libraries are the prerequisites to create the program: os and pandas are to access the dataset, python-chess is an “instant” chess-board to test the neural network. Numpy is necessary to perform matrix manipulation. Keras is to create the Neural Network. os.chdir('XXXXXXXXXXX')df = pd.read_csv('chess_normalized.csv')data = df['moves'].tolist()[:500]split_data = []indice = 500 All we need for this project is the pgn of each chessgame from the dataset. Please change the directory path for the os.chdir function to access the directory that the dataset is in. chess_dict = { 'p' : [1,0,0,0,0,0,0,0,0,0,0,0], 'P' : [0,0,0,0,0,0,1,0,0,0,0,0], 'n' : [0,1,0,0,0,0,0,0,0,0,0,0], 'N' : [0,0,0,0,0,0,0,1,0,0,0,0], 'b' : [0,0,1,0,0,0,0,0,0,0,0,0], 'B' : [0,0,0,0,0,0,0,0,1,0,0,0], 'r' : [0,0,0,1,0,0,0,0,0,0,0,0], 'R' : [0,0,0,0,0,0,0,0,0,1,0,0], 'q' : [0,0,0,0,1,0,0,0,0,0,0,0], 'Q' : [0,0,0,0,0,0,0,0,0,0,1,0], 'k' : [0,0,0,0,0,1,0,0,0,0,0,0], 'K' : [0,0,0,0,0,0,0,0,0,0,0,1], '.' : [0,0,0,0,0,0,0,0,0,0,0,0],}alpha_dict = { 'a' : [0,0,0,0,0,0,0], 'b' : [1,0,0,0,0,0,0], 'c' : [0,1,0,0,0,0,0], 'd' : [0,0,1,0,0,0,0], 'e' : [0,0,0,1,0,0,0], 'f' : [0,0,0,0,1,0,0], 'g' : [0,0,0,0,0,1,0], 'h' : [0,0,0,0,0,0,1],}number_dict = { 1 : [0,0,0,0,0,0,0], 2 : [1,0,0,0,0,0,0], 3 : [0,1,0,0,0,0,0], 4 : [0,0,1,0,0,0,0], 5 : [0,0,0,1,0,0,0], 6 : [0,0,0,0,1,0,0], 7 : [0,0,0,0,0,1,0], 8 : [0,0,0,0,0,0,1],} One-hot encoding is necessary to make sure that no features or certain instances are weighted higher than others, therefore creating a bias in data and hindering the learning of the network. Each move and configuration in the pgn values, is changed into a matrix with a 1 in the appropriate column. def make_matrix(board): pgn = board.epd() foo = [] pieces = pgn.split(" ", 1)[0] rows = pieces.split("/") for row in rows: foo2 = [] for thing in row: if thing.isdigit(): for i in range(0, int(thing)): foo2.append('.') else: foo2.append(thing) foo.append(foo2) return foodef translate(matrix,chess_dict): rows = [] for row in matrix: terms = [] for term in row: terms.append(chess_dict[term]) rows.append(terms) return rows These two functions are the two preliminary functions to translate the board into ascii form and then into a matrix. for point in data[:indice]: point = point.split() split_data.append(point) data = []for game in split_data: board = chess.Board() for move in game: board_ready = board.copy() data.append(board.copy()) board.push_san(move)trans_data = []for board in data: matrix = make_matrix(board) trans = translate(matrix,chess_dict) trans_data.append(trans)pieces = []alphas = []numbers = [] For the input of the neural network, the board itself is enough: The board itself holds temporal data, although not in the correct order. Adding multiple boards to form temporal data would be too computationally intensive for my poor 8GB of RAM to handle. Putting the raw input as the moves would remove temporal data and prevent the convolutional layers to extract features from the data. In the first line, the variable indice is optional. I added this variable to decrease the data size to test if the network and the data were functional, before scaling up. true_data = flatten(split_data)for i in range(len(true_data)): try: term = flatten(split_data)[i] original = term[:] term = term.replace('x','') term = term.replace('#','') term = term.replace('+','') if len(term) == 2: piece = 'p' else: piece = term[0] alpha = term[-2] number = term[-1] pieces.append(chess_dict[piece]) alphas.append(alpha_dict[alpha]) numbers.append(number_dict[int(number)]) except: pass This code removes all instances that cannot be one-hot encoded, by using the try except function and removing all extra notation of a check or a checkmate. Unfortunately, this means that the program will never learn to castle. board_inputs = keras.Input(shape=(8, 8, 12))conv1= layers.Conv2D(10, 3, activation='relu')conv2 = layers.Conv2D(10, 3, activation='relu')pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)flatten = keras.layers.Flatten(data_format=None)x = conv1(board_inputs)x = pooling1(x)x = conv2(x)x = flatten(x)piece_output = layers.Dense(12,name = 'piece')(x)model_pieces = keras.Model(inputs=board_inputs, outputs=piece_output, name="chess_ai_v3")earlystop = keras.callbacks.EarlyStopping(monitor='loss', min_delta=0, patience=250, verbose=0, mode='auto', baseline=None, restore_best_weights=True)model_pieces.compile( loss=keras.losses.mse, optimizer=keras.optimizers.Adam(), metrics=None,)model_pieces.fit(trans_data[:len(pieces)],pieces[:len(pieces)],batch_size=64, epochs=100,callbacks = [earlystop])clear_output()board_inputs = keras.Input(shape=(8, 8, 12))conv1= layers.Conv2D(10, 3, activation='relu')conv2 = layers.Conv2D(10, 3, activation='relu')pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)flatten = keras.layers.Flatten(data_format=None)x = conv1(board_inputs)x = pooling1(x)x = conv2(x)x = flatten(x)alpha_output = layers.Dense(7,name = 'alpha')(x)model_alpha = keras.Model(inputs=board_inputs, outputs=alpha_output, name="chess_ai_v3")earlystop = keras.callbacks.EarlyStopping(monitor='loss', min_delta=0, patience=250, verbose=0, mode='auto', baseline=None, restore_best_weights=True)model_alpha.compile( loss=keras.losses.mse, optimizer=keras.optimizers.Adam(), metrics=None,)model_alpha.fit(trans_data[:len(alphas)],alphas[:len(alphas)],batch_size=64, epochs=100,callbacks = [earlystop])clear_output()board_inputs = keras.Input(shape=(8, 8, 12))conv1= layers.Conv2D(10, 3, activation='relu')conv2 = layers.Conv2D(10, 3, activation='relu')pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)flatten = keras.layers.Flatten(data_format=None)x = conv1(board_inputs)x = pooling1(x)x = conv2(x)x = flatten(x)numbers_output = layers.Dense(7,name = 'number')(x)model_number = keras.Model(inputs=board_inputs, outputs=numbers_output, name="chess_ai_v3")earlystop = keras.callbacks.EarlyStopping(monitor='loss', min_delta=0, patience=250, verbose=0, mode='auto', baseline=None, restore_best_weights=True)model_number.compile( loss=keras.losses.mse, optimizer=keras.optimizers.Adam(), metrics=None,)model_number.fit(trans_data[:len(numbers)],numbers[:len(numbers)],batch_size=64, epochs=100,callbacks = [earlystop])clear_output() The Neural Network is a Convolutional Neural Network, with Max Pooling to extract features from the data. This neural network structure is over-laid for each of the three variables to be predicted: The piece, the “alpha” (the column), and the “number” the row. There are some hard-hitting disadvantages that I could not avoid when designing the Neural Network: The Neural Network might predict moves that are not legal The topology of the Neural Network creates a disconnect for predicting each feature If you think you can solve it, feel free to use this code to better my program! new_chess_dict = {}new_alpha_dict = {}new_number_dict = {}for term in chess_dict: definition = tuple(chess_dict[term]) new_chess_dict[definition] = term new_chess_dict[term] = definition for term in alpha_dict: definition = tuple(alpha_dict[term]) new_alpha_dict[definition] = term new_alpha_dict[term] = definition for term in number_dict: definition = tuple(number_dict[term]) new_number_dict[definition] = term new_number_dict[term] = definitiondata = np.reshape(trans_data[0],(1,8,8,12))pred = model_pieces.predict(data)def translate_pred(pred): translation = np.zeros(pred.shape) index = pred[0].tolist().index(max(pred[0])) translation[0][index] = 1 return translation[0]piece = translate_pred(model_pieces.predict(data))alpha = translate_pred(model_alpha.predict(data))number = translate_pred(model_alpha.predict(data))piece_pred = new_chess_dict[tuple(piece)]alpha_pred = new_alpha_dict[tuple(alpha)]number_pred = new_number_dict[tuple(number)]move =str(piece_pred)+str(alpha_pred)+str(number_pred) To decode the predictions from each of the respective neural networks, one must create inverse dictionaries: This means to take the one-hot encodings and translate them into strings. This is detailed by the new_chess_dict, new_alpha_dict and new_number_dict dictionaries created by reversing the term and definition. With this last bit of code, the program is complete! The Neural Network, although functional in making predictions, frequently predicts illegal moves, as the range of moves are continuous for ranges of moves that are not legal. I could not create a new solution for this, but thought of a new way to implement a chess AI with a different algorithm: Genetic Algorithms! Stay tuned for that! If you want to see more of my content, click this link.
[ { "code": null, "e": 347, "s": 172, "text": "When Gary Kasparov was dethroned by IBM’s Deep Blue chess algorithm, the algorithm did not use Machine Learning, or at least in the way that we define Machine Learning today." }, { "code": null, "e": 492, "s": 347, "text": "This article aims to use Neural Networks to create a successful chess AI, by using Neural Networks, a newer form of machine learning algorithms." }, { "code": null, "e": 656, "s": 492, "text": "Using a chess dataset with over 20,000 instances (contact at victorwtsim@gmail.com for dataset), the Neural Network should output a move, when given a chess-board." }, { "code": null, "e": 700, "s": 656, "text": "Here is the github repo (ads) for the code:" }, { "code": null, "e": 822, "s": 700, "text": "import osimport chessimport numpy as npimport pandas as pdfrom tensorflow import kerasfrom tensorflow.keras import layers" }, { "code": null, "e": 1083, "s": 822, "text": "These libraries are the prerequisites to create the program: os and pandas are to access the dataset, python-chess is an “instant” chess-board to test the neural network. Numpy is necessary to perform matrix manipulation. Keras is to create the Neural Network." }, { "code": null, "e": 1207, "s": 1083, "text": "os.chdir('XXXXXXXXXXX')df = pd.read_csv('chess_normalized.csv')data = df['moves'].tolist()[:500]split_data = []indice = 500" }, { "code": null, "e": 1390, "s": 1207, "text": "All we need for this project is the pgn of each chessgame from the dataset. Please change the directory path for the os.chdir function to access the directory that the dataset is in." }, { "code": null, "e": 2305, "s": 1390, "text": "chess_dict = { 'p' : [1,0,0,0,0,0,0,0,0,0,0,0], 'P' : [0,0,0,0,0,0,1,0,0,0,0,0], 'n' : [0,1,0,0,0,0,0,0,0,0,0,0], 'N' : [0,0,0,0,0,0,0,1,0,0,0,0], 'b' : [0,0,1,0,0,0,0,0,0,0,0,0], 'B' : [0,0,0,0,0,0,0,0,1,0,0,0], 'r' : [0,0,0,1,0,0,0,0,0,0,0,0], 'R' : [0,0,0,0,0,0,0,0,0,1,0,0], 'q' : [0,0,0,0,1,0,0,0,0,0,0,0], 'Q' : [0,0,0,0,0,0,0,0,0,0,1,0], 'k' : [0,0,0,0,0,1,0,0,0,0,0,0], 'K' : [0,0,0,0,0,0,0,0,0,0,0,1], '.' : [0,0,0,0,0,0,0,0,0,0,0,0],}alpha_dict = { 'a' : [0,0,0,0,0,0,0], 'b' : [1,0,0,0,0,0,0], 'c' : [0,1,0,0,0,0,0], 'd' : [0,0,1,0,0,0,0], 'e' : [0,0,0,1,0,0,0], 'f' : [0,0,0,0,1,0,0], 'g' : [0,0,0,0,0,1,0], 'h' : [0,0,0,0,0,0,1],}number_dict = { 1 : [0,0,0,0,0,0,0], 2 : [1,0,0,0,0,0,0], 3 : [0,1,0,0,0,0,0], 4 : [0,0,1,0,0,0,0], 5 : [0,0,0,1,0,0,0], 6 : [0,0,0,0,1,0,0], 7 : [0,0,0,0,0,1,0], 8 : [0,0,0,0,0,0,1],}" }, { "code": null, "e": 2604, "s": 2305, "text": "One-hot encoding is necessary to make sure that no features or certain instances are weighted higher than others, therefore creating a bias in data and hindering the learning of the network. Each move and configuration in the pgn values, is changed into a matrix with a 1 in the appropriate column." }, { "code": null, "e": 3184, "s": 2604, "text": "def make_matrix(board): pgn = board.epd() foo = [] pieces = pgn.split(\" \", 1)[0] rows = pieces.split(\"/\") for row in rows: foo2 = [] for thing in row: if thing.isdigit(): for i in range(0, int(thing)): foo2.append('.') else: foo2.append(thing) foo.append(foo2) return foodef translate(matrix,chess_dict): rows = [] for row in matrix: terms = [] for term in row: terms.append(chess_dict[term]) rows.append(terms) return rows" }, { "code": null, "e": 3301, "s": 3184, "text": "These two functions are the two preliminary functions to translate the board into ascii form and then into a matrix." }, { "code": null, "e": 3725, "s": 3301, "text": "for point in data[:indice]: point = point.split() split_data.append(point) data = []for game in split_data: board = chess.Board() for move in game: board_ready = board.copy() data.append(board.copy()) board.push_san(move)trans_data = []for board in data: matrix = make_matrix(board) trans = translate(matrix,chess_dict) trans_data.append(trans)pieces = []alphas = []numbers = []" }, { "code": null, "e": 3981, "s": 3725, "text": "For the input of the neural network, the board itself is enough: The board itself holds temporal data, although not in the correct order. Adding multiple boards to form temporal data would be too computationally intensive for my poor 8GB of RAM to handle." }, { "code": null, "e": 4287, "s": 3981, "text": "Putting the raw input as the moves would remove temporal data and prevent the convolutional layers to extract features from the data. In the first line, the variable indice is optional. I added this variable to decrease the data size to test if the network and the data were functional, before scaling up." }, { "code": null, "e": 4816, "s": 4287, "text": "true_data = flatten(split_data)for i in range(len(true_data)): try: term = flatten(split_data)[i] original = term[:] term = term.replace('x','') term = term.replace('#','') term = term.replace('+','') if len(term) == 2: piece = 'p' else: piece = term[0] alpha = term[-2] number = term[-1] pieces.append(chess_dict[piece]) alphas.append(alpha_dict[alpha]) numbers.append(number_dict[int(number)]) except: pass" }, { "code": null, "e": 4972, "s": 4816, "text": "This code removes all instances that cannot be one-hot encoded, by using the try except function and removing all extra notation of a check or a checkmate." }, { "code": null, "e": 5043, "s": 4972, "text": "Unfortunately, this means that the program will never learn to castle." }, { "code": null, "e": 7936, "s": 5043, "text": "board_inputs = keras.Input(shape=(8, 8, 12))conv1= layers.Conv2D(10, 3, activation='relu')conv2 = layers.Conv2D(10, 3, activation='relu')pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding=\"valid\", data_format=None,)pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding=\"valid\", data_format=None,)flatten = keras.layers.Flatten(data_format=None)x = conv1(board_inputs)x = pooling1(x)x = conv2(x)x = flatten(x)piece_output = layers.Dense(12,name = 'piece')(x)model_pieces = keras.Model(inputs=board_inputs, outputs=piece_output, name=\"chess_ai_v3\")earlystop = keras.callbacks.EarlyStopping(monitor='loss', min_delta=0, patience=250, verbose=0, mode='auto', baseline=None, restore_best_weights=True)model_pieces.compile( loss=keras.losses.mse, optimizer=keras.optimizers.Adam(), metrics=None,)model_pieces.fit(trans_data[:len(pieces)],pieces[:len(pieces)],batch_size=64, epochs=100,callbacks = [earlystop])clear_output()board_inputs = keras.Input(shape=(8, 8, 12))conv1= layers.Conv2D(10, 3, activation='relu')conv2 = layers.Conv2D(10, 3, activation='relu')pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding=\"valid\", data_format=None,)pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding=\"valid\", data_format=None,)flatten = keras.layers.Flatten(data_format=None)x = conv1(board_inputs)x = pooling1(x)x = conv2(x)x = flatten(x)alpha_output = layers.Dense(7,name = 'alpha')(x)model_alpha = keras.Model(inputs=board_inputs, outputs=alpha_output, name=\"chess_ai_v3\")earlystop = keras.callbacks.EarlyStopping(monitor='loss', min_delta=0, patience=250, verbose=0, mode='auto', baseline=None, restore_best_weights=True)model_alpha.compile( loss=keras.losses.mse, optimizer=keras.optimizers.Adam(), metrics=None,)model_alpha.fit(trans_data[:len(alphas)],alphas[:len(alphas)],batch_size=64, epochs=100,callbacks = [earlystop])clear_output()board_inputs = keras.Input(shape=(8, 8, 12))conv1= layers.Conv2D(10, 3, activation='relu')conv2 = layers.Conv2D(10, 3, activation='relu')pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding=\"valid\", data_format=None,)pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding=\"valid\", data_format=None,)flatten = keras.layers.Flatten(data_format=None)x = conv1(board_inputs)x = pooling1(x)x = conv2(x)x = flatten(x)numbers_output = layers.Dense(7,name = 'number')(x)model_number = keras.Model(inputs=board_inputs, outputs=numbers_output, name=\"chess_ai_v3\")earlystop = keras.callbacks.EarlyStopping(monitor='loss', min_delta=0, patience=250, verbose=0, mode='auto', baseline=None, restore_best_weights=True)model_number.compile( loss=keras.losses.mse, optimizer=keras.optimizers.Adam(), metrics=None,)model_number.fit(trans_data[:len(numbers)],numbers[:len(numbers)],batch_size=64, epochs=100,callbacks = [earlystop])clear_output()" }, { "code": null, "e": 8197, "s": 7936, "text": "The Neural Network is a Convolutional Neural Network, with Max Pooling to extract features from the data. This neural network structure is over-laid for each of the three variables to be predicted: The piece, the “alpha” (the column), and the “number” the row." }, { "code": null, "e": 8297, "s": 8197, "text": "There are some hard-hitting disadvantages that I could not avoid when designing the Neural Network:" }, { "code": null, "e": 8355, "s": 8297, "text": "The Neural Network might predict moves that are not legal" }, { "code": null, "e": 8439, "s": 8355, "text": "The topology of the Neural Network creates a disconnect for predicting each feature" }, { "code": null, "e": 8519, "s": 8439, "text": "If you think you can solve it, feel free to use this code to better my program!" }, { "code": null, "e": 9571, "s": 8519, "text": "new_chess_dict = {}new_alpha_dict = {}new_number_dict = {}for term in chess_dict: definition = tuple(chess_dict[term]) new_chess_dict[definition] = term new_chess_dict[term] = definition for term in alpha_dict: definition = tuple(alpha_dict[term]) new_alpha_dict[definition] = term new_alpha_dict[term] = definition for term in number_dict: definition = tuple(number_dict[term]) new_number_dict[definition] = term new_number_dict[term] = definitiondata = np.reshape(trans_data[0],(1,8,8,12))pred = model_pieces.predict(data)def translate_pred(pred): translation = np.zeros(pred.shape) index = pred[0].tolist().index(max(pred[0])) translation[0][index] = 1 return translation[0]piece = translate_pred(model_pieces.predict(data))alpha = translate_pred(model_alpha.predict(data))number = translate_pred(model_alpha.predict(data))piece_pred = new_chess_dict[tuple(piece)]alpha_pred = new_alpha_dict[tuple(alpha)]number_pred = new_number_dict[tuple(number)]move =str(piece_pred)+str(alpha_pred)+str(number_pred)" }, { "code": null, "e": 9888, "s": 9571, "text": "To decode the predictions from each of the respective neural networks, one must create inverse dictionaries: This means to take the one-hot encodings and translate them into strings. This is detailed by the new_chess_dict, new_alpha_dict and new_number_dict dictionaries created by reversing the term and definition." }, { "code": null, "e": 9941, "s": 9888, "text": "With this last bit of code, the program is complete!" }, { "code": null, "e": 10278, "s": 9941, "text": "The Neural Network, although functional in making predictions, frequently predicts illegal moves, as the range of moves are continuous for ranges of moves that are not legal. I could not create a new solution for this, but thought of a new way to implement a chess AI with a different algorithm: Genetic Algorithms! Stay tuned for that!" } ]
Validate an IP Address | Practice | GeeksforGeeks
Write a program to Validate an IPv4 Address. According to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1 . A valid IPv4 Address is of the form x1.x2.x3.x4 where 0 <= (x1, x2, x3, x4) <= 255. Thus, we can write the generalized form of an IPv4 address as (0-255).(0-255).(0-255).(0-255). Note: Here we are considering numbers only from 0 to 255 and any additional leading zeroes will be considered invalid. Your task is to complete the function isValid which returns 1 if the given IPv4 address is valid else returns 0. The function takes the IPv4 address as the only argument in the form of string. Example 1: Input: IPv4 address = 222.111.111.111 Output: 1 Explanation: Here, the IPv4 address is as per the criteria mentioned and also all four decimal numbers lies in the mentioned range. Example 2: Input: IPv4 address = 5555..555 Output: 0 Explanation: 5555..555 is not a valid IPv4 address, as the middle two portions are missing. Your Task: Complete the function isValid() which takes the address in the form of string s as an input parameter and returns 1 if this is a valid address otherwise returns 0. Expected Time Complexity: O(N), N = length of the string. Expected Auxiliary Space: O(1) Constraints: 1<=length of string <=50 Note: The Input/Output format and Example given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 mukesh kumar3 days ago class Solution { public: int isValid(string s) { if(s.size() < 7) //minimum lenght of ip address 0.0.0.0 return 0; //check for minimum and maximum three dots size_t _count = std::count(s.begin(), s.end(), '.'); if( _count != 3) return 0; string tmpStr(s); string currVal; int currValInt; int pos; while(_count > 0) { pos = tmpStr.find('.'); currVal = tmpStr.substr(0, pos); if(!isdigit(currVal[0])) //to check a.b.c.d return 0; currValInt = stoi(currVal); if(currValInt == 0 && currVal.size()>1) //000.000.000.000 break; if(currVal.size() > 3) //3343.46546.323.11 break; if(currValInt > 255 || currValInt < 0 ) //300.333.266.32 break; if((currValInt < pow(10,currVal.length()-1)) && (currValInt != 0)) //01.022.22.44 return 0; tmpStr = tmpStr.substr(pos + 1); _count--; } if(_count > 0) return 0; //Now validate the last element of the IP address i.e. out of x1.x2.x3.x4 validate x4 currValInt = stoi(tmpStr); if(currValInt == 0 && tmpStr.size() > 1) return 0; if(tmpStr.size() == 0 || tmpStr.size() > 3) return 0; if(stoi(tmpStr) > 255 || stoi(tmpStr) < 0 ) return 0; if((currValInt < pow(10,tmpStr.length()-1)) && (currValInt != 0)) return 0; return 1; }}; 0 nitishmishra9371 week ago public boolean isValid(String s) { // Write your code here StringBuilder b = new StringBuilder(); int subCount = 0; int dotCount = 0; /*if(s.equals("00.00.00.00") || s.equals("000.000.000.000")) { return false; }*/ for(int i = 0; i < s.length(); ++i) { if(s.charAt(i) == '.') { if(dotCount > 3) { return false; } ++dotCount; try { Integer num = Integer.valueOf(b.toString()); if(num > -1 && num < 256) { subCount = 0; b.setLength(0); } else { return false; } } catch (NumberFormatException e) { return false; } } else { ++subCount; if(subCount > 3) { return false; } else { if(b.length() != 0 && b.toString().equals("0")) { return false; } b.append(s.charAt(i)); } } } return dotCount == 3; } 0 ayushmahobia011 week ago int isValid(string s) { // code here int count = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '.') { count++; } } if (count != 3) return 0; unordered_set<string> st; for (int i = 0; i < 256; i++) { st.insert(to_string(i)); } count = 0; string temp = ""; for (int i = 0; i < s.length(); i++) { if (s[i] != '.') { temp += s[i]; } else { if (st.count(temp) != 0) { count++; } temp = ""; } } if (st.count(temp) != 0) { count++; } if (count == 4) return 1; else return 0; } 0 wajid945711 week ago // good question class Solution { private: int solve(string str, char sep){ string temp = ""; int c=0; int count=0; for(int i=0; i<str.length(); i++){ if(str[i] !=sep){ temp += str[i]; if(temp.size()>3|| temp=="00" || ((temp[0]>='a' && temp[0]<='z') || (temp[0]>='A' && temp[0]<='Z')) ){ return 0; } } else{ c++; if(temp.size()==0 || (temp.size()>=2 && temp[0]=='0')|| temp.size()>3){ return 0; } if(stoi(temp)<0 || stoi(temp)>255){ return 0; } temp = ""; } } for(int i=0;i<str.size();i++){ if(str[i]=='.'){ count++; } } if(count>3){ return 0; } if(stoi(temp)<0 || stoi(temp)>255 || (temp.size()>=2 && temp[0]=='0')){ return 0; } if(c<3 || c>3){ return 0; } return 1; } public: int isValid(string s) { return solve(s,'.'); }}; +1 kartikeyashokgautam1 week ago Easy JAVA Solution :- public boolean isValid(String s) { int count = 0; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='.') count++; } if(count!=3) return false; HashSet<String> hs = new HashSet<>(); for(int i=0;i<256;i++) { hs.add(Integer.toString(i)); } count = 0; String temp = ""; for(int i=0;i<s.length();i++) { if(s.charAt(i)!='.') { temp+= s.charAt(i); } else { if(hs.contains(temp)) { count++; } temp = ""; } } if(hs.contains(temp)) { count++; } if(count == 4) { return true; } return false; } -1 roshan852k1 week ago class Solution { private: int solve(string str, char sep){ string temp = ""; int c=0; for(int i=0; i<str.length(); i++){ if(str[i] !=sep){ temp += str[i]; } else{ c++; if(stoi(temp)<0 || stoi(temp)>255){ return 0; } temp = ""; } } if(stoi(temp)<0 || stoi(temp)>255){ return 0; } if(c<3){ return 0; } return 1; } public: int isValid(string s) { // code here return solve(s,'.'); }}; +2 jack11432 weeks ago Executed in 0.01sec class Solution { public: int isValid(string s) { // code here int i = 0, count = 0; while(i < s.size()){ string tmp; while(i < s.size() and s[i] != '.' and s[i] >= '0' and s[i] <= '9')tmp += s[i++]; //only accepting integer if(tmp.size() == 0 || tmp.size() > 3 || stoi(tmp) > 255 || stoi(tmp) < 0)return 0; // valid number checking if(tmp.size() >= 2 and tmp[0] == '0')return 0; //chekcing leading zeros; if(s[i] == '.')count++; i++; } if(count < 3 || count > 3)return 0; //checking 32bit return 1; } 0 sumitsinghrajput786gwalior2 weeks ago //completed in java class Solution { public boolean isValid(String s) { // Write your code here if(s.compareTo("")==0){ return false; } if(s.length()<7)return false; int dot = 0; for(int i=0;i<s.length();i++){ if('.' == s.charAt(i)){ dot++; } } if(dot!=3)return false; String S = s.replace(".","@"); String[] str = S.split("@"); if(str.length != 4){ return false; } boolean ans = true; for(int i=0;i<4;i++){ if(str[i].length()<4){ try{ int n = Integer.parseInt(str[i]); if(0<=n && n<=255){ if(str[i].length()>1 && (n>=0 && n<=9))return false; continue; } else{ return false; } } catch(Exception e){ return false; } } else{ return false; } } return true; }} 0 minipandey3322 weeks ago //Anybody tells me what's wrong in below code. int isValid(string s) { // code here int dot=0; int r=0; for(int i=0; i<s.length(); i++) // 222.111.111.111 { if(s[i]>=0 && s[i] <= 9) { int x = atoi(s[i]); r = r*10 + x; } else if(s[i] == '.') { dot++; if(r>255 || r<0) return 0; r=0; } else return 0; } if(dot==3) return 1; else return 0; }}; +1 dtu_top_coder2 weeks ago 1st Try Solution Accepted C++ Code : class Solution { public: int isValid(string s) { string str=""; int count=0; s.push_back('.'); for(int i=0;i<s.size();i++) { if(s[i]=='.') { if(!check(str)) return false; str=""; count++; } else { str+=s[i]; } } if(count==4) return true; return false; } bool check(string s) { if(s=="" || (s[0]=='0' && s.size()>1)) return false; int a=atoi(s.c_str()); for(auto c:s) if(c<'0' || c>'9') return false; if(a>=0 && a<=255) return true; return false; }}; 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": 781, "s": 238, "text": "Write a program to Validate an IPv4 Address.\nAccording to Wikipedia, IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1 .\nA valid IPv4 Address is of the form x1.x2.x3.x4 where 0 <= (x1, x2, x3, x4) <= 255.\nThus, we can write the generalized form of an IPv4 address as (0-255).(0-255).(0-255).(0-255).\nNote: Here we are considering numbers only from 0 to 255 and any additional leading zeroes will be considered invalid." }, { "code": null, "e": 974, "s": 781, "text": "Your task is to complete the function isValid which returns 1 if the given IPv4 address is valid else returns 0. The function takes the IPv4 address as the only argument in the form of string." }, { "code": null, "e": 985, "s": 974, "text": "Example 1:" }, { "code": null, "e": 1167, "s": 985, "text": "Input:\nIPv4 address = 222.111.111.111\nOutput: 1\nExplanation: Here, the IPv4 address is as\nper the criteria mentioned and also all\nfour decimal numbers lies in the mentioned\nrange.\n\n" }, { "code": null, "e": 1178, "s": 1167, "text": "Example 2:" }, { "code": null, "e": 1312, "s": 1178, "text": "Input:\nIPv4 address = 5555..555\nOutput: 0\nExplanation: 5555..555 is not a valid\nIPv4 address, as the middle two portions\nare missing." }, { "code": null, "e": 1487, "s": 1312, "text": "Your Task:\nComplete the function isValid() which takes the address in the form of string s as an input parameter and returns 1 if this is a valid address otherwise returns 0." }, { "code": null, "e": 1931, "s": 1487, "text": "Expected Time Complexity: O(N), N = length of the string.\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1<=length of string <=50\n\nNote: The Input/Output format and Example given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1933, "s": 1931, "text": "0" }, { "code": null, "e": 1956, "s": 1933, "text": "mukesh kumar3 days ago" }, { "code": null, "e": 3294, "s": 1956, "text": "class Solution { public: int isValid(string s) { if(s.size() < 7) //minimum lenght of ip address 0.0.0.0 return 0; //check for minimum and maximum three dots size_t _count = std::count(s.begin(), s.end(), '.'); if( _count != 3) return 0; string tmpStr(s); string currVal; int currValInt; int pos; while(_count > 0) { pos = tmpStr.find('.'); currVal = tmpStr.substr(0, pos); if(!isdigit(currVal[0])) //to check a.b.c.d return 0; currValInt = stoi(currVal); if(currValInt == 0 && currVal.size()>1) //000.000.000.000 break; if(currVal.size() > 3) //3343.46546.323.11 break; if(currValInt > 255 || currValInt < 0 ) //300.333.266.32 break; if((currValInt < pow(10,currVal.length()-1)) && (currValInt != 0)) //01.022.22.44 return 0; tmpStr = tmpStr.substr(pos + 1); _count--; } if(_count > 0) return 0; //Now validate the last element of the IP address i.e. out of x1.x2.x3.x4 validate x4 currValInt = stoi(tmpStr); if(currValInt == 0 && tmpStr.size() > 1) return 0; if(tmpStr.size() == 0 || tmpStr.size() > 3) return 0; if(stoi(tmpStr) > 255 || stoi(tmpStr) < 0 ) return 0; if((currValInt < pow(10,tmpStr.length()-1)) && (currValInt != 0)) return 0; return 1; }};" }, { "code": null, "e": 3296, "s": 3294, "text": "0" }, { "code": null, "e": 3322, "s": 3296, "text": "nitishmishra9371 week ago" }, { "code": null, "e": 4518, "s": 3322, "text": " public boolean isValid(String s) { // Write your code here StringBuilder b = new StringBuilder(); int subCount = 0; int dotCount = 0; /*if(s.equals(\"00.00.00.00\") || s.equals(\"000.000.000.000\")) { return false; }*/ for(int i = 0; i < s.length(); ++i) { if(s.charAt(i) == '.') { if(dotCount > 3) { return false; } ++dotCount; try { Integer num = Integer.valueOf(b.toString()); if(num > -1 && num < 256) { subCount = 0; b.setLength(0); } else { return false; } } catch (NumberFormatException e) { return false; } } else { ++subCount; if(subCount > 3) { return false; } else { if(b.length() != 0 && b.toString().equals(\"0\")) { return false; } b.append(s.charAt(i)); } } } return dotCount == 3; }" }, { "code": null, "e": 4520, "s": 4518, "text": "0" }, { "code": null, "e": 4545, "s": 4520, "text": "ayushmahobia011 week ago" }, { "code": null, "e": 4761, "s": 4545, "text": " int isValid(string s) { // code here int count = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '.') { count++; } } if (count != 3) return 0;" }, { "code": null, "e": 4861, "s": 4761, "text": " unordered_set<string> st; for (int i = 0; i < 256; i++) { st.insert(to_string(i)); }" }, { "code": null, "e": 5250, "s": 4861, "text": " count = 0; string temp = \"\"; for (int i = 0; i < s.length(); i++) { if (s[i] != '.') { temp += s[i]; } else { if (st.count(temp) != 0) { count++; } temp = \"\"; } } if (st.count(temp) != 0) { count++; } if (count == 4) return 1; else return 0; }" }, { "code": null, "e": 5252, "s": 5250, "text": "0" }, { "code": null, "e": 5273, "s": 5252, "text": "wajid945711 week ago" }, { "code": null, "e": 5290, "s": 5273, "text": "// good question" }, { "code": null, "e": 6129, "s": 5292, "text": "class Solution { private: int solve(string str, char sep){ string temp = \"\"; int c=0; int count=0; for(int i=0; i<str.length(); i++){ if(str[i] !=sep){ temp += str[i]; if(temp.size()>3|| temp==\"00\" || ((temp[0]>='a' && temp[0]<='z') || (temp[0]>='A' && temp[0]<='Z')) ){ return 0; } } else{ c++; if(temp.size()==0 || (temp.size()>=2 && temp[0]=='0')|| temp.size()>3){ return 0; } if(stoi(temp)<0 || stoi(temp)>255){ return 0; } temp = \"\"; } } for(int i=0;i<str.size();i++){ if(str[i]=='.'){ count++; } } if(count>3){ return 0; }" }, { "code": null, "e": 6239, "s": 6129, "text": " if(stoi(temp)<0 || stoi(temp)>255 || (temp.size()>=2 && temp[0]=='0')){ return 0; }" }, { "code": null, "e": 6374, "s": 6239, "text": " if(c<3 || c>3){ return 0; } return 1; } public: int isValid(string s) { return solve(s,'.'); }};" }, { "code": null, "e": 6377, "s": 6374, "text": "+1" }, { "code": null, "e": 6407, "s": 6377, "text": "kartikeyashokgautam1 week ago" }, { "code": null, "e": 6429, "s": 6407, "text": "Easy JAVA Solution :-" }, { "code": null, "e": 6637, "s": 6431, "text": " public boolean isValid(String s) { int count = 0; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='.') count++; } if(count!=3) return false;" }, { "code": null, "e": 7355, "s": 6637, "text": " HashSet<String> hs = new HashSet<>(); for(int i=0;i<256;i++) { hs.add(Integer.toString(i)); } count = 0; String temp = \"\"; for(int i=0;i<s.length();i++) { if(s.charAt(i)!='.') { temp+= s.charAt(i); } else { if(hs.contains(temp)) { count++; } temp = \"\"; } } if(hs.contains(temp)) { count++; } if(count == 4) { return true; } return false;" }, { "code": null, "e": 7360, "s": 7355, "text": " }" }, { "code": null, "e": 7363, "s": 7360, "text": "-1" }, { "code": null, "e": 7384, "s": 7363, "text": "roshan852k1 week ago" }, { "code": null, "e": 8014, "s": 7384, "text": "class Solution { private: int solve(string str, char sep){ string temp = \"\"; int c=0; for(int i=0; i<str.length(); i++){ if(str[i] !=sep){ temp += str[i]; } else{ c++; if(stoi(temp)<0 || stoi(temp)>255){ return 0; } temp = \"\"; } } if(stoi(temp)<0 || stoi(temp)>255){ return 0; } if(c<3){ return 0; } return 1; } public: int isValid(string s) { // code here return solve(s,'.'); }};" }, { "code": null, "e": 8017, "s": 8014, "text": "+2" }, { "code": null, "e": 8037, "s": 8017, "text": "jack11432 weeks ago" }, { "code": null, "e": 8057, "s": 8037, "text": "Executed in 0.01sec" }, { "code": null, "e": 8746, "s": 8057, "text": "class Solution {\n public:\n int isValid(string s) {\n // code here\n int i = 0, count = 0;\n while(i < s.size()){\n string tmp;\n while(i < s.size() and s[i] != '.' and s[i] >= '0' and s[i] <= '9')tmp += s[i++]; //only accepting integer\n if(tmp.size() == 0 || tmp.size() > 3 || stoi(tmp) > 255 || stoi(tmp) < 0)return 0; // valid number checking\n if(tmp.size() >= 2 and tmp[0] == '0')return 0; //chekcing leading zeros;\n if(s[i] == '.')count++;\n i++;\n }\n if(count < 3 || count > 3)return 0; //checking 32bit\n return 1;\n }" }, { "code": null, "e": 8748, "s": 8746, "text": "0" }, { "code": null, "e": 8786, "s": 8748, "text": "sumitsinghrajput786gwalior2 weeks ago" }, { "code": null, "e": 8806, "s": 8786, "text": "//completed in java" }, { "code": null, "e": 8823, "s": 8806, "text": "class Solution {" }, { "code": null, "e": 9883, "s": 8823, "text": " public boolean isValid(String s) { // Write your code here if(s.compareTo(\"\")==0){ return false; } if(s.length()<7)return false; int dot = 0; for(int i=0;i<s.length();i++){ if('.' == s.charAt(i)){ dot++; } } if(dot!=3)return false; String S = s.replace(\".\",\"@\"); String[] str = S.split(\"@\"); if(str.length != 4){ return false; } boolean ans = true; for(int i=0;i<4;i++){ if(str[i].length()<4){ try{ int n = Integer.parseInt(str[i]); if(0<=n && n<=255){ if(str[i].length()>1 && (n>=0 && n<=9))return false; continue; } else{ return false; } } catch(Exception e){ return false; } } else{ return false; } } return true; }}" }, { "code": null, "e": 9885, "s": 9883, "text": "0" }, { "code": null, "e": 9910, "s": 9885, "text": "minipandey3322 weeks ago" }, { "code": null, "e": 9957, "s": 9910, "text": "//Anybody tells me what's wrong in below code." }, { "code": null, "e": 10648, "s": 9957, "text": "int isValid(string s) { // code here int dot=0; int r=0; for(int i=0; i<s.length(); i++) // 222.111.111.111 { if(s[i]>=0 && s[i] <= 9) { int x = atoi(s[i]); r = r*10 + x; } else if(s[i] == '.') { dot++; if(r>255 || r<0) return 0; r=0; } else return 0; } if(dot==3) return 1; else return 0; }};" }, { "code": null, "e": 10651, "s": 10648, "text": "+1" }, { "code": null, "e": 10676, "s": 10651, "text": "dtu_top_coder2 weeks ago" }, { "code": null, "e": 10702, "s": 10676, "text": "1st Try Solution Accepted" }, { "code": null, "e": 10713, "s": 10702, "text": "C++ Code :" }, { "code": null, "e": 11676, "s": 10715, "text": "class Solution { public: int isValid(string s) { string str=\"\"; int count=0; s.push_back('.'); for(int i=0;i<s.size();i++) { if(s[i]=='.') { if(!check(str)) return false; str=\"\"; count++; } else { str+=s[i]; } } if(count==4) return true; return false; } bool check(string s) { if(s==\"\" || (s[0]=='0' && s.size()>1)) return false; int a=atoi(s.c_str()); for(auto c:s) if(c<'0' || c>'9') return false; if(a>=0 && a<=255) return true; return false; }};" }, { "code": null, "e": 11822, "s": 11676, "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": 11858, "s": 11822, "text": " Login to access your submissions. " }, { "code": null, "e": 11868, "s": 11858, "text": "\nProblem\n" }, { "code": null, "e": 11878, "s": 11868, "text": "\nContest\n" }, { "code": null, "e": 11941, "s": 11878, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 12089, "s": 11941, "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": 12297, "s": 12089, "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": 12403, "s": 12297, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
PHP - json_decode() Function
The json_decode() function can decode a JSON string. mixed json_decode( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] ) The json_decode() function can take a JSON encoded string and convert into a PHP variable. The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit. <?php $jsonData= '[ {"name":"Raja", "city":"Hyderabad", "state":"Telangana"}, {"name":"Adithya", "city":"Pune", "state":"Maharastra"}, {"name":"Jai", "city":"Secunderabad", "state":"Telangana"} ]'; $people= json_decode($jsonData, true); $count= count($people); // Access any person who lives in Telangana for ($i=0; $i < $count; $i++) { if($people[$i]["state"] == "Telangana") { echo $people[$i]["name"] . "\n"; echo $people[$i]["city"] . "\n"; echo $people[$i]["state"] . "\n\n"; } } ?> Raja Hyderabad Telangana Jai Secunderabad Telangana <?php // Assign a JSON object to a variable $someJSON = '{"name" : "Raja", "Adithya" : "Jai"}'; // Convert the JSON to an associative array $someArray = json_decode($someJSON, true); // Read the elements of the associative array foreach($someArray as $key => $value) { echo "[" . $key . "][" . $value . "]"; } ?> [name][Raja][Adithya][Jai] 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2811, "s": 2757, "text": "The json_decode() function can decode a JSON string. " }, { "code": null, "e": 2913, "s": 2811, "text": "mixed json_decode( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )\n" }, { "code": null, "e": 3005, "s": 2913, "text": "The json_decode() function can take a JSON encoded string and convert into a PHP variable. " }, { "code": null, "e": 3281, "s": 3005, "text": "The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit." }, { "code": null, "e": 3900, "s": 3281, "text": "<?php \n $jsonData= '[\n {\"name\":\"Raja\", \"city\":\"Hyderabad\", \"state\":\"Telangana\"}, \n {\"name\":\"Adithya\", \"city\":\"Pune\", \"state\":\"Maharastra\"},\n {\"name\":\"Jai\", \"city\":\"Secunderabad\", \"state\":\"Telangana\"}\n ]';\n\n $people= json_decode($jsonData, true);\n $count= count($people);\n\n // Access any person who lives in Telangana\n for ($i=0; $i < $count; $i++) { \n if($people[$i][\"state\"] == \"Telangana\") {\n echo $people[$i][\"name\"] . \"\\n\";\n echo $people[$i][\"city\"] . \"\\n\";\n echo $people[$i][\"state\"] . \"\\n\\n\";\n }\n }\n?>" }, { "code": null, "e": 3954, "s": 3900, "text": "Raja\nHyderabad\nTelangana\n\nJai\nSecunderabad\nTelangana\n" }, { "code": null, "e": 4298, "s": 3954, "text": "<?php\n // Assign a JSON object to a variable\n $someJSON = '{\"name\" : \"Raja\", \"Adithya\" : \"Jai\"}';\n \n // Convert the JSON to an associative array\n $someArray = json_decode($someJSON, true);\n \n // Read the elements of the associative array\n foreach($someArray as $key => $value) {\n echo \"[\" . $key . \"][\" . $value . \"]\";\n }\n?>" }, { "code": null, "e": 4326, "s": 4298, "text": "[name][Raja][Adithya][Jai]\n" }, { "code": null, "e": 4359, "s": 4326, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 4375, "s": 4359, "text": " Malhar Lathkar" }, { "code": null, "e": 4408, "s": 4375, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 4419, "s": 4408, "text": " Syed Raza" }, { "code": null, "e": 4454, "s": 4419, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4471, "s": 4454, "text": " Frahaan Hussain" }, { "code": null, "e": 4504, "s": 4471, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4519, "s": 4504, "text": " Nivedita Jain" }, { "code": null, "e": 4554, "s": 4519, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 4566, "s": 4554, "text": " Azaz Patel" }, { "code": null, "e": 4601, "s": 4566, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4629, "s": 4601, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4636, "s": 4629, "text": " Print" }, { "code": null, "e": 4647, "s": 4636, "text": " Add Notes" } ]
p5.js | loop() Function - GeeksforGeeks
17 Jan, 2020 The loop() function is an inbuilt function in p5.js library. This function is used to play the audio on the web in a loop. The loop function can call after or before the play() function, it does not matter. It will play that loaded sound again and again in a loop. Syntax: loop( startTime, rate, amp, cueStart, duration ) Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file. Parameter: This function accepts five parameters as mentioned above and described below: startTime: This parameter holds an integer number as seconds that defines the scheduled playback and it is an optional parameter. rate: This parameter holds an integer number that defines playback rate and it is an optional parameter. amp: This parameter holds an integer number that defines the amplitude of the playback and it is an optional parameter. cueStart: This parameter holds an integer number as seconds that define the cue start time in seconds and it is an optional parameter. duration: This parameter holds an integer number that defines the duration of playback in seconds and it is an optional parameter. Below given example illustrate the p5.js loop() function in JavaScript:Example: var sound; function preload() { // Initialize sound sound = loadSound("pfivesound.mp3"); } function setup() { // Playing the preloaded sound in a loop sound.play(); sound.loop();} Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Supported Browsers: The browsers supported by p5.js loop() function are listed below: Google Chrome Internet Explorer Firefox Safari Opera JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 Open URL in New Tab using JavaScript ? Set the value of an input field in JavaScript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24168, "s": 24140, "text": "\n17 Jan, 2020" }, { "code": null, "e": 24433, "s": 24168, "text": "The loop() function is an inbuilt function in p5.js library. This function is used to play the audio on the web in a loop. The loop function can call after or before the play() function, it does not matter. It will play that loaded sound again and again in a loop." }, { "code": null, "e": 24441, "s": 24433, "text": "Syntax:" }, { "code": null, "e": 24490, "s": 24441, "text": "loop( startTime, rate, amp, cueStart, duration )" }, { "code": null, "e": 24617, "s": 24490, "text": "Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file." }, { "code": null, "e": 24706, "s": 24617, "text": "Parameter: This function accepts five parameters as mentioned above and described below:" }, { "code": null, "e": 24836, "s": 24706, "text": "startTime: This parameter holds an integer number as seconds that defines the scheduled playback and it is an optional parameter." }, { "code": null, "e": 24941, "s": 24836, "text": "rate: This parameter holds an integer number that defines playback rate and it is an optional parameter." }, { "code": null, "e": 25061, "s": 24941, "text": "amp: This parameter holds an integer number that defines the amplitude of the playback and it is an optional parameter." }, { "code": null, "e": 25196, "s": 25061, "text": "cueStart: This parameter holds an integer number as seconds that define the cue start time in seconds and it is an optional parameter." }, { "code": null, "e": 25327, "s": 25196, "text": "duration: This parameter holds an integer number that defines the duration of playback in seconds and it is an optional parameter." }, { "code": null, "e": 25407, "s": 25327, "text": "Below given example illustrate the p5.js loop() function in JavaScript:Example:" }, { "code": "var sound; function preload() { // Initialize sound sound = loadSound(\"pfivesound.mp3\"); } function setup() { // Playing the preloaded sound in a loop sound.play(); sound.loop();} ", "e": 25615, "s": 25407, "text": null }, { "code": null, "e": 25752, "s": 25615, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 25838, "s": 25752, "text": "Supported Browsers: The browsers supported by p5.js loop() function are listed below:" }, { "code": null, "e": 25852, "s": 25838, "text": "Google Chrome" }, { "code": null, "e": 25870, "s": 25852, "text": "Internet Explorer" }, { "code": null, "e": 25878, "s": 25870, "text": "Firefox" }, { "code": null, "e": 25885, "s": 25878, "text": "Safari" }, { "code": null, "e": 25891, "s": 25885, "text": "Opera" }, { "code": null, "e": 25908, "s": 25891, "text": "JavaScript-p5.js" }, { "code": null, "e": 25919, "s": 25908, "text": "JavaScript" }, { "code": null, "e": 25936, "s": 25919, "text": "Web Technologies" }, { "code": null, "e": 26034, "s": 25936, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26043, "s": 26034, "text": "Comments" }, { "code": null, "e": 26056, "s": 26043, "text": "Old Comments" }, { "code": null, "e": 26101, "s": 26056, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26162, "s": 26101, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26234, "s": 26162, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26280, "s": 26234, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 26326, "s": 26280, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 26368, "s": 26326, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26401, "s": 26368, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26463, "s": 26401, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26506, "s": 26463, "text": "How to fetch data from an API in ReactJS ?" } ]
PHP switch Statement
The switch statement is used to perform different actions based on different conditions. Use the switch statement to select one of many blocks of code to be executed. This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found. Create a switch statement that will output "Hello" if $color is "red", and "welcome" if $color is "green". ($color) { "red": echo "Hello"; break; "green": echo "Welcome"; break; } We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 89, "s": 0, "text": "The switch statement is used to perform different actions based on different conditions." }, { "code": null, "e": 168, "s": 89, "text": "Use the switch statement to select one of many blocks \nof code to be executed." }, { "code": null, "e": 576, "s": 168, "text": "This is how it works: First we have a single expression n (most often a\nvariable), that is evaluated once. The value of the expression is then compared\nwith the values for each case in the structure. If there is a match, the block\nof code associated with that case is executed. Use break to prevent the\ncode from running into the next case automatically. The default statement is used if no \nmatch is found." }, { "code": null, "e": 683, "s": 576, "text": "Create a switch statement that will output \"Hello\"\nif $color is \"red\", and \"welcome\"\nif $color is \"green\"." }, { "code": null, "e": 780, "s": 683, "text": " ($color) {\n \"red\":\n echo \"Hello\";\n break;\n \"green\":\n echo \"Welcome\";\n break;\n}\n" }, { "code": null, "e": 813, "s": 780, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 855, "s": 813, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 962, "s": 855, "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": 981, "s": 962, "text": "help@w3schools.com" } ]
Adding Array Elements | Practice | GeeksforGeeks
Given an array Arr[] of size N and an integer K, you have to add the first two minimum elements of the array until all the elements are greater than or equal to K and find the number of such operations required. Example 1: Input: N = 6, K = 6 Arr[] = {1, 10, 12, 9, 2, 3} Output: 2 Explanation: First we add (1 + 2), now the new list becomes 3 10 12 9 3, then we add (3 + 3), now the new list becomes 6 10 12 9, Now all the elements in the list are greater than 6. Hence the output is 2 i:e 2 operations are required to do this. Example 2: Input: N = 4, K = 4 Arr[] = {5, 4, 6, 4} Output: 0 Explanation: Every element in the given array is greater than or equal to K. Your Task: You don't need to read input or print anything. Your task is to complete the function minOperations() which takes array of integers arr, n and k as parameters and returns an integer denoting the answer. If it is not possible to make elements greater than or equal to K, return -1. Expected Time Complexity: O(N*logN) Expected Auxiliary Space: O(N) Constraints : 1 ≤ N, K ≤ 105 1 ≤ Arr[i] ≤ 106 0 hharshit81182 weeks ago Best Solution : O(nlogn) class Solution{ public: int minOperations(int arr[], int n, int k) { priority_queue<int, vector<int>, greater<int>> p; for(int i=0; i< n; i++){ p.push(arr[i]); } int count = 0; while(p.top() < k){ int curr = p.top(); p.pop(); curr += p.top(); p.pop(); p.push(curr); count++; } return count; }}; +1 yashchawla1162 months ago Simple To Understand And Easy To Implement. https://yashboss116.blogspot.com/2022/03/adding-array-elements-geeks-for-geeks.html +1 himanshukug19cs2 months ago java solution PriorityQueue<Integer> pq = new PriorityQueue<>(); for(int i=0;i<n;i++){ pq.add(arr[i]); } int ans=0; while(pq.peek()<k){ int a = pq.poll(); a+=pq.poll(); pq.add(a); ans++; } return ans; 0 aharshit3502 months ago JAVA SOLUTION class Solution { int minOperations(int[] arr, int n, int k) { // code here PriorityQueue<Integer>pq=new PriorityQueue<>(); for(int i=0;i<n;i++){ pq.add(arr[i]); }int result=0; while(k>pq.peek()){ int x=pq.poll(); int y=pq.poll(); int z=x+y; pq.add(z); result++; }return result; }} 0 excuses3 months ago ///JAVA SOLUTION/// TIME TAKEN -:) 0.9 SEC . int c=0; PriorityQueue<Integer>heap=new PriorityQueue<>(); for(int i=0;i<n;i++) { heap.add(arr[i]); } if(heap.peek()>=k) { return 0; } else { while(heap.peek()<k) { int a=heap.poll(); int b=heap.poll(); int sum=a+b; c++; heap.add(sum); } } return c; +1 sudarshanp49123 months ago EASY SOLUTION: int minOperations(int arr[], int n, int k) { priority_queue<int, vector<int>, greater<int>> minh; int count=0,sum=0; for(int i=0;i<n;i++) { minh.push(arr[i]); sum+=arr[i]; } while(minh.top()<k and minh.size()>=2) { int x=minh.top(); minh.pop(); int y=minh.top(); minh.pop(); minh.push(x+y); count++; } if(sum<k) return -1; return count; } 0 imranwahid5 months ago Easy C++ solution 0 imranwahid This comment was deleted. +1 badgujarsachin836 months ago int minOperations(int arr[], int n, int k) { // code here int operation=0; priority_queue<int,vector<int>,greater<int>> p; for(int i=0;i<n;i++) { p.push(arr[i]); } while(!p.empty()){ int a=p.top(); p.pop(); int b=p.top(); p.pop(); int sum=a+b; if(a>=k and b>=k){ break; } p.push(sum); operation++; } return operation; } -1 rohitpendse1386 months ago class Solution {public: int minOperations(int arr[], int n, int k) { // code here priority_queue<int, vector<int>, greater<int>> mnh; for (int i = 0; i < n; i++) { mnh.push(arr[i]); } int ans = 0; while (!mnh.empty()) { int x = mnh.top(); mnh.pop(); int y = mnh.top(); mnh.pop(); if (x >= k and y >= k) break; mnh.push(x + y); ans++; } return ans; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 450, "s": 238, "text": "Given an array Arr[] of size N and an integer K, you have to add the first two minimum elements of the array until all the elements are greater than or equal to K and find the number of such operations required." }, { "code": null, "e": 461, "s": 450, "text": "Example 1:" }, { "code": null, "e": 770, "s": 461, "text": "Input:\nN = 6, K = 6 \nArr[] = {1, 10, 12, 9, 2, 3}\nOutput: 2\nExplanation: First we add (1 + 2), now the\nnew list becomes 3 10 12 9 3, then we add\n(3 + 3), now the new list becomes 6 10 12 9,\nNow all the elements in the list are greater\nthan 6. Hence the output is 2 i:e 2 operations\nare required to do this. \n" }, { "code": null, "e": 781, "s": 770, "text": "Example 2:" }, { "code": null, "e": 911, "s": 781, "text": "Input:\nN = 4, K = 4\nArr[] = {5, 4, 6, 4}\nOutput: 0\nExplanation: Every element in the given array \nis greater than or equal to K.\n" }, { "code": null, "e": 1203, "s": 911, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function minOperations() which takes array of integers arr, n and k as parameters and returns an integer denoting the answer. If it is not possible to make elements greater than or equal to K, return -1." }, { "code": null, "e": 1270, "s": 1203, "text": "Expected Time Complexity: O(N*logN)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1316, "s": 1270, "text": "Constraints :\n1 ≤ N, K ≤ 105\n1 ≤ Arr[i] ≤ 106" }, { "code": null, "e": 1320, "s": 1318, "text": "0" }, { "code": null, "e": 1344, "s": 1320, "text": "hharshit81182 weeks ago" }, { "code": null, "e": 1369, "s": 1344, "text": "Best Solution : O(nlogn)" }, { "code": null, "e": 1760, "s": 1369, "text": "class Solution{ public: int minOperations(int arr[], int n, int k) { priority_queue<int, vector<int>, greater<int>> p; for(int i=0; i< n; i++){ p.push(arr[i]); } int count = 0; while(p.top() < k){ int curr = p.top(); p.pop(); curr += p.top(); p.pop(); p.push(curr); count++; } return count; }};" }, { "code": null, "e": 1763, "s": 1760, "text": "+1" }, { "code": null, "e": 1789, "s": 1763, "text": "yashchawla1162 months ago" }, { "code": null, "e": 1833, "s": 1789, "text": "Simple To Understand And Easy To Implement." }, { "code": null, "e": 1919, "s": 1835, "text": "https://yashboss116.blogspot.com/2022/03/adding-array-elements-geeks-for-geeks.html" }, { "code": null, "e": 1926, "s": 1923, "text": "+1" }, { "code": null, "e": 1954, "s": 1926, "text": "himanshukug19cs2 months ago" }, { "code": null, "e": 1968, "s": 1954, "text": "java solution" }, { "code": null, "e": 2245, "s": 1970, "text": " PriorityQueue<Integer> pq = new PriorityQueue<>(); for(int i=0;i<n;i++){ pq.add(arr[i]); } int ans=0; while(pq.peek()<k){ int a = pq.poll(); a+=pq.poll(); pq.add(a); ans++; } return ans;" }, { "code": null, "e": 2247, "s": 2245, "text": "0" }, { "code": null, "e": 2271, "s": 2247, "text": "aharshit3502 months ago" }, { "code": null, "e": 2285, "s": 2271, "text": "JAVA SOLUTION" }, { "code": null, "e": 2667, "s": 2285, "text": "class Solution { int minOperations(int[] arr, int n, int k) { // code here PriorityQueue<Integer>pq=new PriorityQueue<>(); for(int i=0;i<n;i++){ pq.add(arr[i]); }int result=0; while(k>pq.peek()){ int x=pq.poll(); int y=pq.poll(); int z=x+y; pq.add(z); result++; }return result; }} " }, { "code": null, "e": 2669, "s": 2667, "text": "0" }, { "code": null, "e": 2689, "s": 2669, "text": "excuses3 months ago" }, { "code": null, "e": 2709, "s": 2689, "text": "///JAVA SOLUTION///" }, { "code": null, "e": 2734, "s": 2709, "text": "TIME TAKEN -:) 0.9 SEC ." }, { "code": null, "e": 3090, "s": 2736, "text": " int c=0; PriorityQueue<Integer>heap=new PriorityQueue<>(); for(int i=0;i<n;i++) { heap.add(arr[i]); } if(heap.peek()>=k) { return 0; } else { while(heap.peek()<k) { int a=heap.poll(); int b=heap.poll(); int sum=a+b; c++; heap.add(sum); } } return c;" }, { "code": null, "e": 3093, "s": 3090, "text": "+1" }, { "code": null, "e": 3120, "s": 3093, "text": "sudarshanp49123 months ago" }, { "code": null, "e": 3135, "s": 3120, "text": "EASY SOLUTION:" }, { "code": null, "e": 3693, "s": 3135, "text": "int minOperations(int arr[], int n, int k)\n {\n priority_queue<int, vector<int>, greater<int>> minh;\n int count=0,sum=0;\n \n for(int i=0;i<n;i++)\n {\n minh.push(arr[i]);\n sum+=arr[i];\n }\n \n while(minh.top()<k and minh.size()>=2)\n {\n int x=minh.top();\n minh.pop();\n int y=minh.top();\n minh.pop();\n minh.push(x+y);\n count++;\n }\n if(sum<k)\n return -1;\n \n return count;\n }" }, { "code": null, "e": 3695, "s": 3693, "text": "0" }, { "code": null, "e": 3718, "s": 3695, "text": "imranwahid5 months ago" }, { "code": null, "e": 3736, "s": 3718, "text": "Easy C++ solution" }, { "code": null, "e": 3738, "s": 3736, "text": "0" }, { "code": null, "e": 3749, "s": 3738, "text": "imranwahid" }, { "code": null, "e": 3775, "s": 3749, "text": "This comment was deleted." }, { "code": null, "e": 3778, "s": 3775, "text": "+1" }, { "code": null, "e": 3807, "s": 3778, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 4318, "s": 3807, "text": "int minOperations(int arr[], int n, int k) {\n // code here\n int operation=0;\n priority_queue<int,vector<int>,greater<int>> p;\n for(int i=0;i<n;i++)\n {\n p.push(arr[i]);\n }\n while(!p.empty()){\n int a=p.top();\n p.pop();\n int b=p.top();\n p.pop();\n int sum=a+b;\n if(a>=k and b>=k){\n break;\n }\n p.push(sum);\n operation++;\n }\n return operation;\n }" }, { "code": null, "e": 4321, "s": 4318, "text": "-1" }, { "code": null, "e": 4348, "s": 4321, "text": "rohitpendse1386 months ago" }, { "code": null, "e": 4832, "s": 4348, "text": "class Solution {public: int minOperations(int arr[], int n, int k) { // code here priority_queue<int, vector<int>, greater<int>> mnh; for (int i = 0; i < n; i++) { mnh.push(arr[i]); } int ans = 0; while (!mnh.empty()) { int x = mnh.top(); mnh.pop(); int y = mnh.top(); mnh.pop(); if (x >= k and y >= k) break; mnh.push(x + y); ans++; } return ans; }};" }, { "code": null, "e": 4978, "s": 4832, "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": 5014, "s": 4978, "text": " Login to access your submissions. " }, { "code": null, "e": 5024, "s": 5014, "text": "\nProblem\n" }, { "code": null, "e": 5034, "s": 5024, "text": "\nContest\n" }, { "code": null, "e": 5097, "s": 5034, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5245, "s": 5097, "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": 5453, "s": 5245, "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": 5559, "s": 5453, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Automatically Rescale ylim and xlim in Matplotlib
To rescale ylim and xlim automatically, we can take the following steps − To plot a line, use plot() method and data range from 0 to 10. To plot a line, use plot() method and data range from 0 to 10. To scale the xlim and ylim automatically, we can make the variable scale_factore=6. To scale the xlim and ylim automatically, we can make the variable scale_factore=6. Use scale_factor (from Step 2) to rescale the xlim and ylim, using xlim() and ylim() methods, respectively. Use scale_factor (from Step 2) to rescale the xlim and ylim, using xlim() and ylim() methods, respectively. To display the figure, use show() method. To display the figure, use show() method. from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True plt.plot(range(0, 10)) scale_factor = 6 xmin, xmax = plt.xlim() ymin, ymax = plt.ylim() plt.xlim(xmin * scale_factor, xmax * scale_factor) plt.ylim(ymin * scale_factor, ymax * scale_factor) plt.show()
[ { "code": null, "e": 1136, "s": 1062, "text": "To rescale ylim and xlim automatically, we can take the following steps −" }, { "code": null, "e": 1199, "s": 1136, "text": "To plot a line, use plot() method and data range from 0 to 10." }, { "code": null, "e": 1262, "s": 1199, "text": "To plot a line, use plot() method and data range from 0 to 10." }, { "code": null, "e": 1346, "s": 1262, "text": "To scale the xlim and ylim automatically, we can make the variable scale_factore=6." }, { "code": null, "e": 1430, "s": 1346, "text": "To scale the xlim and ylim automatically, we can make the variable scale_factore=6." }, { "code": null, "e": 1538, "s": 1430, "text": "Use scale_factor (from Step 2) to rescale the xlim and ylim, using xlim() and ylim() methods, respectively." }, { "code": null, "e": 1646, "s": 1538, "text": "Use scale_factor (from Step 2) to rescale the xlim and ylim, using xlim() and ylim() methods, respectively." }, { "code": null, "e": 1688, "s": 1646, "text": "To display the figure, use show() method." }, { "code": null, "e": 1730, "s": 1688, "text": "To display the figure, use show() method." }, { "code": null, "e": 2055, "s": 1730, "text": "from matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nplt.plot(range(0, 10))\nscale_factor = 6\nxmin, xmax = plt.xlim()\nymin, ymax = plt.ylim()\nplt.xlim(xmin * scale_factor, xmax * scale_factor)\nplt.ylim(ymin * scale_factor, ymax * scale_factor)\nplt.show()" } ]
OCR of English alphabets in Python OpenCV - GeeksforGeeks
15 Sep, 2021 OCR which stands for Optical character recognition is a computer vision technique used to recognize characters such as digits, alphabets, signs, etc. These characters are common in day-to-day life and we can perform character recognition based on our requirements. We will implement optical character recognition of the English alphabets using OpenCV. here we will use the KNN algorithm which is used for classification. Note: You can find the data here data for which we will perform the OCR. There are 20000 rows of data containing 17 columns where the first column represents the alphabet and the remaining 16 will represent its different features. We have to process the data by converting the alphabets into ASCII characters. To perform classification we will use 10000 rows as training_data and 10000 row as testing_data. Below is the implementation. Python3 #Import the librariesimport cv2 as cvimport numpy as np # Read data and use converters# to convert the alphabets to# Numeric value.data= np.loadtxt('letter-recognition', dtype= 'float32', delimiter = ',', converters= {0: lambda ch: ord(ch)-ord('A')}) # split the data into train_data# and test_datatrain_data, test_data = np.vsplit(data,2) # split train_data and test_data# to features and responses.responses, training = np.hsplit(train_data,[1])classes, testing = np.hsplit(test_data,[1]) # Create the knn classifierknn = cv.ml.KNearest_create()knn.train(training, cv.ml.ROW_SAMPLE, responses) # Obtain the results of the classifier# determine the number of neighbors.ret, Output, neighbours,distance = knn.findNearest(testing, k=7) # Match the Output to find the# number of wrong predictions.correct_OP = np.count_nonzero(Output == classes) #calculate accuracy and display it.accuracy = (correct_OP*100.0)/(10000)print( accuracy ) Output 92.82 sumitgumber28 Python-OpenCV 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 ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n15 Sep, 2021" }, { "code": null, "e": 24714, "s": 24292, "text": "OCR which stands for Optical character recognition is a computer vision technique used to recognize characters such as digits, alphabets, signs, etc. These characters are common in day-to-day life and we can perform character recognition based on our requirements. We will implement optical character recognition of the English alphabets using OpenCV. here we will use the KNN algorithm which is used for classification. " }, { "code": null, "e": 24788, "s": 24714, "text": "Note: You can find the data here data for which we will perform the OCR. " }, { "code": null, "e": 25122, "s": 24788, "text": "There are 20000 rows of data containing 17 columns where the first column represents the alphabet and the remaining 16 will represent its different features. We have to process the data by converting the alphabets into ASCII characters. To perform classification we will use 10000 rows as training_data and 10000 row as testing_data." }, { "code": null, "e": 25152, "s": 25122, "text": "Below is the implementation. " }, { "code": null, "e": 25160, "s": 25152, "text": "Python3" }, { "code": "#Import the librariesimport cv2 as cvimport numpy as np # Read data and use converters# to convert the alphabets to# Numeric value.data= np.loadtxt('letter-recognition', dtype= 'float32', delimiter = ',', converters= {0: lambda ch: ord(ch)-ord('A')}) # split the data into train_data# and test_datatrain_data, test_data = np.vsplit(data,2) # split train_data and test_data# to features and responses.responses, training = np.hsplit(train_data,[1])classes, testing = np.hsplit(test_data,[1]) # Create the knn classifierknn = cv.ml.KNearest_create()knn.train(training, cv.ml.ROW_SAMPLE, responses) # Obtain the results of the classifier# determine the number of neighbors.ret, Output, neighbours,distance = knn.findNearest(testing, k=7) # Match the Output to find the# number of wrong predictions.correct_OP = np.count_nonzero(Output == classes) #calculate accuracy and display it.accuracy = (correct_OP*100.0)/(10000)print( accuracy )", "e": 26149, "s": 25160, "text": null }, { "code": null, "e": 26157, "s": 26149, "text": "Output " }, { "code": null, "e": 26163, "s": 26157, "text": "92.82" }, { "code": null, "e": 26179, "s": 26165, "text": "sumitgumber28" }, { "code": null, "e": 26193, "s": 26179, "text": "Python-OpenCV" }, { "code": null, "e": 26200, "s": 26193, "text": "Python" }, { "code": null, "e": 26298, "s": 26200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26307, "s": 26298, "text": "Comments" }, { "code": null, "e": 26320, "s": 26307, "text": "Old Comments" }, { "code": null, "e": 26352, "s": 26320, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26407, "s": 26352, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26463, "s": 26407, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26505, "s": 26463, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26547, "s": 26505, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26586, "s": 26547, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26608, "s": 26586, "text": "Defaultdict in Python" }, { "code": null, "e": 26629, "s": 26608, "text": "Python OOPs Concepts" }, { "code": null, "e": 26660, "s": 26629, "text": "Python | os.path.join() method" } ]
How to Customize AlertDialog Dimensions in Android? - GeeksforGeeks
11 Aug, 2021 AlertDialog in Android is a kind of pop-up message that alerts the user about the activity usages. This is specifically developed by a developer to perform any operations or ask for any permissions and not an Android OS call. Alert Dialog in general has no fixed dimension values and rather varies from device to device depending upon the application screen size. In this article, we will show you how you could customize the Alert Dialog dimensions to a scale in your Android application. Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Button in the layout file. Create a Button that on click will generate an AlertDialog. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Click this button to show alert dialog --> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Alert Dialog" android:layout_centerInParent="true"/> </RelativeLayout> Step 3: 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.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.WindowManagerimport android.widget.Buttonimport androidx.annotation.RequiresApiimport androidx.appcompat.app.AlertDialog class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.R) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing button from the layout val mButton = findViewById<Button>(R.id.button) // When button is clicked mButton.setOnClickListener { // Build an alert dialog, declare its attributes val mDialogBuilder = AlertDialog.Builder(this) mDialogBuilder.apply { setTitle("This is Title") setMessage("This is Message: \n\nWidth & Height set to 50% of app screen size") setPositiveButton("Positive Button", null) setNegativeButton("Negative Button", null) } // Create and show the dialog val mDialog = mDialogBuilder.create() mDialog.show() // Get the current app screen width and height val mDisplayMetrics = windowManager.currentWindowMetrics val mDisplayWidth = mDisplayMetrics.bounds.width() val mDisplayHeight = mDisplayMetrics.bounds.height() // Generate custom width and height and // add to the dialog attributes // we multiplied the width and height by 0.5, // meaning reducing the size to 50% val mLayoutParams = WindowManager.LayoutParams() mLayoutParams.width = (mDisplayWidth * 0.5f).toInt() mLayoutParams.height = (mDisplayHeight * 0.5f).toInt() mDialog.window?.attributes = mLayoutParams } }} Output: You can see that the AlertDialog dimensions are now customized. 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? Flexbox-Layout in Android Retrofit with Kotlin Coroutine in Android Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters Kotlin when expression
[ { "code": null, "e": 26381, "s": 26353, "text": "\n11 Aug, 2021" }, { "code": null, "e": 26745, "s": 26381, "text": "AlertDialog in Android is a kind of pop-up message that alerts the user about the activity usages. This is specifically developed by a developer to perform any operations or ask for any permissions and not an Android OS call. Alert Dialog in general has no fixed dimension values and rather varies from device to device depending upon the application screen size." }, { "code": null, "e": 26871, "s": 26745, "text": "In this article, we will show you how you could customize the Alert Dialog dimensions to a scale in your Android application." }, { "code": null, "e": 26918, "s": 26871, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 27157, "s": 26918, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 27205, "s": 27157, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 27440, "s": 27205, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Button in the layout file. Create a Button that on click will generate an AlertDialog." }, { "code": null, "e": 27444, "s": 27440, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Click this button to show alert dialog --> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Show Alert Dialog\" android:layout_centerInParent=\"true\"/> </RelativeLayout>", "e": 28067, "s": 27444, "text": null }, { "code": null, "e": 28113, "s": 28067, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 28299, "s": 28113, "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": 28306, "s": 28299, "text": "Kotlin" }, { "code": "import android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.WindowManagerimport android.widget.Buttonimport androidx.annotation.RequiresApiimport androidx.appcompat.app.AlertDialog class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.R) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing button from the layout val mButton = findViewById<Button>(R.id.button) // When button is clicked mButton.setOnClickListener { // Build an alert dialog, declare its attributes val mDialogBuilder = AlertDialog.Builder(this) mDialogBuilder.apply { setTitle(\"This is Title\") setMessage(\"This is Message: \\n\\nWidth & Height set to 50% of app screen size\") setPositiveButton(\"Positive Button\", null) setNegativeButton(\"Negative Button\", null) } // Create and show the dialog val mDialog = mDialogBuilder.create() mDialog.show() // Get the current app screen width and height val mDisplayMetrics = windowManager.currentWindowMetrics val mDisplayWidth = mDisplayMetrics.bounds.width() val mDisplayHeight = mDisplayMetrics.bounds.height() // Generate custom width and height and // add to the dialog attributes // we multiplied the width and height by 0.5, // meaning reducing the size to 50% val mLayoutParams = WindowManager.LayoutParams() mLayoutParams.width = (mDisplayWidth * 0.5f).toInt() mLayoutParams.height = (mDisplayHeight * 0.5f).toInt() mDialog.window?.attributes = mLayoutParams } }}", "e": 30207, "s": 28306, "text": null }, { "code": null, "e": 30215, "s": 30207, "text": "Output:" }, { "code": null, "e": 30279, "s": 30215, "text": "You can see that the AlertDialog dimensions are now customized." }, { "code": null, "e": 30287, "s": 30279, "text": "Android" }, { "code": null, "e": 30294, "s": 30287, "text": "Kotlin" }, { "code": null, "e": 30302, "s": 30294, "text": "Android" }, { "code": null, "e": 30400, "s": 30302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30438, "s": 30400, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30477, "s": 30438, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30527, "s": 30477, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30553, "s": 30527, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 30595, "s": 30553, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30614, "s": 30595, "text": "Android UI Layouts" }, { "code": null, "e": 30627, "s": 30614, "text": "Kotlin Array" }, { "code": null, "e": 30669, "s": 30627, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30696, "s": 30669, "text": "Kotlin Setters and Getters" } ]
Sum of the series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ...... + (2+4+6+8+....+2n) - GeeksforGeeks
24 Dec, 2021 Given a positive integer n. The problem is to find the sum of the given series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ...... + (2+4+6+8+....+2n), where i-th term in the series is the sum of first i even natural numbers.Examples: Input : n = 2 Output : 8 (2) + (2+4) = 8 Input : n = 5 Output : 70 (2) + (2+4) + (2+4+6) + (2+4+6+8) + (2+4+6+8+10) = 70 Naive Approach: Using two loops get the sum of each i-th term and then add those sum to the final sum. C++ Java Python3 C# PHP Javascript // C++ implementation to find the sum// of the given series#include <bits/stdc++.h> using namespace std; // function to find the sum// of the given seriesint sumOfTheSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) { // first term of each i-th term int k = 2; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum;} // Driver program to test aboveint main(){ int n = 5; cout << "Sum = " << sumOfTheSeries(n); return 0;} // Java implementation to find the// sum of the given seriesclass GFG{ // function to find the sum // of the given series static int sumOfTheSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) { // first term of each i-th term int k = 2; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum; } // Driver program to test above public static void main(String[] args) { int n = 5; System.out.printf("Sum = %d", sumOfTheSeries(n)); }} // This code is contributed by// Smitha Dinesh Semwal # Python3 implementation to find# the sum of the given series # function to find the sum# of the given seriesdef sumOfTheSeries(n): sum = 0 for i in range(0, n + 1): # first term of each i-th # term k = 2 for j in range(1, i + 1): sum = sum + k; # next term k = k + 2 # required sum return sum; # Driver program to test aboven = 5ans = sumOfTheSeries(n);print (ans) # This code is contributed by saloni1297. // C# implementation to find the// sum of the given seriesusing System; class GFG{ // function to find the sum // of the given series static int sumOfTheSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) { // first term of each i-th term int k = 2; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum; } // Driver program to test above public static void Main() { int n = 5; Console.Write("Sum = "+ sumOfTheSeries(n)); }} // This code is contributed by// vt_m <?php// PHP implementation to find// the sum of the given series // function to find the sum// of the given series function sumOfTheSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) { // first term of each // i-th term $k = 2; for ($j = 1; $j <= $i; $j++) { $sum += $k; // next term $k += 2; } } // required sum return $sum;} // Driver program to test above $n = 5; echo "Sum = ", sumOfTheSeries($n); // This code is contributed by ajit.?> <script>// Javascript implementation to find// the sum of the given series // function to find the sum// of the given series function sumOfTheSeries(n){ let sum = 0; for (let i = 1; i <= n; i++) { // first term of each // i-th term let k = 2; for (let j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum;} // Driver program to test above let n = 5; document.write("Sum = " + sumOfTheSeries(n)); // This code is contributed by gfgking.</script> Output: Sum = 70 Efficient Approach: Let an be the n-th term of the given series. an = (2 + 4 + 6 + 8 +....+ 2n). = sum of first n even numbers. = n * (n + 1). = n2 + n. Refer this post for the proof of above formula.Now, Refer this and this post for the proof of above formula. C++ Java Python3 C# PHP Javascript // C++ implementation to find the sum// of the given series#include <bits/stdc++.h>using namespace std; // function to find the sum// of the given seriesint sumOfTheSeries(int n){ // sum of 1st n natural numbers int sum_n = (n * (n + 1) / 2); // sum of squares of 1st n natural numbers int sum_sq_n = (n * (n + 1) / 2) * (2 * n + 1) / 3; // required sum return (sum_n + sum_sq_n);} // Driver program to test aboveint main(){ int n = 5; cout << "Sum = " << sumOfTheSeries(n); return 0;} // Java implementation to find the// sum of the given seriesclass GFG{ // function to find the sum // of the given series static int sumOfTheSeries(int n) { // sum of 1st n natural numbers int sum_n = (n * (n + 1) / 2); // sum of squares of 1st n natural // numbers int sum_sq_n = (n * (n + 1) / 2) * (2 * n + 1) / 3; // required sum return (sum_n + sum_sq_n); } // Driver program to test above public static void main(String[] args) { int n = 5; System.out.printf("Sum = %d", sumOfTheSeries(n)); }} // This code is contributed by//Smitha Dinesh Semwal # Python3 implementation to find# the sum of the given series # function to find the sum# of the given seriesdef sumOfTheSeries(n): # sum of 1st n natural numbers sum_n = int((n * (n + 1) / 2)); # sum of squares of 1st n natural numbers sum_sq_n = int ((n * (n + 1) / 2) * (2 * n + 1) / 3) # required sum return (sum_n + sum_sq_n); # Driver program to test aboven = 5ans = sumOfTheSeries(n)print (ans) # This code is contributed by saloni1297. // C# implementation to find the// sum of the given seriesusing System; class GFG{ // function to find the sum // of the given series static int sumOfTheSeries(int n) { // sum of 1st n natural numbers int sum_n = (n * (n + 1) / 2); // sum of squares of 1st n // natural numbers int sum_sq_n = (n * (n + 1) / 2) * (2 * n + 1) / 3; // required sum return (sum_n + sum_sq_n); } // Driver program to test above public static void Main() { int n = 5; Console.Write("Sum = "+ sumOfTheSeries(n)); }} // This code is contributed by// vt_m <?php// PHP implementation// to find the sum// of the given series // function to find the// sum of the given seriesfunction sumOfTheSeries($n){ // sum of 1st n // natural numbers $sum_n = ($n * ($n + 1) / 2); // sum of squares of // 1st n natural numbers $sum_sq_n = ($n * ($n + 1) / 2) * (2 * $n + 1) / 3; // required sum return ($sum_n + $sum_sq_n);} // Driver Code$n = 5;echo ("Sum = ".sumOfTheSeries($n)); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // JavaScript Program to find the// sum of the given series // function to find the sum // of the given series function sumOfTheSeries(n) { // sum of 1st n natural numbers let sum_n = (n * (n + 1) / 2); // sum of squares of 1st n natural // numbers let sum_sq_n = (n * (n + 1) / 2) * (2 * n + 1) / 3; // required sum return (sum_n + sum_sq_n); } // Driver code let n = 5; document.write("Sum = " + sumOfTheSeries(n)); </script> Output: Sum = 70 jit_t manishshaw1 splevel62 gfgking surindertarika1234 simmytarika5 surinderdawra388 series series-sum Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python
[ { "code": null, "e": 25961, "s": 25933, "text": "\n24 Dec, 2021" }, { "code": null, "e": 26186, "s": 25961, "text": "Given a positive integer n. The problem is to find the sum of the given series 2 + (2+4) + (2+4+6) + (2+4+6+8) + ...... + (2+4+6+8+....+2n), where i-th term in the series is the sum of first i even natural numbers.Examples: " }, { "code": null, "e": 26308, "s": 26186, "text": "Input : n = 2\nOutput : 8\n(2) + (2+4) = 8\n\nInput : n = 5\nOutput : 70\n(2) + (2+4) + (2+4+6) + (2+4+6+8) + (2+4+6+8+10) = 70" }, { "code": null, "e": 26413, "s": 26310, "text": "Naive Approach: Using two loops get the sum of each i-th term and then add those sum to the final sum." }, { "code": null, "e": 26417, "s": 26413, "text": "C++" }, { "code": null, "e": 26422, "s": 26417, "text": "Java" }, { "code": null, "e": 26430, "s": 26422, "text": "Python3" }, { "code": null, "e": 26433, "s": 26430, "text": "C#" }, { "code": null, "e": 26437, "s": 26433, "text": "PHP" }, { "code": null, "e": 26448, "s": 26437, "text": "Javascript" }, { "code": "// C++ implementation to find the sum// of the given series#include <bits/stdc++.h> using namespace std; // function to find the sum// of the given seriesint sumOfTheSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) { // first term of each i-th term int k = 2; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum;} // Driver program to test aboveint main(){ int n = 5; cout << \"Sum = \" << sumOfTheSeries(n); return 0;}", "e": 27017, "s": 26448, "text": null }, { "code": "// Java implementation to find the// sum of the given seriesclass GFG{ // function to find the sum // of the given series static int sumOfTheSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) { // first term of each i-th term int k = 2; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum; } // Driver program to test above public static void main(String[] args) { int n = 5; System.out.printf(\"Sum = %d\", sumOfTheSeries(n)); }} // This code is contributed by// Smitha Dinesh Semwal", "e": 27755, "s": 27017, "text": null }, { "code": "# Python3 implementation to find# the sum of the given series # function to find the sum# of the given seriesdef sumOfTheSeries(n): sum = 0 for i in range(0, n + 1): # first term of each i-th # term k = 2 for j in range(1, i + 1): sum = sum + k; # next term k = k + 2 # required sum return sum; # Driver program to test aboven = 5ans = sumOfTheSeries(n);print (ans) # This code is contributed by saloni1297.", "e": 28243, "s": 27755, "text": null }, { "code": "// C# implementation to find the// sum of the given seriesusing System; class GFG{ // function to find the sum // of the given series static int sumOfTheSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) { // first term of each i-th term int k = 2; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum; } // Driver program to test above public static void Main() { int n = 5; Console.Write(\"Sum = \"+ sumOfTheSeries(n)); }} // This code is contributed by// vt_m", "e": 28957, "s": 28243, "text": null }, { "code": "<?php// PHP implementation to find// the sum of the given series // function to find the sum// of the given series function sumOfTheSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) { // first term of each // i-th term $k = 2; for ($j = 1; $j <= $i; $j++) { $sum += $k; // next term $k += 2; } } // required sum return $sum;} // Driver program to test above $n = 5; echo \"Sum = \", sumOfTheSeries($n); // This code is contributed by ajit.?>", "e": 29504, "s": 28957, "text": null }, { "code": "<script>// Javascript implementation to find// the sum of the given series // function to find the sum// of the given series function sumOfTheSeries(n){ let sum = 0; for (let i = 1; i <= n; i++) { // first term of each // i-th term let k = 2; for (let j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum;} // Driver program to test above let n = 5; document.write(\"Sum = \" + sumOfTheSeries(n)); // This code is contributed by gfgking.</script>", "e": 30086, "s": 29504, "text": null }, { "code": null, "e": 30095, "s": 30086, "text": "Output: " }, { "code": null, "e": 30104, "s": 30095, "text": "Sum = 70" }, { "code": null, "e": 30171, "s": 30104, "text": "Efficient Approach: Let an be the n-th term of the given series. " }, { "code": null, "e": 30268, "s": 30171, "text": "an = (2 + 4 + 6 + 8 +....+ 2n).\n = sum of first n even numbers.\n = n * (n + 1).\n = n2 + n." }, { "code": null, "e": 30322, "s": 30268, "text": "Refer this post for the proof of above formula.Now, " }, { "code": null, "e": 30379, "s": 30322, "text": "Refer this and this post for the proof of above formula." }, { "code": null, "e": 30383, "s": 30379, "text": "C++" }, { "code": null, "e": 30388, "s": 30383, "text": "Java" }, { "code": null, "e": 30396, "s": 30388, "text": "Python3" }, { "code": null, "e": 30399, "s": 30396, "text": "C#" }, { "code": null, "e": 30403, "s": 30399, "text": "PHP" }, { "code": null, "e": 30414, "s": 30403, "text": "Javascript" }, { "code": "// C++ implementation to find the sum// of the given series#include <bits/stdc++.h>using namespace std; // function to find the sum// of the given seriesint sumOfTheSeries(int n){ // sum of 1st n natural numbers int sum_n = (n * (n + 1) / 2); // sum of squares of 1st n natural numbers int sum_sq_n = (n * (n + 1) / 2) * (2 * n + 1) / 3; // required sum return (sum_n + sum_sq_n);} // Driver program to test aboveint main(){ int n = 5; cout << \"Sum = \" << sumOfTheSeries(n); return 0;}", "e": 30982, "s": 30414, "text": null }, { "code": "// Java implementation to find the// sum of the given seriesclass GFG{ // function to find the sum // of the given series static int sumOfTheSeries(int n) { // sum of 1st n natural numbers int sum_n = (n * (n + 1) / 2); // sum of squares of 1st n natural // numbers int sum_sq_n = (n * (n + 1) / 2) * (2 * n + 1) / 3; // required sum return (sum_n + sum_sq_n); } // Driver program to test above public static void main(String[] args) { int n = 5; System.out.printf(\"Sum = %d\", sumOfTheSeries(n)); }} // This code is contributed by//Smitha Dinesh Semwal", "e": 31725, "s": 30982, "text": null }, { "code": "# Python3 implementation to find# the sum of the given series # function to find the sum# of the given seriesdef sumOfTheSeries(n): # sum of 1st n natural numbers sum_n = int((n * (n + 1) / 2)); # sum of squares of 1st n natural numbers sum_sq_n = int ((n * (n + 1) / 2) * (2 * n + 1) / 3) # required sum return (sum_n + sum_sq_n); # Driver program to test aboven = 5ans = sumOfTheSeries(n)print (ans) # This code is contributed by saloni1297.", "e": 32214, "s": 31725, "text": null }, { "code": "// C# implementation to find the// sum of the given seriesusing System; class GFG{ // function to find the sum // of the given series static int sumOfTheSeries(int n) { // sum of 1st n natural numbers int sum_n = (n * (n + 1) / 2); // sum of squares of 1st n // natural numbers int sum_sq_n = (n * (n + 1) / 2) * (2 * n + 1) / 3; // required sum return (sum_n + sum_sq_n); } // Driver program to test above public static void Main() { int n = 5; Console.Write(\"Sum = \"+ sumOfTheSeries(n)); }} // This code is contributed by// vt_m", "e": 32935, "s": 32214, "text": null }, { "code": "<?php// PHP implementation// to find the sum// of the given series // function to find the// sum of the given seriesfunction sumOfTheSeries($n){ // sum of 1st n // natural numbers $sum_n = ($n * ($n + 1) / 2); // sum of squares of // 1st n natural numbers $sum_sq_n = ($n * ($n + 1) / 2) * (2 * $n + 1) / 3; // required sum return ($sum_n + $sum_sq_n);} // Driver Code$n = 5;echo (\"Sum = \".sumOfTheSeries($n)); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 33484, "s": 32935, "text": null }, { "code": "<script> // JavaScript Program to find the// sum of the given series // function to find the sum // of the given series function sumOfTheSeries(n) { // sum of 1st n natural numbers let sum_n = (n * (n + 1) / 2); // sum of squares of 1st n natural // numbers let sum_sq_n = (n * (n + 1) / 2) * (2 * n + 1) / 3; // required sum return (sum_n + sum_sq_n); } // Driver code let n = 5; document.write(\"Sum = \" + sumOfTheSeries(n)); </script>", "e": 34140, "s": 33484, "text": null }, { "code": null, "e": 34149, "s": 34140, "text": "Output: " }, { "code": null, "e": 34158, "s": 34149, "text": "Sum = 70" }, { "code": null, "e": 34164, "s": 34158, "text": "jit_t" }, { "code": null, "e": 34176, "s": 34164, "text": "manishshaw1" }, { "code": null, "e": 34186, "s": 34176, "text": "splevel62" }, { "code": null, "e": 34194, "s": 34186, "text": "gfgking" }, { "code": null, "e": 34213, "s": 34194, "text": "surindertarika1234" }, { "code": null, "e": 34226, "s": 34213, "text": "simmytarika5" }, { "code": null, "e": 34243, "s": 34226, "text": "surinderdawra388" }, { "code": null, "e": 34250, "s": 34243, "text": "series" }, { "code": null, "e": 34261, "s": 34250, "text": "series-sum" }, { "code": null, "e": 34274, "s": 34261, "text": "Mathematical" }, { "code": null, "e": 34287, "s": 34274, "text": "Mathematical" }, { "code": null, "e": 34294, "s": 34287, "text": "series" }, { "code": null, "e": 34392, "s": 34294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34436, "s": 34392, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34478, "s": 34436, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 34509, "s": 34478, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34580, "s": 34509, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 34605, "s": 34580, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 34637, "s": 34605, "text": "Check if a number is Palindrome" }, { "code": null, "e": 34670, "s": 34637, "text": "Program to multiply two matrices" }, { "code": null, "e": 34705, "s": 34670, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 34751, "s": 34705, "text": "Merge two sorted arrays with O(1) extra space" } ]
Shortest Job First CPU Scheduling with predicted burst time - GeeksforGeeks
16 Aug, 2019 Prerequisite – CPU Scheduling, SJF – Set 1 (Non- preemptive), Set 2 (Preemptive) Shortest Job First (SJF) is an optimal scheduling algorithm as it gives maximum Throughput and minimum average waiting time(WT) and turn around time (TAT) but it is not practically implementable because Burst-Time of a process can’t be predicted in advance. We may not know the length of the next CPU burst, but we may be able to predict its value. We expect the next CPU burst will be similar in length to the previous ones. By computing an approximation of the length of the next CPU burst, we can pick the process with the shortest predicted CPU burst. There are two methods by which we can predict the burst time of the process : 1. Static method – We can predict the Burst-Time by two factors : Process size –Let say we have Process Pold having size 200 KB which is already executed and its Burst-time is 20 Units of time, now lets say we have a New Process Pnew having size 201 KB which is yet to be executed.We take Burst-Time of already executed process Pold which is almost of same size as that of New process as Burst-Time of New Process Pnew. Process type –We can predict Burst-Time depending on the Type of Process. Operating System process(like scheduler, dispatcher, segmentation, fragmentation) are faster than User process( Gaming, application softwares ). Burst-Time for any New O.S process can be predicted from any old O.S process of similar type and same for User process.Note – Static method for burst time prediction is not reliable as it is always not predicted correctly.2. Dynamic method – Let ti be the actual Burst-Time of ith process and Τn+1 be the predicted Burst-time for n+1th process.Simple average – Given n processes ( P1, P2... Pn)Τn+1 = 1/n(Σi=1 to n ti)Exponential average (Aging) –Τn+1 = αtn + (1 - α)Τnwhere α = is smoothing factor and 0 <= α <= 1 ,tn = actual burst time of nth process,Τn = predicted burst time of nth process.General term,αtn + (1 - α)αtn-1 + (1 - α)2αtn-2...+ (1 - α)jαtn-j...+ (1 - α)n+1Τ0 Τ0 is a constant or overall system average.Smoothening factor (α) – It controls the relative weight of recent and past history in our prediction.If α = 0, Τn+1 = Τn i.e. no change in value of initial predicted burst time.If α = 1, Τn+1 = tn i.e. predicted Burst-Time of new process will always change according to actual Burst-time of nth process.If α = 1/2, recent and past history are equally weighted.Example –Calculate the exponential averaging with T1 = 10, α = 0.5 and the algorithm is SJF with previous runs as 8, 7, 4, 16.(a) 9(b) 8(c) 7.5(d) NoneExplanation :Initially T1 = 10 and α = 0.5 and the run times given are 8, 7, 4, 16 as it is shortest job first,So the possible order in which these processes would serve will be 4, 7, 8, 16 since SJF is a non-preemptive technique.So, using formula: T2 = α*t1 + (1-α)T1so we have,T2 = 0.5*4 + 0.5*10 = 7, here t1 = 4 and T1 = 10T3 = 0.5*7 + 0.5*7 = 7, here t2 = 7 and T2 = 7T4 = 0.5*8 + 0.5*7 = 7.5, here t3 = 8 and T3 = 7So the future prediction for 4th process will be T4 = 7.5 which is the option(c).This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave Note – Static method for burst time prediction is not reliable as it is always not predicted correctly. 2. Dynamic method – Let ti be the actual Burst-Time of ith process and Τn+1 be the predicted Burst-time for n+1th process. Simple average – Given n processes ( P1, P2... Pn)Τn+1 = 1/n(Σi=1 to n ti) Τn+1 = 1/n(Σi=1 to n ti) Exponential average (Aging) –Τn+1 = αtn + (1 - α)Τnwhere α = is smoothing factor and 0 <= α <= 1 ,tn = actual burst time of nth process,Τn = predicted burst time of nth process.General term,αtn + (1 - α)αtn-1 + (1 - α)2αtn-2...+ (1 - α)jαtn-j...+ (1 - α)n+1Τ0 Τ0 is a constant or overall system average. Τn+1 = αtn + (1 - α)Τn where α = is smoothing factor and 0 <= α <= 1 , tn = actual burst time of nth process,Τn = predicted burst time of nth process. General term, αtn + (1 - α)αtn-1 + (1 - α)2αtn-2...+ (1 - α)jαtn-j...+ (1 - α)n+1Τ0 Τ0 is a constant or overall system average. Smoothening factor (α) – It controls the relative weight of recent and past history in our prediction. If α = 0, Τn+1 = Τn i.e. no change in value of initial predicted burst time. If α = 1, Τn+1 = tn i.e. predicted Burst-Time of new process will always change according to actual Burst-time of nth process. If α = 1/2, recent and past history are equally weighted. Example –Calculate the exponential averaging with T1 = 10, α = 0.5 and the algorithm is SJF with previous runs as 8, 7, 4, 16.(a) 9(b) 8(c) 7.5(d) None Explanation :Initially T1 = 10 and α = 0.5 and the run times given are 8, 7, 4, 16 as it is shortest job first,So the possible order in which these processes would serve will be 4, 7, 8, 16 since SJF is a non-preemptive technique.So, using formula: T2 = α*t1 + (1-α)T1so we have,T2 = 0.5*4 + 0.5*10 = 7, here t1 = 4 and T1 = 10T3 = 0.5*7 + 0.5*7 = 7, here t2 = 7 and T2 = 7T4 = 0.5*8 + 0.5*7 = 7.5, here t3 = 8 and T3 = 7So the future prediction for 4th process will be T4 = 7.5 which is the option(c). This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. pratikkatariya02 GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Page Replacement Algorithms in Operating Systems Differences between TCP and UDP Introduction of Operating System - Set 1 Inter Process Communication (IPC) Semaphores in Process Synchronization Banker's Algorithm in Operating System Page Replacement Algorithms in Operating Systems Paging in Operating System Introduction of Deadlock in Operating System Introduction of Operating System - Set 1
[ { "code": null, "e": 26135, "s": 26107, "text": "\n16 Aug, 2019" }, { "code": null, "e": 26216, "s": 26135, "text": "Prerequisite – CPU Scheduling, SJF – Set 1 (Non- preemptive), Set 2 (Preemptive)" }, { "code": null, "e": 26474, "s": 26216, "text": "Shortest Job First (SJF) is an optimal scheduling algorithm as it gives maximum Throughput and minimum average waiting time(WT) and turn around time (TAT) but it is not practically implementable because Burst-Time of a process can’t be predicted in advance." }, { "code": null, "e": 26772, "s": 26474, "text": "We may not know the length of the next CPU burst, but we may be able to predict its value. We expect the next CPU burst will be similar in length to the previous ones. By computing an approximation of the length of the next CPU burst, we can pick the process with the shortest predicted CPU burst." }, { "code": null, "e": 26850, "s": 26772, "text": "There are two methods by which we can predict the burst time of the process :" }, { "code": null, "e": 26916, "s": 26850, "text": "1. Static method – We can predict the Burst-Time by two factors :" }, { "code": null, "e": 27270, "s": 26916, "text": "Process size –Let say we have Process Pold having size 200 KB which is already executed and its Burst-time is 20 Units of time, now lets say we have a New Process Pnew having size 201 KB which is yet to be executed.We take Burst-Time of already executed process Pold which is almost of same size as that of New process as Burst-Time of New Process Pnew." }, { "code": null, "e": 29687, "s": 27270, "text": "Process type –We can predict Burst-Time depending on the Type of Process. Operating System process(like scheduler, dispatcher, segmentation, fragmentation) are faster than User process( Gaming, application softwares ). Burst-Time for any New O.S process can be predicted from any old O.S process of similar type and same for User process.Note – Static method for burst time prediction is not reliable as it is always not predicted correctly.2. Dynamic method – Let ti be the actual Burst-Time of ith process and Τn+1 be the predicted Burst-time for n+1th process.Simple average – Given n processes ( P1, P2... Pn)Τn+1 = 1/n(Σi=1 to n ti)Exponential average (Aging) –Τn+1 = αtn + (1 - α)Τnwhere α = is smoothing factor and 0 <= α <= 1 ,tn = actual burst time of nth process,Τn = predicted burst time of nth process.General term,αtn + (1 - α)αtn-1 + (1 - α)2αtn-2...+ (1 - α)jαtn-j...+ (1 - α)n+1Τ0 Τ0 is a constant or overall system average.Smoothening factor (α) – It controls the relative weight of recent and past history in our prediction.If α = 0, Τn+1 = Τn i.e. no change in value of initial predicted burst time.If α = 1, Τn+1 = tn i.e. predicted Burst-Time of new process will always change according to actual Burst-time of nth process.If α = 1/2, recent and past history are equally weighted.Example –Calculate the exponential averaging with T1 = 10, α = 0.5 and the algorithm is SJF with previous runs as 8, 7, 4, 16.(a) 9(b) 8(c) 7.5(d) NoneExplanation :Initially T1 = 10 and α = 0.5 and the run times given are 8, 7, 4, 16 as it is shortest job first,So the possible order in which these processes would serve will be 4, 7, 8, 16 since SJF is a non-preemptive technique.So, using formula: T2 = α*t1 + (1-α)T1so we have,T2 = 0.5*4 + 0.5*10 = 7, here t1 = 4 and T1 = 10T3 = 0.5*7 + 0.5*7 = 7, here t2 = 7 and T2 = 7T4 = 0.5*8 + 0.5*7 = 7.5, here t3 = 8 and T3 = 7So the future prediction for 4th process will be T4 = 7.5 which is the option(c).This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29791, "s": 29687, "text": "Note – Static method for burst time prediction is not reliable as it is always not predicted correctly." }, { "code": null, "e": 29914, "s": 29791, "text": "2. Dynamic method – Let ti be the actual Burst-Time of ith process and Τn+1 be the predicted Burst-time for n+1th process." }, { "code": null, "e": 29989, "s": 29914, "text": "Simple average – Given n processes ( P1, P2... Pn)Τn+1 = 1/n(Σi=1 to n ti)" }, { "code": null, "e": 30014, "s": 29989, "text": "Τn+1 = 1/n(Σi=1 to n ti)" }, { "code": null, "e": 30318, "s": 30014, "text": "Exponential average (Aging) –Τn+1 = αtn + (1 - α)Τnwhere α = is smoothing factor and 0 <= α <= 1 ,tn = actual burst time of nth process,Τn = predicted burst time of nth process.General term,αtn + (1 - α)αtn-1 + (1 - α)2αtn-2...+ (1 - α)jαtn-j...+ (1 - α)n+1Τ0 Τ0 is a constant or overall system average." }, { "code": null, "e": 30341, "s": 30318, "text": "Τn+1 = αtn + (1 - α)Τn" }, { "code": null, "e": 30389, "s": 30341, "text": "where α = is smoothing factor and 0 <= α <= 1 ," }, { "code": null, "e": 30469, "s": 30389, "text": "tn = actual burst time of nth process,Τn = predicted burst time of nth process." }, { "code": null, "e": 30483, "s": 30469, "text": "General term," }, { "code": null, "e": 30554, "s": 30483, "text": "αtn + (1 - α)αtn-1 + (1 - α)2αtn-2...+ (1 - α)jαtn-j...+ (1 - α)n+1Τ0 " }, { "code": null, "e": 30598, "s": 30554, "text": "Τ0 is a constant or overall system average." }, { "code": null, "e": 30701, "s": 30598, "text": "Smoothening factor (α) – It controls the relative weight of recent and past history in our prediction." }, { "code": null, "e": 30778, "s": 30701, "text": "If α = 0, Τn+1 = Τn i.e. no change in value of initial predicted burst time." }, { "code": null, "e": 30910, "s": 30778, "text": "If α = 1, Τn+1 = tn i.e. predicted Burst-Time of new process will always change according to actual Burst-time of nth process." }, { "code": null, "e": 30968, "s": 30910, "text": "If α = 1/2, recent and past history are equally weighted." }, { "code": null, "e": 31120, "s": 30968, "text": "Example –Calculate the exponential averaging with T1 = 10, α = 0.5 and the algorithm is SJF with previous runs as 8, 7, 4, 16.(a) 9(b) 8(c) 7.5(d) None" }, { "code": null, "e": 31623, "s": 31120, "text": "Explanation :Initially T1 = 10 and α = 0.5 and the run times given are 8, 7, 4, 16 as it is shortest job first,So the possible order in which these processes would serve will be 4, 7, 8, 16 since SJF is a non-preemptive technique.So, using formula: T2 = α*t1 + (1-α)T1so we have,T2 = 0.5*4 + 0.5*10 = 7, here t1 = 4 and T1 = 10T3 = 0.5*7 + 0.5*7 = 7, here t2 = 7 and T2 = 7T4 = 0.5*8 + 0.5*7 = 7.5, here t3 = 8 and T3 = 7So the future prediction for 4th process will be T4 = 7.5 which is the option(c)." }, { "code": null, "e": 31922, "s": 31623, "text": "This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 32047, "s": 31922, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 32064, "s": 32047, "text": "pratikkatariya02" }, { "code": null, "e": 32072, "s": 32064, "text": "GATE CS" }, { "code": null, "e": 32090, "s": 32072, "text": "Operating Systems" }, { "code": null, "e": 32108, "s": 32090, "text": "Operating Systems" }, { "code": null, "e": 32206, "s": 32108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32255, "s": 32206, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 32287, "s": 32255, "text": "Differences between TCP and UDP" }, { "code": null, "e": 32328, "s": 32287, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 32362, "s": 32328, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 32400, "s": 32362, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 32439, "s": 32400, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 32488, "s": 32439, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 32515, "s": 32488, "text": "Paging in Operating System" }, { "code": null, "e": 32560, "s": 32515, "text": "Introduction of Deadlock in Operating System" } ]
How to add text in a heatmap cell annotations using seaborn in Python ? - GeeksforGeeks
24 Jan, 2021 Prerequisite: Seaborn heatmap Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. In this, to represent more common values or higher activities brighter colors basically reddish colors are used and to represent less common or activity values, darker colors are preferred. Heatmap is also defined by the name of the shading matrix. Heatmaps in Seaborn can be plotted by using the seaborn.heatmap() function. Syntax: seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs) Important Parameters: data: 2D dataset that can be coerced into an ndarray. vmin, vmax: Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments. cmap: The mapping from data values to color space. center: The value at which to center the colormap when plotting divergent data. annot: If True, write the data value in each cell. fmt: String formatting code to use when adding annotations. linewidths: Width of the lines that will divide each cell. linecolor: Color of the lines that will divide each cell. cbar: Whether to draw a colorbar. All the parameters except data are optional. Returns: An object of type matplotlib.axes._subplots.AxesSubplot Heatmap annotations are a great way of showing additional information about rows and columns in the heatmap. Generally, to show data values over heatmap we set annot parameter to True but if you want to add text to cell annotations it can be done in the following ways – Approach 1: Import module Create data or load dataset Create another array-like data having text-values you want to show on heatmap (with the same shape as your data) Give this array-like data as a value to annot parameter of the heatmap. fmt parameter of the heatmap is necessary if you want to add non-numeric values. This parameter is used to add String formatting code to use when adding annotations. Draw heatmap Display plot Example: Python3 # importing librariesimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # creating random datadata = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]) # creating array of texttext = np.array([['A', 'B', 'C', 'D', 'E'], ['F', 'G', 'H', 'I', 'J'], ['K', 'L', 'M', 'N', 'O']]) # creating subplotfig, ax = plt.subplots() # drawing heatmap on current axesax = sns.heatmap(data, annot=text, fmt="") Output : If you want to show text along with data values you have to create a custom annot by concatenating these two values. Approach 2: Import module Create or load data Declare a data array Reshape data array and text array into 1D using np.flatten(). Then zip them together to iterate over both text and value. Use formatted strings to create customized new value. Return a reshaped array of the same size containing customized values. Create heatmap Display plot Example : Python3 # importing librariesimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # creating random datadata = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])text = np.array([['A', 'B', 'C', 'D', 'E'], ['F', 'G', 'H', 'I', 'J'], ['K', 'L', 'M', 'N', 'O']]) # combining text with valuesformatted_text = (np.asarray(["{0}\n{1:.2f}".format( text, data) for text, data in zip(text.flatten(), data.flatten())])).reshape(3, 5) # drawing heatmapfig, ax = plt.subplots()ax = sns.heatmap(data, annot=formatted_text, fmt="", cmap="cool") Output : Python-Seaborn 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": "\n24 Jan, 2021" }, { "code": null, "e": 25567, "s": 25537, "text": "Prerequisite: Seaborn heatmap" }, { "code": null, "e": 26000, "s": 25567, "text": "Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. In this, to represent more common values or higher activities brighter colors basically reddish colors are used and to represent less common or activity values, darker colors are preferred. Heatmap is also defined by the name of the shading matrix. Heatmaps in Seaborn can be plotted by using the seaborn.heatmap() function." }, { "code": null, "e": 26149, "s": 26000, "text": "Syntax: seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs)" }, { "code": null, "e": 26171, "s": 26149, "text": "Important Parameters:" }, { "code": null, "e": 26225, "s": 26171, "text": "data: 2D dataset that can be coerced into an ndarray." }, { "code": null, "e": 26339, "s": 26225, "text": "vmin, vmax: Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments." }, { "code": null, "e": 26390, "s": 26339, "text": "cmap: The mapping from data values to color space." }, { "code": null, "e": 26470, "s": 26390, "text": "center: The value at which to center the colormap when plotting divergent data." }, { "code": null, "e": 26521, "s": 26470, "text": "annot: If True, write the data value in each cell." }, { "code": null, "e": 26581, "s": 26521, "text": "fmt: String formatting code to use when adding annotations." }, { "code": null, "e": 26640, "s": 26581, "text": "linewidths: Width of the lines that will divide each cell." }, { "code": null, "e": 26698, "s": 26640, "text": "linecolor: Color of the lines that will divide each cell." }, { "code": null, "e": 26732, "s": 26698, "text": "cbar: Whether to draw a colorbar." }, { "code": null, "e": 26777, "s": 26732, "text": "All the parameters except data are optional." }, { "code": null, "e": 26842, "s": 26777, "text": "Returns: An object of type matplotlib.axes._subplots.AxesSubplot" }, { "code": null, "e": 27113, "s": 26842, "text": "Heatmap annotations are a great way of showing additional information about rows and columns in the heatmap. Generally, to show data values over heatmap we set annot parameter to True but if you want to add text to cell annotations it can be done in the following ways –" }, { "code": null, "e": 27127, "s": 27113, "text": "Approach 1: " }, { "code": null, "e": 27141, "s": 27127, "text": "Import module" }, { "code": null, "e": 27170, "s": 27141, "text": "Create data or load dataset " }, { "code": null, "e": 27283, "s": 27170, "text": "Create another array-like data having text-values you want to show on heatmap (with the same shape as your data)" }, { "code": null, "e": 27355, "s": 27283, "text": "Give this array-like data as a value to annot parameter of the heatmap." }, { "code": null, "e": 27521, "s": 27355, "text": "fmt parameter of the heatmap is necessary if you want to add non-numeric values. This parameter is used to add String formatting code to use when adding annotations." }, { "code": null, "e": 27534, "s": 27521, "text": "Draw heatmap" }, { "code": null, "e": 27547, "s": 27534, "text": "Display plot" }, { "code": null, "e": 27557, "s": 27547, "text": "Example: " }, { "code": null, "e": 27565, "s": 27557, "text": "Python3" }, { "code": "# importing librariesimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # creating random datadata = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]) # creating array of texttext = np.array([['A', 'B', 'C', 'D', 'E'], ['F', 'G', 'H', 'I', 'J'], ['K', 'L', 'M', 'N', 'O']]) # creating subplotfig, ax = plt.subplots() # drawing heatmap on current axesax = sns.heatmap(data, annot=text, fmt=\"\")", "e": 28033, "s": 27565, "text": null }, { "code": null, "e": 28043, "s": 28033, "text": "Output : " }, { "code": null, "e": 28160, "s": 28043, "text": "If you want to show text along with data values you have to create a custom annot by concatenating these two values." }, { "code": null, "e": 28174, "s": 28160, "text": "Approach 2: " }, { "code": null, "e": 28188, "s": 28174, "text": "Import module" }, { "code": null, "e": 28208, "s": 28188, "text": "Create or load data" }, { "code": null, "e": 28229, "s": 28208, "text": "Declare a data array" }, { "code": null, "e": 28291, "s": 28229, "text": "Reshape data array and text array into 1D using np.flatten()." }, { "code": null, "e": 28351, "s": 28291, "text": "Then zip them together to iterate over both text and value." }, { "code": null, "e": 28405, "s": 28351, "text": "Use formatted strings to create customized new value." }, { "code": null, "e": 28476, "s": 28405, "text": "Return a reshaped array of the same size containing customized values." }, { "code": null, "e": 28491, "s": 28476, "text": "Create heatmap" }, { "code": null, "e": 28504, "s": 28491, "text": "Display plot" }, { "code": null, "e": 28515, "s": 28504, "text": "Example : " }, { "code": null, "e": 28523, "s": 28515, "text": "Python3" }, { "code": "# importing librariesimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt # creating random datadata = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])text = np.array([['A', 'B', 'C', 'D', 'E'], ['F', 'G', 'H', 'I', 'J'], ['K', 'L', 'M', 'N', 'O']]) # combining text with valuesformatted_text = (np.asarray([\"{0}\\n{1:.2f}\".format( text, data) for text, data in zip(text.flatten(), data.flatten())])).reshape(3, 5) # drawing heatmapfig, ax = plt.subplots()ax = sns.heatmap(data, annot=formatted_text, fmt=\"\", cmap=\"cool\")", "e": 29123, "s": 28523, "text": null }, { "code": null, "e": 29133, "s": 29123, "text": "Output : " }, { "code": null, "e": 29148, "s": 29133, "text": "Python-Seaborn" }, { "code": null, "e": 29155, "s": 29148, "text": "Python" }, { "code": null, "e": 29253, "s": 29155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29285, "s": 29253, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29327, "s": 29285, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29369, "s": 29327, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29396, "s": 29369, "text": "Python Classes and Objects" }, { "code": null, "e": 29452, "s": 29396, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29474, "s": 29452, "text": "Defaultdict in Python" }, { "code": null, "e": 29513, "s": 29474, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29544, "s": 29513, "text": "Python | os.path.join() method" }, { "code": null, "e": 29573, "s": 29544, "text": "Create a directory in Python" } ]
expandtabs() method in Python - GeeksforGeeks
13 Oct, 2020 expandtabs is a method specified in Strings in Python 3. Sometimes, there is a need of specifying the space in the string, but the amount of space to be left is uncertain and depending upon the environment and conditions. For these cases, the need to modify the string, again and again, is a tedious task. Hence python in its library has “expandtabs()” which specifies the amount of space to be substituted with the “\t” symbol in the string. Syntax : expandtabs(space_size) Parameters :space_size : Specifies the space that is to be replaced with the “\t” symbol in the string. By default the space is 8. Returns : Returns the modified string with tabs replaced by the space. Code #1 : Code to demonstrate expandtabs() # Python3 code to demonstrate# working of expandtabs() # initializing string str = "i\tlove\tgfg" # using expandtabs to insert spacingprint("Modified string using default spacing: ", end ="")print(str.expandtabs()) print("\r") # using expandtabs to insert spacingprint("Modified string using less spacing: ", end ="")print(str.expandtabs(2)) print("\r") # using expandtabs to insert spacingprint("Modified string using more spacing: ", end ="")print(str.expandtabs(12)) print("\r") Output: Modified string using default spacing: i love gfg Modified string using less spacing: i love gfg Modified string using more spacing: i love gfg Exception :The exception of using this method is that it doesn’t accept the floating-point number if we want to decide the exact precision of the space we require. Code #2 : Code to demonstrate exception of expandtabs() # Python3 code to demonstrate# exception of expandtabs() # initializing string st = "i\tlove\tgfg" # using expandtabs to insert spacingtry: print("Modified string using default spacing: ") print(st.expandtabs(10.5)) except Exception as e: print("Error !! The error occurred is :") print(str(e)) Output: Modified string using default spacing: Error !! The error occurred is : integer argument expected, got float Applications :There are many possible applications where this can be used such as text formatting or documentation where user requirements keep on changing. Python-Built-in-functions Python-Functions python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 25065, "s": 25037, "text": "\n13 Oct, 2020" }, { "code": null, "e": 25122, "s": 25065, "text": "expandtabs is a method specified in Strings in Python 3." }, { "code": null, "e": 25508, "s": 25122, "text": "Sometimes, there is a need of specifying the space in the string, but the amount of space to be left is uncertain and depending upon the environment and conditions. For these cases, the need to modify the string, again and again, is a tedious task. Hence python in its library has “expandtabs()” which specifies the amount of space to be substituted with the “\\t” symbol in the string." }, { "code": null, "e": 25540, "s": 25508, "text": "Syntax : expandtabs(space_size)" }, { "code": null, "e": 25671, "s": 25540, "text": "Parameters :space_size : Specifies the space that is to be replaced with the “\\t” symbol in the string. By default the space is 8." }, { "code": null, "e": 25742, "s": 25671, "text": "Returns : Returns the modified string with tabs replaced by the space." }, { "code": null, "e": 25786, "s": 25742, "text": " Code #1 : Code to demonstrate expandtabs()" }, { "code": "# Python3 code to demonstrate# working of expandtabs() # initializing string str = \"i\\tlove\\tgfg\" # using expandtabs to insert spacingprint(\"Modified string using default spacing: \", end =\"\")print(str.expandtabs()) print(\"\\r\") # using expandtabs to insert spacingprint(\"Modified string using less spacing: \", end =\"\")print(str.expandtabs(2)) print(\"\\r\") # using expandtabs to insert spacingprint(\"Modified string using more spacing: \", end =\"\")print(str.expandtabs(12)) print(\"\\r\")", "e": 26275, "s": 25786, "text": null }, { "code": null, "e": 26283, "s": 26275, "text": "Output:" }, { "code": null, "e": 26457, "s": 26283, "text": "Modified string using default spacing: i love gfg\n\nModified string using less spacing: i love gfg\n\nModified string using more spacing: i love gfg\n" }, { "code": null, "e": 26621, "s": 26457, "text": "Exception :The exception of using this method is that it doesn’t accept the floating-point number if we want to decide the exact precision of the space we require." }, { "code": null, "e": 26678, "s": 26621, "text": " Code #2 : Code to demonstrate exception of expandtabs()" }, { "code": "# Python3 code to demonstrate# exception of expandtabs() # initializing string st = \"i\\tlove\\tgfg\" # using expandtabs to insert spacingtry: print(\"Modified string using default spacing: \") print(st.expandtabs(10.5)) except Exception as e: print(\"Error !! The error occurred is :\") print(str(e))", "e": 26992, "s": 26678, "text": null }, { "code": null, "e": 27000, "s": 26992, "text": "Output:" }, { "code": null, "e": 27111, "s": 27000, "text": "Modified string using default spacing: \nError !! The error occurred is :\ninteger argument expected, got float\n" }, { "code": null, "e": 27268, "s": 27111, "text": "Applications :There are many possible applications where this can be used such as text formatting or documentation where user requirements keep on changing." }, { "code": null, "e": 27294, "s": 27268, "text": "Python-Built-in-functions" }, { "code": null, "e": 27311, "s": 27294, "text": "Python-Functions" }, { "code": null, "e": 27325, "s": 27311, "text": "python-string" }, { "code": null, "e": 27332, "s": 27325, "text": "Python" }, { "code": null, "e": 27430, "s": 27332, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27458, "s": 27430, "text": "Read JSON file using Python" }, { "code": null, "e": 27508, "s": 27458, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27530, "s": 27508, "text": "Python map() function" }, { "code": null, "e": 27574, "s": 27530, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 27592, "s": 27574, "text": "Python Dictionary" }, { "code": null, "e": 27615, "s": 27592, "text": "Taking input in Python" }, { "code": null, "e": 27650, "s": 27615, "text": "Read a file line by line in Python" }, { "code": null, "e": 27682, "s": 27650, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27704, "s": 27682, "text": "Enumerate() in Python" } ]
Tiling Problem using Divide and Conquer algorithm - GeeksforGeeks
25 Feb, 2022 Given a n by n board where n is of form 2k where k >= 1 (Basically n is a power of 2 with minimum value as 2). The board has one missing cell (of size 1 x 1). Fill the board using L shaped tiles. A L shaped tile is a 2 x 2 square with one cell of size 1×1 missing. Figure 1: An example inputThis problem can be solved using Divide and Conquer. Below is the recursive algorithm. // n is size of given square, p is location of missing cell Tile(int n, Point p) 1) Base case: n = 2, A 2 x 2 square with one cell missing is nothing but a tile and can be filled with a single tile. 2) Place a L shaped tile at the center such that it does not cover the n/2 * n/2 subsquare that has a missing square. Now all four subsquares of size n/2 x n/2 have a missing cell (a cell that doesn't need to be filled). See figure 2 below. 3) Solve the problem recursively for following four. Let p1, p2, p3 and p4 be positions of the 4 missing cells in 4 squares. a) Tile(n/2, p1) b) Tile(n/2, p2) c) Tile(n/2, p3) d) Tile(n/2, p3) The below diagrams show working of above algorithm Figure 2: After placing the first tile Figure 3: Recurring for the first subsquare. Figure 4: Shows the first step in all four subsquares. Examples: Input : size = 2 and mark coordinates = (0, 0) Output : -1 1 1 1 Coordinate (0, 0) is marked. So, no tile is there. In the remaining three positions, a tile is placed with its number as 1. Input : size = 4 and mark coordinates = (0, 0) Output : -1 3 2 2 3 3 1 2 4 1 1 5 4 4 5 5 Below is the implementation of above idea: C++ Java C# Python3 Javascript // C++ program to place tiles#include <bits/stdc++.h>using namespace std; int size_of_grid, b, a, cnt = 0;int arr[128][128]; // Placing tile at the given coordinatesvoid place(int x1, int y1, int x2, int y2, int x3, int y3){ cnt++; arr[x1][y1] = cnt; arr[x2][y2] = cnt; arr[x3][y3] = cnt;}// Quadrant names// 1 2// 3 4 // Function based on divide and conquerint tile(int n, int x, int y){ int r, c; if (n == 2) { cnt++; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[x + i][y + j] == 0) { arr[x + i][y + j] = cnt; } } } return 0; } // finding hole location for (int i = x; i < x + n; i++) { for (int j = y; j < y + n; j++) { if (arr[i][j] != 0) r = i, c = j; } } // If missing tile is 1st quadrant if (r < x + n / 2 && c < y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2); // If missing Tile is in 3rd quadrant else if (r >= x + n / 2 && c < y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + n / 2, x + (n / 2) - 1, y + (n / 2) - 1); // If missing Tile is in 2nd quadrant else if (r < x + n / 2 && c >= y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2 - 1); // If missing Tile is in 4th quadrant else if (r >= x + n / 2 && c >= y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + (n / 2) - 1, x + (n / 2) - 1, y + (n / 2) - 1); // dividing it again in 4 quadrants tile(n / 2, x, y + n / 2); tile(n / 2, x, y); tile(n / 2, x + n / 2, y); tile(n / 2, x + n / 2, y + n / 2); return 0;}// Driver program to test above functionint main(){ // size of box size_of_grid = 8; memset(arr, 0, sizeof(arr)); // Coordinates which will be marked a = 0, b = 0; // Here tile can not be placed arr[a][b] = -1; tile(size_of_grid, 0, 0); // The grid is for (int i = 0; i < size_of_grid; i++) { for (int j = 0; j < size_of_grid; j++) cout << arr[i][j] << " \t"; cout << "\n"; }} // Java program to place tilespublic class GFG{ static int size_of_grid, b, a, cnt = 0; static int[][] arr = new int[128][128]; // Placing tile at the given coordinates static void place(int x1, int y1, int x2, int y2, int x3, int y3) { cnt++; arr[x1][y1] = cnt; arr[x2][y2] = cnt; arr[x3][y3] = cnt; } // Quadrant names // 1 2 // 3 4 // Function based on divide and conquer static int tile(int n, int x, int y) { int r = 0, c = 0; if (n == 2) { cnt++; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[x + i][y + j] == 0) { arr[x + i][y + j] = cnt; } } } return 0; } // finding hole location for (int i = x; i < x + n; i++) { for (int j = y; j < y + n; j++) { if (arr[i][j] != 0) { r = i; c = j; } } } // If missing tile is 1st quadrant if (r < x + n / 2 && c < y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2); // If missing Tile is in 3rd quadrant else if (r >= x + n / 2 && c < y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + n / 2, x + (n / 2) - 1, y + (n / 2) - 1); // If missing Tile is in 2nd quadrant else if (r < x + n / 2 && c >= y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2 - 1); // If missing Tile is in 4th quadrant else if (r >= x + n / 2 && c >= y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + (n / 2) - 1, x + (n / 2) - 1, y + (n / 2) - 1); // dividing it again in 4 quadrants tile(n / 2, x, y + n / 2); tile(n / 2, x, y); tile(n / 2, x + n / 2, y); tile(n / 2, x + n / 2, y + n / 2); return 0; } // Driver code public static void main(String[] args) { // size of box size_of_grid = 8; // Coordinates which will be marked a = 0; b = 0; // Here tile can not be placed arr[a][b] = -1; tile(size_of_grid, 0, 0); // The grid is for (int i = 0; i < size_of_grid; i++) { for (int j = 0; j < size_of_grid; j++) System.out.print(arr[i][j] + " "); System.out.println();; } }} // This code is contributed by divyeshrabadiya07. // C# program to place tilesusing System;class GFG{ static int size_of_grid, b, a, cnt = 0; static int[,] arr = new int[128, 128]; // Placing tile at the given coordinates static void place(int x1, int y1, int x2, int y2, int x3, int y3) { cnt++; arr[x1, y1] = cnt; arr[x2, y2] = cnt; arr[x3, y3] = cnt; } // Quadrant names // 1 2 // 3 4 // Function based on divide and conquer static int tile(int n, int x, int y) { int r = 0, c = 0; if (n == 2) { cnt++; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[x + i, y + j] == 0) { arr[x + i, y + j] = cnt; } } } return 0; } // finding hole location for (int i = x; i < x + n; i++) { for (int j = y; j < y + n; j++) { if (arr[i, j] != 0) { r = i; c = j; } } } // If missing tile is 1st quadrant if (r < x + n / 2 && c < y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2); // If missing Tile is in 3rd quadrant else if (r >= x + n / 2 && c < y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + n / 2, x + (n / 2) - 1, y + (n / 2) - 1); // If missing Tile is in 2nd quadrant else if (r < x + n / 2 && c >= y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2 - 1); // If missing Tile is in 4th quadrant else if (r >= x + n / 2 && c >= y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + (n / 2) - 1, x + (n / 2) - 1, y + (n / 2) - 1); // dividing it again in 4 quadrants tile(n / 2, x, y + n / 2); tile(n / 2, x, y); tile(n / 2, x + n / 2, y); tile(n / 2, x + n / 2, y + n / 2); return 0; } // Driver code static void Main() { // size of box size_of_grid = 8; // Coordinates which will be marked a = 0; b = 0; // Here tile can not be placed arr[a, b] = -1; tile(size_of_grid, 0, 0); // The grid is for (int i = 0; i < size_of_grid; i++) { for (int j = 0; j < size_of_grid; j++) Console.Write(arr[i,j] + " "); Console.WriteLine(); } }} // This code is contributed by divyesh072019. # Python3 program to place tilessize_of_grid = 0b = 0a = 0cnt = 0arr = [[0 for i in range(128)] for j in range(128)] def place(x1, y1, x2, y2, x3, y3): global cnt cnt += 1 arr[x1][y1] = cnt; arr[x2][y2] = cnt; arr[x3][y3] = cnt; def tile(n, x, y): global cnt r = 0 c = 0 if (n == 2): cnt += 1 for i in range(n): for j in range(n): if(arr[x + i][y + j] == 0): arr[x + i][y + j] = cnt return 0; for i in range(x, x + n): for j in range(y, y + n): if (arr[i][j] != 0): r = i c = j if (r < x + n / 2 and c < y + n / 2): place(x + int(n / 2), y + int(n / 2) - 1, x + int(n / 2), y + int(n / 2), x + int(n / 2) - 1, y + int(n / 2)) elif(r >= x + int(n / 2) and c < y + int(n / 2)): place(x + int(n / 2) - 1, y + int(n / 2), x + int(n / 2), y + int(n / 2), x + int(n / 2) - 1, y + int(n / 2) - 1) elif(r < x + int(n / 2) and c >= y + int(n / 2)): place(x + int(n / 2), y + int(n / 2) - 1, x + int(n / 2), y + int(n / 2), x + int(n / 2) - 1, y + int(n / 2) - 1) elif(r >= x + int(n / 2) and c >= y + int(n / 2)): place(x + int(n / 2) - 1, y + int(n / 2), x + int(n / 2), y + int(n / 2) - 1, x + int(n / 2) - 1, y + int(n / 2) - 1) tile(int(n / 2), x, y + int(n / 2)); tile(int(n / 2), x, y); tile(int(n / 2), x + int(n / 2), y); tile(int(n / 2), x + int(n / 2), y + int(n / 2)); return 0 size_of_grid = 8a = 0b = 0arr[a][b] = -1tile(size_of_grid, 0, 0) for i in range(size_of_grid): for j in range(size_of_grid): print(arr[i][j], end=" ") print() # This code is contributed by rag2127 <script> // Javascript program to place tilesvar size_of_grid, b, a, cnt = 0;var arr = Array.from(Array(128), ()=>Array(128).fill(0)); // Placing tile at the given coordinatesfunction place(x1, y1, x2, y2, x3, y3){ cnt++; arr[x1][y1] = cnt; arr[x2][y2] = cnt; arr[x3][y3] = cnt;} // Quadrant names// 1 2// 3 4 // Function based on divide and conquerfunction tile(n, x, y){ var r, c; if (n == 2) { cnt++; for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { if (arr[x + i][y + j] == 0) { arr[x + i][y + j] = cnt; } } } return 0; } // finding hole location for (var i = x; i < x + n; i++) { for (var j = y; j < y + n; j++) { if (arr[i][j] != 0) r = i, c = j; } } // If missing tile is 1st quadrant if (r < x + n / 2 && c < y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2); // If missing Tile is in 3rd quadrant else if (r >= x + n / 2 && c < y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + n / 2, x + (n / 2) - 1, y + (n / 2) - 1); // If missing Tile is in 2nd quadrant else if (r < x + n / 2 && c >= y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2 - 1); // If missing Tile is in 4th quadrant else if (r >= x + n / 2 && c >= y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + (n / 2) - 1, x + (n / 2) - 1, y + (n / 2) - 1); // dividing it again in 4 quadrants tile(n / 2, x, y + n / 2); tile(n / 2, x, y); tile(n / 2, x + n / 2, y); tile(n / 2, x + n / 2, y + n / 2); return 0;} // Driver program to test above function// size of boxsize_of_grid = 8; // Coordinates which will be markeda = 0, b = 0; // Here tile can not be placedarr[a][b] = -1;tile(size_of_grid, 0, 0); // The grid isfor (var i = 0; i < size_of_grid; i++) { for (var j = 0; j < size_of_grid; j++) document.write(arr[i][j] + " "); document.write("<br>");} // This code is contributed by rutvik_56.</script> -1 9 8 8 4 4 3 3 9 9 7 8 4 2 2 3 10 7 7 11 5 5 2 6 10 10 11 11 1 5 6 6 14 14 13 1 1 19 18 18 14 12 13 13 19 19 17 18 15 12 12 16 20 17 17 21 15 15 16 16 20 20 21 21 Time Complexity: Recurrence relation for above recursive algorithm can be written as below. C is a constant. T(n) = 4T(n/2) + C The above recursion can be solved using Master Method and time complexity is O(n2) How does this work? The working of Divide and Conquer algorithm can be proved using Mathematical Induction. Let the input square be of size 2k x 2k where k >=1. Base Case: We know that the problem can be solved for k = 1. We have a 2 x 2 square with one cell missing. Induction Hypothesis: Let the problem can be solved for k-1. Now we need to prove to prove that the problem can be solved for k if it can be solved for k-1. For k, we put a L shaped tile in middle and we have four subsquares with dimension 2k-1 x 2k-1 as shown in figure 2 above. So if we can solve 4 subsquares, we can solve the complete square. References: http://www.comp.nus.edu.sg/~sanjay/cs3230/dandc.pdfThis article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. single__loop sagnikroy0210 divyesh072019 divyeshrabadiya07 rag2127 rutvik_56 sweetyty surinderdawra388 Divide and Conquer Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Search In JavaScript Find a Fixed Point (Value equal to index) in a given array Binary Search (bisect) in Python K-th Element of Two Sorted Arrays Convex Hull using Divide and Conquer Algorithm Multiply two polynomials Search element in a sorted matrix Median of an unsorted array using Quick Select Algorithm Write you own Power without using multiplication(*) and division(/) operators Decrease and Conquer
[ { "code": null, "e": 26159, "s": 26131, "text": "\n25 Feb, 2022" }, { "code": null, "e": 26424, "s": 26159, "text": "Given a n by n board where n is of form 2k where k >= 1 (Basically n is a power of 2 with minimum value as 2). The board has one missing cell (of size 1 x 1). Fill the board using L shaped tiles. A L shaped tile is a 2 x 2 square with one cell of size 1×1 missing." }, { "code": null, "e": 26537, "s": 26424, "text": "Figure 1: An example inputThis problem can be solved using Divide and Conquer. Below is the recursive algorithm." }, { "code": null, "e": 27203, "s": 26537, "text": "// n is size of given square, p is location of missing cell\nTile(int n, Point p)\n\n1) Base case: n = 2, A 2 x 2 square with one cell missing is nothing \n but a tile and can be filled with a single tile.\n\n2) Place a L shaped tile at the center such that it does not cover\n the n/2 * n/2 subsquare that has a missing square. Now all four \n subsquares of size n/2 x n/2 have a missing cell (a cell that doesn't\n need to be filled). See figure 2 below.\n\n3) Solve the problem recursively for following four. Let p1, p2, p3 and\n p4 be positions of the 4 missing cells in 4 squares.\n a) Tile(n/2, p1)\n b) Tile(n/2, p2)\n c) Tile(n/2, p3)\n d) Tile(n/2, p3)" }, { "code": null, "e": 27255, "s": 27203, "text": "The below diagrams show working of above algorithm " }, { "code": null, "e": 27294, "s": 27255, "text": "Figure 2: After placing the first tile" }, { "code": null, "e": 27339, "s": 27294, "text": "Figure 3: Recurring for the first subsquare." }, { "code": null, "e": 27407, "s": 27339, "text": "Figure 4: Shows the first step in all four subsquares. Examples: " }, { "code": null, "e": 27770, "s": 27407, "text": "Input : size = 2 and mark coordinates = (0, 0)\nOutput : \n-1 1\n1 1\nCoordinate (0, 0) is marked. So, no tile is there. In the remaining three positions, \na tile is placed with its number as 1.\nInput : size = 4 and mark coordinates = (0, 0)\nOutput :\n-1 3 2 2\n3 3 1 2\n4 1 1 5\n4 4 5 5" }, { "code": null, "e": 27814, "s": 27770, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 27818, "s": 27814, "text": "C++" }, { "code": null, "e": 27823, "s": 27818, "text": "Java" }, { "code": null, "e": 27826, "s": 27823, "text": "C#" }, { "code": null, "e": 27834, "s": 27826, "text": "Python3" }, { "code": null, "e": 27845, "s": 27834, "text": "Javascript" }, { "code": "// C++ program to place tiles#include <bits/stdc++.h>using namespace std; int size_of_grid, b, a, cnt = 0;int arr[128][128]; // Placing tile at the given coordinatesvoid place(int x1, int y1, int x2, int y2, int x3, int y3){ cnt++; arr[x1][y1] = cnt; arr[x2][y2] = cnt; arr[x3][y3] = cnt;}// Quadrant names// 1 2// 3 4 // Function based on divide and conquerint tile(int n, int x, int y){ int r, c; if (n == 2) { cnt++; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[x + i][y + j] == 0) { arr[x + i][y + j] = cnt; } } } return 0; } // finding hole location for (int i = x; i < x + n; i++) { for (int j = y; j < y + n; j++) { if (arr[i][j] != 0) r = i, c = j; } } // If missing tile is 1st quadrant if (r < x + n / 2 && c < y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2); // If missing Tile is in 3rd quadrant else if (r >= x + n / 2 && c < y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + n / 2, x + (n / 2) - 1, y + (n / 2) - 1); // If missing Tile is in 2nd quadrant else if (r < x + n / 2 && c >= y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2 - 1); // If missing Tile is in 4th quadrant else if (r >= x + n / 2 && c >= y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + (n / 2) - 1, x + (n / 2) - 1, y + (n / 2) - 1); // dividing it again in 4 quadrants tile(n / 2, x, y + n / 2); tile(n / 2, x, y); tile(n / 2, x + n / 2, y); tile(n / 2, x + n / 2, y + n / 2); return 0;}// Driver program to test above functionint main(){ // size of box size_of_grid = 8; memset(arr, 0, sizeof(arr)); // Coordinates which will be marked a = 0, b = 0; // Here tile can not be placed arr[a][b] = -1; tile(size_of_grid, 0, 0); // The grid is for (int i = 0; i < size_of_grid; i++) { for (int j = 0; j < size_of_grid; j++) cout << arr[i][j] << \" \\t\"; cout << \"\\n\"; }}", "e": 30120, "s": 27845, "text": null }, { "code": "// Java program to place tilespublic class GFG{ static int size_of_grid, b, a, cnt = 0; static int[][] arr = new int[128][128]; // Placing tile at the given coordinates static void place(int x1, int y1, int x2, int y2, int x3, int y3) { cnt++; arr[x1][y1] = cnt; arr[x2][y2] = cnt; arr[x3][y3] = cnt; } // Quadrant names // 1 2 // 3 4 // Function based on divide and conquer static int tile(int n, int x, int y) { int r = 0, c = 0; if (n == 2) { cnt++; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[x + i][y + j] == 0) { arr[x + i][y + j] = cnt; } } } return 0; } // finding hole location for (int i = x; i < x + n; i++) { for (int j = y; j < y + n; j++) { if (arr[i][j] != 0) { r = i; c = j; } } } // If missing tile is 1st quadrant if (r < x + n / 2 && c < y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2); // If missing Tile is in 3rd quadrant else if (r >= x + n / 2 && c < y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + n / 2, x + (n / 2) - 1, y + (n / 2) - 1); // If missing Tile is in 2nd quadrant else if (r < x + n / 2 && c >= y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2 - 1); // If missing Tile is in 4th quadrant else if (r >= x + n / 2 && c >= y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + (n / 2) - 1, x + (n / 2) - 1, y + (n / 2) - 1); // dividing it again in 4 quadrants tile(n / 2, x, y + n / 2); tile(n / 2, x, y); tile(n / 2, x + n / 2, y); tile(n / 2, x + n / 2, y + n / 2); return 0; } // Driver code public static void main(String[] args) { // size of box size_of_grid = 8; // Coordinates which will be marked a = 0; b = 0; // Here tile can not be placed arr[a][b] = -1; tile(size_of_grid, 0, 0); // The grid is for (int i = 0; i < size_of_grid; i++) { for (int j = 0; j < size_of_grid; j++) System.out.print(arr[i][j] + \" \"); System.out.println();; } }} // This code is contributed by divyeshrabadiya07.", "e": 32491, "s": 30120, "text": null }, { "code": "// C# program to place tilesusing System;class GFG{ static int size_of_grid, b, a, cnt = 0; static int[,] arr = new int[128, 128]; // Placing tile at the given coordinates static void place(int x1, int y1, int x2, int y2, int x3, int y3) { cnt++; arr[x1, y1] = cnt; arr[x2, y2] = cnt; arr[x3, y3] = cnt; } // Quadrant names // 1 2 // 3 4 // Function based on divide and conquer static int tile(int n, int x, int y) { int r = 0, c = 0; if (n == 2) { cnt++; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[x + i, y + j] == 0) { arr[x + i, y + j] = cnt; } } } return 0; } // finding hole location for (int i = x; i < x + n; i++) { for (int j = y; j < y + n; j++) { if (arr[i, j] != 0) { r = i; c = j; } } } // If missing tile is 1st quadrant if (r < x + n / 2 && c < y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2); // If missing Tile is in 3rd quadrant else if (r >= x + n / 2 && c < y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + n / 2, x + (n / 2) - 1, y + (n / 2) - 1); // If missing Tile is in 2nd quadrant else if (r < x + n / 2 && c >= y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2 - 1); // If missing Tile is in 4th quadrant else if (r >= x + n / 2 && c >= y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + (n / 2) - 1, x + (n / 2) - 1, y + (n / 2) - 1); // dividing it again in 4 quadrants tile(n / 2, x, y + n / 2); tile(n / 2, x, y); tile(n / 2, x + n / 2, y); tile(n / 2, x + n / 2, y + n / 2); return 0; } // Driver code static void Main() { // size of box size_of_grid = 8; // Coordinates which will be marked a = 0; b = 0; // Here tile can not be placed arr[a, b] = -1; tile(size_of_grid, 0, 0); // The grid is for (int i = 0; i < size_of_grid; i++) { for (int j = 0; j < size_of_grid; j++) Console.Write(arr[i,j] + \" \"); Console.WriteLine(); } }} // This code is contributed by divyesh072019.", "e": 35262, "s": 32491, "text": null }, { "code": "# Python3 program to place tilessize_of_grid = 0b = 0a = 0cnt = 0arr = [[0 for i in range(128)] for j in range(128)] def place(x1, y1, x2, y2, x3, y3): global cnt cnt += 1 arr[x1][y1] = cnt; arr[x2][y2] = cnt; arr[x3][y3] = cnt; def tile(n, x, y): global cnt r = 0 c = 0 if (n == 2): cnt += 1 for i in range(n): for j in range(n): if(arr[x + i][y + j] == 0): arr[x + i][y + j] = cnt return 0; for i in range(x, x + n): for j in range(y, y + n): if (arr[i][j] != 0): r = i c = j if (r < x + n / 2 and c < y + n / 2): place(x + int(n / 2), y + int(n / 2) - 1, x + int(n / 2), y + int(n / 2), x + int(n / 2) - 1, y + int(n / 2)) elif(r >= x + int(n / 2) and c < y + int(n / 2)): place(x + int(n / 2) - 1, y + int(n / 2), x + int(n / 2), y + int(n / 2), x + int(n / 2) - 1, y + int(n / 2) - 1) elif(r < x + int(n / 2) and c >= y + int(n / 2)): place(x + int(n / 2), y + int(n / 2) - 1, x + int(n / 2), y + int(n / 2), x + int(n / 2) - 1, y + int(n / 2) - 1) elif(r >= x + int(n / 2) and c >= y + int(n / 2)): place(x + int(n / 2) - 1, y + int(n / 2), x + int(n / 2), y + int(n / 2) - 1, x + int(n / 2) - 1, y + int(n / 2) - 1) tile(int(n / 2), x, y + int(n / 2)); tile(int(n / 2), x, y); tile(int(n / 2), x + int(n / 2), y); tile(int(n / 2), x + int(n / 2), y + int(n / 2)); return 0 size_of_grid = 8a = 0b = 0arr[a][b] = -1tile(size_of_grid, 0, 0) for i in range(size_of_grid): for j in range(size_of_grid): print(arr[i][j], end=\" \") print() # This code is contributed by rag2127", "e": 36984, "s": 35262, "text": null }, { "code": "<script> // Javascript program to place tilesvar size_of_grid, b, a, cnt = 0;var arr = Array.from(Array(128), ()=>Array(128).fill(0)); // Placing tile at the given coordinatesfunction place(x1, y1, x2, y2, x3, y3){ cnt++; arr[x1][y1] = cnt; arr[x2][y2] = cnt; arr[x3][y3] = cnt;} // Quadrant names// 1 2// 3 4 // Function based on divide and conquerfunction tile(n, x, y){ var r, c; if (n == 2) { cnt++; for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { if (arr[x + i][y + j] == 0) { arr[x + i][y + j] = cnt; } } } return 0; } // finding hole location for (var i = x; i < x + n; i++) { for (var j = y; j < y + n; j++) { if (arr[i][j] != 0) r = i, c = j; } } // If missing tile is 1st quadrant if (r < x + n / 2 && c < y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2); // If missing Tile is in 3rd quadrant else if (r >= x + n / 2 && c < y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + n / 2, x + (n / 2) - 1, y + (n / 2) - 1); // If missing Tile is in 2nd quadrant else if (r < x + n / 2 && c >= y + n / 2) place(x + n / 2, y + (n / 2) - 1, x + n / 2, y + n / 2, x + n / 2 - 1, y + n / 2 - 1); // If missing Tile is in 4th quadrant else if (r >= x + n / 2 && c >= y + n / 2) place(x + (n / 2) - 1, y + (n / 2), x + (n / 2), y + (n / 2) - 1, x + (n / 2) - 1, y + (n / 2) - 1); // dividing it again in 4 quadrants tile(n / 2, x, y + n / 2); tile(n / 2, x, y); tile(n / 2, x + n / 2, y); tile(n / 2, x + n / 2, y + n / 2); return 0;} // Driver program to test above function// size of boxsize_of_grid = 8; // Coordinates which will be markeda = 0, b = 0; // Here tile can not be placedarr[a][b] = -1;tile(size_of_grid, 0, 0); // The grid isfor (var i = 0; i < size_of_grid; i++) { for (var j = 0; j < size_of_grid; j++) document.write(arr[i][j] + \" \"); document.write(\"<br>\");} // This code is contributed by rutvik_56.</script>", "e": 39209, "s": 36984, "text": null }, { "code": null, "e": 39638, "s": 39209, "text": "-1 9 8 8 4 4 3 3 \n9 9 7 8 4 2 2 3 \n10 7 7 11 5 5 2 6 \n10 10 11 11 1 5 6 6 \n14 14 13 1 1 19 18 18 \n14 12 13 13 19 19 17 18 \n15 12 12 16 20 17 17 21 \n15 15 16 16 20 20 21 21 " }, { "code": null, "e": 39849, "s": 39638, "text": "Time Complexity: Recurrence relation for above recursive algorithm can be written as below. C is a constant. T(n) = 4T(n/2) + C The above recursion can be solved using Master Method and time complexity is O(n2)" }, { "code": null, "e": 40464, "s": 39849, "text": "How does this work? The working of Divide and Conquer algorithm can be proved using Mathematical Induction. Let the input square be of size 2k x 2k where k >=1. Base Case: We know that the problem can be solved for k = 1. We have a 2 x 2 square with one cell missing. Induction Hypothesis: Let the problem can be solved for k-1. Now we need to prove to prove that the problem can be solved for k if it can be solved for k-1. For k, we put a L shaped tile in middle and we have four subsquares with dimension 2k-1 x 2k-1 as shown in figure 2 above. So if we can solve 4 subsquares, we can solve the complete square." }, { "code": null, "e": 40696, "s": 40464, "text": "References: http://www.comp.nus.edu.sg/~sanjay/cs3230/dandc.pdfThis article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 40709, "s": 40696, "text": "single__loop" }, { "code": null, "e": 40723, "s": 40709, "text": "sagnikroy0210" }, { "code": null, "e": 40737, "s": 40723, "text": "divyesh072019" }, { "code": null, "e": 40755, "s": 40737, "text": "divyeshrabadiya07" }, { "code": null, "e": 40763, "s": 40755, "text": "rag2127" }, { "code": null, "e": 40773, "s": 40763, "text": "rutvik_56" }, { "code": null, "e": 40782, "s": 40773, "text": "sweetyty" }, { "code": null, "e": 40799, "s": 40782, "text": "surinderdawra388" }, { "code": null, "e": 40818, "s": 40799, "text": "Divide and Conquer" }, { "code": null, "e": 40837, "s": 40818, "text": "Divide and Conquer" }, { "code": null, "e": 40935, "s": 40837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40963, "s": 40935, "text": "Binary Search In JavaScript" }, { "code": null, "e": 41022, "s": 40963, "text": "Find a Fixed Point (Value equal to index) in a given array" }, { "code": null, "e": 41055, "s": 41022, "text": "Binary Search (bisect) in Python" }, { "code": null, "e": 41089, "s": 41055, "text": "K-th Element of Two Sorted Arrays" }, { "code": null, "e": 41136, "s": 41089, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 41161, "s": 41136, "text": "Multiply two polynomials" }, { "code": null, "e": 41195, "s": 41161, "text": "Search element in a sorted matrix" }, { "code": null, "e": 41252, "s": 41195, "text": "Median of an unsorted array using Quick Select Algorithm" }, { "code": null, "e": 41330, "s": 41252, "text": "Write you own Power without using multiplication(*) and division(/) operators" } ]
CSS box-sizing Property - GeeksforGeeks
21 Oct, 2021 The box-sizing property in CSS defines how the user should calculate the total width and height of an element i.e padding and borders, are to be included or not. Syntax: box-sizing: content-box|border-box; Property Values: All the properties are described well with the example below. content-box: This is the default value of the box-sizing property. In this mode, the width and height properties include only the content. Border and padding are not included in it i.e if we set an element’s width to 200 pixels, then the element’s content box will be 200 pixels wide, and the width of any border or padding will be added to the final rendered width. Syntax: box-sizing: content-box; Example: This example illustrates the use of the box-sizing property whose value is set to content-box. HTML <!DOCTYPE html><html><head> <title>box-sizing Property</title> <style> div { width: 200px; height: 60px; padding: 20px; border: 2px solid green; background: green; color: white; } .content-box { box-sizing: content-box; } </style></head> <body style="text-align: center;"> <h2>box-sizing: content-box</h2> <br> <div class="content-box">GeeksforGeeks</div></body></html> Output: border-box: In this mode, the width and height properties include content, padding, and borders i.e if we set an element’s width to 200 pixels, that 200 pixels will include any border or padding we added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements. Syntax: box-sizing: border-box; Example: This example illustrates the use of the box-sizing property whose value is set to border-box. HTML <!DOCTYPE html><html><head> <title>box-sizing Property</title> <style> div { width: 200px; height: 60px; padding: 20px; border: 2px solid green; background: green; color: white; } .border-box { box-sizing: content-box; } </style></head> <body style="text-align: center;"> <h2>box-sizing: border-box</h2> <br> <div class="border-box">GeeksforGeeks</div></body></html> Output: Supported Browsers: The browser supported by the box-sizing property are listed below: Google Chrome 10.0 4.0 -webkit- Internet Explorer 8.0 Microsoft Edge 12.0 Firefox 29.0 2.0 -moz- Opera 9.5 Apple Safari 5.1 3.2 -webkit- Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. hritikbhatnagar2182 bhaskargeeksforgeeks CSS-Properties Picked CSS HTML Web Technologies 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 create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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
[ { "code": null, "e": 24958, "s": 24930, "text": "\n21 Oct, 2021" }, { "code": null, "e": 25120, "s": 24958, "text": "The box-sizing property in CSS defines how the user should calculate the total width and height of an element i.e padding and borders, are to be included or not." }, { "code": null, "e": 25128, "s": 25120, "text": "Syntax:" }, { "code": null, "e": 25164, "s": 25128, "text": "box-sizing: content-box|border-box;" }, { "code": null, "e": 25243, "s": 25164, "text": "Property Values: All the properties are described well with the example below." }, { "code": null, "e": 25610, "s": 25243, "text": "content-box: This is the default value of the box-sizing property. In this mode, the width and height properties include only the content. Border and padding are not included in it i.e if we set an element’s width to 200 pixels, then the element’s content box will be 200 pixels wide, and the width of any border or padding will be added to the final rendered width." }, { "code": null, "e": 25618, "s": 25610, "text": "Syntax:" }, { "code": null, "e": 25643, "s": 25618, "text": "box-sizing: content-box;" }, { "code": null, "e": 25747, "s": 25643, "text": "Example: This example illustrates the use of the box-sizing property whose value is set to content-box." }, { "code": null, "e": 25752, "s": 25747, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>box-sizing Property</title> <style> div { width: 200px; height: 60px; padding: 20px; border: 2px solid green; background: green; color: white; } .content-box { box-sizing: content-box; } </style></head> <body style=\"text-align: center;\"> <h2>box-sizing: content-box</h2> <br> <div class=\"content-box\">GeeksforGeeks</div></body></html>", "e": 26206, "s": 25752, "text": null }, { "code": null, "e": 26214, "s": 26206, "text": "Output:" }, { "code": null, "e": 26533, "s": 26214, "text": "border-box: In this mode, the width and height properties include content, padding, and borders i.e if we set an element’s width to 200 pixels, that 200 pixels will include any border or padding we added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements." }, { "code": null, "e": 26541, "s": 26533, "text": "Syntax:" }, { "code": null, "e": 26565, "s": 26541, "text": "box-sizing: border-box;" }, { "code": null, "e": 26668, "s": 26565, "text": "Example: This example illustrates the use of the box-sizing property whose value is set to border-box." }, { "code": null, "e": 26673, "s": 26668, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>box-sizing Property</title> <style> div { width: 200px; height: 60px; padding: 20px; border: 2px solid green; background: green; color: white; } .border-box { box-sizing: content-box; } </style></head> <body style=\"text-align: center;\"> <h2>box-sizing: border-box</h2> <br> <div class=\"border-box\">GeeksforGeeks</div></body></html>", "e": 27124, "s": 26673, "text": null }, { "code": null, "e": 27132, "s": 27124, "text": "Output:" }, { "code": null, "e": 27221, "s": 27132, "text": "Supported Browsers: The browser supported by the box-sizing property are listed below: " }, { "code": null, "e": 27253, "s": 27221, "text": "Google Chrome 10.0 4.0 -webkit-" }, { "code": null, "e": 27275, "s": 27253, "text": "Internet Explorer 8.0" }, { "code": null, "e": 27295, "s": 27275, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 27318, "s": 27295, "text": "Firefox 29.0 2.0 -moz-" }, { "code": null, "e": 27328, "s": 27318, "text": "Opera 9.5" }, { "code": null, "e": 27358, "s": 27328, "text": "Apple Safari 5.1 3.2 -webkit-" }, { "code": null, "e": 27495, "s": 27358, "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": 27515, "s": 27495, "text": "hritikbhatnagar2182" }, { "code": null, "e": 27536, "s": 27515, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27551, "s": 27536, "text": "CSS-Properties" }, { "code": null, "e": 27558, "s": 27551, "text": "Picked" }, { "code": null, "e": 27562, "s": 27558, "text": "CSS" }, { "code": null, "e": 27567, "s": 27562, "text": "HTML" }, { "code": null, "e": 27584, "s": 27567, "text": "Web Technologies" }, { "code": null, "e": 27589, "s": 27584, "text": "HTML" }, { "code": null, "e": 27687, "s": 27589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27737, "s": 27687, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27799, "s": 27737, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27847, "s": 27799, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27905, "s": 27847, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27960, "s": 27905, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28010, "s": 27960, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28072, "s": 28010, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28120, "s": 28072, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 28180, "s": 28120, "text": "How to set the default value for an HTML <select> element ?" } ]
LINQ | Partition Operator | Take - GeeksforGeeks
28 May, 2019 In LINQ, partition operators are used for separating the given sequence into two portions without sorting the elements and return one of the portions. The Standard Query Operators supports 4 different types of partition operators: SkipSkipWhileTakeTakeWhile Skip SkipWhile Take TakeWhile The Take operator is used to return a specified number of adjacent elements from the start of the sequences. Or in other words, we can say that it returns the specified number of items starting from the first item. As shown in the below example: Important Points: It does not support query syntax in C# and VB.Net languages. But you can use the Take method to query variable or you can wrap your query in brackets and then the call Take method. As shown in the Example 2. It support method syntax in both C# and VB.Net languages. It present in both the Queryable and Enumerable class. It is implemented by using deferred execution. It will throw an ArgumentNullException if the source is null. Example 1: // C# program to illustrate the// concept of Taking operatorusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source int[] sequence = {45, 67, 89, 13, 56, 76, 67}; // Query which picks starting 5 ordered // elements from the given sequence // Using Take method var result = sequence.OrderBy(s => s).Take(5); Console.WriteLine("New Sequence: "); // Display new sequence foreach(var val in result) { Console.WriteLine(val); } }} New Sequence: 13 45 56 67 67 Example 2: // C# program to find the names// of the first 4 employeesusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} public class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = "Anu", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 80000}, new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 60000}, new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000}, }; // Query to find the names // of the first 4 employees // Using Take method var res = (from e in emp select e.emp_name) .Take(4); foreach(var val in res) { Console.WriteLine("Employee Name: {0}", val); } }} Employee Name: Anjita Employee Name: Soniya Employee Name: Rohit Employee Name: Anu CSharp LINQ C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25685, "s": 25657, "text": "\n28 May, 2019" }, { "code": null, "e": 25916, "s": 25685, "text": "In LINQ, partition operators are used for separating the given sequence into two portions without sorting the elements and return one of the portions. The Standard Query Operators supports 4 different types of partition operators:" }, { "code": null, "e": 25943, "s": 25916, "text": "SkipSkipWhileTakeTakeWhile" }, { "code": null, "e": 25948, "s": 25943, "text": "Skip" }, { "code": null, "e": 25958, "s": 25948, "text": "SkipWhile" }, { "code": null, "e": 25963, "s": 25958, "text": "Take" }, { "code": null, "e": 25973, "s": 25963, "text": "TakeWhile" }, { "code": null, "e": 26219, "s": 25973, "text": "The Take operator is used to return a specified number of adjacent elements from the start of the sequences. Or in other words, we can say that it returns the specified number of items starting from the first item. As shown in the below example:" }, { "code": null, "e": 26237, "s": 26219, "text": "Important Points:" }, { "code": null, "e": 26445, "s": 26237, "text": "It does not support query syntax in C# and VB.Net languages. But you can use the Take method to query variable or you can wrap your query in brackets and then the call Take method. As shown in the Example 2." }, { "code": null, "e": 26503, "s": 26445, "text": "It support method syntax in both C# and VB.Net languages." }, { "code": null, "e": 26558, "s": 26503, "text": "It present in both the Queryable and Enumerable class." }, { "code": null, "e": 26605, "s": 26558, "text": "It is implemented by using deferred execution." }, { "code": null, "e": 26667, "s": 26605, "text": "It will throw an ArgumentNullException if the source is null." }, { "code": null, "e": 26678, "s": 26667, "text": "Example 1:" }, { "code": "// C# program to illustrate the// concept of Taking operatorusing System;using System.Linq; class GFG { // Main Method static public void Main() { // Data source int[] sequence = {45, 67, 89, 13, 56, 76, 67}; // Query which picks starting 5 ordered // elements from the given sequence // Using Take method var result = sequence.OrderBy(s => s).Take(5); Console.WriteLine(\"New Sequence: \"); // Display new sequence foreach(var val in result) { Console.WriteLine(val); } }}", "e": 27281, "s": 26678, "text": null }, { "code": null, "e": 27312, "s": 27281, "text": "New Sequence: \n13\n45\n56\n67\n67\n" }, { "code": null, "e": 27323, "s": 27312, "text": "Example 2:" }, { "code": "// C# program to find the names// of the first 4 employeesusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} public class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = \"Anu\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 80000}, new Employee() {emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 60000}, new Employee() {emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000}, }; // Query to find the names // of the first 4 employees // Using Take method var res = (from e in emp select e.emp_name) .Take(4); foreach(var val in res) { Console.WriteLine(\"Employee Name: {0}\", val); } }}", "e": 29250, "s": 27323, "text": null }, { "code": null, "e": 29335, "s": 29250, "text": "Employee Name: Anjita\nEmployee Name: Soniya\nEmployee Name: Rohit\nEmployee Name: Anu\n" }, { "code": null, "e": 29347, "s": 29335, "text": "CSharp LINQ" }, { "code": null, "e": 29350, "s": 29347, "text": "C#" }, { "code": null, "e": 29448, "s": 29350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29476, "s": 29448, "text": "C# Dictionary with examples" }, { "code": null, "e": 29491, "s": 29476, "text": "C# | Delegates" }, { "code": null, "e": 29514, "s": 29491, "text": "C# | Method Overriding" }, { "code": null, "e": 29536, "s": 29514, "text": "C# | Abstract Classes" }, { "code": null, "e": 29582, "s": 29536, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29605, "s": 29582, "text": "Extension Method in C#" }, { "code": null, "e": 29627, "s": 29605, "text": "C# | Class and Object" }, { "code": null, "e": 29645, "s": 29627, "text": "C# | Constructors" }, { "code": null, "e": 29685, "s": 29645, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Ruby | Array delete() operation - GeeksforGeeks
21 Aug, 2021 Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array.delete() Parameter: obj - specific element to delete Return: last deleted values from the array. Code #1 : Example for delete() method Ruby # Ruby code for delete() method# to delete elements # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # delete 5puts "delete : #{a.delete(5)}\n\n" # delete 10# printing if no such element is foundputs "delete : #{b.delete(10){"no such element"}}\n\n" # delete 20puts "delete : #{c.delete(20)}\n\n" Output : delete : 5 delete : no such element delete : Code #2 : Example for delete() method Ruby # Ruby code for delete() method# to delete elements # declaring arraya = ["abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # declaring arrayc = ["cat", nil, nil] # deleteputs "delete : #{a.delete("abc")}\n\n" # delete# printing if no such element is foundputs "delete : #{b.delete("geek"){"no such element"}}\n\n" # deleteputs "delete : #{c.delete("cat")}\n\n" Output : delete : abc delete : no such element delete : cat singghakshay Ruby Array-class Ruby Collections Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Types of Variables Ruby | Enumerator each_with_index function Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby For Beginners Ruby Mixins Ruby | Array collect() operation Ruby | Array shift() function Ruby | String concat Method Ruby | Array reject() function Ruby | unless Statement and unless Modifier
[ { "code": null, "e": 25217, "s": 25189, "text": "\n21 Aug, 2021" }, { "code": null, "e": 25385, "s": 25217, "text": "Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. " }, { "code": null, "e": 25502, "s": 25385, "text": "Syntax: Array.delete()\n\nParameter: obj - specific element to delete\n\nReturn: last deleted values from the array. " }, { "code": null, "e": 25540, "s": 25502, "text": "Code #1 : Example for delete() method" }, { "code": null, "e": 25545, "s": 25540, "text": "Ruby" }, { "code": "# Ruby code for delete() method# to delete elements # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # delete 5puts \"delete : #{a.delete(5)}\\n\\n\" # delete 10# printing if no such element is foundputs \"delete : #{b.delete(10){\"no such element\"}}\\n\\n\" # delete 20puts \"delete : #{c.delete(20)}\\n\\n\"", "e": 25926, "s": 25545, "text": null }, { "code": null, "e": 25936, "s": 25926, "text": "Output : " }, { "code": null, "e": 25984, "s": 25936, "text": "delete : 5\n\ndelete : no such element\n\ndelete : " }, { "code": null, "e": 26023, "s": 25984, "text": "Code #2 : Example for delete() method " }, { "code": null, "e": 26028, "s": 26023, "text": "Ruby" }, { "code": "# Ruby code for delete() method# to delete elements # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayb = [\"cow\", nil, \"dog\"] # declaring arrayc = [\"cat\", nil, nil] # deleteputs \"delete : #{a.delete(\"abc\")}\\n\\n\" # delete# printing if no such element is foundputs \"delete : #{b.delete(\"geek\"){\"no such element\"}}\\n\\n\" # deleteputs \"delete : #{c.delete(\"cat\")}\\n\\n\"", "e": 26402, "s": 26028, "text": null }, { "code": null, "e": 26412, "s": 26402, "text": "Output : " }, { "code": null, "e": 26465, "s": 26412, "text": "delete : abc\n\ndelete : no such element\n\ndelete : cat" }, { "code": null, "e": 26480, "s": 26467, "text": "singghakshay" }, { "code": null, "e": 26497, "s": 26480, "text": "Ruby Array-class" }, { "code": null, "e": 26514, "s": 26497, "text": "Ruby Collections" }, { "code": null, "e": 26527, "s": 26514, "text": "Ruby-Methods" }, { "code": null, "e": 26532, "s": 26527, "text": "Ruby" }, { "code": null, "e": 26630, "s": 26532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26656, "s": 26630, "text": "Ruby | Types of Variables" }, { "code": null, "e": 26699, "s": 26656, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 26767, "s": 26699, "text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1" }, { "code": null, "e": 26786, "s": 26767, "text": "Ruby For Beginners" }, { "code": null, "e": 26798, "s": 26786, "text": "Ruby Mixins" }, { "code": null, "e": 26831, "s": 26798, "text": "Ruby | Array collect() operation" }, { "code": null, "e": 26861, "s": 26831, "text": "Ruby | Array shift() function" }, { "code": null, "e": 26889, "s": 26861, "text": "Ruby | String concat Method" }, { "code": null, "e": 26920, "s": 26889, "text": "Ruby | Array reject() function" } ]
How to extract frequency associated with fft values in Python? - GeeksforGeeks
26 Dec, 2020 In this article, we will find out the extract the values of frequency from an FFT. We can obtain the magnitude of frequency from a set of complex numbers obtained after performing FFT i.e Fast Fourier Transform in Python. The frequency can be obtained by calculating the magnitude of the complex number. So simple ab(x) on each of those complex numbers should return the frequency. In order to extract frequency associated with fft values we will be using the fft.fft() and fft.fftfreq() methods of numpy module. numpy.fft.fft(): It calculates the single-dimensional n-point DFT i.e. Discrete Fourier Transform with an optimized FFT i.e Fast Fourier Transform algorithm. Syntax: numpy.fft.fft(a, axis=-1) Parameters: a: Input array can be complex. axis: Axis over which to compute the FFT. If not given, the last axis is used. Returns: The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if the axis is not specified. numpy.fft.fftfreq(): It computes the frequencies associated with the coefficients. Syntax: numpy.fft.fftfreq(n, d=1.0) n: Window length. d: Sample spacing (inverse of the sampling rate). Defaults to 1. Returns: Array of length n containing the sample frequencies. Step 1: Import required modules. Python3 # import moduleimport numpy as np Step 2: Create an array using a NumPy. Python3 # assign datax = np.array([1,2,1,0,1,2,1,0]) Step 3: A signal x defined in the time domain of length N, sampled at a constant interval dt, its DFT W(here specifically W = np.fft.fft(x)), whose elements are sampled on the frequency axis with a sample rate dw. (A DFT converts a list of N complex numbers to a list of N complex numbers) Python3 # compute DFT with optimized FFTw = np.fft.fft(x) Step 4: The np.fft.fftfreq() method tells you the frequencies associated with the coefficients. Python3 # compute frequency associated# with coefficientsfreqs = np.fft.fftfreq(len(x)) Step 5: Extract frequency associated with fft values. Python3 # extract frequencies associated with FFT valuesfor coef, freq in zip(w, freqs): if coef: print('{c:>6} * exp(2 pi i t * {f})'.format(c=coef, f=freq)) Below is the complete program based in the above approach: Python3 # import required modulesimport numpy as np # assign datax = np.array([1, 2, 1, 0, 1, 2, 1, 0]) # compute DFT with optimized FFTw = np.fft.fft(x) # compute frequency associated# with coefficientsfreqs = np.fft.fftfreq(len(x)) # extract frequencies associated with FFT valuesfor coef, freq in zip(w, freqs): if coef: print('{c:>6} * exp(2 pi i t * {f})'.format(c=coef, f=freq)) Output: Python-numpy 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 | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Dec, 2020" }, { "code": null, "e": 25920, "s": 25537, "text": "In this article, we will find out the extract the values of frequency from an FFT. We can obtain the magnitude of frequency from a set of complex numbers obtained after performing FFT i.e Fast Fourier Transform in Python. The frequency can be obtained by calculating the magnitude of the complex number. So simple ab(x) on each of those complex numbers should return the frequency." }, { "code": null, "e": 26051, "s": 25920, "text": "In order to extract frequency associated with fft values we will be using the fft.fft() and fft.fftfreq() methods of numpy module." }, { "code": null, "e": 26209, "s": 26051, "text": "numpy.fft.fft(): It calculates the single-dimensional n-point DFT i.e. Discrete Fourier Transform with an optimized FFT i.e Fast Fourier Transform algorithm." }, { "code": null, "e": 26243, "s": 26209, "text": "Syntax: numpy.fft.fft(a, axis=-1)" }, { "code": null, "e": 26255, "s": 26243, "text": "Parameters:" }, { "code": null, "e": 26286, "s": 26255, "text": "a: Input array can be complex." }, { "code": null, "e": 26365, "s": 26286, "text": "axis: Axis over which to compute the FFT. If not given, the last axis is used." }, { "code": null, "e": 26502, "s": 26365, "text": "Returns: The truncated or zero-padded input, transformed along the axis indicated by axis, or the last one if the axis is not specified." }, { "code": null, "e": 26585, "s": 26502, "text": "numpy.fft.fftfreq(): It computes the frequencies associated with the coefficients." }, { "code": null, "e": 26621, "s": 26585, "text": "Syntax: numpy.fft.fftfreq(n, d=1.0)" }, { "code": null, "e": 26639, "s": 26621, "text": "n: Window length." }, { "code": null, "e": 26704, "s": 26639, "text": "d: Sample spacing (inverse of the sampling rate). Defaults to 1." }, { "code": null, "e": 26766, "s": 26704, "text": "Returns: Array of length n containing the sample frequencies." }, { "code": null, "e": 26799, "s": 26766, "text": "Step 1: Import required modules." }, { "code": null, "e": 26807, "s": 26799, "text": "Python3" }, { "code": "# import moduleimport numpy as np", "e": 26841, "s": 26807, "text": null }, { "code": null, "e": 26880, "s": 26841, "text": "Step 2: Create an array using a NumPy." }, { "code": null, "e": 26888, "s": 26880, "text": "Python3" }, { "code": "# assign datax = np.array([1,2,1,0,1,2,1,0])", "e": 26933, "s": 26888, "text": null }, { "code": null, "e": 27223, "s": 26933, "text": "Step 3: A signal x defined in the time domain of length N, sampled at a constant interval dt, its DFT W(here specifically W = np.fft.fft(x)), whose elements are sampled on the frequency axis with a sample rate dw. (A DFT converts a list of N complex numbers to a list of N complex numbers)" }, { "code": null, "e": 27231, "s": 27223, "text": "Python3" }, { "code": "# compute DFT with optimized FFTw = np.fft.fft(x)", "e": 27281, "s": 27231, "text": null }, { "code": null, "e": 27377, "s": 27281, "text": "Step 4: The np.fft.fftfreq() method tells you the frequencies associated with the coefficients." }, { "code": null, "e": 27385, "s": 27377, "text": "Python3" }, { "code": "# compute frequency associated# with coefficientsfreqs = np.fft.fftfreq(len(x))", "e": 27465, "s": 27385, "text": null }, { "code": null, "e": 27519, "s": 27465, "text": "Step 5: Extract frequency associated with fft values." }, { "code": null, "e": 27527, "s": 27519, "text": "Python3" }, { "code": "# extract frequencies associated with FFT valuesfor coef, freq in zip(w, freqs): if coef: print('{c:>6} * exp(2 pi i t * {f})'.format(c=coef, f=freq))", "e": 27739, "s": 27527, "text": null }, { "code": null, "e": 27798, "s": 27739, "text": "Below is the complete program based in the above approach:" }, { "code": null, "e": 27806, "s": 27798, "text": "Python3" }, { "code": "# import required modulesimport numpy as np # assign datax = np.array([1, 2, 1, 0, 1, 2, 1, 0]) # compute DFT with optimized FFTw = np.fft.fft(x) # compute frequency associated# with coefficientsfreqs = np.fft.fftfreq(len(x)) # extract frequencies associated with FFT valuesfor coef, freq in zip(w, freqs): if coef: print('{c:>6} * exp(2 pi i t * {f})'.format(c=coef, f=freq))", "e": 28248, "s": 27806, "text": null }, { "code": null, "e": 28256, "s": 28248, "text": "Output:" }, { "code": null, "e": 28269, "s": 28256, "text": "Python-numpy" }, { "code": null, "e": 28293, "s": 28269, "text": "Technical Scripter 2020" }, { "code": null, "e": 28300, "s": 28293, "text": "Python" }, { "code": null, "e": 28319, "s": 28300, "text": "Technical Scripter" }, { "code": null, "e": 28417, "s": 28319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28449, "s": 28417, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28491, "s": 28449, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28533, "s": 28491, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28589, "s": 28533, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28616, "s": 28589, "text": "Python Classes and Objects" }, { "code": null, "e": 28647, "s": 28616, "text": "Python | os.path.join() method" }, { "code": null, "e": 28686, "s": 28647, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28715, "s": 28686, "text": "Create a directory in Python" }, { "code": null, "e": 28737, "s": 28715, "text": "Defaultdict in Python" } ]
Angular PrimeNG ScrollTop Component - GeeksforGeeks
24 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the ScrollTop component in Angular PrimeNG. ScrollTop component: It is used to make a component that gets displayed after a certain scroll position to navigate to the top of the page. Properties: target: It specifies the target of the scrollTop, the valid values are “window” and “parent”. It is of string datatype & the default value is a window. threshold: It is the threshold value after which the element is visible. It accepts the number data type as input & the default value is 400. icon: It is the icon to display. It is of string data type & the default value is pi pi-chevron-up. behavior: It is the scrolling behavior, “smooth” add animation and “auto” scrolls with a jump. It is of string data type & the default value is smooth. style: It sets an inline style of the component. It is of object data type, the default value is null. styleClass: It sets the style class of the component. It is of string data type, the default value is null. Styling: p-scrolltop: It is the container element. p-scrolltop-sticky: It is the container element when attached to its parent. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: After complete installation, it will look like the following: Example 1: This is the basic example that illustrates how to use the scrollTop component. The value of the threshold is set to 150, so the scrollTop icon will be displayed after scrolling 150 pixels. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG ScrollTop Component</h5><p-scrollPanel [style]= "{width: '25p0x', height: '100px'}"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> <p-scrollTop target="parent" [threshold]="150" icon="pi pi-arrow-up"> </p-scrollTop></p-scrollPanel> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { ScrollTopModule } from 'primeng/scrolltop';import { ScrollPanelModule } from 'primeng/scrollpanel'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ScrollTopModule, ScrollPanelModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {} Output: Example 2: In this example, we will set the behavior property to auto, so, the animation is not visible while scrolling to the top of the element and the threshold is set to 0, so the scrollTop icon is instantly shown while scrolling. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG ScrollTop Component</h5><p-scrollPanel [style]= "{width: '300px', height: '90px'}"> <div> <span>GeeksforGeeks</span> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. </p> </div> <p-scrollTop target="parent" [threshold]="0" [behavior]='auto' icon="pi pi-arrow-up"> </p-scrollTop></p-scrollPanel> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { ScrollTopModule } from 'primeng/scrolltop';import { ScrollPanelModule } from 'primeng/scrollpanel'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ScrollTopModule, ScrollPanelModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent {} Output: Reference: https://primefaces.org/primeng/showcase/#/scrolltop Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26464, "s": 26436, "text": "\n24 Sep, 2021" }, { "code": null, "e": 26749, "s": 26464, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the ScrollTop component in Angular PrimeNG." }, { "code": null, "e": 26889, "s": 26749, "text": "ScrollTop component: It is used to make a component that gets displayed after a certain scroll position to navigate to the top of the page." }, { "code": null, "e": 26901, "s": 26889, "text": "Properties:" }, { "code": null, "e": 27053, "s": 26901, "text": "target: It specifies the target of the scrollTop, the valid values are “window” and “parent”. It is of string datatype & the default value is a window." }, { "code": null, "e": 27195, "s": 27053, "text": "threshold: It is the threshold value after which the element is visible. It accepts the number data type as input & the default value is 400." }, { "code": null, "e": 27295, "s": 27195, "text": "icon: It is the icon to display. It is of string data type & the default value is pi pi-chevron-up." }, { "code": null, "e": 27447, "s": 27295, "text": "behavior: It is the scrolling behavior, “smooth” add animation and “auto” scrolls with a jump. It is of string data type & the default value is smooth." }, { "code": null, "e": 27550, "s": 27447, "text": "style: It sets an inline style of the component. It is of object data type, the default value is null." }, { "code": null, "e": 27658, "s": 27550, "text": "styleClass: It sets the style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 27667, "s": 27658, "text": "Styling:" }, { "code": null, "e": 27709, "s": 27667, "text": "p-scrolltop: It is the container element." }, { "code": null, "e": 27786, "s": 27709, "text": "p-scrolltop-sticky: It is the container element when attached to its parent." }, { "code": null, "e": 27840, "s": 27788, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 27907, "s": 27840, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 27922, "s": 27907, "text": "ng new appname" }, { "code": null, "e": 28019, "s": 27922, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28030, "s": 28019, "text": "cd appname" }, { "code": null, "e": 28079, "s": 28030, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28136, "s": 28079, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28217, "s": 28136, "text": "Project Structure: After complete installation, it will look like the following:" }, { "code": null, "e": 28417, "s": 28217, "text": "Example 1: This is the basic example that illustrates how to use the scrollTop component. The value of the threshold is set to 150, so the scrollTop icon will be displayed after scrolling 150 pixels." }, { "code": null, "e": 28438, "s": 28419, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG ScrollTop Component</h5><p-scrollPanel [style]= \"{width: '25p0x', height: '100px'}\"> <p> Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. </p> <p-scrollTop target=\"parent\" [threshold]=\"150\" icon=\"pi pi-arrow-up\"> </p-scrollTop></p-scrollPanel>", "e": 29325, "s": 28438, "text": null }, { "code": null, "e": 29339, "s": 29325, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { ScrollTopModule } from 'primeng/scrolltop';import { ScrollPanelModule } from 'primeng/scrollpanel'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ScrollTopModule, ScrollPanelModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 29878, "s": 29339, "text": null }, { "code": null, "e": 29895, "s": 29878, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}", "e": 30040, "s": 29895, "text": null }, { "code": null, "e": 30048, "s": 30040, "text": "Output:" }, { "code": null, "e": 30283, "s": 30048, "text": "Example 2: In this example, we will set the behavior property to auto, so, the animation is not visible while scrolling to the top of the element and the threshold is set to 0, so the scrollTop icon is instantly shown while scrolling." }, { "code": null, "e": 30302, "s": 30283, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG ScrollTop Component</h5><p-scrollPanel [style]= \"{width: '300px', height: '90px'}\"> <div> <span>GeeksforGeeks</span> <p> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles. We provide a variety of services for you to learn, thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses, Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities and Job Opportunities. </p> </div> <p-scrollTop target=\"parent\" [threshold]=\"0\" [behavior]='auto' icon=\"pi pi-arrow-up\"> </p-scrollTop></p-scrollPanel>", "e": 31186, "s": 30302, "text": null }, { "code": null, "e": 31200, "s": 31186, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { ScrollTopModule } from 'primeng/scrolltop';import { ScrollPanelModule } from 'primeng/scrollpanel'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ScrollTopModule, ScrollPanelModule ], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 31739, "s": 31200, "text": null }, { "code": null, "e": 31756, "s": 31739, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent {}", "e": 31903, "s": 31756, "text": null }, { "code": null, "e": 31911, "s": 31903, "text": "Output:" }, { "code": null, "e": 31974, "s": 31911, "text": "Reference: https://primefaces.org/primeng/showcase/#/scrolltop" }, { "code": null, "e": 31990, "s": 31974, "text": "Angular-PrimeNG" }, { "code": null, "e": 32000, "s": 31990, "text": "AngularJS" }, { "code": null, "e": 32017, "s": 32000, "text": "Web Technologies" }, { "code": null, "e": 32115, "s": 32017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32150, "s": 32115, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 32185, "s": 32150, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 32220, "s": 32185, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 32244, "s": 32220, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 32297, "s": 32244, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32337, "s": 32297, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32370, "s": 32337, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32415, "s": 32370, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32458, "s": 32415, "text": "How to fetch data from an API in ReactJS ?" } ]
divmod() in Python and its application
The divmod() is part of python’s standard library which takes two numbers as parameters and gives the quotient and remainder of their division as a tuple. It is useful in many mathematical applications like checking for divisibility of numbers and establishing if a number is prime or not. Syntax: divmod(a, b) a and b : b divides a a and b are integers or floats In the below example see the cases of both integers and floats. On the application of divmod() they give us a resulting tuple which is can also contain integers and float values. # with integers print("5 and 2 give:",divmod(5,2)) print("25 and 5 give:",divmod(25,5)) # with Floats print("5.6 and 2 give:",divmod(5.6,2)) print("11.3 and 9.2 give:",divmod(11.3,9.2)) Running the above code gives us the following result − 5 and 2 give: (2, 1) 25 and 5 give: (5, 0) 5.6 and 2 give: (2.0, 1.5999999999999996) 11.3 and 9.2 give: (1.0, 2.1000000000000014) If the first argument is zero then we get (0,0). And If the second argument is zero then we get Zerodivision error as expected. # With first argument as zero print("0 and 8 give:",divmod(0,8)) # With second argument as zero print("8 and 0 give:",divmod(8,0)) Running the above code gives us the following result − 0 and 8 give: (0, 0) Traceback (most recent call last): File "xxx.py", line 6, in print("8 and 0 give:",divmod(8,0)) ZeroDivisionError: integer division or modulo by zero If the second value of the tuple after division is 0 then we say that the first number is divisible by second. Else it is not divisible. The below example illustrates this. m = 12 n = 4 quotient,remainder = divmod(m,n) print(quotient) print(remainder) if (remainder==0): print(m,' is divisible by ',n) else: print(m,' is not divisible by ',n) Running the above code gives us the following result − 3 0 12 is divisible by 4 We can use divmod() to keep track of the reminders it generates when we start dividing a number by each number starting with itself till 1. For a prime number the count of zero remainder will be only one as no number other than itself will divide it perfectly. If the count of zero remainder is greater than 1 then the number is not prime,. num = 11 a = num # counter the number of remainders with value zero count = 0 while a != 0: q, r = divmod(num, a) a -= 1 if r == 0: count += 1 if count > 2: print(num, 'is not Prime') else: print(num, 'is Prime') Running the above code gives us the following result − 11 is Prime
[ { "code": null, "e": 1352, "s": 1062, "text": "The divmod() is part of python’s standard library which takes two numbers as parameters and gives the quotient and remainder of their division as a tuple. It is useful in many mathematical applications like checking for divisibility of numbers and establishing if a number is prime or not." }, { "code": null, "e": 1426, "s": 1352, "text": "Syntax: divmod(a, b)\na and b : b divides a\na and b are integers or floats" }, { "code": null, "e": 1605, "s": 1426, "text": "In the below example see the cases of both integers and floats. On the application of divmod() they give us a resulting tuple which is can also contain integers and float values." }, { "code": null, "e": 1792, "s": 1605, "text": "# with integers\nprint(\"5 and 2 give:\",divmod(5,2))\nprint(\"25 and 5 give:\",divmod(25,5))\n\n# with Floats\nprint(\"5.6 and 2 give:\",divmod(5.6,2))\nprint(\"11.3 and 9.2 give:\",divmod(11.3,9.2))" }, { "code": null, "e": 1847, "s": 1792, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1977, "s": 1847, "text": "5 and 2 give: (2, 1)\n25 and 5 give: (5, 0)\n5.6 and 2 give: (2.0, 1.5999999999999996)\n11.3 and 9.2 give: (1.0, 2.1000000000000014)" }, { "code": null, "e": 2105, "s": 1977, "text": "If the first argument is zero then we get (0,0). And If the second argument is zero then we get Zerodivision error as expected." }, { "code": null, "e": 2237, "s": 2105, "text": "# With first argument as zero\nprint(\"0 and 8 give:\",divmod(0,8))\n\n# With second argument as zero\nprint(\"8 and 0 give:\",divmod(8,0))" }, { "code": null, "e": 2292, "s": 2237, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2463, "s": 2292, "text": "0 and 8 give: (0, 0)\nTraceback (most recent call last):\nFile \"xxx.py\", line 6, in\nprint(\"8 and 0 give:\",divmod(8,0))\nZeroDivisionError: integer division or modulo by zero" }, { "code": null, "e": 2636, "s": 2463, "text": "If the second value of the tuple after division is 0 then we say that the first number is divisible by second. Else it is not divisible. The below example illustrates this." }, { "code": null, "e": 2812, "s": 2636, "text": "m = 12\nn = 4\nquotient,remainder = divmod(m,n)\nprint(quotient)\nprint(remainder)\nif (remainder==0):\n print(m,' is divisible by ',n)\nelse:\n print(m,' is not divisible by ',n)" }, { "code": null, "e": 2867, "s": 2812, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2892, "s": 2867, "text": "3\n0\n12 is divisible by 4" }, { "code": null, "e": 3233, "s": 2892, "text": "We can use divmod() to keep track of the reminders it generates when we start dividing a number by each number starting with itself till 1. For a prime number the count of zero remainder will be only one as no number other than itself will divide it perfectly. If the count of zero remainder is greater than 1 then the number is not prime,." }, { "code": null, "e": 3467, "s": 3233, "text": "num = 11\na = num\n# counter the number of remainders with value zero\ncount = 0\nwhile a != 0:\n q, r = divmod(num, a)\n a -= 1\n if r == 0:\n count += 1\nif count > 2:\n print(num, 'is not Prime')\nelse:\n print(num, 'is Prime')" }, { "code": null, "e": 3522, "s": 3467, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3534, "s": 3522, "text": "11 is Prime" } ]
Check if a number is positive, negative or zero using bit operators in C++
Here we will check whether a number is positive, or negative or zero using bit operators. If we perform shifting like n >> 31, then it will convert every negative number to -1, every other number to 0. If we perform –n >> 31, then for positive number it will return -1. When we do for 0, then n >> 31, and –n >> 31, both returns 0. for that we will use another formula as below − 1+(n>>31)−(−n>>31) So now, if n is negative: 1 + (-1) – 0 = 0 n is positive: 1 + 0 – (-1) = 2 n is 0: 1 + 0 – 0 = 1 Live Demo #include <iostream> #include <cmath> using namespace std; int checkNumber(int n){ return 1+(n >> 31) - (-n >> 31); } int printNumberType(int n){ int res = checkNumber(n); if(res == 0) cout << n << " is negative"<< endl; else if(res == 1) cout << n << " is Zero" << endl; else if(res == 2) cout << n << " is Positive" << endl; } int main() { printNumberType(50); printNumberType(-10); printNumberType(70); printNumberType(0); } 50 is Positive -10 is negative 70 is Positive 0 is Zero
[ { "code": null, "e": 1442, "s": 1062, "text": "Here we will check whether a number is positive, or negative or zero using bit operators. If we perform shifting like n >> 31, then it will convert every negative number to -1, every other number to 0. If we perform –n >> 31, then for positive number it will return -1. When we do for 0, then n >> 31, and –n >> 31, both returns 0. for that we will use another formula as below −" }, { "code": null, "e": 1461, "s": 1442, "text": "1+(n>>31)−(−n>>31)" }, { "code": null, "e": 1472, "s": 1461, "text": "So now, if" }, { "code": null, "e": 1504, "s": 1472, "text": "n is negative: 1 + (-1) – 0 = 0" }, { "code": null, "e": 1536, "s": 1504, "text": "n is positive: 1 + 0 – (-1) = 2" }, { "code": null, "e": 1558, "s": 1536, "text": "n is 0: 1 + 0 – 0 = 1" }, { "code": null, "e": 1569, "s": 1558, "text": " Live Demo" }, { "code": null, "e": 2041, "s": 1569, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint checkNumber(int n){\n return 1+(n >> 31) - (-n >> 31);\n}\nint printNumberType(int n){\n int res = checkNumber(n);\n if(res == 0)\n cout << n << \" is negative\"<< endl;\n else if(res == 1)\n cout << n << \" is Zero\" << endl;\n else if(res == 2)\n cout << n << \" is Positive\" << endl;\n}\nint main() {\n printNumberType(50);\n printNumberType(-10);\n printNumberType(70);\n printNumberType(0);\n}" }, { "code": null, "e": 2097, "s": 2041, "text": "50 is Positive\n-10 is negative\n70 is Positive\n0 is Zero" } ]
Graph Coloring
Graph coloring problem is a special case of graph labeling. In this problem, each node is colored into some colors. But coloring has some constraints. We cannot use the same color for any adjacent vertices. For solving this problem, we need to use the greedy algorithm, but it does not guaranty to use minimum color. Input: Adjacency matrix of the graph. 0 0 1 0 1 0 0 1 1 1 1 1 0 1 0 0 1 1 0 1 1 1 0 1 0 Output: Node: 0, Assigned with Color: 0 Node: 1, Assigned with Color: 0 Node: 2, Assigned with Color: 1 Node: 3, Assigned with Color: 2 Node: 4, Assigned with Color: 1 graphColoring(graph) Input − The given graph. Output − Each node with some color assigned to it. Begin declare a list of colors initially set the color 0 for first node define an array colorUsed to track which color is used, and which colors have never used. for all vertices i except first one, do mark i as unassigned to any color done mark colorUsed to false for all vertices for all vertices u in the graph except 1st vertex, do for all vertex v adjacent with u, do if color[v] is unassigned, then mark colorUsed[color[v]] := true done for all colors col in the color list, do if color is not used, then stop the loop done color[u] := col for each vertex v which is adjacent with u, do if color[v] is unassigned, then colorUsed[color[v]] := false done done for all vertices u in the graph, do display the node and its color done End #include<iostream> #define NODE 6 using namespace std; int graph[NODE][NODE] = { {0, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0}, {1, 0, 0, 1, 0, 1}, {1, 1, 1, 0, 1, 1}, {0, 1, 0, 1, 0, 1}, {0, 0, 1, 1, 1, 0} }; void graphColoring() { int color[NODE]; color[0] = 0; //Assign first color for the first node bool colorUsed[NODE]; //Used to check whether color is used or not for(int i = 1; i<NODE; i++) color[i] = -1; //initialize all other vertices are unassigned for(int i = 0; i<NODE; i++) colorUsed[i] = false; //initially any colors are not chosen for(int u = 1; u<NODE; u++) { //for all other NODE - 1 vertices for(int v = 0; v<NODE; v++) { if(graph[u][v]){ if(color[v] != -1) //when one color is assigned, make it unavailable colorUsed[color[v]] = true; } } int col; for(col = 0; col<NODE; col++) if(!colorUsed[col]) //find a color which is not assigned break; color[u] = col; //assign found color in the list for(int v = 0; v<NODE; v++) { //for next iteration make color availability to false if(graph[u][v]) { if(color[v] != -1) colorUsed[color[v]] = false; } } } for(int u = 0; u<NODE; u++) cout <<"Color: " << u << ", Assigned with Color: " <<color[u] <<endl; } main() { graphColoring(); } Node: 0, Assigned with Color: 0 Node: 1, Assigned with Color: 0 Node: 2, Assigned with Color: 1 Node: 3, Assigned with Color: 2 Node: 4, Assigned with Color: 1
[ { "code": null, "e": 1269, "s": 1062, "text": "Graph coloring problem is a special case of graph labeling. In this problem, each node is colored into some colors. But coloring has some constraints. We cannot use the same color for any adjacent vertices." }, { "code": null, "e": 1379, "s": 1269, "text": "For solving this problem, we need to use the greedy algorithm, but it does not guaranty to use minimum color." }, { "code": null, "e": 1636, "s": 1379, "text": "Input:\nAdjacency matrix of the graph.\n0 0 1 0 1\n0 0 1 1 1\n1 1 0 1 0\n0 1 1 0 1\n1 1 0 1 0\n\nOutput:\nNode: 0, Assigned with Color: 0\nNode: 1, Assigned with Color: 0\nNode: 2, Assigned with Color: 1\nNode: 3, Assigned with Color: 2\nNode: 4, Assigned with Color: 1" }, { "code": null, "e": 1657, "s": 1636, "text": "graphColoring(graph)" }, { "code": null, "e": 1682, "s": 1657, "text": "Input − The given graph." }, { "code": null, "e": 1733, "s": 1682, "text": "Output − Each node with some color assigned to it." }, { "code": null, "e": 2625, "s": 1733, "text": "Begin\n declare a list of colors\n initially set the color 0 for first node\n define an array colorUsed to track which color is used, and which colors have never used.\n\n for all vertices i except first one, do\n mark i as unassigned to any color\n done\n\n mark colorUsed to false for all vertices\n for all vertices u in the graph except 1st vertex, do\n for all vertex v adjacent with u, do\n if color[v] is unassigned, then\n mark colorUsed[color[v]] := true\n done\n\n for all colors col in the color list, do\n if color is not used, then\n stop the loop\n done\n\n color[u] := col\n for each vertex v which is adjacent with u, do\n if color[v] is unassigned, then\n colorUsed[color[v]] := false\n done\n done\n\n for all vertices u in the graph, do\n display the node and its color\n done\nEnd" }, { "code": null, "e": 4085, "s": 2625, "text": "#include<iostream>\n#define NODE 6\nusing namespace std;\n\nint graph[NODE][NODE] = {\n {0, 1, 1, 1, 0, 0},\n {1, 0, 0, 1, 1, 0},\n {1, 0, 0, 1, 0, 1},\n {1, 1, 1, 0, 1, 1},\n {0, 1, 0, 1, 0, 1},\n {0, 0, 1, 1, 1, 0}\n};\n\nvoid graphColoring() {\n int color[NODE];\n color[0] = 0; //Assign first color for the first node\n bool colorUsed[NODE]; //Used to check whether color is used or not\n\n for(int i = 1; i<NODE; i++)\n color[i] = -1; //initialize all other vertices are unassigned\n\n for(int i = 0; i<NODE; i++)\n colorUsed[i] = false; //initially any colors are not chosen\n \n for(int u = 1; u<NODE; u++) { //for all other NODE - 1 vertices\n for(int v = 0; v<NODE; v++) {\n if(graph[u][v]){\n if(color[v] != -1) //when one color is assigned, make it unavailable\n colorUsed[color[v]] = true;\n }\n }\n\n int col;\n for(col = 0; col<NODE; col++)\n if(!colorUsed[col]) //find a color which is not assigned\n break;\n \n color[u] = col; //assign found color in the list\n \n for(int v = 0; v<NODE; v++) { //for next iteration make color availability to false\n if(graph[u][v]) {\n if(color[v] != -1)\n colorUsed[color[v]] = false;\n }\n } \n }\n \n for(int u = 0; u<NODE; u++)\n cout <<\"Color: \" << u << \", Assigned with Color: \" <<color[u] <<endl;\n}\n\nmain() {\n graphColoring();\n}" }, { "code": null, "e": 4245, "s": 4085, "text": "Node: 0, Assigned with Color: 0\nNode: 1, Assigned with Color: 0\nNode: 2, Assigned with Color: 1\nNode: 3, Assigned with Color: 2\nNode: 4, Assigned with Color: 1" } ]
Balance a Binary Search Tree in c++
Suppose we have a binary search tree, we have to find a balanced binary search tree with the same node values. A binary search tree is said to be balanced if and only if the depth of the two subtrees of every node never differ by more than 1. If there is more than one result, return any of them. So if the tree is like − To solve this, we will follow these steps − Define inorder() method, this will store in order traversal sequence into an array Define inorder() method, this will store in order traversal sequence into an array Define the construct method(), this will take low and high − Define the construct method(), this will take low and high − if low > high then return null if low > high then return null mid := low + (high - low) / 2 mid := low + (high - low) / 2 root := new node with value arr[mid] root := new node with value arr[mid] left of root := construct(low, mid – 1) and right of root := construct(mid + 1, high) left of root := construct(low, mid – 1) and right of root := construct(mid + 1, high) return root return root From the main method, call the inorder method and return construct(0, size of arr - 1) From the main method, call the inorder method and return construct(0, size of arr - 1) Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; }else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; }else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } void tree_level_trav(TreeNode*root){ if (root == NULL) return; cout << "["; queue<TreeNode *> q; TreeNode *curr; q.push(root); q.push(NULL); while (q.size() > 1) { curr = q.front(); q.pop(); if (curr == NULL){ q.push(NULL); } else { if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); if(curr->val == 0 || curr == NULL){ cout << "null" << ", "; }else{ cout << curr->val << ", "; } } } cout << "]"<<endl; } class Solution { public: vector <int> arr; void inorder(TreeNode* node){ if(!node || node->val == 0) return; inorder(node->left); arr.push_back(node->val); inorder(node->right); } TreeNode* construct(int low, int high){ if(low > high) return NULL; int mid = low + (high - low) / 2; TreeNode* root = new TreeNode(arr[mid]); root->left = construct(low, mid - 1); root->right = construct(mid + 1, high); return root; } TreeNode* balanceBST(TreeNode* root) { inorder(root); return construct(0, (int)arr.size() - 1); } }; main(){ vector<int> v = {1,NULL,2,NULL,NULL,NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4}; TreeNode *root = make_tree(v); Solution ob; tree_level_trav(ob.balanceBST(root)); } [1,NULL,2,NULL,NULL,NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4] [2, 1, 3, 4, ]
[ { "code": null, "e": 1384, "s": 1062, "text": "Suppose we have a binary search tree, we have to find a balanced binary search tree with the same node values. A binary search tree is said to be balanced if and only if the depth of the two subtrees of every node never differ by more than 1. If there is more than one result, return any of them. So if the tree is like −" }, { "code": null, "e": 1428, "s": 1384, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1511, "s": 1428, "text": "Define inorder() method, this will store in order traversal sequence into an array" }, { "code": null, "e": 1594, "s": 1511, "text": "Define inorder() method, this will store in order traversal sequence into an array" }, { "code": null, "e": 1655, "s": 1594, "text": "Define the construct method(), this will take low and high −" }, { "code": null, "e": 1716, "s": 1655, "text": "Define the construct method(), this will take low and high −" }, { "code": null, "e": 1747, "s": 1716, "text": "if low > high then return null" }, { "code": null, "e": 1778, "s": 1747, "text": "if low > high then return null" }, { "code": null, "e": 1808, "s": 1778, "text": "mid := low + (high - low) / 2" }, { "code": null, "e": 1838, "s": 1808, "text": "mid := low + (high - low) / 2" }, { "code": null, "e": 1875, "s": 1838, "text": "root := new node with value arr[mid]" }, { "code": null, "e": 1912, "s": 1875, "text": "root := new node with value arr[mid]" }, { "code": null, "e": 1998, "s": 1912, "text": "left of root := construct(low, mid – 1) and right of root := construct(mid + 1, high)" }, { "code": null, "e": 2084, "s": 1998, "text": "left of root := construct(low, mid – 1) and right of root := construct(mid + 1, high)" }, { "code": null, "e": 2096, "s": 2084, "text": "return root" }, { "code": null, "e": 2108, "s": 2096, "text": "return root" }, { "code": null, "e": 2195, "s": 2108, "text": "From the main method, call the inorder method and return construct(0, size of arr - 1)" }, { "code": null, "e": 2282, "s": 2195, "text": "From the main method, call the inorder method and return construct(0, size of arr - 1)" }, { "code": null, "e": 2354, "s": 2282, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2365, "s": 2354, "text": " Live Demo" }, { "code": null, "e": 4701, "s": 2365, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TreeNode{\n public:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = right = NULL;\n }\n};\nvoid insert(TreeNode **root, int val){\n queue<TreeNode*> q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector<int> v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n insert(&root, v[i]);\n }\n return root;\n}\nvoid tree_level_trav(TreeNode*root){\n if (root == NULL) return;\n cout << \"[\";\n queue<TreeNode *> q;\n TreeNode *curr;\n q.push(root);\n q.push(NULL);\n while (q.size() > 1) {\n curr = q.front();\n q.pop();\n if (curr == NULL){\n q.push(NULL);\n } else {\n if(curr->left)\n q.push(curr->left);\n if(curr->right)\n q.push(curr->right);\n if(curr->val == 0 || curr == NULL){\n cout << \"null\" << \", \";\n }else{\n cout << curr->val << \", \";\n }\n }\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n vector <int> arr;\n void inorder(TreeNode* node){\n if(!node || node->val == 0) return;\n inorder(node->left);\n arr.push_back(node->val);\n inorder(node->right);\n }\n TreeNode* construct(int low, int high){\n if(low > high) return NULL;\n int mid = low + (high - low) / 2;\n TreeNode* root = new TreeNode(arr[mid]);\n root->left = construct(low, mid - 1);\n root->right = construct(mid + 1, high);\n return root;\n }\n TreeNode* balanceBST(TreeNode* root) {\n inorder(root);\n return construct(0, (int)arr.size() - 1);\n }\n};\nmain(){\n vector<int> v = {1,NULL,2,NULL,NULL,NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4};\n TreeNode *root = make_tree(v);\n Solution ob;\n tree_level_trav(ob.balanceBST(root));\n}" }, { "code": null, "e": 4766, "s": 4701, "text": "[1,NULL,2,NULL,NULL,NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4]" }, { "code": null, "e": 4781, "s": 4766, "text": "[2, 1, 3, 4, ]" } ]
Probability and Statistics explained in the context of deep learning | by laxman vijay | Towards Data Science
This article is intended for beginners in deep learning who wish to gain knowledge about probability and statistics and also as a reference for practitioners. In my previous article, I wrote about the concepts of linear algebra for deep learning in a top down approach ( link for the article ) (If you do not have enough idea about linear algebra, please read that first).The same top down approach is used here.Providing the description of use cases first and then the concepts. All the example code uses python and numpy.Formulas are provided as images for reuse. Introduction Foundations of probability Measures of central tendency and variability Discrete probability distributions, binomial distribution Continuous probability distributions, uniform and normal distributions Model Accuracy measurement tools Random process and Markov chains Probabilistic programming External resources Introduction: Probability is the science of quantifying uncertain things.Most of machine learning and deep learning systems utilize a lot of data to learn about patterns in the data.Whenever data is utilized in a system rather than sole logic, uncertainty grows up and whenever uncertainty grows up, probability becomes relevant. By introducing probability to a deep learning system, we introduce common sense to the system.Otherwise the system would be very brittle and will not be useful.In deep learning, several models like bayesian models, probabilistic graphical models, hidden markov models are used.They depend entirely on probability concepts. Real world data is chaotic.Since deep learning systems utilize real world data, they require a tool to handle the chaoticness. It is always practical to use a simple and uncertain system rather than a complex but certain and brittle one. The versions of probability and statistics presented here are a highly simplified versions of the actual subjects. Both are very huge and individual research subjects. But the concepts written here is enough for a deep learning aspirant. I have left links for some great resources on these individual subjects in the end of this article. Foundations of probability: If you start deep learning, the very first example(probably), the tutor provides you is the MNIST handwritten digit recognition task.It is like the hello world of deep learning. The task is to classify handwritten digits and label them. As I mentioned earlier, the machine learning system which you create to do this task is not accurate or certain.The images are 28*28 pixel images.For example, consider the below neural network for this task. The input layer is a flattened vector of the size of the input image(28*28=784).It is passed to a layer, where the input vector is multiplied by the weights and added with the bias vector. This layer has 10 neurons. This is the implication that there are 10 digits.Then they go through a softmax activation function. After this step they do not output the exact digit but a vector of length 10 with each element being a probability value for each digit. We use argmax to get the index of the probability with the highest value in the output vector.(which is the prediction) Having said this, we shall revisit softmax in detail.The point here is that to understand this neural network, we have to understand some basics of probability. vector y = [y0, y1, y2, y3, y4, y5, y6, y7, y8 , y9] Where is probability in this? Sample space: The set of all possible values in an experiment.(In the above example, the input can be from a set of images,thus it is the sample space for the input,similarly, the output prediction can take any value from the digits 0 to 9, thus the digits are the sample space for the output prediction.) Random variable: A variable that can take different values of the sample space randomly. In the above neural network, the input vector x is a random variable, the output ‘prediction’ is a random variable, the weights of the neural network is also a random variable(because they are initialized randomly using a probability distribution.) Probability distribution: The probability distribution is a description of how likely the random variable is to take on different values of the sample space.In the neural network, the weights are initialized from a probability distribution.The output vector y follows softmax distribution which is also a probability distribution that shows the probability of X taking different digit values.(In general,softmax provides the probability of categorical values) In this example, the probability distribution y is discrete(having 10 discrete values.) whereas in some other cases, it may be continuous(the sample space is also continuous).In a discrete distribution, the probability distribution is provided by a probability mass function(pmf) denoted by P(x=x). In the above example, the softmax function is the pmf of the random variable X. If you see some instance of the output vector y = [0.03,0.5,0.07,0.04,0.06,0.05,0.05,0.06,0.04,0.1] What’s so special in this? If you look closely they all add up to 1.0 and the argmax shows that index 1 has maximum value of 0.5 indicating the value should be 1. This property of adding upto 1.0 is called normalization.Also the values must be between 0 and 1. An impossible event is denoted by 0 and a sure event is denoted by 1. The same conditions hold true for continuous variables.(We’ll see in a moment.) In any probability book or class, you will always learn these 3 basics in the very beginning.They are conditional probability, marginal probability and joint probability. Joint Probability:What is the probability of two events occurring simultaneously .denoted by P(y=y,x=x) or p(y and x). Example: probability of seeing sun and moon at the same time is very low. Conditional probability: What is the probability of some event y happening, given that other event x had happened .denoted by P(y = y | x =x). since the other event x had occurred, it’s probability can’t be zero. Example: probability of drinking water after eating is very high. Marginal probability:what is the probability of a subset of random variables from a superset of them.Example: probability of people having long hair is the sum of probability of men having long hair and probability of women having long hair.(Here the long hair random variable is kept constant and the gender random variable was changed.) Bayes’ theorem: It describes the probability of an event based on prior knowledge of other events related to that event. Bayes theorem exploits the concept of belief in probability. “I am 40% sure that this event will happen” is not the same as “The dice has 16% chance of showing 6”.The former utilizes belief and is called as bayesian probability while the latter depends on previous data and is called as frequentist probability. Read more Bayes theorem is also used in one of the most simple machine learning algorithm called the naive bayes algorithm.see sklearn docs. Mean: Mean is the arithmetical average value of the data. numpy docs import numpy as npa = np.array([[1,2,3,4,5,6]])np.mean(a,axis=0) Median: It is the middle value of the data. numpy docs. np.median(a,axis=0) Mode: It is the frequently occuring value of the data. scipy docs. import numpy as npfrom scipy import statsstats.mode(a) Expected value: of some variable X with respect to some distribution P(X=x) is the mean value of X when x is drawn from P. The expectation is equal to the statistical mean of the dataset. look why. Variance: It is the measure of variability in the data from the mean value. import numpy as npa = np.array([[1,2,3,4,5,6]])np.var(a) For a random variable, variance is given by, this formula has the same meaning as the above formula. numpy docs. Standard deviation:It is the square root of variance. numpy docs. import numpy as npnp.std(a) The are also some other measures of variation like range and interquartile distance.look here Co variance: It shows how to two variables are linearly related to each other. Numpy outputs a covariance matrix where Cij denotes the covariance between xi and xj. numpy docs np.cov(a) As I mentioned in the beginning,several components of the neural networks are random variables.The values of the random variables are drawn from a probability distribution.In many cases,we use only certain types of probability distributions.Some of them are, Binomial distribution: A binomial random variable is the number of successes in n trials of a random experiment. A random variable x is said to follow binomial distribution when, the random variable can have only two outcomes(success and failure).Naturally , binomial distribution is for discrete random variables. numpy docs. import numpy as npn=10 # number of trialsp=0.5 # probability of successs=1000 # sizenp.random.binomial(n,p,s) Continuous distributions: These are defined for continuous random variables.In continuous distribution, we describe the distribution using probability density functions(pdf) denoted by p(x). Their integral is equal to 1. If you are not comfortable with integral or differential calculus look here, Uniform Distribution: It is the simplest form of continuous distribution, with every element of the sample space being equally likely. numpy docs import numpy as npnp.random.uniform(low=1, high=10,size=100) Normal distribution: “Order from Chaos” It is the most important of all distributions.Also known as Gaussian distribution.In the absence of prior knowledge about what form a distribution over the real numbers should take, the normal distribution is a good choice because, it has high entropy and central limit theorem suggests that sum of several independent random variables is normally distributed. numpy docs import numpy as npmu = 0sigma = 1np.random.normal(mu,sigma,size=100) In a normal distribution, if the mean is 0 and the standard deviation is 1, then it is called as standard normal distribution. In machine learning, you often encounter the word ‘ normalization’ and ‘standardization’. the process which we did above to obtain standard normal distribution is called standardization whereas the process of restricting the range of dataset values between 0.0 to 1.0 is called as normalization. However, these terms are often interchanged. from sklearn.preprocessing import StandardScalerimport numpy as npdata = np.array([1,2,3,4,5])scaler = StandardScaler()scaler.fit_transform(data) At this stage, we have come across several formulae and definitions. It is very useful if you memorize all these.(Or use this article as a reference! )There are also other important distributions like exponential and poisson distribution. refer here for a quick glance. Softmax distribution:In the beginning of this article, I mentioned about softmax. It is a probability distribution kinda.It is best used to represent 1 of N class categorical distribution. It is also the most commonly used distributions in deep learning.It is very convenient to differentiate. def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0)##the np.max(x) is used just for numerical stability.it is Not ##formula In order to measure the performance of a deep learning model, we use several concepts. Knowing these concepts is very important.They are called as metrics.In the above MNIST neural network, if the neural network predicted 95 of the 100 input images correctly, then it’s accuracy is said to be 95% and so on.(This part uses sklearn python library for examples.) You can understand accuracy intuitively, but the theory is,It is the proposition of correct results in the total obtained results. Accuracy is a very simple measurement and it may provide wrong insights sometimes.In some cases, higher accuracy doesn’t mean our model is working correctly.To clarify this, first look at the following definitions, True Positives (TP): number of positive examples, labeled as such. False Positives (FP): number of negative examples, labeled as positive. True Negatives (TN): number of negative examples, labeled as such. False Negatives (FN): number of positive examples, labeled as negative. Accuracy = (TP + TN)/(TP + FP + TN + FN) Confusion matrix: It is a matrix containing the TP, FP,TN and FN values. from sklearn.metrics import confusion_matrixy_true = [2, 0, 2, 2, 0, 1]y_pred = [0, 0, 2, 2, 0, 2]confusion_matrix(y_true, y_pred) Now, Imagine a binary classifier, that outputs 1 or 0. If everything was proper and the model was not biased, it says the actual accuracy.But if we tweak the model to say 0 all the time(or 1 all the time)(now the prediction power of the model is None).but still we would get a high accuracy! consider the table. Classified positive Classified negative Positive class 0 (TP) 25 (FN)Negative class 0 (FP) 125 (TN) This table is obvious that the model is very bad(because all the positive class examples are incorrectly classified) but the accuracy is 83% !! Precision and recall: So we go for two other metrics-precision and recall. Precision tells you how many of the selected objects were correct Recall tells you how many correct objects were selected. In the above example, both precision and recall are 0.0 This indicates that the model is extremely poor. F1 score: It is the harmonic average of precision and recall. F1 score of 0 means worst and 1 means best.By using this, we can resolve the chaotic behaviour of accuracy metric. Sklearn has a classification_report function that you can invoke to get the precision, recall, f1 score. >>> from sklearn.metrics import classification_report>>> y_true = [0, 1, 2, 2, 2]>>> y_pred = [0, 0, 2, 2, 1]>>> target_names = ['class 0', 'class 1', 'class 2']>>> print(classification_report(y_true, y_pred, target_names=target_names)) precision recall f1-score support class 0 0.50 1.00 0.67 1 class 1 0.00 0.00 0.00 1 class 2 1.00 0.67 0.80 3 micro avg 0.60 0.60 0.60 5 macro avg 0.50 0.56 0.49 5weighted avg 0.70 0.60 0.61 5 Mean Absolute error: It is the average of difference between the original and predicted values. Mean squared error: it is the average of square of difference between the original and predicted values. from sklearn.metrics import mean_squared_errory_true = [3, -0.5, 2, 7]y_pred = [2.5, 0.0, 2, 8]mean_squared_error(y_true, y_pred) Mean squared error is widely used because it is easier to compute the gradients. Receiver operating characteristic(ROC) curve:The roc curve is a graph showing the performance of classification models like our digit recognizer example.It has two parameters — True Positive rate(TPR) and False Positive rate(FPR).TPR is the same as recall and is also called as sensitivity. FPR is also 1-specificity. These two are plotted against each other to obtain the following graph(several values of plots are obtained by changing the classification threshold and predicting the results again repeatedly.).The area under this ROC curve is a measure of the accuracy. Interpretation of area under the curve(AUC):When AUC=1.0 the model is best.When AUC=0.5 the model is worst.But if AUC=0.0 then the model is reciprocating the results.(Like classifying 1's as 0’s and 0’s as 1's). import numpy as npfrom sklearn.metrics import roc_auc_scorey_true = np.array([0, 0, 1, 1])y_scores = np.array([0.1, 0.4, 0.35, 0.8])roc_auc_score(y_true, y_scores) More information:look here and here. Calculation of AUC using trapezoidal rule(sklearn uses this rule):look here A random process is a collection of random variables that are indexed by some values.Intuitively, a random process or stochastic process is a mathematical model for a phenomenon that proceeds in an unpredictable manner to the observer.The outcome of the next event is not dependent on the outcome of the current event.Example, a series of coin tosses. If the index set by which the random variables are indexed in a random process are from a discrete natural numbers, then the process is called as discrete time random process or random sequence.If the index set lies in real number line, then the process is continuous time random process.If the index set lies in cartesian plane or some higher dimensional euclidean planes, then the process is said to be random field. Random processes are a really interesting part of probability.They are used to model time related stuffs like weather forecast, stock market, natural phenomenons,etc.There are several random processes.Here we focus on markov chains.For a more elaborate material, refer wikipedia. Markov chains: A markov chain is a probabilistic automaton.It has states.It describes a sequence of events in which probability of transitioning from one state to another depends only on previous event. Here is an excellent visual explanation of markov chains. This is a markov chain that describes the weather condition.The values represent the probability of transition from one state to another. Markov chains are used for simple systems like next word prediction, language generation, sound generation and many other systems. The extension of markov chains known as hidden markov models are used in speech recognition systems. I have stopped random processes till here and planned for an extensive article on them because of the excessive length of the concept. A new paradigm of programming has evolved known as probabilistic programming.These languages or libraries help to model bayesian style machine learning.It is an exciting research field which is supported by both the AI community and the software engineering community.These languages readily support probabilistic functions and models like gaussian models,markov models, etc. One such library for writing probabilistic programs was created by Uber last year known as pyro which supports python with pytorch(a deep learning library) as the backend. If you liked this article about probability and statistics for deep learning, leave claps for the article. The content provided here are intended for beginners in deep learning and can also be used as reference material by deep learning practitioners. But for beginners, I would also suggest several other awesome external resources, to reinforce their knowledge in the interesting field of probability.(Though the knowledge that you gained through this article is enough for proceeding in deep learning) Awesome free course on deep learning and machine learning: fast.ai Intuitive explanation of calculus: 3blue1brown Best book on deep learning: the deep learning book Random process: Sheldon M. Ross Statistics: All of statistics by Larry Wasserman Probability theory: William Feller
[ { "code": null, "e": 330, "s": 171, "text": "This article is intended for beginners in deep learning who wish to gain knowledge about probability and statistics and also as a reference for practitioners." }, { "code": null, "e": 651, "s": 330, "text": "In my previous article, I wrote about the concepts of linear algebra for deep learning in a top down approach ( link for the article ) (If you do not have enough idea about linear algebra, please read that first).The same top down approach is used here.Providing the description of use cases first and then the concepts." }, { "code": null, "e": 737, "s": 651, "text": "All the example code uses python and numpy.Formulas are provided as images for reuse." }, { "code": null, "e": 750, "s": 737, "text": "Introduction" }, { "code": null, "e": 777, "s": 750, "text": "Foundations of probability" }, { "code": null, "e": 822, "s": 777, "text": "Measures of central tendency and variability" }, { "code": null, "e": 880, "s": 822, "text": "Discrete probability distributions, binomial distribution" }, { "code": null, "e": 951, "s": 880, "text": "Continuous probability distributions, uniform and normal distributions" }, { "code": null, "e": 984, "s": 951, "text": "Model Accuracy measurement tools" }, { "code": null, "e": 1017, "s": 984, "text": "Random process and Markov chains" }, { "code": null, "e": 1043, "s": 1017, "text": "Probabilistic programming" }, { "code": null, "e": 1062, "s": 1043, "text": "External resources" }, { "code": null, "e": 1076, "s": 1062, "text": "Introduction:" }, { "code": null, "e": 1392, "s": 1076, "text": "Probability is the science of quantifying uncertain things.Most of machine learning and deep learning systems utilize a lot of data to learn about patterns in the data.Whenever data is utilized in a system rather than sole logic, uncertainty grows up and whenever uncertainty grows up, probability becomes relevant." }, { "code": null, "e": 1715, "s": 1392, "text": "By introducing probability to a deep learning system, we introduce common sense to the system.Otherwise the system would be very brittle and will not be useful.In deep learning, several models like bayesian models, probabilistic graphical models, hidden markov models are used.They depend entirely on probability concepts." }, { "code": null, "e": 1842, "s": 1715, "text": "Real world data is chaotic.Since deep learning systems utilize real world data, they require a tool to handle the chaoticness." }, { "code": null, "e": 1953, "s": 1842, "text": "It is always practical to use a simple and uncertain system rather than a complex but certain and brittle one." }, { "code": null, "e": 2291, "s": 1953, "text": "The versions of probability and statistics presented here are a highly simplified versions of the actual subjects. Both are very huge and individual research subjects. But the concepts written here is enough for a deep learning aspirant. I have left links for some great resources on these individual subjects in the end of this article." }, { "code": null, "e": 2319, "s": 2291, "text": "Foundations of probability:" }, { "code": null, "e": 2497, "s": 2319, "text": "If you start deep learning, the very first example(probably), the tutor provides you is the MNIST handwritten digit recognition task.It is like the hello world of deep learning." }, { "code": null, "e": 2764, "s": 2497, "text": "The task is to classify handwritten digits and label them. As I mentioned earlier, the machine learning system which you create to do this task is not accurate or certain.The images are 28*28 pixel images.For example, consider the below neural network for this task." }, { "code": null, "e": 3081, "s": 2764, "text": "The input layer is a flattened vector of the size of the input image(28*28=784).It is passed to a layer, where the input vector is multiplied by the weights and added with the bias vector. This layer has 10 neurons. This is the implication that there are 10 digits.Then they go through a softmax activation function." }, { "code": null, "e": 3218, "s": 3081, "text": "After this step they do not output the exact digit but a vector of length 10 with each element being a probability value for each digit." }, { "code": null, "e": 3338, "s": 3218, "text": "We use argmax to get the index of the probability with the highest value in the output vector.(which is the prediction)" }, { "code": null, "e": 3499, "s": 3338, "text": "Having said this, we shall revisit softmax in detail.The point here is that to understand this neural network, we have to understand some basics of probability." }, { "code": null, "e": 3552, "s": 3499, "text": "vector y = [y0, y1, y2, y3, y4, y5, y6, y7, y8 , y9]" }, { "code": null, "e": 3582, "s": 3552, "text": "Where is probability in this?" }, { "code": null, "e": 3888, "s": 3582, "text": "Sample space: The set of all possible values in an experiment.(In the above example, the input can be from a set of images,thus it is the sample space for the input,similarly, the output prediction can take any value from the digits 0 to 9, thus the digits are the sample space for the output prediction.)" }, { "code": null, "e": 4226, "s": 3888, "text": "Random variable: A variable that can take different values of the sample space randomly. In the above neural network, the input vector x is a random variable, the output ‘prediction’ is a random variable, the weights of the neural network is also a random variable(because they are initialized randomly using a probability distribution.)" }, { "code": null, "e": 4686, "s": 4226, "text": "Probability distribution: The probability distribution is a description of how likely the random variable is to take on different values of the sample space.In the neural network, the weights are initialized from a probability distribution.The output vector y follows softmax distribution which is also a probability distribution that shows the probability of X taking different digit values.(In general,softmax provides the probability of categorical values)" }, { "code": null, "e": 5065, "s": 4686, "text": "In this example, the probability distribution y is discrete(having 10 discrete values.) whereas in some other cases, it may be continuous(the sample space is also continuous).In a discrete distribution, the probability distribution is provided by a probability mass function(pmf) denoted by P(x=x). In the above example, the softmax function is the pmf of the random variable X." }, { "code": null, "e": 5165, "s": 5065, "text": "If you see some instance of the output vector y = [0.03,0.5,0.07,0.04,0.06,0.05,0.05,0.06,0.04,0.1]" }, { "code": null, "e": 5328, "s": 5165, "text": "What’s so special in this? If you look closely they all add up to 1.0 and the argmax shows that index 1 has maximum value of 0.5 indicating the value should be 1." }, { "code": null, "e": 5496, "s": 5328, "text": "This property of adding upto 1.0 is called normalization.Also the values must be between 0 and 1. An impossible event is denoted by 0 and a sure event is denoted by 1." }, { "code": null, "e": 5576, "s": 5496, "text": "The same conditions hold true for continuous variables.(We’ll see in a moment.)" }, { "code": null, "e": 5747, "s": 5576, "text": "In any probability book or class, you will always learn these 3 basics in the very beginning.They are conditional probability, marginal probability and joint probability." }, { "code": null, "e": 5940, "s": 5747, "text": "Joint Probability:What is the probability of two events occurring simultaneously .denoted by P(y=y,x=x) or p(y and x). Example: probability of seeing sun and moon at the same time is very low." }, { "code": null, "e": 6219, "s": 5940, "text": "Conditional probability: What is the probability of some event y happening, given that other event x had happened .denoted by P(y = y | x =x). since the other event x had occurred, it’s probability can’t be zero. Example: probability of drinking water after eating is very high." }, { "code": null, "e": 6558, "s": 6219, "text": "Marginal probability:what is the probability of a subset of random variables from a superset of them.Example: probability of people having long hair is the sum of probability of men having long hair and probability of women having long hair.(Here the long hair random variable is kept constant and the gender random variable was changed.)" }, { "code": null, "e": 6679, "s": 6558, "text": "Bayes’ theorem: It describes the probability of an event based on prior knowledge of other events related to that event." }, { "code": null, "e": 7001, "s": 6679, "text": "Bayes theorem exploits the concept of belief in probability. “I am 40% sure that this event will happen” is not the same as “The dice has 16% chance of showing 6”.The former utilizes belief and is called as bayesian probability while the latter depends on previous data and is called as frequentist probability. Read more" }, { "code": null, "e": 7132, "s": 7001, "text": "Bayes theorem is also used in one of the most simple machine learning algorithm called the naive bayes algorithm.see sklearn docs." }, { "code": null, "e": 7201, "s": 7132, "text": "Mean: Mean is the arithmetical average value of the data. numpy docs" }, { "code": null, "e": 7266, "s": 7201, "text": "import numpy as npa = np.array([[1,2,3,4,5,6]])np.mean(a,axis=0)" }, { "code": null, "e": 7322, "s": 7266, "text": "Median: It is the middle value of the data. numpy docs." }, { "code": null, "e": 7342, "s": 7322, "text": "np.median(a,axis=0)" }, { "code": null, "e": 7409, "s": 7342, "text": "Mode: It is the frequently occuring value of the data. scipy docs." }, { "code": null, "e": 7464, "s": 7409, "text": "import numpy as npfrom scipy import statsstats.mode(a)" }, { "code": null, "e": 7587, "s": 7464, "text": "Expected value: of some variable X with respect to some distribution P(X=x) is the mean value of X when x is drawn from P." }, { "code": null, "e": 7662, "s": 7587, "text": "The expectation is equal to the statistical mean of the dataset. look why." }, { "code": null, "e": 7738, "s": 7662, "text": "Variance: It is the measure of variability in the data from the mean value." }, { "code": null, "e": 7795, "s": 7738, "text": "import numpy as npa = np.array([[1,2,3,4,5,6]])np.var(a)" }, { "code": null, "e": 7840, "s": 7795, "text": "For a random variable, variance is given by," }, { "code": null, "e": 7908, "s": 7840, "text": "this formula has the same meaning as the above formula. numpy docs." }, { "code": null, "e": 7974, "s": 7908, "text": "Standard deviation:It is the square root of variance. numpy docs." }, { "code": null, "e": 8002, "s": 7974, "text": "import numpy as npnp.std(a)" }, { "code": null, "e": 8096, "s": 8002, "text": "The are also some other measures of variation like range and interquartile distance.look here" }, { "code": null, "e": 8272, "s": 8096, "text": "Co variance: It shows how to two variables are linearly related to each other. Numpy outputs a covariance matrix where Cij denotes the covariance between xi and xj. numpy docs" }, { "code": null, "e": 8282, "s": 8272, "text": "np.cov(a)" }, { "code": null, "e": 8541, "s": 8282, "text": "As I mentioned in the beginning,several components of the neural networks are random variables.The values of the random variables are drawn from a probability distribution.In many cases,we use only certain types of probability distributions.Some of them are," }, { "code": null, "e": 8868, "s": 8541, "text": "Binomial distribution: A binomial random variable is the number of successes in n trials of a random experiment. A random variable x is said to follow binomial distribution when, the random variable can have only two outcomes(success and failure).Naturally , binomial distribution is for discrete random variables. numpy docs." }, { "code": null, "e": 8978, "s": 8868, "text": "import numpy as npn=10 # number of trialsp=0.5 # probability of successs=1000 # sizenp.random.binomial(n,p,s)" }, { "code": null, "e": 9169, "s": 8978, "text": "Continuous distributions: These are defined for continuous random variables.In continuous distribution, we describe the distribution using probability density functions(pdf) denoted by p(x)." }, { "code": null, "e": 9199, "s": 9169, "text": "Their integral is equal to 1." }, { "code": null, "e": 9276, "s": 9199, "text": "If you are not comfortable with integral or differential calculus look here," }, { "code": null, "e": 9422, "s": 9276, "text": "Uniform Distribution: It is the simplest form of continuous distribution, with every element of the sample space being equally likely. numpy docs" }, { "code": null, "e": 9483, "s": 9422, "text": "import numpy as npnp.random.uniform(low=1, high=10,size=100)" }, { "code": null, "e": 9523, "s": 9483, "text": "Normal distribution: “Order from Chaos”" }, { "code": null, "e": 9895, "s": 9523, "text": "It is the most important of all distributions.Also known as Gaussian distribution.In the absence of prior knowledge about what form a distribution over the real numbers should take, the normal distribution is a good choice because, it has high entropy and central limit theorem suggests that sum of several independent random variables is normally distributed. numpy docs" }, { "code": null, "e": 9964, "s": 9895, "text": "import numpy as npmu = 0sigma = 1np.random.normal(mu,sigma,size=100)" }, { "code": null, "e": 10091, "s": 9964, "text": "In a normal distribution, if the mean is 0 and the standard deviation is 1, then it is called as standard normal distribution." }, { "code": null, "e": 10432, "s": 10091, "text": "In machine learning, you often encounter the word ‘ normalization’ and ‘standardization’. the process which we did above to obtain standard normal distribution is called standardization whereas the process of restricting the range of dataset values between 0.0 to 1.0 is called as normalization. However, these terms are often interchanged." }, { "code": null, "e": 10578, "s": 10432, "text": "from sklearn.preprocessing import StandardScalerimport numpy as npdata = np.array([1,2,3,4,5])scaler = StandardScaler()scaler.fit_transform(data)" }, { "code": null, "e": 10848, "s": 10578, "text": "At this stage, we have come across several formulae and definitions. It is very useful if you memorize all these.(Or use this article as a reference! )There are also other important distributions like exponential and poisson distribution. refer here for a quick glance." }, { "code": null, "e": 11142, "s": 10848, "text": "Softmax distribution:In the beginning of this article, I mentioned about softmax. It is a probability distribution kinda.It is best used to represent 1 of N class categorical distribution. It is also the most commonly used distributions in deep learning.It is very convenient to differentiate." }, { "code": null, "e": 11293, "s": 11142, "text": "def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0)##the np.max(x) is used just for numerical stability.it is Not ##formula" }, { "code": null, "e": 11654, "s": 11293, "text": "In order to measure the performance of a deep learning model, we use several concepts. Knowing these concepts is very important.They are called as metrics.In the above MNIST neural network, if the neural network predicted 95 of the 100 input images correctly, then it’s accuracy is said to be 95% and so on.(This part uses sklearn python library for examples.)" }, { "code": null, "e": 11785, "s": 11654, "text": "You can understand accuracy intuitively, but the theory is,It is the proposition of correct results in the total obtained results." }, { "code": null, "e": 12000, "s": 11785, "text": "Accuracy is a very simple measurement and it may provide wrong insights sometimes.In some cases, higher accuracy doesn’t mean our model is working correctly.To clarify this, first look at the following definitions," }, { "code": null, "e": 12067, "s": 12000, "text": "True Positives (TP): number of positive examples, labeled as such." }, { "code": null, "e": 12139, "s": 12067, "text": "False Positives (FP): number of negative examples, labeled as positive." }, { "code": null, "e": 12206, "s": 12139, "text": "True Negatives (TN): number of negative examples, labeled as such." }, { "code": null, "e": 12278, "s": 12206, "text": "False Negatives (FN): number of positive examples, labeled as negative." }, { "code": null, "e": 12319, "s": 12278, "text": "Accuracy = (TP + TN)/(TP + FP + TN + FN)" }, { "code": null, "e": 12392, "s": 12319, "text": "Confusion matrix: It is a matrix containing the TP, FP,TN and FN values." }, { "code": null, "e": 12523, "s": 12392, "text": "from sklearn.metrics import confusion_matrixy_true = [2, 0, 2, 2, 0, 1]y_pred = [0, 0, 2, 2, 0, 2]confusion_matrix(y_true, y_pred)" }, { "code": null, "e": 12835, "s": 12523, "text": "Now, Imagine a binary classifier, that outputs 1 or 0. If everything was proper and the model was not biased, it says the actual accuracy.But if we tweak the model to say 0 all the time(or 1 all the time)(now the prediction power of the model is None).but still we would get a high accuracy! consider the table." }, { "code": null, "e": 12990, "s": 12835, "text": " Classified positive Classified negative Positive class 0 (TP) 25 (FN)Negative class 0 (FP) 125 (TN)" }, { "code": null, "e": 13134, "s": 12990, "text": "This table is obvious that the model is very bad(because all the positive class examples are incorrectly classified) but the accuracy is 83% !!" }, { "code": null, "e": 13209, "s": 13134, "text": "Precision and recall: So we go for two other metrics-precision and recall." }, { "code": null, "e": 13275, "s": 13209, "text": "Precision tells you how many of the selected objects were correct" }, { "code": null, "e": 13332, "s": 13275, "text": "Recall tells you how many correct objects were selected." }, { "code": null, "e": 13437, "s": 13332, "text": "In the above example, both precision and recall are 0.0 This indicates that the model is extremely poor." }, { "code": null, "e": 13499, "s": 13437, "text": "F1 score: It is the harmonic average of precision and recall." }, { "code": null, "e": 13614, "s": 13499, "text": "F1 score of 0 means worst and 1 means best.By using this, we can resolve the chaotic behaviour of accuracy metric." }, { "code": null, "e": 13719, "s": 13614, "text": "Sklearn has a classification_report function that you can invoke to get the precision, recall, f1 score." }, { "code": null, "e": 14327, "s": 13719, "text": ">>> from sklearn.metrics import classification_report>>> y_true = [0, 1, 2, 2, 2]>>> y_pred = [0, 0, 2, 2, 1]>>> target_names = ['class 0', 'class 1', 'class 2']>>> print(classification_report(y_true, y_pred, target_names=target_names)) precision recall f1-score support class 0 0.50 1.00 0.67 1 class 1 0.00 0.00 0.00 1 class 2 1.00 0.67 0.80 3 micro avg 0.60 0.60 0.60 5 macro avg 0.50 0.56 0.49 5weighted avg 0.70 0.60 0.61 5" }, { "code": null, "e": 14423, "s": 14327, "text": "Mean Absolute error: It is the average of difference between the original and predicted values." }, { "code": null, "e": 14528, "s": 14423, "text": "Mean squared error: it is the average of square of difference between the original and predicted values." }, { "code": null, "e": 14658, "s": 14528, "text": "from sklearn.metrics import mean_squared_errory_true = [3, -0.5, 2, 7]y_pred = [2.5, 0.0, 2, 8]mean_squared_error(y_true, y_pred)" }, { "code": null, "e": 14739, "s": 14658, "text": "Mean squared error is widely used because it is easier to compute the gradients." }, { "code": null, "e": 15057, "s": 14739, "text": "Receiver operating characteristic(ROC) curve:The roc curve is a graph showing the performance of classification models like our digit recognizer example.It has two parameters — True Positive rate(TPR) and False Positive rate(FPR).TPR is the same as recall and is also called as sensitivity. FPR is also 1-specificity." }, { "code": null, "e": 15312, "s": 15057, "text": "These two are plotted against each other to obtain the following graph(several values of plots are obtained by changing the classification threshold and predicting the results again repeatedly.).The area under this ROC curve is a measure of the accuracy." }, { "code": null, "e": 15524, "s": 15312, "text": "Interpretation of area under the curve(AUC):When AUC=1.0 the model is best.When AUC=0.5 the model is worst.But if AUC=0.0 then the model is reciprocating the results.(Like classifying 1's as 0’s and 0’s as 1's)." }, { "code": null, "e": 15688, "s": 15524, "text": "import numpy as npfrom sklearn.metrics import roc_auc_scorey_true = np.array([0, 0, 1, 1])y_scores = np.array([0.1, 0.4, 0.35, 0.8])roc_auc_score(y_true, y_scores)" }, { "code": null, "e": 15725, "s": 15688, "text": "More information:look here and here." }, { "code": null, "e": 15801, "s": 15725, "text": "Calculation of AUC using trapezoidal rule(sklearn uses this rule):look here" }, { "code": null, "e": 16153, "s": 15801, "text": "A random process is a collection of random variables that are indexed by some values.Intuitively, a random process or stochastic process is a mathematical model for a phenomenon that proceeds in an unpredictable manner to the observer.The outcome of the next event is not dependent on the outcome of the current event.Example, a series of coin tosses." }, { "code": null, "e": 16572, "s": 16153, "text": "If the index set by which the random variables are indexed in a random process are from a discrete natural numbers, then the process is called as discrete time random process or random sequence.If the index set lies in real number line, then the process is continuous time random process.If the index set lies in cartesian plane or some higher dimensional euclidean planes, then the process is said to be random field." }, { "code": null, "e": 16852, "s": 16572, "text": "Random processes are a really interesting part of probability.They are used to model time related stuffs like weather forecast, stock market, natural phenomenons,etc.There are several random processes.Here we focus on markov chains.For a more elaborate material, refer wikipedia." }, { "code": null, "e": 16867, "s": 16852, "text": "Markov chains:" }, { "code": null, "e": 17113, "s": 16867, "text": "A markov chain is a probabilistic automaton.It has states.It describes a sequence of events in which probability of transitioning from one state to another depends only on previous event. Here is an excellent visual explanation of markov chains." }, { "code": null, "e": 17251, "s": 17113, "text": "This is a markov chain that describes the weather condition.The values represent the probability of transition from one state to another." }, { "code": null, "e": 17382, "s": 17251, "text": "Markov chains are used for simple systems like next word prediction, language generation, sound generation and many other systems." }, { "code": null, "e": 17483, "s": 17382, "text": "The extension of markov chains known as hidden markov models are used in speech recognition systems." }, { "code": null, "e": 17618, "s": 17483, "text": "I have stopped random processes till here and planned for an extensive article on them because of the excessive length of the concept." }, { "code": null, "e": 17994, "s": 17618, "text": "A new paradigm of programming has evolved known as probabilistic programming.These languages or libraries help to model bayesian style machine learning.It is an exciting research field which is supported by both the AI community and the software engineering community.These languages readily support probabilistic functions and models like gaussian models,markov models, etc." }, { "code": null, "e": 18166, "s": 17994, "text": "One such library for writing probabilistic programs was created by Uber last year known as pyro which supports python with pytorch(a deep learning library) as the backend." }, { "code": null, "e": 18671, "s": 18166, "text": "If you liked this article about probability and statistics for deep learning, leave claps for the article. The content provided here are intended for beginners in deep learning and can also be used as reference material by deep learning practitioners. But for beginners, I would also suggest several other awesome external resources, to reinforce their knowledge in the interesting field of probability.(Though the knowledge that you gained through this article is enough for proceeding in deep learning)" }, { "code": null, "e": 18738, "s": 18671, "text": "Awesome free course on deep learning and machine learning: fast.ai" }, { "code": null, "e": 18785, "s": 18738, "text": "Intuitive explanation of calculus: 3blue1brown" }, { "code": null, "e": 18836, "s": 18785, "text": "Best book on deep learning: the deep learning book" }, { "code": null, "e": 18868, "s": 18836, "text": "Random process: Sheldon M. Ross" }, { "code": null, "e": 18917, "s": 18868, "text": "Statistics: All of statistics by Larry Wasserman" } ]
C# Linq Intersect Method
Find common elements between two arrays using the Intersect() method. The following are our arrays − int[] val1 = { 15, 20, 40, 60, 75, 90 }; int[] val2 = { 17, 25, 35, 55, 75, 90 }; To perform intersection. val1.AsQueryable().Intersect(val2); Let us see the entire example. Live Demo using System; using System.Collections.Generic; using System.Linq; class Demo { static void Main() { int[] val1 = { 15, 20, 40, 60, 75, 90 }; int[] val2 = { 17, 25, 35, 55, 75, 90 }; IEnumerable<int> res = val1.AsQueryable().Intersect(val2); Console.WriteLine("Intersection of both the lists..."); foreach (int a in res) Console.WriteLine(a); } } Intersection of both the lists... 75 90
[ { "code": null, "e": 1132, "s": 1062, "text": "Find common elements between two arrays using the Intersect() method." }, { "code": null, "e": 1163, "s": 1132, "text": "The following are our arrays −" }, { "code": null, "e": 1245, "s": 1163, "text": "int[] val1 = { 15, 20, 40, 60, 75, 90 };\nint[] val2 = { 17, 25, 35, 55, 75, 90 };" }, { "code": null, "e": 1270, "s": 1245, "text": "To perform intersection." }, { "code": null, "e": 1306, "s": 1270, "text": "val1.AsQueryable().Intersect(val2);" }, { "code": null, "e": 1337, "s": 1306, "text": "Let us see the entire example." }, { "code": null, "e": 1348, "s": 1337, "text": " Live Demo" }, { "code": null, "e": 1737, "s": 1348, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nclass Demo {\n static void Main() {\n int[] val1 = { 15, 20, 40, 60, 75, 90 };\n int[] val2 = { 17, 25, 35, 55, 75, 90 };\n IEnumerable<int> res = val1.AsQueryable().Intersect(val2);\n Console.WriteLine(\"Intersection of both the lists...\");\n foreach (int a in res)\n Console.WriteLine(a);\n }\n}" }, { "code": null, "e": 1777, "s": 1737, "text": "Intersection of both the lists...\n75\n90" } ]
Check given matrix is magic square or not - GeeksforGeeks
10 Jun, 2021 Given a matrix, check whether it’s Magic Square or not. A Magic Square is a n x n matrix of the distinct elements from 1 to n2 where the sum of any row, column, or diagonal is always equal to the same number.Examples: Input : n = 3 2 7 6 9 5 1 4 3 8 Output : Magic matrix Explanation:In matrix sum of each row and each column and diagonals sum is same = 15. Input : n = 3 1 2 2 2 2 1 2 1 2 Output : Not a Magic Matrix Explanation:In matrix sum of each row and each column and diagonals sum is not same. 1. Find the sum of prime diagonal and secondary diagonal. 2. Calculate the sum of each row and column. 3. If the prime diagonal and secondary diagonal sums are equal to every row’s sum and every column’s sum, then it is the magic matrix. C++ Java Python3 C# PHP Javascript // C++ program to check whether a given// matrix is magic matrix or not#include <bits/stdc++.h> # define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))using namespace std; // Returns true if mat[][] is magic// square, else returns false.bool isMagicSquare(int mat[][3]){ int n = my_sizeof(mat)/my_sizeof(mat[0]); // calculate the sum of // the prime diagonal int i=0,j=0; // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0, sumd2=0; for (i = 0; i < n; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1 += mat[i][i]; sumd2 += mat[i][n-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // For sums of Rows for (i = 0; i < n; i++) { int rowSum = 0, colSum = 0; for (j = 0; j < n; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true;} // driver program to// test above functionint main(){ int mat[3][3] = {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) cout << "Magic Square"; else cout << "Not a magic Square"; return 0;} // JAVA program to check whether a given// matrix is magic matrix or not import java.io.*; class GFG { static int N = 3; // Returns true if mat[][] is magic // square, else returns false. static boolean isMagicSquare(int mat[][]) { // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0,sumd2=0; for (int i = 0; i < N; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, N - i - 1) is the diagonal from top-right -> bottom-left sumd1 += mat[i][i]; sumd2 += mat[i][N-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // calculating sums of Rows and columns and checking if they are equal to each other, // as well as equal to diagonal sum or not for (int i = 0; i < N; i++) { int rowSum = 0, colSum = 0; for (int j = 0; j < N; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true; } // driver program to // test above function public static void main(String[] args) { int mat[][] = {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) System.out.println("Magic Square"); else System.out.println("Not a magic" + " Square"); }} # Python3 program to check whether a given# matrix is magic matrix or not# Returns true if mat[][] is magic# square, else returns false.def isMagicSquare( mat) : n = len(mat) # sumd1 and sumd2 are the sum of the two diagonals sumd1=0 sumd2=0 for i in range(n): # (i, i) is the diagonal from top-left -> bottom-right # (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1+=mat[i][i] sumd2+=mat[i][n-i-1] # if the two diagonal sums are unequal then it is not a magic square if not(sumd1==sumd2): return False for i in range(n): #sumr is rowsum and sumc is colsum sumr=0 sumc=0 for j in range(n): sumr+=mat[i][j] sumc+=mat[j][i] if not(sumr==sumc==sumd1): return False #if all the conditions are satisfied then it is a magic square return True # Driver Codemat = [ [ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ] ] if (isMagicSquare(mat)) : print( "Magic Square")else : print( "Not a magic Square") // C# program to check whether a given// matrix is magic matrix or notusing System; class GFG{ static int N = 3; // Returns true if mat[][] is magic // square, else returns false. static bool isMagicSquare(int[,] mat) { // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0, sumd2 = 0; for (int i = 0; i < N; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, N - i - 1) is the diagonal from top-right -> bottom-left sumd1 = sumd1 + mat[i, i]; sumd2 = sumd2 + mat[i, N-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // For sums of Rows for (int i = 0; i < N; i++) { int rowSum = 0, colSum = 0; for (int j = 0; j < N; j++) { rowSum += mat[i, j]; colSum += mat[j,i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true; } // Driver Code public static void Main() { int[,] mat =new int [,] {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) Console.WriteLine("Magic Square"); else Console.WriteLine("Not a magic" + " Square"); }} <?php// PHP program to check whether a given// matrix is magic matrix or not // Returns true if mat[][] is magic// square, else returns false.function isMagicSquare($mat){ // sumd1 and sumd2 are the sum of the two diagonals $sumd1 = 0; $sumd2 = 0; $N= count($mat); for($i = 0; $i < $N; $i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, N - i - 1) is the diagonal from top-right -> bottom-left $sumd1 = $sumd1 + $mat[$i][$i]; $sumd2 = $sumd2 + $mat[$i][$N-$i-1]; } // if the two diagonal sums are unequal then it is not a magic square if( $sumd1 != $sumd2) return false; for($i = 0; $i < $N; $i++) { $rowSum = 0; $colSum = 0; for ($j = 0; $j < $N; $j++) { $rowSum += $mat[$i][$j]; $colSum += $mat[$j][$i]; } if ($rowSum != $colSum || $colSum != $sumd1) return false; } return true;} // Driver Code{ $mat = array(array(2, 7, 6), array(9, 5, 1), array(4, 3, 8)); if (isMagicSquare($mat)) echo "Magic Square"; else echo "Not a magic Square"; return 0;} ?> <script> // Javascript program to check whether a given// matrix is magic matrix or not // Returns true if mat[][] is magic// square, else returns false.function isMagicSquare(mat){ var N = mat.length // sumd1 and sumd2 are the sum of the two diagonals var sumd1 = 0,sumd2=0; for (var i = 0; i < N; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, N - i - 1) is the diagonal from top-right -> bottom-left sumd1 = sumd1 + mat[i][i]; sumd2 = sumd2 + mat[i][N-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; for (var i = 0; i < N; i++) { var colSum = 0; var rowSum = 0; for (var j = 0; j < N; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true;} // driver program to// test above functionvar mat = [[ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ]]; if (isMagicSquare(mat)) document.write( "Magic Square");else document.write( "Not a magic Square"); </script> Magic Square KRV nitin mittal letMe_Do noob2000 SHRIYAPANDEY Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 The Celebrity Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space Count all possible paths from top left to bottom right of a mXn matrix Maximum size rectangle binary sub-matrix with all 1s Python program to multiply two matrices
[ { "code": null, "e": 24624, "s": 24596, "text": "\n10 Jun, 2021" }, { "code": null, "e": 24844, "s": 24624, "text": "Given a matrix, check whether it’s Magic Square or not. A Magic Square is a n x n matrix of the distinct elements from 1 to n2 where the sum of any row, column, or diagonal is always equal to the same number.Examples: " }, { "code": null, "e": 25168, "s": 24844, "text": "Input : n = 3\n 2 7 6\n 9 5 1\n 4 3 8\nOutput : Magic matrix\nExplanation:In matrix sum of each\nrow and each column and diagonals sum is \nsame = 15.\n\nInput : n = 3\n 1 2 2 \n 2 2 1\n 2 1 2\nOutput : Not a Magic Matrix\nExplanation:In matrix sum of each\nrow and each column and diagonals sum is\nnot same." }, { "code": null, "e": 25409, "s": 25170, "text": "1. Find the sum of prime diagonal and secondary diagonal. 2. Calculate the sum of each row and column. 3. If the prime diagonal and secondary diagonal sums are equal to every row’s sum and every column’s sum, then it is the magic matrix. " }, { "code": null, "e": 25413, "s": 25409, "text": "C++" }, { "code": null, "e": 25418, "s": 25413, "text": "Java" }, { "code": null, "e": 25426, "s": 25418, "text": "Python3" }, { "code": null, "e": 25429, "s": 25426, "text": "C#" }, { "code": null, "e": 25433, "s": 25429, "text": "PHP" }, { "code": null, "e": 25444, "s": 25433, "text": "Javascript" }, { "code": "// C++ program to check whether a given// matrix is magic matrix or not#include <bits/stdc++.h> # define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))using namespace std; // Returns true if mat[][] is magic// square, else returns false.bool isMagicSquare(int mat[][3]){ int n = my_sizeof(mat)/my_sizeof(mat[0]); // calculate the sum of // the prime diagonal int i=0,j=0; // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0, sumd2=0; for (i = 0; i < n; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1 += mat[i][i]; sumd2 += mat[i][n-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // For sums of Rows for (i = 0; i < n; i++) { int rowSum = 0, colSum = 0; for (j = 0; j < n; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true;} // driver program to// test above functionint main(){ int mat[3][3] = {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) cout << \"Magic Square\"; else cout << \"Not a magic Square\"; return 0;}", "e": 26843, "s": 25444, "text": null }, { "code": "// JAVA program to check whether a given// matrix is magic matrix or not import java.io.*; class GFG { static int N = 3; // Returns true if mat[][] is magic // square, else returns false. static boolean isMagicSquare(int mat[][]) { // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0,sumd2=0; for (int i = 0; i < N; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, N - i - 1) is the diagonal from top-right -> bottom-left sumd1 += mat[i][i]; sumd2 += mat[i][N-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // calculating sums of Rows and columns and checking if they are equal to each other, // as well as equal to diagonal sum or not for (int i = 0; i < N; i++) { int rowSum = 0, colSum = 0; for (int j = 0; j < N; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true; } // driver program to // test above function public static void main(String[] args) { int mat[][] = {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) System.out.println(\"Magic Square\"); else System.out.println(\"Not a magic\" + \" Square\"); }}", "e": 28456, "s": 26843, "text": null }, { "code": "# Python3 program to check whether a given# matrix is magic matrix or not# Returns true if mat[][] is magic# square, else returns false.def isMagicSquare( mat) : n = len(mat) # sumd1 and sumd2 are the sum of the two diagonals sumd1=0 sumd2=0 for i in range(n): # (i, i) is the diagonal from top-left -> bottom-right # (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1+=mat[i][i] sumd2+=mat[i][n-i-1] # if the two diagonal sums are unequal then it is not a magic square if not(sumd1==sumd2): return False for i in range(n): #sumr is rowsum and sumc is colsum sumr=0 sumc=0 for j in range(n): sumr+=mat[i][j] sumc+=mat[j][i] if not(sumr==sumc==sumd1): return False #if all the conditions are satisfied then it is a magic square return True # Driver Codemat = [ [ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ] ] if (isMagicSquare(mat)) : print( \"Magic Square\")else : print( \"Not a magic Square\") ", "e": 29475, "s": 28456, "text": null }, { "code": "// C# program to check whether a given// matrix is magic matrix or notusing System; class GFG{ static int N = 3; // Returns true if mat[][] is magic // square, else returns false. static bool isMagicSquare(int[,] mat) { // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0, sumd2 = 0; for (int i = 0; i < N; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, N - i - 1) is the diagonal from top-right -> bottom-left sumd1 = sumd1 + mat[i, i]; sumd2 = sumd2 + mat[i, N-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // For sums of Rows for (int i = 0; i < N; i++) { int rowSum = 0, colSum = 0; for (int j = 0; j < N; j++) { rowSum += mat[i, j]; colSum += mat[j,i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true; } // Driver Code public static void Main() { int[,] mat =new int [,] {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) Console.WriteLine(\"Magic Square\"); else Console.WriteLine(\"Not a magic\" + \" Square\"); }}", "e": 30969, "s": 29475, "text": null }, { "code": "<?php// PHP program to check whether a given// matrix is magic matrix or not // Returns true if mat[][] is magic// square, else returns false.function isMagicSquare($mat){ // sumd1 and sumd2 are the sum of the two diagonals $sumd1 = 0; $sumd2 = 0; $N= count($mat); for($i = 0; $i < $N; $i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, N - i - 1) is the diagonal from top-right -> bottom-left $sumd1 = $sumd1 + $mat[$i][$i]; $sumd2 = $sumd2 + $mat[$i][$N-$i-1]; } // if the two diagonal sums are unequal then it is not a magic square if( $sumd1 != $sumd2) return false; for($i = 0; $i < $N; $i++) { $rowSum = 0; $colSum = 0; for ($j = 0; $j < $N; $j++) { $rowSum += $mat[$i][$j]; $colSum += $mat[$j][$i]; } if ($rowSum != $colSum || $colSum != $sumd1) return false; } return true;} // Driver Code{ $mat = array(array(2, 7, 6), array(9, 5, 1), array(4, 3, 8)); if (isMagicSquare($mat)) echo \"Magic Square\"; else echo \"Not a magic Square\"; return 0;} ?>", "e": 32181, "s": 30969, "text": null }, { "code": "<script> // Javascript program to check whether a given// matrix is magic matrix or not // Returns true if mat[][] is magic// square, else returns false.function isMagicSquare(mat){ var N = mat.length // sumd1 and sumd2 are the sum of the two diagonals var sumd1 = 0,sumd2=0; for (var i = 0; i < N; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, N - i - 1) is the diagonal from top-right -> bottom-left sumd1 = sumd1 + mat[i][i]; sumd2 = sumd2 + mat[i][N-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; for (var i = 0; i < N; i++) { var colSum = 0; var rowSum = 0; for (var j = 0; j < N; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true;} // driver program to// test above functionvar mat = [[ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ]]; if (isMagicSquare(mat)) document.write( \"Magic Square\");else document.write( \"Not a magic Square\"); </script>", "e": 33358, "s": 32181, "text": null }, { "code": null, "e": 33371, "s": 33358, "text": "Magic Square" }, { "code": null, "e": 33375, "s": 33371, "text": "KRV" }, { "code": null, "e": 33388, "s": 33375, "text": "nitin mittal" }, { "code": null, "e": 33397, "s": 33388, "text": "letMe_Do" }, { "code": null, "e": 33406, "s": 33397, "text": "noob2000" }, { "code": null, "e": 33419, "s": 33406, "text": "SHRIYAPANDEY" }, { "code": null, "e": 33426, "s": 33419, "text": "Matrix" }, { "code": null, "e": 33433, "s": 33426, "text": "Matrix" }, { "code": null, "e": 33531, "s": 33433, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33540, "s": 33531, "text": "Comments" }, { "code": null, "e": 33553, "s": 33540, "text": "Old Comments" }, { "code": null, "e": 33577, "s": 33553, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 33639, "s": 33577, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 33672, "s": 33639, "text": "Program to multiply two matrices" }, { "code": null, "e": 33723, "s": 33672, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 33744, "s": 33723, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 33766, "s": 33744, "text": "The Celebrity Problem" }, { "code": null, "e": 33848, "s": 33766, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 33919, "s": 33848, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 33972, "s": 33919, "text": "Maximum size rectangle binary sub-matrix with all 1s" } ]
How to print date in a regular format in Python?
If you print the dates directly using a print function, you'd get regular dates, import datetime today = datetime.date.today() print(today) You will get the output − 2018-1-2 which is exactly what you want. But when you append this to a list and then try to print it, import datetime my_list = [] today = datetime.date.today() my_list.append(today) print(my_list) You will get the output − [datetime.date(2018, 1, 2)] This is happening because datetimes are objects. Therefore, when you manipulate them, you manipulate objects, not strings, not timestamps nor anything. Any object in Python have TWO string representations. The regular representation that is used by "print", can be get using the str() function. This one is implemented using the __str__ function in the class for that object. The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function. So in order to get the correct representation, you need to call str explicitly on your datetime objects. import datetime my_list = [] today = datetime.date.today() my_list.append(str(today)) print(my_list) You will get the output − ['2018-01-02']
[ { "code": null, "e": 1144, "s": 1062, "text": "If you print the dates directly using a print function, you'd get regular dates, " }, { "code": null, "e": 1203, "s": 1144, "text": "import datetime\ntoday = datetime.date.today()\nprint(today)" }, { "code": null, "e": 1229, "s": 1203, "text": "You will get the output −" }, { "code": null, "e": 1238, "s": 1229, "text": "2018-1-2" }, { "code": null, "e": 1332, "s": 1238, "text": "which is exactly what you want. But when you append this to a list and then try to print it, " }, { "code": null, "e": 1428, "s": 1332, "text": "import datetime\nmy_list = []\ntoday = datetime.date.today()\nmy_list.append(today)\nprint(my_list)" }, { "code": null, "e": 1454, "s": 1428, "text": "You will get the output −" }, { "code": null, "e": 1482, "s": 1454, "text": "[datetime.date(2018, 1, 2)]" }, { "code": null, "e": 1987, "s": 1482, "text": "This is happening because datetimes are objects. Therefore, when you manipulate them, you manipulate objects, not strings, not timestamps nor anything. Any object in Python have TWO string representations. The regular representation that is used by \"print\", can be get using the str() function. This one is implemented using the __str__ function in the class for that object. The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function." }, { "code": null, "e": 2093, "s": 1987, "text": "So in order to get the correct representation, you need to call str explicitly on your datetime objects. " }, { "code": null, "e": 2194, "s": 2093, "text": "import datetime\nmy_list = []\ntoday = datetime.date.today()\nmy_list.append(str(today))\nprint(my_list)" }, { "code": null, "e": 2220, "s": 2194, "text": "You will get the output −" }, { "code": null, "e": 2235, "s": 2220, "text": "['2018-01-02']" } ]
Declaring a Fallback Color in CSS
Fallback color is used to specify the color for a situation when the browser doesn’t support RGBA colors. Some browsers that doesn’t support fallback colors are opera 9 and below, IE 8 and below etc. Specify a solid color before a RGBA color so the solid color can still work if the browser doesn’t support the RGBA colors. Following is the code for declaring a fallback color in CSS − Live Demo <!DOCTYPE html> <html> <head> <style> body{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } div { padding:20px; font-size: 24px; background-color: purple; /*fallback color*/ background-color: rgba(128, 0, 128, 0.527); color:white; } </style> </head> <body> <h1>Fallback color example</h1> <div>Some random text inside this div</div> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1386, "s": 1062, "text": "Fallback color is used to specify the color for a situation when the browser doesn’t support RGBA colors. Some browsers that doesn’t support fallback colors are opera 9 and below, IE 8 and below etc. Specify a solid color before a RGBA color so the solid color can still work if the browser doesn’t support the RGBA colors." }, { "code": null, "e": 1448, "s": 1386, "text": "Following is the code for declaring a fallback color in CSS −" }, { "code": null, "e": 1459, "s": 1448, "text": " Live Demo" }, { "code": null, "e": 1842, "s": 1459, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody{\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n}\ndiv {\n padding:20px;\n font-size: 24px;\n background-color: purple; /*fallback color*/\n background-color: rgba(128, 0, 128, 0.527);\n color:white;\n}\n</style>\n</head>\n<body>\n<h1>Fallback color example</h1>\n<div>Some random text inside this div</div>\n</body>\n</html>" }, { "code": null, "e": 1893, "s": 1842, "text": "The above code will produce the following output −" } ]
Boruvka's algorithm | Greedy Algo-9 - GeeksforGeeks
25 Feb, 2022 We have discussed following topics on Minimum Spanning Tree.Applications of Minimum Spanning Tree Problem Kruskal’s Minimum Spanning Tree Algorithm Prim’s Minimum Spanning Tree AlgorithmIn this post, Boruvka’s algorithm is discussed. Like Prim’s and Kruskal’s, Boruvka’s algorithm is also a Greedy algorithm. Below is complete algorithm. 1) Input is a connected, weighted and un-directed graph. 2) Initialize all vertices as individual components (or sets). 3) Initialize MST as empty. 4) While there are more than one components, do following for each component. a) Find the closest weight edge that connects this component to any other component. b) Add this closest edge to MST if not already added. 5) Return MST. Below is the idea behind above algorithm (The idea is same as Prim’s MST algorithm). A spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a Spanning Tree. And they must be connected with the minimum weight edge to make it a Minimum Spanning Tree.Let us understand the algorithm with below example. Initially MST is empty. Every vertex is singe component as highlighted in blue color in below diagram. For every component, find the cheapest edge that connects it to some other component. Component Cheapest Edge that connects it to some other component {0} 0-1 {1} 0-1 {2} 2-8 {3} 2-3 {4} 3-4 {5} 5-6 {6} 6-7 {7} 6-7 {8} 2-8 The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4, 5-6, 6-7}. After above step, components are {{0,1}, {2,3,4,8}, {5,6,7}}. The components are encircled with blue color. We again repeat the step, i.e., for every component, find the cheapest edge that connects it to some other component. Component Cheapest Edge that connects it to some other component {0,1} 1-2 (or 0-7) {2,3,4,8} 2-5 {5,6,7} 2-5 The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4, 5-6, 6-7, 1-2, 2-5} At this stage, there is only one component {0, 1, 2, 3, 4, 5, 6, 7, 8} which has all edges. Since there is only one component left, we stop and return MST.Implementation: Below is implementation of above algorithm. The input graph is represented as a collection of edges and union-find data structure is used to keep track of components. C/C++ Python # Boruvka's algorithm to find Minimum Spanning# Tree of a given connected, undirected and weighted graph from collections import defaultdict #Class to represent a graphclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = [] # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v,w): self.graph.append([u,v,w]) # A utility function to find set of an element i # (uses path compression technique) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) # A function that does union of two sets of x and y # (uses union by rank) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) # Attach smaller rank tree under root of high rank tree # (Union by Rank) if rank[xroot] < rank[yroot]: parent[xroot] = yroot else if rank[xroot] > rank[yroot]: parent[yroot] = xroot #If ranks are same, then make one as root and increment # its rank by one else : parent[yroot] = xroot rank[xroot] += 1 # The main function to construct MST using Kruskal's algorithm def boruvkaMST(self): parent = []; rank = []; # An array to store index of the cheapest edge of # subset. It store [u,v,w] for each component cheapest =[] # Initially there are V different trees. # Finally there will be one tree that will be MST numTrees = self.V MSTweight = 0 # Create V subsets with single elements for node in range(self.V): parent.append(node) rank.append(0) cheapest =[-1] * self.V # Keep combining components (or sets) until all # components are not combined into single MST while numTrees > 1: # Traverse through all edges and update # cheapest of every component for i in range(len(self.graph)): # Find components (or sets) of two corners # of current edge u,v,w = self.graph[i] set1 = self.find(parent, u) set2 = self.find(parent ,v) # If two corners of current edge belong to # same set, ignore current edge. Else check if # current edge is closer to previous # cheapest edges of set1 and set2 if set1 != set2: if cheapest[set1] == -1 or cheapest[set1][2] > w : cheapest[set1] = [u,v,w] if cheapest[set2] == -1 or cheapest[set2][2] > w : cheapest[set2] = [u,v,w] # Consider the above picked cheapest edges and add them # to MST for node in range(self.V): #Check if cheapest for current set exists if cheapest[node] != -1: u,v,w = cheapest[node] set1 = self.find(parent, u) set2 = self.find(parent ,v) if set1 != set2 : MSTweight += w self.union(parent, rank, set1, set2) print ("Edge %d-%d with weight %d included in MST" % (u,v,w)) numTrees = numTrees - 1 #reset cheapest array cheapest =[-1] * self.V print ("Weight of MST is %d" % MSTweight) g = Graph(4)g.addEdge(0, 1, 10)g.addEdge(0, 2, 6)g.addEdge(0, 3, 5)g.addEdge(1, 3, 15)g.addEdge(2, 3, 4) g.boruvkaMST() #This code is contributed by Neelam Yadav Output: Edge 0-3 included in MST Edge 0-1 included in MST Edge 2-3 included in MST Weight of MST is 19 Interesting Facts about Boruvka’s algorithm: 1) Time Complexity of Boruvka’s algorithm is O(E log V) which is same as Kruskal’s and Prim’s algorithms.2) Boruvka’s algorithm is used as a step in a faster randomized algorithm that works in linear time O(E).3) Boruvka’s algorithm is the oldest minimum spanning tree algorithm was discovered by Boruuvka in 1926, long before computers even existed. The algorithm was published as a method of constructing an efficient electricity network.Exercise: The above code assumes that input graph is connected and it fails if a disconnected graph is given. Extend the above algorithm so that it works for a disconnected graph also and produces a forest.References: http://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithmPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Cyberfreak Anirudh Agrawal simranarora5sos surinderdawra388 MST Graph Greedy Greedy Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Detect Cycle in a Directed Graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Program for array rotation Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string Coin Change | DP-7 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
[ { "code": null, "e": 25334, "s": 25306, "text": "\n25 Feb, 2022" }, { "code": null, "e": 25673, "s": 25334, "text": "We have discussed following topics on Minimum Spanning Tree.Applications of Minimum Spanning Tree Problem Kruskal’s Minimum Spanning Tree Algorithm Prim’s Minimum Spanning Tree AlgorithmIn this post, Boruvka’s algorithm is discussed. Like Prim’s and Kruskal’s, Boruvka’s algorithm is also a Greedy algorithm. Below is complete algorithm. " }, { "code": null, "e": 26083, "s": 25673, "text": "1) Input is a connected, weighted and un-directed graph.\n2) Initialize all vertices as individual components (or sets).\n3) Initialize MST as empty.\n4) While there are more than one components, do following\n for each component.\n a) Find the closest weight edge that connects this \n component to any other component.\n b) Add this closest edge to MST if not already added. \n5) Return MST." }, { "code": null, "e": 26468, "s": 26083, "text": "Below is the idea behind above algorithm (The idea is same as Prim’s MST algorithm). A spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a Spanning Tree. And they must be connected with the minimum weight edge to make it a Minimum Spanning Tree.Let us understand the algorithm with below example. " }, { "code": null, "e": 26573, "s": 26468, "text": "Initially MST is empty. Every vertex is singe component as highlighted in blue color in below diagram. " }, { "code": null, "e": 26662, "s": 26573, "text": " For every component, find the cheapest edge that connects it to some other component. " }, { "code": null, "e": 27093, "s": 26662, "text": "Component Cheapest Edge that connects \n it to some other component\n {0} 0-1\n {1} 0-1\n {2} 2-8\n {3} 2-3\n {4} 3-4\n {5} 5-6\n {6} 6-7\n {7} 6-7\n {8} 2-8 " }, { "code": null, "e": 27196, "s": 27093, "text": "The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4, 5-6, 6-7}. " }, { "code": null, "e": 27306, "s": 27196, "text": "After above step, components are {{0,1}, {2,3,4,8}, {5,6,7}}. The components are encircled with blue color. " }, { "code": null, "e": 27426, "s": 27306, "text": " We again repeat the step, i.e., for every component, find the cheapest edge that connects it to some other component." }, { "code": null, "e": 27646, "s": 27426, "text": "Component Cheapest Edge that connects \n it to some other component\n {0,1} 1-2 (or 0-7)\n {2,3,4,8} 2-5\n {5,6,7} 2-5" }, { "code": null, "e": 27758, "s": 27646, "text": "The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4, 5-6, 6-7, 1-2, 2-5} " }, { "code": null, "e": 28098, "s": 27758, "text": "At this stage, there is only one component {0, 1, 2, 3, 4, 5, 6, 7, 8} which has all edges. Since there is only one component left, we stop and return MST.Implementation: Below is implementation of above algorithm. The input graph is represented as a collection of edges and union-find data structure is used to keep track of components. " }, { "code": null, "e": 28104, "s": 28098, "text": "C/C++" }, { "code": null, "e": 28115, "s": 28108, "text": "Python" }, { "code": "# Boruvka's algorithm to find Minimum Spanning# Tree of a given connected, undirected and weighted graph from collections import defaultdict #Class to represent a graphclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = [] # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v,w): self.graph.append([u,v,w]) # A utility function to find set of an element i # (uses path compression technique) def find(self, parent, i): if parent[i] == i: return i return self.find(parent, parent[i]) # A function that does union of two sets of x and y # (uses union by rank) def union(self, parent, rank, x, y): xroot = self.find(parent, x) yroot = self.find(parent, y) # Attach smaller rank tree under root of high rank tree # (Union by Rank) if rank[xroot] < rank[yroot]: parent[xroot] = yroot else if rank[xroot] > rank[yroot]: parent[yroot] = xroot #If ranks are same, then make one as root and increment # its rank by one else : parent[yroot] = xroot rank[xroot] += 1 # The main function to construct MST using Kruskal's algorithm def boruvkaMST(self): parent = []; rank = []; # An array to store index of the cheapest edge of # subset. It store [u,v,w] for each component cheapest =[] # Initially there are V different trees. # Finally there will be one tree that will be MST numTrees = self.V MSTweight = 0 # Create V subsets with single elements for node in range(self.V): parent.append(node) rank.append(0) cheapest =[-1] * self.V # Keep combining components (or sets) until all # components are not combined into single MST while numTrees > 1: # Traverse through all edges and update # cheapest of every component for i in range(len(self.graph)): # Find components (or sets) of two corners # of current edge u,v,w = self.graph[i] set1 = self.find(parent, u) set2 = self.find(parent ,v) # If two corners of current edge belong to # same set, ignore current edge. Else check if # current edge is closer to previous # cheapest edges of set1 and set2 if set1 != set2: if cheapest[set1] == -1 or cheapest[set1][2] > w : cheapest[set1] = [u,v,w] if cheapest[set2] == -1 or cheapest[set2][2] > w : cheapest[set2] = [u,v,w] # Consider the above picked cheapest edges and add them # to MST for node in range(self.V): #Check if cheapest for current set exists if cheapest[node] != -1: u,v,w = cheapest[node] set1 = self.find(parent, u) set2 = self.find(parent ,v) if set1 != set2 : MSTweight += w self.union(parent, rank, set1, set2) print (\"Edge %d-%d with weight %d included in MST\" % (u,v,w)) numTrees = numTrees - 1 #reset cheapest array cheapest =[-1] * self.V print (\"Weight of MST is %d\" % MSTweight) g = Graph(4)g.addEdge(0, 1, 10)g.addEdge(0, 2, 6)g.addEdge(0, 3, 5)g.addEdge(1, 3, 15)g.addEdge(2, 3, 4) g.boruvkaMST() #This code is contributed by Neelam Yadav", "e": 31901, "s": 28115, "text": null }, { "code": null, "e": 31910, "s": 31901, "text": "Output: " }, { "code": null, "e": 32005, "s": 31910, "text": "Edge 0-3 included in MST\nEdge 0-1 included in MST\nEdge 2-3 included in MST\nWeight of MST is 19" }, { "code": null, "e": 32888, "s": 32005, "text": "Interesting Facts about Boruvka’s algorithm: 1) Time Complexity of Boruvka’s algorithm is O(E log V) which is same as Kruskal’s and Prim’s algorithms.2) Boruvka’s algorithm is used as a step in a faster randomized algorithm that works in linear time O(E).3) Boruvka’s algorithm is the oldest minimum spanning tree algorithm was discovered by Boruuvka in 1926, long before computers even existed. The algorithm was published as a method of constructing an efficient electricity network.Exercise: The above code assumes that input graph is connected and it fails if a disconnected graph is given. Extend the above algorithm so that it works for a disconnected graph also and produces a forest.References: http://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithmPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 32899, "s": 32888, "text": "Cyberfreak" }, { "code": null, "e": 32915, "s": 32899, "text": "Anirudh Agrawal" }, { "code": null, "e": 32931, "s": 32915, "text": "simranarora5sos" }, { "code": null, "e": 32948, "s": 32931, "text": "surinderdawra388" }, { "code": null, "e": 32952, "s": 32948, "text": "MST" }, { "code": null, "e": 32958, "s": 32952, "text": "Graph" }, { "code": null, "e": 32965, "s": 32958, "text": "Greedy" }, { "code": null, "e": 32972, "s": 32965, "text": "Greedy" }, { "code": null, "e": 32978, "s": 32972, "text": "Graph" }, { "code": null, "e": 33076, "s": 32978, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33096, "s": 33076, "text": "Topological Sorting" }, { "code": null, "e": 33127, "s": 33096, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 33160, "s": 33127, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 33193, "s": 33160, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 33261, "s": 33193, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 33288, "s": 33261, "text": "Program for array rotation" }, { "code": null, "e": 33319, "s": 33288, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 33379, "s": 33319, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33398, "s": 33379, "text": "Coin Change | DP-7" } ]
Associative arrays in C++
In c++ programming language, an associative array is a special type of array in which the index value can be of any data type i.e. it can be char, float, string, etc. These associative arrays are also known as maps or dictionaries. Also, the indexes are given a different name which is key and the data that is stored at the position of the key is value. So, we can define the associative array as a key-value pair. Let's define an associative array of bikes and their top speed. Bike top speed Ninja 290 S1000rr 310 Bullet 127 Duke 135 R1 286 Live Demo #include <bits/stdc++.h> using namespace std; int main(){ map<string, int> speed{ { "ninja", 290 }, { "s1000rr", 310 }, { "bullet", 127 }, { "Duke", 135 }, { "R1", 286 } }; map<string, int>::iterator i; cout << "The topspeed of bikes are" << endl; for (i = speed.begin(); i != speed.end(); i++) cout<<i->first<<" "<<i->second <<endl; cout << endl; cout << "The top speed of bullet is "<< speed["bullet"] << endl; } The topspeed of bikes are Duke 135 R1 286 Bullet 127 ninja 290 s1000rr 310 The top speed of bullet is 127
[ { "code": null, "e": 1417, "s": 1062, "text": "In c++ programming language, an associative array is a special type of array in which the index value can be of any data type i.e. it can be char, float, string, etc. These associative arrays are also known as maps or dictionaries. Also, the indexes are given a different name which is key and the data that is stored at the position of the key is value." }, { "code": null, "e": 1478, "s": 1417, "text": "So, we can define the associative array as a key-value pair." }, { "code": null, "e": 1542, "s": 1478, "text": "Let's define an associative array of bikes and their top speed." }, { "code": null, "e": 1606, "s": 1542, "text": "Bike top speed\nNinja 290\nS1000rr 310\nBullet 127\nDuke 135\nR1 286" }, { "code": null, "e": 1617, "s": 1606, "text": " Live Demo" }, { "code": null, "e": 2059, "s": 1617, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n map<string, int> speed{ { \"ninja\", 290 },\n { \"s1000rr\", 310 }, { \"bullet\", 127 },\n { \"Duke\", 135 }, { \"R1\", 286 } };\n map<string, int>::iterator i;\n cout << \"The topspeed of bikes are\" << endl;\n for (i = speed.begin(); i != speed.end(); i++)\n cout<<i->first<<\" \"<<i->second <<endl;\n cout << endl;\n cout << \"The top speed of bullet is \"<< speed[\"bullet\"] << endl;\n}" }, { "code": null, "e": 2176, "s": 2059, "text": "The topspeed of bikes are\nDuke 135\nR1 286\nBullet 127\nninja 290\ns1000rr 310\nThe top speed of bullet is 127" } ]
How to resolve "Expected BEGIN_OBJECT but was BEGIN_ARRAY" using Gson in Java?
While deserializing, a Gson can expect a JSON object but it can find a JSON array. Since it can't convert from one to the other, it can throw an error as "JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY" at the runtime. import com.google.gson.Gson; public class GsonErrorTest { public static void main(String args[]) throws Exception { String json = "{\"employee\":[{\"name\":\"Raja Ramesh\", \"technology\":\"java\"}]}"; Gson gson = new Gson(); Software software = gson.fromJson(json, Software.class); System.out.println(software); } } class Software { Employee employee; } class Employee { String name; String technology; } Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14 at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)at com.google.gson.Gson.fromJson(Gson.java:795) at com.google.gson.Gson.fromJson(Gson.java:761) at com.google.gson.Gson.fromJson(Gson.java:710) at com.google.gson.Gson.fromJson(Gson.java:682) at BeginObjectError.main(BeginObjectError.java:7) Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14 at com.google.gson.stream.JsonReader.expect(JsonReader.java:339) at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165) We need to resolve it by changing our POJO type to a Collection or Array type. In the below example, we can use a List collection in our POJO class. import java.util.List; import com.google.gson.Gson; public class GsonListTest { public static void main(String args[]) throws Exception { String jsonString = "{\"employees\":[{\"name\":\"Raja Ramesh\", \"technology\":\"Java\"}]}"; Gson gson = new Gson(); Software software = gson.fromJson(jsonString, Software.class); System.out.println(software); } } class Software { List<Employee> employees; @Override public String toString() { return "Software [employees=" + employees + "]"; } } class Employee { String name; String technology; @Override public String toString() { return "Employee [name=" + name + ", technology=" + technology + "]"; } } Software [employees=[Employee [name=Raja Ramesh, technology=Java]]]
[ { "code": null, "e": 1330, "s": 1062, "text": "While deserializing, a Gson can expect a JSON object but it can find a JSON array. Since it can't convert from one to the other, it can throw an error as \"JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY\" at the runtime." }, { "code": null, "e": 1775, "s": 1330, "text": "import com.google.gson.Gson;\npublic class GsonErrorTest {\n public static void main(String args[]) throws Exception {\n String json = \"{\\\"employee\\\":[{\\\"name\\\":\\\"Raja Ramesh\\\", \\\"technology\\\":\\\"java\\\"}]}\";\n Gson gson = new Gson();\n Software software = gson.fromJson(json, Software.class);\n System.out.println(software);\n }\n}\nclass Software {\n Employee employee;\n}\nclass Employee {\n String name;\n String technology;\n}" }, { "code": null, "e": 2864, "s": 1775, "text": "Exception in thread \"main\" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14\nat com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)\nat com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)at com.google.gson.Gson.fromJson(Gson.java:795)\nat com.google.gson.Gson.fromJson(Gson.java:761)\nat com.google.gson.Gson.fromJson(Gson.java:710)\nat com.google.gson.Gson.fromJson(Gson.java:682)\nat BeginObjectError.main(BeginObjectError.java:7)\nCaused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 14\nat com.google.gson.stream.JsonReader.expect(JsonReader.java:339)\nat com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)\nat com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)" }, { "code": null, "e": 3013, "s": 2864, "text": "We need to resolve it by changing our POJO type to a Collection or Array type. In the below example, we can use a List collection in our POJO class." }, { "code": null, "e": 3727, "s": 3013, "text": "import java.util.List;\nimport com.google.gson.Gson;\npublic class GsonListTest {\n public static void main(String args[]) throws Exception {\n String jsonString = \"{\\\"employees\\\":[{\\\"name\\\":\\\"Raja Ramesh\\\", \\\"technology\\\":\\\"Java\\\"}]}\";\n Gson gson = new Gson();\n Software software = gson.fromJson(jsonString, Software.class);\n System.out.println(software);\n }\n}\nclass Software {\n List<Employee> employees;\n @Override\n public String toString() {\n return \"Software [employees=\" + employees + \"]\";\n }\n}\nclass Employee {\n String name;\n String technology;\n @Override\n public String toString() {\n return \"Employee [name=\" + name + \", technology=\" + technology + \"]\";\n }\n}" }, { "code": null, "e": 3795, "s": 3727, "text": "Software [employees=[Employee [name=Raja Ramesh, technology=Java]]]" } ]
Introduction of Shared Memory Segment - GeeksforGeeks
14 Jun, 2021 Introduction of Shared Memory Segment :The quickest kind of IPC accessible is shared memory. There is no kernel participation in transmitting data between processes after the memory is mapped into the address space of the processes that are sharing the memory region. However, some type of synchronization between the processes that save and retrieve data to and from the shared memory region is usually necessary. Mutexes, condition variables, read-write locks, record locks, and semaphores were all explored in Part 3 of this series.Consider the typical stages in the client-server file copying application we used to demonstrate the various forms of message passing. The input file is read by the server. The kernel reads the data from the file into its memory and then copies it to the process. Using a pipe, FIFO, or message queue, the server writes this data to a message. These types of IPC usually need data transfer from the process to the kernel.In most cases, four copies of the data are necessary. Furthermore, these four copies are made between the kernel and a process, which is typically a costly copy (costlier than copying data within the kernel or inside a single process). The data transfer between the client and server through the kernel is depicted in Figure 1. Figure 1. The difficulty with various types of IPC—pipes, FIFOs, and message queues—is that information must pass through the kernel for two processes to communicate. By allowing two or more processes to share a memory space, shared memory provides a workaround. Of course, the processes must work together to coordinate or synchronize their use of the shared memory. This synchronization can be accomplished using any of the strategies and the following are the stages for the client-server example : A semaphore is used by the server to get access to a shared memory object. The server loads the shared memory object from the input file. The address of the data buffer, which is the second parameter to the read, points to the shared memory object. When the read is finished, the server sends a semaphore message to the client. The data from the shared memory object is written to the output file by the client. Create and initialize a semaphore :We establish and initialize a semaphore to safeguard a variable that we believe is shared (the global count). This semaphore is unnecessary since this assumption is incorrect. Notice how we execute sem unlink to remove the semaphore name from the system; however, while this removes the pathname, it has no effect on the semaphore that is already open. We do this so that even if the program crashes, the pathname is erased from the filesystem. Set unbuffered standard output and fork :Because both the parent and the child would be writing to standard output, we left it unbuffered. The output from the two processes is not interleaved as a result of this. Both the parent and the child run a loop that increases the counter for the set number of times, only incrementing the variable while the semaphore is held. C #include <stdio.h>#include <unpipc.h>#define GEEKSNAME "mysem"int counter = 0;int main(int argc, char** argv){ int i, nloop; sem_t* mutex; if (argc != 2) err_quit("usage: incr1 <#loops>"); nloop = atoi(argv[1]); /* unlink semaphore */ mutex = Sem_open(Px_ipc_name(GEEKSNAME), O_CREAT | O_EXCL, FILE_MODE, 1); Sem_unlink(Px_ipc_name(GEEKSNAME)); setbuf(stdout, NULL); /* stdout is unbuffered */ if (Fork() == 0) { /* child */ for (i = 0; i < nloop; i++) { Sem_wait(mutex); printf("child: %d\n", counter++); Sem_post(mutex); } exit(0); } /* owner */ for (i = 0; i < nloop; i++) { Sem_wait(mutex); printf("parent: %d\n", counter++); Sem_post(mutex); } exit(0);} Both processes, as can be seen, have their own copy of the global count. Each starts with a value of 0 for this variable and then increases its own copy of it. Conclusion :Because one copy of the data in shared memory is available to all threads or processes that share the memory, shared memory is the quickest type of IPC accessible. However, to coordinate the numerous threads or processes that share the memory, some type of synchronization is usually necessary. Because this is one technique to transfer memory across related or unrelated processes, this chapter has focused on the mMap function and the mapping of regular files into memory. We no longer need to read, write, or seek to access a file that has been memory-mapped; instead, we just obtain or save the memory regions that have been mapped to the file by mMap. Picked DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS What is Temporary Table in SQL? Conflict Serializability in DBMS KDD Process in Data Mining Layers of OSI Model TCP/IP Model Types of Operating Systems Page Replacement Algorithms in Operating Systems Differences between TCP and UDP
[ { "code": null, "e": 25659, "s": 25631, "text": "\n14 Jun, 2021" }, { "code": null, "e": 26329, "s": 25659, "text": "Introduction of Shared Memory Segment :The quickest kind of IPC accessible is shared memory. There is no kernel participation in transmitting data between processes after the memory is mapped into the address space of the processes that are sharing the memory region. However, some type of synchronization between the processes that save and retrieve data to and from the shared memory region is usually necessary. Mutexes, condition variables, read-write locks, record locks, and semaphores were all explored in Part 3 of this series.Consider the typical stages in the client-server file copying application we used to demonstrate the various forms of message passing." }, { "code": null, "e": 26458, "s": 26329, "text": "The input file is read by the server. The kernel reads the data from the file into its memory and then copies it to the process." }, { "code": null, "e": 26538, "s": 26458, "text": "Using a pipe, FIFO, or message queue, the server writes this data to a message." }, { "code": null, "e": 26943, "s": 26538, "text": "These types of IPC usually need data transfer from the process to the kernel.In most cases, four copies of the data are necessary. Furthermore, these four copies are made between the kernel and a process, which is typically a costly copy (costlier than copying data within the kernel or inside a single process). The data transfer between the client and server through the kernel is depicted in Figure 1." }, { "code": null, "e": 26953, "s": 26943, "text": "Figure 1." }, { "code": null, "e": 27110, "s": 26953, "text": "The difficulty with various types of IPC—pipes, FIFOs, and message queues—is that information must pass through the kernel for two processes to communicate." }, { "code": null, "e": 27311, "s": 27110, "text": "By allowing two or more processes to share a memory space, shared memory provides a workaround. Of course, the processes must work together to coordinate or synchronize their use of the shared memory." }, { "code": null, "e": 27445, "s": 27311, "text": "This synchronization can be accomplished using any of the strategies and the following are the stages for the client-server example :" }, { "code": null, "e": 27520, "s": 27445, "text": "A semaphore is used by the server to get access to a shared memory object." }, { "code": null, "e": 27694, "s": 27520, "text": "The server loads the shared memory object from the input file. The address of the data buffer, which is the second parameter to the read, points to the shared memory object." }, { "code": null, "e": 27773, "s": 27694, "text": "When the read is finished, the server sends a semaphore message to the client." }, { "code": null, "e": 27857, "s": 27773, "text": "The data from the shared memory object is written to the output file by the client." }, { "code": null, "e": 28337, "s": 27857, "text": "Create and initialize a semaphore :We establish and initialize a semaphore to safeguard a variable that we believe is shared (the global count). This semaphore is unnecessary since this assumption is incorrect. Notice how we execute sem unlink to remove the semaphore name from the system; however, while this removes the pathname, it has no effect on the semaphore that is already open. We do this so that even if the program crashes, the pathname is erased from the filesystem." }, { "code": null, "e": 28707, "s": 28337, "text": "Set unbuffered standard output and fork :Because both the parent and the child would be writing to standard output, we left it unbuffered. The output from the two processes is not interleaved as a result of this. Both the parent and the child run a loop that increases the counter for the set number of times, only incrementing the variable while the semaphore is held." }, { "code": null, "e": 28709, "s": 28707, "text": "C" }, { "code": "#include <stdio.h>#include <unpipc.h>#define GEEKSNAME \"mysem\"int counter = 0;int main(int argc, char** argv){ int i, nloop; sem_t* mutex; if (argc != 2) err_quit(\"usage: incr1 <#loops>\"); nloop = atoi(argv[1]); /* unlink semaphore */ mutex = Sem_open(Px_ipc_name(GEEKSNAME), O_CREAT | O_EXCL, FILE_MODE, 1); Sem_unlink(Px_ipc_name(GEEKSNAME)); setbuf(stdout, NULL); /* stdout is unbuffered */ if (Fork() == 0) { /* child */ for (i = 0; i < nloop; i++) { Sem_wait(mutex); printf(\"child: %d\\n\", counter++); Sem_post(mutex); } exit(0); } /* owner */ for (i = 0; i < nloop; i++) { Sem_wait(mutex); printf(\"parent: %d\\n\", counter++); Sem_post(mutex); } exit(0);}", "e": 29512, "s": 28709, "text": null }, { "code": null, "e": 29672, "s": 29512, "text": "Both processes, as can be seen, have their own copy of the global count. Each starts with a value of 0 for this variable and then increases its own copy of it." }, { "code": null, "e": 29979, "s": 29672, "text": "Conclusion :Because one copy of the data in shared memory is available to all threads or processes that share the memory, shared memory is the quickest type of IPC accessible. However, to coordinate the numerous threads or processes that share the memory, some type of synchronization is usually necessary." }, { "code": null, "e": 30341, "s": 29979, "text": "Because this is one technique to transfer memory across related or unrelated processes, this chapter has focused on the mMap function and the mapping of regular files into memory. We no longer need to read, write, or seek to access a file that has been memory-mapped; instead, we just obtain or save the memory regions that have been mapped to the file by mMap." }, { "code": null, "e": 30348, "s": 30341, "text": "Picked" }, { "code": null, "e": 30353, "s": 30348, "text": "DBMS" }, { "code": null, "e": 30361, "s": 30353, "text": "GATE CS" }, { "code": null, "e": 30366, "s": 30361, "text": "DBMS" }, { "code": null, "e": 30464, "s": 30366, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30481, "s": 30464, "text": "Deadlock in DBMS" }, { "code": null, "e": 30522, "s": 30481, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 30554, "s": 30522, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 30587, "s": 30554, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 30614, "s": 30587, "text": "KDD Process in Data Mining" }, { "code": null, "e": 30634, "s": 30614, "text": "Layers of OSI Model" }, { "code": null, "e": 30647, "s": 30634, "text": "TCP/IP Model" }, { "code": null, "e": 30674, "s": 30647, "text": "Types of Operating Systems" }, { "code": null, "e": 30723, "s": 30674, "text": "Page Replacement Algorithms in Operating Systems" } ]
Sum of two large numbers | Practice | GeeksforGeeks
Given two strings denoting non-negative numbers X and Y. Calculate the sum of X and Y. Example 1: Input: X = "25", Y = "23" Output: 48 Explanation: The sum of 25 and 23 is 48. Example 2: Input: X = "2500", Y = "23" Output: 2523 Explanation: The sum of 2500 and 23 is 2523. Your Task: Your task is to complete the function findSum() which takes two strings as inputs and returns the string without leading zeros. You do not need to take any input or print anything. Expected Time Complexity: O(|X| + |Y|) Expected Auxiliary Space: O(1) Constraints: 1 <= |X|, |Y| <= 105 0 mahesh_phutane1 week ago Simple java solution class Solution { String findSum(String X, String Y) { StringBuilder sb = new StringBuilder(""); int xlen = X.length(); int ylen = Y.length(); int carry = 0; int i = xlen-1; int j = ylen-1; while(i>-1 || j>-1 || carry!=0){ int xsum = i>-1?X.charAt(i--)-'0':0; int ysum = j>-1?Y.charAt(j--)-'0':0; int tsum = xsum+ysum+carry; sb.append(Integer.toString(tsum%10)); carry = tsum/10; } j = sb.length()-1; while(sb.charAt(j)=='0' && j>0){ sb.deleteCharAt(j--); } return sb.reverse().toString(); } } -1 sunilkumarhotta12 weeks ago return (new java.math.BigInteger(X).add(new java.math.BigInteger(Y))).toString(); -1 aakasshuit3 weeks ago //Java Solution java.math.BigInteger b1 = new java.math.BigInteger(X); java.math.BigInteger b2 = new java.math.BigInteger(Y); java.math.BigInteger ans = b1.add(b2); return ans.toString(); +1 prishita1 month ago JAVA Solution: Using BigInteger class Solution { String findSum(String X, String Y) { // code here java.math.BigInteger n1= new java.math.BigInteger(X); java.math.BigInteger n2= new java.math.BigInteger(Y); java.math.BigInteger sum; sum=n1.add(n2); return sum.toString(); } } 0 ayazmrz981 month ago def findSum(self, X, Y): return int(X)+int(Y) +1 sharma_nitin_261 month ago 0 anantkumawat101102 months ago C++ Solution. string findSum(string X, string Y) { string str; int i = X.size() - 1, j = Y.size() - 1, carry = 0, first, second, sum; while(i >= 0 || j >= 0 || carry){ if(i >= 0) first = X[i--] - '0'; else first = 0; if(j >= 0) second = Y[j--] - '0'; else second = 0; sum = first + second + carry; str.insert(0, to_string(sum % 10)); carry = sum / 10; } i = 0; while(str.size() > 1 && str[i] == '0'){ str.erase(0, 1); } return str; } 0 mnkbutola2 months ago string findSum(string X, string Y) { // Your code goes here int i=X.size()-1,j=Y.size()-1; int cary=0; string ans=""; while(i>=0 or j>=0 or cary){ int sum=0; if(i>=0){ sum+=X[i]-'0'; i--; } if(j>=0){ sum+=Y[j]-'0'; j--; } sum+=cary; cary=sum/10; ans=to_string(sum%10)+ans; } for( i=0;i<ans.size();i++){ if(ans[i]=='0') continue; else break; } if(i==ans.size()) return "0"; else return ans.substr(i); } +1 sachinupreti1902 months ago C++ EASY CODE. PLEASE UPVOTE, IF it helps you . // Here is your code. class Solution { public: string findSum(string X, string Y) { string ptr=""; int m,n,i,c=0; m=X.size(); n=Y.size(); for(i=0;i<m;i++) { if(X[i]=='0' && c<m-1) { c++; } else break; } X=X.erase(0,c); c=0; for(i=0;i<n;i++) { if(Y[i]=='0' && c<n-1) { c++; } else break; } Y=Y.erase(0,c); if(X.size()<Y.size()) { for(i=1;i<=Y.size()-X.size();i++) { ptr+="0"; } X=ptr+X; } //return ptr; else if(X.size()==Y.size()) { } else { for(i=1;i<=X.size()-Y.size();i++) { ptr+="0"; } Y=ptr+Y; } reverse(X.begin(),X.end()); reverse(Y.begin(),Y.end()); int carry=0,a,b,l,f; string final="",qtr; for(i=0;i<X.size();i++) { a=X[i]-48; b=Y[i]-48; l=a+b+carry; f=l%10; qtr=to_string(f); final=final+qtr; carry=l/10; } if(carry>0) final+=to_string(carry); reverse(final.begin(),final.end()); return final; } 0 ajeetkumarece222 months ago int charToint(char ch){ return ch-'0';}char intTochar(int num){ return num+'0';} string helper(string res){ int i=0; while(i<res.length() && res[i]=='0'){ i++; } if(i==res.length()){ return "0"; } return res.substr(i); } string findSum(string X, string Y) { // Your code goes here if(X.length()>Y.length()) swap(X,Y); reverse(X.begin(),X.end()); reverse(Y.begin(),Y.end()); string result=""; int carry=0; for(int i=0;i<X.length();i++){ int d1=charToint(X[i]); int d2=charToint(Y[i]); int sum=d1+d2+carry; int op=sum%10; carry=sum/10; result.push_back(intTochar(op)); } for(int i=X.length();i<Y.length();i++){ int d1=charToint(Y[i]); int sum=d1+carry; int op=sum%10; carry=sum/10; result.push_back(intTochar(op)); } if(carry) result.push_back('1'); reverse(result.begin(),result.end()); string r=helper(result); return r; } 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": 326, "s": 238, "text": "Given two strings denoting non-negative numbers X and Y. Calculate the sum of X and Y. " }, { "code": null, "e": 338, "s": 326, "text": "\nExample 1:" }, { "code": null, "e": 416, "s": 338, "text": "Input:\nX = \"25\", Y = \"23\"\nOutput:\n48\nExplanation:\nThe sum of 25 and 23 is 48." }, { "code": null, "e": 427, "s": 416, "text": "Example 2:" }, { "code": null, "e": 513, "s": 427, "text": "Input:\nX = \"2500\", Y = \"23\"\nOutput:\n2523\nExplanation:\nThe sum of 2500 and 23 is 2523." }, { "code": null, "e": 706, "s": 513, "text": "\nYour Task:\nYour task is to complete the function findSum() which takes two strings as inputs and returns the string without leading zeros. You do not need to take any input or print anything." }, { "code": null, "e": 777, "s": 706, "text": "\nExpected Time Complexity: O(|X| + |Y|)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 812, "s": 777, "text": "\nConstraints:\n1 <= |X|, |Y| <= 105" }, { "code": null, "e": 814, "s": 812, "text": "0" }, { "code": null, "e": 839, "s": 814, "text": "mahesh_phutane1 week ago" }, { "code": null, "e": 860, "s": 839, "text": "Simple java solution" }, { "code": null, "e": 1565, "s": 860, "text": "class Solution {\n String findSum(String X, String Y) {\n StringBuilder sb = new StringBuilder(\"\");\n int xlen = X.length();\n int ylen = Y.length();\n int carry = 0;\n int i = xlen-1;\n int j = ylen-1;\n \n while(i>-1 || j>-1 || carry!=0){\n int xsum = i>-1?X.charAt(i--)-'0':0;\n int ysum = j>-1?Y.charAt(j--)-'0':0;\n int tsum = xsum+ysum+carry;\n sb.append(Integer.toString(tsum%10));\n carry = tsum/10;\n }\n \n j = sb.length()-1;\n \n while(sb.charAt(j)=='0' && j>0){\n sb.deleteCharAt(j--);\n }\n \n return sb.reverse().toString();\n }\n}" }, { "code": null, "e": 1568, "s": 1565, "text": "-1" }, { "code": null, "e": 1596, "s": 1568, "text": "sunilkumarhotta12 weeks ago" }, { "code": null, "e": 1687, "s": 1596, "text": " return (new java.math.BigInteger(X).add(new java.math.BigInteger(Y))).toString(); " }, { "code": null, "e": 1690, "s": 1687, "text": "-1" }, { "code": null, "e": 1712, "s": 1690, "text": "aakasshuit3 weeks ago" }, { "code": null, "e": 1951, "s": 1712, "text": "//Java Solution\n\n java.math.BigInteger b1 = new java.math.BigInteger(X);\n java.math.BigInteger b2 = new java.math.BigInteger(Y);\n \n java.math.BigInteger ans = b1.add(b2);\n \n return ans.toString();" }, { "code": null, "e": 1954, "s": 1951, "text": "+1" }, { "code": null, "e": 1974, "s": 1954, "text": "prishita1 month ago" }, { "code": null, "e": 1989, "s": 1974, "text": "JAVA Solution:" }, { "code": null, "e": 2006, "s": 1989, "text": "Using BigInteger" }, { "code": null, "e": 2308, "s": 2008, "text": "class Solution {\n String findSum(String X, String Y) {\n // code here\n java.math.BigInteger n1= new java.math.BigInteger(X);\n java.math.BigInteger n2= new java.math.BigInteger(Y);\n java.math.BigInteger sum;\n sum=n1.add(n2);\n return sum.toString();\n }\n}" }, { "code": null, "e": 2310, "s": 2308, "text": "0" }, { "code": null, "e": 2331, "s": 2310, "text": "ayazmrz981 month ago" }, { "code": null, "e": 2378, "s": 2331, "text": "def findSum(self, X, Y):\n return int(X)+int(Y)" }, { "code": null, "e": 2381, "s": 2378, "text": "+1" }, { "code": null, "e": 2408, "s": 2381, "text": "sharma_nitin_261 month ago" }, { "code": null, "e": 2410, "s": 2408, "text": "0" }, { "code": null, "e": 2440, "s": 2410, "text": "anantkumawat101102 months ago" }, { "code": null, "e": 2454, "s": 2440, "text": "C++ Solution." }, { "code": null, "e": 3021, "s": 2454, "text": "string findSum(string X, string Y) {\n string str;\n int i = X.size() - 1, j = Y.size() - 1, carry = 0, first,\n second, sum;\n \n while(i >= 0 || j >= 0 || carry){\n if(i >= 0) first = X[i--] - '0';\n else first = 0;\n \n if(j >= 0) second = Y[j--] - '0';\n else second = 0;\n \n sum = first + second + carry;\n str.insert(0, to_string(sum % 10));\n carry = sum / 10;\n }\n i = 0;\n while(str.size() > 1 && str[i] == '0'){ \n str.erase(0, 1);\n }\n \n return str;\n}" }, { "code": null, "e": 3023, "s": 3021, "text": "0" }, { "code": null, "e": 3045, "s": 3023, "text": "mnkbutola2 months ago" }, { "code": null, "e": 3670, "s": 3045, "text": " string findSum(string X, string Y) { // Your code goes here int i=X.size()-1,j=Y.size()-1; int cary=0; string ans=\"\"; while(i>=0 or j>=0 or cary){ int sum=0; if(i>=0){ sum+=X[i]-'0'; i--; } if(j>=0){ sum+=Y[j]-'0'; j--; } sum+=cary; cary=sum/10; ans=to_string(sum%10)+ans; } for( i=0;i<ans.size();i++){ if(ans[i]=='0') continue; else break; } if(i==ans.size()) return \"0\"; else return ans.substr(i); }" }, { "code": null, "e": 3673, "s": 3670, "text": "+1" }, { "code": null, "e": 3701, "s": 3673, "text": "sachinupreti1902 months ago" }, { "code": null, "e": 3716, "s": 3701, "text": "C++ EASY CODE." }, { "code": null, "e": 3749, "s": 3716, "text": "PLEASE UPVOTE, IF it helps you ." }, { "code": null, "e": 3773, "s": 3751, "text": "// Here is your code." }, { "code": null, "e": 5194, "s": 3775, "text": "class Solution { public: string findSum(string X, string Y) { string ptr=\"\"; int m,n,i,c=0; m=X.size(); n=Y.size(); for(i=0;i<m;i++) { if(X[i]=='0' && c<m-1) { c++; } else break; } X=X.erase(0,c); c=0; for(i=0;i<n;i++) { if(Y[i]=='0' && c<n-1) { c++; } else break; } Y=Y.erase(0,c); if(X.size()<Y.size()) { for(i=1;i<=Y.size()-X.size();i++) { ptr+=\"0\"; } X=ptr+X; } //return ptr; else if(X.size()==Y.size()) { } else { for(i=1;i<=X.size()-Y.size();i++) { ptr+=\"0\"; } Y=ptr+Y; } reverse(X.begin(),X.end()); reverse(Y.begin(),Y.end()); int carry=0,a,b,l,f; string final=\"\",qtr; for(i=0;i<X.size();i++) { a=X[i]-48; b=Y[i]-48; l=a+b+carry; f=l%10; qtr=to_string(f); final=final+qtr; carry=l/10; } if(carry>0) final+=to_string(carry); reverse(final.begin(),final.end()); return final; }" }, { "code": null, "e": 5196, "s": 5194, "text": "0" }, { "code": null, "e": 5224, "s": 5196, "text": "ajeetkumarece222 months ago" }, { "code": null, "e": 5309, "s": 5224, "text": "int charToint(char ch){ return ch-'0';}char intTochar(int num){ return num+'0';}" }, { "code": null, "e": 6280, "s": 5309, "text": "string helper(string res){ int i=0; while(i<res.length() && res[i]=='0'){ i++; } if(i==res.length()){ return \"0\"; } return res.substr(i); } string findSum(string X, string Y) { // Your code goes here if(X.length()>Y.length()) swap(X,Y); reverse(X.begin(),X.end()); reverse(Y.begin(),Y.end()); string result=\"\"; int carry=0; for(int i=0;i<X.length();i++){ int d1=charToint(X[i]); int d2=charToint(Y[i]); int sum=d1+d2+carry; int op=sum%10; carry=sum/10; result.push_back(intTochar(op)); } for(int i=X.length();i<Y.length();i++){ int d1=charToint(Y[i]); int sum=d1+carry; int op=sum%10; carry=sum/10; result.push_back(intTochar(op)); } if(carry) result.push_back('1'); reverse(result.begin(),result.end()); string r=helper(result); return r;" }, { "code": null, "e": 6282, "s": 6280, "text": "}" }, { "code": null, "e": 6428, "s": 6282, "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": 6464, "s": 6428, "text": " Login to access your submissions. " }, { "code": null, "e": 6474, "s": 6464, "text": "\nProblem\n" }, { "code": null, "e": 6484, "s": 6474, "text": "\nContest\n" }, { "code": null, "e": 6547, "s": 6484, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6695, "s": 6547, "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": 6903, "s": 6695, "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": 7009, "s": 6903, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Static functions in C - GeeksforGeeks
24 Aug, 2020 Prerequisite : Static variables in C In C, functions are global by default. The “static” keyword before a function name makes it static. For example, below function fun() is static. static int fun(void){ printf("I am a static function ");} Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files. For example, if we store following program in one file file1.c /* Inside file1.c */ static void fun1(void){ puts("fun1 called");} And store following program in another file file2.c /* Inside file2.c */ int main(void){ fun1(); getchar(); return 0; } Now, if we compile the above code with command “gcc file2.c file1.c”, we get the error “undefined reference to `fun1’” . This is because fun1() is declared static in file1.c and cannot be used in file2.c. Please write comments if you find anything incorrect in the above article, or want to share more information about static functions in C. akhileshkasturi C-Functions C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. fork() in C Function Pointer in C Substring in C++ rand() and srand() in C/C++ std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++ TCP Server-Client implementation in C Structures in C Different methods to reverse a string in C/C++
[ { "code": null, "e": 26220, "s": 26192, "text": "\n24 Aug, 2020" }, { "code": null, "e": 26257, "s": 26220, "text": "Prerequisite : Static variables in C" }, { "code": null, "e": 26402, "s": 26257, "text": "In C, functions are global by default. The “static” keyword before a function name makes it static. For example, below function fun() is static." }, { "code": "static int fun(void){ printf(\"I am a static function \");}", "e": 26461, "s": 26402, "text": null }, { "code": null, "e": 26745, "s": 26461, "text": "Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files." }, { "code": null, "e": 26808, "s": 26745, "text": "For example, if we store following program in one file file1.c" }, { "code": "/* Inside file1.c */ static void fun1(void){ puts(\"fun1 called\");}", "e": 26876, "s": 26808, "text": null }, { "code": null, "e": 26928, "s": 26876, "text": "And store following program in another file file2.c" }, { "code": "/* Inside file2.c */ int main(void){ fun1(); getchar(); return 0; }", "e": 27002, "s": 26928, "text": null }, { "code": null, "e": 27207, "s": 27002, "text": "Now, if we compile the above code with command “gcc file2.c file1.c”, we get the error “undefined reference to `fun1’” . This is because fun1() is declared static in file1.c and cannot be used in file2.c." }, { "code": null, "e": 27345, "s": 27207, "text": "Please write comments if you find anything incorrect in the above article, or want to share more information about static functions in C." }, { "code": null, "e": 27361, "s": 27345, "text": "akhileshkasturi" }, { "code": null, "e": 27373, "s": 27361, "text": "C-Functions" }, { "code": null, "e": 27384, "s": 27373, "text": "C Language" }, { "code": null, "e": 27482, "s": 27384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27494, "s": 27482, "text": "fork() in C" }, { "code": null, "e": 27516, "s": 27494, "text": "Function Pointer in C" }, { "code": null, "e": 27533, "s": 27516, "text": "Substring in C++" }, { "code": null, "e": 27561, "s": 27533, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27586, "s": 27561, "text": "std::string class in C++" }, { "code": null, "e": 27613, "s": 27586, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 27645, "s": 27613, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27683, "s": 27645, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27699, "s": 27683, "text": "Structures in C" } ]
Google Colab - Quick Guide
Google is quite aggressive in AI research. Over many years, Google developed AI framework called TensorFlow and a development tool called Colaboratory. Today TensorFlow is open-sourced and since 2017, Google made Colaboratory free for public use. Colaboratory is now known as Google Colab or simply Colab. Another attractive feature that Google offers to the developers is the use of GPU. Colab supports GPU and it is totally free. The reasons for making it free for public could be to make its software a standard in the academics for teaching machine learning and data science. It may also have a long term perspective of building a customer base for Google Cloud APIs which are sold per-use basis. Irrespective of the reasons, the introduction of Colab has eased the learning and development of machine learning applications. So, let us get started with Colab. If you have used Jupyter notebook previously, you would quickly learn to use Google Colab. To be precise, Colab is a free Jupyter notebook environment that runs entirely in the cloud. Most importantly, it does not require a setup and the notebooks that you create can be simultaneously edited by your team members - just the way you edit documents in Google Docs. Colab supports many popular machine learning libraries which can be easily loaded in your notebook. As a programmer, you can perform the following using Google Colab. Write and execute code in Python Write and execute code in Python Document your code that supports mathematical equations Document your code that supports mathematical equations Create/Upload/Share notebooks Create/Upload/Share notebooks Import/Save notebooks from/to Google Drive Import/Save notebooks from/to Google Drive Import/Publish notebooks from GitHub Import/Publish notebooks from GitHub Import external datasets e.g. from Kaggle Import external datasets e.g. from Kaggle Integrate PyTorch, TensorFlow, Keras, OpenCV Integrate PyTorch, TensorFlow, Keras, OpenCV Free Cloud service with free GPU Free Cloud service with free GPU In this chapter, you will create and execute your first trivial notebook. Follow the steps that have been given wherever needed. Note − As Colab implicitly uses Google Drive for storing your notebooks, ensure that you are logged in to your Google Drive account before proceeding further. Step 1 − Open the following URL in your browser − https://colab.research.google.com Your browser would display the following screen (assuming that you are logged into your Google Drive) − Step 2 − Click on the NEW PYTHON 3 NOTEBOOK link at the bottom of the screen. A new notebook would open up as shown in the screen below. As you might have noticed, the notebook interface is quite similar to the one provided in Jupyter. There is a code window in which you would enter your Python code. By default, the notebook uses the naming convention UntitledXX.ipynb. To rename the notebook, click on this name and type in the desired name in the edit box as shown here − We will call this notebook as MyFirstColabNotebook. So type in this name in the edit box and hit ENTER. The notebook will acquire the name that you have given now. You will now enter a trivial Python code in the code window and execute it. Enter the following two Python statements in the code window − import time print(time.ctime()) To execute the code, click on the arrow on the left side of the code window. After a while, you will see the output underneath the code window, as shown here − Mon Jun 17 05:58:40 2019 You can clear the output anytime by clicking the icon on the left side of the output display. To add more code to your notebook, select the following menu options − Insert / Code Cell Alternatively, just hover the mouse at the bottom center of the Code cell. When the CODE and TEXT buttons appear, click on the CODE to add a new cell. This is shown in the screenshot below − A new code cell will be added underneath the current cell. Add the following two statements in the newly created code window − time.sleep(5) print (time.ctime()) Now, if you run this cell, you will see the following output − Mon Jun 17 04:50:27 2019 Certainly, the time difference between the two time strings is not 5 seconds. This is obvious as you did take some time to insert the new code. Colab allows you to run all code inside your notebook without an interruption. To run the entire code in your notebook without an interruption, execute the following menu options − Runtime / Reset and run all... It will give you the output as shown below − Note that the time difference between the two outputs is now exactly 5 seconds. The above action can also be initiated by executing the following two menu options − Runtime / Restart runtime... or Runtime / Restart all runtimes... Followed by Runtime / Run all Study the different menu options under the Runtime menu to get yourself acquainted with the various options available to you for executing the notebook. When your notebook contains a large number of code cells, you may come across situations where you would like to change the order of execution of these cells. You can do so by selecting the cell that you want to move and clicking the UP CELL or DOWN CELL buttons shown in the following screenshot − You may click the buttons multiple times to move the cell for more than a single position. During the development of your project, you may have introduced a few now-unwanted cells in your notebook. You can remove such cells from your project easily with a single click. Click on the vertical-dotted icon at the top right corner of your code cell. Click on the Delete cell option and the current cell will be deleted. Now, as you have learned how to run a trivial notebook, let us explore the other capabilities of Colab. As the code cell supports full Python syntax, you may use Python comments in the code window to describe your code. However, many a time you need more than a simple text based comments to illustrate the ML algorithms. ML heavily uses mathematics and to explain those terms and equations to your readers you need an editor that supports LaTex - a language for mathematical representations. Colab provides Text Cells for this purpose. A text cell containing few mathematical equations typically used in ML is shown in the screenshot below − As we move ahead in this chapter, we will see the code for generating the above output. Text Cells are formatted using markdown - a simple markup language. Let us now see you how to add text cells to your notebook and add to it some text containing mathematical equations. Let us look into few examples of markup language syntax to demonstrate its capabilities. Type in the following text in the Text cell. This is **bold**. This is *italic*. This is ~strikethrough~. The output of the above commands is rendered on the right hand side of the Cell as shown here. Add a Text Cell to your notebook and enter the following markdown syntax in the text window − $\sqrt{3x-1}+(1+x)^2$ You will see the immediate rendering of the markdown code in the right hand side panel of the text cell. This is shown in the screenshot below − Hit Enter and the markdown code disappears from the text cell and only the rendered output is shown. Let us try another more complicated equation as shown here − $e^x = \sum_{i = 0}^\infty \frac{1}{i!}x^i$ The rendered output is shown here for your quick reference. Here is the code for the sample equations shown in an earlier screenshot − Constraints are - $3x_1 + 6x_2 + x_3 =< 28$ - $7x_1 + 3x_2 + 2x_3 =< 37$ - $4x_1 + 5x_2 + 2x_3 =< 19$ - $x_1,x_2,x_3 >=0 $ The trial vector is calculated as follows: - $u_i(t) = x_i(t) + \beta(\hat{x}(t) − x_i(t)) + \beta \sum_{k = 1}^{n_v}(x_{i1,k}(t) − x_{i2,k}(t))$ $f(x_1, x_2) = 20 + e - 20exp(-0.2 \sqrt {\frac {1}{n} (x_1^2 + x_2^2)}) - exp (\frac {1}{n}(cos(2\pi x_1) + cos(2\pi x_2))$ $x ∈ [-5, 5]$ >$A_{m,n} = \begin{pmatrix} a_{1,1} > a_{1,2} > \cdots > a_{1,n} \\ a_{2,1} > a_{2,2} > \cdots > a_{2,n} \\ \vdots > \vdots > \ddots > \vdots \\ a_{m,1} > a_{m,2} > \cdots > a_{m,n} \end{pmatrix}$ Describing full markup syntax is beyond the scope of this tutorial. In the next chapter, we will see how to save your work. Colab allows you to save your work to Google Drive or even directly to your GitHub repository. Colab allows you to save your work to your Google Drive. To save your notebook, select the following menu options − File / Save a copy in Drive... You will see the following screen − The action will create a copy of your notebook and save it to your drive. Later on you may rename the copy to your choice of name. You may also save your work to your GitHub repository by selecting the following menu options − File / Save a copy in GitHub... The menu selection is shown in the following screenshot for your quick reference − You will have to wait until you see the login screen to GitHub. Now, enter your credentials. If you do not have a repository, create a new one and save your project as shown in the screenshot below − In the next chapter, we will learn how to share your work with others. To share the notebook that you have created with other co-developers, you may share the copy that you have made in your Google Drive. To publish the notebook to general audience, you may share it from your GitHub repository. There is one more way to share your work and that is by clicking on the SHARE link at the top right hand corner of your Colab notebook. This will open the share box as shown here − You may enter the email IDs of people with whom you would like to share the current document. You can set the kind of access by selecting from the three options shown in the above screen. Click on the Get shareable link option to get the URL of your notebook. You will find options for whom to share as follows − Specified group of people Specified group of people Colleagues in your organization Colleagues in your organization Anyone with the link Anyone with the link All public on the web All public on the web Now. you know how to create/execute/save/share a notebook. In the Code cell, we used Python so far. The code cell can also be used for invoking system commands. This is explained next. Jupyter includes shortcuts for many common system operations. Colab Code cell supports this feature. Enter the following code in the Code cell that uses the system command echo. message = 'A Great Tutorial on Colab by Tutorialspoint!' greeting = !echo -e '$message\n$message' greeting Now, if you run the cell, you will see the following output − ['A Great Tutorial on Colab by Tutorialspoint!', 'A Great Tutorial on Colab by Tutorialspoint!'] Let us look into another example that loads the dataset from a remote server. Type in the following command in your Code cell − !wget http://mlr.cs.umass.edu/ml/machine-learning-databases/adult/adult.data -P "/content/drive/My Drive/app" If you run the code, you would see the following output − --2019-06-20 10:09:53-- http://mlr.cs.umass.edu/ml/machine-learning-databases/adult/adult.data Resolving mlr.cs.umass.edu (mlr.cs.umass.edu)... 128.119.246.96 Connecting to mlr.cs.umass.edu (mlr.cs.umass.edu)|128.119.246.96|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 3974305 (3.8M) [text/plain] Saving to: ‘/content/drive/My Drive/app/adult.data.1’ adult.data.1 100%[===================>] 3.79M 1.74MB/s in 2.2s 2019-06-20 10:09:56 (1.74 MB/s) - ‘/content/drive/My Drive/app/adult.data.1’ saved [3974305/3974305] As the message says, the adult.data.1 file is now added to your drive. You can verify this by examining the folder contents of your drive. Alternatively, type in the following code in a new Code cell − import pandas as pd data = pd.read_csv("/content/drive/My Drive/app/adult.data.1") data.head(5) Run the code now and you will see the following output − Likewise, most of the system commands can be invoked in your code cell by prepending the command with an Exclamation Mark (!). Let us look into another example before giving out the complete list of commands that you can invoke. You can clone the entire GitHub repository into Colab using the gitcommand. For example, to clone the keras tutorial, type the following command in the Code cell − !git clone https://github.com/wxs/keras-mnist-tutorial.git After a successful run of the command, you would see the following output − Cloning into 'keras-mnist-tutorial'... remote: Enumerating objects: 26, done. remote: Total 26 (delta 0), reused 0 (delta 0), pack-reused 26 Unpacking objects: 100% (26/26), done. Once the repo is cloned, locate a Jupyter project (e.g. MINST in keras.ipyab) in it, right-click on the file name and select Open With / Colaboratory menu option to open the project in Colab. To get a list of shortcuts for common operations, execute the following command − !ls /bin You will see the list in the output window as shown below − bash* journalctl* sync* bunzip2* kill* systemctl* bzcat* kmod* systemd@ bzcmp@ less* systemd-ask-password* bzdiff* lessecho* systemd-escape* bzegrep@ lessfile@ systemd-hwdb* bzexe* lesskey* systemd-inhibit* bzfgrep@ lesspipe* systemd-machine-id-setup* bzgrep* ln* systemd-notify* bzip2* login* systemd-sysusers* bzip2recover* loginctl* systemd-tmpfiles* bzless@ ls* systemd-tty-ask-password-agent* bzmore* lsblk* tar* cat* lsmod@ tempfile* chgrp* mkdir* touch* chmod* mknod* true* chown* mktemp* udevadm* cp* more* ulockmgr_server* dash* mount* umount* date* mountpoint* uname* dd* mv* uncompress* df* networkctl* vdir* dir* nisdomainname@ wdctl* dmesg* pidof@ which* dnsdomainname@ ps* ypdomainname@ domainname@ pwd* zcat* echo* rbash@ zcmp* egrep* readlink* zdiff* false* rm* zegrep* fgrep* rmdir* zfgrep* findmnt* run-parts* zforce* fusermount* sed* zgrep* grep* sh@ zless* gunzip* sh.distrib@ zmore* gzexe* sleep* znew* gzip* stty* hostname* su* Execute any of these commands as we have done for echo and wget. In the next chapter, we shall see how to execute your previously created Python code. Suppose, you already have some Python code developed that is stored in your Google Drive. Now, you will like to load this code in Colab for further modifications. In this chapter, we will see how to load and run the code stored in your Google Drive. Tools / Command palette You will see the list of commands as shown in this screenshot − Type a few letters like “m” in the search box to locate the mount command. Select Mount Drive command from the list. The following code would be inserted in your Code cell. # Run this cell to mount your Google Drive. from google.colab import drive drive.mount('/content/drive') If you run this code, you will be asked to enter the authentication code. The corresponding screen looks as shown below − Open the above URL in your browser. You will be asked to login to your Google account. Now, you will see the following screen − If you grant the permissions, you will receive your code as follows − Cut-n-paste this code in the Code cell and hit ENTER. After a while, the drive will be mounted as seen in the screenshot below − Now, you are ready to use the contents of your drive in Colab. You can list the contents of the drive using the ls command as follows − !ls "/content/drive/My Drive/Colab Notebooks" This command will list the contents of your Colab Notebooks folder. The sample output of my drive contents are shown here − Greeting.ipynb hello.py LogisticRegressionCensusData.ipynb LogisticRegressionDigitalOcean.ipynb MyFirstColabNotebook.ipynb SamplePlot.ipynb Now, let us say that you want to run a Python file called hello.py stored in your Google Drive. Type the following command in the Code cell − !python3 "/content/drive/My Drive/Colab Notebooks/hello.py" The contents of hello.py are given here for your reference − print("Welcome to TutorialsPoint!") You will now see the following output − Welcome to TutorialsPoint! Besides the text output, Colab also supports the graphical outputs. We will see this in the next chapter. Colab also supports rich outputs such as charts. Type in the following code in the Code cell. import numpy as np from matplotlib import pyplot as plt y = np.random.randn(100) x = [x for x in range(len(y))] plt.plot(x, y, '-') plt.fill_between(x, y, 200, where = (y > 195), facecolor='g', alpha=0.6) plt.title("Sample Plot") plt.show() Now, if you run the code, you will see the following output − Note that the graphical output is shown in the output section of the Code cell. Likewise, you will be able to create and display several types of charts throughout your program code. Now, as you have got familiar with the basics of Colab, let us move on to the features in Colab that makes your Python code development easier. The present day developers rely heavily on context-sensitive help to the language and library syntaxes. That is why the IDEs are widely used. The Colab notebook editor provides this facility. In this chapter, let us see how to ask for context-sensitive help while writing Python code in Colab. Follow the steps that have been given wherever needed. Step 1 − Open a new notebook and type in the following code in the Code cell − import torch Step 2 − Run the code by clicking on the Run icon in the left panel of the Code cell. Add another Code cell and type in the following code − Tensor = torch. At this point, suppose you have forgotten what are the various functions available in torch module. You can ask for the context-sensitive help on function names by hitting the TAB key. Note the presence of the DOT after the torch keyword. Without this DOT, you will not see the context help. Your screen would look like as shown in the screenshot here − Now, select the desired function from the list and proceed with your coding. Colab gives you the documentation on any function or class as a context-sensitive help. Type the following code in your code window − Tensor = torch.cos( Now, hit TAB and you will see the documentation on cos in the popup window as shown in the screenshot here. Note that you need to type in open parenthesis before hitting TAB. In the next chapter, we will see Magics in Colab that lets us to do more powerful things than what we did with system aliases. Magics is a set of system commands that provide a mini extensive command language. Magics are of two types − Line magics Line magics Cell magics Cell magics The line magics as the name indicates that it consists of a single line of command, while the cell magic covers the entire body of the code cell. In case of line magics, the command is prepended with a single % character and in the case of cell magics, it is prepended with two % characters (%%). Let us look into some examples of both to illustrate these. Type the following code in your code cell − %ldir You will see the contents of your local directory, something like this - drwxr-xr-x 3 root 4096 Jun 20 10:05 drive/ drwxr-xr-x 1 root 4096 May 31 16:17 sample_data/ Try the following command − %history This presents the complete history of commands that you have previously executed. Type in the following code in your code cell − %%html <marquee style='width: 50%; color: Green;'>Welcome to Tutorialspoint!</marquee> Now, if you run the code and you will see the scrolling welcome message on the screen as shown here − The following code will add SVG to your document. %%html <svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 600 400" width="400" height="400"> <rect x="10" y="00" width="300" height="100" rx="0" style="fill:orange; stroke:black; fill-opacity:1.0" /> <rect x="10" y="100" width="300" height="100" rx="0" style="fill:white; stroke:black; fill-opacity:1.0;" /> <rect x="10" y="200" width="300" height="100" rx="0" style="fill:green; stroke:black; fill-opacity:1.0;" /> </svg> If you run the code, you would see the following output − To get a complete list of supported magics, execute the following command − %lsmagic You will see the following output − Available line magics: %alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %profile %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %shell %store %sx %system %tb %tensorflow_version %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode Available cell magics: %%! %%HTML %%SVG %%bash %%bigquery %%capture %%debug %%file %%html %%javascript %%js %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%shell %%svg %%sx %%system %%time %%timeit %%writefile Automagic is ON, % prefix IS NOT needed for line magics. Next, you will learn another powerful feature in Colab to set the program variables at runtime. Colab provides a very useful utility called Forms that allows you to accept inputs from the user at runtime. Let us now move on to see how to add forms to your notebook. In an earlier lesson, you used the following code to create a time delay − import time print(time.ctime()) time.sleep(5) print (time.ctime()) Suppose, you want a user set time delay instead of a fixed delay of 5 seconds. For this, you can add a Form to the Code cell to accept the sleep time. Open a new notebook. Click on the Options (vertically-dotted) menu. A popup menu shows up as seen in the screenshot below − Now, select Add a form option. It will add the form to your Code cell with a Default title as seen in the screenshot here − To change the title of the form, click on the Settings button (pencil icon on the right). It will pop up a settings screen as shown here: Change the form title to “Form” and save the form. You may use some other name of your choice. Notice that it adds the @title to your code cell. You may explore other options on the above screen at a later time. In the next section, we will learn how add input fields to the form. To add a form field, click the Options menu in the Code cell, click on the Form to reveal the submenus. The screen will look as shown below − Select Add a form field menu option. A dialog pops up as seen here − Leave the Form field type to input. Change the Variable name to sleeptime and set the Variable type to integer. Save the changes by clicking the Save button. Your screen will now look like the following with the sleeptime variable added into the code. Next, let us see how to test the form by adding some code that uses the sleeptime variable. Add a new Code cell underneath the form cell. Use the code given below − import time print(time.ctime()) time.sleep(sleeptime) print (time.ctime()) You have used this code in the earlier lesson. It prints the current time, waits for a certain amount of time and prints a new timestamp. The amount of time that the program waits is set in the variable called sleeptime. Now, go back to the Form Cell and type in a value of 2 for the sleeptime. Select the following menu − Runtime / Run all This runs the entire notebook. You can see an output screen as shown below. Notice that it has taken your input value of 2 for the sleeptime To accept a text input in your form, enter the following code in a new code cell. name = 'Tutorialspoint' #@param {type:"string"} print(name) Now, if you run the Code cell, whatever the name you set in the form would be printed on the screen. By default, the following output would appear on the screen. Tutorialspoint Note that you may use the menu options as shown for the integer input to create a Text input field. To add a dropdown list to your form, use the following code − color = 'green' #@param ["red", "green", "blue"] print(color) This creates a dropdown list with three values - red, green and blue. The default selection is green. The dropdown list is shown in the screenshot below − Colab Form allows you to accept dates in your code with validations. Use the following code to input date in your code. #@title Date fields date_input = '2019-06-03' #@param {type:"date"} print(date_input) The Form screen looks like the following. Try inputting a wrong date value and observe the validations. So far you have learned how to use Colab for creating and executing Jupyter notebooks with your Python code. In the next chapter, we will see how to install popular ML libraries in your notebook so that you can use those in your Python code. Colab supports most of machine learning libraries available in the market. In this chapter, let us take a quick overview of how to install these libraries in your Colab notebook. To install a library, you can use either of these options − !pip install or !apt-get install Keras, written in Python, runs on top of TensorFlow, CNTK, or Theano. It enables easy and fast prototyping of neural network applications. It supports both convolutional networks (CNN) and recurrent networks, and also their combinations. It seamlessly supports GPU. To install Keras, use the following command − !pip install -q keras PyTorch is ideal for developing deep learning applications. It is an optimized tensor library and is GPU enabled. To install PyTorch, use the following command − !pip3 install torch torchvision Apache MxNet is another flexible and efficient library for deep learning. To install MxNet execute the following commands − !apt install libnvrtc8.0 !pip install mxnet-cu80 OpenCV is an open source computer vision library for developing machine learning applications. It has more than 2500 optimized algorithms which support several applications such as recognizing faces, identifying objects, tracking moving objects, stitching images, and so on. Giants like Google, Yahoo, Microsoft, Intel, IBM, Sony, Honda, Toyota use this library. This is highly suited for developing real-time vision applications. To install OpenCV use the following command − !apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python XGBoost is a distributed gradient boosting library that runs on major distributed environments such as Hadoop. It is highly efficient, flexible and portable. It implements ML algorithms under the Gradient Boosting framework. To install XGBoost, use the following command − !pip install -q xgboost==0.4a30 Graphviz is an open source software for graph visualizations. It is used for visualization in networking, bioinformatics, database design, and for that matter in many domains where a visual interface of the data is desired. To install GraphViz, use the following command − !apt-get -qq install -y graphviz && pip install -q pydot By this time, you have learned to create Jupyter notebooks containing popular machine learning libraries. You are now ready to develop your machine learning models. This requires high processing power. Colab provides free GPU for your notebooks. In the next chapter, we will learn how to enable GPU for your notebook. Google provides the use of free GPU for your Colab notebooks. To enable GPU in your notebook, select the following menu options − Runtime / Change runtime type You will see the following screen as the output − Select GPU and your notebook would use the free GPU provided in the cloud during processing. To get the feel of GPU processing, try running the sample application from MNIST tutorial that you cloned earlier. !python3 "/content/drive/My Drive/app/mnist_cnn.py" Try running the same Python file without the GPU enabled. Did you notice the difference in speed of execution? You can easily check if the GPU is enabled by executing the following code − import tensorflow as tf tf.test.gpu_device_name() If the GPU is enabled, it will give the following output − '/device:GPU:0' If you are curious to know the devices used during the execution of your notebook in the cloud, try the following code − from tensorflow.python.client import device_lib device_lib.list_local_devices() You will see the output as follows − [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 1734904979049303143, name: "/device:XLA_CPU:0" device_type: "XLA_CPU" memory_limit: 17179869184 locality { } incarnation: 16069148927281628039 physical_device_desc: "device: XLA_CPU device", name: "/device:XLA_GPU:0" device_type: "XLA_GPU" memory_limit: 17179869184 locality { } incarnation: 16623465188569787091 physical_device_desc: "device: XLA_GPU device", name: "/device:GPU:0" device_type: "GPU" memory_limit: 14062547764 locality { bus_id: 1 links { } } incarnation: 6674128802944374158 physical_device_desc: "device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5"] To see the memory resources available for your process, type the following command − !cat /proc/meminfo You will see the following output − MemTotal: 13335276 kB MemFree: 7322964 kB MemAvailable: 10519168 kB Buffers: 95732 kB Cached: 2787632 kB SwapCached: 0 kB Active: 2433984 kB Inactive: 3060124 kB Active(anon): 2101704 kB Inactive(anon): 22880 kB Active(file): 332280 kB Inactive(file): 3037244 kB Unevictable: 0 kB Mlocked: 0 kB SwapTotal: 0 kB SwapFree: 0 kB Dirty: 412 kB Writeback: 0 kB AnonPages: 2610780 kB Mapped: 838200 kB Shmem: 23436 kB Slab: 183240 kB SReclaimable: 135324 kB SUnreclaim: 47916 kBKernelStack: 4992 kB PageTables: 13600 kB NFS_Unstable: 0 kB Bounce: 0 kB WritebackTmp: 0 kB CommitLimit: 6667636 kB Committed_AS: 4801380 kB VmallocTotal: 34359738367 kB VmallocUsed: 0 kB VmallocChunk: 0 kB AnonHugePages: 0 kB ShmemHugePages: 0 kB ShmemPmdMapped: 0 kB HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 HugePages_Surp: 0 Hugepagesize: 2048 kB DirectMap4k: 303092 kB DirectMap2M: 5988352 kB DirectMap1G: 9437184 kB You are now all set for the development of machine learning models in Python using Google Colab. Google Colab is a powerful platform for learning and quickly developing machine learning models in Python. It is based on Jupyter notebook and supports collaborative development. The team members can share and concurrently edit the notebooks, even remotely. The notebooks can also be published on GitHub and shared with the general public. Colab supports many popular ML libraries such as PyTorch, TensorFlow, Keras and OpenCV. The restriction as of today is that it does not support R or Scala yet. There is also a limitation to sessions and size. Considering the benefits, these are small sacrifices one needs to make. 20 Lectures 2.5 hours Asif Hussain 7 Lectures 1 hours Aditya Kulkarni 33 Lectures 2.5 hours Sasha Miller 22 Lectures 1.5 hours Zach Miller 16 Lectures 1.5 hours Sasha Miller 23 Lectures 2.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2347, "s": 2041, "text": "Google is quite aggressive in AI research. Over many years, Google developed AI framework called TensorFlow and a development tool called Colaboratory. Today TensorFlow is open-sourced and since 2017, Google made Colaboratory free for public use. Colaboratory is now known as Google Colab or simply Colab." }, { "code": null, "e": 2742, "s": 2347, "text": "Another attractive feature that Google offers to the developers is the use of GPU. Colab supports GPU and it is totally free. The reasons for making it free for public could be to make its software a standard in the academics for teaching machine learning and data science. It may also have a long term perspective of building a customer base for Google Cloud APIs which are sold per-use basis." }, { "code": null, "e": 2870, "s": 2742, "text": "Irrespective of the reasons, the introduction of Colab has eased the learning and development of machine learning applications." }, { "code": null, "e": 2905, "s": 2870, "text": "So, let us get started with Colab." }, { "code": null, "e": 3369, "s": 2905, "text": "If you have used Jupyter notebook previously, you would quickly learn to use Google Colab. To be precise, Colab is a free Jupyter notebook environment that runs entirely in the cloud. Most importantly, it does not require a setup and the notebooks that you create can be simultaneously edited by your team members - just the way you edit documents in Google Docs. Colab supports many popular machine learning libraries which can be easily loaded in your notebook." }, { "code": null, "e": 3436, "s": 3369, "text": "As a programmer, you can perform the following using Google Colab." }, { "code": null, "e": 3469, "s": 3436, "text": "Write and execute code in Python" }, { "code": null, "e": 3502, "s": 3469, "text": "Write and execute code in Python" }, { "code": null, "e": 3558, "s": 3502, "text": "Document your code that supports mathematical equations" }, { "code": null, "e": 3614, "s": 3558, "text": "Document your code that supports mathematical equations" }, { "code": null, "e": 3644, "s": 3614, "text": "Create/Upload/Share notebooks" }, { "code": null, "e": 3674, "s": 3644, "text": "Create/Upload/Share notebooks" }, { "code": null, "e": 3717, "s": 3674, "text": "Import/Save notebooks from/to Google Drive" }, { "code": null, "e": 3760, "s": 3717, "text": "Import/Save notebooks from/to Google Drive" }, { "code": null, "e": 3797, "s": 3760, "text": "Import/Publish notebooks from GitHub" }, { "code": null, "e": 3834, "s": 3797, "text": "Import/Publish notebooks from GitHub" }, { "code": null, "e": 3876, "s": 3834, "text": "Import external datasets e.g. from Kaggle" }, { "code": null, "e": 3918, "s": 3876, "text": "Import external datasets e.g. from Kaggle" }, { "code": null, "e": 3963, "s": 3918, "text": "Integrate PyTorch, TensorFlow, Keras, OpenCV" }, { "code": null, "e": 4008, "s": 3963, "text": "Integrate PyTorch, TensorFlow, Keras, OpenCV" }, { "code": null, "e": 4041, "s": 4008, "text": "Free Cloud service with free GPU" }, { "code": null, "e": 4074, "s": 4041, "text": "Free Cloud service with free GPU" }, { "code": null, "e": 4203, "s": 4074, "text": "In this chapter, you will create and execute your first trivial notebook. Follow the steps that have been given wherever needed." }, { "code": null, "e": 4362, "s": 4203, "text": "Note − As Colab implicitly uses Google Drive for storing your notebooks, ensure that you are logged in to your Google Drive account before proceeding further." }, { "code": null, "e": 4550, "s": 4362, "text": "Step 1 − Open the following URL in your browser − https://colab.research.google.com Your browser would display the following screen (assuming that you are logged into your Google Drive) −" }, { "code": null, "e": 4687, "s": 4550, "text": "Step 2 − Click on the NEW PYTHON 3 NOTEBOOK link at the bottom of the screen. A new notebook would open up as shown in the screen below." }, { "code": null, "e": 4852, "s": 4687, "text": "As you might have noticed, the notebook interface is quite similar to the one provided in Jupyter. There is a code window in which you would enter your Python code." }, { "code": null, "e": 5026, "s": 4852, "text": "By default, the notebook uses the naming convention UntitledXX.ipynb. To rename the notebook, click on this name and type in the desired name in the edit box as shown here −" }, { "code": null, "e": 5190, "s": 5026, "text": "We will call this notebook as MyFirstColabNotebook. So type in this name in the edit box and hit ENTER. The notebook will acquire the name that you have given now." }, { "code": null, "e": 5266, "s": 5190, "text": "You will now enter a trivial Python code in the code window and execute it." }, { "code": null, "e": 5329, "s": 5266, "text": "Enter the following two Python statements in the code window −" }, { "code": null, "e": 5362, "s": 5329, "text": "import time\nprint(time.ctime())\n" }, { "code": null, "e": 5439, "s": 5362, "text": "To execute the code, click on the arrow on the left side of the code window." }, { "code": null, "e": 5522, "s": 5439, "text": "After a while, you will see the output underneath the code window, as shown here −" }, { "code": null, "e": 5548, "s": 5522, "text": "Mon Jun 17 05:58:40 2019\n" }, { "code": null, "e": 5642, "s": 5548, "text": "You can clear the output anytime by clicking the icon on the left side of the output display." }, { "code": null, "e": 5713, "s": 5642, "text": "To add more code to your notebook, select the following menu options −" }, { "code": null, "e": 5733, "s": 5713, "text": "Insert / Code Cell\n" }, { "code": null, "e": 5924, "s": 5733, "text": "Alternatively, just hover the mouse at the bottom center of the Code cell. When the CODE and TEXT buttons appear, click on the CODE to add a new cell. This is shown in the screenshot below −" }, { "code": null, "e": 6051, "s": 5924, "text": "A new code cell will be added underneath the current cell. Add the following two statements in the newly created code window −" }, { "code": null, "e": 6087, "s": 6051, "text": "time.sleep(5)\nprint (time.ctime())\n" }, { "code": null, "e": 6150, "s": 6087, "text": "Now, if you run this cell, you will see the following output −" }, { "code": null, "e": 6176, "s": 6150, "text": "Mon Jun 17 04:50:27 2019\n" }, { "code": null, "e": 6399, "s": 6176, "text": "Certainly, the time difference between the two time strings is not 5 seconds. This is obvious as you did take some time to insert the new code. Colab allows you to run all code inside your notebook without an interruption." }, { "code": null, "e": 6501, "s": 6399, "text": "To run the entire code in your notebook without an interruption, execute the following menu options −" }, { "code": null, "e": 6533, "s": 6501, "text": "Runtime / Reset and run all...\n" }, { "code": null, "e": 6578, "s": 6533, "text": "It will give you the output as shown below −" }, { "code": null, "e": 6658, "s": 6578, "text": "Note that the time difference between the two outputs is now exactly 5 seconds." }, { "code": null, "e": 6743, "s": 6658, "text": "The above action can also be initiated by executing the following two menu options −" }, { "code": null, "e": 6773, "s": 6743, "text": "Runtime / Restart runtime...\n" }, { "code": null, "e": 6776, "s": 6773, "text": "or" }, { "code": null, "e": 6811, "s": 6776, "text": "Runtime / Restart all runtimes...\n" }, { "code": null, "e": 6823, "s": 6811, "text": "Followed by" }, { "code": null, "e": 6842, "s": 6823, "text": "Runtime / Run all\n" }, { "code": null, "e": 6995, "s": 6842, "text": "Study the different menu options under the Runtime menu to get yourself acquainted with the various options available to you for executing the notebook." }, { "code": null, "e": 7294, "s": 6995, "text": "When your notebook contains a large number of code cells, you may come across situations where you would like to change the order of execution of these cells. You can do so by selecting the cell that you want to move and clicking the UP CELL or DOWN CELL buttons shown in the following screenshot −" }, { "code": null, "e": 7385, "s": 7294, "text": "You may click the buttons multiple times to move the cell for more than a single position." }, { "code": null, "e": 7641, "s": 7385, "text": "During the development of your project, you may have introduced a few now-unwanted cells in your notebook. You can remove such cells from your project easily with a single click. Click on the vertical-dotted icon at the top right corner of your code cell." }, { "code": null, "e": 7711, "s": 7641, "text": "Click on the Delete cell option and the current cell will be deleted." }, { "code": null, "e": 7815, "s": 7711, "text": "Now, as you have learned how to run a trivial notebook, let us explore the other capabilities of Colab." }, { "code": null, "e": 8248, "s": 7815, "text": "As the code cell supports full Python syntax, you may use Python comments in the code window to describe your code. However, many a time you need more than a simple text based comments to illustrate the ML algorithms. ML heavily uses mathematics and to explain those terms and equations to your readers you need an editor that supports LaTex - a language for mathematical representations. Colab provides Text Cells for this purpose." }, { "code": null, "e": 8354, "s": 8248, "text": "A text cell containing few mathematical equations typically used in ML is shown in the screenshot below −" }, { "code": null, "e": 8442, "s": 8354, "text": "As we move ahead in this chapter, we will see the code for generating the above output." }, { "code": null, "e": 8627, "s": 8442, "text": "Text Cells are formatted using markdown - a simple markup language. Let us now see you how to add text cells to your notebook and add to it some text containing mathematical equations." }, { "code": null, "e": 8716, "s": 8627, "text": "Let us look into few examples of markup language syntax to demonstrate its capabilities." }, { "code": null, "e": 8761, "s": 8716, "text": "Type in the following text in the Text cell." }, { "code": null, "e": 8823, "s": 8761, "text": "This is **bold**.\nThis is *italic*.\nThis is ~strikethrough~.\n" }, { "code": null, "e": 8918, "s": 8823, "text": "The output of the above commands is rendered on the right hand side of the Cell as shown here." }, { "code": null, "e": 9012, "s": 8918, "text": "Add a Text Cell to your notebook and enter the following markdown syntax in the text window −" }, { "code": null, "e": 9035, "s": 9012, "text": "$\\sqrt{3x-1}+(1+x)^2$\n" }, { "code": null, "e": 9180, "s": 9035, "text": "You will see the immediate rendering of the markdown code in the right hand side panel of the text cell. This is shown in the screenshot below −" }, { "code": null, "e": 9281, "s": 9180, "text": "Hit Enter and the markdown code disappears from the text cell and only the rendered output is shown." }, { "code": null, "e": 9342, "s": 9281, "text": "Let us try another more complicated equation as shown here −" }, { "code": null, "e": 9387, "s": 9342, "text": "$e^x = \\sum_{i = 0}^\\infty \\frac{1}{i!}x^i$\n" }, { "code": null, "e": 9447, "s": 9387, "text": "The rendered output is shown here for your quick reference." }, { "code": null, "e": 9522, "s": 9447, "text": "Here is the code for the sample equations shown in an earlier screenshot −" }, { "code": null, "e": 10160, "s": 9522, "text": "Constraints are\n - $3x_1 + 6x_2 + x_3 =< 28$\n - $7x_1 + 3x_2 + 2x_3 =< 37$\n - $4x_1 + 5x_2 + 2x_3 =< 19$\n - $x_1,x_2,x_3 >=0 $\n\nThe trial vector is calculated as follows:\n- $u_i(t) = x_i(t) + \\beta(\\hat{x}(t) − x_i(t)) + \\beta \\sum_{k = 1}^{n_v}(x_{i1,k}(t) − x_{i2,k}(t))$\n$f(x_1, x_2) = 20 + e - 20exp(-0.2 \\sqrt {\\frac {1}{n} (x_1^2 + x_2^2)}) - exp (\\frac {1}{n}(cos(2\\pi x_1) + cos(2\\pi x_2))$\n\n$x ∈ [-5, 5]$\n>$A_{m,n} =\n \\begin{pmatrix}\n a_{1,1} > a_{1,2} > \\cdots > a_{1,n} \\\\\n a_{2,1} > a_{2,2} > \\cdots > a_{2,n} \\\\\n \\vdots > \\vdots > \\ddots > \\vdots \\\\\n a_{m,1} > a_{m,2} > \\cdots > a_{m,n}\n \\end{pmatrix}$\n" }, { "code": null, "e": 10284, "s": 10160, "text": "Describing full markup syntax is beyond the scope of this tutorial. In the next chapter, we will see how to save your work." }, { "code": null, "e": 10379, "s": 10284, "text": "Colab allows you to save your work to Google Drive or even directly to your GitHub repository." }, { "code": null, "e": 10495, "s": 10379, "text": "Colab allows you to save your work to your Google Drive. To save your notebook, select the following menu options −" }, { "code": null, "e": 10527, "s": 10495, "text": "File / Save a copy in Drive...\n" }, { "code": null, "e": 10563, "s": 10527, "text": "You will see the following screen −" }, { "code": null, "e": 10694, "s": 10563, "text": "The action will create a copy of your notebook and save it to your drive. Later on you may rename the copy to your choice of name." }, { "code": null, "e": 10790, "s": 10694, "text": "You may also save your work to your GitHub repository by selecting the following menu options −" }, { "code": null, "e": 10823, "s": 10790, "text": "File / Save a copy in GitHub...\n" }, { "code": null, "e": 10906, "s": 10823, "text": "The menu selection is shown in the following screenshot for your quick reference −" }, { "code": null, "e": 10970, "s": 10906, "text": "You will have to wait until you see the login screen to GitHub." }, { "code": null, "e": 11106, "s": 10970, "text": "Now, enter your credentials. If you do not have a repository, create a new one and save your project as shown in the screenshot below −" }, { "code": null, "e": 11177, "s": 11106, "text": "In the next chapter, we will learn how to share your work with others." }, { "code": null, "e": 11311, "s": 11177, "text": "To share the notebook that you have created with other co-developers, you may share the copy that you have made in your Google Drive." }, { "code": null, "e": 11402, "s": 11311, "text": "To publish the notebook to general audience, you may share it from your GitHub repository." }, { "code": null, "e": 11583, "s": 11402, "text": "There is one more way to share your work and that is by clicking on the SHARE link at the top right hand corner of your Colab notebook. This will open the share box as shown here −" }, { "code": null, "e": 11771, "s": 11583, "text": "You may enter the email IDs of people with whom you would like to share the current document. You can set the kind of access by selecting from the three options shown in the above screen." }, { "code": null, "e": 11896, "s": 11771, "text": "Click on the Get shareable link option to get the URL of your notebook. You will find options for whom to share as follows −" }, { "code": null, "e": 11922, "s": 11896, "text": "Specified group of people" }, { "code": null, "e": 11948, "s": 11922, "text": "Specified group of people" }, { "code": null, "e": 11980, "s": 11948, "text": "Colleagues in your organization" }, { "code": null, "e": 12012, "s": 11980, "text": "Colleagues in your organization" }, { "code": null, "e": 12033, "s": 12012, "text": "Anyone with the link" }, { "code": null, "e": 12054, "s": 12033, "text": "Anyone with the link" }, { "code": null, "e": 12076, "s": 12054, "text": "All public on the web" }, { "code": null, "e": 12098, "s": 12076, "text": "All public on the web" }, { "code": null, "e": 12283, "s": 12098, "text": "Now. you know how to create/execute/save/share a notebook. In the Code cell, we used Python so far. The code cell can also be used for invoking system commands. This is explained next." }, { "code": null, "e": 12384, "s": 12283, "text": "Jupyter includes shortcuts for many common system operations. Colab Code cell supports this feature." }, { "code": null, "e": 12461, "s": 12384, "text": "Enter the following code in the Code cell that uses the system command echo." }, { "code": null, "e": 12569, "s": 12461, "text": "message = 'A Great Tutorial on Colab by Tutorialspoint!'\ngreeting = !echo -e '$message\\n$message'\ngreeting\n" }, { "code": null, "e": 12631, "s": 12569, "text": "Now, if you run the cell, you will see the following output −" }, { "code": null, "e": 12729, "s": 12631, "text": "['A Great Tutorial on Colab by Tutorialspoint!', 'A Great Tutorial on Colab by Tutorialspoint!']\n" }, { "code": null, "e": 12857, "s": 12729, "text": "Let us look into another example that loads the dataset from a remote server. Type in the following command in your Code cell −" }, { "code": null, "e": 12968, "s": 12857, "text": "!wget http://mlr.cs.umass.edu/ml/machine-learning-databases/adult/adult.data -P \"/content/drive/My Drive/app\"\n" }, { "code": null, "e": 13026, "s": 12968, "text": "If you run the code, you would see the following output −" }, { "code": null, "e": 13575, "s": 13026, "text": "--2019-06-20 10:09:53-- http://mlr.cs.umass.edu/ml/machine-learning-databases/adult/adult.data\nResolving mlr.cs.umass.edu (mlr.cs.umass.edu)... 128.119.246.96\nConnecting to mlr.cs.umass.edu (mlr.cs.umass.edu)|128.119.246.96|:80... connected. \nHTTP request sent, awaiting response... 200 OK \nLength: 3974305 (3.8M) [text/plain] \nSaving to: ‘/content/drive/My Drive/app/adult.data.1’\n\nadult.data.1 100%[===================>] 3.79M 1.74MB/s in 2.2s\n\n2019-06-20 10:09:56 (1.74 MB/s) - ‘/content/drive/My Drive/app/adult.data.1’ saved [3974305/3974305]\n" }, { "code": null, "e": 13777, "s": 13575, "text": "As the message says, the adult.data.1 file is now added to your drive. You can verify this by examining the folder contents of your drive. Alternatively, type in the following code in a new Code cell −" }, { "code": null, "e": 13874, "s": 13777, "text": "import pandas as pd\ndata = pd.read_csv(\"/content/drive/My Drive/app/adult.data.1\")\ndata.head(5)\n" }, { "code": null, "e": 13931, "s": 13874, "text": "Run the code now and you will see the following output −" }, { "code": null, "e": 14160, "s": 13931, "text": "Likewise, most of the system commands can be invoked in your code cell by prepending the command with an Exclamation Mark (!). Let us look into another example before giving out the complete list of commands that you can invoke." }, { "code": null, "e": 14324, "s": 14160, "text": "You can clone the entire GitHub repository into Colab using the gitcommand. For example, to clone the keras tutorial, type the following command in the Code cell −" }, { "code": null, "e": 14384, "s": 14324, "text": "!git clone https://github.com/wxs/keras-mnist-tutorial.git\n" }, { "code": null, "e": 14460, "s": 14384, "text": "After a successful run of the command, you would see the following output −" }, { "code": null, "e": 14641, "s": 14460, "text": "Cloning into 'keras-mnist-tutorial'...\nremote: Enumerating objects: 26, done.\nremote: Total 26 (delta 0), reused 0 (delta 0), pack-reused 26\nUnpacking objects: 100% (26/26), done.\n" }, { "code": null, "e": 14833, "s": 14641, "text": "Once the repo is cloned, locate a Jupyter project (e.g. MINST in keras.ipyab) in it, right-click on the file name and select Open With / Colaboratory menu option to open the project in Colab." }, { "code": null, "e": 14915, "s": 14833, "text": "To get a list of shortcuts for common operations, execute the following command −" }, { "code": null, "e": 14925, "s": 14915, "text": "!ls /bin\n" }, { "code": null, "e": 14985, "s": 14925, "text": "You will see the list in the output window as shown below −" }, { "code": null, "e": 16682, "s": 14985, "text": "bash* journalctl* sync*\nbunzip2* kill* systemctl*\nbzcat* kmod* systemd@\nbzcmp@ less* systemd-ask-password*\nbzdiff* lessecho* systemd-escape*\nbzegrep@ lessfile@ systemd-hwdb*\nbzexe* lesskey* systemd-inhibit*\nbzfgrep@ lesspipe* systemd-machine-id-setup*\nbzgrep* ln* systemd-notify*\nbzip2* login* systemd-sysusers*\nbzip2recover* loginctl* systemd-tmpfiles*\nbzless@ ls* systemd-tty-ask-password-agent*\nbzmore* lsblk* tar*\ncat* lsmod@ tempfile*\nchgrp* mkdir* touch*\nchmod* mknod* true*\nchown* mktemp* udevadm*\ncp* more* ulockmgr_server*\ndash* mount* umount*\ndate* mountpoint* uname*\ndd* mv* uncompress*\ndf* networkctl* vdir*\ndir* nisdomainname@ wdctl*\ndmesg* pidof@ which*\ndnsdomainname@ ps* ypdomainname@\ndomainname@ pwd* zcat*\necho* rbash@ zcmp*\negrep* readlink* zdiff*\nfalse* rm* zegrep*\nfgrep* rmdir* zfgrep*\nfindmnt* run-parts* zforce*\nfusermount* sed* zgrep*\ngrep* sh@ zless*\ngunzip* sh.distrib@ zmore*\ngzexe* sleep* znew*\ngzip* stty*\nhostname* su*\n" }, { "code": null, "e": 16833, "s": 16682, "text": "Execute any of these commands as we have done for echo and wget. In the next chapter, we shall see how to execute your previously created Python code." }, { "code": null, "e": 17083, "s": 16833, "text": "Suppose, you already have some Python code developed that is stored in your Google Drive. Now, you will like to load this code in Colab for further modifications. In this chapter, we will see how to load and run the code stored in your Google Drive." }, { "code": null, "e": 17108, "s": 17083, "text": "Tools / Command palette\n" }, { "code": null, "e": 17172, "s": 17108, "text": "You will see the list of commands as shown in this screenshot −" }, { "code": null, "e": 17345, "s": 17172, "text": "Type a few letters like “m” in the search box to locate the mount command. Select Mount Drive command from the list. The following code would be inserted in your Code cell." }, { "code": null, "e": 17451, "s": 17345, "text": "# Run this cell to mount your Google Drive.\nfrom google.colab import drive\ndrive.mount('/content/drive')\n" }, { "code": null, "e": 17573, "s": 17451, "text": "If you run this code, you will be asked to enter the authentication code. The corresponding screen looks as shown below −" }, { "code": null, "e": 17701, "s": 17573, "text": "Open the above URL in your browser. You will be asked to login to your Google account. Now, you will see the following screen −" }, { "code": null, "e": 17771, "s": 17701, "text": "If you grant the permissions, you will receive your code as follows −" }, { "code": null, "e": 17900, "s": 17771, "text": "Cut-n-paste this code in the Code cell and hit ENTER. After a while, the drive will be mounted as seen in the screenshot below −" }, { "code": null, "e": 17963, "s": 17900, "text": "Now, you are ready to use the contents of your drive in Colab." }, { "code": null, "e": 18036, "s": 17963, "text": "You can list the contents of the drive using the ls command as follows −" }, { "code": null, "e": 18083, "s": 18036, "text": "!ls \"/content/drive/My Drive/Colab Notebooks\"\n" }, { "code": null, "e": 18207, "s": 18083, "text": "This command will list the contents of your Colab Notebooks folder. The sample output of my drive contents are shown here −" }, { "code": null, "e": 18348, "s": 18207, "text": "Greeting.ipynb hello.py LogisticRegressionCensusData.ipynb LogisticRegressionDigitalOcean.ipynb MyFirstColabNotebook.ipynb SamplePlot.ipynb\n" }, { "code": null, "e": 18490, "s": 18348, "text": "Now, let us say that you want to run a Python file called hello.py stored in your Google Drive. Type the following command in the Code cell −" }, { "code": null, "e": 18551, "s": 18490, "text": "!python3 \"/content/drive/My Drive/Colab Notebooks/hello.py\"\n" }, { "code": null, "e": 18612, "s": 18551, "text": "The contents of hello.py are given here for your reference −" }, { "code": null, "e": 18649, "s": 18612, "text": "print(\"Welcome to TutorialsPoint!\")\n" }, { "code": null, "e": 18689, "s": 18649, "text": "You will now see the following output −" }, { "code": null, "e": 18717, "s": 18689, "text": "Welcome to TutorialsPoint!\n" }, { "code": null, "e": 18823, "s": 18717, "text": "Besides the text output, Colab also supports the graphical outputs. We will see this in the next chapter." }, { "code": null, "e": 18917, "s": 18823, "text": "Colab also supports rich outputs such as charts. Type in the following code in the Code cell." }, { "code": null, "e": 19162, "s": 18917, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\ny = np.random.randn(100)\nx = [x for x in range(len(y))]\n\nplt.plot(x, y, '-')\nplt.fill_between(x, y, 200, where = (y > 195), facecolor='g', alpha=0.6)\n\nplt.title(\"Sample Plot\")\nplt.show()\n" }, { "code": null, "e": 19224, "s": 19162, "text": "Now, if you run the code, you will see the following output −" }, { "code": null, "e": 19407, "s": 19224, "text": "Note that the graphical output is shown in the output section of the Code cell. Likewise, you will be able to create and display several types of charts throughout your program code." }, { "code": null, "e": 19551, "s": 19407, "text": "Now, as you have got familiar with the basics of Colab, let us move on to the features in Colab that makes your Python code development easier." }, { "code": null, "e": 19743, "s": 19551, "text": "The present day developers rely heavily on context-sensitive help to the language and library syntaxes. That is why the IDEs are widely used. The Colab notebook editor provides this facility." }, { "code": null, "e": 19900, "s": 19743, "text": "In this chapter, let us see how to ask for context-sensitive help while writing Python code in Colab. Follow the steps that have been given wherever needed." }, { "code": null, "e": 19979, "s": 19900, "text": "Step 1 − Open a new notebook and type in the following code in the Code cell −" }, { "code": null, "e": 19993, "s": 19979, "text": "import torch\n" }, { "code": null, "e": 20134, "s": 19993, "text": "Step 2 − Run the code by clicking on the Run icon in the left panel of the Code cell. Add another Code cell and type in the following code −" }, { "code": null, "e": 20151, "s": 20134, "text": "Tensor = torch.\n" }, { "code": null, "e": 20505, "s": 20151, "text": "At this point, suppose you have forgotten what are the various functions available in torch module. You can ask for the context-sensitive help on function names by hitting the TAB key. Note the presence of the DOT after the torch keyword. Without this DOT, you will not see the context help. Your screen would look like as shown in the screenshot here −" }, { "code": null, "e": 20582, "s": 20505, "text": "Now, select the desired function from the list and proceed with your coding." }, { "code": null, "e": 20670, "s": 20582, "text": "Colab gives you the documentation on any function or class as a context-sensitive help." }, { "code": null, "e": 20716, "s": 20670, "text": "Type the following code in your code window −" }, { "code": null, "e": 20737, "s": 20716, "text": "Tensor = torch.cos(\n" }, { "code": null, "e": 20912, "s": 20737, "text": "Now, hit TAB and you will see the documentation on cos in the popup window as shown in the screenshot here. Note that you need to type in open parenthesis before hitting TAB." }, { "code": null, "e": 21039, "s": 20912, "text": "In the next chapter, we will see Magics in Colab that lets us to do more powerful things than what we did with system aliases." }, { "code": null, "e": 21122, "s": 21039, "text": "Magics is a set of system commands that provide a mini extensive command language." }, { "code": null, "e": 21148, "s": 21122, "text": "Magics are of two types −" }, { "code": null, "e": 21160, "s": 21148, "text": "Line magics" }, { "code": null, "e": 21172, "s": 21160, "text": "Line magics" }, { "code": null, "e": 21184, "s": 21172, "text": "Cell magics" }, { "code": null, "e": 21196, "s": 21184, "text": "Cell magics" }, { "code": null, "e": 21342, "s": 21196, "text": "The line magics as the name indicates that it consists of a single line of command, while the cell magic covers the entire body of the code cell." }, { "code": null, "e": 21493, "s": 21342, "text": "In case of line magics, the command is prepended with a single % character and in the case of cell magics, it is prepended with two % characters (%%)." }, { "code": null, "e": 21553, "s": 21493, "text": "Let us look into some examples of both to illustrate these." }, { "code": null, "e": 21597, "s": 21553, "text": "Type the following code in your code cell −" }, { "code": null, "e": 21604, "s": 21597, "text": "%ldir\n" }, { "code": null, "e": 21677, "s": 21604, "text": "You will see the contents of your local directory, something like this -" }, { "code": null, "e": 21770, "s": 21677, "text": "drwxr-xr-x 3 root 4096 Jun 20 10:05 drive/\ndrwxr-xr-x 1 root 4096 May 31 16:17 sample_data/\n" }, { "code": null, "e": 21798, "s": 21770, "text": "Try the following command −" }, { "code": null, "e": 21808, "s": 21798, "text": "%history\n" }, { "code": null, "e": 21890, "s": 21808, "text": "This presents the complete history of commands that you have previously executed." }, { "code": null, "e": 21937, "s": 21890, "text": "Type in the following code in your code cell −" }, { "code": null, "e": 22025, "s": 21937, "text": "%%html\n<marquee style='width: 50%; color: Green;'>Welcome to Tutorialspoint!</marquee>\n" }, { "code": null, "e": 22127, "s": 22025, "text": "Now, if you run the code and you will see the scrolling welcome message on the screen as shown here −" }, { "code": null, "e": 22177, "s": 22127, "text": "The following code will add SVG to your document." }, { "code": null, "e": 22613, "s": 22177, "text": "%%html\n<svg xmlns=\"https://www.w3.org/2000/svg\" viewBox=\"0 0 600 400\" width=\"400\" height=\"400\">\n <rect x=\"10\" y=\"00\" width=\"300\" height=\"100\" rx=\"0\" style=\"fill:orange; stroke:black; fill-opacity:1.0\" />\n <rect x=\"10\" y=\"100\" width=\"300\" height=\"100\" rx=\"0\" style=\"fill:white; stroke:black; fill-opacity:1.0;\" />\n <rect x=\"10\" y=\"200\" width=\"300\" height=\"100\" rx=\"0\" style=\"fill:green; stroke:black; fill-opacity:1.0;\" />\n</svg>\n" }, { "code": null, "e": 22671, "s": 22613, "text": "If you run the code, you would see the following output −" }, { "code": null, "e": 22747, "s": 22671, "text": "To get a complete list of supported magics, execute the following command −" }, { "code": null, "e": 22757, "s": 22747, "text": "%lsmagic\n" }, { "code": null, "e": 22793, "s": 22757, "text": "You will see the following output −" }, { "code": null, "e": 23863, "s": 22793, "text": "Available line magics:\n%alias %alias_magic %autocall %automagic %autosave %bookmark %cat %cd %clear\n%colors %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit\n%env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext\n%loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro\n%magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef\n%pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %profile %prun\n%psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall\n%rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save\n%sc %set_env %shell %store %sx %system %tb %tensorflow_version %time %timeit\n%unalias %unload_ext %who %who_ls %whos %xdel %xmode\n\nAvailable cell magics:\n%%! %%HTML %%SVG %%bash %%bigquery %%capture %%debug %%file %%html %%javascript\n%%js %%latex %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script\n%%sh %%shell %%svg %%sx %%system %%time %%timeit %%writefile\n\nAutomagic is ON, % prefix IS NOT needed for line magics.\n" }, { "code": null, "e": 23959, "s": 23863, "text": "Next, you will learn another powerful feature in Colab to set the program variables at runtime." }, { "code": null, "e": 24129, "s": 23959, "text": "Colab provides a very useful utility called Forms that allows you to accept inputs from the user at runtime. Let us now move on to see how to add forms to your notebook." }, { "code": null, "e": 24204, "s": 24129, "text": "In an earlier lesson, you used the following code to create a time delay −" }, { "code": null, "e": 24272, "s": 24204, "text": "import time\nprint(time.ctime())\ntime.sleep(5)\nprint (time.ctime())\n" }, { "code": null, "e": 24423, "s": 24272, "text": "Suppose, you want a user set time delay instead of a fixed delay of 5 seconds. For this, you can add a Form to the Code cell to accept the sleep time." }, { "code": null, "e": 24547, "s": 24423, "text": "Open a new notebook. Click on the Options (vertically-dotted) menu. A popup menu shows up as seen in the screenshot below −" }, { "code": null, "e": 24671, "s": 24547, "text": "Now, select Add a form option. It will add the form to your Code cell with a Default title as seen in the screenshot here −" }, { "code": null, "e": 24809, "s": 24671, "text": "To change the title of the form, click on the Settings button (pencil icon on the right). It will pop up a settings screen as shown here:" }, { "code": null, "e": 24954, "s": 24809, "text": "Change the form title to “Form” and save the form. You may use some other name of your choice. Notice that it adds the @title to your code cell." }, { "code": null, "e": 25090, "s": 24954, "text": "You may explore other options on the above screen at a later time. In the next section, we will learn how add input fields to the form." }, { "code": null, "e": 25232, "s": 25090, "text": "To add a form field, click the Options menu in the Code cell, click on the Form to reveal the submenus. The screen will look as shown below −" }, { "code": null, "e": 25301, "s": 25232, "text": "Select Add a form field menu option. A dialog pops up as seen here −" }, { "code": null, "e": 25460, "s": 25301, "text": "Leave the Form field type to input. Change the Variable name to sleeptime and set the Variable type to integer. Save the changes by clicking the Save button." }, { "code": null, "e": 25554, "s": 25460, "text": "Your screen will now look like the following with the sleeptime variable added into the code." }, { "code": null, "e": 25646, "s": 25554, "text": "Next, let us see how to test the form by adding some code that uses the sleeptime variable." }, { "code": null, "e": 25719, "s": 25646, "text": "Add a new Code cell underneath the form cell. Use the code given below −" }, { "code": null, "e": 25795, "s": 25719, "text": "import time\nprint(time.ctime())\ntime.sleep(sleeptime)\nprint (time.ctime())\n" }, { "code": null, "e": 26016, "s": 25795, "text": "You have used this code in the earlier lesson. It prints the current time, waits for a certain amount of time and prints a new timestamp. The amount of time that the program waits is set in the variable called sleeptime." }, { "code": null, "e": 26118, "s": 26016, "text": "Now, go back to the Form Cell and type in a value of 2 for the sleeptime. Select the following menu −" }, { "code": null, "e": 26137, "s": 26118, "text": "Runtime / Run all\n" }, { "code": null, "e": 26213, "s": 26137, "text": "This runs the entire notebook. You can see an output screen as shown below." }, { "code": null, "e": 26269, "s": 26213, "text": "Notice that it has taken your input value of 2 for the " }, { "code": null, "e": 26279, "s": 26269, "text": "sleeptime" }, { "code": null, "e": 26361, "s": 26279, "text": "To accept a text input in your form, enter the following code in a new code cell." }, { "code": null, "e": 26422, "s": 26361, "text": "name = 'Tutorialspoint' #@param {type:\"string\"}\nprint(name)\n" }, { "code": null, "e": 26584, "s": 26422, "text": "Now, if you run the Code cell, whatever the name you set in the form would be printed on the screen. By default, the following output would appear on the screen." }, { "code": null, "e": 26600, "s": 26584, "text": "Tutorialspoint\n" }, { "code": null, "e": 26700, "s": 26600, "text": "Note that you may use the menu options as shown for the integer input to create a Text input field." }, { "code": null, "e": 26762, "s": 26700, "text": "To add a dropdown list to your form, use the following code −" }, { "code": null, "e": 26825, "s": 26762, "text": "color = 'green' #@param [\"red\", \"green\", \"blue\"]\nprint(color)\n" }, { "code": null, "e": 26927, "s": 26825, "text": "This creates a dropdown list with three values - red, green and blue. The default selection is green." }, { "code": null, "e": 26980, "s": 26927, "text": "The dropdown list is shown in the screenshot below −" }, { "code": null, "e": 27100, "s": 26980, "text": "Colab Form allows you to accept dates in your code with validations. Use the following code to input date in your code." }, { "code": null, "e": 27187, "s": 27100, "text": "#@title Date fields\ndate_input = '2019-06-03' #@param {type:\"date\"}\nprint(date_input)\n" }, { "code": null, "e": 27229, "s": 27187, "text": "The Form screen looks like the following." }, { "code": null, "e": 27291, "s": 27229, "text": "Try inputting a wrong date value and observe the validations." }, { "code": null, "e": 27533, "s": 27291, "text": "So far you have learned how to use Colab for creating and executing Jupyter notebooks with your Python code. In the next chapter, we will see how to install popular ML libraries in your notebook so that you can use those in your Python code." }, { "code": null, "e": 27712, "s": 27533, "text": "Colab supports most of machine learning libraries available in the market. In this chapter, let us take a quick overview of how to install these libraries in your Colab notebook." }, { "code": null, "e": 27772, "s": 27712, "text": "To install a library, you can use either of these options −" }, { "code": null, "e": 27786, "s": 27772, "text": "!pip install\n" }, { "code": null, "e": 27789, "s": 27786, "text": "or" }, { "code": null, "e": 27807, "s": 27789, "text": "!apt-get install\n" }, { "code": null, "e": 28073, "s": 27807, "text": "Keras, written in Python, runs on top of TensorFlow, CNTK, or Theano. It enables easy and fast prototyping of neural network applications. It supports both convolutional networks (CNN) and recurrent networks, and also their combinations. It seamlessly supports GPU." }, { "code": null, "e": 28119, "s": 28073, "text": "To install Keras, use the following command −" }, { "code": null, "e": 28142, "s": 28119, "text": "!pip install -q keras\n" }, { "code": null, "e": 28304, "s": 28142, "text": "PyTorch is ideal for developing deep learning applications. It is an optimized tensor library and is GPU enabled. To install PyTorch, use the following command −" }, { "code": null, "e": 28337, "s": 28304, "text": "!pip3 install torch torchvision\n" }, { "code": null, "e": 28461, "s": 28337, "text": "Apache MxNet is another flexible and efficient library for deep learning. To install MxNet execute the following commands −" }, { "code": null, "e": 28511, "s": 28461, "text": "!apt install libnvrtc8.0\n!pip install mxnet-cu80\n" }, { "code": null, "e": 28942, "s": 28511, "text": "OpenCV is an open source computer vision library for developing machine learning applications. It has more than 2500 optimized algorithms which support several applications such as recognizing faces, identifying objects, tracking moving objects, stitching images, and so on. Giants like Google, Yahoo, Microsoft, Intel, IBM, Sony, Honda, Toyota use this library. This is highly suited for developing real-time vision applications." }, { "code": null, "e": 28988, "s": 28942, "text": "To install OpenCV use the following command −" }, { "code": null, "e": 29064, "s": 28988, "text": "!apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python\n" }, { "code": null, "e": 29289, "s": 29064, "text": "XGBoost is a distributed gradient boosting library that runs on major distributed environments such as Hadoop. It is highly efficient, flexible and portable. It implements ML algorithms under the Gradient Boosting framework." }, { "code": null, "e": 29337, "s": 29289, "text": "To install XGBoost, use the following command −" }, { "code": null, "e": 29370, "s": 29337, "text": "!pip install -q xgboost==0.4a30\n" }, { "code": null, "e": 29594, "s": 29370, "text": "Graphviz is an open source software for graph visualizations. It is used for visualization in networking, bioinformatics, database design, and for that matter in many domains where a visual interface of the data is desired." }, { "code": null, "e": 29643, "s": 29594, "text": "To install GraphViz, use the following command −" }, { "code": null, "e": 29701, "s": 29643, "text": "!apt-get -qq install -y graphviz && pip install -q pydot\n" }, { "code": null, "e": 29947, "s": 29701, "text": "By this time, you have learned to create Jupyter notebooks containing popular machine learning libraries. You are now ready to develop your machine learning models. This requires high processing power. Colab provides free GPU for your notebooks." }, { "code": null, "e": 30019, "s": 29947, "text": "In the next chapter, we will learn how to enable GPU for your notebook." }, { "code": null, "e": 30081, "s": 30019, "text": "Google provides the use of free GPU for your Colab notebooks." }, { "code": null, "e": 30149, "s": 30081, "text": "To enable GPU in your notebook, select the following menu options −" }, { "code": null, "e": 30180, "s": 30149, "text": "Runtime / Change runtime type\n" }, { "code": null, "e": 30230, "s": 30180, "text": "You will see the following screen as the output −" }, { "code": null, "e": 30438, "s": 30230, "text": "Select GPU and your notebook would use the free GPU provided in the cloud during processing. To get the feel of GPU processing, try running the sample application from MNIST tutorial that you cloned earlier." }, { "code": null, "e": 30491, "s": 30438, "text": "!python3 \"/content/drive/My Drive/app/mnist_cnn.py\"\n" }, { "code": null, "e": 30602, "s": 30491, "text": "Try running the same Python file without the GPU enabled. Did you notice the difference in speed of execution?" }, { "code": null, "e": 30679, "s": 30602, "text": "You can easily check if the GPU is enabled by executing the following code −" }, { "code": null, "e": 30730, "s": 30679, "text": "import tensorflow as tf\ntf.test.gpu_device_name()\n" }, { "code": null, "e": 30789, "s": 30730, "text": "If the GPU is enabled, it will give the following output −" }, { "code": null, "e": 30806, "s": 30789, "text": "'/device:GPU:0'\n" }, { "code": null, "e": 30927, "s": 30806, "text": "If you are curious to know the devices used during the execution of your notebook in the cloud, try the following code −" }, { "code": null, "e": 31008, "s": 30927, "text": "from tensorflow.python.client import device_lib\ndevice_lib.list_local_devices()\n" }, { "code": null, "e": 31045, "s": 31008, "text": "You will see the output as follows −" }, { "code": null, "e": 31802, "s": 31045, "text": "[name: \"/device:CPU:0\"\n device_type: \"CPU\"\n memory_limit: 268435456\n locality { }\n incarnation: 1734904979049303143, name: \"/device:XLA_CPU:0\"\n device_type: \"XLA_CPU\" memory_limit: 17179869184\n locality { } \n incarnation: 16069148927281628039\n physical_device_desc: \"device: XLA_CPU device\", name: \"/device:XLA_GPU:0\"\n device_type: \"XLA_GPU\"\n memory_limit: 17179869184\n locality { }\n incarnation: 16623465188569787091\n physical_device_desc: \"device: XLA_GPU device\", name: \"/device:GPU:0\"\n device_type: \"GPU\"\n memory_limit: 14062547764\n locality {\n bus_id: 1\n links { } \n }\n incarnation: 6674128802944374158\nphysical_device_desc: \"device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5\"]\n" }, { "code": null, "e": 31887, "s": 31802, "text": "To see the memory resources available for your process, type the following command −" }, { "code": null, "e": 31907, "s": 31887, "text": "!cat /proc/meminfo\n" }, { "code": null, "e": 31943, "s": 31907, "text": "You will see the following output −" }, { "code": null, "e": 32852, "s": 31943, "text": "MemTotal: 13335276 kB\nMemFree: 7322964 kB\nMemAvailable: 10519168 kB\nBuffers: 95732 kB\nCached: 2787632 kB\nSwapCached: 0 kB\nActive: 2433984 kB\nInactive: 3060124 kB\nActive(anon): 2101704 kB\nInactive(anon): 22880 kB\nActive(file): 332280 kB\nInactive(file): 3037244 kB\nUnevictable: 0 kB\nMlocked: 0 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\nDirty: 412 kB\nWriteback: 0 kB\nAnonPages: 2610780 kB\nMapped: 838200 kB\nShmem: 23436 kB\nSlab: 183240 kB\nSReclaimable: 135324 kB\nSUnreclaim: 47916\nkBKernelStack: 4992 kB\nPageTables: 13600 kB\nNFS_Unstable: 0 kB\nBounce: 0 kB\nWritebackTmp: 0 kB\nCommitLimit: 6667636 kB\nCommitted_AS: 4801380 kB\nVmallocTotal: 34359738367 kB\nVmallocUsed: 0 kB\nVmallocChunk: 0 kB\nAnonHugePages: 0 kB\nShmemHugePages: 0 kB\nShmemPmdMapped: 0 kB\nHugePages_Total: 0\nHugePages_Free: 0\nHugePages_Rsvd: 0\nHugePages_Surp: 0\nHugepagesize: 2048 kB\nDirectMap4k: 303092 kB\nDirectMap2M: 5988352 kB\nDirectMap1G: 9437184 kB\n" }, { "code": null, "e": 32949, "s": 32852, "text": "You are now all set for the development of machine learning models in Python using Google Colab." }, { "code": null, "e": 33570, "s": 32949, "text": "Google Colab is a powerful platform for learning and quickly developing machine learning models in Python. It is based on Jupyter notebook and supports collaborative development. The team members can share and concurrently edit the notebooks, even remotely. The notebooks can also be published on GitHub and shared with the general public. Colab supports many popular ML libraries such as PyTorch, TensorFlow, Keras and OpenCV. The restriction as of today is that it does not support R or Scala yet. There is also a limitation to sessions and size. Considering the benefits, these are small sacrifices one needs to make." }, { "code": null, "e": 33605, "s": 33570, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 33619, "s": 33605, "text": " Asif Hussain" }, { "code": null, "e": 33651, "s": 33619, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 33668, "s": 33651, "text": " Aditya Kulkarni" }, { "code": null, "e": 33703, "s": 33668, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 33717, "s": 33703, "text": " Sasha Miller" }, { "code": null, "e": 33752, "s": 33717, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 33765, "s": 33752, "text": " Zach Miller" }, { "code": null, "e": 33800, "s": 33765, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 33814, "s": 33800, "text": " Sasha Miller" }, { "code": null, "e": 33849, "s": 33814, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 33863, "s": 33849, "text": " Sasha Miller" }, { "code": null, "e": 33870, "s": 33863, "text": " Print" }, { "code": null, "e": 33881, "s": 33870, "text": " Add Notes" } ]
Bootstrap 5 | Breadcrumb - GeeksforGeeks
29 Jul, 2020 Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Breadcrumbs are used to indicate the current page’s location within a navigational hierarchy. Syntax: <ol class="breadcrumb"> <li class="breadcrumb-item"> Content .. </li> </ol> Example 1: This example uses show the working of Breadcrumbs in Bootstrap 5. <!DOCTYPE html><html> <head> <title> Bootstrap 5 | Breadcrumbs </title> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"></head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> </div> <div style="width: 600px;height: 200px; margin:20px;"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item active"> GeeksforGeeks </li> </ol> </nav> </div></body> </html> Output: Example 2: This example uses show the working of Breadcrumbs in Bootstrap 5. <!DOCTYPE html><html> <head> <title> Bootstrap 5 | Breadcrumbs </title> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"></head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> </div> <div style="width: 600px;height: 200px;margin:20px;"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="#">GeeksforGeeks </a></li> <li class="breadcrumb-item">Articles</li> </ol> </nav> </div></body> </html> Output: Example 3: This example uses show the working of Breadcrumbs in Bootstrap 5. <!DOCTYPE html><html> <head> <title> Bootstrap 5 | Breadcrumbs </title> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"></head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> </div> <div style="width: 600px;height: 200px;margin:20px;"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="#">GeeksforGeeks</a></li> <li class="breadcrumb-item"> <a href="#">Articles</a></li> <li class="breadcrumb-item active"> Bootstrap 5</li> </ol> </nav> </div></body> </html> Output: Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Installation of Node.js on Linux Convert a string to an integer in JavaScript
[ { "code": null, "e": 28440, "s": 28412, "text": "\n29 Jul, 2020" }, { "code": null, "e": 28648, "s": 28440, "text": "Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Breadcrumbs are used to indicate the current page’s location within a navigational hierarchy." }, { "code": null, "e": 28656, "s": 28648, "text": "Syntax:" }, { "code": null, "e": 28734, "s": 28656, "text": "<ol class=\"breadcrumb\">\n <li class=\"breadcrumb-item\"> Content .. </li>\n</ol>" }, { "code": null, "e": 28811, "s": 28734, "text": "Example 1: This example uses show the working of Breadcrumbs in Bootstrap 5." }, { "code": "<!DOCTYPE html><html> <head> <title> Bootstrap 5 | Breadcrumbs </title> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"></head> <body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> </div> <div style=\"width: 600px;height: 200px; margin:20px;\"> <nav aria-label=\"breadcrumb\"> <ol class=\"breadcrumb\"> <li class=\"breadcrumb-item active\"> GeeksforGeeks </li> </ol> </nav> </div></body> </html>", "e": 29624, "s": 28811, "text": null }, { "code": null, "e": 29632, "s": 29624, "text": "Output:" }, { "code": null, "e": 29709, "s": 29632, "text": "Example 2: This example uses show the working of Breadcrumbs in Bootstrap 5." }, { "code": "<!DOCTYPE html><html> <head> <title> Bootstrap 5 | Breadcrumbs </title> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"></head> <body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> </div> <div style=\"width: 600px;height: 200px;margin:20px;\"> <nav aria-label=\"breadcrumb\"> <ol class=\"breadcrumb\"> <li class=\"breadcrumb-item\"> <a href=\"#\">GeeksforGeeks </a></li> <li class=\"breadcrumb-item\">Articles</li> </ol> </nav> </div></body> </html> ", "e": 30579, "s": 29709, "text": null }, { "code": null, "e": 30587, "s": 30579, "text": "Output:" }, { "code": null, "e": 30664, "s": 30587, "text": "Example 3: This example uses show the working of Breadcrumbs in Bootstrap 5." }, { "code": "<!DOCTYPE html><html> <head> <title> Bootstrap 5 | Breadcrumbs </title> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"></head> <body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> </div> <div style=\"width: 600px;height: 200px;margin:20px;\"> <nav aria-label=\"breadcrumb\"> <ol class=\"breadcrumb\"> <li class=\"breadcrumb-item\"> <a href=\"#\">GeeksforGeeks</a></li> <li class=\"breadcrumb-item\"> <a href=\"#\">Articles</a></li> <li class=\"breadcrumb-item active\"> Bootstrap 5</li> </ol> </nav> </div></body> </html> ", "e": 31652, "s": 30664, "text": null }, { "code": null, "e": 31660, "s": 31652, "text": "Output:" }, { "code": null, "e": 31675, "s": 31660, "text": "Bootstrap-Misc" }, { "code": null, "e": 31685, "s": 31675, "text": "Bootstrap" }, { "code": null, "e": 31702, "s": 31685, "text": "Web Technologies" }, { "code": null, "e": 31800, "s": 31702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31850, "s": 31800, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 31879, "s": 31850, "text": "Form validation using jQuery" }, { "code": null, "e": 31935, "s": 31879, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 31976, "s": 31935, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 32017, "s": 31976, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 32059, "s": 32017, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 32121, "s": 32059, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32164, "s": 32121, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32197, "s": 32164, "text": "Installation of Node.js on Linux" } ]
Lodash - groupBy method
_.groupBy(collection, [iteratee=_.identity]) Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value). collection (Array|Object) − The collection to iterate over. collection (Array|Object) − The collection to iterate over. [iteratee=_.identity] (Function) − The iteratee to transform keys. [iteratee=_.identity] (Function) − The iteratee to transform keys. (Object) − Returns the composed aggregate object. (Object) − Returns the composed aggregate object. var _ = require('lodash'); var list = [1.1 ,1.4, 2.1, 2.3]; var result = _.groupBy(list, Math.floor); console.log(result); result = _.groupBy(['one', 'two', 'three'], 'length'); console.log(result); Save the above program in tester.js. Run the following command to execute this program. \>node tester.js { '1': [ 1.1, 1.4 ], '2': [ 2.1, 2.3 ] } { '3': [ 'one', 'two' ], '5': [ 'three' ] } Print Add Notes Bookmark this page
[ { "code": null, "e": 1873, "s": 1827, "text": "_.groupBy(collection, [iteratee=_.identity])\n" }, { "code": null, "e": 2217, "s": 1873, "text": "Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value)." }, { "code": null, "e": 2277, "s": 2217, "text": "collection (Array|Object) − The collection to iterate over." }, { "code": null, "e": 2337, "s": 2277, "text": "collection (Array|Object) − The collection to iterate over." }, { "code": null, "e": 2404, "s": 2337, "text": "[iteratee=_.identity] (Function) − The iteratee to transform keys." }, { "code": null, "e": 2471, "s": 2404, "text": "[iteratee=_.identity] (Function) − The iteratee to transform keys." }, { "code": null, "e": 2521, "s": 2471, "text": "(Object) − Returns the composed aggregate object." }, { "code": null, "e": 2571, "s": 2521, "text": "(Object) − Returns the composed aggregate object." }, { "code": null, "e": 2773, "s": 2571, "text": "var _ = require('lodash');\nvar list = [1.1 ,1.4, 2.1, 2.3];\n \nvar result = _.groupBy(list, Math.floor);\nconsole.log(result);\n\nresult = _.groupBy(['one', 'two', 'three'], 'length');\nconsole.log(result);" }, { "code": null, "e": 2861, "s": 2773, "text": "Save the above program in tester.js. Run the following command to execute this program." }, { "code": null, "e": 2879, "s": 2861, "text": "\\>node tester.js\n" }, { "code": null, "e": 2965, "s": 2879, "text": "{ '1': [ 1.1, 1.4 ], '2': [ 2.1, 2.3 ] }\n{ '3': [ 'one', 'two' ], '5': [ 'three' ] }\n" }, { "code": null, "e": 2972, "s": 2965, "text": " Print" }, { "code": null, "e": 2983, "s": 2972, "text": " Add Notes" } ]
Closest numbers from a list of unsorted integers - GeeksforGeeks
08 Apr, 2021 Given a list of distinct unsorted integers, find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.Examples: Input : arr[] = {10, 50, 12, 100} Output : (10, 12) The closest elements are 10 and 12 Input : arr[] = {5, 4, 3, 2} Output : (2, 3), (3, 4), (4, 5) This problem is mainly an extension of Find minimum difference between any two elements. Sort the given array.Find minimum difference of all pairs in linear time in sorted array.Traverse sorted array one more time to print all pairs with minimum difference obtained in step 2. Sort the given array. Find minimum difference of all pairs in linear time in sorted array. Traverse sorted array one more time to print all pairs with minimum difference obtained in step 2. C++ Java Python3 C# PHP Javascript // CPP program to find minimum difference// an unsorted array.#include<bits/stdc++.h>using namespace std; // Returns minimum difference between any// two pair in arr[0..n-1]void printMinDiffPairs(int arr[], int n){ if (n <= 1) return; // Sort array elements sort(arr, arr+n); // Compare differences of adjacent // pairs to find the minimum difference. int minDiff = arr[1] - arr[0]; for (int i = 2 ; i < n ; i++) minDiff = min(minDiff, arr[i] - arr[i-1]); // Traverse array again and print all pairs // with difference as minDiff. for (int i = 1; i < n; i++) if ((arr[i] - arr[i-1]) == minDiff) cout << "(" << arr[i-1] << ", " << arr[i] << "), ";} // Driver codeint main(){ int arr[] = {5, 3, 2, 4, 1}; int n = sizeof(arr) / sizeof(arr[0]); printMinDiffPairs(arr, n); return 0;} // Java program to find minimum// difference an unsorted array.import java.util.*; class GFG{ // Returns minimum difference between // any two pair in arr[0..n-1] static void printMinDiffPairs(int arr[], int n) { if (n <= 1) return; // Sort array elements Arrays.sort(arr); // Compare differences of adjacent // pairs to find the minimum difference. int minDiff = arr[1] - arr[0]; for (int i = 2; i < n; i++) minDiff = Math.min(minDiff, arr[i] - arr[i-1]); // Traverse array again and print all pairs // with difference as minDiff. for ( int i = 1; i < n; i++) { if ((arr[i] - arr[i-1]) == minDiff) { System.out.print("(" + arr[i-1] + ", " + arr[i] + ")," ); } } } // Driver code public static void main (String[] args) { int arr[] = {5, 3, 2, 4, 1}; int n = arr.length; printMinDiffPairs(arr, n); }} // This code is contributed by Ansu Kumari # Python3 program to find minimum# difference in an unsorted array. # Returns minimum difference between# any two pair in arr[0..n-1]def printMinDiffPairs(arr , n): if n <= 1: return # Sort array elements arr.sort() # Compare differences of adjacent # pairs to find the minimum difference. minDiff = arr[1] - arr[0] for i in range(2 , n): minDiff = min(minDiff, arr[i] - arr[i-1]) # Traverse array again and print all # pairs with difference as minDiff. for i in range(1 , n): if (arr[i] - arr[i-1]) == minDiff: print( "(" + str(arr[i-1]) + ", " + str(arr[i]) + "), ", end = '') # Driver codearr = [5, 3, 2, 4, 1]n = len(arr)printMinDiffPairs(arr , n) # This code is contributed by Ansu Kumari // C# program to find minimum// difference an unsorted array.using System; class GFG{ // Returns minimum difference between// any two pair in arr[0..n-1]static void printMinDiffPairs(int []arr, int n){ if (n <= 1) return; // Sort array elements Array.Sort(arr); // Compare differences of adjacent // pairs to find the minimum difference. int minDiff = arr[1] - arr[0]; for (int i = 2; i < n; i++) minDiff = Math.Min(minDiff, arr[i] - arr[i-1]); // Traverse array again and print all pairs // with difference as minDiff. for ( int i = 1; i < n; i++) { if ((arr[i] - arr[i-1]) == minDiff) { Console.Write(" (" + arr[i-1] + ", " + arr[i] + "), " ); } }} // Driver codepublic static void Main (){ int []arr = {5, 3, 2, 4, 1}; int n = arr.Length; printMinDiffPairs(arr, n);}} // This code is contributed by vt_m <?php//PHP program to find minimum difference// an unsorted array. // Returns minimum difference between any// two pair in arr[0..n-1]function printMinDiffPairs($arr, $n){ if ($n <= 1) return; // Sort array elements sort($arr); // Compare differences of adjacent // pairs to find the minimum // difference. $minDiff = $arr[1] - $arr[0]; for ($i = 2 ; $i < $n ; $i++) $minDiff = min($minDiff, $arr[$i] - $arr[$i-1]); // Traverse array again and print all // pairs with difference as minDiff. for ($i = 1; $i < $n; $i++) if (($arr[$i] - $arr[$i-1]) == $minDiff) echo "(" , $arr[$i-1] , ", ", $arr[$i] , "), ";} // Driver code $arr = array(5, 3, 2, 4, 1); $n = sizeof($arr); printMinDiffPairs($arr, $n); // This code is contributed by ajit.?> <script> // JavaScript program to find minimum// difference an unsorted array. // Returns minimum difference between // any two pair in arr[0..n-1] function printMinDiffPairs(arr, n) { if (n <= 1) return; // Sort array elements arr.sort(); // Compare differences of adjacent // pairs to find the minimum difference. let minDiff = arr[1] - arr[0]; for (let i = 2; i < n; i++) minDiff = Math.min(minDiff, arr[i] - arr[i-1]); // Traverse array again and print all pairs // with difference as minDiff. for ( let i = 1; i < n; i++) { if ((arr[i] - arr[i-1]) == minDiff) { document.write("(" + arr[i-1] + ", " + arr[i] + ") , " ); } } } // Driver code let arr = [5, 3, 2, 4, 1]; let n = arr.length; printMinDiffPairs(arr , n); </script> Output: (1, 2), (2, 3), (3, 4), (4, 5), Does above program handle duplicates? The cases like {x, x, x} are not handled by above program. For this case, the expected output (x, x), (x, x), (x, x), but above program prints (x, x), (x, x) jit_t splevel62 Amazon Arrays Searching Sorting Amazon Arrays Searching Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Binary Search Median of two sorted arrays of different sizes Most frequent element in an array Find the index of an array element in Java Count number of occurrences (or frequency) in a sorted array
[ { "code": null, "e": 24429, "s": 24401, "text": "\n08 Apr, 2021" }, { "code": null, "e": 24611, "s": 24429, "text": "Given a list of distinct unsorted integers, find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.Examples: " }, { "code": null, "e": 24760, "s": 24611, "text": "Input : arr[] = {10, 50, 12, 100}\nOutput : (10, 12)\nThe closest elements are 10 and 12\n\nInput : arr[] = {5, 4, 3, 2}\nOutput : (2, 3), (3, 4), (4, 5)" }, { "code": null, "e": 24852, "s": 24762, "text": "This problem is mainly an extension of Find minimum difference between any two elements. " }, { "code": null, "e": 25040, "s": 24852, "text": "Sort the given array.Find minimum difference of all pairs in linear time in sorted array.Traverse sorted array one more time to print all pairs with minimum difference obtained in step 2." }, { "code": null, "e": 25062, "s": 25040, "text": "Sort the given array." }, { "code": null, "e": 25131, "s": 25062, "text": "Find minimum difference of all pairs in linear time in sorted array." }, { "code": null, "e": 25230, "s": 25131, "text": "Traverse sorted array one more time to print all pairs with minimum difference obtained in step 2." }, { "code": null, "e": 25236, "s": 25232, "text": "C++" }, { "code": null, "e": 25241, "s": 25236, "text": "Java" }, { "code": null, "e": 25249, "s": 25241, "text": "Python3" }, { "code": null, "e": 25252, "s": 25249, "text": "C#" }, { "code": null, "e": 25256, "s": 25252, "text": "PHP" }, { "code": null, "e": 25267, "s": 25256, "text": "Javascript" }, { "code": "// CPP program to find minimum difference// an unsorted array.#include<bits/stdc++.h>using namespace std; // Returns minimum difference between any// two pair in arr[0..n-1]void printMinDiffPairs(int arr[], int n){ if (n <= 1) return; // Sort array elements sort(arr, arr+n); // Compare differences of adjacent // pairs to find the minimum difference. int minDiff = arr[1] - arr[0]; for (int i = 2 ; i < n ; i++) minDiff = min(minDiff, arr[i] - arr[i-1]); // Traverse array again and print all pairs // with difference as minDiff. for (int i = 1; i < n; i++) if ((arr[i] - arr[i-1]) == minDiff) cout << \"(\" << arr[i-1] << \", \" << arr[i] << \"), \";} // Driver codeint main(){ int arr[] = {5, 3, 2, 4, 1}; int n = sizeof(arr) / sizeof(arr[0]); printMinDiffPairs(arr, n); return 0;}", "e": 26117, "s": 25267, "text": null }, { "code": "// Java program to find minimum// difference an unsorted array.import java.util.*; class GFG{ // Returns minimum difference between // any two pair in arr[0..n-1] static void printMinDiffPairs(int arr[], int n) { if (n <= 1) return; // Sort array elements Arrays.sort(arr); // Compare differences of adjacent // pairs to find the minimum difference. int minDiff = arr[1] - arr[0]; for (int i = 2; i < n; i++) minDiff = Math.min(minDiff, arr[i] - arr[i-1]); // Traverse array again and print all pairs // with difference as minDiff. for ( int i = 1; i < n; i++) { if ((arr[i] - arr[i-1]) == minDiff) { System.out.print(\"(\" + arr[i-1] + \", \" + arr[i] + \"),\" ); } } } // Driver code public static void main (String[] args) { int arr[] = {5, 3, 2, 4, 1}; int n = arr.length; printMinDiffPairs(arr, n); }} // This code is contributed by Ansu Kumari", "e": 27129, "s": 26117, "text": null }, { "code": "# Python3 program to find minimum# difference in an unsorted array. # Returns minimum difference between# any two pair in arr[0..n-1]def printMinDiffPairs(arr , n): if n <= 1: return # Sort array elements arr.sort() # Compare differences of adjacent # pairs to find the minimum difference. minDiff = arr[1] - arr[0] for i in range(2 , n): minDiff = min(minDiff, arr[i] - arr[i-1]) # Traverse array again and print all # pairs with difference as minDiff. for i in range(1 , n): if (arr[i] - arr[i-1]) == minDiff: print( \"(\" + str(arr[i-1]) + \", \" + str(arr[i]) + \"), \", end = '') # Driver codearr = [5, 3, 2, 4, 1]n = len(arr)printMinDiffPairs(arr , n) # This code is contributed by Ansu Kumari", "e": 27901, "s": 27129, "text": null }, { "code": "// C# program to find minimum// difference an unsorted array.using System; class GFG{ // Returns minimum difference between// any two pair in arr[0..n-1]static void printMinDiffPairs(int []arr, int n){ if (n <= 1) return; // Sort array elements Array.Sort(arr); // Compare differences of adjacent // pairs to find the minimum difference. int minDiff = arr[1] - arr[0]; for (int i = 2; i < n; i++) minDiff = Math.Min(minDiff, arr[i] - arr[i-1]); // Traverse array again and print all pairs // with difference as minDiff. for ( int i = 1; i < n; i++) { if ((arr[i] - arr[i-1]) == minDiff) { Console.Write(\" (\" + arr[i-1] + \", \" + arr[i] + \"), \" ); } }} // Driver codepublic static void Main (){ int []arr = {5, 3, 2, 4, 1}; int n = arr.Length; printMinDiffPairs(arr, n);}} // This code is contributed by vt_m", "e": 28847, "s": 27901, "text": null }, { "code": "<?php//PHP program to find minimum difference// an unsorted array. // Returns minimum difference between any// two pair in arr[0..n-1]function printMinDiffPairs($arr, $n){ if ($n <= 1) return; // Sort array elements sort($arr); // Compare differences of adjacent // pairs to find the minimum // difference. $minDiff = $arr[1] - $arr[0]; for ($i = 2 ; $i < $n ; $i++) $minDiff = min($minDiff, $arr[$i] - $arr[$i-1]); // Traverse array again and print all // pairs with difference as minDiff. for ($i = 1; $i < $n; $i++) if (($arr[$i] - $arr[$i-1]) == $minDiff) echo \"(\" , $arr[$i-1] , \", \", $arr[$i] , \"), \";} // Driver code $arr = array(5, 3, 2, 4, 1); $n = sizeof($arr); printMinDiffPairs($arr, $n); // This code is contributed by ajit.?>", "e": 29766, "s": 28847, "text": null }, { "code": "<script> // JavaScript program to find minimum// difference an unsorted array. // Returns minimum difference between // any two pair in arr[0..n-1] function printMinDiffPairs(arr, n) { if (n <= 1) return; // Sort array elements arr.sort(); // Compare differences of adjacent // pairs to find the minimum difference. let minDiff = arr[1] - arr[0]; for (let i = 2; i < n; i++) minDiff = Math.min(minDiff, arr[i] - arr[i-1]); // Traverse array again and print all pairs // with difference as minDiff. for ( let i = 1; i < n; i++) { if ((arr[i] - arr[i-1]) == minDiff) { document.write(\"(\" + arr[i-1] + \", \" + arr[i] + \") , \" ); } } } // Driver code let arr = [5, 3, 2, 4, 1]; let n = arr.length; printMinDiffPairs(arr , n); </script>", "e": 30678, "s": 29766, "text": null }, { "code": null, "e": 30687, "s": 30678, "text": "Output: " }, { "code": null, "e": 30720, "s": 30687, "text": "(1, 2), (2, 3), (3, 4), (4, 5), " }, { "code": null, "e": 30917, "s": 30720, "text": "Does above program handle duplicates? The cases like {x, x, x} are not handled by above program. For this case, the expected output (x, x), (x, x), (x, x), but above program prints (x, x), (x, x) " }, { "code": null, "e": 30923, "s": 30917, "text": "jit_t" }, { "code": null, "e": 30933, "s": 30923, "text": "splevel62" }, { "code": null, "e": 30940, "s": 30933, "text": "Amazon" }, { "code": null, "e": 30947, "s": 30940, "text": "Arrays" }, { "code": null, "e": 30957, "s": 30947, "text": "Searching" }, { "code": null, "e": 30965, "s": 30957, "text": "Sorting" }, { "code": null, "e": 30972, "s": 30965, "text": "Amazon" }, { "code": null, "e": 30979, "s": 30972, "text": "Arrays" }, { "code": null, "e": 30989, "s": 30979, "text": "Searching" }, { "code": null, "e": 30997, "s": 30989, "text": "Sorting" }, { "code": null, "e": 31095, "s": 30997, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31104, "s": 31095, "text": "Comments" }, { "code": null, "e": 31117, "s": 31104, "text": "Old Comments" }, { "code": null, "e": 31138, "s": 31117, "text": "Next Greater Element" }, { "code": null, "e": 31163, "s": 31138, "text": "Window Sliding Technique" }, { "code": null, "e": 31190, "s": 31163, "text": "Count pairs with given sum" }, { "code": null, "e": 31239, "s": 31190, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31277, "s": 31239, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31291, "s": 31277, "text": "Binary Search" }, { "code": null, "e": 31338, "s": 31291, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 31372, "s": 31338, "text": "Most frequent element in an array" }, { "code": null, "e": 31415, "s": 31372, "text": "Find the index of an array element in Java" } ]
Notes about saving data with Spark 3.0 | by David Vrba | Towards Data Science
Apache Spark is a computational engine frequently used in a big data environment for data processing but it doesn’t provide storage so in a typical scenario the output of the data processing has to be stored in an external storage system. Spark SQL provides a couple of connectors for datasources such as file format (CSV, JSON, text, Parquet, ORC) or JDBC. Since 2.4 there is also support for Apache Avro and since 3.0 also read support for binary files. In addition, there are several libraries that allow connecting to other datasources, for example, MongoDB, ElasticSearch, or DynamoDB to name some. In this article, we will go over some possibilities that we have when saving data to a file format such as Apache Parquet, because the combination of Spark with Parquet provides a very nice experience, especially for analytical queries. We will first explain why Parquet is such a popular format for storing data in the Hadoop ecosystem and then we will describe different ways how to save the data with Spark while focussing especially on features that are missing in the official documentation or are difficult to find. One of these non-trivial features that we will look at is how to save the data in a pre-sorted state so it can be leveraged for data skipping with appropriate filters. The provided code snippets are using the Python API and are checked against Spark 3.0 and 2.4. Apache Parquet is an open-source file format originally developed at Twitter and Cloudera. It is a self-describing format, which means that it contains metadata with information about the schema (among other things). It is using a hybrid model for storing the data on the disk and by hybrid, we mean that it is not strictly row-oriented (such as JSON or CSV) neither strictly columnar but instead the data is first divided vertically into so-called row-groups and then each row-group is stored in a columnar representation. These row-groups allow for splitting the dataset into multiple files (each file can have one or more row-groups) so we don’t end up with one huge file which is important especially in the big data environment. The columnar representation of each row-group is also a very important feature because it allows for a so-called column pruning. In analytical queries, we are not usually interested in all columns of the dataset but rather we select a few columns and do some aggregation on it. This column pruning lets us skip all other columns and scan only those selected in the query so it makes the reading much more efficient as compared to row-oriented formats where all columns have to be scanned. Another advantage of columnar formats is compression — each value in the column has the same data type and the values may even get repeated which can be used to store the data more efficiently using various encoding and compression techniques (that Parquet supports under the hood). Parquet files support data skipping on different levels, namely on partition level and row-group level. So a dataset can be partitioned by some (usually low-cardinality) key and this means that for each distinct value of this field there is going to be a subfolder in the root directory that will contain all records with that particular value of the key (each partition can still be divided into multiple files). The use case for the partitioning is to reduce the volume of the data when reading because when the partition key is used in a filter, Spark will apply partition pruning and it will skip all partitions that are not relevant for the query (this is supported also for other file formats such as JSON or CSV). The row-group level data skipping is based on parquet metadata because each parquet file has a footer that contains metadata about each row-group and this metadata contains statistical information such as min and max value for each column in the row-group. When reading the parquet file, Spark will first read the footer and use these statistics to check whether a given row-group can potentially contain relevant data for the query. This will be useful especially if the parquet file is sorted by the column that we use for filtering. Because, if the file is not sorted, then small and large values can be scattered across all row-groups and thus each row-group will have to be scanned because it can potentially contain some rows satisfied by the filter. The sort here is crucial and as we will see later on, it is not trivial to save the data in the sorted state. One of the options for saving the output of computation in Spark to a file format is using the save method ( df.write .mode('overwrite') # or append .partitionBy(col_name) # this is optional .format('parquet') # this is optional, parquet is default .option('path', output_path) .save()) As you can see it allows you to specify partition columns if you want the data to be partitioned in the file system where you save it. The default format is parquet so if you don’t specify it, it will be assumed. The data analyst who will be using the data will probably more appreciate if you save the data with the saveAsTable method because it will allow him/her to access the data using df = spark.table(table_name) The saveAsTable function allows also for using bucketing where each bucket can be also (optionally) sorted: ( df.write .mode('overwrite') # or append .partitionBy(col_name) # this is optional .bucketBy(n, col_name) # n is number of buckets .sortBy(col_name) .format('parquet') # this is optional, parquet is default .option('path', output_path) .saveAsTable(table_name)) We will not dive into bucketing here, but in general, it is a technique on how to pre-shuffle the data and save it in this state so it can be leveraged by follow-up queries to avoid shuffle. This is going to work if the metastore is properly set up with Spark because the information about bucketing will be saved here. This approach has also other benefits since the metastore can keep also other information about your dataset such as statistics when you call the ANALYZE TABLE command later on. The sortBy can be used only after bucketBy, because what will be sorted are the created buckets. Both modes overwrite and append will work here even if the table doesn’t exist yet because the function will simply create it. Yet another possibility of how to save data is using the insertInto function. Unlike in the previous case, the table has to exist first, because if it doesn’t, you will get an error: AnalysisException: Table not found. The syntax for using this function is rather simple ( df.write .insertInto(table_name)) but there are some cautions that are good to be aware of: You don’t have to specify the output path. Spark will find that information in the metastore. If you specify the path anyway, it will be ignored. The default mode is append, so it will simply add your data to the existing table. The schema of your DataFrame must match the schema of the table. If the order of the columns in your DataFrame is different than the order in the table, Spark will throw an exception if the data types are different and can't be safely cast. But if there is not a mismatch in data types, Spark will insert the data to the table in this wrong order. So this is quite dangerous and it is good to make sure that the schema is the same for example as follows: ( df.select(spark.table(table_name).columns) .write .insertInto(table_name)) if your table is partitioned or bucketed, you don’t specify that (you would get an error) because Spark will pick that information from the metastore. The function insertInto has one big advantage over saveAsTable because it allows for a so-called dynamic overwrite. This feature lets you overwrite a specific partition in a partitioned table. For example, if your table is partitioned by year and you want to update only one year, then with saveAsTable you would have to overwrite the entire table, but with insertInto, you can overwrite only this single partition so it will be a much cheaper operation especially if there are lots of big partitions. To use this feature you have to set a corresponding configuration setting: spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")( df # having data only for specific partitions .write .insertInto(table_name, overwrite=True)) Here again, it is good to be careful, because if the partitionOverwriteMode is set to static (which is the default value) it would overwrite the entire table and so all other partitions would become empty. The dynamic value makes sure that Spark will overwrite only partitions that we have data for in our DataFrame. As we mentioned above, sometimes it is desirable to save the data in the sorted state according to some column so it could be used for data skipping in analytical queries that use this column as a filter. In Spark SQL there are three functions when it comes to sorting. There is orderBy (or equivalently sort), sortWithinPartitions, and sortBy. Let’s see what is the difference between them and how they can be used: orderBy — it is a DataFrame transformation that will invoke a global sort. This will first run a separate job that will sample the data to check the distribution of values in the sorting column. This distribution is then used to create boundaries for partitions and the dataset will be shuffled to create these partitions. It is quite an expensive operation and if you save the data into a partitioned table it may create lots of small files if the data distribution on the cluster is very different from the final distribution of the table in the file system (for example if you sort by date and your table is partitioned by country, each task in the final stage of the Spark job may potentially carry data for each country, so each task will write a new file into each file system partition).sortWithinPartitions — it is also a DataFrame transformation and unlike in the previous case Spark will not try to achieve a global sort but instead, it will sort each partition separately. So here you can distribute the data on the Spark cluster as you require for the final layout using the repartition() function (this will also create a shuffle) and then call sortWithinPartitions to have each partition sorted. The advantage of this approach over the previous one is that you can avoid having lots of small files and still have the output sorted.sortBy — this function can be called on a DataFrameWritter (after calling df.write) if we also call bucketBy and use saveAsTable method for saving. It is going to make sure that each bucket is sorted (one bucket can be either one file or more files depending on the distribution of data on the Spark cluster at the moment of writing). orderBy — it is a DataFrame transformation that will invoke a global sort. This will first run a separate job that will sample the data to check the distribution of values in the sorting column. This distribution is then used to create boundaries for partitions and the dataset will be shuffled to create these partitions. It is quite an expensive operation and if you save the data into a partitioned table it may create lots of small files if the data distribution on the cluster is very different from the final distribution of the table in the file system (for example if you sort by date and your table is partitioned by country, each task in the final stage of the Spark job may potentially carry data for each country, so each task will write a new file into each file system partition). sortWithinPartitions — it is also a DataFrame transformation and unlike in the previous case Spark will not try to achieve a global sort but instead, it will sort each partition separately. So here you can distribute the data on the Spark cluster as you require for the final layout using the repartition() function (this will also create a shuffle) and then call sortWithinPartitions to have each partition sorted. The advantage of this approach over the previous one is that you can avoid having lots of small files and still have the output sorted. sortBy — this function can be called on a DataFrameWritter (after calling df.write) if we also call bucketBy and use saveAsTable method for saving. It is going to make sure that each bucket is sorted (one bucket can be either one file or more files depending on the distribution of data on the Spark cluster at the moment of writing). Using the first two functions has one big catch that you would not find in documentation (written in October 2020). Let’s see it on a simple example. For the sake of simplicity we want to partition the data by year and have each partition sorted by user_id, and for saving we use saveAsTable(). If you just call ( df.repartition('year') .sortWithinPartitions('user_id') .write .mode('overwrite') .partitionBy('year') .option('path', output_path) .saveAsTable(table_name)) It is not going to work! It will not raise any error and it will save the data but the order will not be preserved! The point is that when writing data to a file format, Spark requires this ordering: (partitionColumns + bucketIdExpression + sortColumns) here partitionColumns are columns by which we partition the data to the file system, bucketingIdExpression is derived from the bucketing column (not relevant in our query because we are not using bucketing here) and sortColumns are columns used in sortBy with bucketing (again not relevant for our query). If the data is sorted by these columns (and possibly some more), the requirement will be satisfied and Spark will preserve the order. If however, this requirement is not satisfied, Spark will forget the previous order and will sort the data again according to this requirement while writing the data. In our example, the required ordering is (year) which is the partition column and we don’t have any bucketing here. This requirement is however not satisfied, because the actual ordering is (user_id), which is the column by which we sorted the data and this is the reason why Spark will not preserve our order and will sort the data again by the year column. required_orering = (year)actual_ordering = (user_id) ... this doesn't satisfy the requirement To achieve our goal and save the data (each partition) sorted by user_id we can instead do this: ( df.repartition('year') .sortWithinPartitions('year', 'user_id') .write .mode('overwrite') .partitionBy('year') .option('path', output_path) .saveAsTable(table_name)) Notice the difference now, we sort explicitly each partition by year and user_id, but since the data will be partitioned by year the sort by this column doesn’t really matter. What matters is that now the Spark’s requirement will be satisfied, so Spark will preserve our order and save the data sorted by year and user_id and since we partition by year, it basically means that each partition will be sorted by user_id, which is exactly what we want. required_orering = (year)actual_ordering = (year, user_id) ... this satisfies the requirement Saving the data partitioned where each partition is sorted, will allow for efficient analytical queries with filters that will skip data on two levels — partition level and row-group level. Imagine a query like this: ( spark.table(table_name) .filter(col('year') == 2020) .filter(col('user_id') == 1) .collect()) This will first use the partition filter to prune the partitions and inside this single partition 2020 it will check the metadata from the parquet footers for each row-group. Based on the statistics in the metadata Spark will pick the row-groups with min≤1 and max≥1 and only these row-groups will be scanned, so this will speed-up the query especially if there are lots of row-groups that can be skipped. In this article, we described three different ways how to save data to a file format (specifically Apache Parquet) using Spark and we also explained why Parquet is such a popular data format especially when it comes to analytical queries. We also pointed out some Spark features that are not so obvious such as the behavior of the insertInto function or how to save data in the sorted state.
[ { "code": null, "e": 775, "s": 171, "text": "Apache Spark is a computational engine frequently used in a big data environment for data processing but it doesn’t provide storage so in a typical scenario the output of the data processing has to be stored in an external storage system. Spark SQL provides a couple of connectors for datasources such as file format (CSV, JSON, text, Parquet, ORC) or JDBC. Since 2.4 there is also support for Apache Avro and since 3.0 also read support for binary files. In addition, there are several libraries that allow connecting to other datasources, for example, MongoDB, ElasticSearch, or DynamoDB to name some." }, { "code": null, "e": 1465, "s": 775, "text": "In this article, we will go over some possibilities that we have when saving data to a file format such as Apache Parquet, because the combination of Spark with Parquet provides a very nice experience, especially for analytical queries. We will first explain why Parquet is such a popular format for storing data in the Hadoop ecosystem and then we will describe different ways how to save the data with Spark while focussing especially on features that are missing in the official documentation or are difficult to find. One of these non-trivial features that we will look at is how to save the data in a pre-sorted state so it can be leveraged for data skipping with appropriate filters." }, { "code": null, "e": 1560, "s": 1465, "text": "The provided code snippets are using the Python API and are checked against Spark 3.0 and 2.4." }, { "code": null, "e": 2294, "s": 1560, "text": "Apache Parquet is an open-source file format originally developed at Twitter and Cloudera. It is a self-describing format, which means that it contains metadata with information about the schema (among other things). It is using a hybrid model for storing the data on the disk and by hybrid, we mean that it is not strictly row-oriented (such as JSON or CSV) neither strictly columnar but instead the data is first divided vertically into so-called row-groups and then each row-group is stored in a columnar representation. These row-groups allow for splitting the dataset into multiple files (each file can have one or more row-groups) so we don’t end up with one huge file which is important especially in the big data environment." }, { "code": null, "e": 3066, "s": 2294, "text": "The columnar representation of each row-group is also a very important feature because it allows for a so-called column pruning. In analytical queries, we are not usually interested in all columns of the dataset but rather we select a few columns and do some aggregation on it. This column pruning lets us skip all other columns and scan only those selected in the query so it makes the reading much more efficient as compared to row-oriented formats where all columns have to be scanned. Another advantage of columnar formats is compression — each value in the column has the same data type and the values may even get repeated which can be used to store the data more efficiently using various encoding and compression techniques (that Parquet supports under the hood)." }, { "code": null, "e": 3787, "s": 3066, "text": "Parquet files support data skipping on different levels, namely on partition level and row-group level. So a dataset can be partitioned by some (usually low-cardinality) key and this means that for each distinct value of this field there is going to be a subfolder in the root directory that will contain all records with that particular value of the key (each partition can still be divided into multiple files). The use case for the partitioning is to reduce the volume of the data when reading because when the partition key is used in a filter, Spark will apply partition pruning and it will skip all partitions that are not relevant for the query (this is supported also for other file formats such as JSON or CSV)." }, { "code": null, "e": 4654, "s": 3787, "text": "The row-group level data skipping is based on parquet metadata because each parquet file has a footer that contains metadata about each row-group and this metadata contains statistical information such as min and max value for each column in the row-group. When reading the parquet file, Spark will first read the footer and use these statistics to check whether a given row-group can potentially contain relevant data for the query. This will be useful especially if the parquet file is sorted by the column that we use for filtering. Because, if the file is not sorted, then small and large values can be scattered across all row-groups and thus each row-group will have to be scanned because it can potentially contain some rows satisfied by the filter. The sort here is crucial and as we will see later on, it is not trivial to save the data in the sorted state." }, { "code": null, "e": 4761, "s": 4654, "text": "One of the options for saving the output of computation in Spark to a file format is using the save method" }, { "code": null, "e": 4948, "s": 4761, "text": "( df.write .mode('overwrite') # or append .partitionBy(col_name) # this is optional .format('parquet') # this is optional, parquet is default .option('path', output_path) .save())" }, { "code": null, "e": 5161, "s": 4948, "text": "As you can see it allows you to specify partition columns if you want the data to be partitioned in the file system where you save it. The default format is parquet so if you don’t specify it, it will be assumed." }, { "code": null, "e": 5339, "s": 5161, "text": "The data analyst who will be using the data will probably more appreciate if you save the data with the saveAsTable method because it will allow him/her to access the data using" }, { "code": null, "e": 5368, "s": 5339, "text": "df = spark.table(table_name)" }, { "code": null, "e": 5476, "s": 5368, "text": "The saveAsTable function allows also for using bucketing where each bucket can be also (optionally) sorted:" }, { "code": null, "e": 5748, "s": 5476, "text": "( df.write .mode('overwrite') # or append .partitionBy(col_name) # this is optional .bucketBy(n, col_name) # n is number of buckets .sortBy(col_name) .format('parquet') # this is optional, parquet is default .option('path', output_path) .saveAsTable(table_name))" }, { "code": null, "e": 6470, "s": 5748, "text": "We will not dive into bucketing here, but in general, it is a technique on how to pre-shuffle the data and save it in this state so it can be leveraged by follow-up queries to avoid shuffle. This is going to work if the metastore is properly set up with Spark because the information about bucketing will be saved here. This approach has also other benefits since the metastore can keep also other information about your dataset such as statistics when you call the ANALYZE TABLE command later on. The sortBy can be used only after bucketBy, because what will be sorted are the created buckets. Both modes overwrite and append will work here even if the table doesn’t exist yet because the function will simply create it." }, { "code": null, "e": 6741, "s": 6470, "text": "Yet another possibility of how to save data is using the insertInto function. Unlike in the previous case, the table has to exist first, because if it doesn’t, you will get an error: AnalysisException: Table not found. The syntax for using this function is rather simple" }, { "code": null, "e": 6779, "s": 6741, "text": "( df.write .insertInto(table_name))" }, { "code": null, "e": 6837, "s": 6779, "text": "but there are some cautions that are good to be aware of:" }, { "code": null, "e": 6983, "s": 6837, "text": "You don’t have to specify the output path. Spark will find that information in the metastore. If you specify the path anyway, it will be ignored." }, { "code": null, "e": 7066, "s": 6983, "text": "The default mode is append, so it will simply add your data to the existing table." }, { "code": null, "e": 7521, "s": 7066, "text": "The schema of your DataFrame must match the schema of the table. If the order of the columns in your DataFrame is different than the order in the table, Spark will throw an exception if the data types are different and can't be safely cast. But if there is not a mismatch in data types, Spark will insert the data to the table in this wrong order. So this is quite dangerous and it is good to make sure that the schema is the same for example as follows:" }, { "code": null, "e": 7601, "s": 7521, "text": "( df.select(spark.table(table_name).columns) .write .insertInto(table_name))" }, { "code": null, "e": 7752, "s": 7601, "text": "if your table is partitioned or bucketed, you don’t specify that (you would get an error) because Spark will pick that information from the metastore." }, { "code": null, "e": 8329, "s": 7752, "text": "The function insertInto has one big advantage over saveAsTable because it allows for a so-called dynamic overwrite. This feature lets you overwrite a specific partition in a partitioned table. For example, if your table is partitioned by year and you want to update only one year, then with saveAsTable you would have to overwrite the entire table, but with insertInto, you can overwrite only this single partition so it will be a much cheaper operation especially if there are lots of big partitions. To use this feature you have to set a corresponding configuration setting:" }, { "code": null, "e": 8497, "s": 8329, "text": "spark.conf.set(\"spark.sql.sources.partitionOverwriteMode\", \"dynamic\")( df # having data only for specific partitions .write .insertInto(table_name, overwrite=True))" }, { "code": null, "e": 8814, "s": 8497, "text": "Here again, it is good to be careful, because if the partitionOverwriteMode is set to static (which is the default value) it would overwrite the entire table and so all other partitions would become empty. The dynamic value makes sure that Spark will overwrite only partitions that we have data for in our DataFrame." }, { "code": null, "e": 9231, "s": 8814, "text": "As we mentioned above, sometimes it is desirable to save the data in the sorted state according to some column so it could be used for data skipping in analytical queries that use this column as a filter. In Spark SQL there are three functions when it comes to sorting. There is orderBy (or equivalently sort), sortWithinPartitions, and sortBy. Let’s see what is the difference between them and how they can be used:" }, { "code": null, "e": 10911, "s": 9231, "text": "orderBy — it is a DataFrame transformation that will invoke a global sort. This will first run a separate job that will sample the data to check the distribution of values in the sorting column. This distribution is then used to create boundaries for partitions and the dataset will be shuffled to create these partitions. It is quite an expensive operation and if you save the data into a partitioned table it may create lots of small files if the data distribution on the cluster is very different from the final distribution of the table in the file system (for example if you sort by date and your table is partitioned by country, each task in the final stage of the Spark job may potentially carry data for each country, so each task will write a new file into each file system partition).sortWithinPartitions — it is also a DataFrame transformation and unlike in the previous case Spark will not try to achieve a global sort but instead, it will sort each partition separately. So here you can distribute the data on the Spark cluster as you require for the final layout using the repartition() function (this will also create a shuffle) and then call sortWithinPartitions to have each partition sorted. The advantage of this approach over the previous one is that you can avoid having lots of small files and still have the output sorted.sortBy — this function can be called on a DataFrameWritter (after calling df.write) if we also call bucketBy and use saveAsTable method for saving. It is going to make sure that each bucket is sorted (one bucket can be either one file or more files depending on the distribution of data on the Spark cluster at the moment of writing)." }, { "code": null, "e": 11706, "s": 10911, "text": "orderBy — it is a DataFrame transformation that will invoke a global sort. This will first run a separate job that will sample the data to check the distribution of values in the sorting column. This distribution is then used to create boundaries for partitions and the dataset will be shuffled to create these partitions. It is quite an expensive operation and if you save the data into a partitioned table it may create lots of small files if the data distribution on the cluster is very different from the final distribution of the table in the file system (for example if you sort by date and your table is partitioned by country, each task in the final stage of the Spark job may potentially carry data for each country, so each task will write a new file into each file system partition)." }, { "code": null, "e": 12258, "s": 11706, "text": "sortWithinPartitions — it is also a DataFrame transformation and unlike in the previous case Spark will not try to achieve a global sort but instead, it will sort each partition separately. So here you can distribute the data on the Spark cluster as you require for the final layout using the repartition() function (this will also create a shuffle) and then call sortWithinPartitions to have each partition sorted. The advantage of this approach over the previous one is that you can avoid having lots of small files and still have the output sorted." }, { "code": null, "e": 12593, "s": 12258, "text": "sortBy — this function can be called on a DataFrameWritter (after calling df.write) if we also call bucketBy and use saveAsTable method for saving. It is going to make sure that each bucket is sorted (one bucket can be either one file or more files depending on the distribution of data on the Spark cluster at the moment of writing)." }, { "code": null, "e": 12905, "s": 12593, "text": "Using the first two functions has one big catch that you would not find in documentation (written in October 2020). Let’s see it on a simple example. For the sake of simplicity we want to partition the data by year and have each partition sorted by user_id, and for saving we use saveAsTable(). If you just call" }, { "code": null, "e": 13072, "s": 12905, "text": "( df.repartition('year') .sortWithinPartitions('user_id') .write .mode('overwrite') .partitionBy('year') .option('path', output_path) .saveAsTable(table_name))" }, { "code": null, "e": 13272, "s": 13072, "text": "It is not going to work! It will not raise any error and it will save the data but the order will not be preserved! The point is that when writing data to a file format, Spark requires this ordering:" }, { "code": null, "e": 13326, "s": 13272, "text": "(partitionColumns + bucketIdExpression + sortColumns)" }, { "code": null, "e": 14292, "s": 13326, "text": "here partitionColumns are columns by which we partition the data to the file system, bucketingIdExpression is derived from the bucketing column (not relevant in our query because we are not using bucketing here) and sortColumns are columns used in sortBy with bucketing (again not relevant for our query). If the data is sorted by these columns (and possibly some more), the requirement will be satisfied and Spark will preserve the order. If however, this requirement is not satisfied, Spark will forget the previous order and will sort the data again according to this requirement while writing the data. In our example, the required ordering is (year) which is the partition column and we don’t have any bucketing here. This requirement is however not satisfied, because the actual ordering is (user_id), which is the column by which we sorted the data and this is the reason why Spark will not preserve our order and will sort the data again by the year column." }, { "code": null, "e": 14386, "s": 14292, "text": "required_orering = (year)actual_ordering = (user_id) ... this doesn't satisfy the requirement" }, { "code": null, "e": 14483, "s": 14386, "text": "To achieve our goal and save the data (each partition) sorted by user_id we can instead do this:" }, { "code": null, "e": 14658, "s": 14483, "text": "( df.repartition('year') .sortWithinPartitions('year', 'user_id') .write .mode('overwrite') .partitionBy('year') .option('path', output_path) .saveAsTable(table_name))" }, { "code": null, "e": 15109, "s": 14658, "text": "Notice the difference now, we sort explicitly each partition by year and user_id, but since the data will be partitioned by year the sort by this column doesn’t really matter. What matters is that now the Spark’s requirement will be satisfied, so Spark will preserve our order and save the data sorted by year and user_id and since we partition by year, it basically means that each partition will be sorted by user_id, which is exactly what we want." }, { "code": null, "e": 15203, "s": 15109, "text": "required_orering = (year)actual_ordering = (year, user_id) ... this satisfies the requirement" }, { "code": null, "e": 15420, "s": 15203, "text": "Saving the data partitioned where each partition is sorted, will allow for efficient analytical queries with filters that will skip data on two levels — partition level and row-group level. Imagine a query like this:" }, { "code": null, "e": 15520, "s": 15420, "text": "( spark.table(table_name) .filter(col('year') == 2020) .filter(col('user_id') == 1) .collect())" }, { "code": null, "e": 15926, "s": 15520, "text": "This will first use the partition filter to prune the partitions and inside this single partition 2020 it will check the metadata from the parquet footers for each row-group. Based on the statistics in the metadata Spark will pick the row-groups with min≤1 and max≥1 and only these row-groups will be scanned, so this will speed-up the query especially if there are lots of row-groups that can be skipped." } ]
Change string to a new character set - GeeksforGeeks
24 Feb, 2022 Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd....xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output : code Idea behind conversion of new character set is to use hashing. Perform hashing of new character set where element of set is index and its position will be new alphabet value. Approach1: Given New character set = “qwertyuiopasdfghjklzxcvbnm” First character is q, during hashing we will place ‘a’ (for position ) at index q i.e. (17th).After hashing our new character set is “kxvmcnophqrszyijadlegwbuft”.For input “egrt” = hash[e -‘a’] = c hash[g -‘a’] = o hash[r -‘a’] = d hash[t -‘a’] = eFor “egrt” is equivalent to “code”. First character is q, during hashing we will place ‘a’ (for position ) at index q i.e. (17th). After hashing our new character set is “kxvmcnophqrszyijadlegwbuft”. For input “egrt” = hash[e -‘a’] = c hash[g -‘a’] = o hash[r -‘a’] = d hash[t -‘a’] = eFor “egrt” is equivalent to “code”. C++ Java C# Javascript // CPP program to change the sentence// with virtual dictionary#include<bits/stdc++.h>using namespace std; // Converts str to given character setvoid conversion(char charSet[], string &str){ int n = str.length(); // hashing for new character set char hashChar[26]; for (int i = 0; i < 27; i++) hashChar[charSet[i]-'a'] = 'a' + i; // conversion of new character set for (int i = 0; i < n; i++) str[i] = hashChar[str[i]-'a'];} // Driver codeint main(){ char charSet[27] = "qwertyuiopasdfghjklzxcvbnm"; string str = "egrt"; conversion(charSet, str); cout << str; return 0;} // Java program to change the sentence// with virtual dictionaryclass GFG { // Converts str to given character set static String conversion(char charSet[], String str) { int n = str.length(); // hashing for new character set char hashChar[] = new char[26]; for (int i = 0; i < 26; i++) { int ch = Math.abs(charSet[i] - 'a'); hashChar[ch] = (char) ('a' + i); } // conversion of new character set String s=""; for (int i = 0; i < n; i++) { s += hashChar[str.charAt(i) - 'a']; } return s; } // Driver code public static void main(String[] args) { char charSet[] = "qwertyuiopasdfghjklzxcvbnm".toCharArray(); String str = "egrt"; str = conversion(charSet, str); System.out.println(str);// This code is contributed by princiRaj1992 }} // C# program to change the sentence// with virtual dictionaryusing System; class GFG{ // Converts str to given character set static String conversion(char []charSet, String str) { int n = str.Length; // hashing for new character set char []hashChar = new char[26]; for (int i = 0; i < 26; i++) { int ch = Math.Abs(charSet[i] - 'a'); hashChar[ch] = (char) ('a' + i); } // conversion of new character set String s = ""; for (int i = 0; i < n; i++) { s += hashChar[str[i] - 'a']; } return s; } // Driver code public static void Main(String[] args) { char []charSet = "qwertyuiopasdfghjklzxcvbnm".ToCharArray(); String str = "egrt"; str = conversion(charSet, str); Console.WriteLine(str); }} // This code is contributed by Princi Singh <script>// Javascript program to change the sentence// with virtual dictionary // Converts str to given character setfunction conversion(charSet, str){ var n = str.length; // hashing for new character set var hashChar = Array(26); for (var i = 0; i < 26; i++) { var ch = Math.abs(charSet[i].charCodeAt(0)- 'a'.charCodeAt(0)); hashChar[ch] = String.fromCharCode('a'.charCodeAt(0) + i); } var s = ""; // conversion of new character set for (var i = 0; i < n; i++) s += (hashChar[str[i].charCodeAt(0)-'a'.charCodeAt(0)]); return s;} // Driver codevar charSet = "qwertyuiopasdfghjklzxcvbnm".split('');var str = "egrt";str = conversion(charSet, str);document.write( str); // This code is contributed by importantly.</script> Output: code Approach2: 1.Initialize two strings, one with actual set of alphabets and another with modified one. 2.Get the string to be converted from the user. 3.Retrieve the first element of the string, find its index in the modified set of alphabets(eg:0 for ‘q’). 4.Find the element of same index in the actual set of alphabets and concatenate it with the result string. 5.Repeat the above steps for all the remaining elements of the input string. 6.Return the result string. Java Python3 C# Javascript // Java program to change the sentence// with virtual dictionary class GFG{ static char[] alphabets = "abcdefghijklmnopqrstuvwxyz".toCharArray(); // function for converting the string static String conversion(String charSet, char[] str1) { String s2 = ""; for (char i : str1) // find the index of each element of the // string in the modified set of alphabets // replace the element with the one having the // same index in the actual set of alphabets s2 += alphabets[charSet.indexOf(i)]; return s2; } // Driver Code public static void main(String[] args) { String charSet = "qwertyuiopasdfghjklzxcvbnm"; String str1 = "egrt"; System.out.print(conversion(charSet, str1.toCharArray())); }} // This code is contributed by PrinciRaj1992 # Python3 program to change the sentence# with virtual dictionary #function for converting the stringdef conversion(charSet,str1): s2="" for i in str1: # find the index of each element of the # string in the modified set of alphabets # replace the element with the one having the # same index in the actual set of alphabets s2 += alphabets[charSet.index(i)] return s2 # Driver Codeif __name__=='__main__': alphabets = "abcdefghijklmnopqrstuvwxyz" charSet= "qwertyuiopasdfghjklzxcvbnm" str1 = "egrt" print(conversion(charSet,str1)) #This code is contributed by PradeepEswar // C# program to change the sentence// with virtual dictionaryusing System; class GFG{ static char[] alphabets = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); // function for converting the string static String conversion(String charSet, char[] str1) { String s2 = ""; foreach (char i in str1) // find the index of each element of the // string in the modified set of alphabets // replace the element with the one having the // same index in the actual set of alphabets s2 += alphabets[charSet.IndexOf(i)]; return s2; } // Driver Code public static void Main(String[] args) { String charSet = "qwertyuiopasdfghjklzxcvbnm"; String str1 = "egrt"; Console.Write(conversion(charSet, str1.ToCharArray())); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to change the sentence // with virtual dictionary var alphabets = "abcdefghijklmnopqrstuvwxyz".split(""); // function for converting the string function conversion(charSet, str1) { var s2 = ""; str1.forEach((i) => { // find the index of each element of the // string in the modified set of alphabets // replace the element with the one having the // same index in the actual set of alphabets s2 = s2 + alphabets[charSet.indexOf(i)]; }); return s2; } // Driver Code var charSet = "qwertyuiopasdfghjklzxcvbnm"; var str1 = "egrt"; document.write(conversion(charSet, str1.split(""))); // This code is contributed by rdtank. </script> Output: code PradeepEswar princiraj1992 princi singh Rajput-Ji saurabh1990aror importantly rdtank singhpalak2020 Hash Strings Technical Scripter Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Double Hashing Rearrange an array such that arr[i] = i Design a data structure that supports insert, delete, search and getRandom in constant time Quadratic Probing in Hashing Check if two arrays are equal or not 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 Longest Common Subsequence | DP-4
[ { "code": null, "e": 26391, "s": 26363, "text": "\n24 Feb, 2022" }, { "code": null, "e": 26631, "s": 26391, "text": "Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd....xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set." }, { "code": null, "e": 26642, "s": 26631, "text": "Examples: " }, { "code": null, "e": 26748, "s": 26642, "text": "New character set : qwertyuiopasdfghjklzxcvbnm\nInput : \"utta\"\nOutput : geek\n\nInput : \"egrt\"\nOutput : code" }, { "code": null, "e": 26924, "s": 26748, "text": "Idea behind conversion of new character set is to use hashing. Perform hashing of new character set where element of set is index and its position will be new alphabet value. " }, { "code": null, "e": 26991, "s": 26924, "text": "Approach1: Given New character set = “qwertyuiopasdfghjklzxcvbnm” " }, { "code": null, "e": 27283, "s": 26991, "text": "First character is q, during hashing we will place ‘a’ (for position ) at index q i.e. (17th).After hashing our new character set is “kxvmcnophqrszyijadlegwbuft”.For input “egrt” = hash[e -‘a’] = c hash[g -‘a’] = o hash[r -‘a’] = d hash[t -‘a’] = eFor “egrt” is equivalent to “code”." }, { "code": null, "e": 27378, "s": 27283, "text": "First character is q, during hashing we will place ‘a’ (for position ) at index q i.e. (17th)." }, { "code": null, "e": 27447, "s": 27378, "text": "After hashing our new character set is “kxvmcnophqrszyijadlegwbuft”." }, { "code": null, "e": 27577, "s": 27447, "text": "For input “egrt” = hash[e -‘a’] = c hash[g -‘a’] = o hash[r -‘a’] = d hash[t -‘a’] = eFor “egrt” is equivalent to “code”." }, { "code": null, "e": 27581, "s": 27577, "text": "C++" }, { "code": null, "e": 27586, "s": 27581, "text": "Java" }, { "code": null, "e": 27589, "s": 27586, "text": "C#" }, { "code": null, "e": 27600, "s": 27589, "text": "Javascript" }, { "code": "// CPP program to change the sentence// with virtual dictionary#include<bits/stdc++.h>using namespace std; // Converts str to given character setvoid conversion(char charSet[], string &str){ int n = str.length(); // hashing for new character set char hashChar[26]; for (int i = 0; i < 27; i++) hashChar[charSet[i]-'a'] = 'a' + i; // conversion of new character set for (int i = 0; i < n; i++) str[i] = hashChar[str[i]-'a'];} // Driver codeint main(){ char charSet[27] = \"qwertyuiopasdfghjklzxcvbnm\"; string str = \"egrt\"; conversion(charSet, str); cout << str; return 0;}", "e": 28230, "s": 27600, "text": null }, { "code": "// Java program to change the sentence// with virtual dictionaryclass GFG { // Converts str to given character set static String conversion(char charSet[], String str) { int n = str.length(); // hashing for new character set char hashChar[] = new char[26]; for (int i = 0; i < 26; i++) { int ch = Math.abs(charSet[i] - 'a'); hashChar[ch] = (char) ('a' + i); } // conversion of new character set String s=\"\"; for (int i = 0; i < n; i++) { s += hashChar[str.charAt(i) - 'a']; } return s; } // Driver code public static void main(String[] args) { char charSet[] = \"qwertyuiopasdfghjklzxcvbnm\".toCharArray(); String str = \"egrt\"; str = conversion(charSet, str); System.out.println(str);// This code is contributed by princiRaj1992 }}", "e": 29105, "s": 28230, "text": null }, { "code": "// C# program to change the sentence// with virtual dictionaryusing System; class GFG{ // Converts str to given character set static String conversion(char []charSet, String str) { int n = str.Length; // hashing for new character set char []hashChar = new char[26]; for (int i = 0; i < 26; i++) { int ch = Math.Abs(charSet[i] - 'a'); hashChar[ch] = (char) ('a' + i); } // conversion of new character set String s = \"\"; for (int i = 0; i < n; i++) { s += hashChar[str[i] - 'a']; } return s; } // Driver code public static void Main(String[] args) { char []charSet = \"qwertyuiopasdfghjklzxcvbnm\".ToCharArray(); String str = \"egrt\"; str = conversion(charSet, str); Console.WriteLine(str); }} // This code is contributed by Princi Singh", "e": 30043, "s": 29105, "text": null }, { "code": "<script>// Javascript program to change the sentence// with virtual dictionary // Converts str to given character setfunction conversion(charSet, str){ var n = str.length; // hashing for new character set var hashChar = Array(26); for (var i = 0; i < 26; i++) { var ch = Math.abs(charSet[i].charCodeAt(0)- 'a'.charCodeAt(0)); hashChar[ch] = String.fromCharCode('a'.charCodeAt(0) + i); } var s = \"\"; // conversion of new character set for (var i = 0; i < n; i++) s += (hashChar[str[i].charCodeAt(0)-'a'.charCodeAt(0)]); return s;} // Driver codevar charSet = \"qwertyuiopasdfghjklzxcvbnm\".split('');var str = \"egrt\";str = conversion(charSet, str);document.write( str); // This code is contributed by importantly.</script>", "e": 30835, "s": 30043, "text": null }, { "code": null, "e": 30844, "s": 30835, "text": "Output: " }, { "code": null, "e": 30849, "s": 30844, "text": "code" }, { "code": null, "e": 31330, "s": 30849, "text": "Approach2: 1.Initialize two strings, one with actual set of alphabets and another with modified one. 2.Get the string to be converted from the user. 3.Retrieve the first element of the string, find its index in the modified set of alphabets(eg:0 for ‘q’). 4.Find the element of same index in the actual set of alphabets and concatenate it with the result string. 5.Repeat the above steps for all the remaining elements of the input string. 6.Return the result string. " }, { "code": null, "e": 31335, "s": 31330, "text": "Java" }, { "code": null, "e": 31343, "s": 31335, "text": "Python3" }, { "code": null, "e": 31346, "s": 31343, "text": "C#" }, { "code": null, "e": 31357, "s": 31346, "text": "Javascript" }, { "code": "// Java program to change the sentence// with virtual dictionary class GFG{ static char[] alphabets = \"abcdefghijklmnopqrstuvwxyz\".toCharArray(); // function for converting the string static String conversion(String charSet, char[] str1) { String s2 = \"\"; for (char i : str1) // find the index of each element of the // string in the modified set of alphabets // replace the element with the one having the // same index in the actual set of alphabets s2 += alphabets[charSet.indexOf(i)]; return s2; } // Driver Code public static void main(String[] args) { String charSet = \"qwertyuiopasdfghjklzxcvbnm\"; String str1 = \"egrt\"; System.out.print(conversion(charSet, str1.toCharArray())); }} // This code is contributed by PrinciRaj1992", "e": 32227, "s": 31357, "text": null }, { "code": "# Python3 program to change the sentence# with virtual dictionary #function for converting the stringdef conversion(charSet,str1): s2=\"\" for i in str1: # find the index of each element of the # string in the modified set of alphabets # replace the element with the one having the # same index in the actual set of alphabets s2 += alphabets[charSet.index(i)] return s2 # Driver Codeif __name__=='__main__': alphabets = \"abcdefghijklmnopqrstuvwxyz\" charSet= \"qwertyuiopasdfghjklzxcvbnm\" str1 = \"egrt\" print(conversion(charSet,str1)) #This code is contributed by PradeepEswar", "e": 32866, "s": 32227, "text": null }, { "code": "// C# program to change the sentence// with virtual dictionaryusing System; class GFG{ static char[] alphabets = \"abcdefghijklmnopqrstuvwxyz\".ToCharArray(); // function for converting the string static String conversion(String charSet, char[] str1) { String s2 = \"\"; foreach (char i in str1) // find the index of each element of the // string in the modified set of alphabets // replace the element with the one having the // same index in the actual set of alphabets s2 += alphabets[charSet.IndexOf(i)]; return s2; } // Driver Code public static void Main(String[] args) { String charSet = \"qwertyuiopasdfghjklzxcvbnm\"; String str1 = \"egrt\"; Console.Write(conversion(charSet, str1.ToCharArray())); }} // This code is contributed by Rajput-Ji", "e": 33745, "s": 32866, "text": null }, { "code": "<script> // JavaScript program to change the sentence // with virtual dictionary var alphabets = \"abcdefghijklmnopqrstuvwxyz\".split(\"\"); // function for converting the string function conversion(charSet, str1) { var s2 = \"\"; str1.forEach((i) => { // find the index of each element of the // string in the modified set of alphabets // replace the element with the one having the // same index in the actual set of alphabets s2 = s2 + alphabets[charSet.indexOf(i)]; }); return s2; } // Driver Code var charSet = \"qwertyuiopasdfghjklzxcvbnm\"; var str1 = \"egrt\"; document.write(conversion(charSet, str1.split(\"\"))); // This code is contributed by rdtank. </script>", "e": 34546, "s": 33745, "text": null }, { "code": null, "e": 34555, "s": 34546, "text": "Output: " }, { "code": null, "e": 34560, "s": 34555, "text": "code" }, { "code": null, "e": 34575, "s": 34562, "text": "PradeepEswar" }, { "code": null, "e": 34589, "s": 34575, "text": "princiraj1992" }, { "code": null, "e": 34602, "s": 34589, "text": "princi singh" }, { "code": null, "e": 34612, "s": 34602, "text": "Rajput-Ji" }, { "code": null, "e": 34628, "s": 34612, "text": "saurabh1990aror" }, { "code": null, "e": 34640, "s": 34628, "text": "importantly" }, { "code": null, "e": 34647, "s": 34640, "text": "rdtank" }, { "code": null, "e": 34662, "s": 34647, "text": "singhpalak2020" }, { "code": null, "e": 34667, "s": 34662, "text": "Hash" }, { "code": null, "e": 34675, "s": 34667, "text": "Strings" }, { "code": null, "e": 34694, "s": 34675, "text": "Technical Scripter" }, { "code": null, "e": 34699, "s": 34694, "text": "Hash" }, { "code": null, "e": 34707, "s": 34699, "text": "Strings" }, { "code": null, "e": 34805, "s": 34707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34820, "s": 34805, "text": "Double Hashing" }, { "code": null, "e": 34860, "s": 34820, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 34952, "s": 34860, "text": "Design a data structure that supports insert, delete, search and getRandom in constant time" }, { "code": null, "e": 34981, "s": 34952, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 35018, "s": 34981, "text": "Check if two arrays are equal or not" }, { "code": null, "e": 35064, "s": 35018, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 35089, "s": 35064, "text": "Reverse a string in Java" }, { "code": null, "e": 35149, "s": 35089, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35164, "s": 35149, "text": "C++ Data Types" } ]
Count of lines required to write the given String - GeeksforGeeks
29 Jul, 2021 Given a string str and an integer array width[] where: width[0] = width of character ‘a’ width[1] = width of character ‘b’ ... width[25] = width of character ‘z’ The task is to find the number of lines it’ll take to write the string str on a paper and the width of the last line upto which it is occupied. Note: Width of a line is 10 units.Examples: Input: str = “bbbcccdddaa”, width[] = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} Output: (2, 8) “bbbcccddd” will cover first line (9 * 1 = 9 units) As ‘a’ has a width of 4 which cannot fit the remaining 1 unit in the first line. It’ll have to be written in the second line. So, next line will contain “aa” covering 4 * 2 = 8 units. We need 1 full line and one line with width 8 units.Input: str = “abcdefghijklmnopqrstuvwxyz”, width[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} Output: (3, 6) All the characters have the same width of 1. To write all 26 characters, We need 2 full lines and one line with width 6 units. Approach: We will write each character in the string str one by one. As we write a character, we immediately update (lines, width) that keeps track of how many lines we have used till now and what is the length of the used space in the last line. If the width[char] in str fits our current line, we will add it. Otherwise, we will start with a new lineBelow is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of lines requiredpair<int, int> numberOfLines(string S, int *widths){ // If string is empty if (S.empty()) return {0, 0}; // Initialize lines and width int lines = 1, width = 0; // Iterate through S for (auto character : S) { int w = widths[character - 'a']; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return {lines, width};} // Driver Codeint main(){ string S = "bbbcccdddaa"; int widths[] = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // Function call to print required answer pair<int, int> ans = numberOfLines(S, widths); cout << ans.first << " " << ans.second << endl; return 0;} // This code is contributed by// sanjeev2552 // JAVA implementation of the approachclass GFG{ // Function to return the number of lines requiredstatic int[] numberOfLines(String S, int []widths){ // If String is empty if (S.isEmpty()) return new int[]{0, 0}; // Initialize lines and width int lines = 1, width = 0; // Iterate through S for (char character : S.toCharArray()) { int w = widths[character - 'a']; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return new int[]{lines, width};} // Driver Codepublic static void main(String[] args){ String S = "bbbcccdddaa"; int widths[] = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // Function call to print required answer int []ans = numberOfLines(S, widths); System.out.print(ans[0]+ " " + ans[1] +"\n");}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function to return the number of lines requireddef numberOfLines(S, widths): # If string is empty if(S == ""): return 0, 0 # Initialize lines and width lines, width = 1, 0 # Iterate through S for c in S: w = widths[ord(c) - ord('a')] width += w if width > 10: lines += 1 width = w # Return lines and width used return lines, width # Driver CodeS = "bbbcccdddaa"Widths = [4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Function call to print required answerprint(numberOfLines(S, Widths)) // C# implementation of the approachusing System; class GFG{ // Function to return the number of lines requiredstatic int[] numberOfLines(String S, int []widths){ // If String is empty if (S.Length == 0) return new int[]{0, 0}; // Initialize lines and width int lines = 1, width = 0; // Iterate through S foreach (char character in S.ToCharArray()) { int w = widths[character - 'a']; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return new int[]{lines, width};} // Driver Codepublic static void Main(String[] args){ String S = "bbbcccdddaa"; int []widths = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // Function call to print required answer int []ans = numberOfLines(S, widths); Console.Write(ans[0]+ " " + ans[1] +"\n");}} // This code is contributed by 29AjayKumar <script>// JAVAscript implementation of the approach // Function to return the number of lines requiredfunction numberOfLines(S,widths){ // If String is empty if (S.length==0) return [0, 0]; // Initialize lines and width let lines = 1, width = 0; // Iterate through S for (let character of S.split("")) { let w = widths[character.charCodeAt(0) - 'a'.charCodeAt(0)]; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return [lines, width];} // Driver Codelet S = "bbbcccdddaa";let widths = [4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; // Function call to print required answerlet ans = numberOfLines(S, widths);document.write(ans[0]+ " " + ans[1] +"<br>"); // This code is contributed by rag2127 </script> (2, 8) sanjeev2552 Rajput-Ji 29AjayKumar rag2127 Greedy Pattern Searching Python Strings Strings Greedy Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Program for First Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Max Flow Problem Introduction KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Check if a string is substring of another Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 26561, "s": 26533, "text": "\n29 Jul, 2021" }, { "code": null, "e": 26618, "s": 26561, "text": "Given a string str and an integer array width[] where: " }, { "code": null, "e": 26727, "s": 26618, "text": "width[0] = width of character ‘a’ width[1] = width of character ‘b’ ... width[25] = width of character ‘z’ " }, { "code": null, "e": 26917, "s": 26727, "text": "The task is to find the number of lines it’ll take to write the string str on a paper and the width of the last line upto which it is occupied. Note: Width of a line is 10 units.Examples: " }, { "code": null, "e": 27613, "s": 26917, "text": "Input: str = “bbbcccdddaa”, width[] = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} Output: (2, 8) “bbbcccddd” will cover first line (9 * 1 = 9 units) As ‘a’ has a width of 4 which cannot fit the remaining 1 unit in the first line. It’ll have to be written in the second line. So, next line will contain “aa” covering 4 * 2 = 8 units. We need 1 full line and one line with width 8 units.Input: str = “abcdefghijklmnopqrstuvwxyz”, width[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} Output: (3, 6) All the characters have the same width of 1. To write all 26 characters, We need 2 full lines and one line with width 6 units. " }, { "code": null, "e": 28020, "s": 27615, "text": "Approach: We will write each character in the string str one by one. As we write a character, we immediately update (lines, width) that keeps track of how many lines we have used till now and what is the length of the used space in the last line. If the width[char] in str fits our current line, we will add it. Otherwise, we will start with a new lineBelow is the implementation of the above approach: " }, { "code": null, "e": 28024, "s": 28020, "text": "C++" }, { "code": null, "e": 28029, "s": 28024, "text": "Java" }, { "code": null, "e": 28037, "s": 28029, "text": "Python3" }, { "code": null, "e": 28040, "s": 28037, "text": "C#" }, { "code": null, "e": 28051, "s": 28040, "text": "Javascript" }, { "code": "// CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of lines requiredpair<int, int> numberOfLines(string S, int *widths){ // If string is empty if (S.empty()) return {0, 0}; // Initialize lines and width int lines = 1, width = 0; // Iterate through S for (auto character : S) { int w = widths[character - 'a']; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return {lines, width};} // Driver Codeint main(){ string S = \"bbbcccdddaa\"; int widths[] = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // Function call to print required answer pair<int, int> ans = numberOfLines(S, widths); cout << ans.first << \" \" << ans.second << endl; return 0;} // This code is contributed by// sanjeev2552", "e": 29012, "s": 28051, "text": null }, { "code": "// JAVA implementation of the approachclass GFG{ // Function to return the number of lines requiredstatic int[] numberOfLines(String S, int []widths){ // If String is empty if (S.isEmpty()) return new int[]{0, 0}; // Initialize lines and width int lines = 1, width = 0; // Iterate through S for (char character : S.toCharArray()) { int w = widths[character - 'a']; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return new int[]{lines, width};} // Driver Codepublic static void main(String[] args){ String S = \"bbbcccdddaa\"; int widths[] = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // Function call to print required answer int []ans = numberOfLines(S, widths); System.out.print(ans[0]+ \" \" + ans[1] +\"\\n\");}} // This code is contributed by Rajput-Ji", "e": 29973, "s": 29012, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the number of lines requireddef numberOfLines(S, widths): # If string is empty if(S == \"\"): return 0, 0 # Initialize lines and width lines, width = 1, 0 # Iterate through S for c in S: w = widths[ord(c) - ord('a')] width += w if width > 10: lines += 1 width = w # Return lines and width used return lines, width # Driver CodeS = \"bbbcccdddaa\"Widths = [4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Function call to print required answerprint(numberOfLines(S, Widths))", "e": 30616, "s": 29973, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the number of lines requiredstatic int[] numberOfLines(String S, int []widths){ // If String is empty if (S.Length == 0) return new int[]{0, 0}; // Initialize lines and width int lines = 1, width = 0; // Iterate through S foreach (char character in S.ToCharArray()) { int w = widths[character - 'a']; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return new int[]{lines, width};} // Driver Codepublic static void Main(String[] args){ String S = \"bbbcccdddaa\"; int []widths = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // Function call to print required answer int []ans = numberOfLines(S, widths); Console.Write(ans[0]+ \" \" + ans[1] +\"\\n\");}} // This code is contributed by 29AjayKumar", "e": 31595, "s": 30616, "text": null }, { "code": "<script>// JAVAscript implementation of the approach // Function to return the number of lines requiredfunction numberOfLines(S,widths){ // If String is empty if (S.length==0) return [0, 0]; // Initialize lines and width let lines = 1, width = 0; // Iterate through S for (let character of S.split(\"\")) { let w = widths[character.charCodeAt(0) - 'a'.charCodeAt(0)]; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return [lines, width];} // Driver Codelet S = \"bbbcccdddaa\";let widths = [4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; // Function call to print required answerlet ans = numberOfLines(S, widths);document.write(ans[0]+ \" \" + ans[1] +\"<br>\"); // This code is contributed by rag2127 </script>", "e": 32492, "s": 31595, "text": null }, { "code": null, "e": 32499, "s": 32492, "text": "(2, 8)" }, { "code": null, "e": 32513, "s": 32501, "text": "sanjeev2552" }, { "code": null, "e": 32523, "s": 32513, "text": "Rajput-Ji" }, { "code": null, "e": 32535, "s": 32523, "text": "29AjayKumar" }, { "code": null, "e": 32543, "s": 32535, "text": "rag2127" }, { "code": null, "e": 32550, "s": 32543, "text": "Greedy" }, { "code": null, "e": 32568, "s": 32550, "text": "Pattern Searching" }, { "code": null, "e": 32575, "s": 32568, "text": "Python" }, { "code": null, "e": 32583, "s": 32575, "text": "Strings" }, { "code": null, "e": 32591, "s": 32583, "text": "Strings" }, { "code": null, "e": 32598, "s": 32591, "text": "Greedy" }, { "code": null, "e": 32616, "s": 32598, "text": "Pattern Searching" }, { "code": null, "e": 32714, "s": 32616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32749, "s": 32714, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 32801, "s": 32749, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 32854, "s": 32801, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 32905, "s": 32854, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 32935, "s": 32905, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 32971, "s": 32935, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 33014, "s": 32971, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 33056, "s": 33014, "text": "Check if a string is substring of another" }, { "code": null, "e": 33094, "s": 33056, "text": "Naive algorithm for Pattern Searching" } ]
Autocorrelation plot using Matplotlib - GeeksforGeeks
06 Aug, 2021 Autocorrelation plots are a commonly used tool for checking randomness in a data set. This randomness is ascertained by computing autocorrelations for data values at varying time lags. Characteristics Of Autocorrelation Plot : It measures a set of current values against a set of past values and finds whether they correlate. It is the correlation of one-time series data to another time series data which has a time lag. It varies from +1 to -1. An autocorrelation of +1 indicates that if time series one increases in value the time series 2 also increases in proportion to the change in time series 1. An autocorrelation of -1 indicates that if time series one increases in value the time series 2 decreases in proportion to the change in time series 1. Application of Autocorrelation: Pattern recognition. Signal detection. Signal processing. Estimating pitch. Technical analysis of stocks. To plot the Autocorrelation Plot we can use matplotlib and plot it easily by using matplotlib.pyplot.acorr() function. Syntax: matplotlib.pyplot.acorr(x, *, data=None, **kwargs)Parameters: ‘x’ : This parameter is a sequence of scalar. ‘detrend’ : This parameter is an optional parameter. Its default value is mlab.detrend_none. ‘normed’ : This parameter is also an optional parameter and contains the bool value. Its default value is True. ‘usevlines’ : This parameter is also an optional parameter and contains the bool value. Its default value is True. ‘maxlags’ : This parameter is also an optional parameter and contains the integer value. Its default value is 10. ‘linestyle’ : This parameter is also an optional parameter and used for plotting the data points, only when usevlines is False. ‘marker’ : This parameter is also an optional parameter and contains the string. Its default value is ‘o’. Returns: (lags, c, line, b) Where: lags are a length 2`maxlags+1 lag vector. c is the 2`maxlags+1 auto correlation vector. line is a Line2D instance returned by plot. b is the x-axis. Example 1: Python3 # Importing the libraries.import matplotlib.pyplot as pltimport numpy as np # Data for which we plot Autocorrelation.data = np.array([12.0, 24.0, 7., 20.0, 7.0, 22.0, 18.0,22.0, 6.0, 7.0, 20.0, 13.0, 8.0, 5.0, 8]) # Adding plot title.plt.title("Autocorrelation Plot") # Providing x-axis name.plt.xlabel("Lags") # Plotting the Autocorrelation plot.plt.acorr(data, maxlags = 10) # Displaying the plot.print("The Autocorrelation plot for the data is:")plt.grid(True) plt.show() Output: Example 2: Python3 # Importing the libraries.import matplotlib.pyplot as pltimport numpy as np # Setting up the rondom seed for# fixing the random state.np.random.seed(42) # Creating some random data.data = np.random.randn(25) # Adding plot title.plt.title("Autocorrelation Plot") # Providing x-axis name.plt.xlabel("Lags") # Plotting the Autocorrelation plot.plt.acorr(data, maxlags = 20) # Displaying the plot.print("The Autocorrelation plot for the data is:")plt.grid(True) plt.show() Output: kk9826225 as5853535 Python-matplotlib 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *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
[ { "code": null, "e": 26039, "s": 26011, "text": "\n06 Aug, 2021" }, { "code": null, "e": 26224, "s": 26039, "text": "Autocorrelation plots are a commonly used tool for checking randomness in a data set. This randomness is ascertained by computing autocorrelations for data values at varying time lags." }, { "code": null, "e": 26267, "s": 26224, "text": "Characteristics Of Autocorrelation Plot : " }, { "code": null, "e": 26366, "s": 26267, "text": "It measures a set of current values against a set of past values and finds whether they correlate." }, { "code": null, "e": 26462, "s": 26366, "text": "It is the correlation of one-time series data to another time series data which has a time lag." }, { "code": null, "e": 26487, "s": 26462, "text": "It varies from +1 to -1." }, { "code": null, "e": 26644, "s": 26487, "text": "An autocorrelation of +1 indicates that if time series one increases in value the time series 2 also increases in proportion to the change in time series 1." }, { "code": null, "e": 26796, "s": 26644, "text": "An autocorrelation of -1 indicates that if time series one increases in value the time series 2 decreases in proportion to the change in time series 1." }, { "code": null, "e": 26830, "s": 26796, "text": "Application of Autocorrelation: " }, { "code": null, "e": 26851, "s": 26830, "text": "Pattern recognition." }, { "code": null, "e": 26869, "s": 26851, "text": "Signal detection." }, { "code": null, "e": 26888, "s": 26869, "text": "Signal processing." }, { "code": null, "e": 26906, "s": 26888, "text": "Estimating pitch." }, { "code": null, "e": 26936, "s": 26906, "text": "Technical analysis of stocks." }, { "code": null, "e": 27056, "s": 26936, "text": "To plot the Autocorrelation Plot we can use matplotlib and plot it easily by using matplotlib.pyplot.acorr() function. " }, { "code": null, "e": 27127, "s": 27056, "text": "Syntax: matplotlib.pyplot.acorr(x, *, data=None, **kwargs)Parameters: " }, { "code": null, "e": 27173, "s": 27127, "text": "‘x’ : This parameter is a sequence of scalar." }, { "code": null, "e": 27266, "s": 27173, "text": "‘detrend’ : This parameter is an optional parameter. Its default value is mlab.detrend_none." }, { "code": null, "e": 27378, "s": 27266, "text": "‘normed’ : This parameter is also an optional parameter and contains the bool value. Its default value is True." }, { "code": null, "e": 27493, "s": 27378, "text": "‘usevlines’ : This parameter is also an optional parameter and contains the bool value. Its default value is True." }, { "code": null, "e": 27607, "s": 27493, "text": "‘maxlags’ : This parameter is also an optional parameter and contains the integer value. Its default value is 10." }, { "code": null, "e": 27735, "s": 27607, "text": "‘linestyle’ : This parameter is also an optional parameter and used for plotting the data points, only when usevlines is False." }, { "code": null, "e": 27842, "s": 27735, "text": "‘marker’ : This parameter is also an optional parameter and contains the string. Its default value is ‘o’." }, { "code": null, "e": 27877, "s": 27842, "text": "Returns: (lags, c, line, b) Where:" }, { "code": null, "e": 27919, "s": 27877, "text": "lags are a length 2`maxlags+1 lag vector." }, { "code": null, "e": 27965, "s": 27919, "text": "c is the 2`maxlags+1 auto correlation vector." }, { "code": null, "e": 28009, "s": 27965, "text": "line is a Line2D instance returned by plot." }, { "code": null, "e": 28026, "s": 28009, "text": "b is the x-axis." }, { "code": null, "e": 28039, "s": 28026, "text": "Example 1: " }, { "code": null, "e": 28047, "s": 28039, "text": "Python3" }, { "code": "# Importing the libraries.import matplotlib.pyplot as pltimport numpy as np # Data for which we plot Autocorrelation.data = np.array([12.0, 24.0, 7., 20.0, 7.0, 22.0, 18.0,22.0, 6.0, 7.0, 20.0, 13.0, 8.0, 5.0, 8]) # Adding plot title.plt.title(\"Autocorrelation Plot\") # Providing x-axis name.plt.xlabel(\"Lags\") # Plotting the Autocorrelation plot.plt.acorr(data, maxlags = 10) # Displaying the plot.print(\"The Autocorrelation plot for the data is:\")plt.grid(True) plt.show()", "e": 28574, "s": 28047, "text": null }, { "code": null, "e": 28583, "s": 28574, "text": "Output: " }, { "code": null, "e": 28595, "s": 28583, "text": "Example 2: " }, { "code": null, "e": 28603, "s": 28595, "text": "Python3" }, { "code": "# Importing the libraries.import matplotlib.pyplot as pltimport numpy as np # Setting up the rondom seed for# fixing the random state.np.random.seed(42) # Creating some random data.data = np.random.randn(25) # Adding plot title.plt.title(\"Autocorrelation Plot\") # Providing x-axis name.plt.xlabel(\"Lags\") # Plotting the Autocorrelation plot.plt.acorr(data, maxlags = 20) # Displaying the plot.print(\"The Autocorrelation plot for the data is:\")plt.grid(True) plt.show()", "e": 29078, "s": 28603, "text": null }, { "code": null, "e": 29087, "s": 29078, "text": "Output: " }, { "code": null, "e": 29099, "s": 29089, "text": "kk9826225" }, { "code": null, "e": 29109, "s": 29099, "text": "as5853535" }, { "code": null, "e": 29127, "s": 29109, "text": "Python-matplotlib" }, { "code": null, "e": 29134, "s": 29127, "text": "Python" }, { "code": null, "e": 29232, "s": 29134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29250, "s": 29232, "text": "Python Dictionary" }, { "code": null, "e": 29285, "s": 29250, "text": "Read a file line by line in Python" }, { "code": null, "e": 29317, "s": 29285, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29339, "s": 29317, "text": "Enumerate() in Python" }, { "code": null, "e": 29381, "s": 29339, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29411, "s": 29381, "text": "Iterate over a list in Python" }, { "code": null, "e": 29440, "s": 29411, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29484, "s": 29440, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29521, "s": 29484, "text": "Create a Pandas DataFrame from Lists" } ]
How to generate random number in given range using JavaScript? - GeeksforGeeks
23 Apr, 2019 A number generated by a process, whose outcome is unpredictable is called Random Number. In JavaScript, this can be achieved by using Math.random() function. This article describes how to generate a random number using JavaScript. Method 1: Using Math.random() function: The Math.random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range. Syntax: Math.random(); Example 1: This example generate an integer random number between 1(min) and 5(max). <script> // Function to generate random number function randomNumber(min, max) { return Math.random() * (max - min) + min;} document.write("Random Number between 1 and 5: ") // Function calldocument.write( randomNumber(1, 5) ); </script> Output: Random Number between 1 and 5: 1.0573617826058959 Method 2: Using Math.floor() function: The Math.floor() function in JavaScript is used to round off the number passed as parameter to its nearest integer in Downward direction of rounding i.e towards the lesser value. Syntax: Math.floor(value) Example 2: This example generate random integer number between 1(min) and 100(max). <script> // Function to generate random number function randomNumber(min, max) { return Math.floor(Math.random() * (max - min) + min);} document.write("Random Number between 1 and 100: ") // Function calldocument.write( randomNumber(1, 100) ); </script> Output: Random Number between 1 and 100: 87 Example 3: This example generate random whole number between 1(min) and 10(max) both inclusive. <script> // Function to generate random number function randomNumber(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min;} document.write("Random Number between 1 and 10: ") // Function calldocument.write( randomNumber(1, 10) ); </script> Output: Random Number between 1 and 10: 3 JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26021, "s": 25993, "text": "\n23 Apr, 2019" }, { "code": null, "e": 26252, "s": 26021, "text": "A number generated by a process, whose outcome is unpredictable is called Random Number. In JavaScript, this can be achieved by using Math.random() function. This article describes how to generate a random number using JavaScript." }, { "code": null, "e": 26500, "s": 26252, "text": "Method 1: Using Math.random() function: The Math.random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range." }, { "code": null, "e": 26508, "s": 26500, "text": "Syntax:" }, { "code": null, "e": 26523, "s": 26508, "text": "Math.random();" }, { "code": null, "e": 26608, "s": 26523, "text": "Example 1: This example generate an integer random number between 1(min) and 5(max)." }, { "code": "<script> // Function to generate random number function randomNumber(min, max) { return Math.random() * (max - min) + min;} document.write(\"Random Number between 1 and 5: \") // Function calldocument.write( randomNumber(1, 5) ); </script> ", "e": 26890, "s": 26608, "text": null }, { "code": null, "e": 26898, "s": 26890, "text": "Output:" }, { "code": null, "e": 26948, "s": 26898, "text": "Random Number between 1 and 5: 1.0573617826058959" }, { "code": null, "e": 27166, "s": 26948, "text": "Method 2: Using Math.floor() function: The Math.floor() function in JavaScript is used to round off the number passed as parameter to its nearest integer in Downward direction of rounding i.e towards the lesser value." }, { "code": null, "e": 27174, "s": 27166, "text": "Syntax:" }, { "code": null, "e": 27192, "s": 27174, "text": "Math.floor(value)" }, { "code": null, "e": 27276, "s": 27192, "text": "Example 2: This example generate random integer number between 1(min) and 100(max)." }, { "code": "<script> // Function to generate random number function randomNumber(min, max) { return Math.floor(Math.random() * (max - min) + min);} document.write(\"Random Number between 1 and 100: \") // Function calldocument.write( randomNumber(1, 100) ); </script> ", "e": 27577, "s": 27276, "text": null }, { "code": null, "e": 27585, "s": 27577, "text": "Output:" }, { "code": null, "e": 27621, "s": 27585, "text": "Random Number between 1 and 100: 87" }, { "code": null, "e": 27717, "s": 27621, "text": "Example 3: This example generate random whole number between 1(min) and 10(max) both inclusive." }, { "code": "<script> // Function to generate random number function randomNumber(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min;} document.write(\"Random Number between 1 and 10: \") // Function calldocument.write( randomNumber(1, 10) ); </script> ", "e": 28066, "s": 27717, "text": null }, { "code": null, "e": 28074, "s": 28066, "text": "Output:" }, { "code": null, "e": 28108, "s": 28074, "text": "Random Number between 1 and 10: 3" }, { "code": null, "e": 28124, "s": 28108, "text": "JavaScript-Misc" }, { "code": null, "e": 28131, "s": 28124, "text": "Picked" }, { "code": null, "e": 28142, "s": 28131, "text": "JavaScript" }, { "code": null, "e": 28159, "s": 28142, "text": "Web Technologies" }, { "code": null, "e": 28186, "s": 28159, "text": "Web technologies Questions" }, { "code": null, "e": 28284, "s": 28186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28324, "s": 28284, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28369, "s": 28324, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28430, "s": 28369, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28502, "s": 28430, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28554, "s": 28502, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28594, "s": 28554, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28627, "s": 28594, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28672, "s": 28627, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28715, "s": 28672, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use if, else and not statements in Ember.js ? - GeeksforGeeks
23 Nov, 2021 Ember.js is a framework for web development. It makes the process of development and prototyping faster with its tools. We can create dynamic web pages with it. Based on the dynamic data, we may or may not want to display some data or some UI or modify the UI. So we will learn to use If, Else and Not in an Ember.js application. Step 1: Enter the following command in your Terminal or Command Prompt to create a new project. ember new ember_tutorial Project Structure: Your project structure may look as follows. Project Structure Approach: The idea for our example project is to pass some data to our template(handlebar) file. The handlebar will process the data and based on that it will display the same. Step 2: So let us create some data. Create a new file inside the app\routes folder and name it application.js. Here is a list of items with their availability as true or false. We have exported the items with a model hook. In this way, we can pass data to template files in Ember.js. This is also the place where our application will fetch code from the database or elsewhere. app\routes\application.js Javascript import Route from '@ember/routing/route'; export default class ApplicationRoute extends Route { async model() { return { items: [ { name: 'Milk', available: true, }, { name: 'Eggs', available: true, }, { name: 'Bread', available: true, }, { name: 'Biscuits', available: false, }, ], }; }} Step 3: This is our project data. Now let us implement the application.hbs file. Inside the application.hbs file, run an each-loop to list each item. Here we have first used #each helper to iterate over the list of items. Then we used {{#if condition}} with the item.available to check if the current item is available or not. If available, our item will have the class of available else we used {{else}} tag for the else part of the code. If the item is not available our item will have the class as not available. Next inside the app.css file, add the following code for the styling purpose. HTML CSS <ul class="items"> {{#each @model.items as |item|}} <li> {{#if item.available}} <h4 class="available"> {{item.name}} </h4> {{else}} <h4 class="notavailable"> {{item.name}} </h4> {{/if}} </li> {{/each}}</ul>{{outlet}} .items li { list-style: decimal-leading-zero;}.items li .available { color: green;}.items li .notavailable { color: red;} Step to run the application: Run the project by running the following command on Terminal / Command Prompt. ember serve Output: Step 4: Now let us implement the NOT in Ember.js. In ember, NOT is implemented as {{#unless}}{{/unless}} UNLESS is just the opposite of IF. We can also use ELSE inside the UNLESS. So we will put a text under each item to tell whether the item is available or not. app\templates\application.hbs HTML {{page-title 'EmberTutorial'}}<h2> GeeksforGeeks Ember Tutorial</h2><ul class="items"> {{#each @model.items as |item|}} <li> {{#if item.available}} <h4 class="available"> {{item.name}} </h4> {{else}} <h4 class="notavailable"> {{item.name}} </h4> {{/if}} {{#unless item.available}} <p> Not Available </p> {{else}} <p> Available </p> {{/unless}} </li> {{/each}}</ul>{{outlet}} Step to run the application: Save the code again. Run the project by running the following command on Terminal / Command Prompt. ember serve Output: EmberJS JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n23 Nov, 2021" }, { "code": null, "e": 26875, "s": 26545, "text": "Ember.js is a framework for web development. It makes the process of development and prototyping faster with its tools. We can create dynamic web pages with it. Based on the dynamic data, we may or may not want to display some data or some UI or modify the UI. So we will learn to use If, Else and Not in an Ember.js application." }, { "code": null, "e": 26971, "s": 26875, "text": "Step 1: Enter the following command in your Terminal or Command Prompt to create a new project." }, { "code": null, "e": 26996, "s": 26971, "text": "ember new ember_tutorial" }, { "code": null, "e": 27059, "s": 26996, "text": "Project Structure: Your project structure may look as follows." }, { "code": null, "e": 27077, "s": 27059, "text": "Project Structure" }, { "code": null, "e": 27255, "s": 27077, "text": "Approach: The idea for our example project is to pass some data to our template(handlebar) file. The handlebar will process the data and based on that it will display the same. " }, { "code": null, "e": 27633, "s": 27255, "text": "Step 2: So let us create some data. Create a new file inside the app\\routes folder and name it application.js. Here is a list of items with their availability as true or false. We have exported the items with a model hook. In this way, we can pass data to template files in Ember.js. This is also the place where our application will fetch code from the database or elsewhere." }, { "code": null, "e": 27659, "s": 27633, "text": "app\\routes\\application.js" }, { "code": null, "e": 27670, "s": 27659, "text": "Javascript" }, { "code": "import Route from '@ember/routing/route'; export default class ApplicationRoute extends Route { async model() { return { items: [ { name: 'Milk', available: true, }, { name: 'Eggs', available: true, }, { name: 'Bread', available: true, }, { name: 'Biscuits', available: false, }, ], }; }}", "e": 28106, "s": 27670, "text": null }, { "code": null, "e": 28700, "s": 28106, "text": "Step 3: This is our project data. Now let us implement the application.hbs file. Inside the application.hbs file, run an each-loop to list each item. Here we have first used #each helper to iterate over the list of items. Then we used {{#if condition}} with the item.available to check if the current item is available or not. If available, our item will have the class of available else we used {{else}} tag for the else part of the code. If the item is not available our item will have the class as not available. Next inside the app.css file, add the following code for the styling purpose." }, { "code": null, "e": 28705, "s": 28700, "text": "HTML" }, { "code": null, "e": 28709, "s": 28705, "text": "CSS" }, { "code": "<ul class=\"items\"> {{#each @model.items as |item|}} <li> {{#if item.available}} <h4 class=\"available\"> {{item.name}} </h4> {{else}} <h4 class=\"notavailable\"> {{item.name}} </h4> {{/if}} </li> {{/each}}</ul>{{outlet}}", "e": 28961, "s": 28709, "text": null }, { "code": ".items li { list-style: decimal-leading-zero;}.items li .available { color: green;}.items li .notavailable { color: red;}", "e": 29086, "s": 28961, "text": null }, { "code": null, "e": 29195, "s": 29086, "text": "Step to run the application: Run the project by running the following command on Terminal / Command Prompt." }, { "code": null, "e": 29207, "s": 29195, "text": "ember serve" }, { "code": null, "e": 29215, "s": 29207, "text": "Output:" }, { "code": null, "e": 29298, "s": 29215, "text": "Step 4: Now let us implement the NOT in Ember.js. In ember, NOT is implemented as " }, { "code": null, "e": 29321, "s": 29298, "text": "{{#unless}}{{/unless}}" }, { "code": null, "e": 29481, "s": 29321, "text": "UNLESS is just the opposite of IF. We can also use ELSE inside the UNLESS. So we will put a text under each item to tell whether the item is available or not. " }, { "code": null, "e": 29512, "s": 29481, "text": "app\\templates\\application.hbs " }, { "code": null, "e": 29517, "s": 29512, "text": "HTML" }, { "code": "{{page-title 'EmberTutorial'}}<h2> GeeksforGeeks Ember Tutorial</h2><ul class=\"items\"> {{#each @model.items as |item|}} <li> {{#if item.available}} <h4 class=\"available\"> {{item.name}} </h4> {{else}} <h4 class=\"notavailable\"> {{item.name}} </h4> {{/if}} {{#unless item.available}} <p> Not Available </p> {{else}} <p> Available </p> {{/unless}} </li> {{/each}}</ul>{{outlet}}", "e": 29959, "s": 29517, "text": null }, { "code": null, "e": 30089, "s": 29959, "text": "Step to run the application: Save the code again. Run the project by running the following command on Terminal / Command Prompt." }, { "code": null, "e": 30101, "s": 30089, "text": "ember serve" }, { "code": null, "e": 30109, "s": 30101, "text": "Output:" }, { "code": null, "e": 30117, "s": 30109, "text": "EmberJS" }, { "code": null, "e": 30138, "s": 30117, "text": "JavaScript-Questions" }, { "code": null, "e": 30145, "s": 30138, "text": "Picked" }, { "code": null, "e": 30156, "s": 30145, "text": "JavaScript" }, { "code": null, "e": 30173, "s": 30156, "text": "Web Technologies" }, { "code": null, "e": 30271, "s": 30173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30311, "s": 30271, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30372, "s": 30311, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30413, "s": 30372, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30435, "s": 30413, "text": "JavaScript | Promises" }, { "code": null, "e": 30489, "s": 30435, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30529, "s": 30489, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30562, "s": 30529, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30605, "s": 30562, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30667, "s": 30605, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Program to find Nth term divisible by a or b - GeeksforGeeks
02 Jun, 2021 Given two integers and . The task is to find the Nth term which is divisible by either of or .Examples : Input : a = 2, b = 5, N = 10 Output : 16 Input : a = 3, b = 7, N = 25 Output : 57 Naive Approach: A simple approach is to traverse over all the terms starting from 1 until we find the desired Nth term which is divisible by either of or . This solution has time complexity of O(N).Efficient Approach: The idea is to use Binary search. Here we can calculate how many numbers from 1 to are divisible by either a or b by using formula:All the multiples of lcm(a, b) will be divisible by both and so we need to remove these terms. Now if the number of divisible terms is less than N we will increase the low position of binary search otherwise decrease high until number of divisible terms is equal to N.Below is the implementation of the above idea : C++ Java Python3 C# Javascript // C++ program to find nth term// divisible by a or b #include <bits/stdc++.h>using namespace std; // Function to return// gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate how many numbers// from 1 to num are divisible by a or bint divTermCount(int a, int b, int lcm, int num){ // calculate number of terms divisible by a and // by b then, remove the terms which is are // divisible by both a and b return num / a + num / b - num / lcm;} // Binary search to find the nth term// divisible by a or bint findNthTerm(int a, int b, int n){ // set low to 1 and high to max(a, b)*n, here // we have taken high as 10^18 int low = 1, high = INT_MAX, mid; int lcm = (a * b) / gcd(a, b); while (low < high) { mid = low + (high - low) / 2; // if the current term is less than // n then we need to increase low // to mid + 1 if (divTermCount(a, b, lcm, mid) < n) low = mid + 1; // if current term is greater than equal to // n then high = mid else high = mid; } return low;} // Driver codeint main(){ int a = 2, b = 5, n = 10; cout << findNthTerm(a, b, n) << endl; return 0;} // Java program to find nth term// divisible by a or bclass GFG{// Function to return// gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate how many numbers// from 1 to num are divisible by a or bstatic int divTermCount(int a, int b, int lcm, int num){ // calculate number of terms // divisible by a and by b then, // remove the terms which is are // divisible by both a and b return num / a + num / b - num / lcm;} // Binary search to find the// nth term divisible by a or bstatic int findNthTerm(int a, int b, int n){ // set low to 1 and high to max(a, b)*n, // here we have taken high as 10^18 int low = 1, high = Integer.MAX_VALUE, mid; int lcm = (a * b) / gcd(a, b); while (low < high) { mid = low + (high - low) / 2; // if the current term is less // than n then we need to increase // low to mid + 1 if (divTermCount(a, b, lcm, mid) < n) low = mid + 1; // if current term is greater // than equal to n then high = mid else high = mid; } return low;} // Driver codepublic static void main (String[] args){ int a = 2, b = 5, n = 10; System.out.println(findNthTerm(a, b, n));}} // This code is contributed by Smitha # Python 3 program to find nth term# divisible by a or bimport sys # Function to return gcd of a and bdef gcd(a, b): if a == 0: return b return gcd(b % a, a) # Function to calculate how many numbers# from 1 to num are divisible by a or bdef divTermCount(a, b, lcm, num): # calculate number of terms divisible # by a and by b then, remove the terms # which are divisible by both a and b return num // a + num // b - num // lcm # Binary search to find the nth term# divisible by a or bdef findNthTerm(a, b, n): # set low to 1 and high to max(a, b)*n, # here we have taken high as 10^18 low = 1; high = sys.maxsize lcm = (a * b) // gcd(a, b) while low < high: mid = low + (high - low) // 2 # if the current term is less # than n then we need to increase # low to mid + 1 if divTermCount(a, b, lcm, mid) < n: low = mid + 1 # if current term is greater # than equal to n then high = mid else: high = mid return low # Driver codea = 2; b = 5; n = 10print(findNthTerm(a, b, n)) # This code is contributed by Shrikant13 // C# program to find nth term// divisible by a or busing System; class GFG{// Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate how many numbers// from 1 to num are divisible by a or bstatic int divTermCount(int a, int b, int lcm, int num){ // calculate number of terms // divisible by a and by b then, // remove the terms which is are // divisible by both a and b return num / a + num / b - num / lcm;} // Binary search to find the// nth term divisible by a or bstatic int findNthTerm(int a, int b, int n){ // set low to 1 and high to max(a, b)*n, // here we have taken high as 10^18 int low = 1, high = int.MaxValue, mid; int lcm = (a * b) / gcd(a, b); while (low < high) { mid = low + (high - low) / 2; // if the current term is less // than n then we need to increase // low to mid + 1 if (divTermCount(a, b, lcm, mid) < n) low = mid + 1; // if current term is greater // than equal to n then high = mid else high = mid; } return low;} // Driver codestatic public void Main (){ int a = 2, b = 5, n = 10; Console.WriteLine(findNthTerm(a, b, n));}} // This code is contributed by Sach_Code <script> // JavaScript program to find nth term// divisible by a or b // Function to return// gcd of a and bfunction gcd(a , b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate how many numbers// from 1 to num are divisible by a or bfunction divTermCount(a , b, lcm , num){ // calculate number of terms // divisible by a and by b then, // remove the terms which is are // divisible by both a and b return parseInt(num / a) + parseInt(num / b) - parseInt(num / lcm);} // Binary search to find the// nth term divisible by a or bfunction findNthTerm(a , b , n){ // set low to 1 and high to max(a, b)*n, // here we have taken high as 10^18 var low = 1, high = Number.MAX_VALUE, mid; var lcm = parseInt((a * b) / gcd(a, b)); while (low < high) { mid = low + parseInt((high - low) / 2); // if the current term is less // than n then we need to increase // low to mid + 1 if (divTermCount(a, b, lcm, mid) < n) low = mid + 1; // if current term is greater // than equal to n then high = mid else high = mid; } return low;} // Driver codevar a = 2, b = 5, n = 10;document.write(findNthTerm(a, b, n)); // This code is contributed by Amit Katiyar </script> 16 Smitha Dinesh Semwal Sach_Code shrikanth13 amit143katiyar Binary Search divisibility GCD-LCM Searching Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Search an element in a sorted and rotated array Program to find largest element in an array k largest(or smallest) elements in an array Given an array of size n and a number k, find all elements that appear more than n/k times Median of two sorted arrays of different sizes Find the index of an array element in Java Two Pointers Technique Count number of occurrences (or frequency) in a sorted array Most frequent element in an array Best First Search (Informed Search)
[ { "code": null, "e": 26535, "s": 26507, "text": "\n02 Jun, 2021" }, { "code": null, "e": 26642, "s": 26535, "text": "Given two integers and . The task is to find the Nth term which is divisible by either of or .Examples : " }, { "code": null, "e": 26725, "s": 26642, "text": "Input : a = 2, b = 5, N = 10\nOutput : 16\n\nInput : a = 3, b = 7, N = 25\nOutput : 57" }, { "code": null, "e": 27394, "s": 26727, "text": "Naive Approach: A simple approach is to traverse over all the terms starting from 1 until we find the desired Nth term which is divisible by either of or . This solution has time complexity of O(N).Efficient Approach: The idea is to use Binary search. Here we can calculate how many numbers from 1 to are divisible by either a or b by using formula:All the multiples of lcm(a, b) will be divisible by both and so we need to remove these terms. Now if the number of divisible terms is less than N we will increase the low position of binary search otherwise decrease high until number of divisible terms is equal to N.Below is the implementation of the above idea : " }, { "code": null, "e": 27398, "s": 27394, "text": "C++" }, { "code": null, "e": 27403, "s": 27398, "text": "Java" }, { "code": null, "e": 27411, "s": 27403, "text": "Python3" }, { "code": null, "e": 27414, "s": 27411, "text": "C#" }, { "code": null, "e": 27425, "s": 27414, "text": "Javascript" }, { "code": "// C++ program to find nth term// divisible by a or b #include <bits/stdc++.h>using namespace std; // Function to return// gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate how many numbers// from 1 to num are divisible by a or bint divTermCount(int a, int b, int lcm, int num){ // calculate number of terms divisible by a and // by b then, remove the terms which is are // divisible by both a and b return num / a + num / b - num / lcm;} // Binary search to find the nth term// divisible by a or bint findNthTerm(int a, int b, int n){ // set low to 1 and high to max(a, b)*n, here // we have taken high as 10^18 int low = 1, high = INT_MAX, mid; int lcm = (a * b) / gcd(a, b); while (low < high) { mid = low + (high - low) / 2; // if the current term is less than // n then we need to increase low // to mid + 1 if (divTermCount(a, b, lcm, mid) < n) low = mid + 1; // if current term is greater than equal to // n then high = mid else high = mid; } return low;} // Driver codeint main(){ int a = 2, b = 5, n = 10; cout << findNthTerm(a, b, n) << endl; return 0;}", "e": 28685, "s": 27425, "text": null }, { "code": "// Java program to find nth term// divisible by a or bclass GFG{// Function to return// gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate how many numbers// from 1 to num are divisible by a or bstatic int divTermCount(int a, int b, int lcm, int num){ // calculate number of terms // divisible by a and by b then, // remove the terms which is are // divisible by both a and b return num / a + num / b - num / lcm;} // Binary search to find the// nth term divisible by a or bstatic int findNthTerm(int a, int b, int n){ // set low to 1 and high to max(a, b)*n, // here we have taken high as 10^18 int low = 1, high = Integer.MAX_VALUE, mid; int lcm = (a * b) / gcd(a, b); while (low < high) { mid = low + (high - low) / 2; // if the current term is less // than n then we need to increase // low to mid + 1 if (divTermCount(a, b, lcm, mid) < n) low = mid + 1; // if current term is greater // than equal to n then high = mid else high = mid; } return low;} // Driver codepublic static void main (String[] args){ int a = 2, b = 5, n = 10; System.out.println(findNthTerm(a, b, n));}} // This code is contributed by Smitha", "e": 30032, "s": 28685, "text": null }, { "code": "# Python 3 program to find nth term# divisible by a or bimport sys # Function to return gcd of a and bdef gcd(a, b): if a == 0: return b return gcd(b % a, a) # Function to calculate how many numbers# from 1 to num are divisible by a or bdef divTermCount(a, b, lcm, num): # calculate number of terms divisible # by a and by b then, remove the terms # which are divisible by both a and b return num // a + num // b - num // lcm # Binary search to find the nth term# divisible by a or bdef findNthTerm(a, b, n): # set low to 1 and high to max(a, b)*n, # here we have taken high as 10^18 low = 1; high = sys.maxsize lcm = (a * b) // gcd(a, b) while low < high: mid = low + (high - low) // 2 # if the current term is less # than n then we need to increase # low to mid + 1 if divTermCount(a, b, lcm, mid) < n: low = mid + 1 # if current term is greater # than equal to n then high = mid else: high = mid return low # Driver codea = 2; b = 5; n = 10print(findNthTerm(a, b, n)) # This code is contributed by Shrikant13", "e": 31170, "s": 30032, "text": null }, { "code": "// C# program to find nth term// divisible by a or busing System; class GFG{// Function to return gcd of a and bstatic int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate how many numbers// from 1 to num are divisible by a or bstatic int divTermCount(int a, int b, int lcm, int num){ // calculate number of terms // divisible by a and by b then, // remove the terms which is are // divisible by both a and b return num / a + num / b - num / lcm;} // Binary search to find the// nth term divisible by a or bstatic int findNthTerm(int a, int b, int n){ // set low to 1 and high to max(a, b)*n, // here we have taken high as 10^18 int low = 1, high = int.MaxValue, mid; int lcm = (a * b) / gcd(a, b); while (low < high) { mid = low + (high - low) / 2; // if the current term is less // than n then we need to increase // low to mid + 1 if (divTermCount(a, b, lcm, mid) < n) low = mid + 1; // if current term is greater // than equal to n then high = mid else high = mid; } return low;} // Driver codestatic public void Main (){ int a = 2, b = 5, n = 10; Console.WriteLine(findNthTerm(a, b, n));}} // This code is contributed by Sach_Code", "e": 32510, "s": 31170, "text": null }, { "code": "<script> // JavaScript program to find nth term// divisible by a or b // Function to return// gcd of a and bfunction gcd(a , b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate how many numbers// from 1 to num are divisible by a or bfunction divTermCount(a , b, lcm , num){ // calculate number of terms // divisible by a and by b then, // remove the terms which is are // divisible by both a and b return parseInt(num / a) + parseInt(num / b) - parseInt(num / lcm);} // Binary search to find the// nth term divisible by a or bfunction findNthTerm(a , b , n){ // set low to 1 and high to max(a, b)*n, // here we have taken high as 10^18 var low = 1, high = Number.MAX_VALUE, mid; var lcm = parseInt((a * b) / gcd(a, b)); while (low < high) { mid = low + parseInt((high - low) / 2); // if the current term is less // than n then we need to increase // low to mid + 1 if (divTermCount(a, b, lcm, mid) < n) low = mid + 1; // if current term is greater // than equal to n then high = mid else high = mid; } return low;} // Driver codevar a = 2, b = 5, n = 10;document.write(findNthTerm(a, b, n)); // This code is contributed by Amit Katiyar </script>", "e": 33818, "s": 32510, "text": null }, { "code": null, "e": 33821, "s": 33818, "text": "16" }, { "code": null, "e": 33844, "s": 33823, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 33854, "s": 33844, "text": "Sach_Code" }, { "code": null, "e": 33866, "s": 33854, "text": "shrikanth13" }, { "code": null, "e": 33881, "s": 33866, "text": "amit143katiyar" }, { "code": null, "e": 33895, "s": 33881, "text": "Binary Search" }, { "code": null, "e": 33908, "s": 33895, "text": "divisibility" }, { "code": null, "e": 33916, "s": 33908, "text": "GCD-LCM" }, { "code": null, "e": 33926, "s": 33916, "text": "Searching" }, { "code": null, "e": 33936, "s": 33926, "text": "Searching" }, { "code": null, "e": 33950, "s": 33936, "text": "Binary Search" }, { "code": null, "e": 34048, "s": 33950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34096, "s": 34048, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 34140, "s": 34096, "text": "Program to find largest element in an array" }, { "code": null, "e": 34184, "s": 34140, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 34275, "s": 34184, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 34322, "s": 34275, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 34365, "s": 34322, "text": "Find the index of an array element in Java" }, { "code": null, "e": 34388, "s": 34365, "text": "Two Pointers Technique" }, { "code": null, "e": 34449, "s": 34388, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 34483, "s": 34449, "text": "Most frequent element in an array" } ]
Generate a permutation of first N natural numbers from an array of differences between adjacent elements - GeeksforGeeks
25 Feb, 2022 Given an array arr[] consisting of (N – 1), the task is to construct a permutation array P[] consisting of the first N Natural Numbers such that arr[i] = (P[i +1] – P[i]). If there exists no such permutation, then print “-1”. Examples: Input: arr[] = {-1, 2, -3, -1}Output: 4 3 5 2 1Explanation:For the array {4, 3, 5, 2, 1}, the adjacent difference array of consecutive elements is {4 – 3, 5 – 3, 2 – 5, 1 – 2} = {-1, 2, -3, -1} which is the same as the array arr[]. Input: arr[] = {1, 1, 1, 1}Output: 1 2 3 4 5 Approach: The given problem can be solved by considering the first element of the permutation as 0 and then constructing a new permutation array by using the given array arr[]. After this, add the minimum element of the new array to each element to make the array elements over the range [1, N]. Follow the steps below to solve the problem: Initialize an array, say perm[] of size N to store the resultant permutation. Initialize perm[0] as 0, and also initialize a variable, say lastEle as 0. Iterate over the range [1, N] using the variable i, and add the value of arr[i – 1] to the element lastEle and update the value of perm[i] as lastEle. Initialize a variable, say minimumElement to the minimum element of the array perm[]. Initialize a HashSet of integers st, to store all elements of the permutation. Also, initialize a variable mx as 0 to store the maximum element in the perm[] array. Traverse through the perm[] array and add the value of (-sm) + 1 to the value perm[i], update the value of mx as max(mx, perm[i]) and add perm[i] to st. After completing the above steps, if the value of mx and the size of HashSet st is N, then print the array perm[] as the resultant array. Otherwise, print -1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the permutation of// N integers from the given difference// array A[]void findPermutation(int A[], int N){ int lasEle = 0; // Stores the resultant permutation int perm[N]; perm[0] = 0; for (int i = 1; i < N; i++) { // Update the value of lastEle lasEle += A[i - 1]; // Initialize the value of // perm[i] perm[i] = lasEle; } // Stores the minimum element of // the array perm[] int sm = *min_element(perm, perm + N); // Stores the elements of the // permutation array perm[] unordered_set<int> st; int mx = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update the value of perm[i] perm[i] += (-sm) + 1; // Update the value of mx mx = max(mx, perm[i]); // Insert the current element // in the hashset st.insert(perm[i]); } // Check if the maximum element and // the size of hashset is N or not if (mx == N and st.size() == N) { // Print the permutation for (int i = 0; i < N; i++) { cout << perm[i] << " "; } } // Otherwise print -1 else { cout << -1 << " "; }} // Driver Codeint main(){ int arr[] = { -1, 2, -3, -1 }; int N = sizeof(arr) / sizeof(arr[0]); findPermutation(arr, N + 1); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to find the permutation of// N integers from the given difference// array A[]static void findPermutation(int []A, int N){ int lasEle = 0; // Stores the resultant permutation int []perm = new int[N]; perm[0] = 0; for (int i = 1; i < N; i++) { // Update the value of lastEle lasEle += A[i - 1]; // Initialize the value of // perm[i] perm[i] = lasEle; } // Stores the minimum element of // the array perm[] int sm = perm[0]; //Loop through the array for (int i = 0; i < perm.length; i++) { //Compare elements of array with min if(perm[i] <sm) sm = perm[i]; } // Stores the elements of the // permutation array perm[] Set<Integer> st = new HashSet<Integer>(); int mx = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update the value of perm[i] perm[i] += (-sm) + 1; // Update the value of mx mx = Math.max(mx, perm[i]); // Insert the current element // in the hashset st.add(perm[i]); } // Check if the maximum element and // the size of hashset is N or not if (mx == N && st.size() == N) { // Print the permutation for (int i = 0; i < N; i++) { System.out.print(perm[i]+" "); } } // Otherwise print -1 else { System.out.print(-1); }} // Driver Codepublic static void main(String args[]){ int arr[] = { -1, 2, -3, -1 }; int N = arr.length; findPermutation(arr, N + 1);}} // This code is contributed by SURENDRA_GANGWAR. # Python program for the above approach # Function to find the permutation of# N integers from the given difference# array A[]def findPermutation(A, N): lasEle = 0 # Stores the resultant permutation perm = [0]*N perm[0] = 0 for i in range(1,N): # Update the value of lastEle lasEle += A[i - 1] # Initialize the value of # perm[i] perm[i] = lasEle # Stores the minimum element of # the array perm[] sm = min(perm) # Stores the elements of the # permutation array perm[] st = {} mx = 0 # Traverse the array for i in range(N): # Update the value of perm[i] perm[i] += (-sm) + 1 # Update the value of mx mx = max(mx, perm[i]) # Insert the current element # in the hashset st[perm[i]] = 1 # Check if the maximum element and # the size of hashset is N or not if (mx == N and len(st) == N): # Print the permutation for i in range(N): print(perm[i],end=" ") # Otherwise print -1 else: print(-1,end=" ") # Driver Codeif __name__ == '__main__': arr = [-1, 2, -3, -1] N = len(arr) findPermutation(arr, N + 1) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;using System.Linq;using System.Collections.Generic; class GFG { // Function to find the permutation of// N integers from the given difference// array A[]static void findPermutation(int[] A, int N){ int lasEle = 0; // Stores the resultant permutation int[] perm = new int[N]; perm[0] = 0; for (int i = 1; i < N; i++) { // Update the value of lastEle lasEle += A[i - 1]; // Initialize the value of // perm[i] perm[i] = lasEle; } // Stores the minimum element of // the array perm[] int sm = perm.Min(); // Stores the elements of the // permutation array perm[] List<int> st = new List<int>(); int mx = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update the value of perm[i] perm[i] += (-sm) + 1; // Update the value of mx mx = Math.Max(mx, perm[i]); // Insert the current element // in the hashset st.Add(perm[i]); } // Check if the maximum element and // the size of hashset is N or not if (mx == N && st.Count == N) { // Print the permutation for (int i = 0; i < N; i++) { Console.Write(perm[i] + " "); } } // Otherwise print -1 else { Console.Write(-1 + " "); }} // Driver Code static void Main() { int[] arr= { -1, 2, -3, -1 }; int N = arr.Length; findPermutation(arr, N + 1); }} // This code is contributed by sanjoy_62. <script> // JavaScript program for the above approach // Function to find the permutation of// N integers from the given difference// array A[]function findPermutation(A, N) { let lasEle = 0; // Stores the resultant permutation let perm = new Array(N); perm[0] = 0; for (let i = 1; i < N; i++) { // Update the value of lastEle lasEle += A[i - 1]; // Initialize the value of // perm[i] perm[i] = lasEle; } // Stores the minimum element of // the array perm[] let temp = [...perm]; let sm = temp.sort((a, b) => a - b)[0] // Stores the elements of the // permutation array perm[] let st = new Set(); let mx = 0; // Traverse the array for (let i = 0; i < N; i++) { // Update the value of perm[i] perm[i] += (-sm) + 1; // Update the value of mx mx = Math.max(mx, perm[i]); // Insert the current element // in the hashset st.add(perm[i]); } // Check if the maximum element and // the size of hashset is N or not if (mx == N && st.size == N) { // Print the permutation for (let i of perm) { document.write(i + " ") } } // Otherwise print -1 else { document.write(-1 + " "); }} // Driver Code let arr = [-1, 2, -3, -1];let N = arr.lengthfindPermutation(arr, N + 1); </script> 4 3 5 2 1 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 sanjoy_62 _saurabh_jaiswal SURENDRA_GANGWAR simranarora5sos HashSet Natural Numbers permutation Arrays Hash Mathematical Arrays Hash Mathematical permutation 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 Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 26067, "s": 26039, "text": "\n25 Feb, 2022" }, { "code": null, "e": 26293, "s": 26067, "text": "Given an array arr[] consisting of (N – 1), the task is to construct a permutation array P[] consisting of the first N Natural Numbers such that arr[i] = (P[i +1] – P[i]). If there exists no such permutation, then print “-1”." }, { "code": null, "e": 26303, "s": 26293, "text": "Examples:" }, { "code": null, "e": 26535, "s": 26303, "text": "Input: arr[] = {-1, 2, -3, -1}Output: 4 3 5 2 1Explanation:For the array {4, 3, 5, 2, 1}, the adjacent difference array of consecutive elements is {4 – 3, 5 – 3, 2 – 5, 1 – 2} = {-1, 2, -3, -1} which is the same as the array arr[]." }, { "code": null, "e": 26580, "s": 26535, "text": "Input: arr[] = {1, 1, 1, 1}Output: 1 2 3 4 5" }, { "code": null, "e": 26921, "s": 26580, "text": "Approach: The given problem can be solved by considering the first element of the permutation as 0 and then constructing a new permutation array by using the given array arr[]. After this, add the minimum element of the new array to each element to make the array elements over the range [1, N]. Follow the steps below to solve the problem:" }, { "code": null, "e": 26999, "s": 26921, "text": "Initialize an array, say perm[] of size N to store the resultant permutation." }, { "code": null, "e": 27074, "s": 26999, "text": "Initialize perm[0] as 0, and also initialize a variable, say lastEle as 0." }, { "code": null, "e": 27225, "s": 27074, "text": "Iterate over the range [1, N] using the variable i, and add the value of arr[i – 1] to the element lastEle and update the value of perm[i] as lastEle." }, { "code": null, "e": 27311, "s": 27225, "text": "Initialize a variable, say minimumElement to the minimum element of the array perm[]." }, { "code": null, "e": 27476, "s": 27311, "text": "Initialize a HashSet of integers st, to store all elements of the permutation. Also, initialize a variable mx as 0 to store the maximum element in the perm[] array." }, { "code": null, "e": 27629, "s": 27476, "text": "Traverse through the perm[] array and add the value of (-sm) + 1 to the value perm[i], update the value of mx as max(mx, perm[i]) and add perm[i] to st." }, { "code": null, "e": 27788, "s": 27629, "text": "After completing the above steps, if the value of mx and the size of HashSet st is N, then print the array perm[] as the resultant array. Otherwise, print -1." }, { "code": null, "e": 27840, "s": 27788, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27844, "s": 27840, "text": "C++" }, { "code": null, "e": 27849, "s": 27844, "text": "Java" }, { "code": null, "e": 27857, "s": 27849, "text": "Python3" }, { "code": null, "e": 27860, "s": 27857, "text": "C#" }, { "code": null, "e": 27871, "s": 27860, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the permutation of// N integers from the given difference// array A[]void findPermutation(int A[], int N){ int lasEle = 0; // Stores the resultant permutation int perm[N]; perm[0] = 0; for (int i = 1; i < N; i++) { // Update the value of lastEle lasEle += A[i - 1]; // Initialize the value of // perm[i] perm[i] = lasEle; } // Stores the minimum element of // the array perm[] int sm = *min_element(perm, perm + N); // Stores the elements of the // permutation array perm[] unordered_set<int> st; int mx = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update the value of perm[i] perm[i] += (-sm) + 1; // Update the value of mx mx = max(mx, perm[i]); // Insert the current element // in the hashset st.insert(perm[i]); } // Check if the maximum element and // the size of hashset is N or not if (mx == N and st.size() == N) { // Print the permutation for (int i = 0; i < N; i++) { cout << perm[i] << \" \"; } } // Otherwise print -1 else { cout << -1 << \" \"; }} // Driver Codeint main(){ int arr[] = { -1, 2, -3, -1 }; int N = sizeof(arr) / sizeof(arr[0]); findPermutation(arr, N + 1); return 0;}", "e": 29299, "s": 27871, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the permutation of// N integers from the given difference// array A[]static void findPermutation(int []A, int N){ int lasEle = 0; // Stores the resultant permutation int []perm = new int[N]; perm[0] = 0; for (int i = 1; i < N; i++) { // Update the value of lastEle lasEle += A[i - 1]; // Initialize the value of // perm[i] perm[i] = lasEle; } // Stores the minimum element of // the array perm[] int sm = perm[0]; //Loop through the array for (int i = 0; i < perm.length; i++) { //Compare elements of array with min if(perm[i] <sm) sm = perm[i]; } // Stores the elements of the // permutation array perm[] Set<Integer> st = new HashSet<Integer>(); int mx = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update the value of perm[i] perm[i] += (-sm) + 1; // Update the value of mx mx = Math.max(mx, perm[i]); // Insert the current element // in the hashset st.add(perm[i]); } // Check if the maximum element and // the size of hashset is N or not if (mx == N && st.size() == N) { // Print the permutation for (int i = 0; i < N; i++) { System.out.print(perm[i]+\" \"); } } // Otherwise print -1 else { System.out.print(-1); }} // Driver Codepublic static void main(String args[]){ int arr[] = { -1, 2, -3, -1 }; int N = arr.length; findPermutation(arr, N + 1);}} // This code is contributed by SURENDRA_GANGWAR.", "e": 30984, "s": 29299, "text": null }, { "code": "# Python program for the above approach # Function to find the permutation of# N integers from the given difference# array A[]def findPermutation(A, N): lasEle = 0 # Stores the resultant permutation perm = [0]*N perm[0] = 0 for i in range(1,N): # Update the value of lastEle lasEle += A[i - 1] # Initialize the value of # perm[i] perm[i] = lasEle # Stores the minimum element of # the array perm[] sm = min(perm) # Stores the elements of the # permutation array perm[] st = {} mx = 0 # Traverse the array for i in range(N): # Update the value of perm[i] perm[i] += (-sm) + 1 # Update the value of mx mx = max(mx, perm[i]) # Insert the current element # in the hashset st[perm[i]] = 1 # Check if the maximum element and # the size of hashset is N or not if (mx == N and len(st) == N): # Print the permutation for i in range(N): print(perm[i],end=\" \") # Otherwise print -1 else: print(-1,end=\" \") # Driver Codeif __name__ == '__main__': arr = [-1, 2, -3, -1] N = len(arr) findPermutation(arr, N + 1) # This code is contributed by mohit kumar 29.", "e": 32220, "s": 30984, "text": null }, { "code": "// C# program for the above approachusing System;using System.Linq;using System.Collections.Generic; class GFG { // Function to find the permutation of// N integers from the given difference// array A[]static void findPermutation(int[] A, int N){ int lasEle = 0; // Stores the resultant permutation int[] perm = new int[N]; perm[0] = 0; for (int i = 1; i < N; i++) { // Update the value of lastEle lasEle += A[i - 1]; // Initialize the value of // perm[i] perm[i] = lasEle; } // Stores the minimum element of // the array perm[] int sm = perm.Min(); // Stores the elements of the // permutation array perm[] List<int> st = new List<int>(); int mx = 0; // Traverse the array for (int i = 0; i < N; i++) { // Update the value of perm[i] perm[i] += (-sm) + 1; // Update the value of mx mx = Math.Max(mx, perm[i]); // Insert the current element // in the hashset st.Add(perm[i]); } // Check if the maximum element and // the size of hashset is N or not if (mx == N && st.Count == N) { // Print the permutation for (int i = 0; i < N; i++) { Console.Write(perm[i] + \" \"); } } // Otherwise print -1 else { Console.Write(-1 + \" \"); }} // Driver Code static void Main() { int[] arr= { -1, 2, -3, -1 }; int N = arr.Length; findPermutation(arr, N + 1); }} // This code is contributed by sanjoy_62.", "e": 33736, "s": 32220, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the permutation of// N integers from the given difference// array A[]function findPermutation(A, N) { let lasEle = 0; // Stores the resultant permutation let perm = new Array(N); perm[0] = 0; for (let i = 1; i < N; i++) { // Update the value of lastEle lasEle += A[i - 1]; // Initialize the value of // perm[i] perm[i] = lasEle; } // Stores the minimum element of // the array perm[] let temp = [...perm]; let sm = temp.sort((a, b) => a - b)[0] // Stores the elements of the // permutation array perm[] let st = new Set(); let mx = 0; // Traverse the array for (let i = 0; i < N; i++) { // Update the value of perm[i] perm[i] += (-sm) + 1; // Update the value of mx mx = Math.max(mx, perm[i]); // Insert the current element // in the hashset st.add(perm[i]); } // Check if the maximum element and // the size of hashset is N or not if (mx == N && st.size == N) { // Print the permutation for (let i of perm) { document.write(i + \" \") } } // Otherwise print -1 else { document.write(-1 + \" \"); }} // Driver Code let arr = [-1, 2, -3, -1];let N = arr.lengthfindPermutation(arr, N + 1); </script>", "e": 35114, "s": 33736, "text": null }, { "code": null, "e": 35124, "s": 35114, "text": "4 3 5 2 1" }, { "code": null, "e": 35169, "s": 35126, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 35184, "s": 35169, "text": "mohit kumar 29" }, { "code": null, "e": 35194, "s": 35184, "text": "sanjoy_62" }, { "code": null, "e": 35211, "s": 35194, "text": "_saurabh_jaiswal" }, { "code": null, "e": 35228, "s": 35211, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 35244, "s": 35228, "text": "simranarora5sos" }, { "code": null, "e": 35252, "s": 35244, "text": "HashSet" }, { "code": null, "e": 35268, "s": 35252, "text": "Natural Numbers" }, { "code": null, "e": 35280, "s": 35268, "text": "permutation" }, { "code": null, "e": 35287, "s": 35280, "text": "Arrays" }, { "code": null, "e": 35292, "s": 35287, "text": "Hash" }, { "code": null, "e": 35305, "s": 35292, "text": "Mathematical" }, { "code": null, "e": 35312, "s": 35305, "text": "Arrays" }, { "code": null, "e": 35317, "s": 35312, "text": "Hash" }, { "code": null, "e": 35330, "s": 35317, "text": "Mathematical" }, { "code": null, "e": 35342, "s": 35330, "text": "permutation" }, { "code": null, "e": 35440, "s": 35342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35467, "s": 35440, "text": "Count pairs with given sum" }, { "code": null, "e": 35498, "s": 35467, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35523, "s": 35498, "text": "Window Sliding Technique" }, { "code": null, "e": 35561, "s": 35523, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35582, "s": 35561, "text": "Next Greater Element" }, { "code": null, "e": 35618, "s": 35582, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 35645, "s": 35618, "text": "Count pairs with given sum" }, { "code": null, "e": 35676, "s": 35645, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 35710, "s": 35676, "text": "Hashing | Set 3 (Open Addressing)" } ]
DQL Full Form - GeeksforGeeks
30 Sep, 2021 Structured Query Language (SQL) is a nonprocedural language used for retrieving data from the queries. It was introduced by IBM as a part of the R project. It was declared as a standard language by ANSI and ISO. DQL statements are used for performing queries on the data within schema objects. The purpose of the DQL Command is to get some schema relation based on the query passed to it. We can define DQL as follows it is a component of SQL statement that allows getting data from the database and imposing order upon it. It includes the SELECT statement. This command allows getting the data out of the database to perform operations with it. When a SELECT is fired against a table or tables the result is compiled into a further temporary table, which is displayed or perhaps received by the program i.e. a front-end. Data Query Language (DQL) or Data Retrieval Language (DRL). Data Query Language has commands that retrieve the data from the query. It has a single command: select. It has subcategories: DDL or Data Definition Language has commands like create, rename, alter. DML or Data Manipulation Language has commands like update, insert, delete. DCL or Data Control Language has commands like grant and revoke. TCL or Transaction Control Language has commands like rollback, commit. It is used for retrieving data. A user can retrieve data according to his/her requirements using the select command. Example: If a user wants to retrieve all the from the employee table, the query must be given as follows: select * from employee; asterisk mark (*) indicates that all the rows are retrieved from the table. If a user wants to know the average salary of the employees, the query must be given as follows: select avg(salary) from employee; This displays the average salary of the employees. Here asterisk mark isn’t needed as we need to retrieve only particular rows. If a user wants to know the name of the employee whose salary is less than 10, 000; the query is: select ename from employee where salary<=10, 000; A condition is placed to retrieve the data and a relational operator is used as well. Advantages: SELECT is a standard command used for almost every query. It can also be written as SELECT as SQL is a case-insensitive language. It makes the data retrieving process easier. No coding is needed. This domain language can be used for communicating with the databases and receive answers to complex questions in seconds. Disadvantages: Data Query Language has no disadvantages. It is not possible to imagine Structured Query Language without the select command. Interfacing a DQL database is more complex than adding a few lines of code. The operating cost of some DQL versions makes it difficult for some programmers to access them. Applications: Analytical Queries. Retrieve Information from the database. Modify the index structures and database table. jyoti369 varshachoudhary Picked DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. KDD Process in Data Mining Deadlock in DBMS Types of Functional dependencies in DBMS Conflict Serializability in DBMS Introduction of Relational Algebra in DBMS SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? MySQL | Group_CONCAT() Function
[ { "code": null, "e": 25575, "s": 25547, "text": "\n30 Sep, 2021" }, { "code": null, "e": 26586, "s": 25575, "text": "Structured Query Language (SQL) is a nonprocedural language used for retrieving data from the queries. It was introduced by IBM as a part of the R project. It was declared as a standard language by ANSI and ISO. DQL statements are used for performing queries on the data within schema objects. The purpose of the DQL Command is to get some schema relation based on the query passed to it. We can define DQL as follows it is a component of SQL statement that allows getting data from the database and imposing order upon it. It includes the SELECT statement. This command allows getting the data out of the database to perform operations with it. When a SELECT is fired against a table or tables the result is compiled into a further temporary table, which is displayed or perhaps received by the program i.e. a front-end. Data Query Language (DQL) or Data Retrieval Language (DRL). Data Query Language has commands that retrieve the data from the query. It has a single command: select. It has subcategories: " }, { "code": null, "e": 26661, "s": 26586, "text": "DDL or Data Definition Language has commands like create, rename, alter. " }, { "code": null, "e": 26739, "s": 26661, "text": "DML or Data Manipulation Language has commands like update, insert, delete. " }, { "code": null, "e": 26806, "s": 26739, "text": "DCL or Data Control Language has commands like grant and revoke. " }, { "code": null, "e": 26880, "s": 26806, "text": "TCL or Transaction Control Language has commands like rollback, commit. " }, { "code": null, "e": 26998, "s": 26880, "text": "It is used for retrieving data. A user can retrieve data according to his/her requirements using the select command. " }, { "code": null, "e": 27106, "s": 26998, "text": "Example: If a user wants to retrieve all the from the employee table, the query must be given as follows: " }, { "code": null, "e": 27132, "s": 27106, "text": "select *\nfrom employee; " }, { "code": null, "e": 27209, "s": 27132, "text": "asterisk mark (*) indicates that all the rows are retrieved from the table. " }, { "code": null, "e": 27308, "s": 27209, "text": "If a user wants to know the average salary of the employees, the query must be given as follows: " }, { "code": null, "e": 27344, "s": 27308, "text": "select avg(salary) \nfrom employee; " }, { "code": null, "e": 27473, "s": 27344, "text": "This displays the average salary of the employees. Here asterisk mark isn’t needed as we need to retrieve only particular rows. " }, { "code": null, "e": 27573, "s": 27473, "text": "If a user wants to know the name of the employee whose salary is less than 10, 000; the query is: " }, { "code": null, "e": 27626, "s": 27573, "text": "select ename \nfrom employee \nwhere salary<=10, 000; " }, { "code": null, "e": 27713, "s": 27626, "text": "A condition is placed to retrieve the data and a relational operator is used as well. " }, { "code": null, "e": 27726, "s": 27713, "text": "Advantages: " }, { "code": null, "e": 27784, "s": 27726, "text": "SELECT is a standard command used for almost every query." }, { "code": null, "e": 27856, "s": 27784, "text": "It can also be written as SELECT as SQL is a case-insensitive language." }, { "code": null, "e": 27901, "s": 27856, "text": "It makes the data retrieving process easier." }, { "code": null, "e": 27922, "s": 27901, "text": "No coding is needed." }, { "code": null, "e": 28045, "s": 27922, "text": "This domain language can be used for communicating with the databases and receive answers to complex questions in seconds." }, { "code": null, "e": 28060, "s": 28045, "text": "Disadvantages:" }, { "code": null, "e": 28102, "s": 28060, "text": "Data Query Language has no disadvantages." }, { "code": null, "e": 28186, "s": 28102, "text": "It is not possible to imagine Structured Query Language without the select command." }, { "code": null, "e": 28262, "s": 28186, "text": "Interfacing a DQL database is more complex than adding a few lines of code." }, { "code": null, "e": 28358, "s": 28262, "text": "The operating cost of some DQL versions makes it difficult for some programmers to access them." }, { "code": null, "e": 28373, "s": 28358, "text": "Applications: " }, { "code": null, "e": 28393, "s": 28373, "text": "Analytical Queries." }, { "code": null, "e": 28433, "s": 28393, "text": "Retrieve Information from the database." }, { "code": null, "e": 28482, "s": 28433, "text": "Modify the index structures and database table. " }, { "code": null, "e": 28491, "s": 28482, "text": "jyoti369" }, { "code": null, "e": 28507, "s": 28491, "text": "varshachoudhary" }, { "code": null, "e": 28514, "s": 28507, "text": "Picked" }, { "code": null, "e": 28519, "s": 28514, "text": "DBMS" }, { "code": null, "e": 28523, "s": 28519, "text": "SQL" }, { "code": null, "e": 28528, "s": 28523, "text": "DBMS" }, { "code": null, "e": 28532, "s": 28528, "text": "SQL" }, { "code": null, "e": 28630, "s": 28532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28657, "s": 28630, "text": "KDD Process in Data Mining" }, { "code": null, "e": 28674, "s": 28657, "text": "Deadlock in DBMS" }, { "code": null, "e": 28715, "s": 28674, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 28748, "s": 28715, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 28791, "s": 28748, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 28833, "s": 28791, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 28877, "s": 28833, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 28898, "s": 28877, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 28964, "s": 28898, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Arithmetic Number - GeeksforGeeks
30 Nov, 2021 In number theory, an arithmetic number is an integer for which the average of its positive divisors is also an integer. Or in other words, a number N is arithmetic if the number of divisors divides the sum of divisors. Given a positive integer n. The task is to check whether n is Arithmetic number or not.Examples: Input : n = 6 Output : Yes Sum of divisor of 6 = 1 + 2 + 3 + 6 = 12. Number of divisor of 6 = 4. So, on dividing Sum of divisor by Number of divisor = 12/4 = 3, which is an integer. Input : n = 2 Output : No Algorithm Find sum of all the factors of a number , say sum.Find count of divisors (say Count).Check if sum is divisible by count. Find sum of all the factors of a number , say sum. Find count of divisors (say Count). Check if sum is divisible by count. C++ Java Python3 C# PHP Javascript // CPP program to check if a number is Arithmetic// number or not#include <bits/stdc++.h>using namespace std; // Sieve Of Eratosthenesvoid SieveOfEratosthenes(int n, bool prime[], bool primesquare[], int a[]){ for (int i = 2; i <= n; i++) prime[i] = true; for (int i = 0; i <= (n * n + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsint countDivisors(int n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; bool prime[n + 1], primesquare[n * n + 1]; int a[n]; // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of // distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; cnt = cnt + 1; // incrementing power } // Calculating number of divisors // If n = a^p * b^q then total // divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Returns sum of all factors of n.int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Check if number is Arithmetic Number// or not.bool checkArithmetic(int n){ int count = countDivisors(n); int sum = sumofFactors(n); return (sum % count == 0);} // Driven Programint main(){ int n = 6; (checkArithmetic(n)) ? (cout << "Yes") : (cout << "No"); return 0;} // Java program to check if a number is Arithmetic// number or notclass GFG{ // Sieve Of Eratosthenesstatic void SieveOfEratosthenes(int n, boolean prime[], boolean primesquare[], int a[]){ for (int i = 2; i <= n; i++) prime[i] = true; for (int i = 0; i <= (n * n ); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsstatic int countDivisors(int n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; boolean prime[] = new boolean[n + 1], primesquare[] = new boolean[n * n + 1]; int a[] = new int[n]; // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of // distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; cnt = cnt + 1; // incrementing power } // Calculating number of divisors // If n = a^p * b^q then total // divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Returns sum of all factors of n.static int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Check if number is Arithmetic Number// or not.static boolean checkArithmetic(int n){ int count = countDivisors(n); int sum = sumofFactors(n); return (sum % count == 0);} // Driver Programpublic static void main(String[] args){ int n = 6; if(checkArithmetic(n)) System.out.println("Yes"); else System.out.println("No");}} // This code has been contributed by 29AjayKumar # Python3 program to check if# a number is Arithmetic# number or notimport math # Sieve Of Eratosthenesdef SieveOfEratosthenes(n, prime,primesquare, a): for i in range(2,n+1): prime[i] = True; for i in range((n * n + 1)+1): primesquare[i] = False; # 1 is not a # prime number prime[1] = False; p = 2; while (p * p <= n): # If prime[p] is # not changed, then # it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2,n+1,p): prime[i] = False; p+=1; j = 0; for p in range(2,n+1): if (prime[p]): # Storing primes in an array a[j] = p; # Update value in # primesquare[p*p], # if p is prime. primesquare[p * p] = True; j+=1; # Function to count divisorsdef countDivisors(n): # If number is 1, then it # will have only 1 as a # factor. So, total factors # will be 1. if (n == 1): return 1; prime = [False]*(n + 2); primesquare = [False]*(n *n + 3); # for storing primes upto n a = [0]*n; # Calling SieveOfEratosthenes # to store prime factors of # n and to store square of # prime factors of n SieveOfEratosthenes(n, prime,primesquare, a); # ans will contain # total number of # distinct divisors ans = 1; # Loop for counting # factors of n for i in range(0,True): # a[i] is not less # than cube root n if (a[i] * a[i] * a[i] > n): break; # Calculating power of # a[i] in n. cnt is power # of prime a[i] in n. cnt = 1; # if a[i] is a factor of n while (n % a[i] == 0): n //= a[i]; # incrementing power cnt = cnt + 1; # Calculating number of # divisors. If n = a^p * b^q # then total divisors # of n are (p+1)*(q+1) ans = ans * cnt; # if a[i] is greater # than cube root of n # First case if (prime[n]): ans = ans * 2; # Second case elif (primesquare[n]): ans = ans * 3; # Third case elif (n != 1): ans = ans * 4; return ans; # Total divisors # Returns sum of# all factors of n.def sumofFactors(n): # Traversing through # all prime factors. res = 1; for i in range(2,int(math.sqrt(n))+1): count = 0; curr_sum = 1; curr_term = 1; while (n % i == 0): count+=1; n //= i; curr_term *= i; curr_sum += curr_term; res *= curr_sum; # This condition is to handle # the case when n is a prime # number greater than 2. if (n >= 2): res *= (1 + n); return res; # Check if number is# Arithmetic Number or not.def checkArithmetic(n): count = countDivisors(n); sum = sumofFactors(n); return (sum % count == 0); # Driver coden = 6;if(checkArithmetic(n)): print("Yes");else: print("No"); # This code is contributed# by mits // C# program to check if a number// is arithmetic number or notusing System; class GFG{ // Sieve Of Eratosthenesstatic void SieveOfEratosthenes(int n, bool []prime, bool []primesquare, int []a){ for (int i = 2; i <= n; i++) prime[i] = true; for (int i = 0; i <= (n * n ); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsstatic int countDivisors(int n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; bool []prime = new bool[n + 1]; bool []primesquare = new bool[n * n + 1]; int []a = new int[n]; // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of // distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; cnt = cnt + 1; // incrementing power } // Calculating number of divisors // If n = a^p * b^q then total // divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Returns sum of all factors of n.static int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Check if number is Arithmetic Number// or not.static bool checkArithmetic(int n){ int count = countDivisors(n); int sum = sumofFactors(n); return (sum % count == 0);} // Driver codepublic static void Main(String[] args){ int n = 6; if(checkArithmetic(n)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code contributed by Rajput-Ji <?php// PHP program to check if// a number is Arithmetic// number or not // Sieve Of Eratosthenesfunction SieveOfEratosthenes($n, &$prime, &$primesquare, &$a){ for ($i = 2; $i <= $n; $i++) $prime[$i] = true; for ($i = 0; $i <= ($n * $n + 1); $i++) $primesquare[$i] = false; // 1 is not a // prime number $prime[1] = false; for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is // not changed, then // it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } $j = 0; for ($p = 2; $p <= $n; $p++) { if ($prime[$p]) { // Storing primes in an array $a[$j] = $p; // Update value in // primesquare[p*p], // if p is prime. $primesquare[$p * $p] = true; $j++; } }} // Function to count divisorsfunction countDivisors($n){ // If number is 1, then it // will have only 1 as a // factor. So, total factors // will be 1. if ($n == 1) return 1; $prime = array_fill(0, ($n + 1), false); $primesquare = array_fill(0, ($n * $n + 1), false); // for storing primes upto n $a = array_fill(0, $n, 0); // Calling SieveOfEratosthenes // to store prime factors of // n and to store square of // prime factors of n SieveOfEratosthenes($n, $prime, $primesquare, $a); // ans will contain // total number of // distinct divisors $ans = 1; // Loop for counting // factors of n for ($i = 0;; $i++) { // a[i] is not less // than cube root n if ($a[$i] * $a[$i] * $a[$i] > $n) break; // Calculating power of // a[i] in n. cnt is power // of prime a[i] in n. $cnt = 1; // if a[i] is a factor of n while ($n % $a[$i] == 0) { $n = (int)($n / $a[$i]); // incrementing power $cnt = $cnt + 1; } // Calculating number of // divisors. If n = a^p * b^q // then total divisors // of n are (p+1)*(q+1) $ans = $ans * $cnt; } // if a[i] is greater // than cube root of n // First case if ($prime[$n]) $ans = $ans * 2; // Second case else if ($primesquare[$n]) $ans = $ans * 3; // Third case else if ($n != 1) $ans = $ans * 4; return $ans; // Total divisors} // Returns sum of// all factors of n.function sumofFactors($n){ // Traversing through // all prime factors. $res = 1; for ($i = 2; $i <= sqrt($n); $i++) { $count = 0; $curr_sum = 1; $curr_term = 1; while ($n % $i == 0) { $count++; $n = (int)($n / $i); $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if ($n >= 2) $res *= (1 + $n); return $res;} // Check if number is// Arithmetic Number or not.function checkArithmetic($n){ $count = countDivisors($n); $sum = sumofFactors($n); return ($sum % $count == 0);} // Driver code$n = 6;echo (checkArithmetic($n)) ? "Yes" : "No"; // This code is contributed// by mits?> <script> // Javascript program to check if a number is Arithmetic// number or not // Sieve Of Eratosthenesfunction SieveOfEratosthenes(n, prime, primesquare, a){ for (var i = 2; i <= n; i++) prime[i] = true; for (var i = 0; i <= (n * n + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (var p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p * 2; i <= n; i += p) prime[i] = false; } } var j = 0; for (var p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsfunction countDivisors(n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; var prime = Array(n+1).fill(false); var primesquare = Array(n * n + 1).fill(0); var a = Array(n).fill(0); // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of // distinct divisors var ans = 1; // Loop for counting factors of n for (var i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. var cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = parseInt(n / a[i]); cnt = cnt + 1; // incrementing power } // Calculating number of divisors // If n = a^p * b^q then total // divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Returns sum of all factors of n.function sumofFactors(n){ // Traversing through all prime factors. var res = 1; for (var i = 2; i <= Math.sqrt(n); i++) { var count = 0, curr_sum = 1; var curr_term = 1; while (n % i == 0) { count++; n = parseInt(n / i); curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Check if number is Arithmetic Number// or not.function checkArithmetic(n){ var count = countDivisors(n); var sum = sumofFactors(n); return (sum % count == 0);} // Driven Programvar n = 6;(checkArithmetic(n)) ? (document.write( "Yes")) : (document.write( "No")); // This code is contributed by noob2000.</script> Yes Mithun Kumar 29AjayKumar Rajput-Ji noob2000 surindertarika1234 divisors number-theory sieve Mathematical number-theory Mathematical sieve 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) Count all possible paths from top left to bottom right of a mXn matrix Modular multiplicative inverse Program to multiply two matrices Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Min Cost Path | DP-6
[ { "code": null, "e": 25961, "s": 25933, "text": "\n30 Nov, 2021" }, { "code": null, "e": 26279, "s": 25961, "text": "In number theory, an arithmetic number is an integer for which the average of its positive divisors is also an integer. Or in other words, a number N is arithmetic if the number of divisors divides the sum of divisors. Given a positive integer n. The task is to check whether n is Arithmetic number or not.Examples: " }, { "code": null, "e": 26488, "s": 26279, "text": "Input : n = 6\nOutput : Yes\nSum of divisor of 6 = 1 + 2 + 3 + 6 = 12.\nNumber of divisor of 6 = 4.\nSo, on dividing Sum of divisor by Number of divisor\n= 12/4 = 3, which is an integer.\n\nInput : n = 2\nOutput : No" }, { "code": null, "e": 26500, "s": 26490, "text": "Algorithm" }, { "code": null, "e": 26621, "s": 26500, "text": "Find sum of all the factors of a number , say sum.Find count of divisors (say Count).Check if sum is divisible by count." }, { "code": null, "e": 26672, "s": 26621, "text": "Find sum of all the factors of a number , say sum." }, { "code": null, "e": 26708, "s": 26672, "text": "Find count of divisors (say Count)." }, { "code": null, "e": 26744, "s": 26708, "text": "Check if sum is divisible by count." }, { "code": null, "e": 26750, "s": 26746, "text": "C++" }, { "code": null, "e": 26755, "s": 26750, "text": "Java" }, { "code": null, "e": 26763, "s": 26755, "text": "Python3" }, { "code": null, "e": 26766, "s": 26763, "text": "C#" }, { "code": null, "e": 26770, "s": 26766, "text": "PHP" }, { "code": null, "e": 26781, "s": 26770, "text": "Javascript" }, { "code": "// CPP program to check if a number is Arithmetic// number or not#include <bits/stdc++.h>using namespace std; // Sieve Of Eratosthenesvoid SieveOfEratosthenes(int n, bool prime[], bool primesquare[], int a[]){ for (int i = 2; i <= n; i++) prime[i] = true; for (int i = 0; i <= (n * n + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsint countDivisors(int n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; bool prime[n + 1], primesquare[n * n + 1]; int a[n]; // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of // distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; cnt = cnt + 1; // incrementing power } // Calculating number of divisors // If n = a^p * b^q then total // divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Returns sum of all factors of n.int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Check if number is Arithmetic Number// or not.bool checkArithmetic(int n){ int count = countDivisors(n); int sum = sumofFactors(n); return (sum % count == 0);} // Driven Programint main(){ int n = 6; (checkArithmetic(n)) ? (cout << \"Yes\") : (cout << \"No\"); return 0;}", "e": 29982, "s": 26781, "text": null }, { "code": "// Java program to check if a number is Arithmetic// number or notclass GFG{ // Sieve Of Eratosthenesstatic void SieveOfEratosthenes(int n, boolean prime[], boolean primesquare[], int a[]){ for (int i = 2; i <= n; i++) prime[i] = true; for (int i = 0; i <= (n * n ); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsstatic int countDivisors(int n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; boolean prime[] = new boolean[n + 1], primesquare[] = new boolean[n * n + 1]; int a[] = new int[n]; // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of // distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; cnt = cnt + 1; // incrementing power } // Calculating number of divisors // If n = a^p * b^q then total // divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Returns sum of all factors of n.static int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Check if number is Arithmetic Number// or not.static boolean checkArithmetic(int n){ int count = countDivisors(n); int sum = sumofFactors(n); return (sum % count == 0);} // Driver Programpublic static void main(String[] args){ int n = 6; if(checkArithmetic(n)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code has been contributed by 29AjayKumar", "e": 33362, "s": 29982, "text": null }, { "code": "# Python3 program to check if# a number is Arithmetic# number or notimport math # Sieve Of Eratosthenesdef SieveOfEratosthenes(n, prime,primesquare, a): for i in range(2,n+1): prime[i] = True; for i in range((n * n + 1)+1): primesquare[i] = False; # 1 is not a # prime number prime[1] = False; p = 2; while (p * p <= n): # If prime[p] is # not changed, then # it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2,n+1,p): prime[i] = False; p+=1; j = 0; for p in range(2,n+1): if (prime[p]): # Storing primes in an array a[j] = p; # Update value in # primesquare[p*p], # if p is prime. primesquare[p * p] = True; j+=1; # Function to count divisorsdef countDivisors(n): # If number is 1, then it # will have only 1 as a # factor. So, total factors # will be 1. if (n == 1): return 1; prime = [False]*(n + 2); primesquare = [False]*(n *n + 3); # for storing primes upto n a = [0]*n; # Calling SieveOfEratosthenes # to store prime factors of # n and to store square of # prime factors of n SieveOfEratosthenes(n, prime,primesquare, a); # ans will contain # total number of # distinct divisors ans = 1; # Loop for counting # factors of n for i in range(0,True): # a[i] is not less # than cube root n if (a[i] * a[i] * a[i] > n): break; # Calculating power of # a[i] in n. cnt is power # of prime a[i] in n. cnt = 1; # if a[i] is a factor of n while (n % a[i] == 0): n //= a[i]; # incrementing power cnt = cnt + 1; # Calculating number of # divisors. If n = a^p * b^q # then total divisors # of n are (p+1)*(q+1) ans = ans * cnt; # if a[i] is greater # than cube root of n # First case if (prime[n]): ans = ans * 2; # Second case elif (primesquare[n]): ans = ans * 3; # Third case elif (n != 1): ans = ans * 4; return ans; # Total divisors # Returns sum of# all factors of n.def sumofFactors(n): # Traversing through # all prime factors. res = 1; for i in range(2,int(math.sqrt(n))+1): count = 0; curr_sum = 1; curr_term = 1; while (n % i == 0): count+=1; n //= i; curr_term *= i; curr_sum += curr_term; res *= curr_sum; # This condition is to handle # the case when n is a prime # number greater than 2. if (n >= 2): res *= (1 + n); return res; # Check if number is# Arithmetic Number or not.def checkArithmetic(n): count = countDivisors(n); sum = sumofFactors(n); return (sum % count == 0); # Driver coden = 6;if(checkArithmetic(n)): print(\"Yes\");else: print(\"No\"); # This code is contributed# by mits", "e": 36440, "s": 33362, "text": null }, { "code": "// C# program to check if a number// is arithmetic number or notusing System; class GFG{ // Sieve Of Eratosthenesstatic void SieveOfEratosthenes(int n, bool []prime, bool []primesquare, int []a){ for (int i = 2; i <= n; i++) prime[i] = true; for (int i = 0; i <= (n * n ); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } int j = 0; for (int p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsstatic int countDivisors(int n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; bool []prime = new bool[n + 1]; bool []primesquare = new bool[n * n + 1]; int []a = new int[n]; // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of // distinct divisors int ans = 1; // Loop for counting factors of n for (int i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. int cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = n / a[i]; cnt = cnt + 1; // incrementing power } // Calculating number of divisors // If n = a^p * b^q then total // divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Returns sum of all factors of n.static int sumofFactors(int n){ // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; while (n % i == 0) { count++; n = n / i; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Check if number is Arithmetic Number// or not.static bool checkArithmetic(int n){ int count = countDivisors(n); int sum = sumofFactors(n); return (sum % count == 0);} // Driver codepublic static void Main(String[] args){ int n = 6; if(checkArithmetic(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code contributed by Rajput-Ji", "e": 39795, "s": 36440, "text": null }, { "code": "<?php// PHP program to check if// a number is Arithmetic// number or not // Sieve Of Eratosthenesfunction SieveOfEratosthenes($n, &$prime, &$primesquare, &$a){ for ($i = 2; $i <= $n; $i++) $prime[$i] = true; for ($i = 0; $i <= ($n * $n + 1); $i++) $primesquare[$i] = false; // 1 is not a // prime number $prime[1] = false; for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is // not changed, then // it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } $j = 0; for ($p = 2; $p <= $n; $p++) { if ($prime[$p]) { // Storing primes in an array $a[$j] = $p; // Update value in // primesquare[p*p], // if p is prime. $primesquare[$p * $p] = true; $j++; } }} // Function to count divisorsfunction countDivisors($n){ // If number is 1, then it // will have only 1 as a // factor. So, total factors // will be 1. if ($n == 1) return 1; $prime = array_fill(0, ($n + 1), false); $primesquare = array_fill(0, ($n * $n + 1), false); // for storing primes upto n $a = array_fill(0, $n, 0); // Calling SieveOfEratosthenes // to store prime factors of // n and to store square of // prime factors of n SieveOfEratosthenes($n, $prime, $primesquare, $a); // ans will contain // total number of // distinct divisors $ans = 1; // Loop for counting // factors of n for ($i = 0;; $i++) { // a[i] is not less // than cube root n if ($a[$i] * $a[$i] * $a[$i] > $n) break; // Calculating power of // a[i] in n. cnt is power // of prime a[i] in n. $cnt = 1; // if a[i] is a factor of n while ($n % $a[$i] == 0) { $n = (int)($n / $a[$i]); // incrementing power $cnt = $cnt + 1; } // Calculating number of // divisors. If n = a^p * b^q // then total divisors // of n are (p+1)*(q+1) $ans = $ans * $cnt; } // if a[i] is greater // than cube root of n // First case if ($prime[$n]) $ans = $ans * 2; // Second case else if ($primesquare[$n]) $ans = $ans * 3; // Third case else if ($n != 1) $ans = $ans * 4; return $ans; // Total divisors} // Returns sum of// all factors of n.function sumofFactors($n){ // Traversing through // all prime factors. $res = 1; for ($i = 2; $i <= sqrt($n); $i++) { $count = 0; $curr_sum = 1; $curr_term = 1; while ($n % $i == 0) { $count++; $n = (int)($n / $i); $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if ($n >= 2) $res *= (1 + $n); return $res;} // Check if number is// Arithmetic Number or not.function checkArithmetic($n){ $count = countDivisors($n); $sum = sumofFactors($n); return ($sum % $count == 0);} // Driver code$n = 6;echo (checkArithmetic($n)) ? \"Yes\" : \"No\"; // This code is contributed// by mits?>", "e": 43319, "s": 39795, "text": null }, { "code": "<script> // Javascript program to check if a number is Arithmetic// number or not // Sieve Of Eratosthenesfunction SieveOfEratosthenes(n, prime, primesquare, a){ for (var i = 2; i <= n; i++) prime[i] = true; for (var i = 0; i <= (n * n + 1); i++) primesquare[i] = false; // 1 is not a prime number prime[1] = false; for (var p = 2; p * p <= n; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p * 2; i <= n; i += p) prime[i] = false; } } var j = 0; for (var p = 2; p <= n; p++) { if (prime[p]) { // Storing primes in an array a[j] = p; // Update value in primesquare[p*p], // if p is prime. primesquare[p * p] = true; j++; } }} // Function to count divisorsfunction countDivisors(n){ // If number is 1, then it will have only 1 // as a factor. So, total factors will be 1. if (n == 1) return 1; var prime = Array(n+1).fill(false); var primesquare = Array(n * n + 1).fill(0); var a = Array(n).fill(0); // for storing primes upto n // Calling SieveOfEratosthenes to store prime // factors of n and to store square of prime // factors of n SieveOfEratosthenes(n, prime, primesquare, a); // ans will contain total number of // distinct divisors var ans = 1; // Loop for counting factors of n for (var i = 0;; i++) { // a[i] is not less than cube root n if (a[i] * a[i] * a[i] > n) break; // Calculating power of a[i] in n. // cnt is power of prime a[i] in n. var cnt = 1; // if a[i] is a factor of n while (n % a[i] == 0) { n = parseInt(n / a[i]); cnt = cnt + 1; // incrementing power } // Calculating number of divisors // If n = a^p * b^q then total // divisors of n // are (p+1)*(q+1) ans = ans * cnt; } // if a[i] is greater than cube root of n // First case if (prime[n]) ans = ans * 2; // Second case else if (primesquare[n]) ans = ans * 3; // Third case else if (n != 1) ans = ans * 4; return ans; // Total divisors} // Returns sum of all factors of n.function sumofFactors(n){ // Traversing through all prime factors. var res = 1; for (var i = 2; i <= Math.sqrt(n); i++) { var count = 0, curr_sum = 1; var curr_term = 1; while (n % i == 0) { count++; n = parseInt(n / i); curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle // the case when n is a prime // number greater than 2. if (n >= 2) res *= (1 + n); return res;} // Check if number is Arithmetic Number// or not.function checkArithmetic(n){ var count = countDivisors(n); var sum = sumofFactors(n); return (sum % count == 0);} // Driven Programvar n = 6;(checkArithmetic(n)) ? (document.write( \"Yes\")) : (document.write( \"No\")); // This code is contributed by noob2000.</script>", "e": 46567, "s": 43319, "text": null }, { "code": null, "e": 46571, "s": 46567, "text": "Yes" }, { "code": null, "e": 46586, "s": 46573, "text": "Mithun Kumar" }, { "code": null, "e": 46598, "s": 46586, "text": "29AjayKumar" }, { "code": null, "e": 46608, "s": 46598, "text": "Rajput-Ji" }, { "code": null, "e": 46617, "s": 46608, "text": "noob2000" }, { "code": null, "e": 46636, "s": 46617, "text": "surindertarika1234" }, { "code": null, "e": 46645, "s": 46636, "text": "divisors" }, { "code": null, "e": 46659, "s": 46645, "text": "number-theory" }, { "code": null, "e": 46665, "s": 46659, "text": "sieve" }, { "code": null, "e": 46678, "s": 46665, "text": "Mathematical" }, { "code": null, "e": 46692, "s": 46678, "text": "number-theory" }, { "code": null, "e": 46705, "s": 46692, "text": "Mathematical" }, { "code": null, "e": 46711, "s": 46705, "text": "sieve" }, { "code": null, "e": 46809, "s": 46711, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46853, "s": 46809, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 46895, "s": 46853, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 46966, "s": 46895, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 46997, "s": 46966, "text": "Modular multiplicative inverse" }, { "code": null, "e": 47030, "s": 46997, "text": "Program to multiply two matrices" }, { "code": null, "e": 47055, "s": 47030, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 47087, "s": 47055, "text": "Check if a number is Palindrome" }, { "code": null, "e": 47122, "s": 47087, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 47168, "s": 47122, "text": "Merge two sorted arrays with O(1) extra space" } ]
SIGN() Function in SQL Server - GeeksforGeeks
30 Dec, 2020 SIGN() function :This function in SQL Server is used to return the sign of the specified number. It returns 1 if the number is positive, -1 if the number is negative and 0 for zero number. Features : This function is used to find the sign of the given number i.e., that given number is positive or negative or zero. This function accepts only all type of numbers i.e., positive, negative, zero. This function also accepts fraction numbers. This function always returns 1 if the number is positive, -1 if the number is negative and 0 for zero number. Syntax : SIGN(number) Parameter :This method accepts a parameter as given below : number : Specified number to return the sign for. Returns :It returns the sign of the specified number. Example-1 :Getting the result as 1 i.e., positive for the specified number 2. SELECT SIGN(2); Output : 1 Example-2 :Getting the result as -1 i.e., negative for the specified number -7. SELECT SIGN(-7); Output : -1 Example-3 :Using SIGN() function with a variable and getting the result as 0 for the specified number 0. DECLARE @Parameter_Value INT; SET @Parameter_Value = 0; SELECT SIGN(@Parameter_Value); Output : 0 Example-4 :Getting the result as 1 i.e., positive for the result of “5/2”. SELECT SIGN(5/2); Output : 1 Example-5 :Using SIGN() function with a variable and getting the result as 1 i.e., positive for the float value “5.75”. DECLARE @Parameter_Value FLOAT; SET @Parameter_Value = 5.75; SELECT SIGN(@Parameter_Value); Output : 1.0 Application :This function is used to return the sign of the specified number. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL | Subquery SQL Query to Convert VARCHAR to INT SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n30 Dec, 2020" }, { "code": null, "e": 25702, "s": 25513, "text": "SIGN() function :This function in SQL Server is used to return the sign of the specified number. It returns 1 if the number is positive, -1 if the number is negative and 0 for zero number." }, { "code": null, "e": 25713, "s": 25702, "text": "Features :" }, { "code": null, "e": 25829, "s": 25713, "text": "This function is used to find the sign of the given number i.e., that given number is positive or negative or zero." }, { "code": null, "e": 25908, "s": 25829, "text": "This function accepts only all type of numbers i.e., positive, negative, zero." }, { "code": null, "e": 25953, "s": 25908, "text": "This function also accepts fraction numbers." }, { "code": null, "e": 26063, "s": 25953, "text": "This function always returns 1 if the number is positive, -1 if the number is negative and 0 for zero number." }, { "code": null, "e": 26072, "s": 26063, "text": "Syntax :" }, { "code": null, "e": 26085, "s": 26072, "text": "SIGN(number)" }, { "code": null, "e": 26145, "s": 26085, "text": "Parameter :This method accepts a parameter as given below :" }, { "code": null, "e": 26195, "s": 26145, "text": "number : Specified number to return the sign for." }, { "code": null, "e": 26249, "s": 26195, "text": "Returns :It returns the sign of the specified number." }, { "code": null, "e": 26327, "s": 26249, "text": "Example-1 :Getting the result as 1 i.e., positive for the specified number 2." }, { "code": null, "e": 26343, "s": 26327, "text": "SELECT SIGN(2);" }, { "code": null, "e": 26352, "s": 26343, "text": "Output :" }, { "code": null, "e": 26354, "s": 26352, "text": "1" }, { "code": null, "e": 26434, "s": 26354, "text": "Example-2 :Getting the result as -1 i.e., negative for the specified number -7." }, { "code": null, "e": 26451, "s": 26434, "text": "SELECT SIGN(-7);" }, { "code": null, "e": 26460, "s": 26451, "text": "Output :" }, { "code": null, "e": 26463, "s": 26460, "text": "-1" }, { "code": null, "e": 26568, "s": 26463, "text": "Example-3 :Using SIGN() function with a variable and getting the result as 0 for the specified number 0." }, { "code": null, "e": 26656, "s": 26568, "text": "DECLARE @Parameter_Value INT;\nSET @Parameter_Value = 0;\nSELECT SIGN(@Parameter_Value);\n" }, { "code": null, "e": 26665, "s": 26656, "text": "Output :" }, { "code": null, "e": 26667, "s": 26665, "text": "0" }, { "code": null, "e": 26742, "s": 26667, "text": "Example-4 :Getting the result as 1 i.e., positive for the result of “5/2”." }, { "code": null, "e": 26760, "s": 26742, "text": "SELECT SIGN(5/2);" }, { "code": null, "e": 26769, "s": 26760, "text": "Output :" }, { "code": null, "e": 26771, "s": 26769, "text": "1" }, { "code": null, "e": 26891, "s": 26771, "text": "Example-5 :Using SIGN() function with a variable and getting the result as 1 i.e., positive for the float value “5.75”." }, { "code": null, "e": 26984, "s": 26891, "text": "DECLARE @Parameter_Value FLOAT;\nSET @Parameter_Value = 5.75;\nSELECT SIGN(@Parameter_Value);\n" }, { "code": null, "e": 26993, "s": 26984, "text": "Output :" }, { "code": null, "e": 26997, "s": 26993, "text": "1.0" }, { "code": null, "e": 27076, "s": 26997, "text": "Application :This function is used to return the sign of the specified number." }, { "code": null, "e": 27085, "s": 27076, "text": "DBMS-SQL" }, { "code": null, "e": 27096, "s": 27085, "text": "SQL-Server" }, { "code": null, "e": 27100, "s": 27096, "text": "SQL" }, { "code": null, "e": 27104, "s": 27100, "text": "SQL" }, { "code": null, "e": 27202, "s": 27104, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27268, "s": 27202, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27325, "s": 27268, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27357, "s": 27325, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27372, "s": 27357, "text": "SQL | Subquery" }, { "code": null, "e": 27408, "s": 27372, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27486, "s": 27408, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27503, "s": 27486, "text": "SQL using Python" }, { "code": null, "e": 27569, "s": 27503, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27631, "s": 27569, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
PHP | mysqli_real_escape_string() Function - GeeksforGeeks
16 Oct, 2021 The mysqli_real_escape_string() function is an inbuilt function in PHP which is used to escape all special characters for use in an SQL query. It is used before inserting a string in a database, as it removes any special characters that may interfere with the query operations. When simple strings are used, there are chances that special characters like backslashes and apostrophes are included in them (especially when they are getting data directly from a form where such data is entered). These are considered to be part of the query string and interfere with its normal functioning. php <?php $connection = mysqli_connect( "localhost", "root", "", "Persons"); // Check connectionif (mysqli_connect_errno()) { echo "Database connection failed.";} $firstname = "Robert'O";$lastname = "O'Connell"; $sql="INSERT INTO Persons (FirstName, LastName) VALUES ('$firstname', '$lastname')"; if (mysqli_query($connection, $sql)) { // Print the number of rows inserted in // the table, if insertion is successful printf("%d row inserted.\n", $mysqli->affected_rows);}else { // Query fails because the apostrophe in // the string interferes with the query printf("An error occurred!");} ?> In the above code, the query fails because the apostrophes are considered as part of the query when it is executed using mysqli_query(). The solution is to use mysqli_real_escape_string() before using the strings in the query. php <?php $connection = mysqli_connect( "localhost", "root", "", "Persons"); // Check connectionif (mysqli_connect_errno()) { echo "Database connection failed.";} $firstname = "Robert'O";$lastname = "O'Connell"; // Remove the special characters from the// string using mysqli_real_escape_string $lastname_escape = mysqli_real_escape_string( $connection, $lastname); $firstname_escape = mysqli_real_escape_string( $connection, $firstname); $sql="INSERT INTO Persons (FirstName, LastName) VALUES ('$firstname_escape', '$lastname_escape')"; if (mysqli_query($connection, $sql)) { // Print the number of rows inserted in // the table, if insertion is successful printf("%d row inserted.\n", $mysqli->affected_rows);} ?> Output: 1 row inserted. ezequieldesimone PHP-function PHP-MySQL PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 42163, "s": 42135, "text": "\n16 Oct, 2021" }, { "code": null, "e": 42753, "s": 42163, "text": "The mysqli_real_escape_string() function is an inbuilt function in PHP which is used to escape all special characters for use in an SQL query. It is used before inserting a string in a database, as it removes any special characters that may interfere with the query operations. When simple strings are used, there are chances that special characters like backslashes and apostrophes are included in them (especially when they are getting data directly from a form where such data is entered). These are considered to be part of the query string and interfere with its normal functioning. " }, { "code": null, "e": 42757, "s": 42753, "text": "php" }, { "code": "<?php $connection = mysqli_connect( \"localhost\", \"root\", \"\", \"Persons\"); // Check connectionif (mysqli_connect_errno()) { echo \"Database connection failed.\";} $firstname = \"Robert'O\";$lastname = \"O'Connell\"; $sql=\"INSERT INTO Persons (FirstName, LastName) VALUES ('$firstname', '$lastname')\"; if (mysqli_query($connection, $sql)) { // Print the number of rows inserted in // the table, if insertion is successful printf(\"%d row inserted.\\n\", $mysqli->affected_rows);}else { // Query fails because the apostrophe in // the string interferes with the query printf(\"An error occurred!\");} ?>", "e": 43415, "s": 42757, "text": null }, { "code": null, "e": 43643, "s": 43415, "text": "In the above code, the query fails because the apostrophes are considered as part of the query when it is executed using mysqli_query(). The solution is to use mysqli_real_escape_string() before using the strings in the query. " }, { "code": null, "e": 43647, "s": 43643, "text": "php" }, { "code": "<?php $connection = mysqli_connect( \"localhost\", \"root\", \"\", \"Persons\"); // Check connectionif (mysqli_connect_errno()) { echo \"Database connection failed.\";} $firstname = \"Robert'O\";$lastname = \"O'Connell\"; // Remove the special characters from the// string using mysqli_real_escape_string $lastname_escape = mysqli_real_escape_string( $connection, $lastname); $firstname_escape = mysqli_real_escape_string( $connection, $firstname); $sql=\"INSERT INTO Persons (FirstName, LastName) VALUES ('$firstname_escape', '$lastname_escape')\"; if (mysqli_query($connection, $sql)) { // Print the number of rows inserted in // the table, if insertion is successful printf(\"%d row inserted.\\n\", $mysqli->affected_rows);} ?>", "e": 44462, "s": 43647, "text": null }, { "code": null, "e": 44472, "s": 44462, "text": "Output: " }, { "code": null, "e": 44489, "s": 44472, "text": "1 row inserted. " }, { "code": null, "e": 44508, "s": 44491, "text": "ezequieldesimone" }, { "code": null, "e": 44521, "s": 44508, "text": "PHP-function" }, { "code": null, "e": 44531, "s": 44521, "text": "PHP-MySQL" }, { "code": null, "e": 44535, "s": 44531, "text": "PHP" }, { "code": null, "e": 44552, "s": 44535, "text": "Web Technologies" }, { "code": null, "e": 44556, "s": 44552, "text": "PHP" }, { "code": null, "e": 44654, "s": 44556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44699, "s": 44654, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 44749, "s": 44699, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 44789, "s": 44749, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 44813, "s": 44789, "text": "PHP in_array() Function" }, { "code": null, "e": 44857, "s": 44813, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 44897, "s": 44857, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 44930, "s": 44897, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 44975, "s": 44930, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45018, "s": 44975, "text": "How to fetch data from an API in ReactJS ?" } ]
How to store Data Triplet in a Vector in C++?
06 Jul, 2017 Given a vector, how can we store 3 elements in one cell of vector. Examples: Input : 2 5 10 3 6 15 Output : (2, 5, 10) // In first cell of vector (3, 6, 15) // In second cell of vector One solution is to create a user defined class or structure. We create a structure with three members, then create a vector of this structure. // C++ program to store data triplet in a vector// using user defined structure.#include<bits/stdc++.h>using namespace std; struct Test{ int x, y, z;}; int main(){ // Creating a vector of Test vector<Test> myvec; // Inserting elements into vector. First // value is assigned to x, second to y // and third to z. myvec.push_back({2, 31, 102}); myvec.push_back({5, 23, 114}); myvec.push_back({9, 10, 158}); int s = myvec.size(); for (int i=0;i<s;i++) { // Accessing structure members using their // names. cout << myvec[i].x << ", " << myvec[i].y << ", " << myvec[i].z << endl; } return 0;} Output : 2, 31, 102 5, 23, 114 9, 10, 158 Another solution is to use pair class in C++ STL. We make a pair with first element as normal element and second element as another pair, therefore storing 3 elements simultaneously. // C++ program to store data triplet in a vector// using pair class#include<bits/stdc++.h>using namespace std; int main(){ // We make a pair with first element as normal // element and second element as another pair. // therefore 3 elements simultaneously. vector< pair<int, pair<int, int> > > myvec; // For inserting element in pair use // make_pair(). myvec.push_back(make_pair(2, make_pair(31, 102))); myvec.push_back(make_pair(5, make_pair(23, 114))); myvec.push_back(make_pair(9, make_pair(10, 158))); int s = myvec.size(); for (int i=0; i<s; i++) { // The elements can be directly accessed // according to first or second element // of the pair. cout << myvec[i].first << ", " << myvec[i].second.first << ", " << myvec[i].second.second << endl; } return 0;} Output: 2, 31, 102 5, 23, 114 9, 10, 158 This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library std::find in C++ List in C++ Standard Template Library (STL) Inline Functions in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2017" }, { "code": null, "e": 119, "s": 52, "text": "Given a vector, how can we store 3 elements in one cell of vector." }, { "code": null, "e": 129, "s": 119, "text": "Examples:" }, { "code": null, "e": 257, "s": 129, "text": "Input : 2 5 10\n 3 6 15\nOutput : (2, 5, 10) // In first cell of vector\n (3, 6, 15) // In second cell of vector\n" }, { "code": null, "e": 400, "s": 257, "text": "One solution is to create a user defined class or structure. We create a structure with three members, then create a vector of this structure." }, { "code": "// C++ program to store data triplet in a vector// using user defined structure.#include<bits/stdc++.h>using namespace std; struct Test{ int x, y, z;}; int main(){ // Creating a vector of Test vector<Test> myvec; // Inserting elements into vector. First // value is assigned to x, second to y // and third to z. myvec.push_back({2, 31, 102}); myvec.push_back({5, 23, 114}); myvec.push_back({9, 10, 158}); int s = myvec.size(); for (int i=0;i<s;i++) { // Accessing structure members using their // names. cout << myvec[i].x << \", \" << myvec[i].y << \", \" << myvec[i].z << endl; } return 0;}", "e": 1069, "s": 400, "text": null }, { "code": null, "e": 1078, "s": 1069, "text": "Output :" }, { "code": null, "e": 1112, "s": 1078, "text": "2, 31, 102\n5, 23, 114\n9, 10, 158\n" }, { "code": null, "e": 1297, "s": 1114, "text": "Another solution is to use pair class in C++ STL. We make a pair with first element as normal element and second element as another pair, therefore storing 3 elements simultaneously." }, { "code": "// C++ program to store data triplet in a vector// using pair class#include<bits/stdc++.h>using namespace std; int main(){ // We make a pair with first element as normal // element and second element as another pair. // therefore 3 elements simultaneously. vector< pair<int, pair<int, int> > > myvec; // For inserting element in pair use // make_pair(). myvec.push_back(make_pair(2, make_pair(31, 102))); myvec.push_back(make_pair(5, make_pair(23, 114))); myvec.push_back(make_pair(9, make_pair(10, 158))); int s = myvec.size(); for (int i=0; i<s; i++) { // The elements can be directly accessed // according to first or second element // of the pair. cout << myvec[i].first << \", \" << myvec[i].second.first << \", \" << myvec[i].second.second << endl; } return 0;} ", "e": 2150, "s": 1297, "text": null }, { "code": null, "e": 2158, "s": 2150, "text": "Output:" }, { "code": null, "e": 2192, "s": 2158, "text": "2, 31, 102\n5, 23, 114\n9, 10, 158\n" }, { "code": null, "e": 2491, "s": 2192, "text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2616, "s": 2491, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2638, "s": 2616, "text": "cpp-algorithm-library" }, { "code": null, "e": 2642, "s": 2638, "text": "STL" }, { "code": null, "e": 2646, "s": 2642, "text": "C++" }, { "code": null, "e": 2650, "s": 2646, "text": "STL" }, { "code": null, "e": 2654, "s": 2650, "text": "CPP" }, { "code": null, "e": 2752, "s": 2654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2776, "s": 2752, "text": "Sorting a vector in C++" }, { "code": null, "e": 2796, "s": 2776, "text": "Polymorphism in C++" }, { "code": null, "e": 2829, "s": 2796, "text": "Friend class and function in C++" }, { "code": null, "e": 2873, "s": 2829, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 2898, "s": 2873, "text": "std::string class in C++" }, { "code": null, "e": 2943, "s": 2898, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2991, "s": 2943, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3008, "s": 2991, "text": "std::find in C++" }, { "code": null, "e": 3052, "s": 3008, "text": "List in C++ Standard Template Library (STL)" } ]
SAP ABAP - If...Else Statement
In case of IF....ELSE statements, if the expression evaluates to true then the IF block of code will be executed. Otherwise, ELSE block of code will be executed. The following syntax is used for IF....ELSE statement. IF<condition_1>. <statement block 1>. ELSE. <statement block 2>. ENDIF. Report YH_SEP_15. Data Title_1(20) TYPE C. Title_1 = 'Tutorials'. IF Title_1 = 'Tutorial'. write 'This is IF Statement'. ELSE. write 'This is ELSE Statement'. ENDIF. The above code produces the following output − This is ELSE Statement. Sometimes nesting of the IF statements can make the code difficult to understand. In such cases, the ELSEIF statement is used to avoid nesting of the IF statement. When using IF, ELSEIF and ELSE statements there are a few points to consider − An IF statement can have zero or one ELSE statement and it must come after any ELSEIF statement. An IF statement can have zero or one ELSE statement and it must come after any ELSEIF statement. An IF statement can have zero to many ELSEIF statements and they must come before the ELSE statement. An IF statement can have zero to many ELSEIF statements and they must come before the ELSE statement. If an ELSEIF statement succeeds, none of the remaining ELSEIF statements or ELSE statement will be tested. If an ELSEIF statement succeeds, none of the remaining ELSEIF statements or ELSE statement will be tested. The following syntax is used for the IF....ELSEIF....ELSE statement. IF<condition_1>. <statement block 1>. ELSEIF<condition_2>. <statement block 2>. ELSEIF<condition_3>. <statement block 3>. ...... ...... ...... ...... ELSE. <statement block>. ENDIF. In the above syntax, the execution of the processing block is based on the result of one or more logical conditions associated with the processing block. Here − condition_1 of IF statement represents a logical condition that evaluates a true or false condition. condition_1 of IF statement represents a logical condition that evaluates a true or false condition. condition_2 shows the second condition specified in the ELSEIF statement, which is executed when the IF statement condition turns out to be false. condition_2 shows the second condition specified in the ELSEIF statement, which is executed when the IF statement condition turns out to be false. ENDIF denotes the end of the IF statement block. ENDIF denotes the end of the IF statement block. Report YH_SEP_15. Data Result TYPE I VALUE 65. IF Result < 0. Write / 'Result is less than zero'. ELSEIF Result < 70. Write / 'Result is less than seventy'. ELSE. Write / 'Result is greater than seventy'. ENDIF. The above code produces the following output − Result is less than seventy.
[ { "code": null, "e": 3194, "s": 3032, "text": "In case of IF....ELSE statements, if the expression evaluates to true then the IF block of code will be executed. Otherwise, ELSE block of code will be executed." }, { "code": null, "e": 3249, "s": 3194, "text": "The following syntax is used for IF....ELSE statement." }, { "code": null, "e": 3337, "s": 3249, "text": "IF<condition_1>. \n <statement block 1>. \nELSE. \n <statement block 2>. \nENDIF.\n" }, { "code": null, "e": 3530, "s": 3337, "text": "Report YH_SEP_15.\n \nData Title_1(20) TYPE C. \n Title_1 = 'Tutorials'.\n\t\nIF Title_1 = 'Tutorial'. \n write 'This is IF Statement'. \nELSE. \n write 'This is ELSE Statement'.\n \nENDIF." }, { "code": null, "e": 3577, "s": 3530, "text": "The above code produces the following output −" }, { "code": null, "e": 3602, "s": 3577, "text": "This is ELSE Statement.\n" }, { "code": null, "e": 3766, "s": 3602, "text": "Sometimes nesting of the IF statements can make the code difficult to understand. In such cases, the ELSEIF statement is used to avoid nesting of the IF statement." }, { "code": null, "e": 3845, "s": 3766, "text": "When using IF, ELSEIF and ELSE statements there are a few points to consider −" }, { "code": null, "e": 3942, "s": 3845, "text": "An IF statement can have zero or one ELSE statement and it must come after any ELSEIF statement." }, { "code": null, "e": 4039, "s": 3942, "text": "An IF statement can have zero or one ELSE statement and it must come after any ELSEIF statement." }, { "code": null, "e": 4141, "s": 4039, "text": "An IF statement can have zero to many ELSEIF statements and they must come before the ELSE statement." }, { "code": null, "e": 4243, "s": 4141, "text": "An IF statement can have zero to many ELSEIF statements and they must come before the ELSE statement." }, { "code": null, "e": 4350, "s": 4243, "text": "If an ELSEIF statement succeeds, none of the remaining ELSEIF statements or ELSE statement will be tested." }, { "code": null, "e": 4457, "s": 4350, "text": "If an ELSEIF statement succeeds, none of the remaining ELSEIF statements or ELSE statement will be tested." }, { "code": null, "e": 4526, "s": 4457, "text": "The following syntax is used for the IF....ELSEIF....ELSE statement." }, { "code": null, "e": 4735, "s": 4526, "text": "IF<condition_1>.\n \n<statement block 1>.\n \nELSEIF<condition_2>.\n \n<statement block 2>.\n \nELSEIF<condition_3>. \n \n<statement block 3>. \n...... \n...... \n...... \n...... \nELSE.\n \n<statement block>. \n\nENDIF.\n" }, { "code": null, "e": 4896, "s": 4735, "text": "In the above syntax, the execution of the processing block is based on the result of one or more logical conditions associated with the processing block. Here −" }, { "code": null, "e": 4997, "s": 4896, "text": "condition_1 of IF statement represents a logical condition that evaluates a true or false condition." }, { "code": null, "e": 5098, "s": 4997, "text": "condition_1 of IF statement represents a logical condition that evaluates a true or false condition." }, { "code": null, "e": 5245, "s": 5098, "text": "condition_2 shows the second condition specified in the ELSEIF statement, which is executed when the IF statement condition turns out to be false." }, { "code": null, "e": 5392, "s": 5245, "text": "condition_2 shows the second condition specified in the ELSEIF statement, which is executed when the IF statement condition turns out to be false." }, { "code": null, "e": 5441, "s": 5392, "text": "ENDIF denotes the end of the IF statement block." }, { "code": null, "e": 5490, "s": 5441, "text": "ENDIF denotes the end of the IF statement block." }, { "code": null, "e": 5733, "s": 5490, "text": "Report YH_SEP_15. \nData Result TYPE I VALUE 65. \n IF Result < 0. \n\t\nWrite / 'Result is less than zero'. \n ELSEIF Result < 70. \n\t\nWrite / 'Result is less than seventy'. \nELSE. \n\nWrite / 'Result is greater than seventy'.\n \n ENDIF." }, { "code": null, "e": 5780, "s": 5733, "text": "The above code produces the following output −" } ]
Recursive insertion and traversal linked list
03 Jul, 2022 We have discussed different methods of linked list insertion. How to recursively create a linked list? Recursively inserting at the end: To create a Linked list using recursion follow these steps. Below steps insert a new node recursively at the end of linked list. C++ Java Python3 C# Javascript // Function to insert a new node at the// end of linked list using recursion.Node* insertEnd(Node* head, int data){ // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == NULL) return newNode(data); // If we have not reached end, keep traversing // recursively. else head->next = insertEnd(head->next, data); return head;} // Function to insert a new node at the// end of linked list using recursion.static Node insertEnd(Node head, int data){ // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head;} // This code is contributed by rutvik_56 # Function to insert a new node at the# end of linked list using recursion.def insertEnd(head, data): # If linked list is empty, create a # new node (Assuming newNode() allocates # a new node with given data) if (head == None): return newNode(data) # If we have not reached end, # keep traversing recursively. else: head.next = insertEnd(head.next, data) return head # This code is contributed by divyeshrabadiya07 // Function to insert a new node at the // end of linked list using recursion. static Node insertEnd(Node head, int data) { // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head; } // This code is contributed by divyesh072019 <script> // Function to insert a new node at the// end of linked list using recursion.function insertEnd(head , data){ // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) { return newNode(data); } // If we have not reached end, keep traversing // recursively. else { head.next = insertEnd(head.next, data); } return head;} // This code is contributed by shubhamsingh10 </script> Recursively traversing the list: The idea is simple, we print current node and recur for remaining list. C++ Java Python3 C# void traverse(Node* head){ if (head == NULL) return; // If head is not NULL, print current node // and recur for remaining list cout << head->data << " "; traverse(head->next);} static void traverse(Node head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list System.out.print( head.data + " "); traverse(head.next); } // This code is contributed by SUBHAMSINGH10 def traverse(head): if (head == None): return # If head is not None, print current node # and recur for remaining list print(head.data, end = " "); traverse(head.next) # This code is contributed by Pratham76 static void traverse(Node head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list Console.Write(head.data + " "); traverse(head.next); } Complete Program: Below is complete program to demonstrate working of insert and traverse a linked list. C++ Java Python3 C# Javascript // Recursive C++ program to recursively insert// a node and recursively print the list.#include <bits/stdc++.h>using namespace std;struct Node { int data; Node* next;}; // Allocates a new node with given dataNode *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a new node at the// end of linked list using recursion.Node* insertEnd(Node* head, int data){ // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == NULL) return newNode(data); // If we have not reached end, keep traversing // recursively. else head->next = insertEnd(head->next, data); return head;} void traverse(Node* head){ if (head == NULL) return; // If head is not NULL, print current node // and recur for remaining list cout << head->data << " "; traverse(head->next);} // Driver codeint main(){ Node* head = NULL; head = insertEnd(head, 6); head = insertEnd(head, 8); head = insertEnd(head, 10); head = insertEnd(head, 12); head = insertEnd(head, 14); traverse(head);} // Recursive Java program to recursively insert // a node and recursively print the list. class GFG{ static class Node { int data; Node next; }; // Allocates a new node with given data static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Function to insert a new node at the // end of linked list using recursion. static Node insertEnd(Node head, int data) { // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head; } static void traverse(Node head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list System.out.print( head.data + " "); traverse(head.next); } // Driver code public static void main(String args[]){ Node head = null; head = insertEnd(head, 6); head = insertEnd(head, 8); head = insertEnd(head, 10); head = insertEnd(head, 12); head = insertEnd(head, 14); traverse(head); } } // This code is contributed by andrew1234 # Recursive Python3 program to # recursively insert a node and# recursively print the list.import math class Node: def __init__(self, data): self.data = data self.next = None # Allocates a new node with given datadef newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to insert a new node at the# end of linked list using recursion.def insertEnd(head, data): # If linked list is empty, create a # new node (Assuming newNode() allocates # a new node with given data) if (head == None): return newNode(data) # If we have not reached end, # keep traversing recursively. else: head.next = insertEnd(head.next, data) return head def traverse(head): if (head == None): return # If head is not None, print current node # and recur for remaining list print(head.data, end = " "); traverse(head.next) # Driver codeif __name__=='__main__': head = None head = insertEnd(head, 6) head = insertEnd(head, 8) head = insertEnd(head, 10) head = insertEnd(head, 12) head = insertEnd(head, 14) traverse(head) # This code is contributed by sapna singh // Recursive C# program to recursively insert // a node and recursively print the list. using System; class GFG { public class Node { public int data; public Node next; }; // Allocates a new node with given data static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Function to insert a new node at the // end of linked list using recursion. static Node insertEnd(Node head, int data) { // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head; } static void traverse(Node head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list Console.Write(head.data + " "); traverse(head.next); } // Driver code public static void Main(String []args) { Node head = null; head = insertEnd(head, 6); head = insertEnd(head, 8); head = insertEnd(head, 10); head = insertEnd(head, 12); head = insertEnd(head, 14); traverse(head); } } // This code is contributed by 29AjayKumar <script> // Recursive Javascript program to recursively insert // a node and recursively print the list. class Node { constructor(data) { this.next = null; this.data = data; } } // Allocates a new node with given data function newNode(data) { let new_node = new Node(data); return new_node; } // Function to insert a new node at the // end of linked list using recursion. function insertEnd(head, data) { // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head; } function traverse(head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list document.write(head.data + " "); traverse(head.next); } let head = null; head = insertEnd(head, 6); head = insertEnd(head, 8); head = insertEnd(head, 10); head = insertEnd(head, 12); head = insertEnd(head, 14); traverse(head); // This code is contributed by mukesh07.</script> Output: 6 8 10 12 14 This article is contributed by AMIT KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. andrew1234 29AjayKumar sapnasingh4991 rutvik_56 divyesh072019 divyeshrabadiya07 pratham76 SHUBHAMSINGH10 mukesh07 Linked List Recursion Linked List Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion) Merge two sorted linked lists What is Data Structure: Types, Classifications and Applications Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jul, 2022" }, { "code": null, "e": 157, "s": 54, "text": "We have discussed different methods of linked list insertion. How to recursively create a linked list?" }, { "code": null, "e": 322, "s": 157, "text": "Recursively inserting at the end: To create a Linked list using recursion follow these steps. Below steps insert a new node recursively at the end of linked list. " }, { "code": null, "e": 326, "s": 322, "text": "C++" }, { "code": null, "e": 331, "s": 326, "text": "Java" }, { "code": null, "e": 339, "s": 331, "text": "Python3" }, { "code": null, "e": 342, "s": 339, "text": "C#" }, { "code": null, "e": 353, "s": 342, "text": "Javascript" }, { "code": "// Function to insert a new node at the// end of linked list using recursion.Node* insertEnd(Node* head, int data){ // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == NULL) return newNode(data); // If we have not reached end, keep traversing // recursively. else head->next = insertEnd(head->next, data); return head;}", "e": 787, "s": 353, "text": null }, { "code": "// Function to insert a new node at the// end of linked list using recursion.static Node insertEnd(Node head, int data){ // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head;} // This code is contributed by rutvik_56", "e": 1274, "s": 787, "text": null }, { "code": "# Function to insert a new node at the# end of linked list using recursion.def insertEnd(head, data): # If linked list is empty, create a # new node (Assuming newNode() allocates # a new node with given data) if (head == None): return newNode(data) # If we have not reached end, # keep traversing recursively. else: head.next = insertEnd(head.next, data) return head # This code is contributed by divyeshrabadiya07", "e": 1747, "s": 1274, "text": null }, { "code": "// Function to insert a new node at the // end of linked list using recursion. static Node insertEnd(Node head, int data) { // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head; } // This code is contributed by divyesh072019", "e": 2262, "s": 1747, "text": null }, { "code": "<script> // Function to insert a new node at the// end of linked list using recursion.function insertEnd(head , data){ // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) { return newNode(data); } // If we have not reached end, keep traversing // recursively. else { head.next = insertEnd(head.next, data); } return head;} // This code is contributed by shubhamsingh10 </script>", "e": 2780, "s": 2262, "text": null }, { "code": null, "e": 2887, "s": 2780, "text": "Recursively traversing the list: The idea is simple, we print current node and recur for remaining list. " }, { "code": null, "e": 2891, "s": 2887, "text": "C++" }, { "code": null, "e": 2896, "s": 2891, "text": "Java" }, { "code": null, "e": 2904, "s": 2896, "text": "Python3" }, { "code": null, "e": 2907, "s": 2904, "text": "C#" }, { "code": "void traverse(Node* head){ if (head == NULL) return; // If head is not NULL, print current node // and recur for remaining list cout << head->data << \" \"; traverse(head->next);}", "e": 3117, "s": 2907, "text": null }, { "code": "static void traverse(Node head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list System.out.print( head.data + \" \"); traverse(head.next); } // This code is contributed by SUBHAMSINGH10", "e": 3390, "s": 3117, "text": null }, { "code": "def traverse(head): if (head == None): return # If head is not None, print current node # and recur for remaining list print(head.data, end = \" \"); traverse(head.next) # This code is contributed by Pratham76", "e": 3637, "s": 3390, "text": null }, { "code": "static void traverse(Node head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list Console.Write(head.data + \" \"); traverse(head.next); }", "e": 3859, "s": 3637, "text": null }, { "code": null, "e": 3966, "s": 3859, "text": " Complete Program: Below is complete program to demonstrate working of insert and traverse a linked list. " }, { "code": null, "e": 3970, "s": 3966, "text": "C++" }, { "code": null, "e": 3975, "s": 3970, "text": "Java" }, { "code": null, "e": 3983, "s": 3975, "text": "Python3" }, { "code": null, "e": 3986, "s": 3983, "text": "C#" }, { "code": null, "e": 3997, "s": 3986, "text": "Javascript" }, { "code": "// Recursive C++ program to recursively insert// a node and recursively print the list.#include <bits/stdc++.h>using namespace std;struct Node { int data; Node* next;}; // Allocates a new node with given dataNode *newNode(int data){ Node *new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a new node at the// end of linked list using recursion.Node* insertEnd(Node* head, int data){ // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == NULL) return newNode(data); // If we have not reached end, keep traversing // recursively. else head->next = insertEnd(head->next, data); return head;} void traverse(Node* head){ if (head == NULL) return; // If head is not NULL, print current node // and recur for remaining list cout << head->data << \" \"; traverse(head->next);} // Driver codeint main(){ Node* head = NULL; head = insertEnd(head, 6); head = insertEnd(head, 8); head = insertEnd(head, 10); head = insertEnd(head, 12); head = insertEnd(head, 14); traverse(head);}", "e": 5208, "s": 3997, "text": null }, { "code": "// Recursive Java program to recursively insert // a node and recursively print the list. class GFG{ static class Node { int data; Node next; }; // Allocates a new node with given data static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Function to insert a new node at the // end of linked list using recursion. static Node insertEnd(Node head, int data) { // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head; } static void traverse(Node head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list System.out.print( head.data + \" \"); traverse(head.next); } // Driver code public static void main(String args[]){ Node head = null; head = insertEnd(head, 6); head = insertEnd(head, 8); head = insertEnd(head, 10); head = insertEnd(head, 12); head = insertEnd(head, 14); traverse(head); } } // This code is contributed by andrew1234", "e": 6527, "s": 5208, "text": null }, { "code": "# Recursive Python3 program to # recursively insert a node and# recursively print the list.import math class Node: def __init__(self, data): self.data = data self.next = None # Allocates a new node with given datadef newNode(data): new_node = Node(data) new_node.data = data new_node.next = None return new_node # Function to insert a new node at the# end of linked list using recursion.def insertEnd(head, data): # If linked list is empty, create a # new node (Assuming newNode() allocates # a new node with given data) if (head == None): return newNode(data) # If we have not reached end, # keep traversing recursively. else: head.next = insertEnd(head.next, data) return head def traverse(head): if (head == None): return # If head is not None, print current node # and recur for remaining list print(head.data, end = \" \"); traverse(head.next) # Driver codeif __name__=='__main__': head = None head = insertEnd(head, 6) head = insertEnd(head, 8) head = insertEnd(head, 10) head = insertEnd(head, 12) head = insertEnd(head, 14) traverse(head) # This code is contributed by sapna singh", "e": 7751, "s": 6527, "text": null }, { "code": "// Recursive C# program to recursively insert // a node and recursively print the list. using System; class GFG { public class Node { public int data; public Node next; }; // Allocates a new node with given data static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Function to insert a new node at the // end of linked list using recursion. static Node insertEnd(Node head, int data) { // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head; } static void traverse(Node head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list Console.Write(head.data + \" \"); traverse(head.next); } // Driver code public static void Main(String []args) { Node head = null; head = insertEnd(head, 6); head = insertEnd(head, 8); head = insertEnd(head, 10); head = insertEnd(head, 12); head = insertEnd(head, 14); traverse(head); } } // This code is contributed by 29AjayKumar", "e": 9099, "s": 7751, "text": null }, { "code": "<script> // Recursive Javascript program to recursively insert // a node and recursively print the list. class Node { constructor(data) { this.next = null; this.data = data; } } // Allocates a new node with given data function newNode(data) { let new_node = new Node(data); return new_node; } // Function to insert a new node at the // end of linked list using recursion. function insertEnd(head, data) { // If linked list is empty, create a // new node (Assuming newNode() allocates // a new node with given data) if (head == null) return newNode(data); // If we have not reached end, keep traversing // recursively. else head.next = insertEnd(head.next, data); return head; } function traverse(head) { if (head == null) return; // If head is not null, print current node // and recur for remaining list document.write(head.data + \" \"); traverse(head.next); } let head = null; head = insertEnd(head, 6); head = insertEnd(head, 8); head = insertEnd(head, 10); head = insertEnd(head, 12); head = insertEnd(head, 14); traverse(head); // This code is contributed by mukesh07.</script>", "e": 10454, "s": 9099, "text": null }, { "code": null, "e": 10463, "s": 10454, "text": "Output: " }, { "code": null, "e": 10476, "s": 10463, "text": "6 8 10 12 14" }, { "code": null, "e": 10895, "s": 10476, "text": "This article is contributed by AMIT KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10906, "s": 10895, "text": "andrew1234" }, { "code": null, "e": 10918, "s": 10906, "text": "29AjayKumar" }, { "code": null, "e": 10933, "s": 10918, "text": "sapnasingh4991" }, { "code": null, "e": 10943, "s": 10933, "text": "rutvik_56" }, { "code": null, "e": 10957, "s": 10943, "text": "divyesh072019" }, { "code": null, "e": 10975, "s": 10957, "text": "divyeshrabadiya07" }, { "code": null, "e": 10985, "s": 10975, "text": "pratham76" }, { "code": null, "e": 11000, "s": 10985, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 11009, "s": 11000, "text": "mukesh07" }, { "code": null, "e": 11021, "s": 11009, "text": "Linked List" }, { "code": null, "e": 11031, "s": 11021, "text": "Recursion" }, { "code": null, "e": 11043, "s": 11031, "text": "Linked List" }, { "code": null, "e": 11053, "s": 11043, "text": "Recursion" }, { "code": null, "e": 11151, "s": 11053, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11170, "s": 11151, "text": "LinkedList in Java" }, { "code": null, "e": 11202, "s": 11170, "text": "Introduction to Data Structures" }, { "code": null, "e": 11258, "s": 11202, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 11288, "s": 11258, "text": "Merge two sorted linked lists" }, { "code": null, "e": 11352, "s": 11288, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 11412, "s": 11352, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 11497, "s": 11412, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 11507, "s": 11497, "text": "Recursion" }, { "code": null, "e": 11534, "s": 11507, "text": "Program for Tower of Hanoi" } ]
Program to build a DFA that checks if a string ends with “01” or “10”
10 May, 2021 DFA or Deterministic Finite Automata is a finite state machine which accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.Problem: Given a string of ‘0’s and ‘1’s character by character, check for the last two characters to be “01” or “10” else reject the string. Also print the state diagram irrespective of acceptance or rejection. Since in DFA, there is no concept of memory, therefore we can only check for one character at a time, beginning with the 0th character. The input set for this problem is {0, 1}. For each character in the input set, each state of DFA redirects to another valid state.DFA Machine: For the above problem statement, we must first build a DFA machine. DFA machine is similar to a flowchart with various states and transitions. DFA machine corresponding to the above problem is shown below, Q3 and Q4 are the final states: Examples: Input: 010101 Output: State transitions are q0->q1->q3->q4 ->q3->q4->q3->YES Explanation : 010101 ends with "01". Input: 0100 Output: State transitions are q0->q1->q3->q4->q1->NO Explanation : 0100 ends with "00", which is not equal to any of "01" or "10". Algorithm: Define the minimum number of states required to make the state diagram. Use functions to define various states.List all the valid transitions. Each state must have a transition for every valid symbol.Define the final states by applying the base condition.Define all the state transitions using state function calls.Define a returning condition for the end of the string. Define the minimum number of states required to make the state diagram. Use functions to define various states. List all the valid transitions. Each state must have a transition for every valid symbol. Define the final states by applying the base condition. Define all the state transitions using state function calls. Define a returning condition for the end of the string. For the given DFA Machine: Q0, Q1, Q2, Q3, Q4 are defined as the number of states.0 and 1 are valid symbols. Each state has transitions for 0 and 1.Q3 and Q4 are defined as the final states.Suppose at state Q0, if 0 comes, the function call is made to Q1. So, if 1 comes, the function call is made to Q2.If the program reaches the end of the string, the output is made according to the state, the program is at. Q0, Q1, Q2, Q3, Q4 are defined as the number of states. 0 and 1 are valid symbols. Each state has transitions for 0 and 1. Q3 and Q4 are defined as the final states. Suppose at state Q0, if 0 comes, the function call is made to Q1. So, if 1 comes, the function call is made to Q2. If the program reaches the end of the string, the output is made according to the state, the program is at. Implementation: C++ Java Python3 C# Javascript // CPP Program to DFA that accepts string ending// with 01 or 10. #include <bits/stdc++.h>using namespace std; // Various states of DFA machine are defined// using functions.void q1(string, int);void q2(string, int);void q3(string, int);void q4(string, int); // End position is checked using the string// length value.// q0 is the starting state.// q1 and q2 are intermediate states.// q3 and q4 are final states.void q1(string s, int i){ cout << "q1->"; if (i == s.length()) { cout << "NO \n"; return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] == '0') q1(s, i + 1); else q3(s, i + 1);} void q2(string s, int i){ cout << "q2->"; if (i == s.length()) { cout << "NO \n"; return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] == '0') q4(s, i + 1); else q2(s, i + 1);} void q3(string s, int i){ cout << "q3->"; if (i == s.length()) { cout << "YES \n"; return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] == '0') q4(s, i + 1); else q2(s, i + 1);} void q4(string s, int i){ cout << "q4->"; if (i == s.length()) { cout << "YES \n"; return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] == '0') q1(s, i + 1); else q3(s, i + 1);} void q0(string s, int i){ cout << "q0->"; if (i == s.length()) { cout << "NO \n"; return; } // state transitions // 0 takes to q1, 1 takes to q2 if (s[i] == '0') q1(s, i + 1); else q2(s, i + 1);} // Driver Codeint main(){ string s = "010101"; // all state transitions are printed. // if string is accpetable, YES is printed. // else NO is printed cout << "State transitions are "; q0(s, 0);} // Java Program to DFA that accepts string ending// with 01 or 10.class GFG{ // End position is checked using the string // length value. // q0 is the starting state. // q1 and q2 are intermediate states. // q3 and q4 are final states. static void q1(String s, int i) { System.out.print("q1->"); if (i == s.length()) { System.out.println("NO"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s.charAt(i) == '0') q1(s, i + 1); else q3(s, i + 1); } static void q2(String s, int i) { System.out.print("q2->"); if (i == s.length()) { System.out.println("NO "); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s.charAt(i) == '0') q4(s, i + 1); else q2(s, i + 1); } static void q3(String s, int i) { System.out.print("q3->"); if (i == s.length()) { System.out.println("YES"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s.charAt(i) == '0') q4(s, i + 1); else q2(s, i + 1); } static void q4(String s, int i) { System.out.print("q4->"); if (i == s.length()) { System.out.println("YES"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s.charAt(i) == '0') q1(s, i + 1); else q3(s, i + 1); } static void q0(String s, int i) { System.out.print("q0->"); if (i == s.length()) { System.out.println("NO"); return; } // state transitions // 0 takes to q1, 1 takes to q2 if (s.charAt(i) == '0') q1(s, i + 1); else q2(s, i + 1); } // Driver Code public static void main (String[] args) { String s = "010101"; // all state transitions are printed. // if string is accpetable, YES is printed. // else NO is printed System.out.print("State transitions are "); q0(s, 0); }} // This code is contributed by AnkitRai01 # Python3 Program to DFA that accepts string ending# with 01 or 10. # End position is checked using the string# length value.# q0 is the starting state.# q1 and q2 are intermediate states.# q3 and q4 are final states.def q1(s, i) : print("q1->", end=""); if (i == len(s)) : print("NO"); return; # state transitions # 0 takes to q1, 1 takes to q3 if (s[i] == '0') : q1(s, i + 1); else : q3(s, i + 1); def q2(s, i) : print("q2->", end = ""); if (i == len(s)) : print("NO"); return; # state transitions # 0 takes to q4, 1 takes to q2 if (s[i] == '0') : q4(s, i + 1); else : q2(s, i + 1); def q3(s, i) : print("q3->", end = ""); if (i == len(s)) : print("YES"); return; # state transitions # 0 takes to q4, 1 takes to q2 if (s[i] == '0') : q4(s, i + 1); else : q2(s, i + 1); def q4(s, i) : print("q4->", end = ""); if (i == len(s)) : print("YES"); return; # state transitions # 0 takes to q1, 1 takes to q3 if (s[i] == '0') : q1(s, i + 1); else : q3(s, i + 1); def q0( s, i) : print("q0->", end = ""); if (i == len(s)) : print("NO"); return; # state transitions # 0 takes to q1, 1 takes to q2 if (s[i] == '0') : q1(s, i + 1); else : q2(s, i + 1); # Driver Codeif __name__ == "__main__" : s = "010101"; # all state transitions are printed. # if string is accpetable, YES is printed. # else NO is printed print("State transitions are", end = " "); q0(s, 0); # This code is contributed by AnkitRai01 // C# Program to DFA that accepts string ending// with 01 or 10.using System; class GFG{ // End position is checked using the string // length value. // q0 is the starting state. // q1 and q2 are intermediate states. // q3 and q4 are final states. static void q1(string s, int i) { Console.Write("q1->"); if (i == s.Length ) { Console.WriteLine("NO"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] == '0') q1(s, i + 1); else q3(s, i + 1); } static void q2(string s, int i) { Console.Write("q2->"); if (i == s.Length) { Console.WriteLine("NO "); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] == '0') q4(s, i + 1); else q2(s, i + 1); } static void q3(string s, int i) { Console.Write("q3->"); if (i == s.Length) { Console.WriteLine("YES"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] == '0') q4(s, i + 1); else q2(s, i + 1); } static void q4(string s, int i) { Console.Write("q4->"); if (i == s.Length) { Console.WriteLine("YES"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] == '0') q1(s, i + 1); else q3(s, i + 1); } static void q0(string s, int i) { Console.Write("q0->"); if (i == s.Length) { Console.WriteLine("NO"); return; } // state transitions // 0 takes to q1, 1 takes to q2 if (s[i] == '0') q1(s, i + 1); else q2(s, i + 1); } // Driver Code public static void Main() { string s = "010101"; // all state transitions are printed. // if string is accpetable, YES is printed. // else NO is printed Console.Write("State transitions are "); q0(s, 0); }} // This code is contributed by AnkitRai01 <script> // JavaScript Program to DFA that accepts string ending // with 01 or 10. // End position is checked using the string // length value. // q0 is the starting state. // q1 and q2 are intermediate states. // q3 and q4 are final states. function q1(s, i) { document.write("q1->"); if (i === s.length) { document.write("NO"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] === "0") q1(s, i + 1); else q3(s, i + 1); } function q2(s, i) { document.write("q2->"); if (i === s.length) { document.write("NO "); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] === "0") q4(s, i + 1); else q2(s, i + 1); } function q3(s, i) { document.write("q3->"); if (i === s.length) { document.write("YES"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] === "0") q4(s, i + 1); else q2(s, i + 1); } function q4(s, i) { document.write("q4->"); if (i === s.length) { document.write("YES"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] === "0") q1(s, i + 1); else q3(s, i + 1); } function q0(s, i) { document.write("q0->"); if (i === s.length) { document.write("NO"); return; } // state transitions // 0 takes to q1, 1 takes to q2 if (s[i] === "0") q1(s, i + 1); else q2(s, i + 1); } // Driver Code var s = "010101"; // all state transitions are printed. // if string is accpetable, YES is printed. // else NO is printed document.write("State transitions are "); q0(s, 0); </script> State transitions are q0->q1->q3->q4->q3->q4->q3->YES Complexity: O(n) where a string of length n requires traversal through n states.There can be more than one possible DFA for a problem statement. ankthon rdtank DFA Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if an URL is valid or not using Regular Expression Wildcard Pattern Matching Search a Word in a 2D Grid of characters Split the binary string into substrings with equal number of 0s and 1s Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1 Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2021" }, { "code": null, "e": 926, "s": 28, "text": "DFA or Deterministic Finite Automata is a finite state machine which accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.Problem: Given a string of ‘0’s and ‘1’s character by character, check for the last two characters to be “01” or “10” else reject the string. Also print the state diagram irrespective of acceptance or rejection. Since in DFA, there is no concept of memory, therefore we can only check for one character at a time, beginning with the 0th character. The input set for this problem is {0, 1}. For each character in the input set, each state of DFA redirects to another valid state.DFA Machine: For the above problem statement, we must first build a DFA machine. DFA machine is similar to a flowchart with various states and transitions. DFA machine corresponding to the above problem is shown below, Q3 and Q4 are the final states: " }, { "code": null, "e": 938, "s": 926, "text": "Examples: " }, { "code": null, "e": 1198, "s": 938, "text": "Input: 010101\nOutput:\nState transitions are q0->q1->q3->q4\n->q3->q4->q3->YES\n\nExplanation : 010101 ends with \"01\".\n\nInput: 0100\nOutput:\nState transitions are q0->q1->q3->q4->q1->NO\nExplanation : 0100 ends with \"00\", \nwhich is not equal to any of \"01\" or \"10\"." }, { "code": null, "e": 1211, "s": 1198, "text": "Algorithm: " }, { "code": null, "e": 1582, "s": 1211, "text": "Define the minimum number of states required to make the state diagram. Use functions to define various states.List all the valid transitions. Each state must have a transition for every valid symbol.Define the final states by applying the base condition.Define all the state transitions using state function calls.Define a returning condition for the end of the string." }, { "code": null, "e": 1694, "s": 1582, "text": "Define the minimum number of states required to make the state diagram. Use functions to define various states." }, { "code": null, "e": 1784, "s": 1694, "text": "List all the valid transitions. Each state must have a transition for every valid symbol." }, { "code": null, "e": 1840, "s": 1784, "text": "Define the final states by applying the base condition." }, { "code": null, "e": 1901, "s": 1840, "text": "Define all the state transitions using state function calls." }, { "code": null, "e": 1957, "s": 1901, "text": "Define a returning condition for the end of the string." }, { "code": null, "e": 1986, "s": 1957, "text": "For the given DFA Machine: " }, { "code": null, "e": 2371, "s": 1986, "text": "Q0, Q1, Q2, Q3, Q4 are defined as the number of states.0 and 1 are valid symbols. Each state has transitions for 0 and 1.Q3 and Q4 are defined as the final states.Suppose at state Q0, if 0 comes, the function call is made to Q1. So, if 1 comes, the function call is made to Q2.If the program reaches the end of the string, the output is made according to the state, the program is at." }, { "code": null, "e": 2427, "s": 2371, "text": "Q0, Q1, Q2, Q3, Q4 are defined as the number of states." }, { "code": null, "e": 2494, "s": 2427, "text": "0 and 1 are valid symbols. Each state has transitions for 0 and 1." }, { "code": null, "e": 2537, "s": 2494, "text": "Q3 and Q4 are defined as the final states." }, { "code": null, "e": 2652, "s": 2537, "text": "Suppose at state Q0, if 0 comes, the function call is made to Q1. So, if 1 comes, the function call is made to Q2." }, { "code": null, "e": 2760, "s": 2652, "text": "If the program reaches the end of the string, the output is made according to the state, the program is at." }, { "code": null, "e": 2778, "s": 2760, "text": "Implementation: " }, { "code": null, "e": 2782, "s": 2778, "text": "C++" }, { "code": null, "e": 2787, "s": 2782, "text": "Java" }, { "code": null, "e": 2795, "s": 2787, "text": "Python3" }, { "code": null, "e": 2798, "s": 2795, "text": "C#" }, { "code": null, "e": 2809, "s": 2798, "text": "Javascript" }, { "code": "// CPP Program to DFA that accepts string ending// with 01 or 10. #include <bits/stdc++.h>using namespace std; // Various states of DFA machine are defined// using functions.void q1(string, int);void q2(string, int);void q3(string, int);void q4(string, int); // End position is checked using the string// length value.// q0 is the starting state.// q1 and q2 are intermediate states.// q3 and q4 are final states.void q1(string s, int i){ cout << \"q1->\"; if (i == s.length()) { cout << \"NO \\n\"; return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] == '0') q1(s, i + 1); else q3(s, i + 1);} void q2(string s, int i){ cout << \"q2->\"; if (i == s.length()) { cout << \"NO \\n\"; return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] == '0') q4(s, i + 1); else q2(s, i + 1);} void q3(string s, int i){ cout << \"q3->\"; if (i == s.length()) { cout << \"YES \\n\"; return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] == '0') q4(s, i + 1); else q2(s, i + 1);} void q4(string s, int i){ cout << \"q4->\"; if (i == s.length()) { cout << \"YES \\n\"; return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] == '0') q1(s, i + 1); else q3(s, i + 1);} void q0(string s, int i){ cout << \"q0->\"; if (i == s.length()) { cout << \"NO \\n\"; return; } // state transitions // 0 takes to q1, 1 takes to q2 if (s[i] == '0') q1(s, i + 1); else q2(s, i + 1);} // Driver Codeint main(){ string s = \"010101\"; // all state transitions are printed. // if string is accpetable, YES is printed. // else NO is printed cout << \"State transitions are \"; q0(s, 0);}", "e": 4669, "s": 2809, "text": null }, { "code": "// Java Program to DFA that accepts string ending// with 01 or 10.class GFG{ // End position is checked using the string // length value. // q0 is the starting state. // q1 and q2 are intermediate states. // q3 and q4 are final states. static void q1(String s, int i) { System.out.print(\"q1->\"); if (i == s.length()) { System.out.println(\"NO\"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s.charAt(i) == '0') q1(s, i + 1); else q3(s, i + 1); } static void q2(String s, int i) { System.out.print(\"q2->\"); if (i == s.length()) { System.out.println(\"NO \"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s.charAt(i) == '0') q4(s, i + 1); else q2(s, i + 1); } static void q3(String s, int i) { System.out.print(\"q3->\"); if (i == s.length()) { System.out.println(\"YES\"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s.charAt(i) == '0') q4(s, i + 1); else q2(s, i + 1); } static void q4(String s, int i) { System.out.print(\"q4->\"); if (i == s.length()) { System.out.println(\"YES\"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s.charAt(i) == '0') q1(s, i + 1); else q3(s, i + 1); } static void q0(String s, int i) { System.out.print(\"q0->\"); if (i == s.length()) { System.out.println(\"NO\"); return; } // state transitions // 0 takes to q1, 1 takes to q2 if (s.charAt(i) == '0') q1(s, i + 1); else q2(s, i + 1); } // Driver Code public static void main (String[] args) { String s = \"010101\"; // all state transitions are printed. // if string is accpetable, YES is printed. // else NO is printed System.out.print(\"State transitions are \"); q0(s, 0); }} // This code is contributed by AnkitRai01", "e": 7022, "s": 4669, "text": null }, { "code": "# Python3 Program to DFA that accepts string ending# with 01 or 10. # End position is checked using the string# length value.# q0 is the starting state.# q1 and q2 are intermediate states.# q3 and q4 are final states.def q1(s, i) : print(\"q1->\", end=\"\"); if (i == len(s)) : print(\"NO\"); return; # state transitions # 0 takes to q1, 1 takes to q3 if (s[i] == '0') : q1(s, i + 1); else : q3(s, i + 1); def q2(s, i) : print(\"q2->\", end = \"\"); if (i == len(s)) : print(\"NO\"); return; # state transitions # 0 takes to q4, 1 takes to q2 if (s[i] == '0') : q4(s, i + 1); else : q2(s, i + 1); def q3(s, i) : print(\"q3->\", end = \"\"); if (i == len(s)) : print(\"YES\"); return; # state transitions # 0 takes to q4, 1 takes to q2 if (s[i] == '0') : q4(s, i + 1); else : q2(s, i + 1); def q4(s, i) : print(\"q4->\", end = \"\"); if (i == len(s)) : print(\"YES\"); return; # state transitions # 0 takes to q1, 1 takes to q3 if (s[i] == '0') : q1(s, i + 1); else : q3(s, i + 1); def q0( s, i) : print(\"q0->\", end = \"\"); if (i == len(s)) : print(\"NO\"); return; # state transitions # 0 takes to q1, 1 takes to q2 if (s[i] == '0') : q1(s, i + 1); else : q2(s, i + 1); # Driver Codeif __name__ == \"__main__\" : s = \"010101\"; # all state transitions are printed. # if string is accpetable, YES is printed. # else NO is printed print(\"State transitions are\", end = \" \"); q0(s, 0); # This code is contributed by AnkitRai01", "e": 8683, "s": 7022, "text": null }, { "code": "// C# Program to DFA that accepts string ending// with 01 or 10.using System; class GFG{ // End position is checked using the string // length value. // q0 is the starting state. // q1 and q2 are intermediate states. // q3 and q4 are final states. static void q1(string s, int i) { Console.Write(\"q1->\"); if (i == s.Length ) { Console.WriteLine(\"NO\"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] == '0') q1(s, i + 1); else q3(s, i + 1); } static void q2(string s, int i) { Console.Write(\"q2->\"); if (i == s.Length) { Console.WriteLine(\"NO \"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] == '0') q4(s, i + 1); else q2(s, i + 1); } static void q3(string s, int i) { Console.Write(\"q3->\"); if (i == s.Length) { Console.WriteLine(\"YES\"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] == '0') q4(s, i + 1); else q2(s, i + 1); } static void q4(string s, int i) { Console.Write(\"q4->\"); if (i == s.Length) { Console.WriteLine(\"YES\"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] == '0') q1(s, i + 1); else q3(s, i + 1); } static void q0(string s, int i) { Console.Write(\"q0->\"); if (i == s.Length) { Console.WriteLine(\"NO\"); return; } // state transitions // 0 takes to q1, 1 takes to q2 if (s[i] == '0') q1(s, i + 1); else q2(s, i + 1); } // Driver Code public static void Main() { string s = \"010101\"; // all state transitions are printed. // if string is accpetable, YES is printed. // else NO is printed Console.Write(\"State transitions are \"); q0(s, 0); }} // This code is contributed by AnkitRai01", "e": 10967, "s": 8683, "text": null }, { "code": "<script> // JavaScript Program to DFA that accepts string ending // with 01 or 10. // End position is checked using the string // length value. // q0 is the starting state. // q1 and q2 are intermediate states. // q3 and q4 are final states. function q1(s, i) { document.write(\"q1->\"); if (i === s.length) { document.write(\"NO\"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] === \"0\") q1(s, i + 1); else q3(s, i + 1); } function q2(s, i) { document.write(\"q2->\"); if (i === s.length) { document.write(\"NO \"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] === \"0\") q4(s, i + 1); else q2(s, i + 1); } function q3(s, i) { document.write(\"q3->\"); if (i === s.length) { document.write(\"YES\"); return; } // state transitions // 0 takes to q4, 1 takes to q2 if (s[i] === \"0\") q4(s, i + 1); else q2(s, i + 1); } function q4(s, i) { document.write(\"q4->\"); if (i === s.length) { document.write(\"YES\"); return; } // state transitions // 0 takes to q1, 1 takes to q3 if (s[i] === \"0\") q1(s, i + 1); else q3(s, i + 1); } function q0(s, i) { document.write(\"q0->\"); if (i === s.length) { document.write(\"NO\"); return; } // state transitions // 0 takes to q1, 1 takes to q2 if (s[i] === \"0\") q1(s, i + 1); else q2(s, i + 1); } // Driver Code var s = \"010101\"; // all state transitions are printed. // if string is accpetable, YES is printed. // else NO is printed document.write(\"State transitions are \"); q0(s, 0); </script>", "e": 12899, "s": 10967, "text": null }, { "code": null, "e": 12953, "s": 12899, "text": "State transitions are q0->q1->q3->q4->q3->q4->q3->YES" }, { "code": null, "e": 13101, "s": 12955, "text": "Complexity: O(n) where a string of length n requires traversal through n states.There can be more than one possible DFA for a problem statement. " }, { "code": null, "e": 13109, "s": 13101, "text": "ankthon" }, { "code": null, "e": 13116, "s": 13109, "text": "rdtank" }, { "code": null, "e": 13120, "s": 13116, "text": "DFA" }, { "code": null, "e": 13138, "s": 13120, "text": "Pattern Searching" }, { "code": null, "e": 13146, "s": 13138, "text": "Strings" }, { "code": null, "e": 13154, "s": 13146, "text": "Strings" }, { "code": null, "e": 13172, "s": 13154, "text": "Pattern Searching" }, { "code": null, "e": 13270, "s": 13172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13327, "s": 13270, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 13353, "s": 13327, "text": "Wildcard Pattern Matching" }, { "code": null, "e": 13394, "s": 13353, "text": "Search a Word in a 2D Grid of characters" }, { "code": null, "e": 13465, "s": 13394, "text": "Split the binary string into substrings with equal number of 0s and 1s" }, { "code": null, "e": 13539, "s": 13465, "text": "Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1" }, { "code": null, "e": 13585, "s": 13539, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 13610, "s": 13585, "text": "Reverse a string in Java" }, { "code": null, "e": 13670, "s": 13610, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 13685, "s": 13670, "text": "C++ Data Types" } ]
Check whether the given character is in upper case, lower case or non alphabetic character
09 Jun, 2022 Given a character, the task is to check whether the given character is in upper case, lower case, or non-alphabetic character Examples: Input: ch = 'A' Output: A is an UpperCase character Input: ch = 'a' Output: a is an LowerCase character Input: ch = '0' Output: 0 is not an aplhabetic character Approach: The key to solving this problem lies in the ASCII value of a character. It is the simplest way to find out about a character. This problem is solved with the help of the following detail: Capital letter Alphabets (A-Z) lie in the range 65-91 of the ASCII value Small letter Alphabets (a-z) lie in the range 97-122 of the ASCII value Any other ASCII value is a non-alphabetic character. C++ C Java Python3 C# PHP Javascript // C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; void check(char ch){ if (ch >= 'A' && ch <= 'Z') cout<< ch << " is an UpperCase character\n"; else if (ch >= 'a' && ch <= 'z') cout<< ch << " is an LowerCase character\n"; else cout<< ch << " is not an aplhabetic character\n"; } // Driver Codeint main(){ char ch; // Get the character ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); return 0;} // This code is contributed by Code_Mech // C implementation of the above approach#include <stdio.h> void check(char ch){ if (ch >= 'A' && ch <= 'Z') printf("\n%c is an UpperCase character", ch); else if (ch >= 'a' && ch <= 'z') printf("\n%c is an LowerCase character", ch); else printf("\n%c is not an aplhabetic character", ch);} // Driver Codeint main(){ char ch; // Get the character ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); return 0;} // Java implementation of the above approach class GFG{ static void check(char ch) { if (ch >= 'A' && ch <= 'Z') System.out.println("\n" + ch + " is an UpperCase character"); else if (ch >= 'a' && ch <= 'z') System.out.println("\n" + ch + " is an LowerCase character" ); else System.out.println("\n" + ch + " is not an aplhabetic character" ); } // Driver Code public static void main(String []args) { char ch; // Get the character ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); }} // This code is contributed by Ryuga # Python3 implementation of the above approach def check(ch): if (ch >= 'A' and ch <= 'Z'): print(ch,"is an UpperCase character"); elif (ch >= 'a' and ch <= 'z'): print(ch,"is an LowerCase character"); else: print(ch,"is not an aplhabetic character"); # Driver Code # Get the characterch = 'A'; # Check the charactercheck(ch); # Get the characterch = 'a'; # Check the charactercheck(ch); # Get the characterch = '0'; # Check the charactercheck(ch); # This code is contributed by mits // C# implementation of the above approachusing System; class GFG{ static void check(char ch) { if (ch >= 'A' && ch <= 'Z') Console.WriteLine("\n" + ch + " is an UpperCase character"); else if (ch >= 'a' && ch <= 'z') Console.WriteLine("\n" + ch + " is an LowerCase character" ); else Console.WriteLine("\n" + ch + " is not an aplhabetic character" ); } // Driver Code public static void Main(String []args) { char ch; // Get the character ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); }} // This code is contributed by Rajput-JI <?php// PHP implementation of the above approach function check($ch){ if ($ch >= 'A' && $ch <= 'Z') print($ch . " is an UpperCase character\n"); else if ($ch >= 'a' && $ch <= 'z') print($ch . " is an LowerCase character\n"); else print($ch . " is not an aplhabetic " . "character\n");} // Driver Code // Get the character$ch = 'A'; // Check the charactercheck($ch); // Get the character$ch = 'a'; // Check the charactercheck($ch); // Get the character$ch = '0'; // Check the charactercheck($ch); // This code is contributed by mits?> <script> // JavaScript implementation of // the above approach function check(ch) { if (ch >= "A" && ch <= "Z") document.write(ch + " is an UpperCase character <br>"); else if (ch >= "a" && ch <= "z") document.write(ch + " is an LowerCase character <br>"); else document.write(ch + " is not an aplhabetic character <br>"); } // Driver Code var ch; // Get the character ch = "A"; // Check the character check(ch); // Get the character ch = "a"; // Check the character check(ch); // Get the character ch = "0"; // Check the character check(ch); </script> A is an UpperCase character a is an LowerCase character 0 is not an aplhabetic character Approach using C+++ STL: islower() – check whether a character is lowercase. isupper() – check whether a character is uppercase. Below is the implementation of the above approach. C++ // C++ code to check if a char is uppercase,// lowercase or not an aplhabetic character#include <bits/stdc++.h>using namespace std; void check(char ch){ if (isupper(ch)) cout << ch << " is an UpperCase character\n"; else if (islower(ch)) cout << ch << " is an LowerCase character\n"; else cout << ch << " is not an aplhabetic character\n";} // Driver Codeint main(){ char ch; ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); return 0; // This code is contributed by Shivesh Kumar Dwivedi} A is an UpperCase character a is an LowerCase character 0 is not an aplhabetic character Time Complexity: O(1)Auxiliary Space: O(1) ankthon Rajput-Ji Mithun Kumar Code_Mech rdtank cpdwivedi916 ASCII C Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 192, "s": 54, "text": "Given a character, the task is to check whether the given character is in upper case, lower case, or non-alphabetic character Examples: " }, { "code": null, "e": 355, "s": 192, "text": "Input: ch = 'A'\nOutput: A is an UpperCase character\n\nInput: ch = 'a'\nOutput: a is an LowerCase character\n\nInput: ch = '0'\nOutput: 0 is not an aplhabetic character" }, { "code": null, "e": 557, "s": 357, "text": "Approach: The key to solving this problem lies in the ASCII value of a character. It is the simplest way to find out about a character. This problem is solved with the help of the following detail: " }, { "code": null, "e": 630, "s": 557, "text": "Capital letter Alphabets (A-Z) lie in the range 65-91 of the ASCII value" }, { "code": null, "e": 702, "s": 630, "text": "Small letter Alphabets (a-z) lie in the range 97-122 of the ASCII value" }, { "code": null, "e": 755, "s": 702, "text": "Any other ASCII value is a non-alphabetic character." }, { "code": null, "e": 759, "s": 755, "text": "C++" }, { "code": null, "e": 761, "s": 759, "text": "C" }, { "code": null, "e": 766, "s": 761, "text": "Java" }, { "code": null, "e": 774, "s": 766, "text": "Python3" }, { "code": null, "e": 777, "s": 774, "text": "C#" }, { "code": null, "e": 781, "s": 777, "text": "PHP" }, { "code": null, "e": 792, "s": 781, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; void check(char ch){ if (ch >= 'A' && ch <= 'Z') cout<< ch << \" is an UpperCase character\\n\"; else if (ch >= 'a' && ch <= 'z') cout<< ch << \" is an LowerCase character\\n\"; else cout<< ch << \" is not an aplhabetic character\\n\"; } // Driver Codeint main(){ char ch; // Get the character ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); return 0;} // This code is contributed by Code_Mech", "e": 1493, "s": 792, "text": null }, { "code": "// C implementation of the above approach#include <stdio.h> void check(char ch){ if (ch >= 'A' && ch <= 'Z') printf(\"\\n%c is an UpperCase character\", ch); else if (ch >= 'a' && ch <= 'z') printf(\"\\n%c is an LowerCase character\", ch); else printf(\"\\n%c is not an aplhabetic character\", ch);} // Driver Codeint main(){ char ch; // Get the character ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); return 0;}", "e": 2149, "s": 1493, "text": null }, { "code": "// Java implementation of the above approach class GFG{ static void check(char ch) { if (ch >= 'A' && ch <= 'Z') System.out.println(\"\\n\" + ch + \" is an UpperCase character\"); else if (ch >= 'a' && ch <= 'z') System.out.println(\"\\n\" + ch + \" is an LowerCase character\" ); else System.out.println(\"\\n\" + ch + \" is not an aplhabetic character\" ); } // Driver Code public static void main(String []args) { char ch; // Get the character ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); }} // This code is contributed by Ryuga", "e": 3070, "s": 2149, "text": null }, { "code": "# Python3 implementation of the above approach def check(ch): if (ch >= 'A' and ch <= 'Z'): print(ch,\"is an UpperCase character\"); elif (ch >= 'a' and ch <= 'z'): print(ch,\"is an LowerCase character\"); else: print(ch,\"is not an aplhabetic character\"); # Driver Code # Get the characterch = 'A'; # Check the charactercheck(ch); # Get the characterch = 'a'; # Check the charactercheck(ch); # Get the characterch = '0'; # Check the charactercheck(ch); # This code is contributed by mits", "e": 3586, "s": 3070, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ static void check(char ch) { if (ch >= 'A' && ch <= 'Z') Console.WriteLine(\"\\n\" + ch + \" is an UpperCase character\"); else if (ch >= 'a' && ch <= 'z') Console.WriteLine(\"\\n\" + ch + \" is an LowerCase character\" ); else Console.WriteLine(\"\\n\" + ch + \" is not an aplhabetic character\" ); } // Driver Code public static void Main(String []args) { char ch; // Get the character ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); }} // This code is contributed by Rajput-JI", "e": 4499, "s": 3586, "text": null }, { "code": "<?php// PHP implementation of the above approach function check($ch){ if ($ch >= 'A' && $ch <= 'Z') print($ch . \" is an UpperCase character\\n\"); else if ($ch >= 'a' && $ch <= 'z') print($ch . \" is an LowerCase character\\n\"); else print($ch . \" is not an aplhabetic \" . \"character\\n\");} // Driver Code // Get the character$ch = 'A'; // Check the charactercheck($ch); // Get the character$ch = 'a'; // Check the charactercheck($ch); // Get the character$ch = '0'; // Check the charactercheck($ch); // This code is contributed by mits?>", "e": 5094, "s": 4499, "text": null }, { "code": "<script> // JavaScript implementation of // the above approach function check(ch) { if (ch >= \"A\" && ch <= \"Z\") document.write(ch + \" is an UpperCase character <br>\"); else if (ch >= \"a\" && ch <= \"z\") document.write(ch + \" is an LowerCase character <br>\"); else document.write(ch + \" is not an aplhabetic character <br>\"); } // Driver Code var ch; // Get the character ch = \"A\"; // Check the character check(ch); // Get the character ch = \"a\"; // Check the character check(ch); // Get the character ch = \"0\"; // Check the character check(ch); </script>", "e": 5851, "s": 5094, "text": null }, { "code": null, "e": 5941, "s": 5851, "text": "A is an UpperCase character\na is an LowerCase character\n0 is not an aplhabetic character\n" }, { "code": null, "e": 5966, "s": 5941, "text": "Approach using C+++ STL:" }, { "code": null, "e": 6018, "s": 5966, "text": "islower() – check whether a character is lowercase." }, { "code": null, "e": 6070, "s": 6018, "text": "isupper() – check whether a character is uppercase." }, { "code": null, "e": 6121, "s": 6070, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 6125, "s": 6121, "text": "C++" }, { "code": "// C++ code to check if a char is uppercase,// lowercase or not an aplhabetic character#include <bits/stdc++.h>using namespace std; void check(char ch){ if (isupper(ch)) cout << ch << \" is an UpperCase character\\n\"; else if (islower(ch)) cout << ch << \" is an LowerCase character\\n\"; else cout << ch << \" is not an aplhabetic character\\n\";} // Driver Codeint main(){ char ch; ch = 'A'; // Check the character check(ch); // Get the character ch = 'a'; // Check the character check(ch); // Get the character ch = '0'; // Check the character check(ch); return 0; // This code is contributed by Shivesh Kumar Dwivedi}", "e": 6819, "s": 6125, "text": null }, { "code": null, "e": 6908, "s": 6819, "text": "A is an UpperCase character\na is an LowerCase character\n0 is not an aplhabetic character" }, { "code": null, "e": 6951, "s": 6908, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 6959, "s": 6951, "text": "ankthon" }, { "code": null, "e": 6969, "s": 6959, "text": "Rajput-Ji" }, { "code": null, "e": 6982, "s": 6969, "text": "Mithun Kumar" }, { "code": null, "e": 6992, "s": 6982, "text": "Code_Mech" }, { "code": null, "e": 6999, "s": 6992, "text": "rdtank" }, { "code": null, "e": 7012, "s": 6999, "text": "cpdwivedi916" }, { "code": null, "e": 7018, "s": 7012, "text": "ASCII" }, { "code": null, "e": 7029, "s": 7018, "text": "C Programs" }, { "code": null, "e": 7048, "s": 7029, "text": "School Programming" } ]
Python Interview Questions
Dear readers, these Python Programming Language Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Python Programming Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer − Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages. Following are some of the salient features of python − It supports functional and structured programming methods as well as OOP. It supports functional and structured programming methods as well as OOP. It can be used as a scripting language or can be compiled to byte-code for building large applications. It can be used as a scripting language or can be compiled to byte-code for building large applications. It provides very high-level dynamic data types and supports dynamic type checking. It provides very high-level dynamic data types and supports dynamic type checking. It supports automatic garbage collection. It supports automatic garbage collection. It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. PYTHONPATH - It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer. PYTHONSTARTUP - It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH. PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it. PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy. Yes! Python is a case sensitive programming language. Python has five standard data types − Numbers Numbers String String List List Tuple Tuple Dictionary Dictionary It will print complete string. Output would be Hello World!. It will print first character of the string. Output would be H. It will print characters starting from 3rd to 5th. Output would be llo. It will print characters starting from 3rd character. Output would be llo World!. It will print string two times. Output would be Hello World!Hello World!. It will print concatenated string. Output would be Hello World!TEST. It will print complete list. Output would be ['abcd', 786, 2.23, 'john', 70.200000000000003]. It will print first element of the list. Output would be abcd. It will print elements starting from 2nd till 3rd. Output would be [786, 2.23]. It will print elements starting from 3rd element. Output would be [2.23, 'john', 70.200000000000003]. It will print list two times. Output would be [123, 'john', 123, 'john']. It will print concatenated lists. Output would be ['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. It will print complete tuple. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003). It will print first element of the tuple. Output would be abcd. It will print elements starting from 2nd till 3rd. Output would be (786, 2.23). It will print elements starting from 3rd element. Output would be (2.23, 'john', 70.200000000000003). It will print tuple two times. Output would be (123, 'john', 123, 'john'). It will print concatenated tuples. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john'). Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} Using dictionary.keys() function, we can get all the keys from the dictionary object. print dict.keys() # Prints all the keys Using dictionary.values() function, we can get all the values from the dictionary object. print dict.values() # Prints all the values int(x [,base]) - Converts x to an integer. base specifies the base if x is a string. long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string. float(x) − Converts x to a floating-point number. str(x) − Converts object x to a string representation. repr(x) − Converts object x to an expression string. eval(str) − Evaluates a string and returns an object. tuple(s) − Converts s to a tuple. list(s) − Converts s to a list. set(s) − Converts s to a set. dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples. frozenset(s) − Converts s to a frozen set. chr(x) − Converts an integer to a character. unichr(x) − Converts an integer to a Unicode character. ord(x) − Converts a single character to its integer value. hex(x) − Converts an integer to a hexadecimal string. oct(x) − Converts an integer to an octal string. ** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20. // Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed. is − Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y). not in − Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y. break statement − Terminates the loop statement and transfers execution to the statement immediately following the loop. continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. pass statement − The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. choice(seq) − Returns a random item from a list, tuple, or string. randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop, step). random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1. seed([x]) − Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None. shuffle(lst) − Randomizes the items of a list in place. Returns None. capitalize() − Capitalizes first letter of string. isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. isdigit() − Returns true if string contains only digits and false otherwise. islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise. isspace() − Returns true if string contains only whitespace characters and false otherwise. istitle() − Returns true if string is properly "titlecased" and false otherwise. isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise. join(seq) − Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string. len(string) − Returns the length of the string. ljust(width[, fillchar]) − Returns a space-padded string with the original string left-justified to a total of width columns. lower() − Converts all uppercase letters in string to lowercase. lstrip() − Removes all leading whitespace in string. max(str) − Returns the max alphabetical character from the string str. min(str) − Returns the min alphabetical character from the string str. replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given. strip([chars]) − Performs both lstrip() and rstrip() on string. swapcase() − Inverts case for all letters in string. title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase. upper() − Converts all lowercase letters in string to uppercase. isdecimal() − Returns true if a unicode string contains only decimal characters and false otherwise. To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. 3. [1, 2, 3, 4, 5, 6] ['Hi!', 'Hi!', 'Hi!', 'Hi!'] True 1 2 3 3, Offsets start at zero. 1, Negative: count from the right. 2, 3, Slicing fetches sections. cmp(list1, list2) − Compares elements of both lists. len(list) − Gives the total length of the list. max(list) − Returns item from the list with max value. min(list) − Returns item from the list with min value. list.index(obj) − Returns the lowest index in list that obj appears. list.insert(index, obj) − Inserts object obj into list at offset index. list.pop(obj=list[-1]) − Removes and returns last object or obj from list. list.remove(obj) − Removes object obj from list. list.reverse() − Reverses objects of list in place. list.sort([func]) − Sorts objects of list, use compare func if given. ‘lambda’ is a keyword in python which creates an anonymous function. Lambda does not contain block of statements. It does not contain return statements. Stub. Stack. Yes. No There are some modules and functions in python that can only run on certain platforms. Yes Yes it has a complier which works automatically so we don’t notice the compiler of python. Django (Web framework of Python). 2. Micro Frame work such as Flask and Bottle. 3. Plone and Django CMS for advanced content Management. Table below explains the difference between Python version 2 and Python version 3. Print command can be used without parentheses. Python 3 needs parentheses to print any string. It will raise error without parentheses. ASCII str() types and separate Unicode() but there is no byte type code in Python 2. Unicode (utf-8) and it has two byte classes − Byte Bytearray S. Python 2 accepts both new and old notations of syntax. Python 3 raises a SyntaxError in turn when we don’t enclose the exception argument in parentheses. It does not raise any error. It raises ‘TypeError’ as warning if we try to compare unorderable types. Jython (Jython is successor of Jpython.) No Yes. No. OS. A block begins when the line is intended by 4 spaces. def check(a,b): if(len(a)!=len(b)): return False else: if(sorted(list(a)) == sorted(list(b))): return True else: return False Scikit-learn python Library used for Machine learning Pass indicates that nothing is to be done i.e. it signifies a no operation. Pylint and pychecker. Sample list − (100, 200, 300, 400, 0, 500) Expected output − 1500 Program for sum of all the numbers in list is − def sum(numbers): total = 0 for num in numbers: total+=num print(''Sum of the numbers: '', total) sum((100, 200, 300, 400, 0, 500)) We define a function ‘sum’ with numbers as parameter. The in for loop we store the sum of all the values of list. Program to reverse a string in given below − def string_reverse(str1): rev_str = ' ' index = len(str1) #defining index as length of string. while(index>0): rev_str = rev_str + str1[index-1] index = index-1 return(rev_str) print(string_reverse('1tniop')) First we declare a variable to store the reverse string. Then using while loop and indexing of string (index is calculated by string length) we reverse the string. While loop starts when index is greater than zero. Index is reduced to value 1 each time. When index reaches zero we obtain the reverse of string. Program is − def test_range(num): if num in range(0, 101): print(''%s is in range''%str(num)) else: print(''%s is not in range''%str(num)) Output − test_range(101) 101 is not in the range To test any number in a particular range we make use of the method ‘if..in’ and else condition. Test on String: ''Tutorials POINT'' Program is − def string_test(s): a = { ''Lower_Case'':0 , ''Upper_Case'':0} #intiail count of lower and upper for ch in s: #for loop if(ch.islower()): #if-elif-else condition a[''Lower_Case''] = a[''Lower_Case''] + 1 elif(ch.isupper()): a[''Upper_Case''] = a [''Upper_Case''] + 1 else: pass print(''String in testing is: '',s) #printing the statements. print(''Number of Lower Case characters in String: '',a[''Lower_Case'']) print(''Number of Upper Case characters in String: '',a[''Upper_Case'']) Output − string_test(''Tutorials POINT'') String in testing is: Tutorials POINT Number of Lower Case characters in String: 8 Number of Upper Case characters in String: 6 We make use of the methods .islower() and .isupper(). We initialise the count for lower and upper. Using if and else condition we calculate total number of lower and upper case characters. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
[ { "code": null, "e": 2857, "s": 2378, "text": "Dear readers, these Python Programming Language Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Python Programming Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −" }, { "code": null, "e": 3132, "s": 2857, "text": " Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages." }, { "code": null, "e": 3188, "s": 3132, "text": " Following are some of the salient features of python −" }, { "code": null, "e": 3262, "s": 3188, "text": "It supports functional and structured programming methods as well as OOP." }, { "code": null, "e": 3336, "s": 3262, "text": "It supports functional and structured programming methods as well as OOP." }, { "code": null, "e": 3440, "s": 3336, "text": "It can be used as a scripting language or can be compiled to byte-code for building large applications." }, { "code": null, "e": 3544, "s": 3440, "text": "It can be used as a scripting language or can be compiled to byte-code for building large applications." }, { "code": null, "e": 3627, "s": 3544, "text": "It provides very high-level dynamic data types and supports dynamic type checking." }, { "code": null, "e": 3710, "s": 3627, "text": "It provides very high-level dynamic data types and supports dynamic type checking." }, { "code": null, "e": 3752, "s": 3710, "text": "It supports automatic garbage collection." }, { "code": null, "e": 3794, "s": 3752, "text": "It supports automatic garbage collection." }, { "code": null, "e": 3866, "s": 3794, "text": "It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java." }, { "code": null, "e": 3938, "s": 3866, "text": "It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java." }, { "code": null, "e": 4245, "s": 3938, "text": " PYTHONPATH - It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer." }, { "code": null, "e": 4496, "s": 4245, "text": " PYTHONSTARTUP - It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH." }, { "code": null, "e": 4666, "s": 4496, "text": " PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it." }, { "code": null, "e": 4832, "s": 4666, "text": " PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy." }, { "code": null, "e": 4887, "s": 4832, "text": " Yes! Python is a case sensitive programming language." }, { "code": null, "e": 4926, "s": 4887, "text": " Python has five standard data types −" }, { "code": null, "e": 4934, "s": 4926, "text": "Numbers" }, { "code": null, "e": 4942, "s": 4934, "text": "Numbers" }, { "code": null, "e": 4949, "s": 4942, "text": "String" }, { "code": null, "e": 4956, "s": 4949, "text": "String" }, { "code": null, "e": 4961, "s": 4956, "text": "List" }, { "code": null, "e": 4966, "s": 4961, "text": "List" }, { "code": null, "e": 4972, "s": 4966, "text": "Tuple" }, { "code": null, "e": 4978, "s": 4972, "text": "Tuple" }, { "code": null, "e": 4989, "s": 4978, "text": "Dictionary" }, { "code": null, "e": 5000, "s": 4989, "text": "Dictionary" }, { "code": null, "e": 5062, "s": 5000, "text": " It will print complete string. Output would be Hello World!." }, { "code": null, "e": 5127, "s": 5062, "text": " It will print first character of the string. Output would be H." }, { "code": null, "e": 5200, "s": 5127, "text": " It will print characters starting from 3rd to 5th. Output would be llo." }, { "code": null, "e": 5283, "s": 5200, "text": " It will print characters starting from 3rd character. Output would be llo World!." }, { "code": null, "e": 5358, "s": 5283, "text": " It will print string two times. Output would be Hello World!Hello World!." }, { "code": null, "e": 5428, "s": 5358, "text": " It will print concatenated string. Output would be Hello World!TEST." }, { "code": null, "e": 5523, "s": 5428, "text": " It will print complete list. Output would be ['abcd', 786, 2.23, 'john', 70.200000000000003]." }, { "code": null, "e": 5587, "s": 5523, "text": " It will print first element of the list. Output would be abcd." }, { "code": null, "e": 5668, "s": 5587, "text": " It will print elements starting from 2nd till 3rd. Output would be [786, 2.23]." }, { "code": null, "e": 5771, "s": 5668, "text": " It will print elements starting from 3rd element. Output would be [2.23, 'john', 70.200000000000003]." }, { "code": null, "e": 5846, "s": 5771, "text": " It will print list two times. Output would be [123, 'john', 123, 'john']." }, { "code": null, "e": 5943, "s": 5846, "text": "It will print concatenated lists. Output would be ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']" }, { "code": null, "e": 6134, "s": 5943, "text": " A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses." }, { "code": null, "e": 6387, "s": 6134, "text": " The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists." }, { "code": null, "e": 6483, "s": 6387, "text": " It will print complete tuple. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003)." }, { "code": null, "e": 6548, "s": 6483, "text": " It will print first element of the tuple. Output would be abcd." }, { "code": null, "e": 6629, "s": 6548, "text": " It will print elements starting from 2nd till 3rd. Output would be (786, 2.23)." }, { "code": null, "e": 6732, "s": 6629, "text": " It will print elements starting from 3rd element. Output would be (2.23, 'john', 70.200000000000003)." }, { "code": null, "e": 6808, "s": 6732, "text": " It will print tuple two times. Output would be (123, 'john', 123, 'john')." }, { "code": null, "e": 6922, "s": 6808, "text": " It will print concatenated tuples. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')." }, { "code": null, "e": 7211, "s": 6922, "text": " Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object." }, { "code": null, "e": 7326, "s": 7211, "text": " Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([])." }, { "code": null, "e": 7449, "s": 7326, "text": "dict = {}\ndict['one'] = \"This is one\"\ndict[2] = \"This is two\"\ntinydict = {'name': 'john','code':6734, 'dept': 'sales'}" }, { "code": null, "e": 7536, "s": 7449, "text": " Using dictionary.keys() function, we can get all the keys from the dictionary object." }, { "code": null, "e": 7578, "s": 7536, "text": "print dict.keys() # Prints all the keys" }, { "code": null, "e": 7669, "s": 7578, "text": " Using dictionary.values() function, we can get all the values from the dictionary object." }, { "code": null, "e": 7715, "s": 7669, "text": "print dict.values() # Prints all the values" }, { "code": null, "e": 7801, "s": 7715, "text": " int(x [,base]) - Converts x to an integer. base specifies the base if x is a string." }, { "code": null, "e": 7893, "s": 7801, "text": " long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string." }, { "code": null, "e": 7944, "s": 7893, "text": " float(x) − Converts x to a floating-point number." }, { "code": null, "e": 8000, "s": 7944, "text": " str(x) − Converts object x to a string representation." }, { "code": null, "e": 8054, "s": 8000, "text": " repr(x) − Converts object x to an expression string." }, { "code": null, "e": 8109, "s": 8054, "text": " eval(str) − Evaluates a string and returns an object." }, { "code": null, "e": 8144, "s": 8109, "text": " tuple(s) − Converts s to a tuple." }, { "code": null, "e": 8177, "s": 8144, "text": " list(s) − Converts s to a list." }, { "code": null, "e": 8208, "s": 8177, "text": " set(s) − Converts s to a set." }, { "code": null, "e": 8285, "s": 8208, "text": " dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples." }, { "code": null, "e": 8329, "s": 8285, "text": " frozenset(s) − Converts s to a frozen set." }, { "code": null, "e": 8375, "s": 8329, "text": " chr(x) − Converts an integer to a character." }, { "code": null, "e": 8432, "s": 8375, "text": " unichr(x) − Converts an integer to a Unicode character." }, { "code": null, "e": 8492, "s": 8432, "text": " ord(x) − Converts a single character to its integer value." }, { "code": null, "e": 8547, "s": 8492, "text": " hex(x) − Converts an integer to a hexadecimal string." }, { "code": null, "e": 8597, "s": 8547, "text": " oct(x) − Converts an integer to an octal string." }, { "code": null, "e": 8715, "s": 8597, "text": " ** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20." }, { "code": null, "e": 8852, "s": 8715, "text": " // Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed." }, { "code": null, "e": 9022, "s": 8852, "text": " is − Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y)." }, { "code": null, "e": 9204, "s": 9022, "text": " not in − Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y." }, { "code": null, "e": 9326, "s": 9204, "text": " break statement − Terminates the loop statement and transfers execution to the statement immediately following the loop." }, { "code": null, "e": 9457, "s": 9326, "text": " continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating." }, { "code": null, "e": 9607, "s": 9457, "text": " pass statement − The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute." }, { "code": null, "e": 9675, "s": 9607, "text": " choice(seq) − Returns a random item from a list, tuple, or string." }, { "code": null, "e": 9779, "s": 9675, "text": " randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop, step)." }, { "code": null, "e": 9878, "s": 9779, "text": " random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1." }, { "code": null, "e": 10040, "s": 9878, "text": " seed([x]) − Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None." }, { "code": null, "e": 10111, "s": 10040, "text": " shuffle(lst) − Randomizes the items of a list in place. Returns None." }, { "code": null, "e": 10163, "s": 10111, "text": " capitalize() − Capitalizes first letter of string." }, { "code": null, "e": 10281, "s": 10163, "text": " isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise." }, { "code": null, "e": 10359, "s": 10281, "text": " isdigit() − Returns true if string contains only digits and false otherwise." }, { "code": null, "e": 10489, "s": 10359, "text": " islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise." }, { "code": null, "e": 10591, "s": 10489, "text": " isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise." }, { "code": null, "e": 10684, "s": 10591, "text": " isspace() − Returns true if string contains only whitespace characters and false otherwise." }, { "code": null, "e": 10766, "s": 10684, "text": " istitle() − Returns true if string is properly \"titlecased\" and false otherwise." }, { "code": null, "e": 10898, "s": 10766, "text": " isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise." }, { "code": null, "e": 11026, "s": 10898, "text": " join(seq) − Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string." }, { "code": null, "e": 11075, "s": 11026, "text": " len(string) − Returns the length of the string." }, { "code": null, "e": 11202, "s": 11075, "text": " ljust(width[, fillchar]) − Returns a space-padded string with the original string left-justified to a total of width columns." }, { "code": null, "e": 11268, "s": 11202, "text": " lower() − Converts all uppercase letters in string to lowercase." }, { "code": null, "e": 11322, "s": 11268, "text": " lstrip() − Removes all leading whitespace in string." }, { "code": null, "e": 11394, "s": 11322, "text": " max(str) − Returns the max alphabetical character from the string str." }, { "code": null, "e": 11466, "s": 11394, "text": " min(str) − Returns the min alphabetical character from the string str." }, { "code": null, "e": 11587, "s": 11466, "text": " replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given." }, { "code": null, "e": 11652, "s": 11587, "text": " strip([chars]) − Performs both lstrip() and rstrip() on string." }, { "code": null, "e": 11706, "s": 11652, "text": " swapcase() − Inverts case for all letters in string." }, { "code": null, "e": 11825, "s": 11706, "text": " title() − Returns \"titlecased\" version of string, that is, all words begin with uppercase and the rest are lowercase." }, { "code": null, "e": 11891, "s": 11825, "text": " upper() − Converts all lowercase letters in string to uppercase." }, { "code": null, "e": 11993, "s": 11891, "text": " isdecimal() − Returns true if a unicode string contains only decimal characters and false otherwise." }, { "code": null, "e": 12155, "s": 11993, "text": " To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. " }, { "code": null, "e": 12159, "s": 12155, "text": " 3." }, { "code": null, "e": 12179, "s": 12159, "text": " [1, 2, 3, 4, 5, 6]" }, { "code": null, "e": 12209, "s": 12179, "text": " ['Hi!', 'Hi!', 'Hi!', 'Hi!']" }, { "code": null, "e": 12215, "s": 12209, "text": " True" }, { "code": null, "e": 12222, "s": 12215, "text": "1\n2\n3\n" }, { "code": null, "e": 12249, "s": 12222, "text": " 3, Offsets start at zero." }, { "code": null, "e": 12285, "s": 12249, "text": " 1, Negative: count from the right." }, { "code": null, "e": 12318, "s": 12285, "text": " 2, 3, Slicing fetches sections." }, { "code": null, "e": 12372, "s": 12318, "text": " cmp(list1, list2) − Compares elements of both lists." }, { "code": null, "e": 12421, "s": 12372, "text": " len(list) − Gives the total length of the list." }, { "code": null, "e": 12477, "s": 12421, "text": " max(list) − Returns item from the list with max value." }, { "code": null, "e": 12533, "s": 12477, "text": " min(list) − Returns item from the list with min value." }, { "code": null, "e": 12603, "s": 12533, "text": " list.index(obj) − Returns the lowest index in list that obj appears." }, { "code": null, "e": 12676, "s": 12603, "text": " list.insert(index, obj) − Inserts object obj into list at offset index." }, { "code": null, "e": 12752, "s": 12676, "text": " list.pop(obj=list[-1]) − Removes and returns last object or obj from list." }, { "code": null, "e": 12802, "s": 12752, "text": " list.remove(obj) − Removes object obj from list." }, { "code": null, "e": 12855, "s": 12802, "text": " list.reverse() − Reverses objects of list in place." }, { "code": null, "e": 12926, "s": 12855, "text": " list.sort([func]) − Sorts objects of list, use compare func if given." }, { "code": null, "e": 13080, "s": 12926, "text": " ‘lambda’ is a keyword in python which creates an anonymous function. Lambda does not contain block of statements. It does not contain return statements." }, { "code": null, "e": 13087, "s": 13080, "text": " Stub." }, { "code": null, "e": 13095, "s": 13087, "text": " Stack." }, { "code": null, "e": 13101, "s": 13095, "text": " Yes." }, { "code": null, "e": 13105, "s": 13101, "text": " No" }, { "code": null, "e": 13192, "s": 13105, "text": "There are some modules and functions in python that can only run on certain platforms." }, { "code": null, "e": 13197, "s": 13192, "text": " Yes" }, { "code": null, "e": 13288, "s": 13197, "text": "Yes it has a complier which works automatically so we don’t notice the compiler of python." }, { "code": null, "e": 13323, "s": 13288, "text": " Django (Web framework of Python)." }, { "code": null, "e": 13369, "s": 13323, "text": "2. Micro Frame work such as Flask and Bottle." }, { "code": null, "e": 13426, "s": 13369, "text": "3. Plone and Django CMS for advanced content Management." }, { "code": null, "e": 13510, "s": 13426, "text": " Table below explains the difference between Python version 2 and Python version 3." }, { "code": null, "e": 13557, "s": 13510, "text": "Print command can be used without parentheses." }, { "code": null, "e": 13646, "s": 13557, "text": "Python 3 needs parentheses to print any string. It will raise error without parentheses." }, { "code": null, "e": 13731, "s": 13646, "text": "ASCII str() types and separate Unicode() but there is no byte type code in Python 2." }, { "code": null, "e": 13778, "s": 13731, "text": "Unicode (utf-8) and it has two byte classes −\n" }, { "code": null, "e": 13783, "s": 13778, "text": "Byte" }, { "code": null, "e": 13796, "s": 13783, "text": "Bytearray S." }, { "code": null, "e": 13851, "s": 13796, "text": "Python 2 accepts both new and old notations of syntax." }, { "code": null, "e": 13950, "s": 13851, "text": "Python 3 raises a SyntaxError in turn when we don’t enclose the exception argument in parentheses." }, { "code": null, "e": 13979, "s": 13950, "text": "It does not raise any error." }, { "code": null, "e": 14052, "s": 13979, "text": "It raises ‘TypeError’ as warning if we try to compare unorderable types." }, { "code": null, "e": 14060, "s": 14052, "text": " Jython" }, { "code": null, "e": 14094, "s": 14060, "text": "(Jython is successor of Jpython.)" }, { "code": null, "e": 14098, "s": 14094, "text": " No" }, { "code": null, "e": 14104, "s": 14098, "text": " Yes." }, { "code": null, "e": 14109, "s": 14104, "text": " No." }, { "code": null, "e": 14114, "s": 14109, "text": " OS." }, { "code": null, "e": 14169, "s": 14114, "text": " A block begins when the line is intended by 4 spaces." }, { "code": null, "e": 14331, "s": 14169, "text": "def check(a,b):\n if(len(a)!=len(b)):\n return False\n else:\n if(sorted(list(a)) == sorted(list(b))):\n return True\n else:\n return False" }, { "code": null, "e": 14386, "s": 14331, "text": " Scikit-learn python Library used for Machine learning" }, { "code": null, "e": 14463, "s": 14386, "text": " Pass indicates that nothing is to be done i.e. it signifies a no operation." }, { "code": null, "e": 14486, "s": 14463, "text": " Pylint and pychecker." }, { "code": null, "e": 14529, "s": 14486, "text": "Sample list − (100, 200, 300, 400, 0, 500)" }, { "code": null, "e": 14552, "s": 14529, "text": "Expected output − 1500" }, { "code": null, "e": 14601, "s": 14552, "text": " Program for sum of all the numbers in list is −" }, { "code": null, "e": 14748, "s": 14601, "text": "def sum(numbers):\n total = 0\n for num in numbers:\n total+=num\n print(''Sum of the numbers: '', total)\nsum((100, 200, 300, 400, 0, 500))" }, { "code": null, "e": 14862, "s": 14748, "text": "We define a function ‘sum’ with numbers as parameter. The in for loop we store the sum of all the values of list." }, { "code": null, "e": 14908, "s": 14862, "text": " Program to reverse a string in given below −" }, { "code": null, "e": 15128, "s": 14908, "text": "def string_reverse(str1):\n\nrev_str = ' '\nindex = len(str1) #defining index as length of string.\nwhile(index>0):\n rev_str = rev_str + str1[index-1]\n index = index-1\n return(rev_str)\n\nprint(string_reverse('1tniop'))" }, { "code": null, "e": 15439, "s": 15128, "text": "First we declare a variable to store the reverse string. Then using while loop and indexing of string (index is calculated by string length) we reverse the string. While loop starts when index is greater than zero. Index is reduced to value 1 each time. When index reaches zero we obtain the reverse of string." }, { "code": null, "e": 15453, "s": 15439, "text": " Program is −" }, { "code": null, "e": 15597, "s": 15453, "text": "def test_range(num):\n if num in range(0, 101):\n print(''%s is in range''%str(num))\n else:\n print(''%s is not in range''%str(num))" }, { "code": null, "e": 15606, "s": 15597, "text": "Output −" }, { "code": null, "e": 15622, "s": 15606, "text": "test_range(101)" }, { "code": null, "e": 15646, "s": 15622, "text": "101 is not in the range" }, { "code": null, "e": 15742, "s": 15646, "text": "To test any number in a particular range we make use of the method ‘if..in’ and else condition." }, { "code": null, "e": 15778, "s": 15742, "text": "Test on String: ''Tutorials POINT''" }, { "code": null, "e": 15792, "s": 15778, "text": " Program is −" }, { "code": null, "e": 16307, "s": 15792, "text": "def string_test(s):\n\na = { ''Lower_Case'':0 , ''Upper_Case'':0} #intiail count of lower and upper\nfor ch in s: #for loop\n if(ch.islower()): #if-elif-else condition\n a[''Lower_Case''] = a[''Lower_Case''] + 1\n elif(ch.isupper()):\n a[''Upper_Case''] = a [''Upper_Case''] + 1\n else:\n pass\n\nprint(''String in testing is: '',s) #printing the statements.\nprint(''Number of Lower Case characters in String: '',a[''Lower_Case''])\nprint(''Number of Upper Case characters in String: '',a[''Upper_Case''])" }, { "code": null, "e": 16316, "s": 16307, "text": "Output −" }, { "code": null, "e": 16349, "s": 16316, "text": "string_test(''Tutorials POINT'')" }, { "code": null, "e": 16387, "s": 16349, "text": "String in testing is: Tutorials POINT" }, { "code": null, "e": 16432, "s": 16387, "text": "Number of Lower Case characters in String: 8" }, { "code": null, "e": 16477, "s": 16432, "text": "Number of Upper Case characters in String: 6" }, { "code": null, "e": 16666, "s": 16477, "text": "We make use of the methods .islower() and .isupper(). We initialise the count for lower and upper. Using if and else condition we calculate total number of lower and upper case characters." }, { "code": null, "e": 16953, "s": 16666, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." } ]
Lodash _.hasIn() Method
09 Sep, 2020 The _.hasIn() method is used to check whether the path is a direct or inherited property of object or not. It returns true if path exists, else it returns false. Syntax: _.hasIn(object, path) Parameters: This method accepts two parameters as mentioned above and described below: object: This parameter holds the object to query. path: This parameter holds the path to check. The path will be array or string. Return Value: This method returns true if path exists, else false Example 1: Javascript // Requiring the lodash library const _ = require("lodash"); // Given objectvar object = _.create({ 'a': _.create({ 'b': 2 }) }); // Use of _.hasIn method console.log(_.hasIn(object, 'a')); console.log(_.hasIn(object, ['a'])); console.log(_.hasIn(object, ['b'])); Output: true true false Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Given objectvar object = _.create({ 'a': _.create({ 'b': 2 }) }); // Use of _.hasIn method console.log(_.hasIn(object, 'a.b')); console.log(_.hasIn(object, ['a','b'])); console.log(_.hasIn(object, ['a','b','c'])); Output: true true false JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises 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": 28, "s": 0, "text": "\n09 Sep, 2020" }, { "code": null, "e": 190, "s": 28, "text": "The _.hasIn() method is used to check whether the path is a direct or inherited property of object or not. It returns true if path exists, else it returns false." }, { "code": null, "e": 198, "s": 190, "text": "Syntax:" }, { "code": null, "e": 221, "s": 198, "text": "_.hasIn(object, path)\n" }, { "code": null, "e": 308, "s": 221, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 358, "s": 308, "text": "object: This parameter holds the object to query." }, { "code": null, "e": 438, "s": 358, "text": "path: This parameter holds the path to check. The path will be array or string." }, { "code": null, "e": 504, "s": 438, "text": "Return Value: This method returns true if path exists, else false" }, { "code": null, "e": 515, "s": 504, "text": "Example 1:" }, { "code": null, "e": 526, "s": 515, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Given objectvar object = _.create({ 'a': _.create({ 'b': 2 }) }); // Use of _.hasIn method console.log(_.hasIn(object, 'a')); console.log(_.hasIn(object, ['a'])); console.log(_.hasIn(object, ['b'])); ", "e": 797, "s": 526, "text": null }, { "code": null, "e": 805, "s": 797, "text": "Output:" }, { "code": null, "e": 822, "s": 805, "text": "true\ntrue\nfalse\n" }, { "code": null, "e": 835, "s": 822, "text": "Example 2: " }, { "code": null, "e": 846, "s": 835, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Given objectvar object = _.create({ 'a': _.create({ 'b': 2 }) }); // Use of _.hasIn method console.log(_.hasIn(object, 'a.b')); console.log(_.hasIn(object, ['a','b'])); console.log(_.hasIn(object, ['a','b','c'])); ", "e": 1131, "s": 846, "text": null }, { "code": null, "e": 1139, "s": 1131, "text": "Output:" }, { "code": null, "e": 1156, "s": 1139, "text": "true\ntrue\nfalse\n" }, { "code": null, "e": 1174, "s": 1156, "text": "JavaScript-Lodash" }, { "code": null, "e": 1185, "s": 1174, "text": "JavaScript" }, { "code": null, "e": 1202, "s": 1185, "text": "Web Technologies" }, { "code": null, "e": 1300, "s": 1202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1361, "s": 1300, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1401, "s": 1361, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1442, "s": 1401, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1484, "s": 1442, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1506, "s": 1484, "text": "JavaScript | Promises" }, { "code": null, "e": 1568, "s": 1506, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1601, "s": 1568, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1662, "s": 1601, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1712, "s": 1662, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Red Hat Interview Experience | Set 1 (For Internship)
30 Dec, 2014 I am doing my final year B.E CSE. I would like to thank geeksforgeeks. It helped a lot for cracking the interview. I applied online for the post of a Associate software Engineer Intern at Red hat, Bangalore. The first round was a written test round. We had nearly around 30 questions in aptitude as well as coding and a C program to write. Aptitude: The aptitude questions were moderate and it covered all most all of the topics. It is not necessary for you to remember any formula.Most of the problem involved solving it logically. If you know the concepts you can solve. Majority of the questions were on probability, permutation combination, work and time,average, ratio, and few which combined the concepts. One could crack easily if you brush up the Apti concepts. Programs: You need to be strong to answer this programmatic questions. All the questions were either from C or C++. some of the questions I remember was onMacro functions With different signaturesOperators precedence checking snippetMain within main functionSwitch special casesLoop exceptional casesStorage classes and so onProgram: It was a file program read input from a file and say the occurrence of each string i.e output the occurrence of each word along with the count to a different file. I solved aptitude and programs. I am sure of getting 23+ in both. We were given only 1 hour and 15 mins. So I solved 23 each qns in Apti and pgms. Then I started writing code. To get additional points I have written a C program as well as a Shell Script program for that. After writing the code they stil gave us some time and I did few questions in Apti and code. Since there was no negative marks I just marked some option for the remaining qns.The results were announced and only 3 of them were selected for the next round. I was the one to clear first with higher marks. So were asked to wait and after ten minutes they asked me to attend Technical Hr 1The HR was very friendly and cool. He asked me about the first round and there was an ice breaking session.Then he started technical questions.He asked why pointers, usage, advantage, disadvantage, discussed many cases, malloc, calloc, dangling pointer, null pointer, a code for implementation, be strong in your project,asked to draw use case,he stated some flaws and asked how would I rectify it in project, I had around 4 projects, which means I included 2 C programs that solved a real world problem.So he went discussing all these.Asked about data structures,A linked list programs just to find the middle node in single access, I just said use two pointers ,one move once and the other move twice, approach ,which was so easy. He asked if I knew it earlier. I said yes.code was asked to write for al pgms. The next program was to find the intersection of linked lists. I know it already but just took little time to solve.Even if you know the programs earlier take few time to answer. Then simple C programs Sort an array with 0 and 1 in O(n) complexity. first i said merge sort then I said keep one pointer at start and the other pointer at end.If you find any 1 from start, then start decrementing the end pointer til you find a 0 and exchange those.If I and j points to adjacent positions then stop the program.A matrix program to print for any n*n order.1 2 3 45 6 7 89 10 11 1213 14 15 16 and the output is1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10.I wrote the code and made lot of changes to make it efficient. Then he asked few questions from OOPS and web technologies and questions from my Resume about paper presentations, memberships clubs etc..I was confident enough that I would clear this round.One of them was eliminated and two of us was asked to attend the next round after having lunch in their office. The second technical round was with a hiring manager. He asked about data structures.Given family tree problem and asked how would I solve. I proposed graph and he was satisfied with the data structure and told how would I have a structure for it and few exceptional cases how would I solve. Questions were on projects. He asked many questions from each of the project.About each ppt that I have done.He also asked C programs involving storage classes,pointers,Ascii values.Asked commands and pgms in shell scripting,he asked in detail about testing and asked to say test cases.I told all the functional and non functional test cases.He asked if I know to work with any testing tool.I said no.He asked in Python.I could answer only one question,then I said I have just started learning python and I am not familiar.i said I will learn well before I would join. Then he asked few HR questions. Why red hat What is the post that I am going to join The tool that I am going to work.it would be mentioned in the job requirement post Will I be able to work wel continuously and so on What are you proud about yourself About my family And few more common questions and asked me if I have any questions I asked a question about the tool I am going to work what kind of work will I be having, Then I thanked him for having a nice session and for meeting him. We were asked to leave for the day and said results would be announced later. Tips:Be confident ,express yourself,Take your project reports to add up,Express that you want the job.Most of the programs were on geeksforgeeks. All the best!! If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Red Hat Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE 1 TCS Digital Interview Questions Google Interview Questions Amazon Interview Experience SDE-2 (3 Years Experienced) TCS Ninja Interview Experience (2020 batch) Write It Up: Share Your Interview Experiences Samsung RnD Coding Round Questions Nagarro Interview Experience
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Dec, 2014" }, { "code": null, "e": 260, "s": 52, "text": "I am doing my final year B.E CSE. I would like to thank geeksforgeeks. It helped a lot for cracking the interview. I applied online for the post of a Associate software Engineer Intern at Red hat, Bangalore." }, { "code": null, "e": 392, "s": 260, "text": "The first round was a written test round. We had nearly around 30 questions in aptitude as well as coding and a C program to write." }, { "code": null, "e": 822, "s": 392, "text": "Aptitude: The aptitude questions were moderate and it covered all most all of the topics. It is not necessary for you to remember any formula.Most of the problem involved solving it logically. If you know the concepts you can solve. Majority of the questions were on probability, permutation combination, work and time,average, ratio, and few which combined the concepts. One could crack easily if you brush up the Apti concepts." }, { "code": null, "e": 1320, "s": 822, "text": "Programs: You need to be strong to answer this programmatic questions. All the questions were either from C or C++. some of the questions I remember was onMacro functions With different signaturesOperators precedence checking snippetMain within main functionSwitch special casesLoop exceptional casesStorage classes and so onProgram: It was a file program read input from a file and say the occurrence of each string i.e output the occurrence of each word along with the count to a different file." }, { "code": null, "e": 2789, "s": 1320, "text": "I solved aptitude and programs. I am sure of getting 23+ in both. We were given only 1 hour and 15 mins. So I solved 23 each qns in Apti and pgms. Then I started writing code. To get additional points I have written a C program as well as a Shell Script program for that. After writing the code they stil gave us some time and I did few questions in Apti and code. Since there was no negative marks I just marked some option for the remaining qns.The results were announced and only 3 of them were selected for the next round. I was the one to clear first with higher marks. So were asked to wait and after ten minutes they asked me to attend Technical Hr 1The HR was very friendly and cool. He asked me about the first round and there was an ice breaking session.Then he started technical questions.He asked why pointers, usage, advantage, disadvantage, discussed many cases, malloc, calloc, dangling pointer, null pointer, a code for implementation, be strong in your project,asked to draw use case,he stated some flaws and asked how would I rectify it in project, I had around 4 projects, which means I included 2 C programs that solved a real world problem.So he went discussing all these.Asked about data structures,A linked list programs just to find the middle node in single access, I just said use two pointers ,one move once and the other move twice, approach ,which was so easy. He asked if I knew it earlier. I said yes.code was asked to write for al pgms." }, { "code": null, "e": 2991, "s": 2789, "text": "The next program was to find the intersection of linked lists. I know it already but just took little time to solve.Even if you know the programs earlier take few time to answer. Then simple C programs" }, { "code": null, "e": 3799, "s": 2991, "text": "Sort an array with 0 and 1 in O(n) complexity. first i said merge sort then I said keep one pointer at start and the other pointer at end.If you find any 1 from start, then start decrementing the end pointer til you find a 0 and exchange those.If I and j points to adjacent positions then stop the program.A matrix program to print for any n*n order.1 2 3 45 6 7 89 10 11 1213 14 15 16 and the output is1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10.I wrote the code and made lot of changes to make it efficient. Then he asked few questions from OOPS and web technologies and questions from my Resume about paper presentations, memberships clubs etc..I was confident enough that I would clear this round.One of them was eliminated and two of us was asked to attend the next round after having lunch in their office." }, { "code": null, "e": 4091, "s": 3799, "text": "The second technical round was with a hiring manager. He asked about data structures.Given family tree problem and asked how would I solve. I proposed graph and he was satisfied with the data structure and told how would I have a structure for it and few exceptional cases how would I solve." }, { "code": null, "e": 4692, "s": 4091, "text": "Questions were on projects. He asked many questions from each of the project.About each ppt that I have done.He also asked C programs involving storage classes,pointers,Ascii values.Asked commands and pgms in shell scripting,he asked in detail about testing and asked to say test cases.I told all the functional and non functional test cases.He asked if I know to work with any testing tool.I said no.He asked in Python.I could answer only one question,then I said I have just started learning python and I am not familiar.i said I will learn well before I would join. Then he asked few HR questions." }, { "code": null, "e": 4704, "s": 4692, "text": "Why red hat" }, { "code": null, "e": 4745, "s": 4704, "text": "What is the post that I am going to join" }, { "code": null, "e": 4828, "s": 4745, "text": "The tool that I am going to work.it would be mentioned in the job requirement post" }, { "code": null, "e": 4878, "s": 4828, "text": "Will I be able to work wel continuously and so on" }, { "code": null, "e": 4912, "s": 4878, "text": "What are you proud about yourself" }, { "code": null, "e": 4928, "s": 4912, "text": "About my family" }, { "code": null, "e": 4995, "s": 4928, "text": "And few more common questions and asked me if I have any questions" }, { "code": null, "e": 5084, "s": 4995, "text": "I asked a question about the tool I am going to work what kind of work will I be having," }, { "code": null, "e": 5228, "s": 5084, "text": "Then I thanked him for having a nice session and for meeting him. We were asked to leave for the day and said results would be announced later." }, { "code": null, "e": 5374, "s": 5228, "text": "Tips:Be confident ,express yourself,Take your project reports to add up,Express that you want the job.Most of the programs were on geeksforgeeks." }, { "code": null, "e": 5389, "s": 5374, "text": "All the best!!" }, { "code": null, "e": 5610, "s": 5389, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5618, "s": 5610, "text": "Red Hat" }, { "code": null, "e": 5640, "s": 5618, "text": "Interview Experiences" }, { "code": null, "e": 5738, "s": 5640, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5808, "s": 5738, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 5881, "s": 5808, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 5919, "s": 5881, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 5951, "s": 5919, "text": "TCS Digital Interview Questions" }, { "code": null, "e": 5978, "s": 5951, "text": "Google Interview Questions" }, { "code": null, "e": 6034, "s": 5978, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 6078, "s": 6034, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 6124, "s": 6078, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 6159, "s": 6124, "text": "Samsung RnD Coding Round Questions" } ]
How do I plot Shapely polygons and objects using Matplotlib?
To plot shapely polygons and objects using matplotlib, the steps are as follows − Create a polygon object using (x, y) data points. Create a polygon object using (x, y) data points. Get x and y, the exterior data, and the array using polygon.exterior.xy. Get x and y, the exterior data, and the array using polygon.exterior.xy. Plot x and y data points using plot() method with red color. Plot x and y data points using plot() method with red color. from shapely.geometry import Polygon import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True polygon1 = Polygon([(0, 5), (1, 1), (3, 0), (4, 6), ]) x, y = polygon1.exterior.xy plt.plot(x, y, c="red") plt.show()
[ { "code": null, "e": 1269, "s": 1187, "text": "To plot shapely polygons and objects using matplotlib, the steps are as follows −" }, { "code": null, "e": 1319, "s": 1269, "text": "Create a polygon object using (x, y) data points." }, { "code": null, "e": 1369, "s": 1319, "text": "Create a polygon object using (x, y) data points." }, { "code": null, "e": 1442, "s": 1369, "text": "Get x and y, the exterior data, and the array using polygon.exterior.xy." }, { "code": null, "e": 1515, "s": 1442, "text": "Get x and y, the exterior data, and the array using polygon.exterior.xy." }, { "code": null, "e": 1576, "s": 1515, "text": "Plot x and y data points using plot() method with red color." }, { "code": null, "e": 1637, "s": 1576, "text": "Plot x and y data points using plot() method with red color." }, { "code": null, "e": 1920, "s": 1637, "text": "from shapely.geometry import Polygon\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\npolygon1 = Polygon([(0, 5),\n (1, 1),\n (3, 0),\n (4, 6),\n])\nx, y = polygon1.exterior.xy\nplt.plot(x, y, c=\"red\")\nplt.show()" } ]
Count ways to build street under given constraints
20 Sep, 2021 There is a street of length n and as we know it has two sides. Therefore a total of 2 * n spots are available. In each of these spots either a house or an office can be built with following 2 restrictions: 1. No two offices on the same side of the street can be adjacent. 2. No two offices on different sides of the street can be exactly opposite to each other i.e. they can’t overlook each other. There are no restrictions on building houses and each spot must either have a house or office. Given length of the street n, find total number of ways to build the street. Examples: Input : 2 Output : 7 Please see below diagram for explanation. Input : 3 Output : 17 Following image depicts the 7 possible ways for building the street with N = 2 Ways for building street with length 1 with 2 houses: (H H) = {1} with 1 office and 1 house: (O H) (H O) = {2} (O O) is not allowed according to the problem statement. Total = 1 + 2 = 3 For length = 2, with 2 houses: (H H) can be added to all the cases of length 1: (H H) (H H) (H H) (H H) (O H) (H O) = {3} with 1 office and 1 house: (O H) and (H O) can both be added to all the cases of length 1 with last row (H H) (O H) (H O) (H H) (H H) = {2} when last row of a case of length 1 contains 1 office, it can only be extended in one way to build an office in row 2. (H O) (O H) (O H) (H O) = {2} (O H) (H O) (O O) (O H) (H O) (O H) etc are not allowed. Total = 3 + 2 + 2 = 7 Since the problem can be solved by finding solution for smaller subproblems and then extending the same logic, it can be solved using dynamic programming. We move in steps of one unit length. For each row we have two options: Build houses in both the spots Build one house and one officeThe first one can be done without any constraints. There is one way of building houses in both the spots at length i. So total ways using this choice = total ways for length i – 1.For the second choice, if row (i-1) had houses in both spots we have two ways of building a office i.e. (H O) and (O H) if row(i-1) had an office in one of its two spots we only have one way to build an office in row i.If prev row had (O H) curr row would have (H O) and similarly for prev row = (H O) curr row = (O H). From the above logic, total ways with this choice = 2 * (choice1(i-1)) + choice2(i-1)We will build a 2D dp for this. dp[0][i] indicates choice1 and dp[1][i] indicates choice2 for row i. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // C++ program to count ways to build street// under given constraints#include <bits/stdc++.h>using namespace std; // function to count ways of building// a street of n rowslong countWays(int n){ long dp[2][n + 1]; // base case dp[0][1] = 1; dp[1][1] = 2; for (int i = 2; i <= n; i++) { // ways of building houses in both // the spots of ith row dp[0][i] = dp[0][i - 1] + dp[1][i - 1]; // ways of building an office in one of // the two spots of ith row dp[1][i] = dp[0][i - 1] * 2 + dp[1][i - 1]; } // total ways for n rows return dp[0][n] + dp[1][n];} // driver program for checking above functionint main(){ int n = 5; cout << "Total no of ways with n = " << n << " are: " << countWays(n) << endl;} // Java program to count ways to build street// under given constraintspublic class GFG { // function to count ways of building// a street of n rows static long countWays(int n) { long dp[][] = new long[2][n + 1]; // base case dp[0][1] = 1; dp[1][1] = 2; for (int i = 2; i <= n; i++) { // ways of building houses in both // the spots of ith row dp[0][i] = dp[0][i - 1] + dp[1][i - 1]; // ways of building an office in one of // the two spots of ith row dp[1][i] = dp[0][i - 1] * 2 + dp[1][i - 1]; } // total ways for n rows return dp[0][n] + dp[1][n]; } // driver program for checking above function public static void main(String[] args) { int n = 5; System.out.print("Total no of ways with n = " + n + " are: " + countWays(n)); } } /*This code is contributed by PrinciRaj1992*/ # Python3 program to count ways to build# street under given constraints # function to count ways of building# a street of n rowsdef countWays(n) : dp = [[0] * (n + 1) for i in range(2)] # base case dp[0][1] = 1 dp[1][1] = 2 for i in range(2, n + 1) : # ways of building houses in both # the spots of ith row dp[0][i] = dp[0][i - 1] + dp[1][i - 1] # ways of building an office in one of # the two spots of ith row dp[1][i] = (dp[0][i - 1] * 2 + dp[1][i - 1]) # total ways for n rows return dp[0][n] + dp[1][n] # Driver Codeif __name__ == "__main__" : n = 5 print("Total no of ways with n =", n, "are:", countWays(n)) # This code is contributed by Ryuga // C# program to count ways to build street// under given constraints using System;public class GFG{ // function to count ways of building// a street of n rows static long countWays(int n) { long [,]dp = new long[2 , n + 1]; // base case dp[0,1] = 1; dp[1,1] = 2; for (int i = 2; i <= n; i++) { // ways of building houses in both // the spots of ith row dp[0 , i] = dp[0 , i - 1] + dp[1 , i - 1]; // ways of building an office in one of // the two spots of ith row dp[1 , i] = dp[0 , i - 1] * 2 + dp[1 , i - 1]; } // total ways for n rows return dp[0 , n] + dp[1 , n]; } // driver program for checking above function public static void Main() { int n = 5; Console.Write("Total no of ways with n = " + n + " are: " + countWays(n)); } } /*This code is contributed by PrinciRaj1992*/ <?php// PHP program to count ways to build street// under given constraints // function to count ways of building// a street of n rowsfunction countWays($n){ // base case $dp[0][1] = 1; $dp[1][1] = 2; for ($i = 2; $i <= $n; $i++) { // ways of building houses in both // the spots of ith row $dp[0][$i] = $dp[0][$i - 1] + $dp[1][$i - 1]; // ways of building an office in one of // the two spots of ith row $dp[1][$i] = $dp[0][$i - 1] * 2 + $dp[1][$i - 1]; } // total ways for n rows return $dp[0][$n] + $dp[1][$n];} // Driver Code $n = 5; echo "Total no of ways with n = ",$n, " are: " ,countWays($n),"\n"; // This code is contributed by jit_t?> <script> // Javascript program to count ways to// build street under given constraints // Function to count ways of building// a street of n rowsfunction countWays(n){ let dp = new Array(2); for(let i = 0; i < 2; i++) { dp[i] = new Array(n + 1); } // Base case dp[0][1] = 1; dp[1][1] = 2; for(let i = 2; i <= n; i++) { // Ways of building houses in both // the spots of ith row dp[0][i] = dp[0][i - 1] + dp[1][i - 1]; // Ways of building an office in one of // the two spots of ith row dp[1][i] = dp[0][i - 1] * 2 + dp[1][i - 1]; } // Total ways for n rows return dp[0][n] + dp[1][n];} // Driver codelet n = 5;document.write("Total no of ways with n = " + n + " are: " + countWays(n)); // This code is contributed by suresh07 </script> Total no of ways with n = 5 are: 99 Time Complexity: O(N) Auxiliary Space: O(N) Another Method Suppose you have A(n-1) and A(n-2) ,where A(i) depicts ways for 2*i buildings, then :A(n) = (Number of ways you have (H H) in A(n-1) )*3 + (Number of ways you have (O H) in A(n-1))*2How these cases arise ? Simply you can think of making 2 states as examined in above explanation.Number of ways you have (H H) in A(n-1) = Fix H H in (n-1)th position, this is equal to number of ways of n-2 position (fixing n-1 to H H). Number of ways you have (O H) in A(n-1) = (Number of ways in n-1 ) – (Number of ways of H H in A(n-1) position). So A(n) = 3*A(n-2) + 2*(A(n-1)-A(n-2)) = 2*A(n-1)+A(n-2) C++ Java Python3 C# Javascript // C++ program of above approach#include <iostream>using namespace std; // Program to count waysint countways(long long n){ long long A[n+1]; A[0] = 1; A[1] = 3; A[2] = 7; // Iterate from 2 to n for(int i=2;i<=n;i++) { A[i] = 2*A[i-1]+A[i-2]; } return A[n];} // Driver codeint main() { int n = 5; // Count Ways cout << countways(5) << endl; return 0;} // Java program of above approachimport java.io.*; class GFG{ // Program to count waysstatic int countways(int n){ int [] A = new int[n+1]; A[0] = 1; A[1] = 3; A[2] = 7; // Iterate from 2 to n for(int i = 2; i <= n; i++) { A[i] = 2 * A[i - 1] + A[i - 2]; } return A[n];} // Driver codepublic static void main(String[] args){ int n = 5; // Count Ways System.out.println(countways(5));}} // This code is contributed by Ankita saini # Python3 program of above approach # Program to count waysdef countways(n): A = [0 for i in range(n + 2)] A[0] = 1 A[1] = 3 A[2] = 7 # Iterate from 2 to n for i in range(2, n + 1): A[i] = 2 * A[i - 1] + A[i - 2] return A[n] # Driver coden = 5 # Count Waysprint(countways(5)) # This code is contributed by Sanjit_Prasad // C# program of above approachusing System; class GFG{ // Program to count waysstatic int countways(int n){ int [] A = new int[n+1]; A[0] = 1; A[1] = 3; A[2] = 7; // Iterate from 2 to n for(int i = 2; i <= n; i++) { A[i] = 2 * A[i - 1] + A[i - 2]; } return A[n];} // Driver codepublic static void Main(){ int n = 5; // Count Ways Console.Write(countways(n));}} // This code is contributed by bunnyram19. <script> // Javascript program of above approach // Program to count waysfunction countways(n){ let A = new Array(n+1).fill(0); A[0] = 1; A[1] = 3; A[2] = 7; // Iterate from 2 to n for(let i=2;i<=n;i++) { A[i] = 2*A[i-1]+A[i-2]; } return A[n];} // driver program let n = 5; // Count Ways document.write(countways(5)) </script> 99 Time Complexity: O(N) Auxiliary Space: O(N) This article is contributed by Aditi Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t princiraj1992 ankthon PulkitJoshi Sanjit_Prasad suresh07 sanjoy_62 ankita_saini bunnyram19 chhabradhanvi Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Find if there is a path between two vertices in an undirected graph Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Bellman–Ford Algorithm | DP-23 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Sieve of Eratosthenes Find minimum number of coins that make a given value
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Sep, 2021" }, { "code": null, "e": 259, "s": 52, "text": "There is a street of length n and as we know it has two sides. Therefore a total of 2 * n spots are available. In each of these spots either a house or an office can be built with following 2 restrictions: " }, { "code": null, "e": 623, "s": 259, "text": "1. No two offices on the same side of the street can be adjacent. 2. No two offices on different sides of the street can be exactly opposite to each other i.e. they can’t overlook each other. There are no restrictions on building houses and each spot must either have a house or office. Given length of the street n, find total number of ways to build the street." }, { "code": null, "e": 635, "s": 623, "text": "Examples: " }, { "code": null, "e": 721, "s": 635, "text": "Input : 2\nOutput : 7\nPlease see below diagram for explanation.\n\nInput : 3\nOutput : 17" }, { "code": null, "e": 802, "s": 721, "text": "Following image depicts the 7 possible ways for building the street with N = 2 " }, { "code": null, "e": 991, "s": 804, "text": "Ways for building street with length 1\nwith 2 houses: (H H) = {1}\nwith 1 office and 1 house: (O H) (H O) = {2}\n(O O) is not allowed according to the problem statement.\nTotal = 1 + 2 = 3" }, { "code": null, "e": 1529, "s": 991, "text": "For length = 2,\nwith 2 houses: (H H) can be added to all\nthe cases of length 1:\n\n(H H) (H H) (H H)\n(H H) (O H) (H O) = {3}\n\nwith 1 office and 1 house:\n(O H) and (H O) can both be added to all \nthe cases of length 1 with last row (H H)\n\n(O H) (H O)\n(H H) (H H) = {2}\n\nwhen last row of a case of length 1 \ncontains 1 office, it can only be \nextended in one way to build an office\nin row 2. \n(H O) (O H) \n(O H) (H O) = {2}\n\n(O H) (H O) (O O) \n(O H) (H O) (O H) etc are not allowed.\n\nTotal = 3 + 2 + 2 = 7" }, { "code": null, "e": 2502, "s": 1529, "text": "Since the problem can be solved by finding solution for smaller subproblems and then extending the same logic, it can be solved using dynamic programming. We move in steps of one unit length. For each row we have two options: Build houses in both the spots Build one house and one officeThe first one can be done without any constraints. There is one way of building houses in both the spots at length i. So total ways using this choice = total ways for length i – 1.For the second choice, if row (i-1) had houses in both spots we have two ways of building a office i.e. (H O) and (O H) if row(i-1) had an office in one of its two spots we only have one way to build an office in row i.If prev row had (O H) curr row would have (H O) and similarly for prev row = (H O) curr row = (O H). From the above logic, total ways with this choice = 2 * (choice1(i-1)) + choice2(i-1)We will build a 2D dp for this. dp[0][i] indicates choice1 and dp[1][i] indicates choice2 for row i." }, { "code": null, "e": 2548, "s": 2502, "text": "Below is the implementation of above idea : " }, { "code": null, "e": 2552, "s": 2548, "text": "C++" }, { "code": null, "e": 2557, "s": 2552, "text": "Java" }, { "code": null, "e": 2565, "s": 2557, "text": "Python3" }, { "code": null, "e": 2568, "s": 2565, "text": "C#" }, { "code": null, "e": 2572, "s": 2568, "text": "PHP" }, { "code": null, "e": 2583, "s": 2572, "text": "Javascript" }, { "code": "// C++ program to count ways to build street// under given constraints#include <bits/stdc++.h>using namespace std; // function to count ways of building// a street of n rowslong countWays(int n){ long dp[2][n + 1]; // base case dp[0][1] = 1; dp[1][1] = 2; for (int i = 2; i <= n; i++) { // ways of building houses in both // the spots of ith row dp[0][i] = dp[0][i - 1] + dp[1][i - 1]; // ways of building an office in one of // the two spots of ith row dp[1][i] = dp[0][i - 1] * 2 + dp[1][i - 1]; } // total ways for n rows return dp[0][n] + dp[1][n];} // driver program for checking above functionint main(){ int n = 5; cout << \"Total no of ways with n = \" << n << \" are: \" << countWays(n) << endl;}", "e": 3371, "s": 2583, "text": null }, { "code": "// Java program to count ways to build street// under given constraintspublic class GFG { // function to count ways of building// a street of n rows static long countWays(int n) { long dp[][] = new long[2][n + 1]; // base case dp[0][1] = 1; dp[1][1] = 2; for (int i = 2; i <= n; i++) { // ways of building houses in both // the spots of ith row dp[0][i] = dp[0][i - 1] + dp[1][i - 1]; // ways of building an office in one of // the two spots of ith row dp[1][i] = dp[0][i - 1] * 2 + dp[1][i - 1]; } // total ways for n rows return dp[0][n] + dp[1][n]; } // driver program for checking above function public static void main(String[] args) { int n = 5; System.out.print(\"Total no of ways with n = \" + n + \" are: \" + countWays(n)); } } /*This code is contributed by PrinciRaj1992*/", "e": 4320, "s": 3371, "text": null }, { "code": "# Python3 program to count ways to build# street under given constraints # function to count ways of building# a street of n rowsdef countWays(n) : dp = [[0] * (n + 1) for i in range(2)] # base case dp[0][1] = 1 dp[1][1] = 2 for i in range(2, n + 1) : # ways of building houses in both # the spots of ith row dp[0][i] = dp[0][i - 1] + dp[1][i - 1] # ways of building an office in one of # the two spots of ith row dp[1][i] = (dp[0][i - 1] * 2 + dp[1][i - 1]) # total ways for n rows return dp[0][n] + dp[1][n] # Driver Codeif __name__ == \"__main__\" : n = 5 print(\"Total no of ways with n =\", n, \"are:\", countWays(n)) # This code is contributed by Ryuga", "e": 5118, "s": 4320, "text": null }, { "code": "// C# program to count ways to build street// under given constraints using System;public class GFG{ // function to count ways of building// a street of n rows static long countWays(int n) { long [,]dp = new long[2 , n + 1]; // base case dp[0,1] = 1; dp[1,1] = 2; for (int i = 2; i <= n; i++) { // ways of building houses in both // the spots of ith row dp[0 , i] = dp[0 , i - 1] + dp[1 , i - 1]; // ways of building an office in one of // the two spots of ith row dp[1 , i] = dp[0 , i - 1] * 2 + dp[1 , i - 1]; } // total ways for n rows return dp[0 , n] + dp[1 , n]; } // driver program for checking above function public static void Main() { int n = 5; Console.Write(\"Total no of ways with n = \" + n + \" are: \" + countWays(n)); } } /*This code is contributed by PrinciRaj1992*/", "e": 6069, "s": 5118, "text": null }, { "code": "<?php// PHP program to count ways to build street// under given constraints // function to count ways of building// a street of n rowsfunction countWays($n){ // base case $dp[0][1] = 1; $dp[1][1] = 2; for ($i = 2; $i <= $n; $i++) { // ways of building houses in both // the spots of ith row $dp[0][$i] = $dp[0][$i - 1] + $dp[1][$i - 1]; // ways of building an office in one of // the two spots of ith row $dp[1][$i] = $dp[0][$i - 1] * 2 + $dp[1][$i - 1]; } // total ways for n rows return $dp[0][$n] + $dp[1][$n];} // Driver Code $n = 5; echo \"Total no of ways with n = \",$n, \" are: \" ,countWays($n),\"\\n\"; // This code is contributed by jit_t?>", "e": 6840, "s": 6069, "text": null }, { "code": "<script> // Javascript program to count ways to// build street under given constraints // Function to count ways of building// a street of n rowsfunction countWays(n){ let dp = new Array(2); for(let i = 0; i < 2; i++) { dp[i] = new Array(n + 1); } // Base case dp[0][1] = 1; dp[1][1] = 2; for(let i = 2; i <= n; i++) { // Ways of building houses in both // the spots of ith row dp[0][i] = dp[0][i - 1] + dp[1][i - 1]; // Ways of building an office in one of // the two spots of ith row dp[1][i] = dp[0][i - 1] * 2 + dp[1][i - 1]; } // Total ways for n rows return dp[0][n] + dp[1][n];} // Driver codelet n = 5;document.write(\"Total no of ways with n = \" + n + \" are: \" + countWays(n)); // This code is contributed by suresh07 </script>", "e": 7711, "s": 6840, "text": null }, { "code": null, "e": 7747, "s": 7711, "text": "Total no of ways with n = 5 are: 99" }, { "code": null, "e": 7791, "s": 7747, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 8395, "s": 7791, "text": "Another Method Suppose you have A(n-1) and A(n-2) ,where A(i) depicts ways for 2*i buildings, then :A(n) = (Number of ways you have (H H) in A(n-1) )*3 + (Number of ways you have (O H) in A(n-1))*2How these cases arise ? Simply you can think of making 2 states as examined in above explanation.Number of ways you have (H H) in A(n-1) = Fix H H in (n-1)th position, this is equal to number of ways of n-2 position (fixing n-1 to H H). Number of ways you have (O H) in A(n-1) = (Number of ways in n-1 ) – (Number of ways of H H in A(n-1) position). So A(n) = 3*A(n-2) + 2*(A(n-1)-A(n-2)) = 2*A(n-1)+A(n-2)" }, { "code": null, "e": 8399, "s": 8395, "text": "C++" }, { "code": null, "e": 8404, "s": 8399, "text": "Java" }, { "code": null, "e": 8412, "s": 8404, "text": "Python3" }, { "code": null, "e": 8415, "s": 8412, "text": "C#" }, { "code": null, "e": 8426, "s": 8415, "text": "Javascript" }, { "code": "// C++ program of above approach#include <iostream>using namespace std; // Program to count waysint countways(long long n){ long long A[n+1]; A[0] = 1; A[1] = 3; A[2] = 7; // Iterate from 2 to n for(int i=2;i<=n;i++) { A[i] = 2*A[i-1]+A[i-2]; } return A[n];} // Driver codeint main() { int n = 5; // Count Ways cout << countways(5) << endl; return 0;}", "e": 8831, "s": 8426, "text": null }, { "code": "// Java program of above approachimport java.io.*; class GFG{ // Program to count waysstatic int countways(int n){ int [] A = new int[n+1]; A[0] = 1; A[1] = 3; A[2] = 7; // Iterate from 2 to n for(int i = 2; i <= n; i++) { A[i] = 2 * A[i - 1] + A[i - 2]; } return A[n];} // Driver codepublic static void main(String[] args){ int n = 5; // Count Ways System.out.println(countways(5));}} // This code is contributed by Ankita saini", "e": 9317, "s": 8831, "text": null }, { "code": "# Python3 program of above approach # Program to count waysdef countways(n): A = [0 for i in range(n + 2)] A[0] = 1 A[1] = 3 A[2] = 7 # Iterate from 2 to n for i in range(2, n + 1): A[i] = 2 * A[i - 1] + A[i - 2] return A[n] # Driver coden = 5 # Count Waysprint(countways(5)) # This code is contributed by Sanjit_Prasad", "e": 9680, "s": 9317, "text": null }, { "code": "// C# program of above approachusing System; class GFG{ // Program to count waysstatic int countways(int n){ int [] A = new int[n+1]; A[0] = 1; A[1] = 3; A[2] = 7; // Iterate from 2 to n for(int i = 2; i <= n; i++) { A[i] = 2 * A[i - 1] + A[i - 2]; } return A[n];} // Driver codepublic static void Main(){ int n = 5; // Count Ways Console.Write(countways(n));}} // This code is contributed by bunnyram19.", "e": 10141, "s": 9680, "text": null }, { "code": "<script> // Javascript program of above approach // Program to count waysfunction countways(n){ let A = new Array(n+1).fill(0); A[0] = 1; A[1] = 3; A[2] = 7; // Iterate from 2 to n for(let i=2;i<=n;i++) { A[i] = 2*A[i-1]+A[i-2]; } return A[n];} // driver program let n = 5; // Count Ways document.write(countways(5)) </script>", "e": 10531, "s": 10141, "text": null }, { "code": null, "e": 10534, "s": 10531, "text": "99" }, { "code": null, "e": 10578, "s": 10534, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 10999, "s": 10578, "text": "This article is contributed by Aditi Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11005, "s": 10999, "text": "jit_t" }, { "code": null, "e": 11019, "s": 11005, "text": "princiraj1992" }, { "code": null, "e": 11027, "s": 11019, "text": "ankthon" }, { "code": null, "e": 11039, "s": 11027, "text": "PulkitJoshi" }, { "code": null, "e": 11053, "s": 11039, "text": "Sanjit_Prasad" }, { "code": null, "e": 11062, "s": 11053, "text": "suresh07" }, { "code": null, "e": 11072, "s": 11062, "text": "sanjoy_62" }, { "code": null, "e": 11085, "s": 11072, "text": "ankita_saini" }, { "code": null, "e": 11096, "s": 11085, "text": "bunnyram19" }, { "code": null, "e": 11110, "s": 11096, "text": "chhabradhanvi" }, { "code": null, "e": 11130, "s": 11110, "text": "Dynamic Programming" }, { "code": null, "e": 11150, "s": 11130, "text": "Dynamic Programming" }, { "code": null, "e": 11248, "s": 11150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11275, "s": 11248, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 11313, "s": 11275, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 11381, "s": 11313, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 11414, "s": 11381, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 11433, "s": 11414, "text": "Coin Change | DP-7" }, { "code": null, "e": 11464, "s": 11433, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 11499, "s": 11464, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 11567, "s": 11499, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 11589, "s": 11567, "text": "Sieve of Eratosthenes" } ]
Lock Variable Synchronization Mechanism
17 Dec, 2021 Prerequisites – Process SynchronizationA lock variable provides the simplest synchronization mechanism for processes. Some noteworthy points regarding Lock Variables are- Its a software mechanism implemented in user mode, i.e. no support required from the Operating System.Its a busy waiting solution (keeps the CPU busy even when its technically waiting).It can be used for more than two processes. Its a software mechanism implemented in user mode, i.e. no support required from the Operating System. Its a busy waiting solution (keeps the CPU busy even when its technically waiting). It can be used for more than two processes. When Lock = 0 implies critical section is vacant (initial value ) and Lock = 1 implies critical section occupied.The pseudocode looks something like this – Entry section - while(lock != 0); Lock = 1; //critical section Exit section - Lock = 0; A more formal approach to the Lock Variable method for process synchronization can be seen in the following code snippet : C char buffer[SIZE];int count = 0, start = 0, end = 0;struct lock l; // initialize lock variablelock_init(&l); void put(char c){ // entry section lock_acquire(&l); // critical section begins while (count == SIZE) { lock_release(&l); lock_acquire(&l); } count++; buffer[start] = c; start++; if (start == SIZE) { start = 0; } // critical section ends // exit section lock_release(&l);} char get(){ char c; // entry section lock_acquire(&l); // critical section begins while (count == 0) { lock_release(&l); lock_acquire(&l); } count--; c = buffer[end]; end++; if (end == SIZE) { end = 0; } // critical section ends // exit section lock_release(&l); return c;} Here we can see a classic implementation of the reader-writer’s problem. The buffer here is the shared memory and many processes are either trying to read or write a character to it. To prevent any ambiguity of data we restrict concurrent access by using a lock variable. We have also applied a constraint on the number of readers/writers that can have access.Now every Synchronization mechanism is judged on the basis of three primary parameters : Mutual Exclusion.Progress.Bounded Waiting. Mutual Exclusion. Progress. Bounded Waiting. Of which mutual exclusion is the most important of all parameters. The Lock Variable doesn’t provide mutual exclusion in some cases. This fact can be best verified by writing its pseudo-code in the form of an assembly language code as given below. 1. Load Lock, R0 ; (Store the value of Lock in Register R0.) 2. CMP R0, #0 ; (Compare the value of register R0 with 0.) 3. JNZ Step 1 ; (Jump to step 1 if value of R0 is not 0.) 4. Store #1, Lock ; (Set new value of Lock as 1.) Enter critical section 5. Store #0, Lock ; (Set the value of lock as 0 again.) Now let’s suppose that processes P1 and P2 are competing for Critical Section and their sequence of execution be as follows (initial value of Lock = 0) – P1 executes statement 1 and gets pre-empted.P2 executes statement 1, 2, 3, 4 and enters Critical Section and gets pre-empted.P1 executes statement 2, 3, 4 and also enters Critical Section. P1 executes statement 1 and gets pre-empted. P2 executes statement 1, 2, 3, 4 and enters Critical Section and gets pre-empted. P1 executes statement 2, 3, 4 and also enters Critical Section. Here initially the R0 of process P1 stores lock value as 0 but fails to update the lock value as 1. So when P2 executes it also finds the LOCK value as 0 and enters Critical Section by setting LOCK value as 1. But the real problem arises when P1 executes again it doesn’t check the updated value of Lock. It only checks the previous value stored in R0 which was 0 and it enters critical section.This is only one possible sequence of execution among many others. Some may even provide mutual exclusion but we cannot dwell on that. According to murphy’s law “Anything that can go wrong will go wrong“. So like all easy things the Lock Variable Synchronization method comes with its fair share of Demerits but its a good starting point for us to develop better Synchronization Algorithms to take care of the problems that we face here. This article is contributed by Siddhant Bajaj 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. avtarkumar719 GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology Difference between Clustered and Non-clustered index Difference between Process and Thread Three address code in Compiler Banker's Algorithm in Operating System Disk Scheduling Algorithms Paging in Operating System File Allocation Methods CPU Scheduling in Operating Systems
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Dec, 2021" }, { "code": null, "e": 226, "s": 54, "text": "Prerequisites – Process SynchronizationA lock variable provides the simplest synchronization mechanism for processes. Some noteworthy points regarding Lock Variables are- " }, { "code": null, "e": 455, "s": 226, "text": "Its a software mechanism implemented in user mode, i.e. no support required from the Operating System.Its a busy waiting solution (keeps the CPU busy even when its technically waiting).It can be used for more than two processes." }, { "code": null, "e": 558, "s": 455, "text": "Its a software mechanism implemented in user mode, i.e. no support required from the Operating System." }, { "code": null, "e": 642, "s": 558, "text": "Its a busy waiting solution (keeps the CPU busy even when its technically waiting)." }, { "code": null, "e": 686, "s": 642, "text": "It can be used for more than two processes." }, { "code": null, "e": 843, "s": 686, "text": "When Lock = 0 implies critical section is vacant (initial value ) and Lock = 1 implies critical section occupied.The pseudocode looks something like this – " }, { "code": null, "e": 947, "s": 843, "text": "Entry section - while(lock != 0);\n Lock = 1;\n//critical section\nExit section - Lock = 0;" }, { "code": null, "e": 1070, "s": 947, "text": "A more formal approach to the Lock Variable method for process synchronization can be seen in the following code snippet :" }, { "code": null, "e": 1072, "s": 1070, "text": "C" }, { "code": "char buffer[SIZE];int count = 0, start = 0, end = 0;struct lock l; // initialize lock variablelock_init(&l); void put(char c){ // entry section lock_acquire(&l); // critical section begins while (count == SIZE) { lock_release(&l); lock_acquire(&l); } count++; buffer[start] = c; start++; if (start == SIZE) { start = 0; } // critical section ends // exit section lock_release(&l);} char get(){ char c; // entry section lock_acquire(&l); // critical section begins while (count == 0) { lock_release(&l); lock_acquire(&l); } count--; c = buffer[end]; end++; if (end == SIZE) { end = 0; } // critical section ends // exit section lock_release(&l); return c;}", "e": 1876, "s": 1072, "text": null }, { "code": null, "e": 2326, "s": 1876, "text": "Here we can see a classic implementation of the reader-writer’s problem. The buffer here is the shared memory and many processes are either trying to read or write a character to it. To prevent any ambiguity of data we restrict concurrent access by using a lock variable. We have also applied a constraint on the number of readers/writers that can have access.Now every Synchronization mechanism is judged on the basis of three primary parameters : " }, { "code": null, "e": 2369, "s": 2326, "text": "Mutual Exclusion.Progress.Bounded Waiting." }, { "code": null, "e": 2387, "s": 2369, "text": "Mutual Exclusion." }, { "code": null, "e": 2397, "s": 2387, "text": "Progress." }, { "code": null, "e": 2414, "s": 2397, "text": "Bounded Waiting." }, { "code": null, "e": 2662, "s": 2414, "text": "Of which mutual exclusion is the most important of all parameters. The Lock Variable doesn’t provide mutual exclusion in some cases. This fact can be best verified by writing its pseudo-code in the form of an assembly language code as given below." }, { "code": null, "e": 2969, "s": 2662, "text": "1. Load Lock, R0 ; (Store the value of Lock in Register R0.)\n2. CMP R0, #0 ; (Compare the value of register R0 with 0.)\n3. JNZ Step 1 ; (Jump to step 1 if value of R0 is not 0.)\n4. Store #1, Lock ; (Set new value of Lock as 1.)\nEnter critical section\n5. Store #0, Lock ; (Set the value of lock as 0 again.)" }, { "code": null, "e": 3123, "s": 2969, "text": "Now let’s suppose that processes P1 and P2 are competing for Critical Section and their sequence of execution be as follows (initial value of Lock = 0) –" }, { "code": null, "e": 3312, "s": 3123, "text": "P1 executes statement 1 and gets pre-empted.P2 executes statement 1, 2, 3, 4 and enters Critical Section and gets pre-empted.P1 executes statement 2, 3, 4 and also enters Critical Section." }, { "code": null, "e": 3357, "s": 3312, "text": "P1 executes statement 1 and gets pre-empted." }, { "code": null, "e": 3439, "s": 3357, "text": "P2 executes statement 1, 2, 3, 4 and enters Critical Section and gets pre-empted." }, { "code": null, "e": 3503, "s": 3439, "text": "P1 executes statement 2, 3, 4 and also enters Critical Section." }, { "code": null, "e": 4760, "s": 3503, "text": "Here initially the R0 of process P1 stores lock value as 0 but fails to update the lock value as 1. So when P2 executes it also finds the LOCK value as 0 and enters Critical Section by setting LOCK value as 1. But the real problem arises when P1 executes again it doesn’t check the updated value of Lock. It only checks the previous value stored in R0 which was 0 and it enters critical section.This is only one possible sequence of execution among many others. Some may even provide mutual exclusion but we cannot dwell on that. According to murphy’s law “Anything that can go wrong will go wrong“. So like all easy things the Lock Variable Synchronization method comes with its fair share of Demerits but its a good starting point for us to develop better Synchronization Algorithms to take care of the problems that we face here. This article is contributed by Siddhant Bajaj 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4774, "s": 4760, "text": "avtarkumar719" }, { "code": null, "e": 4782, "s": 4774, "text": "GATE CS" }, { "code": null, "e": 4800, "s": 4782, "text": "Operating Systems" }, { "code": null, "e": 4818, "s": 4800, "text": "Operating Systems" }, { "code": null, "e": 4916, "s": 4818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4948, "s": 4916, "text": "Differences between TCP and UDP" }, { "code": null, "e": 4974, "s": 4948, "text": "Types of Network Topology" }, { "code": null, "e": 5027, "s": 4974, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 5065, "s": 5027, "text": "Difference between Process and Thread" }, { "code": null, "e": 5096, "s": 5065, "text": "Three address code in Compiler" }, { "code": null, "e": 5135, "s": 5096, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 5162, "s": 5135, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 5189, "s": 5162, "text": "Paging in Operating System" }, { "code": null, "e": 5213, "s": 5189, "text": "File Allocation Methods" } ]
How to Toggle an Element Class in JavaScript ?
16 Apr, 2020 Toggling the class means if there is no class name assigned to the element, then a class name can be assigned to it dynamically or if a certain class is already present, then it can be removed dynamically by just using the toggle() or by using contains(), add(), remove() methods of DOMTokenList object within JavaScript. Properties of HTML elements being used: classList: This property returns the class name(s) of the element as a DOMTokenList object. This object has some well known methods including contains(), add(), remove(), toggle(). contains(): This method returns a boolean value indicating if a particular class name is present or not. add(): This method is used to add one or more class names to an element. remove(): This method is used to remove one or more class names from an element. toggle(): This method belongs to DOMTokenList object, and is used to toggle between the classes Method 1: By Using toggle() method: Let’s first make a template of the HTML file that includes a paragraph tag and a button tag. After that let’s apply some style for the class that is to be toggled. In our example, the class name is “paragraphClass” and button’s ID is “Button”. Copy this code inside the <head> of the html page. <style> .paragraphClass { font-size: 30px; color: red; } #Button { margin-top: 15px; } </style> Now, let’s write the script for toggling the class. Following is the script, that is to be written within <head> of the html page. In this method, we will use the toggle() function for toggling the class names. <script> function myFunc() { var para = document.getElementById("p"); para.classList.toggle("paragraphClass"); } </script> Example: Let’s get to the working example by combining all the concepts described above. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Geeks for Geeks</title> <style> .paragraphClass { font-size: 30px; color: red; } #Button { margin-top: 15px; } </style> <script> function myFunc() { var para = document.getElementById("p"); para.classList.toggle("paragraphClass"); } </script></head> <body> <p id="p"> Click on the button to toggle between the class to see the effects </p> <button id="Button" onclick="myFunc()"> Click Me </button></body> </html> Output: Without Clicking the Button: After Clicking the Button Once: After Clicking the Button Twice: Method 2: By Using contains(), add() and remove() method: Let’s first make a template of the HTML file that includes a paragraph tag and a button tag. After that let’s apply some style for the class that is to be toggled. In our example, the class name is “paragraphClass” and button’s ID is “Button”. Copy this code inside the <head> of the html page. <style> .paragraphClass { font-size: 30px; color: red; } #Button { margin-top: 15px; } </style> Now, let’s write the script for toggling the class. Following is the script, that is to be written within the <head> of the html page. In this method, we will use the contains(), add(), remove() method for toggling the class names. The trick here is that we will check whether a particular class is present or not using contains() method, and then we will add or remove the class names from the element using add() or remove() respectively. <script> function myFunc() { var para = document.getElementById("p"); if(para.classList.contains("paragraphClass")) { para.classList.remove("paragraphClass"); } else { para.classList.add("paragraphClass"); } } </script> Example: Let’s get to the working example by combining all the concepts described above. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Geeks for Geeks</title> <style> .paragraphClass { font-size: 30px; color: red; } #Button { margin-top: 15px; } </style> <script> function myFunc() { var para = document.getElementById("p"); if(para.classList.contains("paragraphClass")) { para.classList.remove("paragraphClass"); } else { para.classList.add("paragraphClass"); } } </script></head> <body> <p id="p"> Click on the button to toggle between the class to see the effects </p> <button id="Button" onclick="myFunc()"> Click Me </button></body> </html> Output: Without Clicking the Button: After Clicking the Button Once: After Clicking the Button Twice: JavaScript-Misc Picked CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Apr, 2020" }, { "code": null, "e": 374, "s": 52, "text": "Toggling the class means if there is no class name assigned to the element, then a class name can be assigned to it dynamically or if a certain class is already present, then it can be removed dynamically by just using the toggle() or by using contains(), add(), remove() methods of DOMTokenList object within JavaScript." }, { "code": null, "e": 414, "s": 374, "text": "Properties of HTML elements being used:" }, { "code": null, "e": 595, "s": 414, "text": "classList: This property returns the class name(s) of the element as a DOMTokenList object. This object has some well known methods including contains(), add(), remove(), toggle()." }, { "code": null, "e": 700, "s": 595, "text": "contains(): This method returns a boolean value indicating if a particular class name is present or not." }, { "code": null, "e": 773, "s": 700, "text": "add(): This method is used to add one or more class names to an element." }, { "code": null, "e": 854, "s": 773, "text": "remove(): This method is used to remove one or more class names from an element." }, { "code": null, "e": 950, "s": 854, "text": "toggle(): This method belongs to DOMTokenList object, and is used to toggle between the classes" }, { "code": null, "e": 1281, "s": 950, "text": "Method 1: By Using toggle() method: Let’s first make a template of the HTML file that includes a paragraph tag and a button tag. After that let’s apply some style for the class that is to be toggled. In our example, the class name is “paragraphClass” and button’s ID is “Button”. Copy this code inside the <head> of the html page." }, { "code": null, "e": 1419, "s": 1281, "text": "<style>\n .paragraphClass {\n font-size: 30px;\n color: red;\n }\n\n #Button {\n margin-top: 15px;\n }\n</style>\n" }, { "code": null, "e": 1630, "s": 1419, "text": "Now, let’s write the script for toggling the class. Following is the script, that is to be written within <head> of the html page. In this method, we will use the toggle() function for toggling the class names." }, { "code": null, "e": 1778, "s": 1630, "text": "<script>\n function myFunc() {\n var para = document.getElementById(\"p\");\n para.classList.toggle(\"paragraphClass\");\n }\n</script>\n" }, { "code": null, "e": 1867, "s": 1778, "text": "Example: Let’s get to the working example by combining all the concepts described above." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Geeks for Geeks</title> <style> .paragraphClass { font-size: 30px; color: red; } #Button { margin-top: 15px; } </style> <script> function myFunc() { var para = document.getElementById(\"p\"); para.classList.toggle(\"paragraphClass\"); } </script></head> <body> <p id=\"p\"> Click on the button to toggle between the class to see the effects </p> <button id=\"Button\" onclick=\"myFunc()\"> Click Me </button></body> </html>", "e": 2513, "s": 1867, "text": null }, { "code": null, "e": 2521, "s": 2513, "text": "Output:" }, { "code": null, "e": 2550, "s": 2521, "text": "Without Clicking the Button:" }, { "code": null, "e": 2582, "s": 2550, "text": "After Clicking the Button Once:" }, { "code": null, "e": 2615, "s": 2582, "text": "After Clicking the Button Twice:" }, { "code": null, "e": 2968, "s": 2615, "text": "Method 2: By Using contains(), add() and remove() method: Let’s first make a template of the HTML file that includes a paragraph tag and a button tag. After that let’s apply some style for the class that is to be toggled. In our example, the class name is “paragraphClass” and button’s ID is “Button”. Copy this code inside the <head> of the html page." }, { "code": null, "e": 3106, "s": 2968, "text": "<style>\n .paragraphClass {\n font-size: 30px;\n color: red;\n }\n\n #Button {\n margin-top: 15px;\n }\n</style>\n" }, { "code": null, "e": 3547, "s": 3106, "text": "Now, let’s write the script for toggling the class. Following is the script, that is to be written within the <head> of the html page. In this method, we will use the contains(), add(), remove() method for toggling the class names. The trick here is that we will check whether a particular class is present or not using contains() method, and then we will add or remove the class names from the element using add() or remove() respectively." }, { "code": null, "e": 3805, "s": 3547, "text": "<script>\nfunction myFunc() {\n var para = document.getElementById(\"p\");\n\n if(para.classList.contains(\"paragraphClass\")) {\n para.classList.remove(\"paragraphClass\");\n }\n else {\n para.classList.add(\"paragraphClass\");\n }\n}\n</script>\n" }, { "code": null, "e": 3894, "s": 3805, "text": "Example: Let’s get to the working example by combining all the concepts described above." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <title>Geeks for Geeks</title> <style> .paragraphClass { font-size: 30px; color: red; } #Button { margin-top: 15px; } </style> <script> function myFunc() { var para = document.getElementById(\"p\"); if(para.classList.contains(\"paragraphClass\")) { para.classList.remove(\"paragraphClass\"); } else { para.classList.add(\"paragraphClass\"); } } </script></head> <body> <p id=\"p\"> Click on the button to toggle between the class to see the effects </p> <button id=\"Button\" onclick=\"myFunc()\"> Click Me </button></body> </html>", "e": 4701, "s": 3894, "text": null }, { "code": null, "e": 4709, "s": 4701, "text": "Output:" }, { "code": null, "e": 4738, "s": 4709, "text": "Without Clicking the Button:" }, { "code": null, "e": 4770, "s": 4738, "text": "After Clicking the Button Once:" }, { "code": null, "e": 4803, "s": 4770, "text": "After Clicking the Button Twice:" }, { "code": null, "e": 4819, "s": 4803, "text": "JavaScript-Misc" }, { "code": null, "e": 4826, "s": 4819, "text": "Picked" }, { "code": null, "e": 4830, "s": 4826, "text": "CSS" }, { "code": null, "e": 4835, "s": 4830, "text": "HTML" }, { "code": null, "e": 4846, "s": 4835, "text": "JavaScript" }, { "code": null, "e": 4863, "s": 4846, "text": "Web Technologies" }, { "code": null, "e": 4868, "s": 4863, "text": "HTML" } ]
Node.js - Path Module
Node.js path module is used for handling and transforming file paths. This module can be imported using the following syntax. var path = require("path") path.normalize(p) Normalize a string path, taking care of '..' and '.' parts. path.join([path1][, path2][, ...]) Join all the arguments together and normalize the resulting path. path.resolve([from ...], to) Resolves to an absolute path. path.isAbsolute(path) Determines whether the path is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. path.relative(from, to) Solve the relative path from from to to. path.dirname(p) Return the directory name of a path. Similar to the Unix dirname command. path.basename(p[, ext]) Return the last portion of a path. Similar to the Unix basename command. path.extname(p) Return the extension of the path, from the last '.' to end of string in the last portion of the path. If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. path.parse(pathString) Returns an object from a path string. path.format(pathObject) Returns a path string from an object, the opposite of path.parse above. path.sep The platform-specific file separator. '\\' or '/'. path.delimiter The platform-specific path delimiter, ; or ':'. path.posix Provide access to aforementioned path methods but always interact in a posix compatible way. path.win32 Provide access to aforementioned path methods but always interact in a win32 compatible way. Create a js file named main.js with the following code − var path = require("path"); // Normalization console.log('normalization : ' + path.normalize('/test/test1//2slashes/1slash/tab/..')); // Join console.log('joint path : ' + path.join('/test', 'test1', '2slashes/1slash', 'tab', '..')); // Resolve console.log('resolve : ' + path.resolve('main.js')); // extName console.log('ext name : ' + path.extname('main.js')); Now run the main.js to see the result − $ node main.js Verify the Output. normalization : /test/test1/2slashes/1slash joint path : /test/test1/2slashes/1slash resolve : /web/com/1427176256_27423/main.js ext name : .js
[ { "code": null, "e": 2278, "s": 2152, "text": "Node.js path module is used for handling and transforming file paths. This module can be imported using the following syntax." }, { "code": null, "e": 2306, "s": 2278, "text": "var path = require(\"path\")\n" }, { "code": null, "e": 2324, "s": 2306, "text": "path.normalize(p)" }, { "code": null, "e": 2384, "s": 2324, "text": "Normalize a string path, taking care of '..' and '.' parts." }, { "code": null, "e": 2419, "s": 2384, "text": "path.join([path1][, path2][, ...])" }, { "code": null, "e": 2485, "s": 2419, "text": "Join all the arguments together and normalize the resulting path." }, { "code": null, "e": 2514, "s": 2485, "text": "path.resolve([from ...], to)" }, { "code": null, "e": 2544, "s": 2514, "text": "Resolves to an absolute path." }, { "code": null, "e": 2566, "s": 2544, "text": "path.isAbsolute(path)" }, { "code": null, "e": 2711, "s": 2566, "text": "Determines whether the path is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory." }, { "code": null, "e": 2735, "s": 2711, "text": "path.relative(from, to)" }, { "code": null, "e": 2776, "s": 2735, "text": "Solve the relative path from from to to." }, { "code": null, "e": 2792, "s": 2776, "text": "path.dirname(p)" }, { "code": null, "e": 2866, "s": 2792, "text": "Return the directory name of a path. Similar to the Unix dirname command." }, { "code": null, "e": 2890, "s": 2866, "text": "path.basename(p[, ext])" }, { "code": null, "e": 2963, "s": 2890, "text": "Return the last portion of a path. Similar to the Unix basename command." }, { "code": null, "e": 2979, "s": 2963, "text": "path.extname(p)" }, { "code": null, "e": 3202, "s": 2979, "text": "Return the extension of the path, from the last '.' to end of string in the last portion of the path. If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string." }, { "code": null, "e": 3225, "s": 3202, "text": "path.parse(pathString)" }, { "code": null, "e": 3263, "s": 3225, "text": "Returns an object from a path string." }, { "code": null, "e": 3287, "s": 3263, "text": "path.format(pathObject)" }, { "code": null, "e": 3359, "s": 3287, "text": "Returns a path string from an object, the opposite of path.parse above." }, { "code": null, "e": 3368, "s": 3359, "text": "path.sep" }, { "code": null, "e": 3419, "s": 3368, "text": "The platform-specific file separator. '\\\\' or '/'." }, { "code": null, "e": 3434, "s": 3419, "text": "path.delimiter" }, { "code": null, "e": 3482, "s": 3434, "text": "The platform-specific path delimiter, ; or ':'." }, { "code": null, "e": 3493, "s": 3482, "text": "path.posix" }, { "code": null, "e": 3586, "s": 3493, "text": "Provide access to aforementioned path methods but always interact in a posix compatible way." }, { "code": null, "e": 3597, "s": 3586, "text": "path.win32" }, { "code": null, "e": 3690, "s": 3597, "text": "Provide access to aforementioned path methods but always interact in a win32 compatible way." }, { "code": null, "e": 3747, "s": 3690, "text": "Create a js file named main.js with the following code −" }, { "code": null, "e": 4114, "s": 3747, "text": "var path = require(\"path\");\n\n// Normalization\nconsole.log('normalization : ' + path.normalize('/test/test1//2slashes/1slash/tab/..'));\n\n// Join\nconsole.log('joint path : ' + path.join('/test', 'test1', '2slashes/1slash', 'tab', '..'));\n\n// Resolve\nconsole.log('resolve : ' + path.resolve('main.js'));\n\n// extName\nconsole.log('ext name : ' + path.extname('main.js'));" }, { "code": null, "e": 4154, "s": 4114, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 4170, "s": 4154, "text": "$ node main.js\n" }, { "code": null, "e": 4189, "s": 4170, "text": "Verify the Output." } ]
Multiline Strings in Perl
If you want to introduce multiline strings into your programs, you can use the standard single quotes as below − Live Demo #!/usr/bin/perl $string = 'This is a multiline string'; print "$string\n"; This will produce the following result − This is a multiline string You can use "here" document syntax as well to store or print multiline as below − Live Demo #!/usr/bin/perl print <<EOF; This is a multiline string EOF This will also produce the same result − This is a multiline string
[ { "code": null, "e": 1300, "s": 1187, "text": "If you want to introduce multiline strings into your programs, you can use the standard single quotes as below −" }, { "code": null, "e": 1311, "s": 1300, "text": " Live Demo" }, { "code": null, "e": 1386, "s": 1311, "text": "#!/usr/bin/perl\n$string = 'This is\na multiline\nstring';\nprint \"$string\\n\";" }, { "code": null, "e": 1427, "s": 1386, "text": "This will produce the following result −" }, { "code": null, "e": 1454, "s": 1427, "text": "This is\na multiline\nstring" }, { "code": null, "e": 1536, "s": 1454, "text": "You can use \"here\" document syntax as well to store or print multiline as below −" }, { "code": null, "e": 1547, "s": 1536, "text": " Live Demo" }, { "code": null, "e": 1607, "s": 1547, "text": "#!/usr/bin/perl\nprint <<EOF;\nThis is\na multiline\nstring\nEOF" }, { "code": null, "e": 1648, "s": 1607, "text": "This will also produce the same result −" }, { "code": null, "e": 1675, "s": 1648, "text": "This is\na multiline\nstring" } ]
Deploying models to production with TensorFlow model server | by Rishit Dagli | Towards Data Science
Model creation is definitely an important part of AI applications but it is very important to also know what after training. I will be showing how you could serve TensorFlow models over HTTP and HTTPS and do things like model versioning or model server maintenance easily with TF Model Server. You will also see the steps required for this and the process you should follow. We will also take a look at Kubernetes and GKE to autoscale your deployments. All the code used for the demos in this blog post and some additional examples are available at this GitHub repo- github.com I also delivered a talk about this at GDG (Google Developers Group) Ahmedabad, find the recorded version here- The slide deck for the same is available here- bit.ly/tf-server-deck I expect that you have worked with some Deep Learning models and made a few models yourself, it could be with Keras too. This is a very accurate representation of the ideal scenario, your model works well or does a good job in the testing or development set and when you bring it out in the real world or production that is when problems start coming and things start failing. You further need to ensure your model is up and running all the time and your users have an easy way to interact with the model. It should also work well on all platforms be it web, Android, IoS, or embedded systems. You would need to have a resilient pipeline to serve your model and an efficient way to pass data. These are just a few differences between production and development. Package the model So first you would want to get the model and package it in a way that you can use it in a production environment. You ideally would not put a Jupyter notebook in the same format into production, you can if you wanted to but it is generally not advised to do so. Post the model on Cloud Hosted Server Then you would want to host your model on some cloud-hosted server so you can serve your users, provide them the model whenever they need the model. Maintain the server Now that you have posted your model on a cloud-hosted server you also need to maintain it. One of the main things which I refer to while saying you need to maintain the server is autoscaling. You should be able to handle your users if you experience an increase in number in your users maybe by increasing your resources. Global availability Another thing you now want to ensure is that you have a global availability for your models. This also means that your users in a particular region should not face a high amount of latency. API After this you also need to provide a way for your model to interact with your devices, most probably you would provide an API to work with. This API can then be called by you in or maybe someone could call your model and get the predictions back. And you have another thing to maintain and keep running now an API. Model Versioning So tomorrow when you or your team make an update to model, you need to ensure your users get the latest version of your model and we will talk about this in great detail in some time. As an example consider you provide some image classification services you would have to update your models constantly so it can predict with good accuracy the newly available images. Now that you know what it takes to actually deploy your models to a cloud-hosted server or serving your models let us see what TF Model server is and more importantly how it can help you in your use case. TF Serving is a part of TFX or TensorFlow Extended, simply enough TF Extended is an API that is designed to help you to make production-ready, Machine Learning systems. We will only be talking about a specific subpart of TFX called TF serving. So this is all that you would have to do to create a full-fledged ML solution. What I want you to take a look at is that modeling is not the only part and in fact, is not the major process in creating a deployment. TF Serving helps you do the serving infrastructure part easily. So maybe you want to run your models on multiple devices, maybe on mobile devices, on low power embedded systems or on the web. Maybe you could use TF Lite to deploy it on mobile devices and embedded systems or create a JavaScript representation of your model and run it directly on the web. Many times it is a better idea to have a centralized model where your devices can send a response, the server would then execute them and send them back to the device that made the call. Remember we talked about model versioning in an architecture like this you would just need to update your new version of the model at the server and all your devices could instantly have access to it. However, if you used the traditional approach like sending out app updates some users have the new model and some have the old model creating a bad experience. In a cloud-based environment to do so you could use dynamic assignment of resources according to the number of users you have. TF Serving allows you to do this quite easily so you don’t run into issues like “Oh I just updated my model and my server is down!” and things like that. Let’s see this in practice now. Install TF Serving So of course before starting you need to install TF Serving. The code examples for this blog in the repo have the installation commands typed out for you. Installing it is pretty straightforward, find installation steps here. Converting the model So, you already have a model and the first thing you would do is simply save it in a format usable by TF Serving. The third line here directory_path shows your model where to save the model and the other two lines just pass the inputs and the outputs- tf.saved_model.simple_save( keras.backend.get_session(), directory_path, inputs = {'input_image': model.input}, outputs = {i.name: i for i in model.outputs}) If you navigate to the path where you saved this model you would see a directory structure like this, also I made a directory 1which is my model version we will see how TF server helps us manage and deploy these versions. And also note your model is saved in a .pb extension. Saved Model CLI There is another great interface called the saved model CLI which I find pretty useful. This gives you a lot of useful information about your saved model like operation signatures and input-output shapes. !saved_model_cli show --dir [DIR] --all Here is sample output showing the information this tool provides- Starting the model server So here is how you would then start the model server let us break this down- os.environ["MODEL_DIR"] = MODEL_DIR%%bash --bgnohup tensorflow_model_server \ --rest_api_port = 8501 \ --model_name = test \ --model_base_path="${MODEL_DIR}" >server.log 2>&1 So the third line here tells it to use the tensorflow model server, of course you would not include the bash magic cell while implementing it in practice i.e. the code line %bash --bg but as Iassume most of you might use Colab I have added that as Colab doesn’t provide you a direct terminal. The fourth line here specifies the port on which you want to run the TF Model Server and is pretty straightforward too. A thing to noteid that the --model_name will also appear in the URL on which you will be serving your models, so if you have multiple models at action managing your serving model URLs also becomes a lot easier. The last line here specifies that you want to enable logging and sometimes logs are just so helpful while debugging. I have personally used them quite a lot to figure out errors easily. Let us now get to the most interesting part which is performing inference over the model. Passing in data A thing to keep in mind while performing inference over the model is that while passing the data in, your data should be lists of lists and not just lists. This is in fact an added advantage for developers. Let us see what this means- xs = np.array([[case_1], [case_2] ... [case_n]]) Here each of the case_1 , case_2 ... case_n has all the values for your features from x1 , x2 ... xi . Creating a JSON object for the data data = json.dumps({"signature_name": [SIGNATURE], "instances": xs.tolist()}) If you know a bit about saved models, you might know about SignatureDef, for folks who don’t know it defines the signature of a computation supported in a TensorFlow graph. So you can have support for I/O for a function. You can easily find that by the saved_model_cli . In the instances part we will put in the xs we just created. Making an inference request Now you can simply make an inference request- json_response = requests.post( 'http://localhost:8501/v1/models/test:predict', data = data, headers = headers) Remember us talking about versions, not the model URL it contains v1 which allows us to easily specify that we want to use version 1 of the model. You can also see the model name test to be reflected in the URL. Your headers would simply be something like this as you are passing data in as JSON- headers = {"content-type": "application/json"} Images! A lot of you might feel that it would be interesting to see how you would pass in images. It is in fact very easy to do so. In place of case_1 which we saw above, you would just replace that with a list of values that make your image. Now that you know how TF server works and how you could use it. Having known this, here are a few more things it provides. Now you can understand that if let us say you deploy version 2 of your model, in case of any problems your version 1 will still be active and usable. Also while the time your new model version is being deployed you have no downtime, your older version will continue to work just normal and these things are often quite helpful. TF Model server helps you in doing so very easily. Focus on real code A really wonderful part about TF Model Server is to let you focus on writing real code and not worry about infrastructure and managing it and that is something really useful, you do not want to spend time doing these infrastructure things as a developer. This, in turn, allows you to build better ML applications and get them up and running a lot faster. The things we saw now could be well scaled to the cloud making it even more powerful, you could always have your own server we will not be discussing why Cloud or on-premise here or how load balancing takes place. We will see a brief workflow for deploying the model on cloud with Kubernetes. With TF Model Server this becomes a lot easier. Creating a cluster I will start by assuming you have trained a model and built a docker image for it. The steps to doing this are pretty straightforward and I have also listed them in the GitHub repo for this session. So we will start by creating a Kubernetes cluster with 5 nodes and I will be showing you how you can deploy a simple resnetmodel on the cloud so the name. gcloud container clusters create resnet-serving-cluster --num-nodes 5 Pushing the docker image docker tag $USER/resnet_serving gcr.io/[PROJECT_ID]/resnetdocker push gcr.io/[PROJECT_ID]/resnet You can then push your docker image to Container Registry Creating the deployment And with that you are all ready to create a deployment, the YAML file shown here would create the metadata for deployments like your image and the number of replicas you want, I have included a sample for you in the repo. kubectl create -f [yaml] Another thing to keep in mind while performing inference with a model hosted on the Cloud you would now use the external IP to make inference requests instead of the localhost we used earlier. We started out with why it is worth to have a process for deployment. We then saw what is required to deploy your model, versioning, availability, a global nature, infrastructure, and a lot more. We then saw what TF Model server provides us with and why should you choose TF Model server to make deployments. We then saw the process involved with TF Model server. You also saw how it allows you to write real code and not worry about infrastructure, the version wise URLs, and easy management of them. We then moved to see how this could be replicated on the cloud and saw how Kubernetes could make this easy for us. I have included a few notebooks for you which implement all that you saw in this post, try them out for yourself. Hi everyone I am Rishit Dagli Twitter Website If you want to ask me some questions, report any mistake, suggest improvements, give feedback you are free to do so by emailing me at —
[ { "code": null, "e": 625, "s": 172, "text": "Model creation is definitely an important part of AI applications but it is very important to also know what after training. I will be showing how you could serve TensorFlow models over HTTP and HTTPS and do things like model versioning or model server maintenance easily with TF Model Server. You will also see the steps required for this and the process you should follow. We will also take a look at Kubernetes and GKE to autoscale your deployments." }, { "code": null, "e": 739, "s": 625, "text": "All the code used for the demos in this blog post and some additional examples are available at this GitHub repo-" }, { "code": null, "e": 750, "s": 739, "text": "github.com" }, { "code": null, "e": 861, "s": 750, "text": "I also delivered a talk about this at GDG (Google Developers Group) Ahmedabad, find the recorded version here-" }, { "code": null, "e": 930, "s": 861, "text": "The slide deck for the same is available here- bit.ly/tf-server-deck" }, { "code": null, "e": 1051, "s": 930, "text": "I expect that you have worked with some Deep Learning models and made a few models yourself, it could be with Keras too." }, { "code": null, "e": 1692, "s": 1051, "text": "This is a very accurate representation of the ideal scenario, your model works well or does a good job in the testing or development set and when you bring it out in the real world or production that is when problems start coming and things start failing. You further need to ensure your model is up and running all the time and your users have an easy way to interact with the model. It should also work well on all platforms be it web, Android, IoS, or embedded systems. You would need to have a resilient pipeline to serve your model and an efficient way to pass data. These are just a few differences between production and development." }, { "code": null, "e": 1710, "s": 1692, "text": "Package the model" }, { "code": null, "e": 1972, "s": 1710, "text": "So first you would want to get the model and package it in a way that you can use it in a production environment. You ideally would not put a Jupyter notebook in the same format into production, you can if you wanted to but it is generally not advised to do so." }, { "code": null, "e": 2010, "s": 1972, "text": "Post the model on Cloud Hosted Server" }, { "code": null, "e": 2159, "s": 2010, "text": "Then you would want to host your model on some cloud-hosted server so you can serve your users, provide them the model whenever they need the model." }, { "code": null, "e": 2179, "s": 2159, "text": "Maintain the server" }, { "code": null, "e": 2501, "s": 2179, "text": "Now that you have posted your model on a cloud-hosted server you also need to maintain it. One of the main things which I refer to while saying you need to maintain the server is autoscaling. You should be able to handle your users if you experience an increase in number in your users maybe by increasing your resources." }, { "code": null, "e": 2521, "s": 2501, "text": "Global availability" }, { "code": null, "e": 2711, "s": 2521, "text": "Another thing you now want to ensure is that you have a global availability for your models. This also means that your users in a particular region should not face a high amount of latency." }, { "code": null, "e": 2715, "s": 2711, "text": "API" }, { "code": null, "e": 3031, "s": 2715, "text": "After this you also need to provide a way for your model to interact with your devices, most probably you would provide an API to work with. This API can then be called by you in or maybe someone could call your model and get the predictions back. And you have another thing to maintain and keep running now an API." }, { "code": null, "e": 3048, "s": 3031, "text": "Model Versioning" }, { "code": null, "e": 3415, "s": 3048, "text": "So tomorrow when you or your team make an update to model, you need to ensure your users get the latest version of your model and we will talk about this in great detail in some time. As an example consider you provide some image classification services you would have to update your models constantly so it can predict with good accuracy the newly available images." }, { "code": null, "e": 3620, "s": 3415, "text": "Now that you know what it takes to actually deploy your models to a cloud-hosted server or serving your models let us see what TF Model server is and more importantly how it can help you in your use case." }, { "code": null, "e": 3864, "s": 3620, "text": "TF Serving is a part of TFX or TensorFlow Extended, simply enough TF Extended is an API that is designed to help you to make production-ready, Machine Learning systems. We will only be talking about a specific subpart of TFX called TF serving." }, { "code": null, "e": 4143, "s": 3864, "text": "So this is all that you would have to do to create a full-fledged ML solution. What I want you to take a look at is that modeling is not the only part and in fact, is not the major process in creating a deployment. TF Serving helps you do the serving infrastructure part easily." }, { "code": null, "e": 4622, "s": 4143, "text": "So maybe you want to run your models on multiple devices, maybe on mobile devices, on low power embedded systems or on the web. Maybe you could use TF Lite to deploy it on mobile devices and embedded systems or create a JavaScript representation of your model and run it directly on the web. Many times it is a better idea to have a centralized model where your devices can send a response, the server would then execute them and send them back to the device that made the call." }, { "code": null, "e": 5110, "s": 4622, "text": "Remember we talked about model versioning in an architecture like this you would just need to update your new version of the model at the server and all your devices could instantly have access to it. However, if you used the traditional approach like sending out app updates some users have the new model and some have the old model creating a bad experience. In a cloud-based environment to do so you could use dynamic assignment of resources according to the number of users you have." }, { "code": null, "e": 5296, "s": 5110, "text": "TF Serving allows you to do this quite easily so you don’t run into issues like “Oh I just updated my model and my server is down!” and things like that. Let’s see this in practice now." }, { "code": null, "e": 5315, "s": 5296, "text": "Install TF Serving" }, { "code": null, "e": 5541, "s": 5315, "text": "So of course before starting you need to install TF Serving. The code examples for this blog in the repo have the installation commands typed out for you. Installing it is pretty straightforward, find installation steps here." }, { "code": null, "e": 5562, "s": 5541, "text": "Converting the model" }, { "code": null, "e": 5814, "s": 5562, "text": "So, you already have a model and the first thing you would do is simply save it in a format usable by TF Serving. The third line here directory_path shows your model where to save the model and the other two lines just pass the inputs and the outputs-" }, { "code": null, "e": 5984, "s": 5814, "text": "tf.saved_model.simple_save( keras.backend.get_session(), directory_path, inputs = {'input_image': model.input}, outputs = {i.name: i for i in model.outputs})" }, { "code": null, "e": 6260, "s": 5984, "text": "If you navigate to the path where you saved this model you would see a directory structure like this, also I made a directory 1which is my model version we will see how TF server helps us manage and deploy these versions. And also note your model is saved in a .pb extension." }, { "code": null, "e": 6276, "s": 6260, "text": "Saved Model CLI" }, { "code": null, "e": 6481, "s": 6276, "text": "There is another great interface called the saved model CLI which I find pretty useful. This gives you a lot of useful information about your saved model like operation signatures and input-output shapes." }, { "code": null, "e": 6521, "s": 6481, "text": "!saved_model_cli show --dir [DIR] --all" }, { "code": null, "e": 6587, "s": 6521, "text": "Here is sample output showing the information this tool provides-" }, { "code": null, "e": 6613, "s": 6587, "text": "Starting the model server" }, { "code": null, "e": 6690, "s": 6613, "text": "So here is how you would then start the model server let us break this down-" }, { "code": null, "e": 6874, "s": 6690, "text": "os.environ[\"MODEL_DIR\"] = MODEL_DIR%%bash --bgnohup tensorflow_model_server \\ --rest_api_port = 8501 \\ --model_name = test \\ --model_base_path=\"${MODEL_DIR}\" >server.log 2>&1" }, { "code": null, "e": 7167, "s": 6874, "text": "So the third line here tells it to use the tensorflow model server, of course you would not include the bash magic cell while implementing it in practice i.e. the code line %bash --bg but as Iassume most of you might use Colab I have added that as Colab doesn’t provide you a direct terminal." }, { "code": null, "e": 7287, "s": 7167, "text": "The fourth line here specifies the port on which you want to run the TF Model Server and is pretty straightforward too." }, { "code": null, "e": 7498, "s": 7287, "text": "A thing to noteid that the --model_name will also appear in the URL on which you will be serving your models, so if you have multiple models at action managing your serving model URLs also becomes a lot easier." }, { "code": null, "e": 7684, "s": 7498, "text": "The last line here specifies that you want to enable logging and sometimes logs are just so helpful while debugging. I have personally used them quite a lot to figure out errors easily." }, { "code": null, "e": 7774, "s": 7684, "text": "Let us now get to the most interesting part which is performing inference over the model." }, { "code": null, "e": 7790, "s": 7774, "text": "Passing in data" }, { "code": null, "e": 8025, "s": 7790, "text": "A thing to keep in mind while performing inference over the model is that while passing the data in, your data should be lists of lists and not just lists. This is in fact an added advantage for developers. Let us see what this means-" }, { "code": null, "e": 8074, "s": 8025, "text": "xs = np.array([[case_1], [case_2] ... [case_n]])" }, { "code": null, "e": 8177, "s": 8074, "text": "Here each of the case_1 , case_2 ... case_n has all the values for your features from x1 , x2 ... xi ." }, { "code": null, "e": 8213, "s": 8177, "text": "Creating a JSON object for the data" }, { "code": null, "e": 8308, "s": 8213, "text": "data = json.dumps({\"signature_name\": [SIGNATURE], \"instances\": xs.tolist()})" }, { "code": null, "e": 8640, "s": 8308, "text": "If you know a bit about saved models, you might know about SignatureDef, for folks who don’t know it defines the signature of a computation supported in a TensorFlow graph. So you can have support for I/O for a function. You can easily find that by the saved_model_cli . In the instances part we will put in the xs we just created." }, { "code": null, "e": 8668, "s": 8640, "text": "Making an inference request" }, { "code": null, "e": 8714, "s": 8668, "text": "Now you can simply make an inference request-" }, { "code": null, "e": 8843, "s": 8714, "text": "json_response = requests.post( 'http://localhost:8501/v1/models/test:predict', data = data, headers = headers)" }, { "code": null, "e": 9055, "s": 8843, "text": "Remember us talking about versions, not the model URL it contains v1 which allows us to easily specify that we want to use version 1 of the model. You can also see the model name test to be reflected in the URL." }, { "code": null, "e": 9140, "s": 9055, "text": "Your headers would simply be something like this as you are passing data in as JSON-" }, { "code": null, "e": 9187, "s": 9140, "text": "headers = {\"content-type\": \"application/json\"}" }, { "code": null, "e": 9195, "s": 9187, "text": "Images!" }, { "code": null, "e": 9430, "s": 9195, "text": "A lot of you might feel that it would be interesting to see how you would pass in images. It is in fact very easy to do so. In place of case_1 which we saw above, you would just replace that with a list of values that make your image." }, { "code": null, "e": 9703, "s": 9430, "text": "Now that you know how TF server works and how you could use it. Having known this, here are a few more things it provides. Now you can understand that if let us say you deploy version 2 of your model, in case of any problems your version 1 will still be active and usable." }, { "code": null, "e": 9932, "s": 9703, "text": "Also while the time your new model version is being deployed you have no downtime, your older version will continue to work just normal and these things are often quite helpful. TF Model server helps you in doing so very easily." }, { "code": null, "e": 9951, "s": 9932, "text": "Focus on real code" }, { "code": null, "e": 10306, "s": 9951, "text": "A really wonderful part about TF Model Server is to let you focus on writing real code and not worry about infrastructure and managing it and that is something really useful, you do not want to spend time doing these infrastructure things as a developer. This, in turn, allows you to build better ML applications and get them up and running a lot faster." }, { "code": null, "e": 10647, "s": 10306, "text": "The things we saw now could be well scaled to the cloud making it even more powerful, you could always have your own server we will not be discussing why Cloud or on-premise here or how load balancing takes place. We will see a brief workflow for deploying the model on cloud with Kubernetes. With TF Model Server this becomes a lot easier." }, { "code": null, "e": 10666, "s": 10647, "text": "Creating a cluster" }, { "code": null, "e": 11020, "s": 10666, "text": "I will start by assuming you have trained a model and built a docker image for it. The steps to doing this are pretty straightforward and I have also listed them in the GitHub repo for this session. So we will start by creating a Kubernetes cluster with 5 nodes and I will be showing you how you can deploy a simple resnetmodel on the cloud so the name." }, { "code": null, "e": 11096, "s": 11020, "text": "gcloud container clusters create resnet-serving-cluster --num-nodes 5" }, { "code": null, "e": 11121, "s": 11096, "text": "Pushing the docker image" }, { "code": null, "e": 11227, "s": 11121, "text": "docker tag $USER/resnet_serving gcr.io/[PROJECT_ID]/resnetdocker push gcr.io/[PROJECT_ID]/resnet" }, { "code": null, "e": 11285, "s": 11227, "text": "You can then push your docker image to Container Registry" }, { "code": null, "e": 11309, "s": 11285, "text": "Creating the deployment" }, { "code": null, "e": 11531, "s": 11309, "text": "And with that you are all ready to create a deployment, the YAML file shown here would create the metadata for deployments like your image and the number of replicas you want, I have included a sample for you in the repo." }, { "code": null, "e": 11556, "s": 11531, "text": "kubectl create -f [yaml]" }, { "code": null, "e": 11749, "s": 11556, "text": "Another thing to keep in mind while performing inference with a model hosted on the Cloud you would now use the external IP to make inference requests instead of the localhost we used earlier." }, { "code": null, "e": 12366, "s": 11749, "text": "We started out with why it is worth to have a process for deployment. We then saw what is required to deploy your model, versioning, availability, a global nature, infrastructure, and a lot more. We then saw what TF Model server provides us with and why should you choose TF Model server to make deployments. We then saw the process involved with TF Model server. You also saw how it allows you to write real code and not worry about infrastructure, the version wise URLs, and easy management of them. We then moved to see how this could be replicated on the cloud and saw how Kubernetes could make this easy for us." }, { "code": null, "e": 12480, "s": 12366, "text": "I have included a few notebooks for you which implement all that you saw in this post, try them out for yourself." }, { "code": null, "e": 12510, "s": 12480, "text": "Hi everyone I am Rishit Dagli" }, { "code": null, "e": 12518, "s": 12510, "text": "Twitter" }, { "code": null, "e": 12526, "s": 12518, "text": "Website" } ]
How to check if array contains a duplicate number using C#?
Firstly, set an array − int[] arr = { 87, 55, 23, 87, 45, 23, 98 }; Now declare a dictionary and loop through the array and get the count of all the elements. The value you get from the dictionary displays the occurrence of numbers − foreach(var count in arr) { if (dict.ContainsKey(count)) dict[count]++; else dict[count] = 1; } Let us see the complete example − using System; using System.Collections.Generic; namespace Demo { public class Program { public static void Main(string[] args) { int[] arr = { 87, 55, 23, 87, 45, 23, 98 }; var dict = new Dictionary < int, int > (); foreach(var count in arr) { if (dict.ContainsKey(count)) dict[count]++; else dict[count] = 1; } foreach(var val in dict) Console.WriteLine("{0} occurred {1} times", val.Key, val.Value); } } }
[ { "code": null, "e": 1086, "s": 1062, "text": "Firstly, set an array −" }, { "code": null, "e": 1151, "s": 1086, "text": "int[] arr = {\n 87,\n 55,\n 23,\n 87,\n 45,\n 23,\n 98\n};" }, { "code": null, "e": 1317, "s": 1151, "text": "Now declare a dictionary and loop through the array and get the count of all the elements. The value you get from the dictionary displays the occurrence of numbers −" }, { "code": null, "e": 1425, "s": 1317, "text": "foreach(var count in arr) {\n if (dict.ContainsKey(count))\n dict[count]++;\n else\n dict[count] = 1;\n}" }, { "code": null, "e": 1459, "s": 1425, "text": "Let us see the complete example −" }, { "code": null, "e": 2086, "s": 1459, "text": "using System;\nusing System.Collections.Generic;\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n \n int[] arr = {\n 87,\n 55,\n 23,\n 87,\n 45,\n 23,\n 98\n };\n var dict = new Dictionary < int, int > ();\n foreach(var count in arr) {\n if (dict.ContainsKey(count))\n dict[count]++;\n else\n dict[count] = 1;\n }\n foreach(var val in dict)\n Console.WriteLine(\"{0} occurred {1} times\", val.Key, val.Value);\n }\n }\n}" } ]
Java Program to Check If a Number is Spy number or not - GeeksforGeeks
04 Jan, 2021 A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. For performing the task we need to reverse through the number which will take log(N) time. Example: Input : 22 Output: Given number is a SPY number. Explanation: Sum of the number is 4 (2 + 2) Product of the number is as 4 (2 * 2) Input : 1241 Output: Given number is not a SPY number. Approach: Calculate the sum of digits of the input Number. Calculate the product of digits of the input Number. If the sum of digits equals the product of digits then the number is Spy number otherwise not. Calculate the sum of digits of the input Number. Calculate the product of digits of the input Number. If the sum of digits equals the product of digits then the number is Spy number otherwise not. Below is the implementation of the above approach: Java // Java Program to Check If a Number is Spy number or not import java.io.*; class GFG { public static void main(String[] args) { int product = 1, sum = 0, ld; int n = 22; // calculate sum and product of the number here. while (n > 0) { ld = n % 10; sum = sum + ld; product = product * ld; n = n / 10; } // compare the sum and product. if (sum == product) System.out.println( "Given number is spy number"); else System.out.println( "Given number is not spy number"); } } Given number is spy number Complexity: O(log(n)) Picked Java Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23629, "s": 23598, "text": " \n04 Jan, 2021\n" }, { "code": null, "e": 23824, "s": 23629, "text": "A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. For performing the task we need to reverse through the number which will take log(N) time." }, { "code": null, "e": 23835, "s": 23824, "text": " Example:" }, { "code": null, "e": 24037, "s": 23835, "text": "Input : 22\nOutput: Given number is a SPY number.\nExplanation: Sum of the number is 4 (2 + 2)\n Product of the number is as 4 (2 * 2) \nInput : 1241\nOutput: Given number is not a SPY number." }, { "code": null, "e": 24047, "s": 24037, "text": "Approach:" }, { "code": null, "e": 24246, "s": 24047, "text": "\nCalculate the sum of digits of the input Number.\nCalculate the product of digits of the input Number.\nIf the sum of digits equals the product of digits then the number is Spy number otherwise not.\n" }, { "code": null, "e": 24295, "s": 24246, "text": "Calculate the sum of digits of the input Number." }, { "code": null, "e": 24348, "s": 24295, "text": "Calculate the product of digits of the input Number." }, { "code": null, "e": 24443, "s": 24348, "text": "If the sum of digits equals the product of digits then the number is Spy number otherwise not." }, { "code": null, "e": 24494, "s": 24443, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 24499, "s": 24494, "text": "Java" }, { "code": "\n\n\n\n\n\n\n// Java Program to Check If a Number is Spy number or not \nimport java.io.*; \n \nclass GFG { \n public static void main(String[] args) \n { \n int product = 1, sum = 0, ld; \n int n = 22; \n \n // calculate sum and product of the number here. \n while (n > 0) { \n ld = n % 10; \n sum = sum + ld; \n product = product * ld; \n n = n / 10; \n } \n \n // compare the sum and product. \n if (sum == product) \n System.out.println( \n \"Given number is spy number\"); \n else\n System.out.println( \n \"Given number is not spy number\"); \n } \n}\n\n\n\n\n\n", "e": 25202, "s": 24509, "text": null }, { "code": null, "e": 25230, "s": 25202, "text": "Given number is spy number\n" }, { "code": null, "e": 25252, "s": 25230, "text": "Complexity: O(log(n))" }, { "code": null, "e": 25261, "s": 25252, "text": "\nPicked\n" }, { "code": null, "e": 25268, "s": 25261, "text": "\nJava\n" }, { "code": null, "e": 25284, "s": 25268, "text": "\nJava Programs\n" }, { "code": null, "e": 25489, "s": 25284, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 25519, "s": 25489, "text": "Functional Interfaces in Java" }, { "code": null, "e": 25534, "s": 25519, "text": "Stream In Java" }, { "code": null, "e": 25555, "s": 25534, "text": "Constructors in Java" }, { "code": null, "e": 25601, "s": 25555, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25620, "s": 25601, "text": "Exceptions in Java" }, { "code": null, "e": 25664, "s": 25620, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 25690, "s": 25664, "text": "Java Programming Examples" }, { "code": null, "e": 25724, "s": 25690, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 25771, "s": 25724, "text": "Implementing a Linked List in Java using Class" } ]
How to iterate over dictionaries using 'for' loops in Python?
Even though dictionary itself is not an iterable object, the items(), keys() and values methods return iterable view objects which can be used to iterate through dictionary. The items() method returns a list of tuples, each tuple being key and value pair. >>> d1={'name': 'Ravi', 'age': 23, 'marks': 56} >>> for t in d1.items(): print (t) ('name', 'Ravi') ('age', 23) ('marks', 56) Key and value out of each pair can be separately stored in two variables and traversed like this − >>> d1={'name': 'Ravi', 'age': 23, 'marks': 56} >>> for k,v in d1.items(): print (k,v) name Ravi age 23 marks 56 Using iterable of keys() method each key and associated value can be obtained as follows − >>> for k in d1.keys(): print (k, d1.get(k)) name Ravi age 23 marks 56
[ { "code": null, "e": 1236, "s": 1062, "text": "Even though dictionary itself is not an iterable object, the items(), keys() and values methods return iterable view objects which can be used to iterate through dictionary." }, { "code": null, "e": 1318, "s": 1236, "text": "The items() method returns a list of tuples, each tuple being key and value pair." }, { "code": null, "e": 1445, "s": 1318, "text": ">>> d1={'name': 'Ravi', 'age': 23, 'marks': 56}\n>>> for t in d1.items():\nprint (t)\n\n('name', 'Ravi')\n('age', 23)\n('marks', 56)" }, { "code": null, "e": 1544, "s": 1445, "text": "Key and value out of each pair can be separately stored in two variables and traversed like this −" }, { "code": null, "e": 1658, "s": 1544, "text": ">>> d1={'name': 'Ravi', 'age': 23, 'marks': 56}\n>>> for k,v in d1.items():\nprint (k,v)\n\nname Ravi\nage 23\nmarks 56" }, { "code": null, "e": 1749, "s": 1658, "text": "Using iterable of keys() method each key and associated value can be obtained as follows −" }, { "code": null, "e": 1822, "s": 1749, "text": ">>> for k in d1.keys():\nprint (k, d1.get(k))\n\nname Ravi\nage 23\nmarks 56\n" } ]
Matplotlib.figure.Figure.colorbar() in Python
30 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements. The colorbar() method of figure module of matplotlib library is used to add a colorbar to a plot. Syntax: colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw) Parameters: This accept the following parameters that are described below: mappable: This parameter is mandatory for the Figure.colorbar method. cax : This parameter is the Axes into which the colorbar will be drawn. ax : This parameter is the parent axes from which space for a new colorbar axes will be stolen. use_gridspec : This parameter is used to create an instance of Subplot using the gridspec module. Returns: This method does not return any value. Below examples illustrate the matplotlib.figure.Figure.colorbar() function in matplotlib.figure: Example 1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as mtriimport numpy as np # Create triangulation.x = np.asarray([0, 1, 2, 3, 0.5, 1.5, 2.5, 1, 2, 1.5]) y = np.asarray([0, 0, 0, 0, 1.0, 1.0, 1.0, 2, 2, 3.0]) triangles = [[0, 1, 4], [1, 5, 4], [2, 6, 5], [4, 5, 7], [5, 6, 8], [5, 8, 7], [7, 8, 9], [1, 2, 5], [2, 3, 6]] triang = mtri.Triangulation(x, y, triangles)z = np.cos(3 * x) * np.cos(6 * y)+np.sin(6 * x) fig, axs = plt.subplots()t = axs.tricontourf(triang, z)axs.tricontour(triang, z, colors ='white')fig.colorbar(t) fig.suptitle('matplotlib.figure.Figure.colorbar() \function Example\n\n', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np n_angles = 26n_radii = 10min_radius = 0.35radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint = False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis = 1) angles[:, 1::2] += np.pi / n_angles x = (10 * radii * np.cos(angles)).flatten()y = (10 * radii * np.sin(angles)).flatten()z = (np.cos(4 * radii) * np.cos(3 * angles)).flatten() triang = tri.Triangulation(x, y) triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < min_radius) fig1, ax1 = plt.subplots()ax1.set_aspect('equal')tcf = ax1.tricontourf(triang, z)fig1.colorbar(tcf)ax1.tricontour(triang, z, colors ='g') fig1.suptitle('matplotlib.figure.Figure.colorbar()\function Example\n\n', fontweight ="bold") plt.show() Output: Matplotlib figure-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2020" }, { "code": null, "e": 339, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements." }, { "code": null, "e": 437, "s": 339, "text": "The colorbar() method of figure module of matplotlib library is used to add a colorbar to a plot." }, { "code": null, "e": 514, "s": 437, "text": "Syntax: colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw)" }, { "code": null, "e": 589, "s": 514, "text": "Parameters: This accept the following parameters that are described below:" }, { "code": null, "e": 659, "s": 589, "text": "mappable: This parameter is mandatory for the Figure.colorbar method." }, { "code": null, "e": 731, "s": 659, "text": "cax : This parameter is the Axes into which the colorbar will be drawn." }, { "code": null, "e": 827, "s": 731, "text": "ax : This parameter is the parent axes from which space for a new colorbar axes will be stolen." }, { "code": null, "e": 925, "s": 827, "text": "use_gridspec : This parameter is used to create an instance of Subplot using the gridspec module." }, { "code": null, "e": 973, "s": 925, "text": "Returns: This method does not return any value." }, { "code": null, "e": 1070, "s": 973, "text": "Below examples illustrate the matplotlib.figure.Figure.colorbar() function in matplotlib.figure:" }, { "code": null, "e": 1081, "s": 1070, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as mtriimport numpy as np # Create triangulation.x = np.asarray([0, 1, 2, 3, 0.5, 1.5, 2.5, 1, 2, 1.5]) y = np.asarray([0, 0, 0, 0, 1.0, 1.0, 1.0, 2, 2, 3.0]) triangles = [[0, 1, 4], [1, 5, 4], [2, 6, 5], [4, 5, 7], [5, 6, 8], [5, 8, 7], [7, 8, 9], [1, 2, 5], [2, 3, 6]] triang = mtri.Triangulation(x, y, triangles)z = np.cos(3 * x) * np.cos(6 * y)+np.sin(6 * x) fig, axs = plt.subplots()t = axs.tricontourf(triang, z)axs.tricontour(triang, z, colors ='white')fig.colorbar(t) fig.suptitle('matplotlib.figure.Figure.colorbar() \\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 1883, "s": 1081, "text": null }, { "code": null, "e": 1891, "s": 1883, "text": "Output:" }, { "code": null, "e": 1902, "s": 1891, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np n_angles = 26n_radii = 10min_radius = 0.35radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * np.pi, n_angles, endpoint = False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis = 1) angles[:, 1::2] += np.pi / n_angles x = (10 * radii * np.cos(angles)).flatten()y = (10 * radii * np.sin(angles)).flatten()z = (np.cos(4 * radii) * np.cos(3 * angles)).flatten() triang = tri.Triangulation(x, y) triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < min_radius) fig1, ax1 = plt.subplots()ax1.set_aspect('equal')tcf = ax1.tricontourf(triang, z)fig1.colorbar(tcf)ax1.tricontour(triang, z, colors ='g') fig1.suptitle('matplotlib.figure.Figure.colorbar()\\function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 2972, "s": 1902, "text": null }, { "code": null, "e": 2980, "s": 2972, "text": "Output:" }, { "code": null, "e": 3004, "s": 2980, "text": "Matplotlib figure-class" }, { "code": null, "e": 3022, "s": 3004, "text": "Python-matplotlib" }, { "code": null, "e": 3029, "s": 3022, "text": "Python" } ]
numpy.sinh() in Python
04 Dec, 2020 The numpy.sinh() is a mathematical function that helps user to calculate hyperbolic sine for all x(being the array elements). Equivalent to 1/2 * (np.exp(x) – np.exp(-x)) or -1j * np.sin(1j*x). Syntax: numpy.sinh(x[, out]) = ufunc ‘sin’)Parameters : array : [array_like] elements are in radians.2pi Radians = 36o degrees Return : An array with hyperbolic sine of x for all x i.e. array elements Code #1 : Working # Python3 program explaining# sinh() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print ("Input array : \n", in_array) Sinh_Values = np.sinh(in_array)print ("\nSine Hyperbolic values : \n", Sinh_Values) Output : Input array : [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793] Sine Hyperbolic values : [ 0. 2.3012989 1.24936705 11.54873936] Code #2 : Graphical representation # Python program showing Graphical# representation of sinh() functionimport numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array = np.sinh(in_array) print("in_array : ", in_array)print("\nout_array : ", out_array) # red for numpy.sinh()plt.plot(in_array, out_array, color = 'red', marker = "o")plt.title("numpy.sinh()")plt.xlabel("X")plt.ylabel("Y")plt.show() Output : in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265] out_array : [-11.54873936 -6.49723393 -3.62383424 -1.9652737 -0.96554336 -0.28949778 0.28949778 0.96554336 1.9652737 3.62383424 6.49723393 11.54873936] References :https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.sinh.html#numpy.sinh. Python numpy-Mathematical Function Python-numpy 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 Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2020" }, { "code": null, "e": 154, "s": 28, "text": "The numpy.sinh() is a mathematical function that helps user to calculate hyperbolic sine for all x(being the array elements)." }, { "code": null, "e": 222, "s": 154, "text": "Equivalent to 1/2 * (np.exp(x) – np.exp(-x)) or -1j * np.sin(1j*x)." }, { "code": null, "e": 278, "s": 222, "text": "Syntax: numpy.sinh(x[, out]) = ufunc ‘sin’)Parameters :" }, { "code": null, "e": 349, "s": 278, "text": "array : [array_like] elements are in radians.2pi Radians = 36o degrees" }, { "code": null, "e": 423, "s": 349, "text": "Return : An array with hyperbolic sine of x for all x i.e. array elements" }, { "code": null, "e": 442, "s": 423, "text": " Code #1 : Working" }, { "code": "# Python3 program explaining# sinh() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print (\"Input array : \\n\", in_array) Sinh_Values = np.sinh(in_array)print (\"\\nSine Hyperbolic values : \\n\", Sinh_Values)", "e": 687, "s": 442, "text": null }, { "code": null, "e": 696, "s": 687, "text": "Output :" }, { "code": null, "e": 858, "s": 696, "text": "Input array : \n [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]\n\nSine Hyperbolic values : \n [ 0. 2.3012989 1.24936705 11.54873936]\n" }, { "code": null, "e": 894, "s": 858, "text": " Code #2 : Graphical representation" }, { "code": "# Python program showing Graphical# representation of sinh() functionimport numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-np.pi, np.pi, 12)out_array = np.sinh(in_array) print(\"in_array : \", in_array)print(\"\\nout_array : \", out_array) # red for numpy.sinh()plt.plot(in_array, out_array, color = 'red', marker = \"o\")plt.title(\"numpy.sinh()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show()", "e": 1298, "s": 894, "text": null }, { "code": null, "e": 1307, "s": 1298, "text": "Output :" }, { "code": null, "e": 1640, "s": 1307, "text": "in_array : [-3.14159265 -2.57039399 -1.99919533 -1.42799666 -0.856798 -0.28559933\n 0.28559933 0.856798 1.42799666 1.99919533 2.57039399 3.14159265]\n\nout_array : [-11.54873936 -6.49723393 -3.62383424 -1.9652737 -0.96554336\n -0.28949778 0.28949778 0.96554336 1.9652737 3.62383424\n 6.49723393 11.54873936]" }, { "code": null, "e": 1741, "s": 1640, "text": " References :https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.sinh.html#numpy.sinh." }, { "code": null, "e": 1776, "s": 1741, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 1789, "s": 1776, "text": "Python-numpy" }, { "code": null, "e": 1796, "s": 1789, "text": "Python" }, { "code": null, "e": 1894, "s": 1796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1926, "s": 1894, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1953, "s": 1926, "text": "Python Classes and Objects" }, { "code": null, "e": 1974, "s": 1953, "text": "Python OOPs Concepts" }, { "code": null, "e": 2005, "s": 1974, "text": "Python | os.path.join() method" }, { "code": null, "e": 2061, "s": 2005, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2084, "s": 2061, "text": "Introduction To PYTHON" }, { "code": null, "e": 2126, "s": 2084, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2168, "s": 2126, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2207, "s": 2168, "text": "Python | datetime.timedelta() function" } ]
How to validate email address using RegExp in JavaScript ?
20 Sep, 2019 Given an email id and the task is to validate the email id is valid or not. The validation of email is done with the help of Regular Expressions. Approach 1: RegExp – It checks for the valid characters in the Email-Id (like, numbers, alphabets, few special characters.) It is allowing every special symbol in the email-id (like, !, #, $, %, ^, &, *) symbols in the Email-Id but not allowing the second @ symbol in ID. Example: This example implements the above approach. <!DOCTYPE html> <html> <head> <title> How to validate email address using RegExp in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var email = 'GeeksForGeeks@gmail.com'; up.innerHTML = "Click on the button to check the " + "validity of Email Id.<br>" + email; function isEmail(email) { // Regular Expression (Not accepts second @ symbol // before the @gmail.com and accepts everything else) var regexp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; // Converting the email to lowercase return regexp.test(String(email).toLowerCase()); } function GFG_Fun() { down.innerHTML = isEmail(email); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: RegExp – It checks for the pattern like anything@anything.anything Not like the previous example, RegExp is accepting every character along with special character multiple times. Example 2: This example implements the above approach. <!DOCTYPE HTML> <html> <head> <title> How to validate email address using RegExp in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var email = 'Gee%E^%ksForGeeks@gmail.com'; up.innerHTML = "Click on the button to check the " + "validity of Email Id.<br>" + email; function isEmail(email) { // Regular Expression (Accepts every special // character along with @ symbol) var regexp = /\S+@\S+\.\S+/; // Converting the email to lowercase return regexp.test(String(email).toLowerCase()); } function GFG_Fun() { down.innerHTML = isEmail(email); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Sep, 2019" }, { "code": null, "e": 174, "s": 28, "text": "Given an email id and the task is to validate the email id is valid or not. The validation of email is done with the help of Regular Expressions." }, { "code": null, "e": 186, "s": 174, "text": "Approach 1:" }, { "code": null, "e": 298, "s": 186, "text": "RegExp – It checks for the valid characters in the Email-Id (like, numbers, alphabets, few special characters.)" }, { "code": null, "e": 446, "s": 298, "text": "It is allowing every special symbol in the email-id (like, !, #, $, %, ^, &, *) symbols in the Email-Id but not allowing the second @ symbol in ID." }, { "code": null, "e": 499, "s": 446, "text": "Example: This example implements the above approach." }, { "code": "<!DOCTYPE html> <html> <head> <title> How to validate email address using RegExp in JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var email = 'GeeksForGeeks@gmail.com'; up.innerHTML = \"Click on the button to check the \" + \"validity of Email Id.<br>\" + email; function isEmail(email) { // Regular Expression (Not accepts second @ symbol // before the @gmail.com and accepts everything else) var regexp = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; // Converting the email to lowercase return regexp.test(String(email).toLowerCase()); } function GFG_Fun() { down.innerHTML = isEmail(email); } </script> </body> </html>", "e": 1938, "s": 499, "text": null }, { "code": null, "e": 1946, "s": 1938, "text": "Output:" }, { "code": null, "e": 1977, "s": 1946, "text": "Before clicking on the button:" }, { "code": null, "e": 2007, "s": 1977, "text": "After clicking on the button:" }, { "code": null, "e": 2019, "s": 2007, "text": "Approach 2:" }, { "code": null, "e": 2086, "s": 2019, "text": "RegExp – It checks for the pattern like anything@anything.anything" }, { "code": null, "e": 2198, "s": 2086, "text": "Not like the previous example, RegExp is accepting every character along with special character multiple times." }, { "code": null, "e": 2253, "s": 2198, "text": "Example 2: This example implements the above approach." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to validate email address using RegExp in JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var email = 'Gee%E^%ksForGeeks@gmail.com'; up.innerHTML = \"Click on the button to check the \" + \"validity of Email Id.<br>\" + email; function isEmail(email) { // Regular Expression (Accepts every special // character along with @ symbol) var regexp = /\\S+@\\S+\\.\\S+/; // Converting the email to lowercase return regexp.test(String(email).toLowerCase()); } function GFG_Fun() { down.innerHTML = isEmail(email); } </script> </body> </html>", "e": 3529, "s": 2253, "text": null }, { "code": null, "e": 3537, "s": 3529, "text": "Output:" }, { "code": null, "e": 3568, "s": 3537, "text": "Before clicking on the button:" }, { "code": null, "e": 3598, "s": 3568, "text": "After clicking on the button:" }, { "code": null, "e": 3609, "s": 3598, "text": "JavaScript" }, { "code": null, "e": 3626, "s": 3609, "text": "Web Technologies" }, { "code": null, "e": 3653, "s": 3626, "text": "Web technologies Questions" } ]