title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
What is the class "class" in Java?
|
The Java.lang.Class class instance represent classes and interfaces in a running Java application. It has no public constructor.
Following is the example demonstrates the usage of the class Class.
The java.lang.Class.getCanonicalName() method returns the canonical name of the underlying class as defined by the Java Language Specification. It returns null if the class does not have a canonical name.
Live Demo
import java.lang.*;
public class ClassDemo {
public static void main(String[] args) {
ClassDemo c = new ClassDemo();
Class cls = c.getClass();
//Returns the canonical name of the underlying class if it exists
System.out.println("Class = " + cls.getCanonicalName());
}
}
Class = com.tutorialspoint.ClassDemo
|
[
{
"code": null,
"e": 1191,
"s": 1062,
"text": "The Java.lang.Class class instance represent classes and interfaces in a running Java application. It has no public constructor."
},
{
"code": null,
"e": 1259,
"s": 1191,
"text": "Following is the example demonstrates the usage of the class Class."
},
{
"code": null,
"e": 1464,
"s": 1259,
"text": "The java.lang.Class.getCanonicalName() method returns the canonical name of the underlying class as defined by the Java Language Specification. It returns null if the class does not have a canonical name."
},
{
"code": null,
"e": 1475,
"s": 1464,
"text": " Live Demo"
},
{
"code": null,
"e": 1783,
"s": 1475,
"text": "import java.lang.*;\n\npublic class ClassDemo {\n public static void main(String[] args) {\n ClassDemo c = new ClassDemo();\n Class cls = c.getClass();\n \n //Returns the canonical name of the underlying class if it exists\n System.out.println(\"Class = \" + cls.getCanonicalName());\n }\n}"
},
{
"code": null,
"e": 1821,
"s": 1783,
"text": "Class = com.tutorialspoint.ClassDemo\n"
}
] |
How to open a file in binary mode with Python?
|
"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document formats like Word or PDF. In Python, files are opened in text mode by default. To open files in binary mode, when specifying a mode, add 'b' to it.
f = open('my_file.mp3', 'rb')
file_content = f.read()
f.close()
Above code opens my_file.mp3 in binary read mode and stores the file content in file_content variable.
|
[
{
"code": null,
"e": 1395,
"s": 1062,
"text": "\"Binary\" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document formats like Word or PDF. In Python, files are opened in text mode by default. To open files in binary mode, when specifying a mode, add 'b' to it."
},
{
"code": null,
"e": 1459,
"s": 1395,
"text": "f = open('my_file.mp3', 'rb')\nfile_content = f.read()\nf.close()"
},
{
"code": null,
"e": 1563,
"s": 1459,
"text": " Above code opens my_file.mp3 in binary read mode and stores the file content in file_content variable."
}
] |
strcpy() in C/C++
|
The function strcpy() is a standard library function. It is used to copy one string to another. In C language,it is declared in “string.h” header file while in C++ language, it is declared in cstring header file. It returns the pointer to the destination.
Here is the syntax of strcpy() in C language,
char* strcpy(char* dest, const char* src);
Some key points of strcpy().
It copies the whole string to the destination string. It replaces the whole string instead of appending it.
It copies the whole string to the destination string. It replaces the whole string instead of appending it.
It won’t change the source string.
It won’t change the source string.
Here is an example of strcpy() in C language,
Live Demo
#include <stdio.h>
#include<string.h>
int main() {
char s1[] = "Hello world!";
char s2[] = "Welcome";
printf("String s1 before: %s\n", s1);
strcpy(s1, s2);
printf("String s1 after: %s\n", s1);
printf("String s2 : %s", s2);
return 0;
}
String s1 before: Hello world!
String s1 after: Welcome
String s2 : Welcome
|
[
{
"code": null,
"e": 1318,
"s": 1062,
"text": "The function strcpy() is a standard library function. It is used to copy one string to another. In C language,it is declared in “string.h” header file while in C++ language, it is declared in cstring header file. It returns the pointer to the destination."
},
{
"code": null,
"e": 1364,
"s": 1318,
"text": "Here is the syntax of strcpy() in C language,"
},
{
"code": null,
"e": 1407,
"s": 1364,
"text": "char* strcpy(char* dest, const char* src);"
},
{
"code": null,
"e": 1436,
"s": 1407,
"text": "Some key points of strcpy()."
},
{
"code": null,
"e": 1544,
"s": 1436,
"text": "It copies the whole string to the destination string. It replaces the whole string instead of appending it."
},
{
"code": null,
"e": 1652,
"s": 1544,
"text": "It copies the whole string to the destination string. It replaces the whole string instead of appending it."
},
{
"code": null,
"e": 1687,
"s": 1652,
"text": "It won’t change the source string."
},
{
"code": null,
"e": 1722,
"s": 1687,
"text": "It won’t change the source string."
},
{
"code": null,
"e": 1768,
"s": 1722,
"text": "Here is an example of strcpy() in C language,"
},
{
"code": null,
"e": 1779,
"s": 1768,
"text": " Live Demo"
},
{
"code": null,
"e": 2035,
"s": 1779,
"text": "#include <stdio.h>\n#include<string.h>\nint main() {\n char s1[] = \"Hello world!\";\n char s2[] = \"Welcome\";\n printf(\"String s1 before: %s\\n\", s1);\n strcpy(s1, s2);\n printf(\"String s1 after: %s\\n\", s1);\n printf(\"String s2 : %s\", s2);\n return 0;\n}"
},
{
"code": null,
"e": 2111,
"s": 2035,
"text": "String s1 before: Hello world!\nString s1 after: Welcome\nString s2 : Welcome"
}
] |
strrchr() function in C/C++ - GeeksforGeeks
|
27 Aug, 2018
The strrchr() function in C/C++ locates the last occurrence of a character in a string. It returns a pointer to the last occurrence in the string. The terminating null character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string. It is defined in cstring header file.Syntax :
const char* strrchr( const char* str, int ch )
or
char* strrchr( char* str, int ch )
Parameter :The function takes two mandatory parameters which are described below:
str : specifies the pointer to the null terminated string to be searched for.
ch: specifies the character to be search for.
Return Value: The function returns a pointer to the last location of ch in string, if the ch is found. If not found, it returns a null pointer.
Below programs illustrate the above function:
Program 1:
// C++ program to illustrate// the strrchr() function#include <bits/stdc++.h>using namespace std; int main(){ // Storing it in string array char string[] = "Geeks for Geeks"; // The character we've to search for char character = 'k'; // Storing in a pointer ptr char* ptr = strrchr(string, character); // ptr-string gives the index location if (ptr) cout << "Last position of " << character << " in " << string << " is " << ptr - string; // If the character we're searching is not present in the array else cout << character << " is not present " << string << endl; return 0;}
Last position of k in Geeks for Geeks is 13
Program 2:
// C++ program to illustrate // the strrchr() function#include <bits/stdc++.h>using namespace std; int main(){ // Storing it in string array char string[] = "Geeks for Geeks"; char* ptr; // The character we've to search for char character = 'z'; // Storing in a pointer ptr ptr = strrchr(string, character); // ptr-string gives the index location if (ptr) cout << "Last position of " << character << " in " << string << " is " << ptr - string; // If the character we're searching // is not present in the array else cout << character << " is not present in " << string << endl; return 0;}
z is not present in Geeks for Geeks
C-Library
CPP-Functions
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
|
[
{
"code": null,
"e": 24258,
"s": 24230,
"text": "\n27 Aug, 2018"
},
{
"code": null,
"e": 24598,
"s": 24258,
"text": "The strrchr() function in C/C++ locates the last occurrence of a character in a string. It returns a pointer to the last occurrence in the string. The terminating null character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string. It is defined in cstring header file.Syntax :"
},
{
"code": null,
"e": 24696,
"s": 24598,
"text": "const char* strrchr( const char* str, int ch )\n or\nchar* strrchr( char* str, int ch )\n"
},
{
"code": null,
"e": 24778,
"s": 24696,
"text": "Parameter :The function takes two mandatory parameters which are described below:"
},
{
"code": null,
"e": 24856,
"s": 24778,
"text": "str : specifies the pointer to the null terminated string to be searched for."
},
{
"code": null,
"e": 24902,
"s": 24856,
"text": "ch: specifies the character to be search for."
},
{
"code": null,
"e": 25046,
"s": 24902,
"text": "Return Value: The function returns a pointer to the last location of ch in string, if the ch is found. If not found, it returns a null pointer."
},
{
"code": null,
"e": 25092,
"s": 25046,
"text": "Below programs illustrate the above function:"
},
{
"code": null,
"e": 25103,
"s": 25092,
"text": "Program 1:"
},
{
"code": "// C++ program to illustrate// the strrchr() function#include <bits/stdc++.h>using namespace std; int main(){ // Storing it in string array char string[] = \"Geeks for Geeks\"; // The character we've to search for char character = 'k'; // Storing in a pointer ptr char* ptr = strrchr(string, character); // ptr-string gives the index location if (ptr) cout << \"Last position of \" << character << \" in \" << string << \" is \" << ptr - string; // If the character we're searching is not present in the array else cout << character << \" is not present \" << string << endl; return 0;}",
"e": 25760,
"s": 25103,
"text": null
},
{
"code": null,
"e": 25805,
"s": 25760,
"text": "Last position of k in Geeks for Geeks is 13\n"
},
{
"code": null,
"e": 25816,
"s": 25805,
"text": "Program 2:"
},
{
"code": "// C++ program to illustrate // the strrchr() function#include <bits/stdc++.h>using namespace std; int main(){ // Storing it in string array char string[] = \"Geeks for Geeks\"; char* ptr; // The character we've to search for char character = 'z'; // Storing in a pointer ptr ptr = strrchr(string, character); // ptr-string gives the index location if (ptr) cout << \"Last position of \" << character << \" in \" << string << \" is \" << ptr - string; // If the character we're searching // is not present in the array else cout << character << \" is not present in \" << string << endl; return 0;}",
"e": 26491,
"s": 25816,
"text": null
},
{
"code": null,
"e": 26528,
"s": 26491,
"text": "z is not present in Geeks for Geeks\n"
},
{
"code": null,
"e": 26538,
"s": 26528,
"text": "C-Library"
},
{
"code": null,
"e": 26552,
"s": 26538,
"text": "CPP-Functions"
},
{
"code": null,
"e": 26563,
"s": 26552,
"text": "C Language"
},
{
"code": null,
"e": 26567,
"s": 26563,
"text": "C++"
},
{
"code": null,
"e": 26571,
"s": 26567,
"text": "CPP"
},
{
"code": null,
"e": 26669,
"s": 26571,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26678,
"s": 26669,
"text": "Comments"
},
{
"code": null,
"e": 26691,
"s": 26678,
"text": "Old Comments"
},
{
"code": null,
"e": 26726,
"s": 26691,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26754,
"s": 26726,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26800,
"s": 26754,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26812,
"s": 26800,
"text": "fork() in C"
},
{
"code": null,
"e": 26844,
"s": 26812,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26862,
"s": 26844,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 26908,
"s": 26862,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 26951,
"s": 26908,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26970,
"s": 26951,
"text": "Inheritance in C++"
}
] |
Creating alias in a MongoDB query?
|
You can use aggregate framework to create an alias. Let us first create a collection with documents −
> db.creatingAliasDemo.insertOne({_id:101,"Name":"John Doe"});
{ "acknowledged" : true, "insertedId" : 101 }
> db.creatingAliasDemo.insertOne({_id:102,"Name":"David Miller"});
{ "acknowledged" : true, "insertedId" : 102 }
> db.creatingAliasDemo.insertOne({_id:103,"Name":"Sam Williams"});
{ "acknowledged" : true, "insertedId" : 103 }
Following is the query to display all documents from the collection with the help of find() method −
> db.creatingAliasDemo.find().pretty();
This will produce the following output −
{ "_id" : 101, "Name" : "John Doe" }
{ "_id" : 102, "Name" : "David Miller" }
{ "_id" : 103, "Name" : "Sam Williams" }
Following is the query to create alias in a query −
> db.creatingAliasDemo.aggregate(
... [
... {
... $project: {
... _id:1,
... "FullName":"$Name"
... }
... }
... ]
... );
This will produce the following output −
{ "_id" : 101, "FullName" : "John Doe" }
{ "_id" : 102, "FullName" : "David Miller" }
{ "_id" : 103, "FullName" : "Sam Williams" }
|
[
{
"code": null,
"e": 1164,
"s": 1062,
"text": "You can use aggregate framework to create an alias. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1499,
"s": 1164,
"text": "> db.creatingAliasDemo.insertOne({_id:101,\"Name\":\"John Doe\"});\n{ \"acknowledged\" : true, \"insertedId\" : 101 }\n> db.creatingAliasDemo.insertOne({_id:102,\"Name\":\"David Miller\"});\n{ \"acknowledged\" : true, \"insertedId\" : 102 }\n> db.creatingAliasDemo.insertOne({_id:103,\"Name\":\"Sam Williams\"});\n{ \"acknowledged\" : true, \"insertedId\" : 103 }"
},
{
"code": null,
"e": 1600,
"s": 1499,
"text": "Following is the query to display all documents from the collection with the help of find() method −"
},
{
"code": null,
"e": 1640,
"s": 1600,
"text": "> db.creatingAliasDemo.find().pretty();"
},
{
"code": null,
"e": 1681,
"s": 1640,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1800,
"s": 1681,
"text": "{ \"_id\" : 101, \"Name\" : \"John Doe\" }\n{ \"_id\" : 102, \"Name\" : \"David Miller\" }\n{ \"_id\" : 103, \"Name\" : \"Sam Williams\" }"
},
{
"code": null,
"e": 1852,
"s": 1800,
"text": "Following is the query to create alias in a query −"
},
{
"code": null,
"e": 2033,
"s": 1852,
"text": "> db.creatingAliasDemo.aggregate(\n... [\n... {\n... $project: {\n... _id:1,\n... \"FullName\":\"$Name\"\n... }\n... }\n... ]\n... );"
},
{
"code": null,
"e": 2074,
"s": 2033,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2205,
"s": 2074,
"text": "{ \"_id\" : 101, \"FullName\" : \"John Doe\" }\n{ \"_id\" : 102, \"FullName\" : \"David Miller\" }\n{ \"_id\" : 103, \"FullName\" : \"Sam Williams\" }"
}
] |
How to Delete Row(s) in R DataFrame ? - GeeksforGeeks
|
09 May, 2021
In this article, we will see how row(s) can be deleted from a Dataframe in R Programming Language.
For this, the index of the row to be deleted is passed with a minus sign.
Syntax:
df[-(index), ]
Example 1 :
R
# creating a data frame with# some data .df=data.frame(id=c(1,2,3), name=c("karthik","sravan","nikhil"), branch=c("IT","IT","CSE")) # using - with indexing deleting# 3rd row .df[-3,]
Output :
Example 2 :
R
# creating a data frame with # some data .df=data.frame(id=c(1,2,3), name=c("karthik","sravan","nikhil"), branch=c("IT","IT","CSE")) # using - with indexing deleting # 2nd rowdf[-2,]
Output :
Method 1: Using Range
For this, the range of the rows to be deleted is passed to the dataframe name.
Syntax:
df[-(start_index,end_index), ]
Example 1:
R
# creating a data frame with # some datadf=data.frame(id=c(1,2,3,4,5), name=c("karthik","sravan","nikhil", "bhagiradh","sai"), branch=c("IT","IT","CSE","IT","CSE")) # deleting multiple rows using # vector df[-c(3,5),]
Output:
Example 2:
R
# creating a data frame with # some datadf=data.frame(id=c(1,2,3,4,5), name=c("karthik","sravan","nikhil", "bhagiradh","sai"), branch=c("IT","IT","CSE","IT","CSE")) # deleting multiple rows using # vectordf[-c(2,4),]
Output :
Method 2: Using anti_join( )
anti_join method is available in dplyr package. So we have to install dplyr package first. To install we can use install.package() method, and we have to pass package name as parameter. To import the package into the R environment we need to use library( ) function. In this function, we have to pass the package name as a parameter.
Syntax :
anti_join (data_frame_name , data_frame_name [ c(row_index 1 ,...row_index n),c( column_index 1,......column_index n)] )
Example 1 :
R
library(dplyr) # creating a data frame with some datadf=data.frame(id=c(1,2,3,4,5), name=c("karthik","sravan","nikhil", "bhagiradh","sai"), branch=c("IT","IT","CSE","IT","CSE")) anti_join(df,df[c(1,2),])
Output :
Example 2:
R
library(dplyr) # creating a data frame with # some datadf=data.frame(id=c(1,2,3,4,5), name=c("karthik","sravan","nikhil", "bhagiradh","sai"), branch=c("IT","IT","CSE","IT","CSE")) anti_join(df,df[c(1,3),])
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.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n09 May, 2021"
},
{
"code": null,
"e": 24950,
"s": 24851,
"text": "In this article, we will see how row(s) can be deleted from a Dataframe in R Programming Language."
},
{
"code": null,
"e": 25024,
"s": 24950,
"text": "For this, the index of the row to be deleted is passed with a minus sign."
},
{
"code": null,
"e": 25032,
"s": 25024,
"text": "Syntax:"
},
{
"code": null,
"e": 25047,
"s": 25032,
"text": "df[-(index), ]"
},
{
"code": null,
"e": 25060,
"s": 25047,
"text": "Example 1 : "
},
{
"code": null,
"e": 25062,
"s": 25060,
"text": "R"
},
{
"code": "# creating a data frame with# some data .df=data.frame(id=c(1,2,3), name=c(\"karthik\",\"sravan\",\"nikhil\"), branch=c(\"IT\",\"IT\",\"CSE\")) # using - with indexing deleting# 3rd row .df[-3,] ",
"e": 25273,
"s": 25062,
"text": null
},
{
"code": null,
"e": 25282,
"s": 25273,
"text": "Output :"
},
{
"code": null,
"e": 25295,
"s": 25282,
"text": "Example 2 : "
},
{
"code": null,
"e": 25297,
"s": 25295,
"text": "R"
},
{
"code": "# creating a data frame with # some data .df=data.frame(id=c(1,2,3), name=c(\"karthik\",\"sravan\",\"nikhil\"), branch=c(\"IT\",\"IT\",\"CSE\")) # using - with indexing deleting # 2nd rowdf[-2,] ",
"e": 25508,
"s": 25297,
"text": null
},
{
"code": null,
"e": 25517,
"s": 25508,
"text": "Output :"
},
{
"code": null,
"e": 25539,
"s": 25517,
"text": "Method 1: Using Range"
},
{
"code": null,
"e": 25618,
"s": 25539,
"text": "For this, the range of the rows to be deleted is passed to the dataframe name."
},
{
"code": null,
"e": 25626,
"s": 25618,
"text": "Syntax:"
},
{
"code": null,
"e": 25657,
"s": 25626,
"text": "df[-(start_index,end_index), ]"
},
{
"code": null,
"e": 25669,
"s": 25657,
"text": "Example 1: "
},
{
"code": null,
"e": 25671,
"s": 25669,
"text": "R"
},
{
"code": "# creating a data frame with # some datadf=data.frame(id=c(1,2,3,4,5), name=c(\"karthik\",\"sravan\",\"nikhil\", \"bhagiradh\",\"sai\"), branch=c(\"IT\",\"IT\",\"CSE\",\"IT\",\"CSE\")) # deleting multiple rows using # vector df[-c(3,5),] ",
"e": 25969,
"s": 25671,
"text": null
},
{
"code": null,
"e": 25977,
"s": 25969,
"text": "Output:"
},
{
"code": null,
"e": 25989,
"s": 25977,
"text": "Example 2: "
},
{
"code": null,
"e": 25991,
"s": 25989,
"text": "R"
},
{
"code": "# creating a data frame with # some datadf=data.frame(id=c(1,2,3,4,5), name=c(\"karthik\",\"sravan\",\"nikhil\", \"bhagiradh\",\"sai\"), branch=c(\"IT\",\"IT\",\"CSE\",\"IT\",\"CSE\")) # deleting multiple rows using # vectordf[-c(2,4),] ",
"e": 26288,
"s": 25991,
"text": null
},
{
"code": null,
"e": 26297,
"s": 26288,
"text": "Output :"
},
{
"code": null,
"e": 26326,
"s": 26297,
"text": "Method 2: Using anti_join( )"
},
{
"code": null,
"e": 26660,
"s": 26326,
"text": "anti_join method is available in dplyr package. So we have to install dplyr package first. To install we can use install.package() method, and we have to pass package name as parameter. To import the package into the R environment we need to use library( ) function. In this function, we have to pass the package name as a parameter."
},
{
"code": null,
"e": 26670,
"s": 26660,
"text": "Syntax : "
},
{
"code": null,
"e": 26791,
"s": 26670,
"text": "anti_join (data_frame_name , data_frame_name [ c(row_index 1 ,...row_index n),c( column_index 1,......column_index n)] )"
},
{
"code": null,
"e": 26803,
"s": 26791,
"text": "Example 1 :"
},
{
"code": null,
"e": 26805,
"s": 26803,
"text": "R"
},
{
"code": "library(dplyr) # creating a data frame with some datadf=data.frame(id=c(1,2,3,4,5), name=c(\"karthik\",\"sravan\",\"nikhil\", \"bhagiradh\",\"sai\"), branch=c(\"IT\",\"IT\",\"CSE\",\"IT\",\"CSE\")) anti_join(df,df[c(1,2),])",
"e": 27089,
"s": 26805,
"text": null
},
{
"code": null,
"e": 27098,
"s": 27089,
"text": "Output :"
},
{
"code": null,
"e": 27109,
"s": 27098,
"text": "Example 2:"
},
{
"code": null,
"e": 27111,
"s": 27109,
"text": "R"
},
{
"code": "library(dplyr) # creating a data frame with # some datadf=data.frame(id=c(1,2,3,4,5), name=c(\"karthik\",\"sravan\",\"nikhil\", \"bhagiradh\",\"sai\"), branch=c(\"IT\",\"IT\",\"CSE\",\"IT\",\"CSE\")) anti_join(df,df[c(1,3),])",
"e": 27397,
"s": 27111,
"text": null
},
{
"code": null,
"e": 27406,
"s": 27397,
"text": "Output :"
},
{
"code": null,
"e": 27413,
"s": 27406,
"text": "Picked"
},
{
"code": null,
"e": 27434,
"s": 27413,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 27446,
"s": 27434,
"text": "R-DataFrame"
},
{
"code": null,
"e": 27457,
"s": 27446,
"text": "R Language"
},
{
"code": null,
"e": 27468,
"s": 27457,
"text": "R Programs"
},
{
"code": null,
"e": 27566,
"s": 27468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27575,
"s": 27566,
"text": "Comments"
},
{
"code": null,
"e": 27588,
"s": 27575,
"text": "Old Comments"
},
{
"code": null,
"e": 27640,
"s": 27588,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27678,
"s": 27640,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27713,
"s": 27678,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27771,
"s": 27713,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27814,
"s": 27771,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27872,
"s": 27814,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27915,
"s": 27872,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27964,
"s": 27915,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28014,
"s": 27964,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
Flask â Application
|
In order to test Flask installation, type the following code in the editor as Hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World’
if __name__ == '__main__':
app.run()
Importing flask module in the project is mandatory. An object of Flask class is our WSGI application.
Flask constructor takes the name of current module (__name__) as argument.
The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.
app.route(rule, options)
The rule parameter represents URL binding with the function.
The rule parameter represents URL binding with the function.
The options is a list of parameters to be forwarded to the underlying Rule object.
The options is a list of parameters to be forwarded to the underlying Rule object.
In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered.
Finally the run() method of Flask class runs the application on the local development server.
app.run(host, port, debug, options)
All parameters are optional
host
Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally
port
Defaults to 5000
debug
Defaults to false. If set to true, provides a debug information
options
To be forwarded to underlying Werkzeug server.
The above given Python script is executed from Python shell.
Python Hello.py
A message in Python shell informs you that
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Open the above URL (localhost:5000) in the browser. ‘Hello World’ message will be displayed on it.
A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application.
The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.
app.debug = True
app.run()
app.run(debug = True)
22 Lectures
6 hours
Malhar Lathkar
21 Lectures
1.5 hours
Jack Chan
16 Lectures
4 hours
Malhar Lathkar
54 Lectures
6 hours
Srikanth Guskra
88 Lectures
3.5 hours
Jorge Escobar
80 Lectures
12 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2120,
"s": 2033,
"text": "In order to test Flask installation, type the following code in the editor as Hello.py"
},
{
"code": null,
"e": 2267,
"s": 2120,
"text": "from flask import Flask\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n return 'Hello World’\n\nif __name__ == '__main__':\n app.run()"
},
{
"code": null,
"e": 2369,
"s": 2267,
"text": "Importing flask module in the project is mandatory. An object of Flask class is our WSGI application."
},
{
"code": null,
"e": 2444,
"s": 2369,
"text": "Flask constructor takes the name of current module (__name__) as argument."
},
{
"code": null,
"e": 2575,
"s": 2444,
"text": "The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function."
},
{
"code": null,
"e": 2601,
"s": 2575,
"text": "app.route(rule, options)\n"
},
{
"code": null,
"e": 2662,
"s": 2601,
"text": "The rule parameter represents URL binding with the function."
},
{
"code": null,
"e": 2723,
"s": 2662,
"text": "The rule parameter represents URL binding with the function."
},
{
"code": null,
"e": 2806,
"s": 2723,
"text": "The options is a list of parameters to be forwarded to the underlying Rule object."
},
{
"code": null,
"e": 2889,
"s": 2806,
"text": "The options is a list of parameters to be forwarded to the underlying Rule object."
},
{
"code": null,
"e": 3065,
"s": 2889,
"text": "In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered."
},
{
"code": null,
"e": 3159,
"s": 3065,
"text": "Finally the run() method of Flask class runs the application on the local development server."
},
{
"code": null,
"e": 3196,
"s": 3159,
"text": "app.run(host, port, debug, options)\n"
},
{
"code": null,
"e": 3224,
"s": 3196,
"text": "All parameters are optional"
},
{
"code": null,
"e": 3229,
"s": 3224,
"text": "host"
},
{
"code": null,
"e": 3340,
"s": 3229,
"text": "Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have server available externally"
},
{
"code": null,
"e": 3345,
"s": 3340,
"text": "port"
},
{
"code": null,
"e": 3362,
"s": 3345,
"text": "Defaults to 5000"
},
{
"code": null,
"e": 3368,
"s": 3362,
"text": "debug"
},
{
"code": null,
"e": 3432,
"s": 3368,
"text": "Defaults to false. If set to true, provides a debug information"
},
{
"code": null,
"e": 3440,
"s": 3432,
"text": "options"
},
{
"code": null,
"e": 3487,
"s": 3440,
"text": "To be forwarded to underlying Werkzeug server."
},
{
"code": null,
"e": 3548,
"s": 3487,
"text": "The above given Python script is executed from Python shell."
},
{
"code": null,
"e": 3565,
"s": 3548,
"text": "Python Hello.py\n"
},
{
"code": null,
"e": 3608,
"s": 3565,
"text": "A message in Python shell informs you that"
},
{
"code": null,
"e": 3668,
"s": 3608,
"text": "* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)\n"
},
{
"code": null,
"e": 3767,
"s": 3668,
"text": "Open the above URL (localhost:5000) in the browser. ‘Hello World’ message will be displayed on it."
},
{
"code": null,
"e": 4135,
"s": 3767,
"text": "A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application."
},
{
"code": null,
"e": 4292,
"s": 4135,
"text": "The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method."
},
{
"code": null,
"e": 4341,
"s": 4292,
"text": "app.debug = True\napp.run()\napp.run(debug = True)"
},
{
"code": null,
"e": 4374,
"s": 4341,
"text": "\n 22 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4390,
"s": 4374,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4425,
"s": 4390,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4436,
"s": 4425,
"text": " Jack Chan"
},
{
"code": null,
"e": 4469,
"s": 4436,
"text": "\n 16 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4485,
"s": 4469,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4518,
"s": 4485,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4535,
"s": 4518,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 4570,
"s": 4535,
"text": "\n 88 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4585,
"s": 4570,
"text": " Jorge Escobar"
},
{
"code": null,
"e": 4619,
"s": 4585,
"text": "\n 80 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 4642,
"s": 4619,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4649,
"s": 4642,
"text": " Print"
},
{
"code": null,
"e": 4660,
"s": 4649,
"text": " Add Notes"
}
] |
Effective community detection with Markov Clustering | by Francesco Gadaleta | Towards Data Science
|
This post first appeared on amethix.com
“If intelligence is a cake, the bulk of the cake is unsupervised learning, the icing on the cake is supervised learning, and the cherry on the cake is reinforcement learning”.
This famous quote from Facebook AI Chief Yann LeCun highlights how humans rely on unsupervised learning. Effective community detection with Markov Clustering. They use such an approach to make sense of the world around them. As a matter of fact, children learn to recognize objects and speak without much supervision. In contrast, sophisticated deep learning algorithms need millions of carefully annotated data. This is necessary to reach human-like performance in tasks such as object detection and language generation.
This post provides you with a great method for effective community detection with Markov Clustering.
In this realm, one can consider clustering as one of the most useful tools to learn interesting patterns from data in an unsupervised fashion.
Whether one categorize emails or performs customer segmentation, clustering is most of the time the way to go. This approach consists of dividing the dataset into groups (or clusters) such that objects belonging to the same cluster are more similar than items belonging to different clusters. It is possible to calculate such similarity according to a specific metric that of course can change with the problem to be solved.
Data scientists use clustering algorithms such as k-means, hierarchical clustering or DBSCAN in exploratory data analysis of tabular data. There is another type of data that is also common: networks. In the network analysis jargon, researchers refer to clustering network data to as community detection. In such a context, the clusters represent the communities. Refer to [1] and [2] for more details on community detection and state-of-the-art algorithms for clustering networks, respectively.
The purpose of this post is to unravel some of the most important properties of a specific algorithm referred to as Markov clustering (MCL). Researchers have designed this algorithm primarily to perform community detection. However, one can use MCL to cluster tabular data too. A more technical explanation of the MCL algorithm is provided in reference [3] and an application of the method to cluster biological sequences is detailed in [4].Let’s now refresh some concepts of graph theory that will become useful to understand the working mechanism of the MCL technique.
As mentioned in a previous post, many systems in nature can be represented as graphs. Graphs are nothing more than a set of nodes connected by edges. Social networks probably are the most familiar example of graphs. Nodes represent users while an edge connecting any two nodes represents the fact that the two users are interacting with each other.
One of the common approaches to analyze graphs and derive insights from simulations is the so-called random walk. Here is an example that clarifies what random walk means. Suppose there is a tourist who is starting a trip from his hometown and is going to visit several cities. One can think of the cities as the nodes of a graph. Such nodes are connected by an edge whenever it is possible to directly reach one city from the other. Let’s assume the aforementioned tourist is amazed by surprises. She hasn’t planned her trip in advance and she randomly picks the next city.
From a mathematical point of view, the trip of the tourist is a stochastic process known as a random walk.A natural question that may arise: which cities will be visited next by our tourist in the long term? The answer to such a question depends on how the cities are connected to each other. For example, if cities form well-separated clusters ( connected components), and the tourist starts her trip inside one of these clusters, she may never be able to reach any city of the other clusters.Simulating a random walk on a graph represents precisely the idea behind the MCL algorithm.
The purpose of the MCL algorithm is to find a cluster structure. This is achieved by simulating a random walk on a graph until it reaches equilibrium.The first step one needs to take is to obtain the aforementioned graph.
In the case of network data, the only task to perform is to compute the adjacency (or affinity) matrix A. Such a matrix perfectly describes the network. The definition of such a matrix is Aij= 1 if there is an edge from vertex i to vertex j, and 0 otherwise
In the case of tabular data, one has to construct a similarity matrix. This happens by computing pairwise similarities between all existing records (i.e. the rows of the table). Such similarity matrix represents a weighted graph. The nodes of such a graph represent the observations and the edges have weights corresponding to the similarity score between them.
By properly scaling either the adjacency or the similarity matrix, one can obtain the Markov matrix. This is a matrix of probabilities representing the chances for a node reaching another one it is connected to.Finally, once one builds the Markov matrix, the random walk on the graph is simulated by alternating two operators called expansion and inflation.
Expansion allows the random walker to take higher length paths. For instance taking a large number of steps from one node to the other.Inflation changes the transition probabilities by favouring more probable walks over less probable ones.
The combination of expansion and inflation will boost the probabilities of walks inside each cluster. Moreover it will reduce walks between the clusters. This happens because higher length paths are more common within the same clusters than between different clusters.
Such behavior will emerge in the long term. The iteration of expansion and inflation operations leads to the separation of the graph into different connected components. Therefore, unlike many clustering algorithms that need the user to specify the expected number of clusters beforehand, sometimes mistakenly, the MCL algorithm provides a partition of the data into clusters that naturally arises from the graph topology itself.
Let’s see how to use the MCL algorithm in practice with Python and how to perform effective community detection with Markov Clustering.First of all, install the required package that implements the algorithm with pip install markov_clustering[drawing] and the networkx package to analyze and visualize graphs.
Then execute the code below
# Import librariesimport markov_clustering as mcimport networkx as nx# Load network dataG = nx.karate_club_graph()# Build adjacency matrixA = nx.to_numpy_matrix(G)# Run MCL algorithmresult = mc.run_mcl(A)clusters = mc.get_clusters(result)# Draw clustersmc.draw_graph(A, clusters, node_size=50, with_labels=True, edge_color="silver")
In the above code, we use the MCL algorithm to detect the clusters, also called communities, in Zachary’s karate club, which is a popular benchmark to test community detection algorithms. Zachary’s karate club is a social network of a university karate club. The network captures 34 members of a karate club, documenting links between pairs of members who interacted outside the club.
During the study, a conflict arose between the administrator (node 0) and instructor (node 33) which led to the split of the club into two subgraphs. Half of the members formed a new club around the instructor, while members from the other part found a new instructor or gave up karate.
As shown in the picture below, the MCL algorithm nicely detects the presence of two distinct communities in the network, comprising the members that mostly had interactions either with the administrator or the instructor:
In this post, we have seen how a community detection algorithm known as Markov clustering can be constructed by combining simple concepts like random walks, graphs, similarity matrix. Moreover, we highlighted how one can build a similarity graph and then run an effective community detection algorithm on such graph (such as Markov clustering or other state-of-the-art methods) to find clusters in tabular data.
Follow podcast https://datascienceathome.com/Don’t forget to join the conversation on our new Discord channel. See you there!
[1] S. Fortunato, “Community detection in graphs”, Physics Reports, volume 486, issues 3–5, pages 75–174, February 2010.
[2] Z. Yang, et al., “A Comparative Analysis of Community Detection Algorithms on Artificial Networks”, Scientific Reports volume 6, Article number: 30750 (2016)
[3] S. Dongen, “A cluster algorithm for graphs”, Technical Report, CWI (Centre for Mathematics and Computer Science) Amsterdam, The Netherlands, 2000.
[4] A. J. Enright, et al., “An efficient algorithm for large-scale detection of protein families”, Nucleic Acids Research, volume 30, issue 7, pages 1575–1584, 2002.
Originally published at https://amethix.com on August 21, 2019.
|
[
{
"code": null,
"e": 212,
"s": 172,
"text": "This post first appeared on amethix.com"
},
{
"code": null,
"e": 388,
"s": 212,
"text": "“If intelligence is a cake, the bulk of the cake is unsupervised learning, the icing on the cake is supervised learning, and the cherry on the cake is reinforcement learning”."
},
{
"code": null,
"e": 910,
"s": 388,
"text": "This famous quote from Facebook AI Chief Yann LeCun highlights how humans rely on unsupervised learning. Effective community detection with Markov Clustering. They use such an approach to make sense of the world around them. As a matter of fact, children learn to recognize objects and speak without much supervision. In contrast, sophisticated deep learning algorithms need millions of carefully annotated data. This is necessary to reach human-like performance in tasks such as object detection and language generation."
},
{
"code": null,
"e": 1011,
"s": 910,
"text": "This post provides you with a great method for effective community detection with Markov Clustering."
},
{
"code": null,
"e": 1154,
"s": 1011,
"text": "In this realm, one can consider clustering as one of the most useful tools to learn interesting patterns from data in an unsupervised fashion."
},
{
"code": null,
"e": 1579,
"s": 1154,
"text": "Whether one categorize emails or performs customer segmentation, clustering is most of the time the way to go. This approach consists of dividing the dataset into groups (or clusters) such that objects belonging to the same cluster are more similar than items belonging to different clusters. It is possible to calculate such similarity according to a specific metric that of course can change with the problem to be solved."
},
{
"code": null,
"e": 2074,
"s": 1579,
"text": "Data scientists use clustering algorithms such as k-means, hierarchical clustering or DBSCAN in exploratory data analysis of tabular data. There is another type of data that is also common: networks. In the network analysis jargon, researchers refer to clustering network data to as community detection. In such a context, the clusters represent the communities. Refer to [1] and [2] for more details on community detection and state-of-the-art algorithms for clustering networks, respectively."
},
{
"code": null,
"e": 2645,
"s": 2074,
"text": "The purpose of this post is to unravel some of the most important properties of a specific algorithm referred to as Markov clustering (MCL). Researchers have designed this algorithm primarily to perform community detection. However, one can use MCL to cluster tabular data too. A more technical explanation of the MCL algorithm is provided in reference [3] and an application of the method to cluster biological sequences is detailed in [4].Let’s now refresh some concepts of graph theory that will become useful to understand the working mechanism of the MCL technique."
},
{
"code": null,
"e": 2994,
"s": 2645,
"text": "As mentioned in a previous post, many systems in nature can be represented as graphs. Graphs are nothing more than a set of nodes connected by edges. Social networks probably are the most familiar example of graphs. Nodes represent users while an edge connecting any two nodes represents the fact that the two users are interacting with each other."
},
{
"code": null,
"e": 3569,
"s": 2994,
"text": "One of the common approaches to analyze graphs and derive insights from simulations is the so-called random walk. Here is an example that clarifies what random walk means. Suppose there is a tourist who is starting a trip from his hometown and is going to visit several cities. One can think of the cities as the nodes of a graph. Such nodes are connected by an edge whenever it is possible to directly reach one city from the other. Let’s assume the aforementioned tourist is amazed by surprises. She hasn’t planned her trip in advance and she randomly picks the next city."
},
{
"code": null,
"e": 4155,
"s": 3569,
"text": "From a mathematical point of view, the trip of the tourist is a stochastic process known as a random walk.A natural question that may arise: which cities will be visited next by our tourist in the long term? The answer to such a question depends on how the cities are connected to each other. For example, if cities form well-separated clusters ( connected components), and the tourist starts her trip inside one of these clusters, she may never be able to reach any city of the other clusters.Simulating a random walk on a graph represents precisely the idea behind the MCL algorithm."
},
{
"code": null,
"e": 4377,
"s": 4155,
"text": "The purpose of the MCL algorithm is to find a cluster structure. This is achieved by simulating a random walk on a graph until it reaches equilibrium.The first step one needs to take is to obtain the aforementioned graph."
},
{
"code": null,
"e": 4635,
"s": 4377,
"text": "In the case of network data, the only task to perform is to compute the adjacency (or affinity) matrix A. Such a matrix perfectly describes the network. The definition of such a matrix is Aij= 1 if there is an edge from vertex i to vertex j, and 0 otherwise"
},
{
"code": null,
"e": 4997,
"s": 4635,
"text": "In the case of tabular data, one has to construct a similarity matrix. This happens by computing pairwise similarities between all existing records (i.e. the rows of the table). Such similarity matrix represents a weighted graph. The nodes of such a graph represent the observations and the edges have weights corresponding to the similarity score between them."
},
{
"code": null,
"e": 5355,
"s": 4997,
"text": "By properly scaling either the adjacency or the similarity matrix, one can obtain the Markov matrix. This is a matrix of probabilities representing the chances for a node reaching another one it is connected to.Finally, once one builds the Markov matrix, the random walk on the graph is simulated by alternating two operators called expansion and inflation."
},
{
"code": null,
"e": 5595,
"s": 5355,
"text": "Expansion allows the random walker to take higher length paths. For instance taking a large number of steps from one node to the other.Inflation changes the transition probabilities by favouring more probable walks over less probable ones."
},
{
"code": null,
"e": 5864,
"s": 5595,
"text": "The combination of expansion and inflation will boost the probabilities of walks inside each cluster. Moreover it will reduce walks between the clusters. This happens because higher length paths are more common within the same clusters than between different clusters."
},
{
"code": null,
"e": 6294,
"s": 5864,
"text": "Such behavior will emerge in the long term. The iteration of expansion and inflation operations leads to the separation of the graph into different connected components. Therefore, unlike many clustering algorithms that need the user to specify the expected number of clusters beforehand, sometimes mistakenly, the MCL algorithm provides a partition of the data into clusters that naturally arises from the graph topology itself."
},
{
"code": null,
"e": 6604,
"s": 6294,
"text": "Let’s see how to use the MCL algorithm in practice with Python and how to perform effective community detection with Markov Clustering.First of all, install the required package that implements the algorithm with pip install markov_clustering[drawing] and the networkx package to analyze and visualize graphs."
},
{
"code": null,
"e": 6632,
"s": 6604,
"text": "Then execute the code below"
},
{
"code": null,
"e": 6965,
"s": 6632,
"text": "# Import librariesimport markov_clustering as mcimport networkx as nx# Load network dataG = nx.karate_club_graph()# Build adjacency matrixA = nx.to_numpy_matrix(G)# Run MCL algorithmresult = mc.run_mcl(A)clusters = mc.get_clusters(result)# Draw clustersmc.draw_graph(A, clusters, node_size=50, with_labels=True, edge_color=\"silver\")"
},
{
"code": null,
"e": 7350,
"s": 6965,
"text": "In the above code, we use the MCL algorithm to detect the clusters, also called communities, in Zachary’s karate club, which is a popular benchmark to test community detection algorithms. Zachary’s karate club is a social network of a university karate club. The network captures 34 members of a karate club, documenting links between pairs of members who interacted outside the club."
},
{
"code": null,
"e": 7637,
"s": 7350,
"text": "During the study, a conflict arose between the administrator (node 0) and instructor (node 33) which led to the split of the club into two subgraphs. Half of the members formed a new club around the instructor, while members from the other part found a new instructor or gave up karate."
},
{
"code": null,
"e": 7859,
"s": 7637,
"text": "As shown in the picture below, the MCL algorithm nicely detects the presence of two distinct communities in the network, comprising the members that mostly had interactions either with the administrator or the instructor:"
},
{
"code": null,
"e": 8271,
"s": 7859,
"text": "In this post, we have seen how a community detection algorithm known as Markov clustering can be constructed by combining simple concepts like random walks, graphs, similarity matrix. Moreover, we highlighted how one can build a similarity graph and then run an effective community detection algorithm on such graph (such as Markov clustering or other state-of-the-art methods) to find clusters in tabular data."
},
{
"code": null,
"e": 8397,
"s": 8271,
"text": "Follow podcast https://datascienceathome.com/Don’t forget to join the conversation on our new Discord channel. See you there!"
},
{
"code": null,
"e": 8518,
"s": 8397,
"text": "[1] S. Fortunato, “Community detection in graphs”, Physics Reports, volume 486, issues 3–5, pages 75–174, February 2010."
},
{
"code": null,
"e": 8680,
"s": 8518,
"text": "[2] Z. Yang, et al., “A Comparative Analysis of Community Detection Algorithms on Artificial Networks”, Scientific Reports volume 6, Article number: 30750 (2016)"
},
{
"code": null,
"e": 8831,
"s": 8680,
"text": "[3] S. Dongen, “A cluster algorithm for graphs”, Technical Report, CWI (Centre for Mathematics and Computer Science) Amsterdam, The Netherlands, 2000."
},
{
"code": null,
"e": 8997,
"s": 8831,
"text": "[4] A. J. Enright, et al., “An efficient algorithm for large-scale detection of protein families”, Nucleic Acids Research, volume 30, issue 7, pages 1575–1584, 2002."
}
] |
Removing property from a JSON object in JavaScript
|
Let’s say, we create an object as follows −
const myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
We are required to illustrate the best way to remove the property regex to end up with new
myObject as follows −
const myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
The delete operator is used to remove properties from objects −
const myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
delete myObject['regex'];
console.log(myObject.hasOwnProperty("regex")); // false
The delete operator in JavaScript has a different function to that of the keyword in C and C++ −
It does not directly free memory. Instead, its sole purpose is to remove properties from objects.
Following is the console output −
False
|
[
{
"code": null,
"e": 1106,
"s": 1062,
"text": "Let’s say, we create an object as follows −"
},
{
"code": null,
"e": 1202,
"s": 1106,
"text": "const myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};"
},
{
"code": null,
"e": 1315,
"s": 1202,
"text": "We are required to illustrate the best way to remove the property regex to end up with new\nmyObject as follows −"
},
{
"code": null,
"e": 1385,
"s": 1315,
"text": "const myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\"\n};"
},
{
"code": null,
"e": 1449,
"s": 1385,
"text": "The delete operator is used to remove properties from objects −"
},
{
"code": null,
"e": 1627,
"s": 1449,
"text": "const myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\ndelete myObject['regex'];\nconsole.log(myObject.hasOwnProperty(\"regex\")); // false"
},
{
"code": null,
"e": 1724,
"s": 1627,
"text": "The delete operator in JavaScript has a different function to that of the keyword in C and C++ −"
},
{
"code": null,
"e": 1822,
"s": 1724,
"text": "It does not directly free memory. Instead, its sole purpose is to remove properties from objects."
},
{
"code": null,
"e": 1856,
"s": 1822,
"text": "Following is the console output −"
},
{
"code": null,
"e": 1862,
"s": 1856,
"text": "False"
}
] |
Normalization, Standardization and Normal Distribution | by Gustavo Santos | Towards Data Science
|
I will start this post with a statement: normalization and standardization will not change the distribution of your data. In other words, if your variable is not normally distributed, it won’t be turn into one with the normalize method.
normalize() or StandardScaler() from sklearn won’t change the shape of your data.
Standardization can be done using sklearn.preprocessing.StandardScaler module. What it does to your variable is centering the data to a mean of 0 and standard deviation of 1.
Doing that is important to put your data in the same scale. Sometimes you’re working with many variables of different scales. For example, let’s say you’re working on a linear regression project that has variables like years of study and salary.
Do you agree with me that years of study will float somewhere between 1 to 30? And do you also agree that the salary variable will be within the tens of thousands range?
Well, that’s a big difference between variables. That said, once the linear regression algorithm will calculate the coefficients, naturally it will give a higher number to salary in opposition to years of study. But we know we don’t want the model to make that differentiation, so we can standardize the data to put them in the same scale.
import pandas as pdimport seaborn as snsfrom sklearn.preprocessing import StandardScaler, normalizeimport scipy.stats as scs# Pull a datasetdf = sns.load_dataset('tips')# Histogram of tip variablesns.histoplot(data=df, x='tip');
Ok. Applying standardization.
# standardizingscaler = StandardScaler()scaled = scaler.fit_transform(df[['tip']])# Mean and Std of standardized dataprint(f'Mean: {scaled.mean().round()} | Std: {scaled.std().round()}')[OUT]: Mean: 0.0 | Std: 1.0# Histplotsns.histplot(scaled);
The shape is the same. It wasn’t normal before. It’s not normal now. And we can take a Shapiro test for normal distributions before and after to confirm. The p-Value is the second number in the parenthesis (statistic test number, p-Value) and if smaller than 0.05, it means not normal distribution.
# Normal test original datascs.shapiro(df.tip)[OUT]: (0.897811233997345, 8.20057563521992e-12)# Normal test scaled datascs.shapiro(scaled)[OUT]: (0.8978115916252136, 8.201060490431455e-12)
Normalization can be performed in Python with normalize() from sklearn and it won’t change the shape of your data as well. It brings the data to the same scale as well, but the main difference here is that it will present numbers between 0 and 1 (but it won’t center the data on mean 0 and std =1).
One of the most common ways to normalize is the Min Max normalization, that basically makes the maximum value equals 1 and the minimum equals 0. Everything in between will be a percentage of that, or a number between 0 and 1. However, in this example we’re using the normalize function from sklearn.
# normalizenormalized = normalize(df[['tip']], axis=0)# Normalized, but NOT Normal distribution. p-Value < 0.05scs.shapiro(normalized)[OUT]: (0.897811233997345, 8.20057563521992e-12)
Again, our shape remains the same. The data is still not normally distributed.
Standardization and Normalization are important to put all of the features in the same scale.
Algorithms like linear regression are called deterministic and what they do is to find the best numbers to solve a mathematical equation, better said, a linear equation if we’re talking about linear regression.
So the model will test many values to put as each variable’s coefficients. The numbers will be proportional to the magnitude of the variables. That said, we can understand that variables floating on the tens of thousands will have higher coefficients than those in the units range. The importance given to each will follow.
Including very large and very small numbers in a regression can lead to computational problems. When you normalize or standardize, you mitigate the problem.
There is a transformation that can change the shape of your data and make it to approximate of a normal distribution. That is the logarithmic transformation.
# Log transform and Normality scs.shapiro(df.tip.apply(np.log))[OUT]: (0.9888471961021423, 0.05621703341603279)p-Value > 0.05 : Data is normal# Histogram after Log transformationsns.histplot(df.tip.apply(np.log) );
The log transformation will remove the skewness of a dataset because it puts everything in perspective. The variances will be proportional rather than absolute, thus the shape changes and resembles a normal distribution.
A nice description I saw about this is that log transformation is like looking at a map with a scale legend where 1 cm = 1 km. We put the whole mapped space on the perspective of centimeters. We normalized the data.
As far as I researched, there is no consensus whether it’s better to use Normalization or Standardization. I guess each dataset will react differently to the transformations. It is a matter of testing and comparing, given the computational power these days.
Regarding the log transformation, well, if your data is not originally normally distributed, it won’t be a log transformation that will make it that way. You can transform it, but you must reverse it later to get the real number as prediction result, for example.
The Ordinary Least Squares (OLS) regression method — calculates the linear equation that best fits to the data considering that the sum of the squares of the errors is minimum — is a math expression that predicts y based on a constant (intercept value) plus a coefficient multiplying X plus an error component (y = a + bx + e). The OLS method operates better when those errors are normally distributed, and the analyzing the residuals (predicted - actual value) are the best proxy for that.
When the residuals don’t follow a normal distribution, it is recommended that we transform the independent variable (target) to a normal distribution using a log transformation (or another Box-Cox power transformation). If that is not enough, then you can try transforming the dependent variables as well, aiming for a better fit of the model.
Thus, log transformation is recommended if you’re working with a linear model and needs to improve the linear relationship between two variables. Sometimes the relationship between variables can be exponential and log is the inverse operation of the exponential power, thus a curve becomes a line after transformation.
I am no statistician or mathematician. I always make that clear and I also encourage statisticians to help me to explain this content to a broader public, the easiest way possible.
It is not easy to explain such a dense content in simple words.
I will end here with these references.
Why to log transform.
Normalization and data shape.
Normalize or Not.
When to Normalize or Standardize.
If this content is useful, follow my blog for more.
If you want to support my content by subscribing to medium, use this referral link:
|
[
{
"code": null,
"e": 408,
"s": 171,
"text": "I will start this post with a statement: normalization and standardization will not change the distribution of your data. In other words, if your variable is not normally distributed, it won’t be turn into one with the normalize method."
},
{
"code": null,
"e": 490,
"s": 408,
"text": "normalize() or StandardScaler() from sklearn won’t change the shape of your data."
},
{
"code": null,
"e": 665,
"s": 490,
"text": "Standardization can be done using sklearn.preprocessing.StandardScaler module. What it does to your variable is centering the data to a mean of 0 and standard deviation of 1."
},
{
"code": null,
"e": 911,
"s": 665,
"text": "Doing that is important to put your data in the same scale. Sometimes you’re working with many variables of different scales. For example, let’s say you’re working on a linear regression project that has variables like years of study and salary."
},
{
"code": null,
"e": 1081,
"s": 911,
"text": "Do you agree with me that years of study will float somewhere between 1 to 30? And do you also agree that the salary variable will be within the tens of thousands range?"
},
{
"code": null,
"e": 1421,
"s": 1081,
"text": "Well, that’s a big difference between variables. That said, once the linear regression algorithm will calculate the coefficients, naturally it will give a higher number to salary in opposition to years of study. But we know we don’t want the model to make that differentiation, so we can standardize the data to put them in the same scale."
},
{
"code": null,
"e": 1650,
"s": 1421,
"text": "import pandas as pdimport seaborn as snsfrom sklearn.preprocessing import StandardScaler, normalizeimport scipy.stats as scs# Pull a datasetdf = sns.load_dataset('tips')# Histogram of tip variablesns.histoplot(data=df, x='tip');"
},
{
"code": null,
"e": 1680,
"s": 1650,
"text": "Ok. Applying standardization."
},
{
"code": null,
"e": 1925,
"s": 1680,
"text": "# standardizingscaler = StandardScaler()scaled = scaler.fit_transform(df[['tip']])# Mean and Std of standardized dataprint(f'Mean: {scaled.mean().round()} | Std: {scaled.std().round()}')[OUT]: Mean: 0.0 | Std: 1.0# Histplotsns.histplot(scaled);"
},
{
"code": null,
"e": 2224,
"s": 1925,
"text": "The shape is the same. It wasn’t normal before. It’s not normal now. And we can take a Shapiro test for normal distributions before and after to confirm. The p-Value is the second number in the parenthesis (statistic test number, p-Value) and if smaller than 0.05, it means not normal distribution."
},
{
"code": null,
"e": 2413,
"s": 2224,
"text": "# Normal test original datascs.shapiro(df.tip)[OUT]: (0.897811233997345, 8.20057563521992e-12)# Normal test scaled datascs.shapiro(scaled)[OUT]: (0.8978115916252136, 8.201060490431455e-12)"
},
{
"code": null,
"e": 2712,
"s": 2413,
"text": "Normalization can be performed in Python with normalize() from sklearn and it won’t change the shape of your data as well. It brings the data to the same scale as well, but the main difference here is that it will present numbers between 0 and 1 (but it won’t center the data on mean 0 and std =1)."
},
{
"code": null,
"e": 3012,
"s": 2712,
"text": "One of the most common ways to normalize is the Min Max normalization, that basically makes the maximum value equals 1 and the minimum equals 0. Everything in between will be a percentage of that, or a number between 0 and 1. However, in this example we’re using the normalize function from sklearn."
},
{
"code": null,
"e": 3195,
"s": 3012,
"text": "# normalizenormalized = normalize(df[['tip']], axis=0)# Normalized, but NOT Normal distribution. p-Value < 0.05scs.shapiro(normalized)[OUT]: (0.897811233997345, 8.20057563521992e-12)"
},
{
"code": null,
"e": 3274,
"s": 3195,
"text": "Again, our shape remains the same. The data is still not normally distributed."
},
{
"code": null,
"e": 3368,
"s": 3274,
"text": "Standardization and Normalization are important to put all of the features in the same scale."
},
{
"code": null,
"e": 3579,
"s": 3368,
"text": "Algorithms like linear regression are called deterministic and what they do is to find the best numbers to solve a mathematical equation, better said, a linear equation if we’re talking about linear regression."
},
{
"code": null,
"e": 3903,
"s": 3579,
"text": "So the model will test many values to put as each variable’s coefficients. The numbers will be proportional to the magnitude of the variables. That said, we can understand that variables floating on the tens of thousands will have higher coefficients than those in the units range. The importance given to each will follow."
},
{
"code": null,
"e": 4060,
"s": 3903,
"text": "Including very large and very small numbers in a regression can lead to computational problems. When you normalize or standardize, you mitigate the problem."
},
{
"code": null,
"e": 4218,
"s": 4060,
"text": "There is a transformation that can change the shape of your data and make it to approximate of a normal distribution. That is the logarithmic transformation."
},
{
"code": null,
"e": 4433,
"s": 4218,
"text": "# Log transform and Normality scs.shapiro(df.tip.apply(np.log))[OUT]: (0.9888471961021423, 0.05621703341603279)p-Value > 0.05 : Data is normal# Histogram after Log transformationsns.histplot(df.tip.apply(np.log) );"
},
{
"code": null,
"e": 4654,
"s": 4433,
"text": "The log transformation will remove the skewness of a dataset because it puts everything in perspective. The variances will be proportional rather than absolute, thus the shape changes and resembles a normal distribution."
},
{
"code": null,
"e": 4870,
"s": 4654,
"text": "A nice description I saw about this is that log transformation is like looking at a map with a scale legend where 1 cm = 1 km. We put the whole mapped space on the perspective of centimeters. We normalized the data."
},
{
"code": null,
"e": 5128,
"s": 4870,
"text": "As far as I researched, there is no consensus whether it’s better to use Normalization or Standardization. I guess each dataset will react differently to the transformations. It is a matter of testing and comparing, given the computational power these days."
},
{
"code": null,
"e": 5392,
"s": 5128,
"text": "Regarding the log transformation, well, if your data is not originally normally distributed, it won’t be a log transformation that will make it that way. You can transform it, but you must reverse it later to get the real number as prediction result, for example."
},
{
"code": null,
"e": 5883,
"s": 5392,
"text": "The Ordinary Least Squares (OLS) regression method — calculates the linear equation that best fits to the data considering that the sum of the squares of the errors is minimum — is a math expression that predicts y based on a constant (intercept value) plus a coefficient multiplying X plus an error component (y = a + bx + e). The OLS method operates better when those errors are normally distributed, and the analyzing the residuals (predicted - actual value) are the best proxy for that."
},
{
"code": null,
"e": 6227,
"s": 5883,
"text": "When the residuals don’t follow a normal distribution, it is recommended that we transform the independent variable (target) to a normal distribution using a log transformation (or another Box-Cox power transformation). If that is not enough, then you can try transforming the dependent variables as well, aiming for a better fit of the model."
},
{
"code": null,
"e": 6546,
"s": 6227,
"text": "Thus, log transformation is recommended if you’re working with a linear model and needs to improve the linear relationship between two variables. Sometimes the relationship between variables can be exponential and log is the inverse operation of the exponential power, thus a curve becomes a line after transformation."
},
{
"code": null,
"e": 6727,
"s": 6546,
"text": "I am no statistician or mathematician. I always make that clear and I also encourage statisticians to help me to explain this content to a broader public, the easiest way possible."
},
{
"code": null,
"e": 6791,
"s": 6727,
"text": "It is not easy to explain such a dense content in simple words."
},
{
"code": null,
"e": 6830,
"s": 6791,
"text": "I will end here with these references."
},
{
"code": null,
"e": 6852,
"s": 6830,
"text": "Why to log transform."
},
{
"code": null,
"e": 6882,
"s": 6852,
"text": "Normalization and data shape."
},
{
"code": null,
"e": 6900,
"s": 6882,
"text": "Normalize or Not."
},
{
"code": null,
"e": 6934,
"s": 6900,
"text": "When to Normalize or Standardize."
},
{
"code": null,
"e": 6986,
"s": 6934,
"text": "If this content is useful, follow my blog for more."
}
] |
Rotate xtick labels in Seaborn boxplot using Matplotlib
|
To rotate xtick labels in Seaborn boxplot, we can take the following steps −
Create data points for xticks.
Create data points for xticks.
Draw a boxplot using boxplot() method that returns the axis.
Draw a boxplot using boxplot() method that returns the axis.
Now, set the xticks using set_xticks() method, pass xticks.
Now, set the xticks using set_xticks() method, pass xticks.
Set xticklabels and pass a list of labels and rotate them by passing rotation=45, using set_xticklabels() method.
Set xticklabels and pass a list of labels and rotate them by passing rotation=45, using set_xticklabels() method.
To display the figure, use show() method.
To display the figure, use show() method.
import seaborn as sns
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
xticks = [1, 4, 5, 2, 3]
ax = sns.boxplot(xticks)
ax.set_xticks(xticks)
ax.set_xticklabels(["one", "two", "three", "four", "five"], rotation=45)
plt.show()
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To rotate xtick labels in Seaborn boxplot, we can take the following steps −"
},
{
"code": null,
"e": 1170,
"s": 1139,
"text": "Create data points for xticks."
},
{
"code": null,
"e": 1201,
"s": 1170,
"text": "Create data points for xticks."
},
{
"code": null,
"e": 1262,
"s": 1201,
"text": "Draw a boxplot using boxplot() method that returns the axis."
},
{
"code": null,
"e": 1323,
"s": 1262,
"text": "Draw a boxplot using boxplot() method that returns the axis."
},
{
"code": null,
"e": 1383,
"s": 1323,
"text": "Now, set the xticks using set_xticks() method, pass xticks."
},
{
"code": null,
"e": 1443,
"s": 1383,
"text": "Now, set the xticks using set_xticks() method, pass xticks."
},
{
"code": null,
"e": 1557,
"s": 1443,
"text": "Set xticklabels and pass a list of labels and rotate them by passing rotation=45, using set_xticklabels() method."
},
{
"code": null,
"e": 1671,
"s": 1557,
"text": "Set xticklabels and pass a list of labels and rotate them by passing rotation=45, using set_xticklabels() method."
},
{
"code": null,
"e": 1713,
"s": 1671,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1755,
"s": 1713,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2057,
"s": 1755,
"text": "import seaborn as sns\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nxticks = [1, 4, 5, 2, 3]\nax = sns.boxplot(xticks)\nax.set_xticks(xticks)\nax.set_xticklabels([\"one\", \"two\", \"three\", \"four\", \"five\"], rotation=45)\nplt.show()"
}
] |
Logistic Regression Model Tuning with scikit-learn — Part 1 | by Finn Qiao | Towards Data Science
|
Classifiers are a core component of machine learning models and can be applied widely across a variety of disciplines and problem statements.
With all the packages available out there, running a logistic regression in Python is as easy as running a few lines of code and getting the accuracy of predictions on a test set.
What are some ways to improve on such a base model and how do the results compare?
For the purpose of showing some techniques, we will run some models with the Bank Marketing dataset from the UCI Machine Learning Repository. This dataset represents the direct marketing campaigns of a Portuguese bank and whether the efforts led to a bank term deposit.
After importing the necessary packages for the basic EDA and using the missingno package, it seems that most data is present for this dataset.
To run a logistic regression on this data, we would have to convert all non-numeric features into numeric ones. There are two popular ways to do this: label encoding and one hot encoding.
For label encoding, a different number is assigned to each unique value in the feature column. A potential issue with this method would be the assumption that the label sizes represent ordinality (i.e. a label of 3 is greater than a label of 1).
For one hot encoding, a new feature column is created for each unique value in the feature column. The value would be 1 if the value was present for that observation and 0 otherwise. This method however could easily lead to an explosion in number of features and lead to the curse of dimensionality.
Below, we try to fit one model with only dummy variables and another with only label encoded variables.
Model accuracy is 0.8963340616654528
Model accuracy is 0.9053168244719592
While the resulting model accuracies are quite comparable, a quick look at AUC, another model metric indicates a drastic improvement when label encoding were used.
It seems that label encoding performs much better across the spectrum of different threshold values. However, there are a few features in which the label ordering did not make sense. For example, days of week:
{'fri': 1, 'mon': 2, 'thu': 3, 'tue': 4, 'wed': 5}
Furthermore, the ‘job’ feature in particular would be more explanatory if converted to dummy variables as one’s job would appear to be an important determinant of whether they open a term deposit and an ordinal scale wouldn’t quite make sense.
Below, custom orders were determined for education, month, and day of the week while dummy variables were created for jobs.
Model accuracy is 0.9053168244719592
The resulting model has a comparable accuracy to only label encoded variables while maintaining a similarly high AUC score of 0.92. More importantly, the new mix of labels and dummy variables can now be clearly explained and identified.
The above base model was performed on the original data without any normalization. Here, we adopt the MinMaxScaler and constrain the range of values to be between 0 and 1.
Model accuracy is 0.906409322651129
One might also be skeptical of the immediate AUC score of around 0.9. Upon examining the sample of the response variable, there appears to be a class imbalance problem where only around 10% of the customers subscribed to the term deposit.
There is debate around the severity of the class imbalance issue with a 10:90 split as there are many conversion experiments out there that could have up to a 1:99 split.
Nonetheless, we explore a resampling technique here using SMOTE. In our particular scenario, we oversample the minority class by synthetically generating additional samples.
Model accuracy is 0.8661082787084243
While the resampled data slightly outperformed on AUC, the accuracy drops to 86.6%. This is in fact even lower than our base model.
While we have been using the basic logistic regression model in the above test cases, another popular approach to classification is the random forest model.
Lets repeat the above two models with normalized data and resampled data with the random forest model.
Normalized Model accuracy is 0.9059237679048313Resampled Model accuracy is 0.9047098810390871
Both have comparable accuracy scores but it is interesting to note how the model accuracy on the resampled data greatly improved with the random forest model as opposed to the base logistic regression model.
While both AUC scores were slightly lower than those of the logistic models, it seems that using a random forest model on resampled data performed better on aggregate across accuracy and AUC metrics.
It is notable that the above models were run with the default parameters determined by the LogisticRegression and RandomForestClassifier modules. Could we improve the model by tuning the hyperparameters of the model?
To achieve this, we define a “grid” of parameters that we would want to test out in the model and select the best model using GridSearchCV.
With the above grid search, we utilize a parameter grid that consists of two dictionaries.
The first dictionary includes all variations of LogisticRegression I want to run in the model that includes variations with respect to type of regularization, size of penalty, and type of solver used.
The second dictionary includes all variations of RandomForestClassifier and includes different ranges for the number of estimators (trees) and the maximum number of features used in the model.
Fitting 5 folds for each of 100 candidates, totalling 500 fits[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.[Parallel(n_jobs=-1)]: Done 42 tasks | elapsed: 4.7s[Parallel(n_jobs=-1)]: Done 192 tasks | elapsed: 43.1s[Parallel(n_jobs=-1)]: Done 442 tasks | elapsed: 6.4min[Parallel(n_jobs=-1)]: Done 500 out of 500 | elapsed: 8.8min finished
With the defined parameter ranges, 100 potential models were evaluated. As I had chosen a 5-fold cross validation, that resulted in 500 different models being fitted. This took around 9 minutes.
This is what the “best” model looks like for parameters:
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features=6, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False)
The accuracy of 0.908 and AUC score of 0.94 are both the highest we’ve seen of each respective metric from all models so far.
Model accuracy is 0.9083515416363195
Repeating the same fit on resampled data yielded the same accuracy and classification report but took up to 23 minutes to run.
How have different classification metrics improved from our base model?
Base model classification report:
precision recall f1-score support 0 0.97 0.92 0.95 7691 1 0.38 0.64 0.47 547 micro avg 0.91 0.91 0.91 8238 macro avg 0.67 0.78 0.71 8238weighted avg 0.93 0.91 0.92 8238
“Final” model classification report:
precision recall f1-score support 0 0.97 0.94 0.95 7537 1 0.48 0.64 0.55 701 micro avg 0.91 0.91 0.91 8238 macro avg 0.72 0.79 0.75 8238weighted avg 0.92 0.91 0.92 8238
It appears that all models performed very well for the majority class, with precision, recall metrics all above 0.9.
The new improved model though performs much better for the minority class and arguably the “more important” classification of whether a customer was going to subscribe to the term deposit.
The AUC score was also improved to 0.94 which suggests that the final model also performs better across different threshold values.
While we have managed to improve the base model, there are still many ways to tune the model including polynomial feature generation, sklearn feature selection, and tuning of more hyperparameters for grid search.
These will be the focus of Part 2! In the meantime, thanks for reading and the code can be found here. Feel free to connect on LinkedIn as well!
|
[
{
"code": null,
"e": 313,
"s": 171,
"text": "Classifiers are a core component of machine learning models and can be applied widely across a variety of disciplines and problem statements."
},
{
"code": null,
"e": 493,
"s": 313,
"text": "With all the packages available out there, running a logistic regression in Python is as easy as running a few lines of code and getting the accuracy of predictions on a test set."
},
{
"code": null,
"e": 576,
"s": 493,
"text": "What are some ways to improve on such a base model and how do the results compare?"
},
{
"code": null,
"e": 846,
"s": 576,
"text": "For the purpose of showing some techniques, we will run some models with the Bank Marketing dataset from the UCI Machine Learning Repository. This dataset represents the direct marketing campaigns of a Portuguese bank and whether the efforts led to a bank term deposit."
},
{
"code": null,
"e": 989,
"s": 846,
"text": "After importing the necessary packages for the basic EDA and using the missingno package, it seems that most data is present for this dataset."
},
{
"code": null,
"e": 1177,
"s": 989,
"text": "To run a logistic regression on this data, we would have to convert all non-numeric features into numeric ones. There are two popular ways to do this: label encoding and one hot encoding."
},
{
"code": null,
"e": 1423,
"s": 1177,
"text": "For label encoding, a different number is assigned to each unique value in the feature column. A potential issue with this method would be the assumption that the label sizes represent ordinality (i.e. a label of 3 is greater than a label of 1)."
},
{
"code": null,
"e": 1723,
"s": 1423,
"text": "For one hot encoding, a new feature column is created for each unique value in the feature column. The value would be 1 if the value was present for that observation and 0 otherwise. This method however could easily lead to an explosion in number of features and lead to the curse of dimensionality."
},
{
"code": null,
"e": 1827,
"s": 1723,
"text": "Below, we try to fit one model with only dummy variables and another with only label encoded variables."
},
{
"code": null,
"e": 1864,
"s": 1827,
"text": "Model accuracy is 0.8963340616654528"
},
{
"code": null,
"e": 1901,
"s": 1864,
"text": "Model accuracy is 0.9053168244719592"
},
{
"code": null,
"e": 2065,
"s": 1901,
"text": "While the resulting model accuracies are quite comparable, a quick look at AUC, another model metric indicates a drastic improvement when label encoding were used."
},
{
"code": null,
"e": 2275,
"s": 2065,
"text": "It seems that label encoding performs much better across the spectrum of different threshold values. However, there are a few features in which the label ordering did not make sense. For example, days of week:"
},
{
"code": null,
"e": 2326,
"s": 2275,
"text": "{'fri': 1, 'mon': 2, 'thu': 3, 'tue': 4, 'wed': 5}"
},
{
"code": null,
"e": 2570,
"s": 2326,
"text": "Furthermore, the ‘job’ feature in particular would be more explanatory if converted to dummy variables as one’s job would appear to be an important determinant of whether they open a term deposit and an ordinal scale wouldn’t quite make sense."
},
{
"code": null,
"e": 2694,
"s": 2570,
"text": "Below, custom orders were determined for education, month, and day of the week while dummy variables were created for jobs."
},
{
"code": null,
"e": 2731,
"s": 2694,
"text": "Model accuracy is 0.9053168244719592"
},
{
"code": null,
"e": 2968,
"s": 2731,
"text": "The resulting model has a comparable accuracy to only label encoded variables while maintaining a similarly high AUC score of 0.92. More importantly, the new mix of labels and dummy variables can now be clearly explained and identified."
},
{
"code": null,
"e": 3140,
"s": 2968,
"text": "The above base model was performed on the original data without any normalization. Here, we adopt the MinMaxScaler and constrain the range of values to be between 0 and 1."
},
{
"code": null,
"e": 3176,
"s": 3140,
"text": "Model accuracy is 0.906409322651129"
},
{
"code": null,
"e": 3415,
"s": 3176,
"text": "One might also be skeptical of the immediate AUC score of around 0.9. Upon examining the sample of the response variable, there appears to be a class imbalance problem where only around 10% of the customers subscribed to the term deposit."
},
{
"code": null,
"e": 3586,
"s": 3415,
"text": "There is debate around the severity of the class imbalance issue with a 10:90 split as there are many conversion experiments out there that could have up to a 1:99 split."
},
{
"code": null,
"e": 3760,
"s": 3586,
"text": "Nonetheless, we explore a resampling technique here using SMOTE. In our particular scenario, we oversample the minority class by synthetically generating additional samples."
},
{
"code": null,
"e": 3797,
"s": 3760,
"text": "Model accuracy is 0.8661082787084243"
},
{
"code": null,
"e": 3929,
"s": 3797,
"text": "While the resampled data slightly outperformed on AUC, the accuracy drops to 86.6%. This is in fact even lower than our base model."
},
{
"code": null,
"e": 4086,
"s": 3929,
"text": "While we have been using the basic logistic regression model in the above test cases, another popular approach to classification is the random forest model."
},
{
"code": null,
"e": 4189,
"s": 4086,
"text": "Lets repeat the above two models with normalized data and resampled data with the random forest model."
},
{
"code": null,
"e": 4283,
"s": 4189,
"text": "Normalized Model accuracy is 0.9059237679048313Resampled Model accuracy is 0.9047098810390871"
},
{
"code": null,
"e": 4491,
"s": 4283,
"text": "Both have comparable accuracy scores but it is interesting to note how the model accuracy on the resampled data greatly improved with the random forest model as opposed to the base logistic regression model."
},
{
"code": null,
"e": 4691,
"s": 4491,
"text": "While both AUC scores were slightly lower than those of the logistic models, it seems that using a random forest model on resampled data performed better on aggregate across accuracy and AUC metrics."
},
{
"code": null,
"e": 4908,
"s": 4691,
"text": "It is notable that the above models were run with the default parameters determined by the LogisticRegression and RandomForestClassifier modules. Could we improve the model by tuning the hyperparameters of the model?"
},
{
"code": null,
"e": 5048,
"s": 4908,
"text": "To achieve this, we define a “grid” of parameters that we would want to test out in the model and select the best model using GridSearchCV."
},
{
"code": null,
"e": 5139,
"s": 5048,
"text": "With the above grid search, we utilize a parameter grid that consists of two dictionaries."
},
{
"code": null,
"e": 5340,
"s": 5139,
"text": "The first dictionary includes all variations of LogisticRegression I want to run in the model that includes variations with respect to type of regularization, size of penalty, and type of solver used."
},
{
"code": null,
"e": 5533,
"s": 5340,
"text": "The second dictionary includes all variations of RandomForestClassifier and includes different ranges for the number of estimators (trees) and the maximum number of features used in the model."
},
{
"code": null,
"e": 5924,
"s": 5533,
"text": "Fitting 5 folds for each of 100 candidates, totalling 500 fits[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.[Parallel(n_jobs=-1)]: Done 42 tasks | elapsed: 4.7s[Parallel(n_jobs=-1)]: Done 192 tasks | elapsed: 43.1s[Parallel(n_jobs=-1)]: Done 442 tasks | elapsed: 6.4min[Parallel(n_jobs=-1)]: Done 500 out of 500 | elapsed: 8.8min finished"
},
{
"code": null,
"e": 6119,
"s": 5924,
"text": "With the defined parameter ranges, 100 potential models were evaluated. As I had chosen a 5-fold cross validation, that resulted in 500 different models being fitted. This took around 9 minutes."
},
{
"code": null,
"e": 6176,
"s": 6119,
"text": "This is what the “best” model looks like for parameters:"
},
{
"code": null,
"e": 6590,
"s": 6176,
"text": "RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None, max_features=6, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False)"
},
{
"code": null,
"e": 6716,
"s": 6590,
"text": "The accuracy of 0.908 and AUC score of 0.94 are both the highest we’ve seen of each respective metric from all models so far."
},
{
"code": null,
"e": 6753,
"s": 6716,
"text": "Model accuracy is 0.9083515416363195"
},
{
"code": null,
"e": 6880,
"s": 6753,
"text": "Repeating the same fit on resampled data yielded the same accuracy and classification report but took up to 23 minutes to run."
},
{
"code": null,
"e": 6952,
"s": 6880,
"text": "How have different classification metrics improved from our base model?"
},
{
"code": null,
"e": 6986,
"s": 6952,
"text": "Base model classification report:"
},
{
"code": null,
"e": 7305,
"s": 6986,
"text": " precision recall f1-score support 0 0.97 0.92 0.95 7691 1 0.38 0.64 0.47 547 micro avg 0.91 0.91 0.91 8238 macro avg 0.67 0.78 0.71 8238weighted avg 0.93 0.91 0.92 8238"
},
{
"code": null,
"e": 7342,
"s": 7305,
"text": "“Final” model classification report:"
},
{
"code": null,
"e": 7661,
"s": 7342,
"text": " precision recall f1-score support 0 0.97 0.94 0.95 7537 1 0.48 0.64 0.55 701 micro avg 0.91 0.91 0.91 8238 macro avg 0.72 0.79 0.75 8238weighted avg 0.92 0.91 0.92 8238"
},
{
"code": null,
"e": 7778,
"s": 7661,
"text": "It appears that all models performed very well for the majority class, with precision, recall metrics all above 0.9."
},
{
"code": null,
"e": 7967,
"s": 7778,
"text": "The new improved model though performs much better for the minority class and arguably the “more important” classification of whether a customer was going to subscribe to the term deposit."
},
{
"code": null,
"e": 8099,
"s": 7967,
"text": "The AUC score was also improved to 0.94 which suggests that the final model also performs better across different threshold values."
},
{
"code": null,
"e": 8312,
"s": 8099,
"text": "While we have managed to improve the base model, there are still many ways to tune the model including polynomial feature generation, sklearn feature selection, and tuning of more hyperparameters for grid search."
}
] |
Program to extract frames using OpenCV in Python?
|
OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products.
With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & reorganization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more.
In this exercise we are going to implement frame by frame video processing. The input video can be live camera video or video stored in your local machine. We are going to create frames from the video stored in our local machine & then store the frames in our local drive.
As opencv is not a standard python library, so we need to install it. We can install it using pip very easily:
pip install opencv-python
Collecting opencv-python
Downloading https://files.pythonhosted.org/packages/49/4b/ad55a2e2c309fb698e1283e687129e0892c7864de9a4424c4ff01ba0a3bb/opencv_python-4.0.0.21-cp36-cp36m-win32.whl (22.1MB)
100% |████████████████████████████████| 22.1MB 141kB/s
Requirement already satisfied: numpy>=1.11.3 in c:\python\python361\lib\site-packages (from opencv-python) (1.13.0)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.0.0.21
My video file is stored in the f: drive, which I want to convert into frames (thumbnails) and then store the frames in my chosen location.
Code: Program to read a video file and extract frames from it.
#Import libraries
import cv2
import os
#Function to extract frames
def extractFrames(pathIn, pathOut):
#directory path, where my video images will be stored
os.mkdir(r'c:/users/rajesh/Desktop/data')
#Capture vidoe from video file
cap = cv2.VideoCapture(pathIn)
#Counter Variable
count = 0
while (cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
if ret == True:
print('Read %d frame: ' % count, ret)
# save frame as JPEG file
cv2.imwrite(os.path.join(pathOut, "frame{:d}.jpg".format(count)), frame)
count += 1
else:
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def main():
extractFrames(r'f:/I Miss You.mp4' , 'data')
if __name__=="__main__":
main()
We can see, a data folder is created in my desktop(destination path) and the frames from the video are stored inside the folder.
|
[
{
"code": null,
"e": 1338,
"s": 1062,
"text": "OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products."
},
{
"code": null,
"e": 1767,
"s": 1338,
"text": "With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & reorganization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more."
},
{
"code": null,
"e": 2040,
"s": 1767,
"text": "In this exercise we are going to implement frame by frame video processing. The input video can be live camera video or video stored in your local machine. We are going to create frames from the video stored in our local machine & then store the frames in our local drive."
},
{
"code": null,
"e": 2151,
"s": 2040,
"text": "As opencv is not a standard python library, so we need to install it. We can install it using pip very easily:"
},
{
"code": null,
"e": 2636,
"s": 2151,
"text": "pip install opencv-python\nCollecting opencv-python\nDownloading https://files.pythonhosted.org/packages/49/4b/ad55a2e2c309fb698e1283e687129e0892c7864de9a4424c4ff01ba0a3bb/opencv_python-4.0.0.21-cp36-cp36m-win32.whl (22.1MB)\n100% |████████████████████████████████| 22.1MB 141kB/s\nRequirement already satisfied: numpy>=1.11.3 in c:\\python\\python361\\lib\\site-packages (from opencv-python) (1.13.0)\nInstalling collected packages: opencv-python\nSuccessfully installed opencv-python-4.0.0.21"
},
{
"code": null,
"e": 2775,
"s": 2636,
"text": "My video file is stored in the f: drive, which I want to convert into frames (thumbnails) and then store the frames in my chosen location."
},
{
"code": null,
"e": 2838,
"s": 2775,
"text": "Code: Program to read a video file and extract frames from it."
},
{
"code": null,
"e": 3608,
"s": 2838,
"text": "#Import libraries\nimport cv2\nimport os\n#Function to extract frames\ndef extractFrames(pathIn, pathOut):\n #directory path, where my video images will be stored\n os.mkdir(r'c:/users/rajesh/Desktop/data')\n #Capture vidoe from video file\n cap = cv2.VideoCapture(pathIn)\n#Counter Variable\ncount = 0\n\nwhile (cap.isOpened()):\n # Capture frame-by-frame\n ret, frame = cap.read()\n if ret == True:\n print('Read %d frame: ' % count, ret)\n # save frame as JPEG file\n cv2.imwrite(os.path.join(pathOut, \"frame{:d}.jpg\".format(count)), frame)\n count += 1\n else:\n break\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\ndef main():\n extractFrames(r'f:/I Miss You.mp4' , 'data')\nif __name__==\"__main__\":\n main()"
},
{
"code": null,
"e": 3737,
"s": 3608,
"text": "We can see, a data folder is created in my desktop(destination path) and the frames from the video are stored inside the folder."
}
] |
3D Scatter Plot using graph_objects Class in Plotly-Python - GeeksforGeeks
|
10 Jul, 2020
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
If a plotly express does not provide a good starting point, then it is possible to use go.Scatter3D class from plotly.graph_objects. Scatter plot are those charts in which data points are represented horizontally and on the vertical axis to show how one variable affect on another variable. The mode of the property decides the appearance of data points.
Syntax: plotly.graph_objects.Scatter3d(arg=None, connectgaps=None, customdata=None, customdatasrc=None, error_x=None, error_y=None, error_z=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, projection=None, scene=None, showlegend=None, stream=None, surfaceaxis=None, surfacecolor=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, visible=None, x=None, xcalendar=None, xsrc=None, y=None, ycalendar=None, ysrc=None, z=None, zcalendar=None, zsrc=None, **kwargs)
Parameters:
x – Sets the x coordinates.
y – Sets the y coordinates.
z – Sets the z coordinates.
mode – Determines the drawing mode for this scatter trace.
Example 1:
Python3
import plotly.express as pximport plotly.graph_objects as go df = px.data.tips() fig = go.Figure(data =[go.Scatter3d(x = df['total_bill'], y = df['time'], z = df['tip'], mode ='markers')])fig.show()
Output:
Example 2:
Python3
import plotly.express as pximport plotly.graph_objects as go df = px.data.iris() fig = go.Figure(data =[go.Scatter3d(x = df['sepal_width'], y = df['sepal_length'], z = df['petal_length'], mode ='markers')])fig.show()
Output:
In plotly, color scaling and marker styling are a way to represent the data more effectively, and it makes data more understandable.
Example 1:
Python3
import plotly.express as pximport plotly.graph_objects as go df = px.data.iris() fig = go.Figure(data =[go.Scatter3d(x = df['sepal_width'], y = df['sepal_length'], z = df['petal_length'], mode ='markers', marker = dict( size = 12, color = df['petal_width'], colorscale ='Viridis', opacity = 0.8 ))]) fig.show()
Output:
Example 2:
Python3
import plotly.express as pximport plotly.graph_objects as go df = px.data.tips() fig = go.Figure(data =[go.Scatter3d(x = df['total_bill'], y = df['time'], z = df['day'], mode ='markers', marker = dict( color = df['tip'], colorscale ='Viridis', opacity = 0.5 ))])fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions
sum() function in Python
|
[
{
"code": null,
"e": 24726,
"s": 24698,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 25028,
"s": 24726,
"text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 25383,
"s": 25028,
"text": "If a plotly express does not provide a good starting point, then it is possible to use go.Scatter3D class from plotly.graph_objects. Scatter plot are those charts in which data points are represented horizontally and on the vertical axis to show how one variable affect on another variable. The mode of the property decides the appearance of data points."
},
{
"code": null,
"e": 26159,
"s": 25383,
"text": "Syntax: plotly.graph_objects.Scatter3d(arg=None, connectgaps=None, customdata=None, customdatasrc=None, error_x=None, error_y=None, error_z=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, projection=None, scene=None, showlegend=None, stream=None, surfaceaxis=None, surfacecolor=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, visible=None, x=None, xcalendar=None, xsrc=None, y=None, ycalendar=None, ysrc=None, z=None, zcalendar=None, zsrc=None, **kwargs)"
},
{
"code": null,
"e": 26171,
"s": 26159,
"text": "Parameters:"
},
{
"code": null,
"e": 26199,
"s": 26171,
"text": "x – Sets the x coordinates."
},
{
"code": null,
"e": 26227,
"s": 26199,
"text": "y – Sets the y coordinates."
},
{
"code": null,
"e": 26255,
"s": 26227,
"text": "z – Sets the z coordinates."
},
{
"code": null,
"e": 26314,
"s": 26255,
"text": "mode – Determines the drawing mode for this scatter trace."
},
{
"code": null,
"e": 26325,
"s": 26314,
"text": "Example 1:"
},
{
"code": null,
"e": 26333,
"s": 26325,
"text": "Python3"
},
{
"code": "import plotly.express as pximport plotly.graph_objects as go df = px.data.tips() fig = go.Figure(data =[go.Scatter3d(x = df['total_bill'], y = df['time'], z = df['tip'], mode ='markers')])fig.show()",
"e": 26636,
"s": 26333,
"text": null
},
{
"code": null,
"e": 26644,
"s": 26636,
"text": "Output:"
},
{
"code": null,
"e": 26655,
"s": 26644,
"text": "Example 2:"
},
{
"code": null,
"e": 26663,
"s": 26655,
"text": "Python3"
},
{
"code": "import plotly.express as pximport plotly.graph_objects as go df = px.data.iris() fig = go.Figure(data =[go.Scatter3d(x = df['sepal_width'], y = df['sepal_length'], z = df['petal_length'], mode ='markers')])fig.show()",
"e": 26984,
"s": 26663,
"text": null
},
{
"code": null,
"e": 26992,
"s": 26984,
"text": "Output:"
},
{
"code": null,
"e": 27126,
"s": 26992,
"text": "In plotly, color scaling and marker styling are a way to represent the data more effectively, and it makes data more understandable. "
},
{
"code": null,
"e": 27137,
"s": 27126,
"text": "Example 1:"
},
{
"code": null,
"e": 27145,
"s": 27137,
"text": "Python3"
},
{
"code": "import plotly.express as pximport plotly.graph_objects as go df = px.data.iris() fig = go.Figure(data =[go.Scatter3d(x = df['sepal_width'], y = df['sepal_length'], z = df['petal_length'], mode ='markers', marker = dict( size = 12, color = df['petal_width'], colorscale ='Viridis', opacity = 0.8 ))]) fig.show()",
"e": 27774,
"s": 27145,
"text": null
},
{
"code": null,
"e": 27782,
"s": 27774,
"text": "Output:"
},
{
"code": null,
"e": 27793,
"s": 27782,
"text": "Example 2:"
},
{
"code": null,
"e": 27801,
"s": 27793,
"text": "Python3"
},
{
"code": "import plotly.express as pximport plotly.graph_objects as go df = px.data.tips() fig = go.Figure(data =[go.Scatter3d(x = df['total_bill'], y = df['time'], z = df['day'], mode ='markers', marker = dict( color = df['tip'], colorscale ='Viridis', opacity = 0.5 ))])fig.show()",
"e": 28354,
"s": 27801,
"text": null
},
{
"code": null,
"e": 28362,
"s": 28354,
"text": "Output:"
},
{
"code": null,
"e": 28376,
"s": 28362,
"text": "Python-Plotly"
},
{
"code": null,
"e": 28383,
"s": 28376,
"text": "Python"
},
{
"code": null,
"e": 28481,
"s": 28383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28490,
"s": 28481,
"text": "Comments"
},
{
"code": null,
"e": 28503,
"s": 28490,
"text": "Old Comments"
},
{
"code": null,
"e": 28521,
"s": 28503,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28556,
"s": 28521,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28578,
"s": 28556,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28610,
"s": 28578,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28652,
"s": 28610,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28678,
"s": 28652,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28715,
"s": 28678,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28759,
"s": 28715,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28814,
"s": 28759,
"text": "Selecting rows in pandas DataFrame based on conditions"
}
] |
Express.js – app.post() Method
|
The app.post() method routes all the HTTP POST requests to the specified path with the specified callback functions.
app.path(path, callback, [callback])
path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these.
callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route).
Create a file with the name "appPost.js" and copy the following code snippet. After creating the file, use the command "node appPost.js" to run this code.
// app.post() Method Demo Example
// Importing the express module
const express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Creating a POST request
app.post('/api', (req, res) => {
console.log("POST Request Called for /api endpoint")
res.send("POST Request Called")
})
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Hit the following Endpoint with a POST request
http://localhost:3000/api
C:\home\node>> node appPost.js
Server listening on PORT 3000
POST Request Called for /api endpoint
Let’s take a look at one more example.
// app.post() Method Demo Example
// Importing the express module
const express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Creating a POST request
app.post('/api', (req, res) => {
console.log("Method called is -- ", req.method)
res.end()
})
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Now, hit the following Endpoint with a POST request
http://localhost:3000/api
C:\home\node>> node appPost.js
Server listening on PORT 3000
Method called is -- POST
|
[
{
"code": null,
"e": 1179,
"s": 1062,
"text": "The app.post() method routes all the HTTP POST requests to the specified path with the specified callback functions."
},
{
"code": null,
"e": 1216,
"s": 1179,
"text": "app.path(path, callback, [callback])"
},
{
"code": null,
"e": 1371,
"s": 1216,
"text": "path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these."
},
{
"code": null,
"e": 1534,
"s": 1371,
"text": "callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route)."
},
{
"code": null,
"e": 1689,
"s": 1534,
"text": "Create a file with the name \"appPost.js\" and copy the following code snippet. After creating the file, use the command \"node appPost.js\" to run this code."
},
{
"code": null,
"e": 2253,
"s": 1689,
"text": "// app.post() Method Demo Example\n\n// Importing the express module\nconst express = require('express');\n\n// Initializing the express and port number\nvar app = express();\n// Initializing the router from express\nvar router = express.Router();\nvar PORT = 3000;\n\n// Creating a POST request\napp.post('/api', (req, res) => {\n console.log(\"POST Request Called for /api endpoint\")\n res.send(\"POST Request Called\")\n})\n\n// App listening on the below port\napp.listen(PORT, function(err){\n if (err) console.log(err);\n console.log(\"Server listening on PORT\", PORT);\n});"
},
{
"code": null,
"e": 2300,
"s": 2253,
"text": "Hit the following Endpoint with a POST request"
},
{
"code": null,
"e": 2327,
"s": 2300,
"text": "http://localhost:3000/api\n"
},
{
"code": null,
"e": 2426,
"s": 2327,
"text": "C:\\home\\node>> node appPost.js\nServer listening on PORT 3000\nPOST Request Called for /api endpoint"
},
{
"code": null,
"e": 2465,
"s": 2426,
"text": "Let’s take a look at one more example."
},
{
"code": null,
"e": 3002,
"s": 2465,
"text": "// app.post() Method Demo Example\n\n// Importing the express module\nconst express = require('express');\n\n// Initializing the express and port number\nvar app = express();\n// Initializing the router from express\nvar router = express.Router();\nvar PORT = 3000;\n\n// Creating a POST request\napp.post('/api', (req, res) => {\n console.log(\"Method called is -- \", req.method)\n res.end()\n})\n\n// App listening on the below port\napp.listen(PORT, function(err){\n if (err) console.log(err);\n console.log(\"Server listening on PORT\", PORT);\n});"
},
{
"code": null,
"e": 3054,
"s": 3002,
"text": "Now, hit the following Endpoint with a POST request"
},
{
"code": null,
"e": 3081,
"s": 3054,
"text": "http://localhost:3000/api\n"
},
{
"code": null,
"e": 3167,
"s": 3081,
"text": "C:\\home\\node>> node appPost.js\nServer listening on PORT 3000\nMethod called is -- POST"
}
] |
Lodash _.prototype.toJSON() Method - GeeksforGeeks
|
18 Sep, 2020
The _.prototype.toJSON() method of Sequence in lodash is used to execute the chain sequence in order to solve the unwrapped value.
Syntax:
_.prototype.toJSON()
Parameters: This method doesn’t accept any parameter.
Return Value: This method returns the resolved unwrapped value.
Below examples illustrate the Lodash _.prototype.toJSON() method in JavaScript:
Example 1:
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Calling _.prototype.toJSON() method let unwrap_val = _([6, 7, 8]).toJSON(); // Displays outputconsole.log(unwrap_val);
Output:
[ 6, 7, 8 ]
Example 2:
Javascript
// Requiring lodash libraryconst _ = require('lodash'); // Defining valueslet values = {"gfg":3, "geek":15}; // Calling _.prototype.toJSON() method let res = _(values).toJSON(); // Displays outputconsole.log(res);
Output:
{ gfg: 3, geek: 15 }
JavaScript-Lodash
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Hide or show elements in HTML using display property
JavaScript | console.log() with Examples
Difference Between PUT and PATCH Request
|
[
{
"code": null,
"e": 37043,
"s": 37015,
"text": "\n18 Sep, 2020"
},
{
"code": null,
"e": 37174,
"s": 37043,
"text": "The _.prototype.toJSON() method of Sequence in lodash is used to execute the chain sequence in order to solve the unwrapped value."
},
{
"code": null,
"e": 37182,
"s": 37174,
"text": "Syntax:"
},
{
"code": null,
"e": 37204,
"s": 37182,
"text": "_.prototype.toJSON()\n"
},
{
"code": null,
"e": 37258,
"s": 37204,
"text": "Parameters: This method doesn’t accept any parameter."
},
{
"code": null,
"e": 37322,
"s": 37258,
"text": "Return Value: This method returns the resolved unwrapped value."
},
{
"code": null,
"e": 37402,
"s": 37322,
"text": "Below examples illustrate the Lodash _.prototype.toJSON() method in JavaScript:"
},
{
"code": null,
"e": 37413,
"s": 37402,
"text": "Example 1:"
},
{
"code": null,
"e": 37424,
"s": 37413,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Calling _.prototype.toJSON() method let unwrap_val = _([6, 7, 8]).toJSON(); // Displays outputconsole.log(unwrap_val);",
"e": 37604,
"s": 37424,
"text": null
},
{
"code": null,
"e": 37612,
"s": 37604,
"text": "Output:"
},
{
"code": null,
"e": 37625,
"s": 37612,
"text": "[ 6, 7, 8 ]\n"
},
{
"code": null,
"e": 37636,
"s": 37625,
"text": "Example 2:"
},
{
"code": null,
"e": 37647,
"s": 37636,
"text": "Javascript"
},
{
"code": "// Requiring lodash libraryconst _ = require('lodash'); // Defining valueslet values = {\"gfg\":3, \"geek\":15}; // Calling _.prototype.toJSON() method let res = _(values).toJSON(); // Displays outputconsole.log(res);",
"e": 37864,
"s": 37647,
"text": null
},
{
"code": null,
"e": 37872,
"s": 37864,
"text": "Output:"
},
{
"code": null,
"e": 37894,
"s": 37872,
"text": "{ gfg: 3, geek: 15 }\n"
},
{
"code": null,
"e": 37912,
"s": 37894,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 37923,
"s": 37912,
"text": "JavaScript"
},
{
"code": null,
"e": 38021,
"s": 37923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38030,
"s": 38021,
"text": "Comments"
},
{
"code": null,
"e": 38043,
"s": 38030,
"text": "Old Comments"
},
{
"code": null,
"e": 38104,
"s": 38043,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 38149,
"s": 38104,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 38221,
"s": 38149,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 38290,
"s": 38221,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 38317,
"s": 38290,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 38369,
"s": 38317,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 38415,
"s": 38369,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 38468,
"s": 38415,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 38509,
"s": 38468,
"text": "JavaScript | console.log() with Examples"
}
] |
reflect.Pointer() Function in Golang with Examples
|
05 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Pointer() Function in Golang is used to get the v’s value as a uintptr. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (v Value) Pointer() uintptr
Parameters: This function does not accept any parameter.
Return Value: This function returns the v’s value as a uintptr.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Pointer() Function package main import ( "reflect" "unsafe" "fmt") func main() { var s = struct{ foo int }{100} var i int rs := reflect.ValueOf(&s).Elem() rf := rs.Field(0) ri := reflect.ValueOf(&i).Elem() // use of Pointer() method rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem() ri.Set(rf) rf.Set(ri) fmt.Println(rf)}
Output:
100
Example 2:
// Golang program to illustrate// reflect.Pointer() Function package main import ( "fmt" "play.ground/foo" "reflect" "unsafe") func GetUnexportedField(field reflect.Value) interface{} { return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Interface()} func SetUnexportedField(field reflect.Value, value interface{}) { reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())). Elem(). Set(reflect.ValueOf(value))} func main() { f := &foo.Foo{ Exported: "Old Value ", } fmt.Println(f.Exported) field := reflect.ValueOf(f).Elem().FieldByName("unexported") SetUnexportedField(field, "New Value") fmt.Println(GetUnexportedField(field))} -- go.mod --module play.ground -- foo/foo.go --package foo type Foo struct { Exported string unexported string}
Output:
Old Value
New Value
Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 369,
"s": 28,
"text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Pointer() Function in Golang is used to get the v’s value as a uintptr. To access this function, one needs to imports the reflect package in the program."
},
{
"code": null,
"e": 377,
"s": 369,
"text": "Syntax:"
},
{
"code": null,
"e": 411,
"s": 377,
"text": "func (v Value) Pointer() uintptr\n"
},
{
"code": null,
"e": 468,
"s": 411,
"text": "Parameters: This function does not accept any parameter."
},
{
"code": null,
"e": 532,
"s": 468,
"text": "Return Value: This function returns the v’s value as a uintptr."
},
{
"code": null,
"e": 597,
"s": 532,
"text": "Below examples illustrate the use of the above method in Golang:"
},
{
"code": null,
"e": 608,
"s": 597,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate// reflect.Pointer() Function package main import ( \"reflect\" \"unsafe\" \"fmt\") func main() { var s = struct{ foo int }{100} var i int rs := reflect.ValueOf(&s).Elem() rf := rs.Field(0) ri := reflect.ValueOf(&i).Elem() // use of Pointer() method rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem() ri.Set(rf) rf.Set(ri) fmt.Println(rf)}",
"e": 1070,
"s": 608,
"text": null
},
{
"code": null,
"e": 1078,
"s": 1070,
"text": "Output:"
},
{
"code": null,
"e": 1083,
"s": 1078,
"text": "100\n"
},
{
"code": null,
"e": 1094,
"s": 1083,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate// reflect.Pointer() Function package main import ( \"fmt\" \"play.ground/foo\" \"reflect\" \"unsafe\") func GetUnexportedField(field reflect.Value) interface{} { return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Interface()} func SetUnexportedField(field reflect.Value, value interface{}) { reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())). Elem(). Set(reflect.ValueOf(value))} func main() { f := &foo.Foo{ Exported: \"Old Value \", } fmt.Println(f.Exported) field := reflect.ValueOf(f).Elem().FieldByName(\"unexported\") SetUnexportedField(field, \"New Value\") fmt.Println(GetUnexportedField(field))} -- go.mod --module play.ground -- foo/foo.go --package foo type Foo struct { Exported string unexported string}",
"e": 1963,
"s": 1094,
"text": null
},
{
"code": null,
"e": 1971,
"s": 1963,
"text": "Output:"
},
{
"code": null,
"e": 1993,
"s": 1971,
"text": "Old Value \nNew Value\n"
},
{
"code": null,
"e": 2008,
"s": 1993,
"text": "Golang-reflect"
},
{
"code": null,
"e": 2020,
"s": 2008,
"text": "Go Language"
}
] |
Convert LinkedList to String in Java
|
28 Mar, 2022
A LinkedList is a linear data structure, in which the elements are not stored at contiguous memory locations.
For converting a linked list to a string we need to traverse the linked list and after that, we need to append the element of the linked list to the string variable.
We can use String class, StringBuilder, or StringBuffer for converting a LinkedList to string.
For appending string we can use the “+” operator for the String class and append method for StringBuffer and StringBuilder.
Example 1:
Java
// Java program to Convert LinkedList to String in Java import java.util.Iterator;import java.util.LinkedList;import java.util.ListIterator; class GFG { public static void main(String[] args) { // creating a linkedlist LinkedList<Integer> list = new LinkedList<>(); // adding elements to linkedlist list.add(100); list.add(200); list.add(300); list.add(400); // By using String Class String s = ""; // using iterator for traversing a linkedlist Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()) { // appending using "+" operator s = s + iterator.next() + " "; } // Displaying output System.out.println(s); // By using String Buffer StringBuffer stringBuffer = new StringBuffer(); // using enhanced for loop for traversing a // linkedlist for (Integer integer : list) { // using append method for appending string stringBuffer.append(integer).append(" "); } // displaying output System.out.println(stringBuffer); // By using String Builder StringBuilder stringBuilder = new StringBuilder(); // using ListIterator for traversing a linked list ListIterator<Integer> listIterator = list.listIterator(); while (listIterator.hasNext()) { // using append method for appending string stringBuilder.append(listIterator.next()) .append(" "); } // displaying output System.out.println(stringBuilder); }}
100 200 300 400
100 200 300 400
100 200 300 400
Example 2:In this example, we will use a user-defined class
Java
// Java program to Convert LinkedList to String in Java import java.util.Iterator;import java.util.LinkedList;import java.util.ListIterator; class friendsDetail { // class field private String name; private String nickName; private int id; // parameterised constructor public friendsDetail(String name, String nickName, int id) { this.name = name; this.nickName = nickName; this.id = id; } // getter for name public String getName() { return name; } // setter for name public void setName(String name) { this.name = name; } // getter for marks public int getID() { return id; } // setter for marks public void setID(int id) { this.id = id; } // getter for nickname public String getNickName() { return nickName; } // setter for nickname public void setNickName(String nickName) { this.nickName = nickName; } //@Override toString method public String toString() { return "name='" + name + '\'' + ", nickName='" + nickName + '\'' + ", ID=" + id; }} class Main { public static void main(String[] args) { LinkedList<friendsDetail> list = new LinkedList<>(); // adding elements to linked list list.add( new friendsDetail("Ridhi", "Goda", 202199)); list.add( new friendsDetail("Ananya", "Natki", 202195)); list.add(new friendsDetail("Ankit", "Chota Don", 202192)); list.add( new friendsDetail("Suraj", "Bhindi", 202147)); list.add( new friendsDetail("Sarthak", "Nagin", 202178)); list.add(new friendsDetail("Sonika", "Chipkali", 202167)); list.add(new friendsDetail("Shishya", "Gorilla", 202157)); System.out.println("Using String Class\n"); // using string class String s = ""; // using iterator for traversing a linked list Iterator<friendsDetail> itr = list.iterator(); while (itr.hasNext()) { // appending string using "+" operator s = s + itr.next() + "\n"; } // Displaying output System.out.println(s); System.out.println("\nUsing String Buffer\n"); // using string buffer StringBuffer stringBuffer = new StringBuffer(); // using enhanced for loop for linked list traversal for (friendsDetail friendmarks : list) { // using append method for appending stringBuffer.append(friendmarks).append("\n"); } // displaying output System.out.println(stringBuffer); // using string builder System.out.println("\nUsing String Builder\n"); // using list iterator for traversing a linked list ListIterator<friendsDetail> itr2 = list.listIterator(); StringBuilder stringBuilder = new StringBuilder(); while (itr2.hasNext()) { // using append method for appending stringBuilder.append(itr2.next()).append("\n"); } // displaying output System.out.println(stringBuilder); }}
Using String Class
name='Ridhi', nickName='Goda', ID=202199
name='Ananya', nickName='Natki', ID=202195
name='Ankit', nickName='Chota Don', ID=202192
name='Suraj', nickName='Bhindi', ID=202147
name='Sarthak', nickName='Nagin', ID=202178
name='Sonika', nickName='Chipkali', ID=202167
name='Shishya', nickName='Gorilla', ID=202157
Using String Buffer
name='Ridhi', nickName='Goda', ID=202199
name='Ananya', nickName='Natki', ID=202195
name='Ankit', nickName='Chota Don', ID=202192
name='Suraj', nickName='Bhindi', ID=202147
name='Sarthak', nickName='Nagin', ID=202178
name='Sonika', nickName='Chipkali', ID=202167
name='Shishya', nickName='Gorilla', ID=202157
Using String Builder
name='Ridhi', nickName='Goda', ID=202199
name='Ananya', nickName='Natki', ID=202195
name='Ankit', nickName='Chota Don', ID=202192
name='Suraj', nickName='Bhindi', ID=202147
name='Sarthak', nickName='Nagin', ID=202178
name='Sonika', nickName='Chipkali', ID=202167
name='Shishya', nickName='Gorilla', ID=202157
arorakashish0911
akshaysingh98088
varshagumber28
Java-Collections
java-LinkedList
Java-Strings
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java-Strings
Java
Java-Collections
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "A LinkedList is a linear data structure, in which the elements are not stored at contiguous memory locations."
},
{
"code": null,
"e": 304,
"s": 138,
"text": "For converting a linked list to a string we need to traverse the linked list and after that, we need to append the element of the linked list to the string variable."
},
{
"code": null,
"e": 399,
"s": 304,
"text": "We can use String class, StringBuilder, or StringBuffer for converting a LinkedList to string."
},
{
"code": null,
"e": 523,
"s": 399,
"text": "For appending string we can use the “+” operator for the String class and append method for StringBuffer and StringBuilder."
},
{
"code": null,
"e": 534,
"s": 523,
"text": "Example 1:"
},
{
"code": null,
"e": 539,
"s": 534,
"text": "Java"
},
{
"code": "// Java program to Convert LinkedList to String in Java import java.util.Iterator;import java.util.LinkedList;import java.util.ListIterator; class GFG { public static void main(String[] args) { // creating a linkedlist LinkedList<Integer> list = new LinkedList<>(); // adding elements to linkedlist list.add(100); list.add(200); list.add(300); list.add(400); // By using String Class String s = \"\"; // using iterator for traversing a linkedlist Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()) { // appending using \"+\" operator s = s + iterator.next() + \" \"; } // Displaying output System.out.println(s); // By using String Buffer StringBuffer stringBuffer = new StringBuffer(); // using enhanced for loop for traversing a // linkedlist for (Integer integer : list) { // using append method for appending string stringBuffer.append(integer).append(\" \"); } // displaying output System.out.println(stringBuffer); // By using String Builder StringBuilder stringBuilder = new StringBuilder(); // using ListIterator for traversing a linked list ListIterator<Integer> listIterator = list.listIterator(); while (listIterator.hasNext()) { // using append method for appending string stringBuilder.append(listIterator.next()) .append(\" \"); } // displaying output System.out.println(stringBuilder); }}",
"e": 2208,
"s": 539,
"text": null
},
{
"code": null,
"e": 2259,
"s": 2208,
"text": "100 200 300 400 \n100 200 300 400 \n100 200 300 400 "
},
{
"code": null,
"e": 2319,
"s": 2259,
"text": "Example 2:In this example, we will use a user-defined class"
},
{
"code": null,
"e": 2324,
"s": 2319,
"text": "Java"
},
{
"code": "// Java program to Convert LinkedList to String in Java import java.util.Iterator;import java.util.LinkedList;import java.util.ListIterator; class friendsDetail { // class field private String name; private String nickName; private int id; // parameterised constructor public friendsDetail(String name, String nickName, int id) { this.name = name; this.nickName = nickName; this.id = id; } // getter for name public String getName() { return name; } // setter for name public void setName(String name) { this.name = name; } // getter for marks public int getID() { return id; } // setter for marks public void setID(int id) { this.id = id; } // getter for nickname public String getNickName() { return nickName; } // setter for nickname public void setNickName(String nickName) { this.nickName = nickName; } //@Override toString method public String toString() { return \"name='\" + name + '\\'' + \", nickName='\" + nickName + '\\'' + \", ID=\" + id; }} class Main { public static void main(String[] args) { LinkedList<friendsDetail> list = new LinkedList<>(); // adding elements to linked list list.add( new friendsDetail(\"Ridhi\", \"Goda\", 202199)); list.add( new friendsDetail(\"Ananya\", \"Natki\", 202195)); list.add(new friendsDetail(\"Ankit\", \"Chota Don\", 202192)); list.add( new friendsDetail(\"Suraj\", \"Bhindi\", 202147)); list.add( new friendsDetail(\"Sarthak\", \"Nagin\", 202178)); list.add(new friendsDetail(\"Sonika\", \"Chipkali\", 202167)); list.add(new friendsDetail(\"Shishya\", \"Gorilla\", 202157)); System.out.println(\"Using String Class\\n\"); // using string class String s = \"\"; // using iterator for traversing a linked list Iterator<friendsDetail> itr = list.iterator(); while (itr.hasNext()) { // appending string using \"+\" operator s = s + itr.next() + \"\\n\"; } // Displaying output System.out.println(s); System.out.println(\"\\nUsing String Buffer\\n\"); // using string buffer StringBuffer stringBuffer = new StringBuffer(); // using enhanced for loop for linked list traversal for (friendsDetail friendmarks : list) { // using append method for appending stringBuffer.append(friendmarks).append(\"\\n\"); } // displaying output System.out.println(stringBuffer); // using string builder System.out.println(\"\\nUsing String Builder\\n\"); // using list iterator for traversing a linked list ListIterator<friendsDetail> itr2 = list.listIterator(); StringBuilder stringBuilder = new StringBuilder(); while (itr2.hasNext()) { // using append method for appending stringBuilder.append(itr2.next()).append(\"\\n\"); } // displaying output System.out.println(stringBuilder); }}",
"e": 5532,
"s": 2324,
"text": null
},
{
"code": null,
"e": 6526,
"s": 5532,
"text": "Using String Class\n\nname='Ridhi', nickName='Goda', ID=202199\nname='Ananya', nickName='Natki', ID=202195\nname='Ankit', nickName='Chota Don', ID=202192\nname='Suraj', nickName='Bhindi', ID=202147\nname='Sarthak', nickName='Nagin', ID=202178\nname='Sonika', nickName='Chipkali', ID=202167\nname='Shishya', nickName='Gorilla', ID=202157\n\n\nUsing String Buffer\n\nname='Ridhi', nickName='Goda', ID=202199\nname='Ananya', nickName='Natki', ID=202195\nname='Ankit', nickName='Chota Don', ID=202192\nname='Suraj', nickName='Bhindi', ID=202147\nname='Sarthak', nickName='Nagin', ID=202178\nname='Sonika', nickName='Chipkali', ID=202167\nname='Shishya', nickName='Gorilla', ID=202157\n\n\nUsing String Builder\n\nname='Ridhi', nickName='Goda', ID=202199\nname='Ananya', nickName='Natki', ID=202195\nname='Ankit', nickName='Chota Don', ID=202192\nname='Suraj', nickName='Bhindi', ID=202147\nname='Sarthak', nickName='Nagin', ID=202178\nname='Sonika', nickName='Chipkali', ID=202167\nname='Shishya', nickName='Gorilla', ID=202157"
},
{
"code": null,
"e": 6543,
"s": 6526,
"text": "arorakashish0911"
},
{
"code": null,
"e": 6560,
"s": 6543,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 6575,
"s": 6560,
"text": "varshagumber28"
},
{
"code": null,
"e": 6592,
"s": 6575,
"text": "Java-Collections"
},
{
"code": null,
"e": 6608,
"s": 6592,
"text": "java-LinkedList"
},
{
"code": null,
"e": 6621,
"s": 6608,
"text": "Java-Strings"
},
{
"code": null,
"e": 6628,
"s": 6621,
"text": "Picked"
},
{
"code": null,
"e": 6652,
"s": 6628,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6657,
"s": 6652,
"text": "Java"
},
{
"code": null,
"e": 6671,
"s": 6657,
"text": "Java Programs"
},
{
"code": null,
"e": 6690,
"s": 6671,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6703,
"s": 6690,
"text": "Java-Strings"
},
{
"code": null,
"e": 6708,
"s": 6703,
"text": "Java"
},
{
"code": null,
"e": 6725,
"s": 6708,
"text": "Java-Collections"
},
{
"code": null,
"e": 6823,
"s": 6725,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6838,
"s": 6823,
"text": "Stream In Java"
},
{
"code": null,
"e": 6859,
"s": 6838,
"text": "Introduction to Java"
},
{
"code": null,
"e": 6880,
"s": 6859,
"text": "Constructors in Java"
},
{
"code": null,
"e": 6899,
"s": 6880,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 6916,
"s": 6899,
"text": "Generics in Java"
},
{
"code": null,
"e": 6942,
"s": 6916,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6976,
"s": 6942,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 7023,
"s": 6976,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 7061,
"s": 7023,
"text": "Factory method design pattern in Java"
}
] |
REPLACE() Function in MySQL
|
31 Aug, 2020
REPLACE() function could be used to replaces all presence of a substring within a string, with a new substring. REPLACE() function is a case-sensitive.
Syntax :
SELECT REPLACE(string, from_string, new_string)
Parameter string is used to replace the original string from_string to be new_string.
Example-1:In this example, you will see how you can replace any string value with a new string value by using the replace function.Let’s consider an example where “MySQL” replace with “HTML” value. Below given is the replace function values.
Replace "MySQL" with "HTML"
Now, you will see how you can read the replace values.
SELECT REPLACE("MySQL in Geeksforgeeks", "SQL", "HTML");
Output :
Example-2:
Replace "X" with "A"
Now, If you want to read the replaced value then use the following function given below.
SELECT REPLACE("It is Good to study XXX from GFG", "X", "A");
Output :
Example-3:
Replace "x" with "a"
Now, If you want to read the replaced value then use the following function given below.
SELECT REPLACE("It is Good to study xxx from GFG", "x", "a");
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 180,
"s": 28,
"text": "REPLACE() function could be used to replaces all presence of a substring within a string, with a new substring. REPLACE() function is a case-sensitive."
},
{
"code": null,
"e": 189,
"s": 180,
"text": "Syntax :"
},
{
"code": null,
"e": 238,
"s": 189,
"text": "SELECT REPLACE(string, from_string, new_string)\n"
},
{
"code": null,
"e": 324,
"s": 238,
"text": "Parameter string is used to replace the original string from_string to be new_string."
},
{
"code": null,
"e": 566,
"s": 324,
"text": "Example-1:In this example, you will see how you can replace any string value with a new string value by using the replace function.Let’s consider an example where “MySQL” replace with “HTML” value. Below given is the replace function values."
},
{
"code": null,
"e": 595,
"s": 566,
"text": "Replace \"MySQL\" with \"HTML\"\n"
},
{
"code": null,
"e": 650,
"s": 595,
"text": "Now, you will see how you can read the replace values."
},
{
"code": null,
"e": 708,
"s": 650,
"text": "SELECT REPLACE(\"MySQL in Geeksforgeeks\", \"SQL\", \"HTML\");\n"
},
{
"code": null,
"e": 717,
"s": 708,
"text": "Output :"
},
{
"code": null,
"e": 728,
"s": 717,
"text": "Example-2:"
},
{
"code": null,
"e": 750,
"s": 728,
"text": "Replace \"X\" with \"A\"\n"
},
{
"code": null,
"e": 839,
"s": 750,
"text": "Now, If you want to read the replaced value then use the following function given below."
},
{
"code": null,
"e": 902,
"s": 839,
"text": "SELECT REPLACE(\"It is Good to study XXX from GFG\", \"X\", \"A\");\n"
},
{
"code": null,
"e": 911,
"s": 902,
"text": "Output :"
},
{
"code": null,
"e": 922,
"s": 911,
"text": "Example-3:"
},
{
"code": null,
"e": 944,
"s": 922,
"text": "Replace \"x\" with \"a\"\n"
},
{
"code": null,
"e": 1033,
"s": 944,
"text": "Now, If you want to read the replaced value then use the following function given below."
},
{
"code": null,
"e": 1096,
"s": 1033,
"text": "SELECT REPLACE(\"It is Good to study xxx from GFG\", \"x\", \"a\");\n"
},
{
"code": null,
"e": 1105,
"s": 1096,
"text": "Output :"
},
{
"code": null,
"e": 1114,
"s": 1105,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1120,
"s": 1114,
"text": "mysql"
},
{
"code": null,
"e": 1124,
"s": 1120,
"text": "SQL"
},
{
"code": null,
"e": 1128,
"s": 1124,
"text": "SQL"
}
] |
Python | Pandas DataFrame.astype()
|
25 Jul, 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.
DataFrame.astype() method is used to cast a pandas object to a specified dtype. astype() function also provides the capability to convert any suitable existing column to categorical type.
DataFrame.astype() function comes very handy when we want to case a particular column data type to another data type. Not only that but we can also use a Python dictionary input to change more than one column type at once. The key label in dictionary is corresponding to the column name and the values label in the dictionary is corresponding to the new data types we want the columns to be of.
Syntax: DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)
Parameters:dtype : Use a numpy.dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, ...}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.copy : Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects).
errors : Control raising of exceptions on invalid data for provided dtype.raise : allow exceptions to be raisedignore : suppress exceptions. On error return original object
kwargs :keyword arguments to pass on to the constructor
Returns: casted : type of caller
For link to CSV file Used in Code, click here
Example #1: Convert the Weight column data type.
# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Printing the first 10 rows of # the data frame for visualization df[:10]
As the data have some “nan” values so, to avoid any error we will drop all the rows containing any nan values.
# drop all those rows which # have any 'nan' value in it.df.dropna(inplace = True)
# let's find out the data type of Weight columnbefore = type(df.Weight[0]) # Now we will convert it into 'int64' type.df.Weight = df.Weight.astype('int64') # let's find out the data type after castingafter = type(df.Weight[0]) # print the value of beforebefore # print the value of afterafter
Output:
# print the data frame and see# what it looks like after the changedf
Example #2: Change the data type of more than one column at once
Change the Name column to categorical type and Age column to int64 type.
# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Drop the rows with 'nan' valuesdf = df.dropna() # print the existing data type of each columndf.info()
Output:
Now let’s change both the columns data type at once.
# Passed a dictionary to astype() function df = df.astype({"Name":'category', "Age":'int64'}) # Now print the data type # of all columns after changedf.info()
Output:
# print the data frame# too after the changedf
Output:
nidhi_biet
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jul, 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": 430,
"s": 242,
"text": "DataFrame.astype() method is used to cast a pandas object to a specified dtype. astype() function also provides the capability to convert any suitable existing column to categorical type."
},
{
"code": null,
"e": 825,
"s": 430,
"text": "DataFrame.astype() function comes very handy when we want to case a particular column data type to another data type. Not only that but we can also use a Python dictionary input to change more than one column type at once. The key label in dictionary is corresponding to the column name and the values label in the dictionary is corresponding to the new data types we want the columns to be of."
},
{
"code": null,
"e": 894,
"s": 825,
"text": "Syntax: DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)"
},
{
"code": null,
"e": 1311,
"s": 894,
"text": "Parameters:dtype : Use a numpy.dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, ...}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.copy : Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects)."
},
{
"code": null,
"e": 1484,
"s": 1311,
"text": "errors : Control raising of exceptions on invalid data for provided dtype.raise : allow exceptions to be raisedignore : suppress exceptions. On error return original object"
},
{
"code": null,
"e": 1540,
"s": 1484,
"text": "kwargs :keyword arguments to pass on to the constructor"
},
{
"code": null,
"e": 1573,
"s": 1540,
"text": "Returns: casted : type of caller"
},
{
"code": null,
"e": 1619,
"s": 1573,
"text": "For link to CSV file Used in Code, click here"
},
{
"code": null,
"e": 1668,
"s": 1619,
"text": "Example #1: Convert the Weight column data type."
},
{
"code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Printing the first 10 rows of # the data frame for visualization df[:10]",
"e": 1855,
"s": 1668,
"text": null
},
{
"code": null,
"e": 1966,
"s": 1855,
"text": "As the data have some “nan” values so, to avoid any error we will drop all the rows containing any nan values."
},
{
"code": "# drop all those rows which # have any 'nan' value in it.df.dropna(inplace = True)",
"e": 2049,
"s": 1966,
"text": null
},
{
"code": "# let's find out the data type of Weight columnbefore = type(df.Weight[0]) # Now we will convert it into 'int64' type.df.Weight = df.Weight.astype('int64') # let's find out the data type after castingafter = type(df.Weight[0]) # print the value of beforebefore # print the value of afterafter",
"e": 2346,
"s": 2049,
"text": null
},
{
"code": null,
"e": 2354,
"s": 2346,
"text": "Output:"
},
{
"code": "# print the data frame and see# what it looks like after the changedf",
"e": 2424,
"s": 2354,
"text": null
},
{
"code": null,
"e": 2491,
"s": 2426,
"text": "Example #2: Change the data type of more than one column at once"
},
{
"code": null,
"e": 2564,
"s": 2491,
"text": "Change the Name column to categorical type and Age column to int64 type."
},
{
"code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Drop the rows with 'nan' valuesdf = df.dropna() # print the existing data type of each columndf.info()",
"e": 2781,
"s": 2564,
"text": null
},
{
"code": null,
"e": 2789,
"s": 2781,
"text": "Output:"
},
{
"code": null,
"e": 2842,
"s": 2789,
"text": "Now let’s change both the columns data type at once."
},
{
"code": "# Passed a dictionary to astype() function df = df.astype({\"Name\":'category', \"Age\":'int64'}) # Now print the data type # of all columns after changedf.info()",
"e": 3002,
"s": 2842,
"text": null
},
{
"code": null,
"e": 3010,
"s": 3002,
"text": "Output:"
},
{
"code": "# print the data frame# too after the changedf",
"e": 3057,
"s": 3010,
"text": null
},
{
"code": null,
"e": 3065,
"s": 3057,
"text": "Output:"
},
{
"code": null,
"e": 3076,
"s": 3065,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3100,
"s": 3076,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3132,
"s": 3100,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 3146,
"s": 3132,
"text": "Python-pandas"
},
{
"code": null,
"e": 3153,
"s": 3146,
"text": "Python"
},
{
"code": null,
"e": 3251,
"s": 3153,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3269,
"s": 3251,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3311,
"s": 3269,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3333,
"s": 3311,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3368,
"s": 3333,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3400,
"s": 3368,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3429,
"s": 3400,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3456,
"s": 3429,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3477,
"s": 3456,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3500,
"s": 3477,
"text": "Introduction To PYTHON"
}
] |
C++ String Library - swap
|
It exchanges the content of the container by the content of str, which is another string object. Lengths may differ.
Following is the declaration for std::string::swap.
void swap (string& str);
void swap (string& str);
void swap (string& str);
str − It is a string object.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::swap.
#include <iostream>
#include <string>
main () {
std::string buyer ("money");
std::string seller ("goods");
std::cout << "Before the swap, buyer has " << buyer;
std::cout << " and seller has " << seller << '\n';
seller.swap (buyer);
std::cout << " After the swap, buyer has " << buyer;
std::cout << " and seller has " << seller << '\n';
return 0;
}
The sample output should be like this −
Before the swap, buyer has money and seller has goods
After the swap, buyer has goods and seller has money
|
[
{
"code": null,
"e": 2854,
"s": 2737,
"text": "It exchanges the content of the container by the content of str, which is another string object. Lengths may differ."
},
{
"code": null,
"e": 2906,
"s": 2854,
"text": "Following is the declaration for std::string::swap."
},
{
"code": null,
"e": 2931,
"s": 2906,
"text": "void swap (string& str);"
},
{
"code": null,
"e": 2956,
"s": 2931,
"text": "void swap (string& str);"
},
{
"code": null,
"e": 2981,
"s": 2956,
"text": "void swap (string& str);"
},
{
"code": null,
"e": 3010,
"s": 2981,
"text": "str − It is a string object."
},
{
"code": null,
"e": 3015,
"s": 3010,
"text": "none"
},
{
"code": null,
"e": 3078,
"s": 3015,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 3118,
"s": 3078,
"text": "In below example for std::string::swap."
},
{
"code": null,
"e": 3495,
"s": 3118,
"text": "#include <iostream>\n#include <string>\n\nmain () {\n std::string buyer (\"money\");\n std::string seller (\"goods\");\n\n std::cout << \"Before the swap, buyer has \" << buyer;\n std::cout << \" and seller has \" << seller << '\\n';\n\n seller.swap (buyer);\n\n std::cout << \" After the swap, buyer has \" << buyer;\n std::cout << \" and seller has \" << seller << '\\n';\n\n return 0;\n}"
},
{
"code": null,
"e": 3535,
"s": 3495,
"text": "The sample output should be like this −"
}
] |
Pandas Groupby and Sum
|
25 Nov, 2020
Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users.
Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept but it’s an extremely valuable technique that’s widely used in data science. It is helpful in the sense that we can :
Compute summary statistics for every group
Perform group-specific transformations
Do the filtration of data
The groupby() involves a combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups such as sum().
Example 1:
Python3
# import required moduleimport pandas as pd # create dataframedf = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], 'Max Speed': [380., 370., 24., 26.]}) # use groupby() to compute sumdf.groupby(['Animal']).sum()
Output
Example 2:
Python3
# import required moduleimport pandas as pd # assign listl = [[100, 200, 300], [10, None, 40], [20, 10, 30], [100, 200, 200]] # create dataframedf = pd.DataFrame(l, columns=["a", "b", "c"]) # use groupby() to generate sumdf.groupby(by=["b"]).sum()
Output:
Example 3:
Python3
# import required moduleimport pandas as pd # assign dataipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3, 4, 1, 1, 2, 4, 1, 2], 'Year': [2014, 2015, 2014, 2015, 2014, 2015, 2016, 2017, 2016, 2014, 2015, 2017], 'Points': [876, 789, 863, 673, 741, 812, 756, 788, 694, 701, 804, 690]} # create dataframedf = pd.DataFrame(ipl_data) # use groupby() to generate sumdf.groupby(['Team']).sum()
Output:
Python pandas-groupby
Python-pandas
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 360,
"s": 28,
"text": "Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users. "
},
{
"code": null,
"e": 615,
"s": 360,
"text": "Groupby is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept but it’s an extremely valuable technique that’s widely used in data science. It is helpful in the sense that we can :"
},
{
"code": null,
"e": 658,
"s": 615,
"text": "Compute summary statistics for every group"
},
{
"code": null,
"e": 697,
"s": 658,
"text": "Perform group-specific transformations"
},
{
"code": null,
"e": 723,
"s": 697,
"text": "Do the filtration of data"
},
{
"code": null,
"e": 935,
"s": 723,
"text": "The groupby() involves a combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups such as sum()."
},
{
"code": null,
"e": 946,
"s": 935,
"text": "Example 1:"
},
{
"code": null,
"e": 954,
"s": 946,
"text": "Python3"
},
{
"code": "# import required moduleimport pandas as pd # create dataframedf = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], 'Max Speed': [380., 370., 24., 26.]}) # use groupby() to compute sumdf.groupby(['Animal']).sum()",
"e": 1204,
"s": 954,
"text": null
},
{
"code": null,
"e": 1211,
"s": 1204,
"text": "Output"
},
{
"code": null,
"e": 1222,
"s": 1211,
"text": "Example 2:"
},
{
"code": null,
"e": 1230,
"s": 1222,
"text": "Python3"
},
{
"code": "# import required moduleimport pandas as pd # assign listl = [[100, 200, 300], [10, None, 40], [20, 10, 30], [100, 200, 200]] # create dataframedf = pd.DataFrame(l, columns=[\"a\", \"b\", \"c\"]) # use groupby() to generate sumdf.groupby(by=[\"b\"]).sum()",
"e": 1485,
"s": 1230,
"text": null
},
{
"code": null,
"e": 1493,
"s": 1485,
"text": "Output:"
},
{
"code": null,
"e": 1504,
"s": 1493,
"text": "Example 3:"
},
{
"code": null,
"e": 1512,
"s": 1504,
"text": "Python3"
},
{
"code": "# import required moduleimport pandas as pd # assign dataipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3, 4, 1, 1, 2, 4, 1, 2], 'Year': [2014, 2015, 2014, 2015, 2014, 2015, 2016, 2017, 2016, 2014, 2015, 2017], 'Points': [876, 789, 863, 673, 741, 812, 756, 788, 694, 701, 804, 690]} # create dataframedf = pd.DataFrame(ipl_data) # use groupby() to generate sumdf.groupby(['Team']).sum()",
"e": 2136,
"s": 1512,
"text": null
},
{
"code": null,
"e": 2144,
"s": 2136,
"text": "Output:"
},
{
"code": null,
"e": 2166,
"s": 2144,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 2180,
"s": 2166,
"text": "Python-pandas"
},
{
"code": null,
"e": 2204,
"s": 2180,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2211,
"s": 2204,
"text": "Python"
},
{
"code": null,
"e": 2230,
"s": 2211,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2328,
"s": 2230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2360,
"s": 2328,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2387,
"s": 2360,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2408,
"s": 2387,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2431,
"s": 2408,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2487,
"s": 2431,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2518,
"s": 2487,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2560,
"s": 2518,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2602,
"s": 2560,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2641,
"s": 2602,
"text": "Python | datetime.timedelta() function"
}
] |
Software Engineering - GeeksforGeeks
|
22 Jan, 2014
GROUP I GROUP II
(P) Service oriented computing (1) Interoperability
(Q) Heterogeneous communicating systems (2) BPMN
(R) Information representation (3) Publish-find-bind
(S) Process description (4) XML
Coupling between M1 and M2 = (Number of external links) /
(Number of modules)
= 2/2
= 1
Cohesion of a module = (Number of internal links) /
(Number of methods)
Cohesion of M1 = 8/4 = 2
Cohesion of M2 = 6/3 = 2
After moving method m to M2, we get following
Coupling = 2/2 = 1
Cohesion of M1 = 6/3 = 2
Cohesion of M2 = 8/4 = 2
Effort Applied (E) = ab(KLOC)bb [ person-months ]
= 2.8 x(40)1.20
= 2.8 x 83.65
= 234.25
/* This function computes the roots of a quadratic equation
a.x^2 + b.x + c = . The function stores two real roots
in *root1 and *root2 and returns the status of validity
of roots. It handles four different kinds of cases.
(i) When coefficient a is zero irrespective of discriminant
(ii) When discreminant is positive
(iii) When discriminant is zero
(iv) When discriminant is negative.
Only in case (ii) and (iii) the stored roots are valid.
Otherwise 0 is stored in roots. The function returns
0 when the roots are valid and -1 otherwise.
The function also ensures root1 >= root2
int get_QuadRoots( float a, float b, float c,
float *root1, float *root2);
*/
Cyclomatic Complexity of module = Number of decision points + 1
Number of decision points in A = 10 - 1 = 9
Number of decision points in B = 10 - 1 = 9
Cyclomatic Complexity of the integration = Number of decision points + 1
= (9 + 9) + 1
= 19
P. Requirements Capture 1.Module Development and Integration
Q. Design 2.Domain Analysis
R. Implementation 3.Structural and Behavioral Modeling
S. Maintenance 4.Performance Tuning
begin
if (a== b) {S1; exit;}
else if (c== d) {S2;]
else {S3; exit;}
S4;
end
T1 checks S1
T2 checks S3
T4 checks S2 and S4
I. Content coupling
II. Common coupling
III. Control coupling
IV. Stamp coupling
V. Data coupling
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Order and Ranking Questions & Answers
Spring Boot - Thymeleaf with Example
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
Explain Promise.all with async-await in JavaScript
Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!
Spring Boot - Annotations
|
[
{
"code": null,
"e": 29323,
"s": 29295,
"text": "\n22 Jan, 2014"
},
{
"code": null,
"e": 29629,
"s": 29323,
"text": "GROUP I GROUP II\n(P) Service oriented computing (1) Interoperability\n(Q) Heterogeneous communicating systems (2) BPMN\n(R) Information representation (3) Publish-find-bind\n(S) Process description (4) XML "
},
{
"code": null,
"e": 30090,
"s": 29629,
"text": "Coupling between M1 and M2 = (Number of external links) / \n (Number of modules) \n = 2/2\n = 1\n\nCohesion of a module = (Number of internal links) / \n (Number of methods)\n \n\nCohesion of M1 = 8/4 = 2\nCohesion of M2 = 6/3 = 2\n\n\nAfter moving method m to M2, we get following\n\n\nCoupling = 2/2 = 1\nCohesion of M1 = 6/3 = 2\nCohesion of M2 = 8/4 = 2 "
},
{
"code": null,
"e": 30239,
"s": 30090,
"text": "Effort Applied (E) = ab(KLOC)bb [ person-months ]\n = 2.8 x(40)1.20 \n = 2.8 x 83.65 \n = 234.25 "
},
{
"code": null,
"e": 31068,
"s": 30239,
"text": " \n /* This function computes the roots of a quadratic equation\n a.x^2 + b.x + c = . The function stores two real roots\n in *root1 and *root2 and returns the status of validity\n of roots. It handles four different kinds of cases.\n (i) When coefficient a is zero irrespective of discriminant\n (ii) When discreminant is positive\n (iii) When discriminant is zero\n (iv) When discriminant is negative.\n Only in case (ii) and (iii) the stored roots are valid.\n Otherwise 0 is stored in roots. The function returns\n 0 when the roots are valid and -1 otherwise.\n The function also ensures root1 >= root2\n int get_QuadRoots( float a, float b, float c,\n float *root1, float *root2);\n */"
},
{
"code": null,
"e": 31396,
"s": 31068,
"text": "Cyclomatic Complexity of module = Number of decision points + 1\n\nNumber of decision points in A = 10 - 1 = 9\nNumber of decision points in B = 10 - 1 = 9\nCyclomatic Complexity of the integration = Number of decision points + 1\n = (9 + 9) + 1\n = 19\n"
},
{
"code": null,
"e": 31596,
"s": 31396,
"text": "P. Requirements Capture\t 1.Module Development and Integration\nQ. Design\t 2.Domain Analysis\nR. Implementation\t 3.Structural and Behavioral Modeling\nS. Maintenance\t 4.Performance Tuning"
},
{
"code": null,
"e": 31686,
"s": 31596,
"text": "begin\n if (a== b) {S1; exit;}\n else if (c== d) {S2;]\n else {S3; exit;}\n S4;\nend "
},
{
"code": null,
"e": 31735,
"s": 31686,
"text": "T1 checks S1 \n\nT2 checks S3\n\nT4 checks S2 and S4"
},
{
"code": null,
"e": 31856,
"s": 31735,
"text": " I. Content coupling\n II. Common coupling\n III. Control coupling \n IV. Stamp coupling\n V. Data coupling "
},
{
"code": null,
"e": 31954,
"s": 31856,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 32028,
"s": 31954,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 32081,
"s": 32028,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 32147,
"s": 32081,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 32185,
"s": 32147,
"text": "Order and Ranking Questions & Answers"
},
{
"code": null,
"e": 32222,
"s": 32185,
"text": "Spring Boot - Thymeleaf with Example"
},
{
"code": null,
"e": 32247,
"s": 32222,
"text": "Naming Convention in C++"
},
{
"code": null,
"e": 32279,
"s": 32247,
"text": "Floyd’s Cycle Finding Algorithm"
},
{
"code": null,
"e": 32330,
"s": 32279,
"text": "Explain Promise.all with async-await in JavaScript"
},
{
"code": null,
"e": 32400,
"s": 32330,
"text": "Free Online Resume Builder By GeeksforGeeks - Create Your Resume Now!"
}
] |
Doctors Clinic | Practice | GeeksforGeeks
|
Given two positive integers N and X, where N is the number of total patients and X is the time duration(in minutes) after which a new patient arrives. Also, doctor will give only 10 minutes to each patient. The task is to calculate the time (in minutes) the last patient needs to wait.
Example 1:
Input: N = 4, X = 5
Output: 15
Explaination: The arrival time of the
patients are 0, 5, 10 and 15 respectively.
The times when the first three patients
are checked are respectively 10, 20, 30.
So the Waiting time is 30 - 15 = 15.
Example 2:
Input: N = 3, X = 10
Output: 0
Explaination: The incoming time of the
patients are 0, 10 and 20 and the firts
two patients are finished checking at 10,
20. So the last patient does not need to
wait.
Your Task:
You do not need to read input or print anything. Your task is to complete the function waitingTime() which takes N and X as input parameters and returns the waiting time of the last patient.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 100
1 ≤ X ≤ 30
0
prashantdhruw2 months ago
class Solution{ static int waitingTime(int N, int X){ if(X>10){ return 0; }else{ return ((N - 1) * (10 - X)); } }}
0
prashantdhruw
This comment was deleted.
-1
shubham4393 months ago
int sum = 0;
int wait = 0;
int ans = 0;
if(X>=10 && N>1){
return 0;
}
if(N==0)
return 0;
if(X<10){
for(int i = 1;i<N;i++){
wait = wait+10;
sum = sum+X;
}
ans = wait-sum;
}
return ans;
+1
badgujarsachin839 months ago
class Solution{
public:
int waitingTime(int N, int X){
// code here
if(X>=10){
return 0;
}
int patient=(N-1)*X;
int doctor=(N-1)*10;
int wait=doctor-patient;
return wait;
}
};
0
badgujarsachin839 months ago
-1
nagesh371270110 months ago
Given two positive integers N and X, where N is the number of total patients and X is the time duration(in minutes) after which a new patient arrives. Also, doctor will give only 10 minutes to each patient. The task is to calculate the time (in minutes) the last patient needs to wait.
-1
kumarbabalu92310 months ago
Babalu Kumar
0
Amar Prakash1 year agoint waitingTime(int N, int X){ if( X > 10) { return 0; } return ((N-1)*10 - (N-1)*X); // code here }Reply Open ExternallyShow 0 RepliesLoading...
Amar Prakash
int waitingTime(int N, int X){
if( X > 10) { return 0; }
return ((N-1)*10 - (N-1)*X); // code here }
-1
Jaspreet Singh2 years agoclass Solution{ static int waitingTime(int N, int X){ // code hereint x=10;if(X>10)return 0;elsereturn(x*(N-1)-X*(N-1)); }}Reply Open ExternallyShow 0 RepliesLoading...
Jaspreet Singh
class Solution{ static int waitingTime(int N, int X){ // code hereint x=10;if(X>10)return 0;elsereturn(x*(N-1)-X*(N-1)); }}
0
Rohit kumar2 years ago#include <iostream>using namespace std;int main() {//codeint t,X,N;cin>>t;while(t--) { cin>>N>>X; cout<<((10-X)*(N-1))<<endl; }="" return="" 0;="" }="">Reply Open ExternallyShow 0 RepliesLoading...
Rohit kumar
#include <iostream>using namespace std;
int main() {//codeint t,X,N;cin>>t;while(t--) { cin>>N>>X; cout<<((10-X)*(N-1))<<endl; }="" return="" 0;="" }="">
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 512,
"s": 226,
"text": "Given two positive integers N and X, where N is the number of total patients and X is the time duration(in minutes) after which a new patient arrives. Also, doctor will give only 10 minutes to each patient. The task is to calculate the time (in minutes) the last patient needs to wait."
},
{
"code": null,
"e": 523,
"s": 512,
"text": "Example 1:"
},
{
"code": null,
"e": 757,
"s": 523,
"text": "Input: N = 4, X = 5\nOutput: 15\nExplaination: The arrival time of the \npatients are 0, 5, 10 and 15 respectively. \nThe times when the first three patients \nare checked are respectively 10, 20, 30. \nSo the Waiting time is 30 - 15 = 15."
},
{
"code": null,
"e": 768,
"s": 757,
"text": "Example 2:"
},
{
"code": null,
"e": 971,
"s": 768,
"text": "Input: N = 3, X = 10\nOutput: 0\nExplaination: The incoming time of the \npatients are 0, 10 and 20 and the firts \ntwo patients are finished checking at 10, \n20. So the last patient does not need to \nwait."
},
{
"code": null,
"e": 1173,
"s": 971,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function waitingTime() which takes N and X as input parameters and returns the waiting time of the last patient."
},
{
"code": null,
"e": 1235,
"s": 1173,
"text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1271,
"s": 1235,
"text": "Constraints:\n1 ≤ N ≤ 100\n1 ≤ X ≤ 30"
},
{
"code": null,
"e": 1273,
"s": 1271,
"text": "0"
},
{
"code": null,
"e": 1299,
"s": 1273,
"text": "prashantdhruw2 months ago"
},
{
"code": null,
"e": 1450,
"s": 1299,
"text": "class Solution{ static int waitingTime(int N, int X){ if(X>10){ return 0; }else{ return ((N - 1) * (10 - X)); } }}"
},
{
"code": null,
"e": 1452,
"s": 1450,
"text": "0"
},
{
"code": null,
"e": 1466,
"s": 1452,
"text": "prashantdhruw"
},
{
"code": null,
"e": 1492,
"s": 1466,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1495,
"s": 1492,
"text": "-1"
},
{
"code": null,
"e": 1518,
"s": 1495,
"text": "shubham4393 months ago"
},
{
"code": null,
"e": 1884,
"s": 1518,
"text": "int sum = 0;\n int wait = 0;\n int ans = 0;\n if(X>=10 && N>1){\n return 0;\n }\n if(N==0)\n return 0;\n if(X<10){\n for(int i = 1;i<N;i++){\n wait = wait+10;\n sum = sum+X;\n \n }\n ans = wait-sum;\n \n }\n return ans;"
},
{
"code": null,
"e": 1887,
"s": 1884,
"text": "+1"
},
{
"code": null,
"e": 1916,
"s": 1887,
"text": "badgujarsachin839 months ago"
},
{
"code": null,
"e": 2168,
"s": 1916,
"text": "class Solution{\npublic:\n int waitingTime(int N, int X){\n // code here\n if(X>=10){\n return 0;\n }\n int patient=(N-1)*X;\n int doctor=(N-1)*10;\n int wait=doctor-patient;\n return wait;\n }\n};"
},
{
"code": null,
"e": 2170,
"s": 2168,
"text": "0"
},
{
"code": null,
"e": 2199,
"s": 2170,
"text": "badgujarsachin839 months ago"
},
{
"code": null,
"e": 2202,
"s": 2199,
"text": "-1"
},
{
"code": null,
"e": 2229,
"s": 2202,
"text": "nagesh371270110 months ago"
},
{
"code": null,
"e": 2515,
"s": 2229,
"text": "Given two positive integers N and X, where N is the number of total patients and X is the time duration(in minutes) after which a new patient arrives. Also, doctor will give only 10 minutes to each patient. The task is to calculate the time (in minutes) the last patient needs to wait."
},
{
"code": null,
"e": 2518,
"s": 2515,
"text": "-1"
},
{
"code": null,
"e": 2546,
"s": 2518,
"text": "kumarbabalu92310 months ago"
},
{
"code": null,
"e": 2559,
"s": 2546,
"text": "Babalu Kumar"
},
{
"code": null,
"e": 2561,
"s": 2559,
"text": "0"
},
{
"code": null,
"e": 2778,
"s": 2561,
"text": "Amar Prakash1 year agoint waitingTime(int N, int X){ if( X > 10) { return 0; } return ((N-1)*10 - (N-1)*X); // code here }Reply Open ExternallyShow 0 RepliesLoading..."
},
{
"code": null,
"e": 2791,
"s": 2778,
"text": "Amar Prakash"
},
{
"code": null,
"e": 2822,
"s": 2791,
"text": "int waitingTime(int N, int X){"
},
{
"code": null,
"e": 2881,
"s": 2822,
"text": " if( X > 10) { return 0; }"
},
{
"code": null,
"e": 2943,
"s": 2881,
"text": " return ((N-1)*10 - (N-1)*X); // code here }"
},
{
"code": null,
"e": 2946,
"s": 2943,
"text": "-1"
},
{
"code": null,
"e": 3153,
"s": 2946,
"text": "Jaspreet Singh2 years agoclass Solution{ static int waitingTime(int N, int X){ // code hereint x=10;if(X>10)return 0;elsereturn(x*(N-1)-X*(N-1)); }}Reply Open ExternallyShow 0 RepliesLoading..."
},
{
"code": null,
"e": 3168,
"s": 3153,
"text": "Jaspreet Singh"
},
{
"code": null,
"e": 3305,
"s": 3168,
"text": "class Solution{ static int waitingTime(int N, int X){ // code hereint x=10;if(X>10)return 0;elsereturn(x*(N-1)-X*(N-1)); }}"
},
{
"code": null,
"e": 3307,
"s": 3305,
"text": "0"
},
{
"code": null,
"e": 3560,
"s": 3307,
"text": "Rohit kumar2 years ago#include <iostream>using namespace std;int main() {//codeint t,X,N;cin>>t;while(t--) { cin>>N>>X; cout<<((10-X)*(N-1))<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">Reply Open ExternallyShow 0 RepliesLoading..."
},
{
"code": null,
"e": 3572,
"s": 3560,
"text": "Rohit kumar"
},
{
"code": null,
"e": 3612,
"s": 3572,
"text": "#include <iostream>using namespace std;"
},
{
"code": null,
"e": 3759,
"s": 3612,
"text": "int main() {//codeint t,X,N;cin>>t;while(t--) { cin>>N>>X; cout<<((10-X)*(N-1))<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">"
},
{
"code": null,
"e": 3905,
"s": 3759,
"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": 3941,
"s": 3905,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3951,
"s": 3941,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3961,
"s": 3951,
"text": "\nContest\n"
},
{
"code": null,
"e": 4024,
"s": 3961,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4209,
"s": 4024,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4493,
"s": 4209,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 4639,
"s": 4493,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 4716,
"s": 4639,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 4757,
"s": 4716,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 4785,
"s": 4757,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 4856,
"s": 4785,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5043,
"s": 4856,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Installation and Configuration Symfony Framework
|
10 May, 2020
Symfony is an open-source PHP web application framework with MVC architecture. It is a set of reusable PHP components/libraries. It is basically designed for developers who need an elegant and simple toolkit to create web applications and is the most popular application frameworks among the open-source developer’s community. It is used to build high-performance complex web applications.
Prerequisites:
PHP installation on windows.
Environment setup to run the project.
Composer software to create symfony project: https://getcomposer.org/download
Symfony software download: https://symfony.com/download
Installation:
Step 1: Go to xampp root folder and open htdocs folder there. Type “cmd” (without inverted commas) in the address bar(shown below) and hit enter.
Step 2: Enter the following command in the command prompt.composer create-project symfony/skeleton project_1In my case the name of project is project_1, you may take any name of your choice.If you see something like this then your project is created successfully.
composer create-project symfony/skeleton project_1
In my case the name of project is project_1, you may take any name of your choice.If you see something like this then your project is created successfully.
Step 3: Start your xampp server and goto localhost/project_1/public.If you see something like this then your project is created successfully.
First Project: Here we will create a Hello World page in three steps.
Step 1: Create a new file named “HelloController.php” in src/Controller/ folder and write the following code in that file.<?phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;class HelloController{ public function hello() { return new Response( 'Hello World' ); }}
<?phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;class HelloController{ public function hello() { return new Response( 'Hello World' ); }}
Step 2: Open config/routes.yaml file and write the following code in that file.app_hello: path: / controller: App\Controller\HelloController::hello
app_hello: path: / controller: App\Controller\HelloController::hello
Step 3: Goto localhost/project_1/public.If you see something like this then you have successfully created hello world page.
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 444,
"s": 54,
"text": "Symfony is an open-source PHP web application framework with MVC architecture. It is a set of reusable PHP components/libraries. It is basically designed for developers who need an elegant and simple toolkit to create web applications and is the most popular application frameworks among the open-source developer’s community. It is used to build high-performance complex web applications."
},
{
"code": null,
"e": 459,
"s": 444,
"text": "Prerequisites:"
},
{
"code": null,
"e": 488,
"s": 459,
"text": "PHP installation on windows."
},
{
"code": null,
"e": 526,
"s": 488,
"text": "Environment setup to run the project."
},
{
"code": null,
"e": 604,
"s": 526,
"text": "Composer software to create symfony project: https://getcomposer.org/download"
},
{
"code": null,
"e": 660,
"s": 604,
"text": "Symfony software download: https://symfony.com/download"
},
{
"code": null,
"e": 674,
"s": 660,
"text": "Installation:"
},
{
"code": null,
"e": 820,
"s": 674,
"text": "Step 1: Go to xampp root folder and open htdocs folder there. Type “cmd” (without inverted commas) in the address bar(shown below) and hit enter."
},
{
"code": null,
"e": 1084,
"s": 820,
"text": "Step 2: Enter the following command in the command prompt.composer create-project symfony/skeleton project_1In my case the name of project is project_1, you may take any name of your choice.If you see something like this then your project is created successfully."
},
{
"code": null,
"e": 1135,
"s": 1084,
"text": "composer create-project symfony/skeleton project_1"
},
{
"code": null,
"e": 1291,
"s": 1135,
"text": "In my case the name of project is project_1, you may take any name of your choice.If you see something like this then your project is created successfully."
},
{
"code": null,
"e": 1433,
"s": 1291,
"text": "Step 3: Start your xampp server and goto localhost/project_1/public.If you see something like this then your project is created successfully."
},
{
"code": null,
"e": 1503,
"s": 1433,
"text": "First Project: Here we will create a Hello World page in three steps."
},
{
"code": null,
"e": 1825,
"s": 1503,
"text": "Step 1: Create a new file named “HelloController.php” in src/Controller/ folder and write the following code in that file.<?phpnamespace App\\Controller;use Symfony\\Component\\HttpFoundation\\Response;class HelloController{ public function hello() { return new Response( 'Hello World' ); }}"
},
{
"code": "<?phpnamespace App\\Controller;use Symfony\\Component\\HttpFoundation\\Response;class HelloController{ public function hello() { return new Response( 'Hello World' ); }}",
"e": 2025,
"s": 1825,
"text": null
},
{
"code": null,
"e": 2179,
"s": 2025,
"text": "Step 2: Open config/routes.yaml file and write the following code in that file.app_hello: path: / controller: App\\Controller\\HelloController::hello"
},
{
"code": "app_hello: path: / controller: App\\Controller\\HelloController::hello",
"e": 2254,
"s": 2179,
"text": null
},
{
"code": null,
"e": 2378,
"s": 2254,
"text": "Step 3: Goto localhost/project_1/public.If you see something like this then you have successfully created hello world page."
},
{
"code": null,
"e": 2382,
"s": 2378,
"text": "PHP"
},
{
"code": null,
"e": 2395,
"s": 2382,
"text": "PHP Programs"
},
{
"code": null,
"e": 2412,
"s": 2395,
"text": "Web Technologies"
},
{
"code": null,
"e": 2416,
"s": 2412,
"text": "PHP"
},
{
"code": null,
"e": 2514,
"s": 2416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2596,
"s": 2514,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 2641,
"s": 2596,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 2692,
"s": 2641,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 2722,
"s": 2692,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 2745,
"s": 2722,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 2797,
"s": 2745,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 2879,
"s": 2797,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 2902,
"s": 2879,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 2944,
"s": 2902,
"text": "How to create admin login page using PHP?"
}
] |
VB.Net - Variables
|
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in VB.Net has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
We have already discussed various data types. The basic value types provided in VB.Net can be categorized as −
VB.Net also allows defining other value types of variable like Enum and reference types of variables like Class. We will discuss date types and Classes in subsequent chapters.
The Dim statement is used for variable declaration and storage allocation for one or more variables. The Dim statement is used at module, class, structure, procedure or block level.
Syntax for variable declaration in VB.Net is −
[ < attributelist > ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]
[ ReadOnly ] Dim [ WithEvents ] variablelist
Where,
attributelist is a list of attributes that apply to the variable. Optional.
attributelist is a list of attributes that apply to the variable. Optional.
accessmodifier defines the access levels of the variables, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.
accessmodifier defines the access levels of the variables, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.
Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure. Optional.
Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure. Optional.
Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared. Optional.
Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared. Optional.
ReadOnly means the variable can be read, but not written. Optional.
ReadOnly means the variable can be read, but not written. Optional.
WithEvents specifies that the variable is used to respond to events raised by the instance assigned to the variable. Optional.
WithEvents specifies that the variable is used to respond to events raised by the instance assigned to the variable. Optional.
Variablelist provides the list of variables declared.
Variablelist provides the list of variables declared.
Each variable in the variable list has the following syntax and parts −
variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]
Where,
variablename − is the name of the variable
variablename − is the name of the variable
boundslist − optional. It provides list of bounds of each dimension of an array variable.
boundslist − optional. It provides list of bounds of each dimension of an array variable.
New − optional. It creates a new instance of the class when the Dim statement runs.
New − optional. It creates a new instance of the class when the Dim statement runs.
datatype − Required if Option Strict is On. It specifies the data type of the variable.
datatype − Required if Option Strict is On. It specifies the data type of the variable.
initializer − Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created.
initializer − Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created.
Some valid variable declarations along with their definition are shown here −
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date
Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is −
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
You can initialize a variable at the time of declaration as follows −
Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"
Try the following example which makes use of various types of variables −
Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double
a = 10
b = 20
c = a + b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
The Console class in the System namespace provides a function ReadLine for accepting input from the user and store it into a variable. For example,
Dim message As String
message = Console.ReadLine
The following example demonstrates it −
Module variablesNdataypes
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result (assume the user inputs Hello World) −
Enter message: Hello World
Your Message: Hello World
There are two kinds of expressions −
lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −
Dim g As Integer = 20
But following is not a valid statement and would generate compile-time error −
20 = g
|
[
{
"code": null,
"e": 2755,
"s": 2434,
"text": "A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in VB.Net has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 2866,
"s": 2755,
"text": "We have already discussed various data types. The basic value types provided in VB.Net can be categorized as −"
},
{
"code": null,
"e": 3042,
"s": 2866,
"text": "VB.Net also allows defining other value types of variable like Enum and reference types of variables like Class. We will discuss date types and Classes in subsequent chapters."
},
{
"code": null,
"e": 3224,
"s": 3042,
"text": "The Dim statement is used for variable declaration and storage allocation for one or more variables. The Dim statement is used at module, class, structure, procedure or block level."
},
{
"code": null,
"e": 3271,
"s": 3224,
"text": "Syntax for variable declaration in VB.Net is −"
},
{
"code": null,
"e": 3396,
"s": 3271,
"text": "[ < attributelist > ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]\n[ ReadOnly ] Dim [ WithEvents ] variablelist\n"
},
{
"code": null,
"e": 3403,
"s": 3396,
"text": "Where,"
},
{
"code": null,
"e": 3479,
"s": 3403,
"text": "attributelist is a list of attributes that apply to the variable. Optional."
},
{
"code": null,
"e": 3555,
"s": 3479,
"text": "attributelist is a list of attributes that apply to the variable. Optional."
},
{
"code": null,
"e": 3701,
"s": 3555,
"text": "accessmodifier defines the access levels of the variables, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional."
},
{
"code": null,
"e": 3847,
"s": 3701,
"text": "accessmodifier defines the access levels of the variables, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional."
},
{
"code": null,
"e": 4033,
"s": 3847,
"text": "Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure. Optional."
},
{
"code": null,
"e": 4219,
"s": 4033,
"text": "Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure. Optional."
},
{
"code": null,
"e": 4364,
"s": 4219,
"text": "Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional."
},
{
"code": null,
"e": 4509,
"s": 4364,
"text": "Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional."
},
{
"code": null,
"e": 4651,
"s": 4509,
"text": "Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared. Optional."
},
{
"code": null,
"e": 4793,
"s": 4651,
"text": "Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared. Optional."
},
{
"code": null,
"e": 4861,
"s": 4793,
"text": "ReadOnly means the variable can be read, but not written. Optional."
},
{
"code": null,
"e": 4929,
"s": 4861,
"text": "ReadOnly means the variable can be read, but not written. Optional."
},
{
"code": null,
"e": 5056,
"s": 4929,
"text": "WithEvents specifies that the variable is used to respond to events raised by the instance assigned to the variable. Optional."
},
{
"code": null,
"e": 5183,
"s": 5056,
"text": "WithEvents specifies that the variable is used to respond to events raised by the instance assigned to the variable. Optional."
},
{
"code": null,
"e": 5237,
"s": 5183,
"text": "Variablelist provides the list of variables declared."
},
{
"code": null,
"e": 5291,
"s": 5237,
"text": "Variablelist provides the list of variables declared."
},
{
"code": null,
"e": 5363,
"s": 5291,
"text": "Each variable in the variable list has the following syntax and parts −"
},
{
"code": null,
"e": 5441,
"s": 5363,
"text": "variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]\n"
},
{
"code": null,
"e": 5448,
"s": 5441,
"text": "Where,"
},
{
"code": null,
"e": 5491,
"s": 5448,
"text": "variablename − is the name of the variable"
},
{
"code": null,
"e": 5534,
"s": 5491,
"text": "variablename − is the name of the variable"
},
{
"code": null,
"e": 5624,
"s": 5534,
"text": "boundslist − optional. It provides list of bounds of each dimension of an array variable."
},
{
"code": null,
"e": 5714,
"s": 5624,
"text": "boundslist − optional. It provides list of bounds of each dimension of an array variable."
},
{
"code": null,
"e": 5798,
"s": 5714,
"text": "New − optional. It creates a new instance of the class when the Dim statement runs."
},
{
"code": null,
"e": 5882,
"s": 5798,
"text": "New − optional. It creates a new instance of the class when the Dim statement runs."
},
{
"code": null,
"e": 5970,
"s": 5882,
"text": "datatype − Required if Option Strict is On. It specifies the data type of the variable."
},
{
"code": null,
"e": 6058,
"s": 5970,
"text": "datatype − Required if Option Strict is On. It specifies the data type of the variable."
},
{
"code": null,
"e": 6184,
"s": 6058,
"text": "initializer − Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created."
},
{
"code": null,
"e": 6310,
"s": 6184,
"text": "initializer − Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created."
},
{
"code": null,
"e": 6388,
"s": 6310,
"text": "Some valid variable declarations along with their definition are shown here −"
},
{
"code": null,
"e": 6593,
"s": 6388,
"text": "Dim StudentID As Integer\nDim StudentName As String\nDim Salary As Double\nDim count1, count2 As Integer\nDim status As Boolean\nDim exitButton As New System.Windows.Forms.Button\nDim lastTime, nextTime As Date"
},
{
"code": null,
"e": 6732,
"s": 6593,
"text": "Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is −"
},
{
"code": null,
"e": 6756,
"s": 6732,
"text": "variable_name = value;\n"
},
{
"code": null,
"e": 6769,
"s": 6756,
"text": "for example,"
},
{
"code": null,
"e": 6799,
"s": 6769,
"text": "Dim pi As Double\npi = 3.14159"
},
{
"code": null,
"e": 6869,
"s": 6799,
"text": "You can initialize a variable at the time of declaration as follows −"
},
{
"code": null,
"e": 6941,
"s": 6869,
"text": "Dim StudentID As Integer = 100\nDim StudentName As String = \"Bill Smith\""
},
{
"code": null,
"e": 7015,
"s": 6941,
"text": "Try the following example which makes use of various types of variables −"
},
{
"code": null,
"e": 7279,
"s": 7015,
"text": "Module variablesNdataypes\n Sub Main()\n Dim a As Short\n Dim b As Integer\n Dim c As Double\n \n a = 10\n b = 20\n c = a + b\n Console.WriteLine(\"a = {0}, b = {1}, c = {2}\", a, b, c)\n Console.ReadLine()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 7360,
"s": 7279,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 7384,
"s": 7360,
"text": "a = 10, b = 20, c = 30\n"
},
{
"code": null,
"e": 7532,
"s": 7384,
"text": "The Console class in the System namespace provides a function ReadLine for accepting input from the user and store it into a variable. For example,"
},
{
"code": null,
"e": 7581,
"s": 7532,
"text": "Dim message As String\nmessage = Console.ReadLine"
},
{
"code": null,
"e": 7621,
"s": 7581,
"text": "The following example demonstrates it −"
},
{
"code": null,
"e": 7888,
"s": 7621,
"text": "Module variablesNdataypes\n Sub Main()\n Dim message As String\n Console.Write(\"Enter message: \")\n message = Console.ReadLine\n Console.WriteLine()\n Console.WriteLine(\"Your Message: {0}\", message)\n Console.ReadLine()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 8006,
"s": 7888,
"text": "When the above code is compiled and executed, it produces the following result (assume the user inputs Hello World) −"
},
{
"code": null,
"e": 8063,
"s": 8006,
"text": "Enter message: Hello World \nYour Message: Hello World\n"
},
{
"code": null,
"e": 8100,
"s": 8063,
"text": "There are two kinds of expressions −"
},
{
"code": null,
"e": 8213,
"s": 8100,
"text": "lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 8326,
"s": 8213,
"text": "lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment."
},
{
"code": null,
"e": 8433,
"s": 8326,
"text": "rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 8540,
"s": 8433,
"text": "rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment."
},
{
"code": null,
"e": 8751,
"s": 8540,
"text": "Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −"
},
{
"code": null,
"e": 8774,
"s": 8751,
"text": "Dim g As Integer = 20\n"
},
{
"code": null,
"e": 8853,
"s": 8774,
"text": "But following is not a valid statement and would generate compile-time error −"
}
] |
HTML | <img> hspace Attribute
|
08 Aug, 2019
The HTML <img> hspace attribute is used to specify the number of whitespaces on the left and the right side of the image. The hspace attribute is not supported by HTML 5 you can use CSS there.
Syntax:
<img hspace="pixels">
Attribute Values:
pixels: It specifies the number of whitespaces in terms of pixels.
Example:
<!DOCTYPE html><html> <head> <title> HTML <img> hspace Attribute </title> <style> h1, h3 { text-align: center; } h4 { font-weight: bold; } </style></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <h3>HTML Image hspace Attribute</h3> <h4>Image without hspace</h4> <p><img id="myImage" src="https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png" alt="Submit" width="42" height="42" align="middle" /> It is a computer science portal for geeks.GeeksforGeeks </p> <h4>Image with hspace</h4> <p><img id="myImage" src="https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png" alt="Submit" hspace="40" width="42" height="42" align="middle" /> It is a computer science portal for geeks.GeeksforGeeks </p> </body> </html>
Output :
Supported Browsers: The browser supported by HTML <img> hspace Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Aug, 2019"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "The HTML <img> hspace attribute is used to specify the number of whitespaces on the left and the right side of the image. The hspace attribute is not supported by HTML 5 you can use CSS there."
},
{
"code": null,
"e": 229,
"s": 221,
"text": "Syntax:"
},
{
"code": null,
"e": 252,
"s": 229,
"text": "<img hspace=\"pixels\"> "
},
{
"code": null,
"e": 270,
"s": 252,
"text": "Attribute Values:"
},
{
"code": null,
"e": 337,
"s": 270,
"text": "pixels: It specifies the number of whitespaces in terms of pixels."
},
{
"code": null,
"e": 346,
"s": 337,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML <img> hspace Attribute </title> <style> h1, h3 { text-align: center; } h4 { font-weight: bold; } </style></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3>HTML Image hspace Attribute</h3> <h4>Image without hspace</h4> <p><img id=\"myImage\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png\" alt=\"Submit\" width=\"42\" height=\"42\" align=\"middle\" /> It is a computer science portal for geeks.GeeksforGeeks </p> <h4>Image with hspace</h4> <p><img id=\"myImage\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png\" alt=\"Submit\" hspace=\"40\" width=\"42\" height=\"42\" align=\"middle\" /> It is a computer science portal for geeks.GeeksforGeeks </p> </body> </html>",
"e": 1350,
"s": 346,
"text": null
},
{
"code": null,
"e": 1359,
"s": 1350,
"text": "Output :"
},
{
"code": null,
"e": 1450,
"s": 1359,
"text": "Supported Browsers: The browser supported by HTML <img> hspace Attribute are listed below:"
},
{
"code": null,
"e": 1464,
"s": 1450,
"text": "Google Chrome"
},
{
"code": null,
"e": 1482,
"s": 1464,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1490,
"s": 1482,
"text": "Firefox"
},
{
"code": null,
"e": 1496,
"s": 1490,
"text": "Opera"
},
{
"code": null,
"e": 1503,
"s": 1496,
"text": "Safari"
},
{
"code": null,
"e": 1519,
"s": 1503,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1524,
"s": 1519,
"text": "HTML"
},
{
"code": null,
"e": 1541,
"s": 1524,
"text": "Web Technologies"
},
{
"code": null,
"e": 1546,
"s": 1541,
"text": "HTML"
}
] |
Find unique elements in a matrix
|
10 Jun, 2022
Given a matrix mat[][] having n rows and m columns. We need to find unique elements in matrix i.e, those elements which are not repeated in the matrix or those elements whose frequency is 1.
Examples:
Input : 20 15 30 2
2 3 5 30
6 7 6 8
Output : 3 20 5 7 8 15
Input : 1 2 3
5 6 2
1 3 5
6 2 2
Output : No unique element in the matrix
Follow these steps to find unique element: 1. Create an empty hash table or dictionary. 2. Traverse through all the elements of the matrix 3. If element is present in the dictionary, then increment its count 4. Otherwise insert element with value = 1.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find unique// element in matrix#include<bits/stdc++.h>using namespace std;#define R 4#define C 4 // function that calculate unique elementint unique(int mat[R][C], int n, int m){ int maximum = 0, flag = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) // Find maximum element in // a matrix if(maximum < mat[i][j]) maximum = mat[i][j]; // Take 1-D array of (maximum + 1) // size int b[maximum + 1] = {0}; for(int i = 0 ; i < n; i++) for(int j = 0; j < m; j++) b[mat[i][j]]++; //print unique element for(int i = 1; i <= maximum; i++) if(b[i] == 1) cout << i << " "; flag = 1; if(!flag){ cout << "No unique element in the matrix"; }} // Driver programint main(){ int mat[R][C] = {{ 1, 2, 3, 20}, {5, 6, 20, 25}, {1, 3, 5, 6}, {6, 7, 8, 15}}; // function that calculate unique element unique(mat, R, C); return 0;} // This code is contributed by Naman_Garg.
// Java program to find unique// element in matrixclass GFG{static int R = 4, C = 4; // function that calculate// unique elementstatic void unique(int mat[][], int n, int m){ int maximum = 0, flag = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) // Find maximum element // in a matrix if(maximum < mat[i][j]) maximum = mat[i][j]; // Take 1-D array of // (maximum + 1) size int b[] = new int [maximum + 1]; for(int i = 0 ; i < n; i++) for(int j = 0; j < m; j++) b[mat[i][j]]++; //print unique element for(int i = 1; i <= maximum; i++) if(b[i] == 1) System.out.print(i + " "); flag = 1; if(flag == 0) { System.out.println("No unique element " + "in the matrix"); }} // Driver Codepublic static void main(String args[]){ int mat[][] = {{1, 2, 3, 20}, {5, 6, 20, 25}, {1, 3, 5, 6}, {6, 7, 8, 15}}; // function that calculate // unique element unique(mat, R, C);}} // This code is contributed// by Arnab Kundu
# Python 3 program to find unique# element in matrixdef unique(mat, n, m): maximum = 0; flag = 0 for i in range(0, n): for j in range(0, m): # Find maximum element in # a matrix if(maximum < mat[i][j]): maximum = mat[i][j]; uniqueElementDict = [0] * (maximum + 1) # loops to traverse through the matrix for i in range(0, n): for j in range(0, m): uniqueElementDict[mat[i][j]] += 1 # Print all those keys whose count is 1 for key in range(maximum + 1): if uniqueElementDict[key] == 1: print (key, end = " ") flag = 1 if(flag == 0): print("No unique element in the matrix") # Driver Codemat = [[1, 2, 3, 20], [5, 6, 20, 25], [1, 3, 5, 6], [6, 7, 8, 15]]n = 4m = 4unique(mat, n, m)
// C# program to find unique// element in matrixusing System; class GFG{static int R = 4, C = 4; // function that calculate// unique elementstatic void unique(int [,]mat, int n, int m){ int maximum = 0, flag = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) // Find maximum element // in a matrix if(maximum < mat[i, j]) maximum = mat[i, j]; // Take 1-D array of // (maximum + 1) size int []b = new int [maximum + 1]; for(int i = 0 ; i < n; i++) for(int j = 0; j < m; j++) b[mat[i, j]]++; // print unique element for(int i = 1; i <= maximum; i++) if(b[i] == 1) Console.Write(i + " "); flag = 1; if(flag == 0) { Console.WriteLine("No unique element " + "in the matrix"); }} // Driver Codepublic static void Main(){ int [,]mat = {{1, 2, 3, 20}, {5, 6, 20, 25}, {1, 3, 5, 6}, {6, 7, 8, 15}}; // function that calculate // unique element unique(mat, R, C);}} // This code is contributed// by Subhadeep
<?php// PHP program to find unique// element in matrix $R = 4;$C = 4; // function that calculate unique elementfunction unique($mat, $n, $m){ $maximum = 0; $flag = 0; for($i = 0; $i < $n; $i++) for($j = 0; $j < $m; $j++) // Find maximum element in // a matrix if($maximum < $mat[$i][$j]) $maximum = $mat[$i][$j]; // Take 1-D array of (maximum + 1) // size $b = array(); for($j = 0; $j < $maximum + 1; $j++) $b[$j] = 0; for($i = 0 ; $i < $n; $i++) for($j = 0; $j < $m; $j++) $b[$mat[$i][$j]]++; // print unique element for($i = 1; $i <= $maximum; $i++) if($b[$i] == 1) echo "$i "; $flag = 1; if(!$flag) { echo "No unique element in the matrix"; }} // Driver Code$mat = array(array(1, 2, 3, 20), array(5, 6, 20, 25), array(1, 3, 5, 6), array(6, 7, 8, 15)); // function that calculate unique elementunique($mat, $R, $C); // This code is contributed by iAyushRaj?>
<script> // Javascript program to find unique// element in matrixvar R = 4, C = 4; // Function that calculate// unique elementfunction unique(mat, n, m){ var maximum = 0, flag = 0; for(var i = 0; i < n; i++) for(var j = 0; j < m; j++) // Find maximum element // in a matrix if (maximum < mat[i][j]) maximum = mat[i][j]; // Take 1-D array of // (maximum + 1) size var b = Array(maximum+1).fill(0); for(var i = 0 ; i < n; i++) for(var j = 0; j < m; j++) b[mat[i][j]]++; // Print unique element for(var i = 1; i <= maximum; i++) if (b[i] == 1) document.write(i + " "); flag = 1; if (flag == 0) { document.write("No unique element " + "in the matrix<br>"); }} // Driver Codevar mat = [ [ 1, 2, 3, 20 ], [ 5, 6, 20, 25 ], [ 1, 3, 5, 6 ], [ 6, 7, 8, 15 ] ]; // Function that calculate// unique elementunique(mat, R, C); // This code is contributed by rrrtnx </script>
2 7 8 15 25
Complexity Analysis:
Time Complexity: O(m*n) where m is the number of rows & n is the number of columns.Auxiliary Space: O(max(matrix)).
andrew1234
tufan_gupta2000
Naman_Garg
iAyushRaj
rrrtnx
vinayedula
python-dict
Matrix
python-dict
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
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
Unique paths in a Grid with Obstacles
Printing all solutions in N-Queen Problem
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 245,
"s": 53,
"text": "Given a matrix mat[][] having n rows and m columns. We need to find unique elements in matrix i.e, those elements which are not repeated in the matrix or those elements whose frequency is 1. "
},
{
"code": null,
"e": 256,
"s": 245,
"text": "Examples: "
},
{
"code": null,
"e": 467,
"s": 256,
"text": "Input : 20 15 30 2\n 2 3 5 30\n 6 7 6 8\nOutput : 3 20 5 7 8 15 \n\nInput : 1 2 3 \n 5 6 2\n 1 3 5\n 6 2 2\nOutput : No unique element in the matrix"
},
{
"code": null,
"e": 720,
"s": 467,
"text": "Follow these steps to find unique element: 1. Create an empty hash table or dictionary. 2. Traverse through all the elements of the matrix 3. If element is present in the dictionary, then increment its count 4. Otherwise insert element with value = 1. "
},
{
"code": null,
"e": 724,
"s": 720,
"text": "C++"
},
{
"code": null,
"e": 729,
"s": 724,
"text": "Java"
},
{
"code": null,
"e": 737,
"s": 729,
"text": "Python3"
},
{
"code": null,
"e": 740,
"s": 737,
"text": "C#"
},
{
"code": null,
"e": 744,
"s": 740,
"text": "PHP"
},
{
"code": null,
"e": 755,
"s": 744,
"text": "Javascript"
},
{
"code": "// C++ program to find unique// element in matrix#include<bits/stdc++.h>using namespace std;#define R 4#define C 4 // function that calculate unique elementint unique(int mat[R][C], int n, int m){ int maximum = 0, flag = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) // Find maximum element in // a matrix if(maximum < mat[i][j]) maximum = mat[i][j]; // Take 1-D array of (maximum + 1) // size int b[maximum + 1] = {0}; for(int i = 0 ; i < n; i++) for(int j = 0; j < m; j++) b[mat[i][j]]++; //print unique element for(int i = 1; i <= maximum; i++) if(b[i] == 1) cout << i << \" \"; flag = 1; if(!flag){ cout << \"No unique element in the matrix\"; }} // Driver programint main(){ int mat[R][C] = {{ 1, 2, 3, 20}, {5, 6, 20, 25}, {1, 3, 5, 6}, {6, 7, 8, 15}}; // function that calculate unique element unique(mat, R, C); return 0;} // This code is contributed by Naman_Garg.",
"e": 1888,
"s": 755,
"text": null
},
{
"code": "// Java program to find unique// element in matrixclass GFG{static int R = 4, C = 4; // function that calculate// unique elementstatic void unique(int mat[][], int n, int m){ int maximum = 0, flag = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) // Find maximum element // in a matrix if(maximum < mat[i][j]) maximum = mat[i][j]; // Take 1-D array of // (maximum + 1) size int b[] = new int [maximum + 1]; for(int i = 0 ; i < n; i++) for(int j = 0; j < m; j++) b[mat[i][j]]++; //print unique element for(int i = 1; i <= maximum; i++) if(b[i] == 1) System.out.print(i + \" \"); flag = 1; if(flag == 0) { System.out.println(\"No unique element \" + \"in the matrix\"); }} // Driver Codepublic static void main(String args[]){ int mat[][] = {{1, 2, 3, 20}, {5, 6, 20, 25}, {1, 3, 5, 6}, {6, 7, 8, 15}}; // function that calculate // unique element unique(mat, R, C);}} // This code is contributed// by Arnab Kundu",
"e": 3109,
"s": 1888,
"text": null
},
{
"code": "# Python 3 program to find unique# element in matrixdef unique(mat, n, m): maximum = 0; flag = 0 for i in range(0, n): for j in range(0, m): # Find maximum element in # a matrix if(maximum < mat[i][j]): maximum = mat[i][j]; uniqueElementDict = [0] * (maximum + 1) # loops to traverse through the matrix for i in range(0, n): for j in range(0, m): uniqueElementDict[mat[i][j]] += 1 # Print all those keys whose count is 1 for key in range(maximum + 1): if uniqueElementDict[key] == 1: print (key, end = \" \") flag = 1 if(flag == 0): print(\"No unique element in the matrix\") # Driver Codemat = [[1, 2, 3, 20], [5, 6, 20, 25], [1, 3, 5, 6], [6, 7, 8, 15]]n = 4m = 4unique(mat, n, m)",
"e": 3970,
"s": 3109,
"text": null
},
{
"code": "// C# program to find unique// element in matrixusing System; class GFG{static int R = 4, C = 4; // function that calculate// unique elementstatic void unique(int [,]mat, int n, int m){ int maximum = 0, flag = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) // Find maximum element // in a matrix if(maximum < mat[i, j]) maximum = mat[i, j]; // Take 1-D array of // (maximum + 1) size int []b = new int [maximum + 1]; for(int i = 0 ; i < n; i++) for(int j = 0; j < m; j++) b[mat[i, j]]++; // print unique element for(int i = 1; i <= maximum; i++) if(b[i] == 1) Console.Write(i + \" \"); flag = 1; if(flag == 0) { Console.WriteLine(\"No unique element \" + \"in the matrix\"); }} // Driver Codepublic static void Main(){ int [,]mat = {{1, 2, 3, 20}, {5, 6, 20, 25}, {1, 3, 5, 6}, {6, 7, 8, 15}}; // function that calculate // unique element unique(mat, R, C);}} // This code is contributed// by Subhadeep",
"e": 5179,
"s": 3970,
"text": null
},
{
"code": "<?php// PHP program to find unique// element in matrix $R = 4;$C = 4; // function that calculate unique elementfunction unique($mat, $n, $m){ $maximum = 0; $flag = 0; for($i = 0; $i < $n; $i++) for($j = 0; $j < $m; $j++) // Find maximum element in // a matrix if($maximum < $mat[$i][$j]) $maximum = $mat[$i][$j]; // Take 1-D array of (maximum + 1) // size $b = array(); for($j = 0; $j < $maximum + 1; $j++) $b[$j] = 0; for($i = 0 ; $i < $n; $i++) for($j = 0; $j < $m; $j++) $b[$mat[$i][$j]]++; // print unique element for($i = 1; $i <= $maximum; $i++) if($b[$i] == 1) echo \"$i \"; $flag = 1; if(!$flag) { echo \"No unique element in the matrix\"; }} // Driver Code$mat = array(array(1, 2, 3, 20), array(5, 6, 20, 25), array(1, 3, 5, 6), array(6, 7, 8, 15)); // function that calculate unique elementunique($mat, $R, $C); // This code is contributed by iAyushRaj?>",
"e": 6280,
"s": 5179,
"text": null
},
{
"code": "<script> // Javascript program to find unique// element in matrixvar R = 4, C = 4; // Function that calculate// unique elementfunction unique(mat, n, m){ var maximum = 0, flag = 0; for(var i = 0; i < n; i++) for(var j = 0; j < m; j++) // Find maximum element // in a matrix if (maximum < mat[i][j]) maximum = mat[i][j]; // Take 1-D array of // (maximum + 1) size var b = Array(maximum+1).fill(0); for(var i = 0 ; i < n; i++) for(var j = 0; j < m; j++) b[mat[i][j]]++; // Print unique element for(var i = 1; i <= maximum; i++) if (b[i] == 1) document.write(i + \" \"); flag = 1; if (flag == 0) { document.write(\"No unique element \" + \"in the matrix<br>\"); }} // Driver Codevar mat = [ [ 1, 2, 3, 20 ], [ 5, 6, 20, 25 ], [ 1, 3, 5, 6 ], [ 6, 7, 8, 15 ] ]; // Function that calculate// unique elementunique(mat, R, C); // This code is contributed by rrrtnx </script>",
"e": 7379,
"s": 6280,
"text": null
},
{
"code": null,
"e": 7392,
"s": 7379,
"text": "2 7 8 15 25 "
},
{
"code": null,
"e": 7413,
"s": 7392,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 7531,
"s": 7413,
"text": "Time Complexity: O(m*n) where m is the number of rows & n is the number of columns.Auxiliary Space: O(max(matrix)). "
},
{
"code": null,
"e": 7542,
"s": 7531,
"text": "andrew1234"
},
{
"code": null,
"e": 7558,
"s": 7542,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 7569,
"s": 7558,
"text": "Naman_Garg"
},
{
"code": null,
"e": 7579,
"s": 7569,
"text": "iAyushRaj"
},
{
"code": null,
"e": 7586,
"s": 7579,
"text": "rrrtnx"
},
{
"code": null,
"e": 7597,
"s": 7586,
"text": "vinayedula"
},
{
"code": null,
"e": 7609,
"s": 7597,
"text": "python-dict"
},
{
"code": null,
"e": 7616,
"s": 7609,
"text": "Matrix"
},
{
"code": null,
"e": 7628,
"s": 7616,
"text": "python-dict"
},
{
"code": null,
"e": 7635,
"s": 7628,
"text": "Matrix"
},
{
"code": null,
"e": 7733,
"s": 7635,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7768,
"s": 7733,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 7812,
"s": 7768,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 7843,
"s": 7812,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 7867,
"s": 7843,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 7914,
"s": 7867,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 7936,
"s": 7914,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 8018,
"s": 7936,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 8089,
"s": 8018,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 8127,
"s": 8089,
"text": "Unique paths in a Grid with Obstacles"
}
] |
Memory Allocation in Static Data Members in C++
|
14 Jun, 2020
C++ allows defining static data members within a class using the static keyword.When a data member is declared as static, then we must keep the following note in mind:
Irrespective of the number of objects created, only a single copy of the static member is created in memory.
All objects of a class share the static member.
All static data members are initiated to zero when the first object of that class is created.
Static data members are visible only within the class but their lifetime is the entire program.
Relevance:Static data members are usually used to maintain values that are common for the entire class. , For Example, to keep a track of how many objects of a particular class have been created.
Place of Storage:Although static data members are declared inside a class, they are not considered to be a part of the objects. Consequently, their declaration in the class is not considered as their definition. A static data member is defined outside the class. This means that even though the static data member is declared in class scope, their definition persists in the entire file. A static member has file scope. However, since a static data member is declared inside the class, they can be accessed only by using the class name and the scope resolution operator.
Below is the program to illustrate memory allocation in static and non-static data members:
Program 1: to illustrate non-static members
// C++ program to illustrate// non-static data membersusing namespace std;#include <iostream> // Classclass GfG {private: // Created a variable int count = 0; public: // Member function to increment // value of count void set_count() { count++; } // Member function to access the // private members of this class void show_count() { // print the count variable cout << count << '\n'; }}; // Driver Codeint main(){ // Objects of class GfG GfG S1, S2, S3; // Set count variable to 1 // for each object S1.set_count(); S2.set_count(); S3.set_count(); // Function to display count // for each object S1.show_count(); S2.show_count(); S3.show_count(); return 0;}
1
1
1
Below is the illustration of memory allocation for the above program:
Explanation:All three objects of class GfG S1, S2, and S3 share the member functions but have a separate copy of the data member count. In main(), the set_count() is explicitly called to set the value of count to 1. Now, each object has the value of its count = 1.
Program 2: to illustrate static members:
// C++ program to illustrate// non-static data membersusing namespace std;#include <iostream> // Classclass GfG {private: // Created a static variable static int count; public: // Member function to increment // value of count void set_count() { count++; } // Member function to access the // private members of this class void show_count() { // print the count variable cout << count << '\n'; }}; int GfG::count = 0; // Driver Codeint main(){ // Objects of class GfG GfG S1, S2, S3; // Increment count variable // by 1 for each object S1.set_count(); S2.set_count(); S3.set_count(); // Function to display count // for each object S1.show_count(); S2.show_count(); S3.show_count(); return 0;}
3
3
3
Below is the illustration of memory allocation for the above program:
Explanation:All three objects of class GfG S1, S2, and S3 shares the member functions as well as the static data member. Only one copy of the static data member exists in the memory. There is no need for a function to explicitly set the value of count because the value of static data members has been initialized to 0 outside the class definition. Now, each object increments the value of count and hence the output.Note: Memory for member functions and static data members is allocated per class and not per object. The class sample has no data member(except static count), but this does not mean no memory space will be allocated to the objects of Sample. In such cases, minimum memory is set aside for object. Therefore, the size of S1, S2, and S3 is 1 byte.
C++-Static Keyword
Memory Management
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
Virtual Function in C++
Templates in C++ with Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2020"
},
{
"code": null,
"e": 220,
"s": 52,
"text": "C++ allows defining static data members within a class using the static keyword.When a data member is declared as static, then we must keep the following note in mind:"
},
{
"code": null,
"e": 329,
"s": 220,
"text": "Irrespective of the number of objects created, only a single copy of the static member is created in memory."
},
{
"code": null,
"e": 377,
"s": 329,
"text": "All objects of a class share the static member."
},
{
"code": null,
"e": 471,
"s": 377,
"text": "All static data members are initiated to zero when the first object of that class is created."
},
{
"code": null,
"e": 567,
"s": 471,
"text": "Static data members are visible only within the class but their lifetime is the entire program."
},
{
"code": null,
"e": 763,
"s": 567,
"text": "Relevance:Static data members are usually used to maintain values that are common for the entire class. , For Example, to keep a track of how many objects of a particular class have been created."
},
{
"code": null,
"e": 1334,
"s": 763,
"text": "Place of Storage:Although static data members are declared inside a class, they are not considered to be a part of the objects. Consequently, their declaration in the class is not considered as their definition. A static data member is defined outside the class. This means that even though the static data member is declared in class scope, their definition persists in the entire file. A static member has file scope. However, since a static data member is declared inside the class, they can be accessed only by using the class name and the scope resolution operator."
},
{
"code": null,
"e": 1426,
"s": 1334,
"text": "Below is the program to illustrate memory allocation in static and non-static data members:"
},
{
"code": null,
"e": 1470,
"s": 1426,
"text": "Program 1: to illustrate non-static members"
},
{
"code": "// C++ program to illustrate// non-static data membersusing namespace std;#include <iostream> // Classclass GfG {private: // Created a variable int count = 0; public: // Member function to increment // value of count void set_count() { count++; } // Member function to access the // private members of this class void show_count() { // print the count variable cout << count << '\\n'; }}; // Driver Codeint main(){ // Objects of class GfG GfG S1, S2, S3; // Set count variable to 1 // for each object S1.set_count(); S2.set_count(); S3.set_count(); // Function to display count // for each object S1.show_count(); S2.show_count(); S3.show_count(); return 0;}",
"e": 2237,
"s": 1470,
"text": null
},
{
"code": null,
"e": 2244,
"s": 2237,
"text": "1\n1\n1\n"
},
{
"code": null,
"e": 2314,
"s": 2244,
"text": "Below is the illustration of memory allocation for the above program:"
},
{
"code": null,
"e": 2579,
"s": 2314,
"text": "Explanation:All three objects of class GfG S1, S2, and S3 share the member functions but have a separate copy of the data member count. In main(), the set_count() is explicitly called to set the value of count to 1. Now, each object has the value of its count = 1."
},
{
"code": null,
"e": 2620,
"s": 2579,
"text": "Program 2: to illustrate static members:"
},
{
"code": "// C++ program to illustrate// non-static data membersusing namespace std;#include <iostream> // Classclass GfG {private: // Created a static variable static int count; public: // Member function to increment // value of count void set_count() { count++; } // Member function to access the // private members of this class void show_count() { // print the count variable cout << count << '\\n'; }}; int GfG::count = 0; // Driver Codeint main(){ // Objects of class GfG GfG S1, S2, S3; // Increment count variable // by 1 for each object S1.set_count(); S2.set_count(); S3.set_count(); // Function to display count // for each object S1.show_count(); S2.show_count(); S3.show_count(); return 0;}",
"e": 3424,
"s": 2620,
"text": null
},
{
"code": null,
"e": 3431,
"s": 3424,
"text": "3\n3\n3\n"
},
{
"code": null,
"e": 3501,
"s": 3431,
"text": "Below is the illustration of memory allocation for the above program:"
},
{
"code": null,
"e": 4264,
"s": 3501,
"text": "Explanation:All three objects of class GfG S1, S2, and S3 shares the member functions as well as the static data member. Only one copy of the static data member exists in the memory. There is no need for a function to explicitly set the value of count because the value of static data members has been initialized to 0 outside the class definition. Now, each object increments the value of count and hence the output.Note: Memory for member functions and static data members is allocated per class and not per object. The class sample has no data member(except static count), but this does not mean no memory space will be allocated to the objects of Sample. In such cases, minimum memory is set aside for object. Therefore, the size of S1, S2, and S3 is 1 byte."
},
{
"code": null,
"e": 4283,
"s": 4264,
"text": "C++-Static Keyword"
},
{
"code": null,
"e": 4301,
"s": 4283,
"text": "Memory Management"
},
{
"code": null,
"e": 4305,
"s": 4301,
"text": "C++"
},
{
"code": null,
"e": 4309,
"s": 4305,
"text": "CPP"
},
{
"code": null,
"e": 4407,
"s": 4309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4461,
"s": 4407,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4504,
"s": 4461,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4538,
"s": 4504,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 4563,
"s": 4538,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 4580,
"s": 4563,
"text": "Substring in C++"
},
{
"code": null,
"e": 4604,
"s": 4580,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 4644,
"s": 4604,
"text": "2D Vector In C++ With User Defined Size"
},
{
"code": null,
"e": 4659,
"s": 4644,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4683,
"s": 4659,
"text": "Virtual Function in C++"
}
] |
Python | Perform operation on each key dictionary
|
26 Jul, 2019
Sometimes, while working with dictionaries, we might come across a problem in which we require to perform a particular operation on each value of keys. This type of problem can occur in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is the naive method in which this task can be performed. In this we simply run a loop to traverse each key in dictionary and perform the desired operation.
# Python3 code to demonstrate working of# Perform operation on each key dictionary# Using loop # Initialize dictionarytest_dict = {'gfg' : 6, 'is' : 4, 'best' : 7} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Using loop# Perform operation on each key dictionaryfor key in test_dict: test_dict[key] *= 3 # printing result print("The dictionary after triple each key's value : " + str(test_dict))
The original dictionary : {‘is’: 4, ‘gfg’: 6, ‘best’: 7}The dictionary after triple each key’s value : {‘is’: 12, ‘gfg’: 18, ‘best’: 21}
Method #2 : Using update() + dictionary comprehensionAn alternate one-liner to perform this task, the combination of above functions can be used to perform this particular task. The update function is used to perform the necessary operation over the dictionary.
# Python3 code to demonstrate working of# Perform operation on each key dictionary# Using update() + dictionary comprehension # Initialize dictionarytest_dict = {'gfg' : 6, 'is' : 4, 'best' : 7} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Using update() + dictionary comprehension# Perform operation on each key dictionarytest_dict.update((x, y * 3) for x, y in test_dict.items()) # printing result print("The dictionary after triple each key's value : " + str(test_dict))
The original dictionary : {‘is’: 4, ‘gfg’: 6, ‘best’: 7}The dictionary after triple each key’s value : {‘is’: 12, ‘gfg’: 18, ‘best’: 21}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2019"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "Sometimes, while working with dictionaries, we might come across a problem in which we require to perform a particular operation on each value of keys. This type of problem can occur in web development domain. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 485,
"s": 302,
"text": "Method #1 : Using loopThis is the naive method in which this task can be performed. In this we simply run a loop to traverse each key in dictionary and perform the desired operation."
},
{
"code": "# Python3 code to demonstrate working of# Perform operation on each key dictionary# Using loop # Initialize dictionarytest_dict = {'gfg' : 6, 'is' : 4, 'best' : 7} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Using loop# Perform operation on each key dictionaryfor key in test_dict: test_dict[key] *= 3 # printing result print(\"The dictionary after triple each key's value : \" + str(test_dict))",
"e": 932,
"s": 485,
"text": null
},
{
"code": null,
"e": 1069,
"s": 932,
"text": "The original dictionary : {‘is’: 4, ‘gfg’: 6, ‘best’: 7}The dictionary after triple each key’s value : {‘is’: 12, ‘gfg’: 18, ‘best’: 21}"
},
{
"code": null,
"e": 1333,
"s": 1071,
"text": "Method #2 : Using update() + dictionary comprehensionAn alternate one-liner to perform this task, the combination of above functions can be used to perform this particular task. The update function is used to perform the necessary operation over the dictionary."
},
{
"code": "# Python3 code to demonstrate working of# Perform operation on each key dictionary# Using update() + dictionary comprehension # Initialize dictionarytest_dict = {'gfg' : 6, 'is' : 4, 'best' : 7} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Using update() + dictionary comprehension# Perform operation on each key dictionarytest_dict.update((x, y * 3) for x, y in test_dict.items()) # printing result print(\"The dictionary after triple each key's value : \" + str(test_dict))",
"e": 1852,
"s": 1333,
"text": null
},
{
"code": null,
"e": 1989,
"s": 1852,
"text": "The original dictionary : {‘is’: 4, ‘gfg’: 6, ‘best’: 7}The dictionary after triple each key’s value : {‘is’: 12, ‘gfg’: 18, ‘best’: 21}"
},
{
"code": null,
"e": 2016,
"s": 1989,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2023,
"s": 2016,
"text": "Python"
},
{
"code": null,
"e": 2039,
"s": 2023,
"text": "Python Programs"
},
{
"code": null,
"e": 2137,
"s": 2039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2155,
"s": 2137,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2197,
"s": 2155,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2232,
"s": 2197,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2258,
"s": 2232,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2290,
"s": 2258,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2333,
"s": 2290,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2355,
"s": 2333,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2394,
"s": 2355,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2432,
"s": 2394,
"text": "Python | Convert a list to dictionary"
}
] |
Matplotlib.pyplot.figtext() in Python
|
19 Apr, 2020
Matplotlib is an extensively used Python library for data visualization. It is a multi-platform data visualization library built on NumPy arrays, also designed to work with the SciPy stack.
Figtext is used to add text to a figure at any location on it. You can even add the text outside the Axes. It uses the complete figure for co-ordinates, where bottom-left denotes (0, 0) and top right represents (1, 1). The centre of the figure is (0.5, 0.5).
Syntax:
matplotlib.pyplot.figtext(x, y, s, *args, **kwargs)
Example #1: A sample example demonstrating the use of figtext.
# importing required modules import matplotlib.pyplot as pltimport numpy as np # values of x and y axes x = np.arange(0, 8, 0.1)y = np.sin(x) plt.plot(x, y) # pyplot.figtext(x, y, string)plt.figtext(0, 0, "This is a sample example \explaining figtext", fontsize = 10) plt.xlabel('x') plt.ylabel('y') plt.show()
The above example places text on the bottom left of the figure of the given font size.
Example #2: We can also place text at a relative position in the figure by adjusting the values of x and y.
# importing required modules import matplotlib.pyplot as pltimport numpy as np # values of x and y axes x = np.arange(0, 8, 0.1)y = np.sin(x) plt.plot(x, y) plt.figtext(0.55, 0.7, "Sin curve", horizontalalignment ="center", verticalalignment ="center", wrap = True, fontsize = 14, color ="green") plt.xlabel('x') plt.ylabel('y') plt.show()
Alignment arguments- horizontalalignment and verticalalignment place the text in the centre while the wrap argument makes sure that the text lies within the figure width. The color argument gives the font color.
Example #3: We can also add a bounding box around the text by using the bbox argument.
# importing required modules import matplotlib.pyplot as pltimport numpy as np # values of x and y axes x = np.arange(0, 8, 0.1)y = np.exp(x) plt.plot(x, y) # pyplot.figtext(x, y, string)plt.figtext(0.55, 0.7, "Exponential Curve", horizontalalignment ="center", wrap = True, fontsize = 10, bbox ={'facecolor':'grey', 'alpha':0.3, 'pad':5}) plt.xlabel('x') plt.ylabel('y') plt.show()
Example #4: We can also use *args and **kwargs to add text properties to our plot. *args and **kwargs are used to pass multiple arguments or keyword arguments to a function.Note: For more info refer to the article: *args and **kwargs in Python
# importing required propertiesimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 100, 501)y = np.sin(x) figtext_args = (0.5, 0, "figtext using args and kwargs") figtext_kwargs = dict(horizontalalignment ="center", fontsize = 14, color ="green", style ="italic", wrap = True) plt.plot(x, y) plt.figtext(*figtext_args, **figtext_kwargs)plt.show()
Python-matplotlib
Python
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": "\n19 Apr, 2020"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "Matplotlib is an extensively used Python library for data visualization. It is a multi-platform data visualization library built on NumPy arrays, also designed to work with the SciPy stack."
},
{
"code": null,
"e": 477,
"s": 218,
"text": "Figtext is used to add text to a figure at any location on it. You can even add the text outside the Axes. It uses the complete figure for co-ordinates, where bottom-left denotes (0, 0) and top right represents (1, 1). The centre of the figure is (0.5, 0.5)."
},
{
"code": null,
"e": 485,
"s": 477,
"text": "Syntax:"
},
{
"code": null,
"e": 537,
"s": 485,
"text": "matplotlib.pyplot.figtext(x, y, s, *args, **kwargs)"
},
{
"code": null,
"e": 600,
"s": 537,
"text": "Example #1: A sample example demonstrating the use of figtext."
},
{
"code": "# importing required modules import matplotlib.pyplot as pltimport numpy as np # values of x and y axes x = np.arange(0, 8, 0.1)y = np.sin(x) plt.plot(x, y) # pyplot.figtext(x, y, string)plt.figtext(0, 0, \"This is a sample example \\explaining figtext\", fontsize = 10) plt.xlabel('x') plt.ylabel('y') plt.show()",
"e": 916,
"s": 600,
"text": null
},
{
"code": null,
"e": 1003,
"s": 916,
"text": "The above example places text on the bottom left of the figure of the given font size."
},
{
"code": null,
"e": 1111,
"s": 1003,
"text": "Example #2: We can also place text at a relative position in the figure by adjusting the values of x and y."
},
{
"code": "# importing required modules import matplotlib.pyplot as pltimport numpy as np # values of x and y axes x = np.arange(0, 8, 0.1)y = np.sin(x) plt.plot(x, y) plt.figtext(0.55, 0.7, \"Sin curve\", horizontalalignment =\"center\", verticalalignment =\"center\", wrap = True, fontsize = 14, color =\"green\") plt.xlabel('x') plt.ylabel('y') plt.show()",
"e": 1514,
"s": 1111,
"text": null
},
{
"code": null,
"e": 1726,
"s": 1514,
"text": "Alignment arguments- horizontalalignment and verticalalignment place the text in the centre while the wrap argument makes sure that the text lies within the figure width. The color argument gives the font color."
},
{
"code": null,
"e": 1813,
"s": 1726,
"text": "Example #3: We can also add a bounding box around the text by using the bbox argument."
},
{
"code": "# importing required modules import matplotlib.pyplot as pltimport numpy as np # values of x and y axes x = np.arange(0, 8, 0.1)y = np.exp(x) plt.plot(x, y) # pyplot.figtext(x, y, string)plt.figtext(0.55, 0.7, \"Exponential Curve\", horizontalalignment =\"center\", wrap = True, fontsize = 10, bbox ={'facecolor':'grey', 'alpha':0.3, 'pad':5}) plt.xlabel('x') plt.ylabel('y') plt.show()",
"e": 2266,
"s": 1813,
"text": null
},
{
"code": null,
"e": 2510,
"s": 2266,
"text": "Example #4: We can also use *args and **kwargs to add text properties to our plot. *args and **kwargs are used to pass multiple arguments or keyword arguments to a function.Note: For more info refer to the article: *args and **kwargs in Python"
},
{
"code": "# importing required propertiesimport numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 100, 501)y = np.sin(x) figtext_args = (0.5, 0, \"figtext using args and kwargs\") figtext_kwargs = dict(horizontalalignment =\"center\", fontsize = 14, color =\"green\", style =\"italic\", wrap = True) plt.plot(x, y) plt.figtext(*figtext_args, **figtext_kwargs)plt.show()",
"e": 2937,
"s": 2510,
"text": null
},
{
"code": null,
"e": 2955,
"s": 2937,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2962,
"s": 2955,
"text": "Python"
},
{
"code": null,
"e": 2978,
"s": 2962,
"text": "Write From Home"
}
] |
Parameter Passing Techniques in C/C++
|
10 Feb, 2022
There are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case A is called the “caller function” and B is called the “called function or callee function”. Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal arguments.
Terminology
Formal Parameter : A variable and its type as they appear in the prototype of the function or method.
Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment.
Modes:IN: Passes info from caller to callee.OUT: Callee writes values in caller.IN/OUT: Caller tells callee value of variable, which may be updated by callee.
IN: Passes info from caller to callee.
OUT: Callee writes values in caller.
IN/OUT: Caller tells callee value of variable, which may be updated by callee.
Important methods of Parameter Passing
Pass By Value: This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.CCPPC// C program to illustrate// call by value#include <stdio.h> void func(int a, int b){ a += b; printf("In func, a = %d b = %d\n", a, b);}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); printf("In main, x = %d y = %d\n", x, y); return 0;}CPP// C++ program to illustrate// call by value#include <iostream>using namespace std; void func(int a, int b){ a += b; cout <<"In func, a = " << a << " b = "<< b << endl;}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); cout << "In main, x = " << x << " y = " << y; return 0;} // This code is contributed by shivanisinghss2110Output:In func, a = 12 b = 7
In main, x = 5 y = 7
Languages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value.Shortcomings:Inefficiency in storage allocationFor objects and arrays, the copy semantics are costlyPass by reference(aliasing): This technique uses in/out-mode semantics. Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as call by reference. This method is efficient in both time and space.CCPPC// C program to illustrate// call by reference#include <stdio.h> void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); printf("a is %d and b is %d\n", a, b); return 0;}CPP// C++ program to illustrate// call by reference#include <iostream.h>using namespace std; void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); cout <<"a is " << a <<" and b is "<< b; return 0;} // this code is contributed by shivanisinghss2110Output:a is 20 and b is 10
C and C++ both support call by value as well as call by reference whereas Java doesn’t support call by reference.Shortcomings:Many potential scenarios can occurPrograms are difficult to understand sometimes
Pass By Value: This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.CCPPC// C program to illustrate// call by value#include <stdio.h> void func(int a, int b){ a += b; printf("In func, a = %d b = %d\n", a, b);}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); printf("In main, x = %d y = %d\n", x, y); return 0;}CPP// C++ program to illustrate// call by value#include <iostream>using namespace std; void func(int a, int b){ a += b; cout <<"In func, a = " << a << " b = "<< b << endl;}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); cout << "In main, x = " << x << " y = " << y; return 0;} // This code is contributed by shivanisinghss2110Output:In func, a = 12 b = 7
In main, x = 5 y = 7
Languages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value.Shortcomings:Inefficiency in storage allocationFor objects and arrays, the copy semantics are costly
C
CPP
// C program to illustrate// call by value#include <stdio.h> void func(int a, int b){ a += b; printf("In func, a = %d b = %d\n", a, b);}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); printf("In main, x = %d y = %d\n", x, y); return 0;}
// C++ program to illustrate// call by value#include <iostream>using namespace std; void func(int a, int b){ a += b; cout <<"In func, a = " << a << " b = "<< b << endl;}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); cout << "In main, x = " << x << " y = " << y; return 0;} // This code is contributed by shivanisinghss2110
Output:
In func, a = 12 b = 7
In main, x = 5 y = 7
Languages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value.Shortcomings:
Inefficiency in storage allocation
For objects and arrays, the copy semantics are costly
Pass by reference(aliasing): This technique uses in/out-mode semantics. Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as call by reference. This method is efficient in both time and space.CCPPC// C program to illustrate// call by reference#include <stdio.h> void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); printf("a is %d and b is %d\n", a, b); return 0;}CPP// C++ program to illustrate// call by reference#include <iostream.h>using namespace std; void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); cout <<"a is " << a <<" and b is "<< b; return 0;} // this code is contributed by shivanisinghss2110Output:a is 20 and b is 10
C and C++ both support call by value as well as call by reference whereas Java doesn’t support call by reference.Shortcomings:Many potential scenarios can occurPrograms are difficult to understand sometimes
C
CPP
// C program to illustrate// call by reference#include <stdio.h> void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); printf("a is %d and b is %d\n", a, b); return 0;}
// C++ program to illustrate// call by reference#include <iostream.h>using namespace std; void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); cout <<"a is " << a <<" and b is "<< b; return 0;} // this code is contributed by shivanisinghss2110
Output:
a is 20 and b is 10
C and C++ both support call by value as well as call by reference whereas Java doesn’t support call by reference.Shortcomings:
Many potential scenarios can occur
Programs are difficult to understand sometimes
Other methods of Parameter Passing
These techniques are older and were used in earlier programming languages like Pascal, Algol and Fortran. These techniques are not applicable in high level languages.
Pass by Result:This method uses out-mode semantics. Just before control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter.T his method is sometimes called call by result. In general, pass by result technique is implemented by copy.Pass by Value-Result: This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-result. Just before the control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called as call by value-resultPass by name : This technique is used in programming language such as Algol. In this technique, symbolic “name” of a variable is passed, which allows it both to be accessed and update.Example:To double the value of C[j], you can pass its name (not its value) into the following procedure.procedure double(x);
real x;
begin
x:=x*2
end;
In general, the effect of pass-by-name is to textually substitute the argument in a procedure call for the corresponding parameter in the body of the procedure.Implications of Pass-by-Name mechanism:The argument expression is re-evaluated each time the formal parameter is passed.The procedure can change the values of variables used in the argument expression and hence change the expression’s value.
Pass by Result:This method uses out-mode semantics. Just before control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter.T his method is sometimes called call by result. In general, pass by result technique is implemented by copy.
Pass by Value-Result: This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-result. Just before the control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called as call by value-result
Pass by name : This technique is used in programming language such as Algol. In this technique, symbolic “name” of a variable is passed, which allows it both to be accessed and update.Example:To double the value of C[j], you can pass its name (not its value) into the following procedure.procedure double(x);
real x;
begin
x:=x*2
end;
In general, the effect of pass-by-name is to textually substitute the argument in a procedure call for the corresponding parameter in the body of the procedure.Implications of Pass-by-Name mechanism:The argument expression is re-evaluated each time the formal parameter is passed.The procedure can change the values of variables used in the argument expression and hence change the expression’s value.
procedure double(x);
real x;
begin
x:=x*2
end;
In general, the effect of pass-by-name is to textually substitute the argument in a procedure call for the corresponding parameter in the body of the procedure.Implications of Pass-by-Name mechanism:
The argument expression is re-evaluated each time the formal parameter is passed.
The procedure can change the values of variables used in the argument expression and hence change the expression’s value.
This article is contributed by Krishna Bhatia. 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.
shivanisinghss2110
sooda367
chhabradhanvi
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 450,
"s": 52,
"text": "There are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case A is called the “caller function” and B is called the “called function or callee function”. Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal arguments."
},
{
"code": null,
"e": 462,
"s": 450,
"text": "Terminology"
},
{
"code": null,
"e": 564,
"s": 462,
"text": "Formal Parameter : A variable and its type as they appear in the prototype of the function or method."
},
{
"code": null,
"e": 718,
"s": 564,
"text": "Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment."
},
{
"code": null,
"e": 877,
"s": 718,
"text": "Modes:IN: Passes info from caller to callee.OUT: Callee writes values in caller.IN/OUT: Caller tells callee value of variable, which may be updated by callee."
},
{
"code": null,
"e": 916,
"s": 877,
"text": "IN: Passes info from caller to callee."
},
{
"code": null,
"e": 953,
"s": 916,
"text": "OUT: Callee writes values in caller."
},
{
"code": null,
"e": 1032,
"s": 953,
"text": "IN/OUT: Caller tells callee value of variable, which may be updated by callee."
},
{
"code": null,
"e": 1071,
"s": 1032,
"text": "Important methods of Parameter Passing"
},
{
"code": null,
"e": 3694,
"s": 1071,
"text": "Pass By Value: This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.CCPPC// C program to illustrate// call by value#include <stdio.h> void func(int a, int b){ a += b; printf(\"In func, a = %d b = %d\\n\", a, b);}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); printf(\"In main, x = %d y = %d\\n\", x, y); return 0;}CPP// C++ program to illustrate// call by value#include <iostream>using namespace std; void func(int a, int b){ a += b; cout <<\"In func, a = \" << a << \" b = \"<< b << endl;}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); cout << \"In main, x = \" << x << \" y = \" << y; return 0;} // This code is contributed by shivanisinghss2110Output:In func, a = 12 b = 7\nIn main, x = 5 y = 7\nLanguages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value.Shortcomings:Inefficiency in storage allocationFor objects and arrays, the copy semantics are costlyPass by reference(aliasing): This technique uses in/out-mode semantics. Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as call by reference. This method is efficient in both time and space.CCPPC// C program to illustrate// call by reference#include <stdio.h> void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); printf(\"a is %d and b is %d\\n\", a, b); return 0;}CPP// C++ program to illustrate// call by reference#include <iostream.h>using namespace std; void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); cout <<\"a is \" << a <<\" and b is \"<< b; return 0;} // this code is contributed by shivanisinghss2110Output:a is 20 and b is 10\nC and C++ both support call by value as well as call by reference whereas Java doesn’t support call by reference.Shortcomings:Many potential scenarios can occurPrograms are difficult to understand sometimes"
},
{
"code": null,
"e": 4987,
"s": 3694,
"text": "Pass By Value: This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.CCPPC// C program to illustrate// call by value#include <stdio.h> void func(int a, int b){ a += b; printf(\"In func, a = %d b = %d\\n\", a, b);}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); printf(\"In main, x = %d y = %d\\n\", x, y); return 0;}CPP// C++ program to illustrate// call by value#include <iostream>using namespace std; void func(int a, int b){ a += b; cout <<\"In func, a = \" << a << \" b = \"<< b << endl;}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); cout << \"In main, x = \" << x << \" y = \" << y; return 0;} // This code is contributed by shivanisinghss2110Output:In func, a = 12 b = 7\nIn main, x = 5 y = 7\nLanguages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value.Shortcomings:Inefficiency in storage allocationFor objects and arrays, the copy semantics are costly"
},
{
"code": null,
"e": 4989,
"s": 4987,
"text": "C"
},
{
"code": null,
"e": 4993,
"s": 4989,
"text": "CPP"
},
{
"code": "// C program to illustrate// call by value#include <stdio.h> void func(int a, int b){ a += b; printf(\"In func, a = %d b = %d\\n\", a, b);}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); printf(\"In main, x = %d y = %d\\n\", x, y); return 0;}",
"e": 5274,
"s": 4993,
"text": null
},
{
"code": "// C++ program to illustrate// call by value#include <iostream>using namespace std; void func(int a, int b){ a += b; cout <<\"In func, a = \" << a << \" b = \"<< b << endl;}int main(void){ int x = 5, y = 7; // Passing parameters func(x, y); cout << \"In main, x = \" << x << \" y = \" << y; return 0;} // This code is contributed by shivanisinghss2110",
"e": 5643,
"s": 5274,
"text": null
},
{
"code": null,
"e": 5651,
"s": 5643,
"text": "Output:"
},
{
"code": null,
"e": 5695,
"s": 5651,
"text": "In func, a = 12 b = 7\nIn main, x = 5 y = 7\n"
},
{
"code": null,
"e": 5816,
"s": 5695,
"text": "Languages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value.Shortcomings:"
},
{
"code": null,
"e": 5851,
"s": 5816,
"text": "Inefficiency in storage allocation"
},
{
"code": null,
"e": 5905,
"s": 5851,
"text": "For objects and arrays, the copy semantics are costly"
},
{
"code": null,
"e": 7236,
"s": 5905,
"text": "Pass by reference(aliasing): This technique uses in/out-mode semantics. Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as call by reference. This method is efficient in both time and space.CCPPC// C program to illustrate// call by reference#include <stdio.h> void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); printf(\"a is %d and b is %d\\n\", a, b); return 0;}CPP// C++ program to illustrate// call by reference#include <iostream.h>using namespace std; void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); cout <<\"a is \" << a <<\" and b is \"<< b; return 0;} // this code is contributed by shivanisinghss2110Output:a is 20 and b is 10\nC and C++ both support call by value as well as call by reference whereas Java doesn’t support call by reference.Shortcomings:Many potential scenarios can occurPrograms are difficult to understand sometimes"
},
{
"code": null,
"e": 7238,
"s": 7236,
"text": "C"
},
{
"code": null,
"e": 7242,
"s": 7238,
"text": "CPP"
},
{
"code": "// C program to illustrate// call by reference#include <stdio.h> void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); printf(\"a is %d and b is %d\\n\", a, b); return 0;}",
"e": 7528,
"s": 7242,
"text": null
},
{
"code": "// C++ program to illustrate// call by reference#include <iostream.h>using namespace std; void swapnum(int* i, int* j){ int temp = *i; *i = *j; *j = temp;} int main(void){ int a = 10, b = 20; // passing parameters swapnum(&a, &b); cout <<\"a is \" << a <<\" and b is \"<< b; return 0;} // this code is contributed by shivanisinghss2110",
"e": 7891,
"s": 7528,
"text": null
},
{
"code": null,
"e": 7899,
"s": 7891,
"text": "Output:"
},
{
"code": null,
"e": 7920,
"s": 7899,
"text": "a is 20 and b is 10\n"
},
{
"code": null,
"e": 8047,
"s": 7920,
"text": "C and C++ both support call by value as well as call by reference whereas Java doesn’t support call by reference.Shortcomings:"
},
{
"code": null,
"e": 8082,
"s": 8047,
"text": "Many potential scenarios can occur"
},
{
"code": null,
"e": 8129,
"s": 8082,
"text": "Programs are difficult to understand sometimes"
},
{
"code": null,
"e": 8164,
"s": 8129,
"text": "Other methods of Parameter Passing"
},
{
"code": null,
"e": 8331,
"s": 8164,
"text": "These techniques are older and were used in earlier programming languages like Pascal, Algol and Fortran. These techniques are not applicable in high level languages."
},
{
"code": null,
"e": 9679,
"s": 8331,
"text": "Pass by Result:This method uses out-mode semantics. Just before control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter.T his method is sometimes called call by result. In general, pass by result technique is implemented by copy.Pass by Value-Result: This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-result. Just before the control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called as call by value-resultPass by name : This technique is used in programming language such as Algol. In this technique, symbolic “name” of a variable is passed, which allows it both to be accessed and update.Example:To double the value of C[j], you can pass its name (not its value) into the following procedure.procedure double(x);\n real x;\nbegin \n x:=x*2\nend;\nIn general, the effect of pass-by-name is to textually substitute the argument in a procedure call for the corresponding parameter in the body of the procedure.Implications of Pass-by-Name mechanism:The argument expression is re-evaluated each time the formal parameter is passed.The procedure can change the values of variables used in the argument expression and hence change the expression’s value."
},
{
"code": null,
"e": 9974,
"s": 9679,
"text": "Pass by Result:This method uses out-mode semantics. Just before control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter.T his method is sometimes called call by result. In general, pass by result technique is implemented by copy."
},
{
"code": null,
"e": 10287,
"s": 9974,
"text": "Pass by Value-Result: This method uses in/out-mode semantics. It is a combination of Pass-by-Value and Pass-by-result. Just before the control is transferred back to the caller, the value of the formal parameter is transmitted back to the actual parameter. This method is sometimes called as call by value-result"
},
{
"code": null,
"e": 11029,
"s": 10287,
"text": "Pass by name : This technique is used in programming language such as Algol. In this technique, symbolic “name” of a variable is passed, which allows it both to be accessed and update.Example:To double the value of C[j], you can pass its name (not its value) into the following procedure.procedure double(x);\n real x;\nbegin \n x:=x*2\nend;\nIn general, the effect of pass-by-name is to textually substitute the argument in a procedure call for the corresponding parameter in the body of the procedure.Implications of Pass-by-Name mechanism:The argument expression is re-evaluated each time the formal parameter is passed.The procedure can change the values of variables used in the argument expression and hence change the expression’s value."
},
{
"code": null,
"e": 11082,
"s": 11029,
"text": "procedure double(x);\n real x;\nbegin \n x:=x*2\nend;\n"
},
{
"code": null,
"e": 11282,
"s": 11082,
"text": "In general, the effect of pass-by-name is to textually substitute the argument in a procedure call for the corresponding parameter in the body of the procedure.Implications of Pass-by-Name mechanism:"
},
{
"code": null,
"e": 11364,
"s": 11282,
"text": "The argument expression is re-evaluated each time the formal parameter is passed."
},
{
"code": null,
"e": 11486,
"s": 11364,
"text": "The procedure can change the values of variables used in the argument expression and hence change the expression’s value."
},
{
"code": null,
"e": 11788,
"s": 11486,
"text": "This article is contributed by Krishna Bhatia. 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": 11913,
"s": 11788,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11932,
"s": 11913,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 11941,
"s": 11932,
"text": "sooda367"
},
{
"code": null,
"e": 11955,
"s": 11941,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 11966,
"s": 11955,
"text": "C Language"
},
{
"code": null,
"e": 11970,
"s": 11966,
"text": "C++"
},
{
"code": null,
"e": 11974,
"s": 11970,
"text": "CPP"
},
{
"code": null,
"e": 12072,
"s": 11974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12089,
"s": 12072,
"text": "Substring in C++"
},
{
"code": null,
"e": 12124,
"s": 12089,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 12146,
"s": 12124,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 12192,
"s": 12146,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 12237,
"s": 12192,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 12255,
"s": 12237,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 12298,
"s": 12255,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 12344,
"s": 12298,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 12398,
"s": 12344,
"text": "Priority Queue in C++ Standard Template Library (STL)"
}
] |
Dynamic NAT (on ASA)
|
25 Oct, 2021
Prerequisite – Adaptive security appliance (ASA), Network address translation (NAT), Static NAT (on ASA) Network Address Translation is used for the translation of private IP addresses into public IP addresses while accessing the internet.NAT generally operates on a router or firewall.
Dynamic NAT – In this type of NAT, multiple private IP addresses are mapped to a pool of public IP addresses. It is used when we know the number of fixed users who want to access the Internet at a given point in time.
Example: If we have 4 public IP address in a pool then at a time, only 4 users private IP address gets translated into public address. The private IP who have a request for the translation first will get translated first (like First Come First Serve). If all the IP addresses in the pool are busy and a request for translation is received then the packets will be dropped.
Procedure (on ASA) – The Procedure is the same as static NAT:
Step-1: Configure the access list – Build the access list stating the permit condition i.e who should be permitted and what protocol should be permitted.
Step-2: Apply the access-list to an interface – The access-group command will be used to state the direction (out or in) in which the action (specified above) should be taken place.
Step-3: Create network object – This will state the host or subnet on which Dynamic NAT will be applied. Note that here 2 objects are created. One will specify the hosts or subnet (private IP address) on which NAT should be applied and the other will the pool of public IP addresses.
Note that here 2 objects are created. One will specify the hosts or subnet (private IP address) on which NAT should be applied and the other will the pool of public IP addresses.
Step-4: Create Dynamic NAT statement – This step will specify the direction in which NAT should take place and on what IP address (Public IP address) the private IP address should be translated.
For example NAT (DMZ, OUTSIDE), Dynamic Private_hosts Public_pool: This states that the Dynamic NAT operation will take place when the traffic is going from DMZ to OUTSIDE and will translate the IP address (specified in the network object Private_hosts) to the available IP address of Pool (Public_pool).
Example –
Three routers namely Router1 (IP address – 10.1.1.1/24), Router2 (IP address – 11.1.1.1/24) and Router3 (IP address – 101.1.1.1) are connected to ASA (IP address- 10.1.1.2/24, name – INSIDE and security level – 100 on Gi0/0, IP address – 11.1.1.2/24, name – DMZ and security level – 50 on Gi0/1, IP address – 101.1.1.2/24, name-OUTSIDE and security level – 0 on Gi0/2) as shown in the above figure.
In this task, we will enable Dynamic NAT for the traffic generating from INSIDE to OUTSIDE and for the traffic going from DMZ to OUTSIDE. Configuring IP addresses on all routers and ASA. Configure IP address on Router1.
Router1(config)#int fa0/0
Router1(config-if)#ip address 10.1.1.1 255.255.255.0
Router1(config-if)#no shut
Configuring IP address on Router2.
Router2(config)#int fa0/0
Router2(config-if)#ip address 11.1.1.1 255.255.255.0
Router2(config-if)#no shut
Configuring IP address on Router3.
Router3(config)#int fa0/0
Router3(config-if)#ip address 101.1.1.1 255.255.255.0
Router3(config-if)#no shut
Configuring IP address, name, and security level on the interface of ASA.
asa(config)#int Gi0/0
asa(config-if)#no shut
asa(config-if)#ip address 10.1.1.2 255.255.255.0
asa(config-if)#nameif INSIDE
asa(config-if)#security level 100
asa(config-if)#exit
asa(config)#int Gi0/1
asa(config-if)#no shut
asa(config-if)#ip address 11.1.1.2 255.255.255.0
asa(config-if)#nameif DMZ
asa(config-if)#security level 50
asa(config-if)#exit
asa(config)#int Gi0/2
asa(config-if)#no shut
asa(config-if)#ip address 101.1.1.2 255.255.255.0
asa(config-if)#nameif OUTSIDE
asa(config-if)#security level 0
Now giving static routes to the routers. Configuring static route to Router1.
Router1(config)#ip route 0.0.0.0 0.0.0.0 10.1.1.2
Configuring static route to Router2.
Router2(config)#ip route 0.0.0.0 0.0.0.0 11.1.1.2
Configuring static route to Router3.
Router3(config)#ip route 0.0.0.0 0.0.0.0 101.1.1.2
Now, at last, configuring a static route to ASA.
asa(config)#route INSIDE 10.1.1.0 255.255.255.0 10.1.1.1
asa(config)#route OUTSIDE 101.1.1.0 255.255.255.0 101.1.1.1
asa(config)#route DMZ 11.1.1.0 255.255.255.0 10.1.1.1
Now, for ICMP, either we have to inspect or we have to use ACL to allow the ICMP echo reply from the lower security level to higher security level (This is to be done because, by default, no traffic is allowed from lower security level to higher security level).
Configuring access-list:
asa(config)#access-list traffic_out permit icmp any any
asa(config)#access-list traffic_dmz permit icmp any any
Here, two access-list has been made:
First, the access-list name is traffic_out which will allow ICMP traffic from OUTSIDE to INSIDE (having an IP address any mask). The second access list has been made named traffic_dmz which will allow ICMP traffic from OUTSIDE to DMZ (having an IP address any mask).
First, the access-list name is traffic_out which will allow ICMP traffic from OUTSIDE to INSIDE (having an IP address any mask).
The second access list has been made named traffic_dmz which will allow ICMP traffic from OUTSIDE to DMZ (having an IP address any mask).
Now, we have to apply this access list to the ASA interfaces:
asa(config)#access-group traffic_out in interface OUTSIDE
asa(config)#access-group traffic_dmz in interface DMZ
The first statement states that the access-list traffic_out is applied in the inwards direction to the OUTSIDE interface The second statement states that the access-list traffic_dmz is applied in the inwards direction to the DMZ interface. Now, INSIDE devices will be able to ping OUTSIDE and DMZ devices. Now, the task is to enable Dynamic NAT on ASA whenever the whole subnet (10.1.1.0/24) traffic goes out from INSIDE to OUTSIDE and traffic of network (11.1.1.0/24) from DMZ to OUTSIDE.
asa(config)#object network inside_nat
asa(config-network-object)#subnet 10.1.1.0 255.255.255.0
asa(config-network-object)#exit
First, we have specified that which subnet should get translated.
asa(config)#object network NAT_pool
asa(config-network-object)#range 110.1.1.1 110.1.1.4
asa(config-network-object)#exit
Now, the NAT pool has been made which contains the public IP address (into which private IP addresses get translated). Now, the direction of NAT translation will be specified.
asa(config)#nat (INSIDE, OUTSIDE) source dynamic inside_nat NAT_pool
Now, applying NAT for traffic going out from DMZ to OUTSIDE.
asa(config)#object network dmz_nat
asa(config-network-object)#subnet 11.1.1.0 255.255.255.0
asa(config-network-object)#exit
Now, Creating NAT pool for this traffic.
asa(config)#object network dmz_nat_pool
asa(config-network-object)#range 120.1.1.1 120.1.1.4
asa(config-network-object)#exit
The pool dmz_nat_pool contains 4 public IP addresses ranging from (120.1.1.1 to 120.1.1.4). Now, the direction for NAT translation is specified.
asa(config)#nat (DMZ, OUTSIDE) source dynamic dmz_nat dmz_nat_pool
The above command specifies that the subnet in dmz_nat should get translated into one of the IP addresses of the pool dmz_nat_pool using dynamic NAT.
vicky978654
vaibhavsinghtanwar
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Secure Socket Layer (SSL)
GSM in Wireless Communication
Wireless Application Protocol
TCP 3-Way Handshake Process
Mobile Internet Protocol (or Mobile IP)
UDP Server-Client implementation in C
User Datagram Protocol (UDP)
Introduction of Mobile Ad hoc Network (MANET)
Advanced Encryption Standard (AES)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 316,
"s": 28,
"text": "Prerequisite – Adaptive security appliance (ASA), Network address translation (NAT), Static NAT (on ASA) Network Address Translation is used for the translation of private IP addresses into public IP addresses while accessing the internet.NAT generally operates on a router or firewall. "
},
{
"code": null,
"e": 535,
"s": 316,
"text": "Dynamic NAT – In this type of NAT, multiple private IP addresses are mapped to a pool of public IP addresses. It is used when we know the number of fixed users who want to access the Internet at a given point in time. "
},
{
"code": null,
"e": 909,
"s": 535,
"text": "Example: If we have 4 public IP address in a pool then at a time, only 4 users private IP address gets translated into public address. The private IP who have a request for the translation first will get translated first (like First Come First Serve). If all the IP addresses in the pool are busy and a request for translation is received then the packets will be dropped. "
},
{
"code": null,
"e": 973,
"s": 909,
"text": "Procedure (on ASA) – The Procedure is the same as static NAT: "
},
{
"code": null,
"e": 1129,
"s": 973,
"text": "Step-1: Configure the access list – Build the access list stating the permit condition i.e who should be permitted and what protocol should be permitted. "
},
{
"code": null,
"e": 1313,
"s": 1129,
"text": "Step-2: Apply the access-list to an interface – The access-group command will be used to state the direction (out or in) in which the action (specified above) should be taken place. "
},
{
"code": null,
"e": 1599,
"s": 1313,
"text": "Step-3: Create network object – This will state the host or subnet on which Dynamic NAT will be applied. Note that here 2 objects are created. One will specify the hosts or subnet (private IP address) on which NAT should be applied and the other will the pool of public IP addresses. "
},
{
"code": null,
"e": 1780,
"s": 1599,
"text": "Note that here 2 objects are created. One will specify the hosts or subnet (private IP address) on which NAT should be applied and the other will the pool of public IP addresses. "
},
{
"code": null,
"e": 1977,
"s": 1780,
"text": "Step-4: Create Dynamic NAT statement – This step will specify the direction in which NAT should take place and on what IP address (Public IP address) the private IP address should be translated. "
},
{
"code": null,
"e": 2283,
"s": 1977,
"text": "For example NAT (DMZ, OUTSIDE), Dynamic Private_hosts Public_pool: This states that the Dynamic NAT operation will take place when the traffic is going from DMZ to OUTSIDE and will translate the IP address (specified in the network object Private_hosts) to the available IP address of Pool (Public_pool). "
},
{
"code": null,
"e": 2294,
"s": 2283,
"text": "Example – "
},
{
"code": null,
"e": 2696,
"s": 2296,
"text": "Three routers namely Router1 (IP address – 10.1.1.1/24), Router2 (IP address – 11.1.1.1/24) and Router3 (IP address – 101.1.1.1) are connected to ASA (IP address- 10.1.1.2/24, name – INSIDE and security level – 100 on Gi0/0, IP address – 11.1.1.2/24, name – DMZ and security level – 50 on Gi0/1, IP address – 101.1.1.2/24, name-OUTSIDE and security level – 0 on Gi0/2) as shown in the above figure. "
},
{
"code": null,
"e": 2918,
"s": 2696,
"text": "In this task, we will enable Dynamic NAT for the traffic generating from INSIDE to OUTSIDE and for the traffic going from DMZ to OUTSIDE. Configuring IP addresses on all routers and ASA. Configure IP address on Router1. "
},
{
"code": null,
"e": 3025,
"s": 2918,
"text": "Router1(config)#int fa0/0\nRouter1(config-if)#ip address 10.1.1.1 255.255.255.0\nRouter1(config-if)#no shut "
},
{
"code": null,
"e": 3062,
"s": 3025,
"text": "Configuring IP address on Router2. "
},
{
"code": null,
"e": 3169,
"s": 3062,
"text": "Router2(config)#int fa0/0\nRouter2(config-if)#ip address 11.1.1.1 255.255.255.0\nRouter2(config-if)#no shut "
},
{
"code": null,
"e": 3206,
"s": 3169,
"text": "Configuring IP address on Router3. "
},
{
"code": null,
"e": 3314,
"s": 3206,
"text": "Router3(config)#int fa0/0\nRouter3(config-if)#ip address 101.1.1.1 255.255.255.0\nRouter3(config-if)#no shut "
},
{
"code": null,
"e": 3390,
"s": 3314,
"text": "Configuring IP address, name, and security level on the interface of ASA. "
},
{
"code": null,
"e": 3898,
"s": 3390,
"text": "asa(config)#int Gi0/0\nasa(config-if)#no shut\nasa(config-if)#ip address 10.1.1.2 255.255.255.0\nasa(config-if)#nameif INSIDE \nasa(config-if)#security level 100\nasa(config-if)#exit\nasa(config)#int Gi0/1\nasa(config-if)#no shut\nasa(config-if)#ip address 11.1.1.2 255.255.255.0\nasa(config-if)#nameif DMZ\nasa(config-if)#security level 50\nasa(config-if)#exit\nasa(config)#int Gi0/2\nasa(config-if)#no shut\nasa(config-if)#ip address 101.1.1.2 255.255.255.0\nasa(config-if)#nameif OUTSIDE\nasa(config-if)#security level 0"
},
{
"code": null,
"e": 3978,
"s": 3898,
"text": "Now giving static routes to the routers. Configuring static route to Router1. "
},
{
"code": null,
"e": 4029,
"s": 3978,
"text": "Router1(config)#ip route 0.0.0.0 0.0.0.0 10.1.1.2 "
},
{
"code": null,
"e": 4068,
"s": 4029,
"text": "Configuring static route to Router2. "
},
{
"code": null,
"e": 4119,
"s": 4068,
"text": "Router2(config)#ip route 0.0.0.0 0.0.0.0 11.1.1.2 "
},
{
"code": null,
"e": 4158,
"s": 4119,
"text": "Configuring static route to Router3. "
},
{
"code": null,
"e": 4210,
"s": 4158,
"text": "Router3(config)#ip route 0.0.0.0 0.0.0.0 101.1.1.2 "
},
{
"code": null,
"e": 4261,
"s": 4210,
"text": "Now, at last, configuring a static route to ASA. "
},
{
"code": null,
"e": 4432,
"s": 4261,
"text": "asa(config)#route INSIDE 10.1.1.0 255.255.255.0 10.1.1.1\nasa(config)#route OUTSIDE 101.1.1.0 255.255.255.0 101.1.1.1\nasa(config)#route DMZ 11.1.1.0 255.255.255.0 10.1.1.1"
},
{
"code": null,
"e": 4696,
"s": 4432,
"text": "Now, for ICMP, either we have to inspect or we have to use ACL to allow the ICMP echo reply from the lower security level to higher security level (This is to be done because, by default, no traffic is allowed from lower security level to higher security level). "
},
{
"code": null,
"e": 4723,
"s": 4696,
"text": "Configuring access-list: "
},
{
"code": null,
"e": 4837,
"s": 4723,
"text": "asa(config)#access-list traffic_out permit icmp any any \nasa(config)#access-list traffic_dmz permit icmp any any "
},
{
"code": null,
"e": 4876,
"s": 4837,
"text": "Here, two access-list has been made: "
},
{
"code": null,
"e": 5146,
"s": 4876,
"text": "First, the access-list name is traffic_out which will allow ICMP traffic from OUTSIDE to INSIDE (having an IP address any mask). The second access list has been made named traffic_dmz which will allow ICMP traffic from OUTSIDE to DMZ (having an IP address any mask). "
},
{
"code": null,
"e": 5277,
"s": 5146,
"text": "First, the access-list name is traffic_out which will allow ICMP traffic from OUTSIDE to INSIDE (having an IP address any mask). "
},
{
"code": null,
"e": 5417,
"s": 5277,
"text": "The second access list has been made named traffic_dmz which will allow ICMP traffic from OUTSIDE to DMZ (having an IP address any mask). "
},
{
"code": null,
"e": 5481,
"s": 5417,
"text": "Now, we have to apply this access list to the ASA interfaces: "
},
{
"code": null,
"e": 5594,
"s": 5481,
"text": "asa(config)#access-group traffic_out in interface OUTSIDE \nasa(config)#access-group traffic_dmz in interface DMZ"
},
{
"code": null,
"e": 6086,
"s": 5594,
"text": "The first statement states that the access-list traffic_out is applied in the inwards direction to the OUTSIDE interface The second statement states that the access-list traffic_dmz is applied in the inwards direction to the DMZ interface. Now, INSIDE devices will be able to ping OUTSIDE and DMZ devices. Now, the task is to enable Dynamic NAT on ASA whenever the whole subnet (10.1.1.0/24) traffic goes out from INSIDE to OUTSIDE and traffic of network (11.1.1.0/24) from DMZ to OUTSIDE. "
},
{
"code": null,
"e": 6213,
"s": 6086,
"text": "asa(config)#object network inside_nat\nasa(config-network-object)#subnet 10.1.1.0 255.255.255.0\nasa(config-network-object)#exit"
},
{
"code": null,
"e": 6281,
"s": 6213,
"text": "First, we have specified that which subnet should get translated. "
},
{
"code": null,
"e": 6402,
"s": 6281,
"text": "asa(config)#object network NAT_pool\nasa(config-network-object)#range 110.1.1.1 110.1.1.4\nasa(config-network-object)#exit"
},
{
"code": null,
"e": 6580,
"s": 6402,
"text": "Now, the NAT pool has been made which contains the public IP address (into which private IP addresses get translated). Now, the direction of NAT translation will be specified. "
},
{
"code": null,
"e": 6649,
"s": 6580,
"text": "asa(config)#nat (INSIDE, OUTSIDE) source dynamic inside_nat NAT_pool"
},
{
"code": null,
"e": 6712,
"s": 6649,
"text": "Now, applying NAT for traffic going out from DMZ to OUTSIDE. "
},
{
"code": null,
"e": 6836,
"s": 6712,
"text": "asa(config)#object network dmz_nat\nasa(config-network-object)#subnet 11.1.1.0 255.255.255.0\nasa(config-network-object)#exit"
},
{
"code": null,
"e": 6879,
"s": 6836,
"text": "Now, Creating NAT pool for this traffic. "
},
{
"code": null,
"e": 7004,
"s": 6879,
"text": "asa(config)#object network dmz_nat_pool\nasa(config-network-object)#range 120.1.1.1 120.1.1.4\nasa(config-network-object)#exit"
},
{
"code": null,
"e": 7151,
"s": 7004,
"text": "The pool dmz_nat_pool contains 4 public IP addresses ranging from (120.1.1.1 to 120.1.1.4). Now, the direction for NAT translation is specified. "
},
{
"code": null,
"e": 7219,
"s": 7151,
"text": "asa(config)#nat (DMZ, OUTSIDE) source dynamic dmz_nat dmz_nat_pool "
},
{
"code": null,
"e": 7370,
"s": 7219,
"text": "The above command specifies that the subnet in dmz_nat should get translated into one of the IP addresses of the pool dmz_nat_pool using dynamic NAT. "
},
{
"code": null,
"e": 7382,
"s": 7370,
"text": "vicky978654"
},
{
"code": null,
"e": 7401,
"s": 7382,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 7419,
"s": 7401,
"text": "Computer Networks"
},
{
"code": null,
"e": 7437,
"s": 7419,
"text": "Computer Networks"
},
{
"code": null,
"e": 7535,
"s": 7437,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7569,
"s": 7535,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 7595,
"s": 7569,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 7625,
"s": 7595,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 7655,
"s": 7625,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 7683,
"s": 7655,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 7723,
"s": 7683,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 7761,
"s": 7723,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 7790,
"s": 7761,
"text": "User Datagram Protocol (UDP)"
},
{
"code": null,
"e": 7836,
"s": 7790,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
}
] |
Bulma | Dropdown
|
10 Aug, 2021
Bulma is a free and open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design.
The dropdown component is a container for a dropdown button and a dropdown menu. Using dropdown and its subclasses, an interactive dropdown menu can be implemented. The dropdown component includes several other components that can be added to design the content. These components are listed below:
dropdown-trigger: It is the container for the dropdown button.
dropdown-menu: It is the container for the toggable menu. It is hidden by default. dropdown-content: It is the dropdown box. It has the white background with shadow. dropdown-item: It represents each item of the dropdown.dropdown-divider: It is the horizontal line separator between the two items.
dropdown-content: It is the dropdown box. It has the white background with shadow. dropdown-item: It represents each item of the dropdown.dropdown-divider: It is the horizontal line separator between the two items.
dropdown-item: It represents each item of the dropdown.
dropdown-divider: It is the horizontal line separator between the two items.
Example 1: This example shows the creation of a simple dropdown using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Dropdown</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom css --> <style> div.columns { margin-top: 80px; } </style></head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Todos</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Take pictures of beautiful flowers </a> <a href="#" class="dropdown-item"> Ride to a horse and write your experience </a> <a href="#" class="dropdown-item"> Go for a trip with bike </a> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Buy a sumsung headset </a> <a href="#" class="dropdown-item"> Listen music for one hour </a> <a href="#" class="dropdown-item"> Go for a morning walk </a> </div> </div> </div> </div> </div> </div> <script> const dropdown = document.querySelector('.dropdown'); const active = document.querySelector('.is-active') document.body.addEventListener('click', function () { if (active) { dropdown.classList.remove('is-active') } }) dropdown.addEventListener('click', function (event) { event.stopPropagation(); this.classList.toggle('is-active'); }); </script></body></html>
Output:
Example 2: This example shows the creation of a hoverable dropdown using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Dropdown</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome Library --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="dropdown is-hoverable"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Todos</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Take pictures of beautiful flowers </a> <a href="#" class="dropdown-item"> Ride to a horse and write your experience </a> <a href="#" class="dropdown-item"> Go for a trip with bike </a> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Buy a sumsung headset </a> <a href="#" class="dropdown-item"> Listen music for one hour </a> <a href="#" class="dropdown-item"> Go for a morning walk </a> </div> </div> </div> </div> </div> </div></body></html>
Output:
Example 3: This example shows the creation of different alignment dropdowns using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Dropdown</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome Library --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="dropdown is-hoverable"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Left Aligned Todos</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Take pictures of beautiful flowers </a> <a href="#" class="dropdown-item"> Ride to a horse and write your experience </a> <a href="#" class="dropdown-item"> Go for a trip with bike </a> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Buy a sumsung headset </a> <a href="#" class="dropdown-item"> Listen music for one hour </a> <a href="#" class="dropdown-item"> Go for a morning walk </a> </div> </div> </div> </div> <div class='column is-5'> <div class="dropdown is-right is-hoverable"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Right Aligned Todos</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Take pictures of beautiful flowers </a> <a href="#" class="dropdown-item"> Ride to a horse and write your experience </a> <a href="#" class="dropdown-item"> Go for a trip with bike </a> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Buy a sumsung headset </a> <a href="#" class="dropdown-item"> Listen music for one hour </a> <a href="#" class="dropdown-item"> Go for a morning walk </a> </div> </div> </div> </div> </div> </div></body></html>
Output:
Example 4: This example shows the creation of a “dropup” using Bulma.
html
<!DOCTYPE html><html> <head> <title>Bulma Dropdown</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome Library --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- Custom CSS --> <style> div.columns { margin-top: 330px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="dropdown is-up is-hoverable"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Left Aligned Todos</span> <span class="icon is-small"> <i class="fas fa-angle-up" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Take pictures of beautiful flowers </a> <a href="#" class="dropdown-item"> Ride to a horse and write your experience </a> <a href="#" class="dropdown-item"> Go for a trip with bike </a> <a href="#" class="dropdown-item"> Design a custom database to store your daily activity </a> <a href="#" class="dropdown-item"> Buy a sumsung headset </a> <a href="#" class="dropdown-item"> Listen music for one hour </a> <a href="#" class="dropdown-item"> Go for a morning walk </a> </div> </div> </div> </div> </div> </div></body></html>
Output:
anikakapoor
Bulma
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 223,
"s": 28,
"text": "Bulma is a free and open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design."
},
{
"code": null,
"e": 521,
"s": 223,
"text": "The dropdown component is a container for a dropdown button and a dropdown menu. Using dropdown and its subclasses, an interactive dropdown menu can be implemented. The dropdown component includes several other components that can be added to design the content. These components are listed below:"
},
{
"code": null,
"e": 584,
"s": 521,
"text": "dropdown-trigger: It is the container for the dropdown button."
},
{
"code": null,
"e": 882,
"s": 584,
"text": "dropdown-menu: It is the container for the toggable menu. It is hidden by default. dropdown-content: It is the dropdown box. It has the white background with shadow. dropdown-item: It represents each item of the dropdown.dropdown-divider: It is the horizontal line separator between the two items."
},
{
"code": null,
"e": 1097,
"s": 882,
"text": "dropdown-content: It is the dropdown box. It has the white background with shadow. dropdown-item: It represents each item of the dropdown.dropdown-divider: It is the horizontal line separator between the two items."
},
{
"code": null,
"e": 1153,
"s": 1097,
"text": "dropdown-item: It represents each item of the dropdown."
},
{
"code": null,
"e": 1230,
"s": 1153,
"text": "dropdown-divider: It is the horizontal line separator between the two items."
},
{
"code": null,
"e": 1307,
"s": 1230,
"text": "Example 1: This example shows the creation of a simple dropdown using Bulma."
},
{
"code": null,
"e": 1312,
"s": 1307,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Dropdown</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- Custom css --> <style> div.columns { margin-top: 80px; } </style></head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"dropdown is-active\"> <div class=\"dropdown-trigger\"> <button class=\"button\" aria-haspopup=\"true\" aria-controls=\"dropdown-menu\"> <span>Todos</span> <span class=\"icon is-small\"> <i class=\"fas fa-angle-down\" aria-hidden=\"true\"></i> </span> </button> </div> <div class=\"dropdown-menu\" id=\"dropdown-menu\" role=\"menu\"> <div class=\"dropdown-content\"> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Take pictures of beautiful flowers </a> <a href=\"#\" class=\"dropdown-item\"> Ride to a horse and write your experience </a> <a href=\"#\" class=\"dropdown-item\"> Go for a trip with bike </a> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Buy a sumsung headset </a> <a href=\"#\" class=\"dropdown-item\"> Listen music for one hour </a> <a href=\"#\" class=\"dropdown-item\"> Go for a morning walk </a> </div> </div> </div> </div> </div> </div> <script> const dropdown = document.querySelector('.dropdown'); const active = document.querySelector('.is-active') document.body.addEventListener('click', function () { if (active) { dropdown.classList.remove('is-active') } }) dropdown.addEventListener('click', function (event) { event.stopPropagation(); this.classList.toggle('is-active'); }); </script></body></html>",
"e": 3903,
"s": 1312,
"text": null
},
{
"code": null,
"e": 3914,
"s": 3903,
"text": " Output: "
},
{
"code": null,
"e": 3995,
"s": 3914,
"text": "Example 2: This example shows the creation of a hoverable dropdown using Bulma. "
},
{
"code": null,
"e": 4000,
"s": 3995,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Dropdown</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome Library --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"dropdown is-hoverable\"> <div class=\"dropdown-trigger\"> <button class=\"button\" aria-haspopup=\"true\" aria-controls=\"dropdown-menu\"> <span>Todos</span> <span class=\"icon is-small\"> <i class=\"fas fa-angle-down\" aria-hidden=\"true\"></i> </span> </button> </div> <div class=\"dropdown-menu\" id=\"dropdown-menu\" role=\"menu\"> <div class=\"dropdown-content\"> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Take pictures of beautiful flowers </a> <a href=\"#\" class=\"dropdown-item\"> Ride to a horse and write your experience </a> <a href=\"#\" class=\"dropdown-item\"> Go for a trip with bike </a> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Buy a sumsung headset </a> <a href=\"#\" class=\"dropdown-item\"> Listen music for one hour </a> <a href=\"#\" class=\"dropdown-item\"> Go for a morning walk </a> </div> </div> </div> </div> </div> </div></body></html>",
"e": 6190,
"s": 4000,
"text": null
},
{
"code": null,
"e": 6201,
"s": 6190,
"text": " Output: "
},
{
"code": null,
"e": 6291,
"s": 6201,
"text": "Example 3: This example shows the creation of different alignment dropdowns using Bulma. "
},
{
"code": null,
"e": 6296,
"s": 6291,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Dropdown</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome Library --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- Custom CSS --> <style> div.columns { margin-top: 80px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"dropdown is-hoverable\"> <div class=\"dropdown-trigger\"> <button class=\"button\" aria-haspopup=\"true\" aria-controls=\"dropdown-menu\"> <span>Left Aligned Todos</span> <span class=\"icon is-small\"> <i class=\"fas fa-angle-down\" aria-hidden=\"true\"></i> </span> </button> </div> <div class=\"dropdown-menu\" id=\"dropdown-menu\" role=\"menu\"> <div class=\"dropdown-content\"> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Take pictures of beautiful flowers </a> <a href=\"#\" class=\"dropdown-item\"> Ride to a horse and write your experience </a> <a href=\"#\" class=\"dropdown-item\"> Go for a trip with bike </a> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Buy a sumsung headset </a> <a href=\"#\" class=\"dropdown-item\"> Listen music for one hour </a> <a href=\"#\" class=\"dropdown-item\"> Go for a morning walk </a> </div> </div> </div> </div> <div class='column is-5'> <div class=\"dropdown is-right is-hoverable\"> <div class=\"dropdown-trigger\"> <button class=\"button\" aria-haspopup=\"true\" aria-controls=\"dropdown-menu\"> <span>Right Aligned Todos</span> <span class=\"icon is-small\"> <i class=\"fas fa-angle-down\" aria-hidden=\"true\"></i> </span> </button> </div> <div class=\"dropdown-menu\" id=\"dropdown-menu\" role=\"menu\"> <div class=\"dropdown-content\"> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Take pictures of beautiful flowers </a> <a href=\"#\" class=\"dropdown-item\"> Ride to a horse and write your experience </a> <a href=\"#\" class=\"dropdown-item\"> Go for a trip with bike </a> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Buy a sumsung headset </a> <a href=\"#\" class=\"dropdown-item\"> Listen music for one hour </a> <a href=\"#\" class=\"dropdown-item\"> Go for a morning walk </a> </div> </div> </div> </div> </div> </div></body></html>",
"e": 10172,
"s": 6296,
"text": null
},
{
"code": null,
"e": 10183,
"s": 10172,
"text": " Output: "
},
{
"code": null,
"e": 10254,
"s": 10183,
"text": "Example 4: This example shows the creation of a “dropup” using Bulma. "
},
{
"code": null,
"e": 10259,
"s": 10254,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bulma Dropdown</title> <!-- Include Bulma CSS --> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- FontAwesome Library --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <!-- Custom CSS --> <style> div.columns { margin-top: 330px; } </style></head> <body> <div class='container has-text-centered'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"dropdown is-up is-hoverable\"> <div class=\"dropdown-trigger\"> <button class=\"button\" aria-haspopup=\"true\" aria-controls=\"dropdown-menu\"> <span>Left Aligned Todos</span> <span class=\"icon is-small\"> <i class=\"fas fa-angle-up\" aria-hidden=\"true\"></i> </span> </button> </div> <div class=\"dropdown-menu\" id=\"dropdown-menu\" role=\"menu\"> <div class=\"dropdown-content\"> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Take pictures of beautiful flowers </a> <a href=\"#\" class=\"dropdown-item\"> Ride to a horse and write your experience </a> <a href=\"#\" class=\"dropdown-item\"> Go for a trip with bike </a> <a href=\"#\" class=\"dropdown-item\"> Design a custom database to store your daily activity </a> <a href=\"#\" class=\"dropdown-item\"> Buy a sumsung headset </a> <a href=\"#\" class=\"dropdown-item\"> Listen music for one hour </a> <a href=\"#\" class=\"dropdown-item\"> Go for a morning walk </a> </div> </div> </div> </div> </div> </div></body></html>",
"e": 12467,
"s": 10259,
"text": null
},
{
"code": null,
"e": 12478,
"s": 12467,
"text": " Output: "
},
{
"code": null,
"e": 12492,
"s": 12480,
"text": "anikakapoor"
},
{
"code": null,
"e": 12498,
"s": 12492,
"text": "Bulma"
},
{
"code": null,
"e": 12502,
"s": 12498,
"text": "CSS"
},
{
"code": null,
"e": 12507,
"s": 12502,
"text": "HTML"
},
{
"code": null,
"e": 12524,
"s": 12507,
"text": "Web Technologies"
},
{
"code": null,
"e": 12529,
"s": 12524,
"text": "HTML"
}
] |
TheSpeedX / TBomb – Call and SMS Bomber for Kali Linux
|
17 Jun, 2021
TBomb is a free and open-source tool available on GitHub which is used to perform call and SMS bombing on the target phone number. This is the best tool for performing pranks on someone. This tool is written in python, so you must have python installed in your kali linux operating system.
This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. This tool doesn’t take your phone number, you only have to enter the target phone number and the tool will do the rest of the work. You must ensure that you always install the latest version of TBomb from GitHub in order to not get stuck with the working of the tool.
Step 1: Open your kali linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command.
git clone https://github.com/TheSpeedX/TBomb.git
cd TBomb
Step 2: Now you are in the TBomb directory, use the following command to run the tool.
bash tBomb.sh
The tool has been installed successfully and running successfully. Now we will have an example of using the tool.
Example 1: Use the TBomb tool to perform SMS Bombing on a phone number.
For SMS bombing press 1
1
after that give all the details to the tool such as country code, phone number, number of SMS you want to send etc.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
TCP Server-Client implementation in C
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 343,
"s": 52,
"text": "TBomb is a free and open-source tool available on GitHub which is used to perform call and SMS bombing on the target phone number. This is the best tool for performing pranks on someone. This tool is written in python, so you must have python installed in your kali linux operating system. "
},
{
"code": null,
"e": 736,
"s": 343,
"text": "This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. This tool doesn’t take your phone number, you only have to enter the target phone number and the tool will do the rest of the work. You must ensure that you always install the latest version of TBomb from GitHub in order to not get stuck with the working of the tool. "
},
{
"code": null,
"e": 906,
"s": 736,
"text": "Step 1: Open your kali linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command."
},
{
"code": null,
"e": 964,
"s": 906,
"text": "git clone https://github.com/TheSpeedX/TBomb.git\ncd TBomb"
},
{
"code": null,
"e": 1051,
"s": 964,
"text": "Step 2: Now you are in the TBomb directory, use the following command to run the tool."
},
{
"code": null,
"e": 1065,
"s": 1051,
"text": "bash tBomb.sh"
},
{
"code": null,
"e": 1179,
"s": 1065,
"text": "The tool has been installed successfully and running successfully. Now we will have an example of using the tool."
},
{
"code": null,
"e": 1251,
"s": 1179,
"text": "Example 1: Use the TBomb tool to perform SMS Bombing on a phone number."
},
{
"code": null,
"e": 1275,
"s": 1251,
"text": "For SMS bombing press 1"
},
{
"code": null,
"e": 1277,
"s": 1275,
"text": "1"
},
{
"code": null,
"e": 1393,
"s": 1277,
"text": "after that give all the details to the tool such as country code, phone number, number of SMS you want to send etc."
},
{
"code": null,
"e": 1404,
"s": 1393,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1416,
"s": 1404,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1427,
"s": 1416,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1525,
"s": 1427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1560,
"s": 1525,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 1595,
"s": 1560,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 1631,
"s": 1595,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 1672,
"s": 1631,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 1710,
"s": 1672,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 1748,
"s": 1710,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 1784,
"s": 1748,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 1822,
"s": 1784,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 1848,
"s": 1822,
"text": "Docker - COPY Instruction"
}
] |
Construct Full Binary Tree from given preorder and postorder traversals
|
17 Jun, 2022
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree.A Full Binary Tree is a binary tree where every node has either 0 or 2 children
Following are examples of Full Trees.
1
/ \
2 3
/ \ / \
4 5 6 7
1
/ \
2 3
/ \
4 5
/ \
6 7
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
It is not possible to construct a general Binary Tree from preorder and postorder traversals (See this). But if know that the Binary Tree is Full, we can construct the tree without ambiguity. Let us understand this with the help of following example.
Let us consider the two given arrays as pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7} and post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1}; In pre[], the leftmost element is root of tree. Since the tree is full and array size is more than 1. The value next to 1 in pre[], must be left child of root. So we know 1 is root and 2 is left child. How to find the all nodes in left subtree? We know 2 is root of all nodes in left subtree. All nodes before 2 in post[] must be in left subtree. Now we know 1 is root, elements {8, 9, 4, 5, 2} are in left subtree, and the elements {6, 7, 3} are in right subtree.
1
/ \
/ \
{8, 9, 4, 5, 2} {6, 7, 3}
We recursively follow the above approach and get the following tree.
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
C++
C
Java
Python3
C#
Javascript
/* program for construction of full binary tree */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node *left; node *right;}; // A utility function to create a nodenode* newNode (int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct Full from pre[] and post[].// preIndex is used to keep track of index in pre[].// l is low index and h is high index for the current subarray in post[]node* constructTreeUtil (int pre[], int post[], int* preIndex, int l, int h, int size){ // Base case if (*preIndex >= size || l > h) return NULL; // The first node in preorder traversal is root. So take the node at // preIndex from preorder and make it root, and increment preIndex node* root = newNode ( pre[*preIndex] ); ++*preIndex; // If the current subarray has only one element, no need to recur if (l == h) return root; // Search the next element of pre[] in post[] int i; for (i = l; i <= h; ++i) if (pre[*preIndex] == post[i]) break; // Use the index of element found in postorder to divide // postorder array in two parts. Left subtree and right subtree if (i <= h) { root->left = constructTreeUtil (pre, post, preIndex, l, i, size); root->right = constructTreeUtil (pre, post, preIndex, i + 1, h-1, size); } return root;} // The main function to construct Full Binary Tree from given preorder and// postorder traversals. This function mainly uses constructTreeUtil()node *constructTree (int pre[], int post[], int size){ int preIndex = 0; return constructTreeUtil (pre, post, &preIndex, 0, size - 1, size);} // A utility function to print inorder traversal of a Binary Treevoid printInorder (node* node){ if (node == NULL) return; printInorder(node->left); cout<<node->data<<" "; printInorder(node->right);} // Driver program to test above functionsint main (){ int pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7}; int post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1}; int size = sizeof( pre ) / sizeof( pre[0] ); node *root = constructTree(pre, post, size); cout<<"Inorder traversal of the constructed tree: \n"; printInorder(root); return 0;} //This code is contributed by rathbhupendra
/* program for construction of full binary tree */#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left; struct node *right;}; // A utility function to create a nodestruct node* newNode (int data){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct Full from pre[] and post[].// preIndex is used to keep track of index in pre[].// l is low index and h is high index for the current subarray in post[]struct node* constructTreeUtil (int pre[], int post[], int* preIndex, int l, int h, int size){ // Base case if (*preIndex >= size || l > h) return NULL; // The first node in preorder traversal is root. So take the node at // preIndex from preorder and make it root, and increment preIndex struct node* root = newNode ( pre[*preIndex] ); ++*preIndex; // If the current subarray has only one element, no need to recur if (l == h) return root; // Search the next element of pre[] in post[] int i; for (i = l; i <= h; ++i) if (pre[*preIndex] == post[i]) break; // Use the index of element found in postorder to divide // postorder array in two parts. Left subtree and right subtree if (i <= h) { root->left = constructTreeUtil (pre, post, preIndex, l, i, size); root->right = constructTreeUtil (pre, post, preIndex, i + 1, h-1, size); } return root;} // The main function to construct Full Binary Tree from given preorder and// postorder traversals. This function mainly uses constructTreeUtil()struct node *constructTree (int pre[], int post[], int size){ int preIndex = 0; return constructTreeUtil (pre, post, &preIndex, 0, size - 1, size);} // A utility function to print inorder traversal of a Binary Treevoid printInorder (struct node* node){ if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right);} // Driver program to test above functionsint main (){ int pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7}; int post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1}; int size = sizeof( pre ) / sizeof( pre[0] ); struct node *root = constructTree(pre, post, size); printf("Inorder traversal of the constructed tree: \n"); printInorder(root); return 0;}
// Java program for construction// of full binary treepublic class fullbinarytreepostpre{ // variable to hold index in pre[] array static int preindex; static class node { int data; node left, right; public node(int data) { this.data = data; } } // A recursive function to construct Full // from pre[] and post[]. preIndex is used // to keep track of index in pre[]. l is // low index and h is high index for the // current subarray in post[] static node constructTreeUtil(int pre[], int post[], int l, int h, int size) { // Base case if (preindex >= size || l > h) return null; // The first node in preorder traversal is // root. So take the node at preIndex from // preorder and make it root, and increment // preIndex node root = new node(pre[preindex]); preindex++; // If the current subarray has only one // element, no need to recur or // preIndex > size after incrementing if (l == h || preindex >= size) return root; int i; // Search the next element of pre[] in post[] for (i = l; i <= h; i++) { if (post[i] == pre[preindex]) break; } // Use the index of element found in // postorder to divide postorder array // in two parts. Left subtree and right subtree if (i <= h) { root.left = constructTreeUtil(pre, post, l, i, size); root.right = constructTreeUtil(pre, post, i + 1, h-1, size); } return root; } // The main function to construct Full // Binary Tree from given preorder and // postorder traversals. This function // mainly uses constructTreeUtil() static node constructTree(int pre[], int post[], int size) { preindex = 0; return constructTreeUtil(pre, post, 0, size - 1, size); } static void printInorder(node root) { if (root == null) return; printInorder(root.left); System.out.print(root.data + " "); printInorder(root.right); } public static void main(String[] args) { int pre[] = { 1, 2, 4, 8, 9, 5, 3, 6, 7 }; int post[] = { 8, 9, 4, 5, 2, 6, 7, 3, 1 }; int size = pre.length; node root = constructTree(pre, post, size); System.out.println("Inorder traversal of the constructed tree:"); printInorder(root); }} // This code is contributed by Rishabh Mahrsee
# Python3 program for construction of# full binary tree # A binary tree node has data, pointer# to left child and a pointer to right childclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # A recursive function to construct# Full from pre[] and post[].# preIndex is used to keep track# of index in pre[]. l is low index# and h is high index for the# current subarray in post[]def constructTreeUtil(pre: list, post: list, l: int, h: int, size: int) -> Node: global preIndex # Base case if (preIndex >= size or l > h): return None # The first node in preorder traversal # is root. So take the node at preIndex # from preorder and make it root, and # increment preIndex root = Node(pre[preIndex]) preIndex += 1 # If the current subarray has only # one element, no need to recur if (l == h or preIndex >= size): return root # Search the next element # of pre[] in post[] i = l while i <= h: if (pre[preIndex] == post[i]): break i += 1 # Use the index of element # found in postorder to divide # postorder array in two parts. # Left subtree and right subtree if (i <= h): root.left = constructTreeUtil(pre, post, l, i, size) root.right = constructTreeUtil(pre, post, i + 1, h-1, size) return root # The main function to construct# Full Binary Tree from given# preorder and postorder traversals.# This function mainly uses constructTreeUtil()def constructTree(pre: list, post: list, size: int) -> Node: global preIndex return constructTreeUtil(pre, post, 0, size - 1, size) # A utility function to print# inorder traversal of a Binary Treedef printInorder(node: Node) -> None: if (node is None): return printInorder(node.left) print(node.data, end = " ") printInorder(node.right) # Driver codeif __name__ == "__main__": pre = [ 1, 2, 4, 8, 9, 5, 3, 6, 7 ] post = [ 8, 9, 4, 5, 2, 6, 7, 3, 1 ] size = len(pre) preIndex = 0 root = constructTree(pre, post, size) print("Inorder traversal of " "the constructed tree: ") printInorder(root) # This code is contributed by sanjeev2552
// C# program for construction// of full binary treeusing System; class GFG{// variable to hold index in pre[] arraypublic static int preindex; public class node{ public int data; public node left, right; public node(int data) { this.data = data; }} // A recursive function to construct Full// from pre[] and post[]. preIndex is used// to keep track of index in pre[]. l is// low index and h is high index for the// current subarray in post[]public static node constructTreeUtil(int[] pre, int[] post, int l, int h, int size){ // Base case if (preindex >= size || l > h) { return null; } // The first node in preorder traversal is // root. So take the node at preIndex from // preorder and make it root, and increment // preIndex node root = new node(pre[preindex]); preindex++; // If the current subarray has only one // element, no need to recur or // preIndex > size after incrementing if (l == h || preindex >= size) { return root; } int i; // Search the next element // of pre[] in post[] for (i = l; i <= h; i++) { if (post[i] == pre[preindex]) { break; } } // Use the index of element found // in postorder to divide postorder // array in two parts. Left subtree // and right subtree if (i <= h) { root.left = constructTreeUtil(pre, post, l, i, size); root.right = constructTreeUtil(pre, post, i + 1, h-1, size); } return root;} // The main function to construct Full// Binary Tree from given preorder and// postorder traversals. This function// mainly uses constructTreeUtil()public static node constructTree(int[] pre, int[] post, int size){ preindex = 0; return constructTreeUtil(pre, post, 0, size - 1, size);} public static void printInorder(node root){ if (root == null) { return; } printInorder(root.left); Console.Write(root.data + " "); printInorder(root.right);} // Driver Codepublic static void Main(string[] args){ int[] pre = new int[] {1, 2, 4, 8, 9, 5, 3, 6, 7}; int[] post = new int[] {8, 9, 4, 5, 2, 6, 7, 3, 1}; int size = pre.Length; node root = constructTree(pre, post, size); Console.WriteLine("Inorder traversal of " + "the constructed tree:"); printInorder(root);}} // This code is contributed by Shrikant13
<script> // Javascript program for construction// of full binary tree // variable to hold index in pre[] arrayvar preindex = 0; class node{ constructor(data) { this.data = data; }} // A recursive function to construct Full// from pre[] and post[]. preIndex is used// to keep track of index in pre[]. l is// low index and h is high index for the// current subarray in post[]function constructTreeUtil(pre, post, l, h, size){ // Base case if (preindex >= size || l > h) { return null; } // The first node in preorder traversal is // root. So take the node at preIndex from // preorder and make it root, and increment // preIndex var root = new node(pre[preindex]); preindex++; // If the current subarray has only one // element, no need to recur or // preIndex > size after incrementing if (l == h || preindex >= size) { return root; } var i; // Search the next element // of pre[] in post[] for (i = l; i <= h; i++) { if (post[i] == pre[preindex]) { break; } } // Use the index of element found // in postorder to divide postorder // array in two parts. Left subtree // and right subtree if (i <= h) { root.left = constructTreeUtil(pre, post, l, i, size); root.right = constructTreeUtil(pre, post, i + 1, h-1, size); } return root;} // The main function to construct Full// Binary Tree from given preorder and// postorder traversals. This function// mainly uses constructTreeUtil()function constructTree(pre, post, size){ preindex = 0; return constructTreeUtil(pre, post, 0, size - 1, size);} function printInorder(root){ if (root == null) { return; } printInorder(root.left); document.write(root.data + " "); printInorder(root.right);} // Driver Codevar pre = [1, 2, 4, 8, 9, 5, 3, 6, 7];var post = [8, 9, 4, 5, 2, 6, 7, 3, 1];var size = pre.length;var root = constructTree(pre, post, size);document.write("Inorder traversal of " + "the constructed tree:<br>");printInorder(root); </script>
Inorder traversal of the constructed tree:
8 4 9 2 5 1 6 3 7
shrikanth13
rathbhupendra
sanjeev2552
rutvik_56
parthagarwal1962000
as5853535
hardikkoriintern
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 247,
"s": 52,
"text": "Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree.A Full Binary Tree is a binary tree where every node has either 0 or 2 children"
},
{
"code": null,
"e": 286,
"s": 247,
"text": "Following are examples of Full Trees. "
},
{
"code": null,
"e": 571,
"s": 286,
"text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n\n\n 1\n / \\\n 2 3\n / \\ \n 4 5\n / \\ \n 6 7\n \n\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\ \n8 9 "
},
{
"code": null,
"e": 822,
"s": 571,
"text": "It is not possible to construct a general Binary Tree from preorder and postorder traversals (See this). But if know that the Binary Tree is Full, we can construct the tree without ambiguity. Let us understand this with the help of following example."
},
{
"code": null,
"e": 1406,
"s": 822,
"text": "Let us consider the two given arrays as pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7} and post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1}; In pre[], the leftmost element is root of tree. Since the tree is full and array size is more than 1. The value next to 1 in pre[], must be left child of root. So we know 1 is root and 2 is left child. How to find the all nodes in left subtree? We know 2 is root of all nodes in left subtree. All nodes before 2 in post[] must be in left subtree. Now we know 1 is root, elements {8, 9, 4, 5, 2} are in left subtree, and the elements {6, 7, 3} are in right subtree. "
},
{
"code": null,
"e": 1507,
"s": 1406,
"text": " 1\n / \\\n / \\\n {8, 9, 4, 5, 2} {6, 7, 3}"
},
{
"code": null,
"e": 1577,
"s": 1507,
"text": "We recursively follow the above approach and get the following tree. "
},
{
"code": null,
"e": 1672,
"s": 1577,
"text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\ \n 8 9 "
},
{
"code": null,
"e": 1676,
"s": 1672,
"text": "C++"
},
{
"code": null,
"e": 1678,
"s": 1676,
"text": "C"
},
{
"code": null,
"e": 1683,
"s": 1678,
"text": "Java"
},
{
"code": null,
"e": 1691,
"s": 1683,
"text": "Python3"
},
{
"code": null,
"e": 1694,
"s": 1691,
"text": "C#"
},
{
"code": null,
"e": 1705,
"s": 1694,
"text": "Javascript"
},
{
"code": "/* program for construction of full binary tree */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node{ public: int data; node *left; node *right;}; // A utility function to create a nodenode* newNode (int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct Full from pre[] and post[].// preIndex is used to keep track of index in pre[].// l is low index and h is high index for the current subarray in post[]node* constructTreeUtil (int pre[], int post[], int* preIndex, int l, int h, int size){ // Base case if (*preIndex >= size || l > h) return NULL; // The first node in preorder traversal is root. So take the node at // preIndex from preorder and make it root, and increment preIndex node* root = newNode ( pre[*preIndex] ); ++*preIndex; // If the current subarray has only one element, no need to recur if (l == h) return root; // Search the next element of pre[] in post[] int i; for (i = l; i <= h; ++i) if (pre[*preIndex] == post[i]) break; // Use the index of element found in postorder to divide // postorder array in two parts. Left subtree and right subtree if (i <= h) { root->left = constructTreeUtil (pre, post, preIndex, l, i, size); root->right = constructTreeUtil (pre, post, preIndex, i + 1, h-1, size); } return root;} // The main function to construct Full Binary Tree from given preorder and// postorder traversals. This function mainly uses constructTreeUtil()node *constructTree (int pre[], int post[], int size){ int preIndex = 0; return constructTreeUtil (pre, post, &preIndex, 0, size - 1, size);} // A utility function to print inorder traversal of a Binary Treevoid printInorder (node* node){ if (node == NULL) return; printInorder(node->left); cout<<node->data<<\" \"; printInorder(node->right);} // Driver program to test above functionsint main (){ int pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7}; int post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1}; int size = sizeof( pre ) / sizeof( pre[0] ); node *root = constructTree(pre, post, size); cout<<\"Inorder traversal of the constructed tree: \\n\"; printInorder(root); return 0;} //This code is contributed by rathbhupendra",
"e": 4267,
"s": 1705,
"text": null
},
{
"code": "/* program for construction of full binary tree */#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left; struct node *right;}; // A utility function to create a nodestruct node* newNode (int data){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; return temp;} // A recursive function to construct Full from pre[] and post[].// preIndex is used to keep track of index in pre[].// l is low index and h is high index for the current subarray in post[]struct node* constructTreeUtil (int pre[], int post[], int* preIndex, int l, int h, int size){ // Base case if (*preIndex >= size || l > h) return NULL; // The first node in preorder traversal is root. So take the node at // preIndex from preorder and make it root, and increment preIndex struct node* root = newNode ( pre[*preIndex] ); ++*preIndex; // If the current subarray has only one element, no need to recur if (l == h) return root; // Search the next element of pre[] in post[] int i; for (i = l; i <= h; ++i) if (pre[*preIndex] == post[i]) break; // Use the index of element found in postorder to divide // postorder array in two parts. Left subtree and right subtree if (i <= h) { root->left = constructTreeUtil (pre, post, preIndex, l, i, size); root->right = constructTreeUtil (pre, post, preIndex, i + 1, h-1, size); } return root;} // The main function to construct Full Binary Tree from given preorder and// postorder traversals. This function mainly uses constructTreeUtil()struct node *constructTree (int pre[], int post[], int size){ int preIndex = 0; return constructTreeUtil (pre, post, &preIndex, 0, size - 1, size);} // A utility function to print inorder traversal of a Binary Treevoid printInorder (struct node* node){ if (node == NULL) return; printInorder(node->left); printf(\"%d \", node->data); printInorder(node->right);} // Driver program to test above functionsint main (){ int pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7}; int post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1}; int size = sizeof( pre ) / sizeof( pre[0] ); struct node *root = constructTree(pre, post, size); printf(\"Inorder traversal of the constructed tree: \\n\"); printInorder(root); return 0;}",
"e": 6855,
"s": 4267,
"text": null
},
{
"code": "// Java program for construction// of full binary treepublic class fullbinarytreepostpre{ // variable to hold index in pre[] array static int preindex; static class node { int data; node left, right; public node(int data) { this.data = data; } } // A recursive function to construct Full // from pre[] and post[]. preIndex is used // to keep track of index in pre[]. l is // low index and h is high index for the // current subarray in post[] static node constructTreeUtil(int pre[], int post[], int l, int h, int size) { // Base case if (preindex >= size || l > h) return null; // The first node in preorder traversal is // root. So take the node at preIndex from // preorder and make it root, and increment // preIndex node root = new node(pre[preindex]); preindex++; // If the current subarray has only one // element, no need to recur or // preIndex > size after incrementing if (l == h || preindex >= size) return root; int i; // Search the next element of pre[] in post[] for (i = l; i <= h; i++) { if (post[i] == pre[preindex]) break; } // Use the index of element found in // postorder to divide postorder array // in two parts. Left subtree and right subtree if (i <= h) { root.left = constructTreeUtil(pre, post, l, i, size); root.right = constructTreeUtil(pre, post, i + 1, h-1, size); } return root; } // The main function to construct Full // Binary Tree from given preorder and // postorder traversals. This function // mainly uses constructTreeUtil() static node constructTree(int pre[], int post[], int size) { preindex = 0; return constructTreeUtil(pre, post, 0, size - 1, size); } static void printInorder(node root) { if (root == null) return; printInorder(root.left); System.out.print(root.data + \" \"); printInorder(root.right); } public static void main(String[] args) { int pre[] = { 1, 2, 4, 8, 9, 5, 3, 6, 7 }; int post[] = { 8, 9, 4, 5, 2, 6, 7, 3, 1 }; int size = pre.length; node root = constructTree(pre, post, size); System.out.println(\"Inorder traversal of the constructed tree:\"); printInorder(root); }} // This code is contributed by Rishabh Mahrsee",
"e": 9465,
"s": 6855,
"text": null
},
{
"code": "# Python3 program for construction of# full binary tree # A binary tree node has data, pointer# to left child and a pointer to right childclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # A recursive function to construct# Full from pre[] and post[].# preIndex is used to keep track# of index in pre[]. l is low index# and h is high index for the# current subarray in post[]def constructTreeUtil(pre: list, post: list, l: int, h: int, size: int) -> Node: global preIndex # Base case if (preIndex >= size or l > h): return None # The first node in preorder traversal # is root. So take the node at preIndex # from preorder and make it root, and # increment preIndex root = Node(pre[preIndex]) preIndex += 1 # If the current subarray has only # one element, no need to recur if (l == h or preIndex >= size): return root # Search the next element # of pre[] in post[] i = l while i <= h: if (pre[preIndex] == post[i]): break i += 1 # Use the index of element # found in postorder to divide # postorder array in two parts. # Left subtree and right subtree if (i <= h): root.left = constructTreeUtil(pre, post, l, i, size) root.right = constructTreeUtil(pre, post, i + 1, h-1, size) return root # The main function to construct# Full Binary Tree from given# preorder and postorder traversals.# This function mainly uses constructTreeUtil()def constructTree(pre: list, post: list, size: int) -> Node: global preIndex return constructTreeUtil(pre, post, 0, size - 1, size) # A utility function to print# inorder traversal of a Binary Treedef printInorder(node: Node) -> None: if (node is None): return printInorder(node.left) print(node.data, end = \" \") printInorder(node.right) # Driver codeif __name__ == \"__main__\": pre = [ 1, 2, 4, 8, 9, 5, 3, 6, 7 ] post = [ 8, 9, 4, 5, 2, 6, 7, 3, 1 ] size = len(pre) preIndex = 0 root = constructTree(pre, post, size) print(\"Inorder traversal of \" \"the constructed tree: \") printInorder(root) # This code is contributed by sanjeev2552",
"e": 11980,
"s": 9465,
"text": null
},
{
"code": "// C# program for construction// of full binary treeusing System; class GFG{// variable to hold index in pre[] arraypublic static int preindex; public class node{ public int data; public node left, right; public node(int data) { this.data = data; }} // A recursive function to construct Full// from pre[] and post[]. preIndex is used// to keep track of index in pre[]. l is// low index and h is high index for the// current subarray in post[]public static node constructTreeUtil(int[] pre, int[] post, int l, int h, int size){ // Base case if (preindex >= size || l > h) { return null; } // The first node in preorder traversal is // root. So take the node at preIndex from // preorder and make it root, and increment // preIndex node root = new node(pre[preindex]); preindex++; // If the current subarray has only one // element, no need to recur or // preIndex > size after incrementing if (l == h || preindex >= size) { return root; } int i; // Search the next element // of pre[] in post[] for (i = l; i <= h; i++) { if (post[i] == pre[preindex]) { break; } } // Use the index of element found // in postorder to divide postorder // array in two parts. Left subtree // and right subtree if (i <= h) { root.left = constructTreeUtil(pre, post, l, i, size); root.right = constructTreeUtil(pre, post, i + 1, h-1, size); } return root;} // The main function to construct Full// Binary Tree from given preorder and// postorder traversals. This function// mainly uses constructTreeUtil()public static node constructTree(int[] pre, int[] post, int size){ preindex = 0; return constructTreeUtil(pre, post, 0, size - 1, size);} public static void printInorder(node root){ if (root == null) { return; } printInorder(root.left); Console.Write(root.data + \" \"); printInorder(root.right);} // Driver Codepublic static void Main(string[] args){ int[] pre = new int[] {1, 2, 4, 8, 9, 5, 3, 6, 7}; int[] post = new int[] {8, 9, 4, 5, 2, 6, 7, 3, 1}; int size = pre.Length; node root = constructTree(pre, post, size); Console.WriteLine(\"Inorder traversal of \" + \"the constructed tree:\"); printInorder(root);}} // This code is contributed by Shrikant13",
"e": 14515,
"s": 11980,
"text": null
},
{
"code": "<script> // Javascript program for construction// of full binary tree // variable to hold index in pre[] arrayvar preindex = 0; class node{ constructor(data) { this.data = data; }} // A recursive function to construct Full// from pre[] and post[]. preIndex is used// to keep track of index in pre[]. l is// low index and h is high index for the// current subarray in post[]function constructTreeUtil(pre, post, l, h, size){ // Base case if (preindex >= size || l > h) { return null; } // The first node in preorder traversal is // root. So take the node at preIndex from // preorder and make it root, and increment // preIndex var root = new node(pre[preindex]); preindex++; // If the current subarray has only one // element, no need to recur or // preIndex > size after incrementing if (l == h || preindex >= size) { return root; } var i; // Search the next element // of pre[] in post[] for (i = l; i <= h; i++) { if (post[i] == pre[preindex]) { break; } } // Use the index of element found // in postorder to divide postorder // array in two parts. Left subtree // and right subtree if (i <= h) { root.left = constructTreeUtil(pre, post, l, i, size); root.right = constructTreeUtil(pre, post, i + 1, h-1, size); } return root;} // The main function to construct Full// Binary Tree from given preorder and// postorder traversals. This function// mainly uses constructTreeUtil()function constructTree(pre, post, size){ preindex = 0; return constructTreeUtil(pre, post, 0, size - 1, size);} function printInorder(root){ if (root == null) { return; } printInorder(root.left); document.write(root.data + \" \"); printInorder(root.right);} // Driver Codevar pre = [1, 2, 4, 8, 9, 5, 3, 6, 7];var post = [8, 9, 4, 5, 2, 6, 7, 3, 1];var size = pre.length;var root = constructTree(pre, post, size);document.write(\"Inorder traversal of \" + \"the constructed tree:<br>\");printInorder(root); </script>",
"e": 16706,
"s": 14515,
"text": null
},
{
"code": null,
"e": 16769,
"s": 16706,
"text": "Inorder traversal of the constructed tree: \n8 4 9 2 5 1 6 3 7 "
},
{
"code": null,
"e": 16781,
"s": 16769,
"text": "shrikanth13"
},
{
"code": null,
"e": 16795,
"s": 16781,
"text": "rathbhupendra"
},
{
"code": null,
"e": 16807,
"s": 16795,
"text": "sanjeev2552"
},
{
"code": null,
"e": 16817,
"s": 16807,
"text": "rutvik_56"
},
{
"code": null,
"e": 16837,
"s": 16817,
"text": "parthagarwal1962000"
},
{
"code": null,
"e": 16847,
"s": 16837,
"text": "as5853535"
},
{
"code": null,
"e": 16864,
"s": 16847,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 16869,
"s": 16864,
"text": "Tree"
},
{
"code": null,
"e": 16874,
"s": 16869,
"text": "Tree"
}
] |
SQL SELECT Statement
|
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
Here, column1, column2, ... are the field names of the table you want to
select data from. If you
want to select all the fields available in the table, use the following syntax:
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement selects the "CustomerName" and "City" columns
from the "Customers" table:
The following SQL statement selects all the columns from the "Customers"
table:
Insert the missing statement to get all the columns from the Customers table.
* FROM Customers;
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 61,
"s": 0,
"text": "The SELECT statement is used to select data from a database."
},
{
"code": null,
"e": 131,
"s": 61,
"text": "The data returned is stored in a result table, called the result-set."
},
{
"code": null,
"e": 311,
"s": 131,
"text": "Here, column1, column2, ... are the field names of the table you want to \nselect data from. If you \nwant to select all the fields available in the table, use the following syntax:"
},
{
"code": null,
"e": 393,
"s": 311,
"text": "Below is a selection from the \"Customers\" table in the Northwind sample database:"
},
{
"code": null,
"e": 496,
"s": 393,
"text": "The following SQL statement selects the \"CustomerName\" and \"City\" columns \nfrom the \"Customers\" table:"
},
{
"code": null,
"e": 577,
"s": 496,
"text": "The following SQL statement selects all the columns from the \"Customers\" \ntable:"
},
{
"code": null,
"e": 655,
"s": 577,
"text": "Insert the missing statement to get all the columns from the Customers table."
},
{
"code": null,
"e": 675,
"s": 655,
"text": " * FROM Customers;\n"
},
{
"code": null,
"e": 694,
"s": 675,
"text": "Start the Exercise"
},
{
"code": null,
"e": 727,
"s": 694,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 769,
"s": 727,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 876,
"s": 769,
"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": 895,
"s": 876,
"text": "help@w3schools.com"
}
] |
Arc function in C
|
In the C programming language, there is an option to create an arc of a circle of a given radius with a given center coordinates and degree of the arc.
The arc()
function is used to create an arc. This arc function is included in graphics.h library in C which contains methods that can draw figures on the output screen.
void arc(int x, int y, int startangle, int endangle, int radius);
Now, let's get deep into the function and understand each parameter passed and output returned by the function.
x − type = int, function: defines the x coordinate of the center of the arc.
y − type = int, function: defines the y coordinate of the center of the arc.
start angle − type = int, function: defines the starting angle of arc.
entangle − type = int, function: defines the ending angle of arc.
Radius − type = int, function: defines the radius of the arc.
#include <graphics.h>
int main(){
int gd = DETECT, gm;
int x = 250;
int y = 250;
int start_angle = 155;
int end_angle = 300;
int radius = 100;
initgraph(&gd, &gm, "");
arc(x, y, start_angle, end_angle, radius);
getch();
closegraph();
return 0;
}
|
[
{
"code": null,
"e": 1214,
"s": 1062,
"text": "In the C programming language, there is an option to create an arc of a circle of a given radius with a given center coordinates and degree of the arc."
},
{
"code": null,
"e": 1383,
"s": 1214,
"text": "The arc()\nfunction is used to create an arc. This arc function is included in graphics.h library in C which contains methods that can draw figures on the output screen."
},
{
"code": null,
"e": 1449,
"s": 1383,
"text": "void arc(int x, int y, int startangle, int endangle, int radius);"
},
{
"code": null,
"e": 1561,
"s": 1449,
"text": "Now, let's get deep into the function and understand each parameter passed and output returned by the function."
},
{
"code": null,
"e": 1638,
"s": 1561,
"text": "x − type = int, function: defines the x coordinate of the center of the arc."
},
{
"code": null,
"e": 1715,
"s": 1638,
"text": "y − type = int, function: defines the y coordinate of the center of the arc."
},
{
"code": null,
"e": 1786,
"s": 1715,
"text": "start angle − type = int, function: defines the starting angle of arc."
},
{
"code": null,
"e": 1852,
"s": 1786,
"text": "entangle − type = int, function: defines the ending angle of arc."
},
{
"code": null,
"e": 1914,
"s": 1852,
"text": "Radius − type = int, function: defines the radius of the arc."
},
{
"code": null,
"e": 2193,
"s": 1914,
"text": "#include <graphics.h>\nint main(){\n int gd = DETECT, gm;\n int x = 250;\n int y = 250;\n int start_angle = 155;\n int end_angle = 300;\n int radius = 100;\n initgraph(&gd, &gm, \"\");\n arc(x, y, start_angle, end_angle, radius);\n getch();\n closegraph();\n return 0;\n}"
}
] |
C++ Queue Library - queue() Function
|
The C++ default constructor std::queue::queue() constructs queue object. If cntr argument is passed to constructor, copy of argument is assigned to container otherwise empty queue object is created.
Following is the declaration for std::queue::queue() constructor form std::queue header.
explicit queue (const container_type& ctnr = container_type());
ctnr − Container type which is second parameter of class template.
Constructor never returns value.
Linear if container of non-zero size is passed as argument otherwise constant.
The following example shows the usage of std::queue::queue() constructor.
#include <iostream>
#include <queue>
using namespace std;
int main(void) {
deque<int> d(5, 100);
queue<int>q1;
queue<int> q2(d);
cout << "Size of q1 = " << q1.size() << endl;
cout << "Size of q2 = " << q2.size() << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
Size of q1 = 0
Size of q2 = 5
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2802,
"s": 2603,
"text": "The C++ default constructor std::queue::queue() constructs queue object. If cntr argument is passed to constructor, copy of argument is assigned to container otherwise empty queue object is created."
},
{
"code": null,
"e": 2891,
"s": 2802,
"text": "Following is the declaration for std::queue::queue() constructor form std::queue header."
},
{
"code": null,
"e": 2956,
"s": 2891,
"text": "explicit queue (const container_type& ctnr = container_type());\n"
},
{
"code": null,
"e": 3023,
"s": 2956,
"text": "ctnr − Container type which is second parameter of class template."
},
{
"code": null,
"e": 3056,
"s": 3023,
"text": "Constructor never returns value."
},
{
"code": null,
"e": 3135,
"s": 3056,
"text": "Linear if container of non-zero size is passed as argument otherwise constant."
},
{
"code": null,
"e": 3209,
"s": 3135,
"text": "The following example shows the usage of std::queue::queue() constructor."
},
{
"code": null,
"e": 3467,
"s": 3209,
"text": "#include <iostream>\n#include <queue>\n\nusing namespace std;\n\nint main(void) { \n deque<int> d(5, 100);\n queue<int>q1;\n queue<int> q2(d);\n\n cout << \"Size of q1 = \" << q1.size() << endl;\n cout << \"Size of q2 = \" << q2.size() << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3550,
"s": 3467,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3581,
"s": 3550,
"text": "Size of q1 = 0\nSize of q2 = 5\n"
},
{
"code": null,
"e": 3588,
"s": 3581,
"text": " Print"
},
{
"code": null,
"e": 3599,
"s": 3588,
"text": " Add Notes"
}
] |
Machine Learning Pipelines With Scikit-Learn | by Jason Wong | Towards Data Science
|
This post will serve as a step by step guide to build pipelines that streamline the machine learning workflow. I will be using the infamous Titanic dataset for this tutorial. The dataset was obtained from Kaggle. The goal being to predict whether a given person survived or not. I will be implementing various classification algorithms, as well as, grid searching and cross validation. This dataset holds records for each passenger consisting of 10 variables (see data dictionary below). For the purposes of this tutorial, I will only be using the train dataset, which will be split into train, validation, and test sets.
The machine learning workflow consists of many steps from data preparation (e.g., dealing with missing values, scaling/encoding, feature extraction). When first learning this workflow, we perform the data preparation one step at a time. This can become time consuming since we need to perform the preparation steps to both the training and testing data. Pipelines allow us to streamline this process by compiling the preparation steps while easing the task of model tuning and monitoring. Scikit-Learn’s Pipeline class provides a structure for applying a series of data transformations followed by an estimator (Mayo, 2017). For a more detailed overview, take a look over the documentation. There are many benefits when implementing a Pipeline:
Convenience and encapsulation: We call fit and predict only once on the data to fit an entire sequence of estimators.
Joint parameter selection: We can perform a grid search over parameters of all estimators in the pipeline.
Cross-Validation: Pipelines help to avoid data leakage from the testing data into the trained model during cross-validation. This is achieved by ensuring that the same samples are used to train the transformers and predictors.
Time to see pipelines in action! Below, I will install and import the necessary libraries. Then move on to loading in the dataset and handling missing values. Once the data is ready, I will create transformers for the different data types and a column transformer to encapsulate the preprocessing steps. Finally, I’ll write a function for training a model with cross validation and a similar function including grid search cross validation.
Installing Scikit-Learn
!pip install -U scikit-learn
Importing the necessary libraries
# Standard Importsimport pandas as pdimport seaborn as snsimport numpy as npimport matplotlib.pyplot as pltimport pickle# Transformersfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler, MinMaxScaler# Modeling Evaluationfrom sklearn.model_selection import train_test_split, cross_val_score, KFold, GridSearchCVfrom sklearn.metrics import accuracy_score, precision_score, recall_score,f1_score, confusion_matrix, classification_reportfrom IPython.display import display, Markdown# Pipelinesfrom sklearn.pipeline import Pipeline, FeatureUnionfrom sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.compose import ColumnTransformer# Machine Learningfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import KFoldfrom sklearn.neighbors import KNeighborsClassifier
Loading in the data and viewing the top 5 rows
df = pd.read_csv("titanic.csv")df.head()
Checking for missing values
df.isna().sum()
There are 177 out of 891 missing values in the Age column. For the purposes of this pipeline tutorial, I am going to go ahead and fill in the missing Age values with the mean age. There are 687 out of 891 missing values in the Cabin column. I am removing this feature since approximately 77% of values are missing. The Embarked feature is only missing 2 values so we can fill these with the most common value. The Name and Ticket features both hold unique values to each passenger and will not be needed for predictive classification so they will also be dropped.
Dropping features
df.drop(["Name", "Ticket", "Cabin"], axis=1, inplace=True)
Filling na values for the Embarked feature with the most frequent value, S.
df.Embarked = df.Embarked.fillna(value='S')
Now that we’ve handled the missing values in the dataset, we can move on to defining the continuous and categorical variables.
Defining variables for the columns in the dataframe to perform a train test split.
columns = ['Pclass', 'Sex', 'SibSp', 'Parch', 'Fare', 'Embarked']numerical_columns = ['Age', 'Fare']categorical_columns = ["Pclass", "Sex", "SibSp", "Parch", "Embarked"]
Next, I am going to create two functions. The first function cross_validate will take in a classifier and cv (cross validator), split the training data into train and test sets, fit the classifier on the training and predict on it as well. The function will then predict on the hold out validation set and return the scores from both the training and test set.
Pipelines allow us to perform the preprocessing (e.g. standardizing, encoding, model fitting) in one step. A pipeline can take in any number of preprocessing steps with each having .fit() and .transform() methods. Below, I am creating two transformers, a standard scaler and a one hot encoder. The two different transformers will be for the different data types.
#Creating ss transformer to scale the continuous numerical data with StandardScaler()ss = Pipeline(steps=[('ss', StandardScaler())])--------------------------------------------------------------------#Creating ohe transformer to encode the categorical data with OneHotEncoder()ohe = Pipeline(steps=[('ohe', OneHotEncoder(drop='first'))])--------------------------------------------------------------------#Creating preprocess column transformer to combine the ss and ohe pipelinespreprocess = ColumnTransformer( transformers=[ ('cont', ss, numerical), ('cat', ohe, categorical) ])
Creating evaluation function to plot a confusion matrix and return the accuracy, precision, recall, and f1 scores
def evaluation(y, y_hat, title = 'Confusion Matrix'): cm = confusion_matrix(y, y_hat) precision = precision_score(y, y_hat) recall = recall_score(y, y_hat) accuracy = accuracy_score(y,y_hat) f1 = f1_score(y,y_hat) print('Recall: ', recall) print('Accuracy: ', accuracy) print('Precision: ', precision) print('F1: ', f1) sns.heatmap(cm, cmap= 'PuBu', annot=True, fmt='g', annot_kws= {'size':20}) plt.xlabel('predicted', fontsize=18) plt.ylabel('actual', fontsize=18) plt.title(title, fontsize=18) plt.show();
Performing train_test_split on the data
X = df.drop(['Survived'], axis=1)y = df.Survivedy = LabelEncoder().fit_transform(y)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
Defines the full pipeline with the preprocess and classifier pipelines
Loop through each fold in the cross validator (default is 5)
Fit the classifier on the train set, train_ind (prevents data leakage from test set)
Predict on the training set
Predict on the validation set
Print out an evaluation report containing a confusion matrix and the mean accuracy scores for both train and validation sets
def cross_validate(classifier, cv): pipeline = Pipeline(steps=[ ('preprocess', preprocess), ('classifier', classifier) ]) train_acc = [] test_acc = [] for train_ind, val_ind in cv.split(X_train, y_train): X_t, y_t = X_train.iloc[train_ind], y_train[train_ind] pipeline.fit(X_t, y_t) y_hat_t = pipeline.predict(X_t) train_acc.append(accuracy_score(y_t, y_hat_t)) X_val, y_val = X_train.iloc[val_ind], y_train[val_ind] y_hat_val = pipeline.predict(X_val) test_acc.append(accuracy_score(y_val, y_hat_val)) print(evaluation(y_val, y_hat_val)) print('Training Accuracy: {}'.format(np.mean(train_acc))) print('\n') print('Validation Accuracy: {}'.format(np.mean(test_acc))) print('\n')
In the function I am using the cross validator to split the training data in order to have a hold out test set (X_test, y_test). Now we can use the function above by inputting the desired classifier and cross validator.
cross_validate(DecisionTreeClassifier(), KFold())
Output:
With K Nearest Neighbors classifier
cross_validate(KNeighborsClassifier(), KFold())
Output:
Let’s say we wanted to find the most optimal parameters for the model in the pipeline, we can just create a grid search pipeline. For a refresher on grid search, check out the documentation. We can create a function like the one above for cross validating but modify it a bit to perform a grid search. This function will take in the desired classifier, parameter grid, and cross validator. Then, will go through the same process as for the cross_validate function with a grid search.
def grid_search(classifier, param_grid, cv): search = GridSearchCV(Pipeline(steps=[ ('preprocess', preprocess), ('classifier', classifier) ]), param_grid, cv=cv) train_acc = [] test_acc = [] for train_ind, val_ind in cv.split(X_train, y_train): X_t, y_t = X_train.iloc[train_ind], y_train[train_ind] search.fit(X_t, y_t) y_hat_t = search.predict(X_t) train_acc.append(accuracy_score(y_t, y_hat_t)) X_val, y_val = X_train.iloc[val_ind], y_train[val_ind] y_hat_val = search.predict(X_val) test_acc.append(accuracy_score(y_val, y_hat_val)) print(evaluation(y_val, y_hat_val)) print('Training Accuracy: {}'.format(np.mean(train_acc))) print('\n') print('Validation Accuracy: {}'.format(np.mean(test_acc))) print('\n') print('Grid Search Best Params:') print('\n') print(search.best_params_)
GridSearchCV with Random Forest
When creating a parameter grid for the model in the pipeline, the model’s name needs to be appended to each parameter. In the code block below, I have appended 'classifier__' to match the name of the model in the pipeline (named the model ‘classifier’ in the pipeline).
#Creating parameter grid for Random Forestrand_forest_parms = {'classifier__n_estimators': [100, 300, 500], 'classifier__max_depth':[6, 25, 50, 70], 'classifier__min_samples_split': [2, 5, 10], 'classifier__min_samples_leaf': [1, 2, 10]}#Calling the grid_search function using the parameters abovegrid_search(RandomForestClassifier(), rand_forest_parms)
Output:
During model training, it is important to perform feature selection to make sure the model is provided with the most predictive power, as well as, making sure our model isn’t too complex. We can check the feature importances for the classifier in the pipeline using the eli5 library. To do this, we need to create a list with the numerical feature columns and the encoded columns. Then, call eli5.explain_weights_df with the grid search pipeline’s best_estimator_ and its named_steps. Of course we can just add this to our grid search function to return the top ten feature importances by modifying the function to take in a boolean value that will print out these features.
The modification to include feature importances in the function below are in bold.
def grid_search(classifier, param_grid, cv, print_feat=False): cv = cv search = GridSearchCV(Pipeline(steps=[ ('preprocess', preprocess), ('classifier', classifier) ]), param_grid, cv=cv) train_acc = [] test_acc = [] for train_ind, val_ind in cv.split(X_train, y_train): X_t, y_t = X_train.iloc[train_ind], y_train[train_ind] search.fit(X_t, y_t) y_hat_t = search.predict(X_t) train_acc.append(accuracy_score(y_t, y_hat_t)) X_val, y_val = X_train.iloc[val_ind], y_train[val_ind] y_hat_val = search.predict(X_val) test_acc.append(accuracy_score(y_val, y_hat_val)) if print_feat: ohe_cols = list(search.best_estimator_.named_steps['preprocess'].named_transformers_['cat'].named_steps['ohe'].get_feature_names( input_features=categorical)) num_feats = list(numerical) num_feats.extend(ohe_cols) feat_imp = eli5.explain_weights_df(search.best_estimator_.named_steps['classifier'], top=10, feature_names=num_feats) print(feat_imp) print('\n') print(evaluation(y_val, y_hat_val)) print('Training Accuracy: {}'.format(np.mean(train_acc))) print('\n') print('Validation Accuracy: {}'.format(np.mean(test_acc))) print('\n') print('Grid Search Best Params:') print('\n') print(search.best_params_)
Performing grid search and returning the top ten features of importance along with their weights
grid_search(RandomForestClassifier(), rand_forest_parms, KFold(), print_feat=True)
Output:
Let’s say that the Random Forest Classifier in the grid search pipeline is performing the best. The next step would be to see how the trained model performs on the hold out test data. All we need to do is create a final pipeline with GridSearchCV and fit it to the entire X_train and y_train. Then, predict on X_test.
Fitting final pipeline to X_train and y_train, and predicting on X_test
final_pipeline = GridSearchCV(Pipeline(steps=[ ('preprocess', preprocess), ('classifier', RandomForestClassifier()) ]), rand_forest_parms, cv=KFold())#Fit and predict on train datafinal_pipeline.fit(X_train, y_train)train_pred = final_pipeline.best_estimator_.predict(X_train)print('Evaluation on training data \n')print(evaluation(y_train, train_pred))print('\n')#Predict on test datatest_pred = final_pipeline.best_estimator_.predict(X_test)print('Evaluation on testing data \n')print(evaluation(y_test, test_pred))
Output:
Pipelines keep our preprocessing steps and models encapsulated, making the machine learning workflow much easier. We can apply more than one preprocessing step if needed before fitting a model in the pipeline. The main benefit for me has been being able to come back to a project and following the workflow I set with pipelines. This process would take hours before I learned about pipelines. I hope this tutorial can become a helpful resource in learning the pipeline workflow.
Managing Machine Learning Workflows with Scikit-learn Pipelines Part 1: A Gentle Introduction. (n.d.). Retrieved from https://www.kdnuggets.com/2017/12/managing-machine-learning-workflows-scikit-learn-pipelines-part-1.html
Koen, S. (2019, August 09). Architecting a Machine Learning Pipeline. Retrieved from https://towardsdatascience.com/architecting-a-machine-learning-pipeline-a847f094d1c7
Sklearn.pipeline.Pipeline. (n.d.). Retrieved from https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html
M, S. (2019, December 13). WHAT IS A PIPELINE IN MACHINE LEARNING?HOW TO CREATE ONE? Retrieved from https://medium.com/analytics-vidhya/what-is-a-pipeline-in-machine-learning-how-to-create-one-bda91d0ceaca#:~:text=A machine learning pipeline is used to help automate machine learning workflows.&text=Machine learning (ML) pipelines consist,and achieve a successful algorithm .
Titanic: Machine Learning from Disaster. (n.d.). Retrieved from https://www.kaggle.com/c/titanic/data
3.2. Tuning the hyper-parameters of an estimator. (n.d.). Retrieved from https://scikit-learn.org/stable/modules/grid_search.html
Overview. (n.d.). Retrieved from https://eli5.readthedocs.io/en/latest/overview.html
|
[
{
"code": null,
"e": 794,
"s": 172,
"text": "This post will serve as a step by step guide to build pipelines that streamline the machine learning workflow. I will be using the infamous Titanic dataset for this tutorial. The dataset was obtained from Kaggle. The goal being to predict whether a given person survived or not. I will be implementing various classification algorithms, as well as, grid searching and cross validation. This dataset holds records for each passenger consisting of 10 variables (see data dictionary below). For the purposes of this tutorial, I will only be using the train dataset, which will be split into train, validation, and test sets."
},
{
"code": null,
"e": 1539,
"s": 794,
"text": "The machine learning workflow consists of many steps from data preparation (e.g., dealing with missing values, scaling/encoding, feature extraction). When first learning this workflow, we perform the data preparation one step at a time. This can become time consuming since we need to perform the preparation steps to both the training and testing data. Pipelines allow us to streamline this process by compiling the preparation steps while easing the task of model tuning and monitoring. Scikit-Learn’s Pipeline class provides a structure for applying a series of data transformations followed by an estimator (Mayo, 2017). For a more detailed overview, take a look over the documentation. There are many benefits when implementing a Pipeline:"
},
{
"code": null,
"e": 1657,
"s": 1539,
"text": "Convenience and encapsulation: We call fit and predict only once on the data to fit an entire sequence of estimators."
},
{
"code": null,
"e": 1764,
"s": 1657,
"text": "Joint parameter selection: We can perform a grid search over parameters of all estimators in the pipeline."
},
{
"code": null,
"e": 1991,
"s": 1764,
"text": "Cross-Validation: Pipelines help to avoid data leakage from the testing data into the trained model during cross-validation. This is achieved by ensuring that the same samples are used to train the transformers and predictors."
},
{
"code": null,
"e": 2432,
"s": 1991,
"text": "Time to see pipelines in action! Below, I will install and import the necessary libraries. Then move on to loading in the dataset and handling missing values. Once the data is ready, I will create transformers for the different data types and a column transformer to encapsulate the preprocessing steps. Finally, I’ll write a function for training a model with cross validation and a similar function including grid search cross validation."
},
{
"code": null,
"e": 2456,
"s": 2432,
"text": "Installing Scikit-Learn"
},
{
"code": null,
"e": 2485,
"s": 2456,
"text": "!pip install -U scikit-learn"
},
{
"code": null,
"e": 2519,
"s": 2485,
"text": "Importing the necessary libraries"
},
{
"code": null,
"e": 3394,
"s": 2519,
"text": "# Standard Importsimport pandas as pdimport seaborn as snsimport numpy as npimport matplotlib.pyplot as pltimport pickle# Transformersfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler, MinMaxScaler# Modeling Evaluationfrom sklearn.model_selection import train_test_split, cross_val_score, KFold, GridSearchCVfrom sklearn.metrics import accuracy_score, precision_score, recall_score,f1_score, confusion_matrix, classification_reportfrom IPython.display import display, Markdown# Pipelinesfrom sklearn.pipeline import Pipeline, FeatureUnionfrom sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.compose import ColumnTransformer# Machine Learningfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import KFoldfrom sklearn.neighbors import KNeighborsClassifier"
},
{
"code": null,
"e": 3441,
"s": 3394,
"text": "Loading in the data and viewing the top 5 rows"
},
{
"code": null,
"e": 3482,
"s": 3441,
"text": "df = pd.read_csv(\"titanic.csv\")df.head()"
},
{
"code": null,
"e": 3510,
"s": 3482,
"text": "Checking for missing values"
},
{
"code": null,
"e": 3526,
"s": 3510,
"text": "df.isna().sum()"
},
{
"code": null,
"e": 4090,
"s": 3526,
"text": "There are 177 out of 891 missing values in the Age column. For the purposes of this pipeline tutorial, I am going to go ahead and fill in the missing Age values with the mean age. There are 687 out of 891 missing values in the Cabin column. I am removing this feature since approximately 77% of values are missing. The Embarked feature is only missing 2 values so we can fill these with the most common value. The Name and Ticket features both hold unique values to each passenger and will not be needed for predictive classification so they will also be dropped."
},
{
"code": null,
"e": 4108,
"s": 4090,
"text": "Dropping features"
},
{
"code": null,
"e": 4167,
"s": 4108,
"text": "df.drop([\"Name\", \"Ticket\", \"Cabin\"], axis=1, inplace=True)"
},
{
"code": null,
"e": 4243,
"s": 4167,
"text": "Filling na values for the Embarked feature with the most frequent value, S."
},
{
"code": null,
"e": 4287,
"s": 4243,
"text": "df.Embarked = df.Embarked.fillna(value='S')"
},
{
"code": null,
"e": 4414,
"s": 4287,
"text": "Now that we’ve handled the missing values in the dataset, we can move on to defining the continuous and categorical variables."
},
{
"code": null,
"e": 4497,
"s": 4414,
"text": "Defining variables for the columns in the dataframe to perform a train test split."
},
{
"code": null,
"e": 4689,
"s": 4497,
"text": "columns = ['Pclass', 'Sex', 'SibSp', 'Parch', 'Fare', 'Embarked']numerical_columns = ['Age', 'Fare']categorical_columns = [\"Pclass\", \"Sex\", \"SibSp\", \"Parch\", \"Embarked\"]"
},
{
"code": null,
"e": 5050,
"s": 4689,
"text": "Next, I am going to create two functions. The first function cross_validate will take in a classifier and cv (cross validator), split the training data into train and test sets, fit the classifier on the training and predict on it as well. The function will then predict on the hold out validation set and return the scores from both the training and test set."
},
{
"code": null,
"e": 5413,
"s": 5050,
"text": "Pipelines allow us to perform the preprocessing (e.g. standardizing, encoding, model fitting) in one step. A pipeline can take in any number of preprocessing steps with each having .fit() and .transform() methods. Below, I am creating two transformers, a standard scaler and a one hot encoder. The two different transformers will be for the different data types."
},
{
"code": null,
"e": 6078,
"s": 5413,
"text": "#Creating ss transformer to scale the continuous numerical data with StandardScaler()ss = Pipeline(steps=[('ss', StandardScaler())])--------------------------------------------------------------------#Creating ohe transformer to encode the categorical data with OneHotEncoder()ohe = Pipeline(steps=[('ohe', OneHotEncoder(drop='first'))])--------------------------------------------------------------------#Creating preprocess column transformer to combine the ss and ohe pipelinespreprocess = ColumnTransformer( transformers=[ ('cont', ss, numerical), ('cat', ohe, categorical) ])"
},
{
"code": null,
"e": 6192,
"s": 6078,
"text": "Creating evaluation function to plot a confusion matrix and return the accuracy, precision, recall, and f1 scores"
},
{
"code": null,
"e": 6750,
"s": 6192,
"text": "def evaluation(y, y_hat, title = 'Confusion Matrix'): cm = confusion_matrix(y, y_hat) precision = precision_score(y, y_hat) recall = recall_score(y, y_hat) accuracy = accuracy_score(y,y_hat) f1 = f1_score(y,y_hat) print('Recall: ', recall) print('Accuracy: ', accuracy) print('Precision: ', precision) print('F1: ', f1) sns.heatmap(cm, cmap= 'PuBu', annot=True, fmt='g', annot_kws= {'size':20}) plt.xlabel('predicted', fontsize=18) plt.ylabel('actual', fontsize=18) plt.title(title, fontsize=18) plt.show();"
},
{
"code": null,
"e": 6790,
"s": 6750,
"text": "Performing train_test_split on the data"
},
{
"code": null,
"e": 6948,
"s": 6790,
"text": "X = df.drop(['Survived'], axis=1)y = df.Survivedy = LabelEncoder().fit_transform(y)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)"
},
{
"code": null,
"e": 7019,
"s": 6948,
"text": "Defines the full pipeline with the preprocess and classifier pipelines"
},
{
"code": null,
"e": 7080,
"s": 7019,
"text": "Loop through each fold in the cross validator (default is 5)"
},
{
"code": null,
"e": 7165,
"s": 7080,
"text": "Fit the classifier on the train set, train_ind (prevents data leakage from test set)"
},
{
"code": null,
"e": 7193,
"s": 7165,
"text": "Predict on the training set"
},
{
"code": null,
"e": 7223,
"s": 7193,
"text": "Predict on the validation set"
},
{
"code": null,
"e": 7348,
"s": 7223,
"text": "Print out an evaluation report containing a confusion matrix and the mean accuracy scores for both train and validation sets"
},
{
"code": null,
"e": 8121,
"s": 7348,
"text": "def cross_validate(classifier, cv): pipeline = Pipeline(steps=[ ('preprocess', preprocess), ('classifier', classifier) ]) train_acc = [] test_acc = [] for train_ind, val_ind in cv.split(X_train, y_train): X_t, y_t = X_train.iloc[train_ind], y_train[train_ind] pipeline.fit(X_t, y_t) y_hat_t = pipeline.predict(X_t) train_acc.append(accuracy_score(y_t, y_hat_t)) X_val, y_val = X_train.iloc[val_ind], y_train[val_ind] y_hat_val = pipeline.predict(X_val) test_acc.append(accuracy_score(y_val, y_hat_val)) print(evaluation(y_val, y_hat_val)) print('Training Accuracy: {}'.format(np.mean(train_acc))) print('\\n') print('Validation Accuracy: {}'.format(np.mean(test_acc))) print('\\n')"
},
{
"code": null,
"e": 8341,
"s": 8121,
"text": "In the function I am using the cross validator to split the training data in order to have a hold out test set (X_test, y_test). Now we can use the function above by inputting the desired classifier and cross validator."
},
{
"code": null,
"e": 8391,
"s": 8341,
"text": "cross_validate(DecisionTreeClassifier(), KFold())"
},
{
"code": null,
"e": 8399,
"s": 8391,
"text": "Output:"
},
{
"code": null,
"e": 8435,
"s": 8399,
"text": "With K Nearest Neighbors classifier"
},
{
"code": null,
"e": 8483,
"s": 8435,
"text": "cross_validate(KNeighborsClassifier(), KFold())"
},
{
"code": null,
"e": 8491,
"s": 8483,
"text": "Output:"
},
{
"code": null,
"e": 8975,
"s": 8491,
"text": "Let’s say we wanted to find the most optimal parameters for the model in the pipeline, we can just create a grid search pipeline. For a refresher on grid search, check out the documentation. We can create a function like the one above for cross validating but modify it a bit to perform a grid search. This function will take in the desired classifier, parameter grid, and cross validator. Then, will go through the same process as for the cross_validate function with a grid search."
},
{
"code": null,
"e": 9864,
"s": 8975,
"text": "def grid_search(classifier, param_grid, cv): search = GridSearchCV(Pipeline(steps=[ ('preprocess', preprocess), ('classifier', classifier) ]), param_grid, cv=cv) train_acc = [] test_acc = [] for train_ind, val_ind in cv.split(X_train, y_train): X_t, y_t = X_train.iloc[train_ind], y_train[train_ind] search.fit(X_t, y_t) y_hat_t = search.predict(X_t) train_acc.append(accuracy_score(y_t, y_hat_t)) X_val, y_val = X_train.iloc[val_ind], y_train[val_ind] y_hat_val = search.predict(X_val) test_acc.append(accuracy_score(y_val, y_hat_val)) print(evaluation(y_val, y_hat_val)) print('Training Accuracy: {}'.format(np.mean(train_acc))) print('\\n') print('Validation Accuracy: {}'.format(np.mean(test_acc))) print('\\n') print('Grid Search Best Params:') print('\\n') print(search.best_params_)"
},
{
"code": null,
"e": 9896,
"s": 9864,
"text": "GridSearchCV with Random Forest"
},
{
"code": null,
"e": 10166,
"s": 9896,
"text": "When creating a parameter grid for the model in the pipeline, the model’s name needs to be appended to each parameter. In the code block below, I have appended 'classifier__' to match the name of the model in the pipeline (named the model ‘classifier’ in the pipeline)."
},
{
"code": null,
"e": 10580,
"s": 10166,
"text": "#Creating parameter grid for Random Forestrand_forest_parms = {'classifier__n_estimators': [100, 300, 500], 'classifier__max_depth':[6, 25, 50, 70], 'classifier__min_samples_split': [2, 5, 10], 'classifier__min_samples_leaf': [1, 2, 10]}#Calling the grid_search function using the parameters abovegrid_search(RandomForestClassifier(), rand_forest_parms)"
},
{
"code": null,
"e": 10588,
"s": 10580,
"text": "Output:"
},
{
"code": null,
"e": 11263,
"s": 10588,
"text": "During model training, it is important to perform feature selection to make sure the model is provided with the most predictive power, as well as, making sure our model isn’t too complex. We can check the feature importances for the classifier in the pipeline using the eli5 library. To do this, we need to create a list with the numerical feature columns and the encoded columns. Then, call eli5.explain_weights_df with the grid search pipeline’s best_estimator_ and its named_steps. Of course we can just add this to our grid search function to return the top ten feature importances by modifying the function to take in a boolean value that will print out these features."
},
{
"code": null,
"e": 11346,
"s": 11263,
"text": "The modification to include feature importances in the function below are in bold."
},
{
"code": null,
"e": 12687,
"s": 11346,
"text": "def grid_search(classifier, param_grid, cv, print_feat=False): cv = cv search = GridSearchCV(Pipeline(steps=[ ('preprocess', preprocess), ('classifier', classifier) ]), param_grid, cv=cv) train_acc = [] test_acc = [] for train_ind, val_ind in cv.split(X_train, y_train): X_t, y_t = X_train.iloc[train_ind], y_train[train_ind] search.fit(X_t, y_t) y_hat_t = search.predict(X_t) train_acc.append(accuracy_score(y_t, y_hat_t)) X_val, y_val = X_train.iloc[val_ind], y_train[val_ind] y_hat_val = search.predict(X_val) test_acc.append(accuracy_score(y_val, y_hat_val)) if print_feat: ohe_cols = list(search.best_estimator_.named_steps['preprocess'].named_transformers_['cat'].named_steps['ohe'].get_feature_names( input_features=categorical)) num_feats = list(numerical) num_feats.extend(ohe_cols) feat_imp = eli5.explain_weights_df(search.best_estimator_.named_steps['classifier'], top=10, feature_names=num_feats) print(feat_imp) print('\\n') print(evaluation(y_val, y_hat_val)) print('Training Accuracy: {}'.format(np.mean(train_acc))) print('\\n') print('Validation Accuracy: {}'.format(np.mean(test_acc))) print('\\n') print('Grid Search Best Params:') print('\\n') print(search.best_params_)"
},
{
"code": null,
"e": 12784,
"s": 12687,
"text": "Performing grid search and returning the top ten features of importance along with their weights"
},
{
"code": null,
"e": 12867,
"s": 12784,
"text": "grid_search(RandomForestClassifier(), rand_forest_parms, KFold(), print_feat=True)"
},
{
"code": null,
"e": 12875,
"s": 12867,
"text": "Output:"
},
{
"code": null,
"e": 13193,
"s": 12875,
"text": "Let’s say that the Random Forest Classifier in the grid search pipeline is performing the best. The next step would be to see how the trained model performs on the hold out test data. All we need to do is create a final pipeline with GridSearchCV and fit it to the entire X_train and y_train. Then, predict on X_test."
},
{
"code": null,
"e": 13265,
"s": 13193,
"text": "Fitting final pipeline to X_train and y_train, and predicting on X_test"
},
{
"code": null,
"e": 13800,
"s": 13265,
"text": "final_pipeline = GridSearchCV(Pipeline(steps=[ ('preprocess', preprocess), ('classifier', RandomForestClassifier()) ]), rand_forest_parms, cv=KFold())#Fit and predict on train datafinal_pipeline.fit(X_train, y_train)train_pred = final_pipeline.best_estimator_.predict(X_train)print('Evaluation on training data \\n')print(evaluation(y_train, train_pred))print('\\n')#Predict on test datatest_pred = final_pipeline.best_estimator_.predict(X_test)print('Evaluation on testing data \\n')print(evaluation(y_test, test_pred))"
},
{
"code": null,
"e": 13808,
"s": 13800,
"text": "Output:"
},
{
"code": null,
"e": 14287,
"s": 13808,
"text": "Pipelines keep our preprocessing steps and models encapsulated, making the machine learning workflow much easier. We can apply more than one preprocessing step if needed before fitting a model in the pipeline. The main benefit for me has been being able to come back to a project and following the workflow I set with pipelines. This process would take hours before I learned about pipelines. I hope this tutorial can become a helpful resource in learning the pipeline workflow."
},
{
"code": null,
"e": 14510,
"s": 14287,
"text": "Managing Machine Learning Workflows with Scikit-learn Pipelines Part 1: A Gentle Introduction. (n.d.). Retrieved from https://www.kdnuggets.com/2017/12/managing-machine-learning-workflows-scikit-learn-pipelines-part-1.html"
},
{
"code": null,
"e": 14680,
"s": 14510,
"text": "Koen, S. (2019, August 09). Architecting a Machine Learning Pipeline. Retrieved from https://towardsdatascience.com/architecting-a-machine-learning-pipeline-a847f094d1c7"
},
{
"code": null,
"e": 14811,
"s": 14680,
"text": "Sklearn.pipeline.Pipeline. (n.d.). Retrieved from https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html"
},
{
"code": null,
"e": 15188,
"s": 14811,
"text": "M, S. (2019, December 13). WHAT IS A PIPELINE IN MACHINE LEARNING?HOW TO CREATE ONE? Retrieved from https://medium.com/analytics-vidhya/what-is-a-pipeline-in-machine-learning-how-to-create-one-bda91d0ceaca#:~:text=A machine learning pipeline is used to help automate machine learning workflows.&text=Machine learning (ML) pipelines consist,and achieve a successful algorithm ."
},
{
"code": null,
"e": 15290,
"s": 15188,
"text": "Titanic: Machine Learning from Disaster. (n.d.). Retrieved from https://www.kaggle.com/c/titanic/data"
},
{
"code": null,
"e": 15420,
"s": 15290,
"text": "3.2. Tuning the hyper-parameters of an estimator. (n.d.). Retrieved from https://scikit-learn.org/stable/modules/grid_search.html"
}
] |
Union of Two Linked Lists | Practice | GeeksforGeeks
|
Given two linked lists, your task is to complete the function makeUnion(), that returns the union of two linked lists. This union should include all the distinct elements only.
Example 1:
Input:
L1 = 9->6->4->2->3->8
L2 = 1->2->8->6->2
Output: 1 2 3 4 6 8 9
Your Task:
The task is to complete the function makeUnion() which makes the union of the given two lists and returns the head of the new list.
Note: The new list formed should be in non-decreasing order.
Expected Time Complexity: O(N * Log(N))
Expected Auxiliary Space: O(N)
Constraints:
1
0
singhvipnesh65 days ago
class Sol{public static Node findUnion(Node head1,Node head2){ HashSet<Integer>set=new HashSet<>(); Node temp1=head1; Node temp2=head2; while(temp1!=null) { if(!set.contains(temp1.data)) set.add(temp1.data); temp1=temp1.next; } while(temp2!=null) { if(!set.contains(temp2.data)) { set.add(temp2.data); } temp2=temp2.next; } ArrayList<Integer>list=new ArrayList<>(set); Node R=null,dummy=null; for(int i=0;i<list.size();i++) { Node newnode = new Node(list.get(i)); if(R == null){ R = newnode; dummy = R; } else { dummy.next=newnode; dummy=dummy.next; } } return R;}}
0
tthakare735 days ago
//java solution -> TC -> 1.20
//hint -> ArrayList or HashSet
class Sol{
public static Node findUnion(Node head1,Node head2){
ArrayList<Integer> union = new ArrayList<>();
while(head1 != null){
if(!union.contains(head1.data)) union.add(new Integer(head1.data));
head1 = head1.next;
}
while(head2 != null){
if(!union.contains(head2.data)) union.add(new Integer(head2.data));
head2 = head2.next;
}
//sort arrayList
Collections.sort(union);
Node Result = null, dummy = null;
for(int i = 0; i < union.size(); i++){
Node newNode = new Node(union.get(i));
if(Result == null){
Result = newNode;
dummy = Result;
} else {
dummy.next = newNode;
dummy = dummy.next;
}
}
return Result;
}
}
0
mitradiptamoy2 weeks ago
//C++ Soln using SETstruct Node* makeUnion(struct Node* head1, struct Node* head2){ // code here Node* ans=new Node(-1); Node* x=ans; set<int>s; while(head1!=NULL) { s.insert(head1->data); head1=head1->next; } while(head2!=NULL) { s.insert(head2->data); head2=head2->next; } for(auto it:s) { Node* t=new Node(it); ans->next=t; ans=ans->next; } x=x->next; return x; }
0
harshpandeyalfa22 weeks ago
(0.12 sec)
struct Node* makeUnion(struct Node* head1, struct Node* head2){ unordered_map<int,int> s; Node* it=head1; while(it) { s[it->data]; it=it->next; } it=head2; while(it) { s[it->data]; it=it->next; } vector<int> q; for(auto i=s.begin() ; i!= s.end() ;i++) { q.push_back(i->first); } sort(q.begin(), q.end()); Node* h; int a=0; h=new Node(q[a]); it=h; a++; while(a!= q.size()) { Node* i=new Node(q[a]); it->next=i; it=i; a++; }
0
tarunlella20003 weeks ago
JAVA
public static Node findUnion(Node head1,Node head2){ //Add your code here. Set<Integer> s = new TreeSet<>(); while(head1 != null){ s.add(head1.data); head1 = head1.next; } while(head2 != null){ s.add(head2.data); head2 = head2.next; } Node ans = new Node(0); Node temp = ans; Iterator<Integer> i = s.iterator(); while(i.hasNext()){ ans.next = new Node(i.next()); ans = ans.next; } return temp.next; }
0
uday10924 weeks ago
struct Node* makeUnion(struct Node* head1, struct Node* head2)
{
set <int> s;
Node * t1 = head1;
Node * t2 = head2;
while(t1 -> next != NULL)
{
t1 = t1 -> next;
}
t1 -> next = t2;
t1 = head1;
while(t1 != NULL)
{
s.insert(t1 -> data);
t1 = t1 -> next;
}
Node * tail = NULL;
Node * head3 = NULL;
for(int i : s)
{
Node * nw = new Node(i);
if(head3 == NULL)
head3 = tail = nw;
else
tail -> next = nw;
tail = nw;
}
return head3;
}
0
hr061 month ago
void insertAtTail(struct Node* &head,struct Node* &tail,int data)
{
Node* node = new Node(data);
if(head == NULL)
{
head = node;
tail = head;
return;
}
tail->next = node;
tail = tail->next;
}
struct Node* makeUnion(struct Node* head1, struct Node* head2)
{
// code here
set<int> s;
Node* curr = head1;
while(curr != NULL)
{
// to keep only distinct elements in a sorted way
s.insert(curr->data);
curr = curr->next;
}
curr = head2;
while(curr != NULL)
{
s.insert(curr->data);
curr = curr->next;
}
Node* newH = NULL;
Node* newT = newH;
// iterate over the set and add the elements at the tail of newH
// Displaying set elements
set<int>::iterator itr;
for (itr = s.begin(); itr != s.end(); itr++)
{
insertAtTail(newH,newT,*itr);
}
return newH;
}
0
abera25831 month ago
//c++,0.3S
struct Node* makeUnion(struct Node* head1, struct Node* head2){ // code here set<int>s; struct Node*temp1=head1; struct Node*temp2=head2; while(temp1!=NULL){ s.insert(temp1->data); temp1=temp1->next; } while(temp2!=NULL){ s.insert(temp2->data); temp2=temp2->next; }Node* newnode = new Node(0);Node*head=NULL;Node*tail=NULL;for(auto value:s){ if(head==NULL){ newnode->data=value; head=newnode; tail=newnode; } else{ Node* newnode = new Node(0); newnode->data=value; tail->next=newnode; tail=newnode; }}return head; }
0
prabhatc78791 month ago
struct Node* makeUnion(struct Node* head1, struct Node* head2)
{
set<int>s;
struct Node* t=head1;
while(t){
s.insert(t->data);
t=t->next;
}
t=head2;
while(t){
s.insert(t->data);
t=t->next;
}
struct Node* dum=new Node(-1);
t=dum;
for(auto x:s){
struct Node* q=new Node(x);
t->next=q;
t=t->next;
}
return dum->next;
}
0
anshulgupta966262 months ago
SWEET AND SIMPLE
struct Node* makeUnion(struct Node* head1, struct Node* head2)
{
// code here
Node *temp1 = head1;
Node *temp2 = head2;
set<int> s1;
while(temp1 != NULL){
s1.insert(temp1->data);
temp1 = temp1->next;
}
while(temp2 != NULL){
s1.insert(temp2->data);
temp2 = temp2->next;
}
Node *new_node = new Node(0);
Node *head = NULL;
Node *tail = NULL;
set<int, greater<int> >::iterator it;
for(it = s1.begin() ; it != s1.end() ; it++){
if(head == NULL){
new_node = new Node(*it);
head = new_node;
tail = head;
}
else{
new_node = new Node(*it);
tail->next = new_node;
tail = new_node;
}
}
return head;
}
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": 415,
"s": 238,
"text": "Given two linked lists, your task is to complete the function makeUnion(), that returns the union of two linked lists. This union should include all the distinct elements only."
},
{
"code": null,
"e": 426,
"s": 415,
"text": "Example 1:"
},
{
"code": null,
"e": 497,
"s": 426,
"text": "Input:\nL1 = 9->6->4->2->3->8\nL2 = 1->2->8->6->2\nOutput: 1 2 3 4 6 8 9\n"
},
{
"code": null,
"e": 640,
"s": 497,
"text": "Your Task:\nThe task is to complete the function makeUnion() which makes the union of the given two lists and returns the head of the new list."
},
{
"code": null,
"e": 701,
"s": 640,
"text": "Note: The new list formed should be in non-decreasing order."
},
{
"code": null,
"e": 772,
"s": 701,
"text": "Expected Time Complexity: O(N * Log(N))\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 787,
"s": 772,
"text": "Constraints:\n1"
},
{
"code": null,
"e": 789,
"s": 787,
"text": "0"
},
{
"code": null,
"e": 813,
"s": 789,
"text": "singhvipnesh65 days ago"
},
{
"code": null,
"e": 1537,
"s": 813,
"text": "class Sol{public static Node findUnion(Node head1,Node head2){ HashSet<Integer>set=new HashSet<>(); Node temp1=head1; Node temp2=head2; while(temp1!=null) { if(!set.contains(temp1.data)) set.add(temp1.data); temp1=temp1.next; } while(temp2!=null) { if(!set.contains(temp2.data)) { set.add(temp2.data); } temp2=temp2.next; } ArrayList<Integer>list=new ArrayList<>(set); Node R=null,dummy=null; for(int i=0;i<list.size();i++) { Node newnode = new Node(list.get(i)); if(R == null){ R = newnode; dummy = R; } else { dummy.next=newnode; dummy=dummy.next; } } return R;}}"
},
{
"code": null,
"e": 1539,
"s": 1537,
"text": "0"
},
{
"code": null,
"e": 1560,
"s": 1539,
"text": "tthakare735 days ago"
},
{
"code": null,
"e": 2449,
"s": 1560,
"text": "//java solution -> TC -> 1.20\n//hint -> ArrayList or HashSet\n\nclass Sol{\n\tpublic static Node findUnion(Node head1,Node head2){\n\t ArrayList<Integer> union = new ArrayList<>();\n\t \n\t while(head1 != null){\n\t if(!union.contains(head1.data)) union.add(new Integer(head1.data));\n\t head1 = head1.next;\n\t }\n\t \n\t while(head2 != null){\n\t if(!union.contains(head2.data)) union.add(new Integer(head2.data));\n\t head2 = head2.next;\n\t }\n\t \n\t //sort arrayList\n\t Collections.sort(union);\n\t \n\t Node Result = null, dummy = null;\n\t for(int i = 0; i < union.size(); i++){\n\t Node newNode = new Node(union.get(i));\n\t if(Result == null){\n\t Result = newNode;\n\t dummy = Result;\n\t } else {\n\t dummy.next = newNode;\n\t dummy = dummy.next;\n\t }\n\t }\n\t \n\t return Result;\n\t}\n}"
},
{
"code": null,
"e": 2451,
"s": 2449,
"text": "0"
},
{
"code": null,
"e": 2476,
"s": 2451,
"text": "mitradiptamoy2 weeks ago"
},
{
"code": null,
"e": 2918,
"s": 2476,
"text": "//C++ Soln using SETstruct Node* makeUnion(struct Node* head1, struct Node* head2){ // code here Node* ans=new Node(-1); Node* x=ans; set<int>s; while(head1!=NULL) { s.insert(head1->data); head1=head1->next; } while(head2!=NULL) { s.insert(head2->data); head2=head2->next; } for(auto it:s) { Node* t=new Node(it); ans->next=t; ans=ans->next; } x=x->next; return x; } "
},
{
"code": null,
"e": 2920,
"s": 2918,
"text": "0"
},
{
"code": null,
"e": 2948,
"s": 2920,
"text": "harshpandeyalfa22 weeks ago"
},
{
"code": null,
"e": 2959,
"s": 2948,
"text": "(0.12 sec)"
},
{
"code": null,
"e": 3488,
"s": 2959,
"text": "struct Node* makeUnion(struct Node* head1, struct Node* head2){ unordered_map<int,int> s; Node* it=head1; while(it) { s[it->data]; it=it->next; } it=head2; while(it) { s[it->data]; it=it->next; } vector<int> q; for(auto i=s.begin() ; i!= s.end() ;i++) { q.push_back(i->first); } sort(q.begin(), q.end()); Node* h; int a=0; h=new Node(q[a]); it=h; a++; while(a!= q.size()) { Node* i=new Node(q[a]); it->next=i; it=i; a++; } "
},
{
"code": null,
"e": 3490,
"s": 3488,
"text": "0"
},
{
"code": null,
"e": 3516,
"s": 3490,
"text": "tarunlella20003 weeks ago"
},
{
"code": null,
"e": 3521,
"s": 3516,
"text": "JAVA"
},
{
"code": null,
"e": 4012,
"s": 3521,
"text": " public static Node findUnion(Node head1,Node head2){ //Add your code here. Set<Integer> s = new TreeSet<>(); while(head1 != null){ s.add(head1.data); head1 = head1.next; } while(head2 != null){ s.add(head2.data); head2 = head2.next; } Node ans = new Node(0); Node temp = ans; Iterator<Integer> i = s.iterator(); while(i.hasNext()){ ans.next = new Node(i.next()); ans = ans.next; } return temp.next; }"
},
{
"code": null,
"e": 4014,
"s": 4012,
"text": "0"
},
{
"code": null,
"e": 4034,
"s": 4014,
"text": "uday10924 weeks ago"
},
{
"code": null,
"e": 4622,
"s": 4034,
"text": "struct Node* makeUnion(struct Node* head1, struct Node* head2)\n{\n set <int> s;\n Node * t1 = head1;\n Node * t2 = head2;\n while(t1 -> next != NULL)\n {\n t1 = t1 -> next;\n }\n t1 -> next = t2;\n t1 = head1;\n \n while(t1 != NULL)\n {\n s.insert(t1 -> data);\n t1 = t1 -> next;\n }\n \n Node * tail = NULL;\n Node * head3 = NULL;\n for(int i : s)\n {\n Node * nw = new Node(i);\n if(head3 == NULL)\n head3 = tail = nw;\n else\n tail -> next = nw;\n tail = nw;\n }\n return head3;\n}"
},
{
"code": null,
"e": 4624,
"s": 4622,
"text": "0"
},
{
"code": null,
"e": 4640,
"s": 4624,
"text": "hr061 month ago"
},
{
"code": null,
"e": 5555,
"s": 4640,
"text": "void insertAtTail(struct Node* &head,struct Node* &tail,int data)\n{\n Node* node = new Node(data);\n \n if(head == NULL)\n {\n head = node;\n tail = head;\n return;\n }\n \n tail->next = node;\n tail = tail->next;\n}\nstruct Node* makeUnion(struct Node* head1, struct Node* head2)\n{\n // code here\n set<int> s;\n Node* curr = head1;\n while(curr != NULL)\n {\t\n \t // to keep only distinct elements in a sorted way\n s.insert(curr->data);\n curr = curr->next;\n }\n \n curr = head2;\n \n while(curr != NULL)\n {\n s.insert(curr->data);\n curr = curr->next;\n }\n \n Node* newH = NULL;\n Node* newT = newH;\n \n // iterate over the set and add the elements at the tail of newH\n \n // Displaying set elements\n set<int>::iterator itr;\n for (itr = s.begin(); itr != s.end(); itr++) \n {\n insertAtTail(newH,newT,*itr);\n }\n \n return newH;\n}"
},
{
"code": null,
"e": 5559,
"s": 5557,
"text": "0"
},
{
"code": null,
"e": 5580,
"s": 5559,
"text": "abera25831 month ago"
},
{
"code": null,
"e": 5591,
"s": 5580,
"text": "//c++,0.3S"
},
{
"code": null,
"e": 6222,
"s": 5591,
"text": "struct Node* makeUnion(struct Node* head1, struct Node* head2){ // code here set<int>s; struct Node*temp1=head1; struct Node*temp2=head2; while(temp1!=NULL){ s.insert(temp1->data); temp1=temp1->next; } while(temp2!=NULL){ s.insert(temp2->data); temp2=temp2->next; }Node* newnode = new Node(0);Node*head=NULL;Node*tail=NULL;for(auto value:s){ if(head==NULL){ newnode->data=value; head=newnode; tail=newnode; } else{ Node* newnode = new Node(0); newnode->data=value; tail->next=newnode; tail=newnode; }}return head; }"
},
{
"code": null,
"e": 6224,
"s": 6222,
"text": "0"
},
{
"code": null,
"e": 6248,
"s": 6224,
"text": "prabhatc78791 month ago"
},
{
"code": null,
"e": 6668,
"s": 6248,
"text": "struct Node* makeUnion(struct Node* head1, struct Node* head2)\n{\n set<int>s;\n struct Node* t=head1;\n while(t){\n s.insert(t->data);\n t=t->next;\n }\n t=head2;\n while(t){\n s.insert(t->data);\n t=t->next;\n }\n struct Node* dum=new Node(-1);\n t=dum;\n for(auto x:s){\n struct Node* q=new Node(x);\n t->next=q;\n t=t->next;\n }\n return dum->next;\n}"
},
{
"code": null,
"e": 6670,
"s": 6668,
"text": "0"
},
{
"code": null,
"e": 6699,
"s": 6670,
"text": "anshulgupta966262 months ago"
},
{
"code": null,
"e": 7504,
"s": 6699,
"text": "SWEET AND SIMPLE \nstruct Node* makeUnion(struct Node* head1, struct Node* head2)\n{\n // code here\n Node *temp1 = head1;\n Node *temp2 = head2;\n set<int> s1;\n while(temp1 != NULL){\n s1.insert(temp1->data);\n temp1 = temp1->next;\n }\n while(temp2 != NULL){\n s1.insert(temp2->data);\n temp2 = temp2->next;\n }\n Node *new_node = new Node(0);\n Node *head = NULL;\n Node *tail = NULL;\n set<int, greater<int> >::iterator it;\n for(it = s1.begin() ; it != s1.end() ; it++){\n if(head == NULL){\n new_node = new Node(*it);\n head = new_node;\n tail = head;\n }\n else{\n new_node = new Node(*it);\n tail->next = new_node;\n tail = new_node;\n }\n }\n return head;\n}\n"
},
{
"code": null,
"e": 7650,
"s": 7504,
"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": 7686,
"s": 7650,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7696,
"s": 7686,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7706,
"s": 7696,
"text": "\nContest\n"
},
{
"code": null,
"e": 7769,
"s": 7706,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7917,
"s": 7769,
"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": 8125,
"s": 7917,
"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": 8231,
"s": 8125,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C++ Map Library - end() Function
|
The C++ function std::map::end() returns an iterator which points to past-the-end element in the map.
The past-the-end element is the theoretical element that would follow the last element in the map.
Following is the declaration for std::map::end() function form std::map header.
iterator end();
const_iterator end() const;
iterator end() noexcept;
const_iterator end() const noexcept;
None
If object is constant qualified then method returns constant iterator otherwise non-constant iterator.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::map::end() function.
#include <iostream>
#include <map>
using namespace std;
int main(void) {
/* Initializer_list constructor */
map<char, int> m = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
cout << "Map contains following elements" << endl;
for (auto it = m.begin(); it != m.end(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}
Let us compile and run the above program, this will produce the following result −
Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2705,
"s": 2603,
"text": "The C++ function std::map::end() returns an iterator which points to past-the-end element in the map."
},
{
"code": null,
"e": 2804,
"s": 2705,
"text": "The past-the-end element is the theoretical element that would follow the last element in the map."
},
{
"code": null,
"e": 2884,
"s": 2804,
"text": "Following is the declaration for std::map::end() function form std::map header."
},
{
"code": null,
"e": 2929,
"s": 2884,
"text": "iterator end();\nconst_iterator end() const;\n"
},
{
"code": null,
"e": 2992,
"s": 2929,
"text": "iterator end() noexcept;\nconst_iterator end() const noexcept;\n"
},
{
"code": null,
"e": 2997,
"s": 2992,
"text": "None"
},
{
"code": null,
"e": 3100,
"s": 2997,
"text": "If object is constant qualified then method returns constant iterator otherwise non-constant iterator."
},
{
"code": null,
"e": 3145,
"s": 3100,
"text": "This member function never throws exception."
},
{
"code": null,
"e": 3164,
"s": 3145,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 3231,
"s": 3164,
"text": "The following example shows the usage of std::map::end() function."
},
{
"code": null,
"e": 3671,
"s": 3231,
"text": "#include <iostream>\n#include <map>\n\nusing namespace std;\n\nint main(void) {\n /* Initializer_list constructor */\n map<char, int> m = {\n {'a', 1},\n {'b', 2},\n {'c', 3},\n {'d', 4},\n {'e', 5},\n };\n\n cout << \"Map contains following elements\" << endl;\n\n for (auto it = m.begin(); it != m.end(); ++it)\n cout << it->first << \" = \" << it->second << endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 3754,
"s": 3671,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3817,
"s": 3754,
"text": "Map contains following elements\na = 1\nb = 2\nc = 3\nd = 4\ne = 5\n"
},
{
"code": null,
"e": 3824,
"s": 3817,
"text": " Print"
},
{
"code": null,
"e": 3835,
"s": 3824,
"text": " Add Notes"
}
] |
First Come First Serve | Practice | GeeksforGeeks
|
CodeMart is a shopping platform and it is distributing gift vouchers to its esteemed users. The voucher can be redeemed by providing a fixed amount of shopping credits to the platform. One credit is sent by a user to the platform by doing one occurance in CodeMart. Since there is a huge rush of people you are required to manage the users on the basis of first come first serve. The user which came first and has exactly k occurrences at last is given the voucher first. You are given an array arr[ ] with the id's of N users in chronological order of their occurances . You are required to print the id of the user which will be given the voucher first. If no such user meets the condition print "-1".
Example 1:
Input:
N = 7
K = 2
arr[] = {1, 7, 4, 3, 4, 8, 7}
Output: 7
Explanation: Both 7 and 4 occur 2 times.
But 7 is the first that occurs 2 times.
Example 2:
Input:
N = 6
K = 1
arr[] = {4, 1, 6, 1, 6, 4}
Output: -1
Explanation: No one occurs exactly 1 time.
Your Task:
This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function firstElement() that takes array arr, integer n and integer k as input parameters and returns the required answer.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(max(arr[i])).
Constraints:
1 ≤ N ≤ 104
1 ≤ arr[i] ≤ 103
0
abhigyanpatek2 weeks ago
Simple C++ Solution:
int firstElement(int arr[], int n, int k) { unordered_map<int, int> map; for(int i = 0; i<n; i++) map[arr[i]]++; for(int i = 0; i<n; i++) if(map[arr[i]] == k) return arr[i]; return -1; }
0
saivivekkunta22 months ago
JAVA
class Solution {
// function to find the first element
// occurring k number of times
static int firstElement(int arr[], int n, int k) {
HashMap<Integer,Integer> map = new HashMap<>();
int ans = -1;
for(int x:arr){
if(map.containsKey(x)==false)
{ map.put(x,1);}
else{
map.put(x,map.get(x)+1);
}
}
for(int x:arr){
if(map.get(x)==k){
return x;
}
}
return ans;
}
}
+1
ankitparashxr2 months ago
java
ArrayList<Integer> a = new ArrayList<>(); HashMap<Integer,Integer> hm = new HashMap<>(); for(int i:arr) { if(hm.containsKey(i)) { hm.put(i,hm.get(i)+1); } else { hm.put(i,1); } } for(int i:hm.keySet()) { if(hm.get(i)==k) { a.add(i); } } for(int i =0;i<n;i++) { if(a.contains(arr[i])) { return arr[i]; } } return -1;
+1
avinav26113 months ago
Easy C++ Solution
+1
rohanpandey7494 months ago
Easy C++ solution:
class Solution{
public:
int firstElement(int arr[], int n, int k)
{
map<int,int>mp;
for(int i=0;i<n;i++){
mp[arr[i]]++;
}
for(int i=0;i<n;i++){
if(mp.find(arr[i])!=mp.end()){
if(mp[arr[i]]==k){
return arr[i];
}
}
}
return -1;
}
};
+1
mishraadi7336 months ago
HashMap <Integer, Integer> mp = new HashMap<>(); for(int i = 0; i<n; i++){ mp.put(arr[i],mp.getOrDefault(arr[i],0)+1); } for(int i = 0; i<n; i++){ if(mp.get(arr[i]) == k){ return arr[i]; } } return -1;
0
sahil01sn6 months ago
Using HashMap
static int firstElement(int num[], int n, int k) {
HashMap<Integer , Integer> map = new HashMap<Integer , Integer>();
for(int i = 0 ; i < n ; i++){
int a = 0;
if(map.get(num[i]) != null){
a = map.get(num[i]);
}
map.put(num[i] , a + 1);
}
for(int i = 0 ; i < n ; i++){
if(map.get(num[i]) == k){
return num[i];
}
}
return -1;
}
}
0
sudhanshu gupta1 year ago
sudhanshu gupta
int firstElement(int arr[], int n, int k) { unordered_map<int ,="" int=""> occ; unordered_set<int> s; for (int i = 0; i < n; i++) occ[arr[i]]++; for (auto i: occ){ if(k == (i.second)){ s.insert(i.first); } } if(s.size()>0){ for(int i=0;i<n;i++){ if(s.find(arr[i])!="s.end()){" return="" arr[i];="" break;="" }="" }="" }="" else="" return="" -1;="" }="" <="" b="">
0
Mangalam1 year ago
Mangalam
LinkedHashMap<integer,integer> lhm= new LinkedHashMap<integer,integer>(); for(int i:arr){ if(lhm.containsKey(i)){ lhm.put(i,lhm.get(i)+1); } else lhm.put(i,1); }
for(Map.Entry<integer, integer=""> value:lhm.entrySet()){ if(value.getValue()==k){ return value.getKey(); } } return -1;
0
Hardik Gupta1 year ago
Hardik Gupta
My Approach
class GFG { static int firstElement(int arr[], int n, int k) { int max = Integer.MIN_VALUE; for(int i: arr){ max = Math.max(max , i); } int [] hash = new int[max + 1]; for(int i: arr){ hash[i]++; } for(int i = 0; i < arr.length; i++){ int x = arr[i]; if(hash[x] == k){ return x; } } return -1; }}
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": 942,
"s": 238,
"text": "CodeMart is a shopping platform and it is distributing gift vouchers to its esteemed users. The voucher can be redeemed by providing a fixed amount of shopping credits to the platform. One credit is sent by a user to the platform by doing one occurance in CodeMart. Since there is a huge rush of people you are required to manage the users on the basis of first come first serve. The user which came first and has exactly k occurrences at last is given the voucher first. You are given an array arr[ ] with the id's of N users in chronological order of their occurances . You are required to print the id of the user which will be given the voucher first. If no such user meets the condition print \"-1\"."
},
{
"code": null,
"e": 953,
"s": 942,
"text": "Example 1:"
},
{
"code": null,
"e": 1097,
"s": 953,
"text": "Input:\nN = 7 \nK = 2\narr[] = {1, 7, 4, 3, 4, 8, 7} \nOutput: 7\nExplanation: Both 7 and 4 occur 2 times.\nBut 7 is the first that occurs 2 times. "
},
{
"code": null,
"e": 1108,
"s": 1097,
"text": "Example 2:"
},
{
"code": null,
"e": 1213,
"s": 1108,
"text": "Input:\nN = 6 \nK = 1 \narr[] = {4, 1, 6, 1, 6, 4} \nOutput: -1 \nExplanation: No one occurs exactly 1 time.\n"
},
{
"code": null,
"e": 1489,
"s": 1213,
"text": "Your Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function firstElement() that takes array arr, integer n and integer k as input parameters and returns the required answer."
},
{
"code": null,
"e": 1563,
"s": 1489,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(max(arr[i]))."
},
{
"code": null,
"e": 1605,
"s": 1563,
"text": "Constraints:\n1 ≤ N ≤ 104\n1 ≤ arr[i] ≤ 103"
},
{
"code": null,
"e": 1607,
"s": 1605,
"text": "0"
},
{
"code": null,
"e": 1632,
"s": 1607,
"text": "abhigyanpatek2 weeks ago"
},
{
"code": null,
"e": 1653,
"s": 1632,
"text": "Simple C++ Solution:"
},
{
"code": null,
"e": 1868,
"s": 1653,
"text": "int firstElement(int arr[], int n, int k) { unordered_map<int, int> map; for(int i = 0; i<n; i++) map[arr[i]]++; for(int i = 0; i<n; i++) if(map[arr[i]] == k) return arr[i]; return -1; }"
},
{
"code": null,
"e": 1870,
"s": 1868,
"text": "0"
},
{
"code": null,
"e": 1897,
"s": 1870,
"text": "saivivekkunta22 months ago"
},
{
"code": null,
"e": 1903,
"s": 1897,
"text": "JAVA "
},
{
"code": null,
"e": 2310,
"s": 1903,
"text": "class Solution { \n \n// function to find the first element \n// occurring k number of times \n static int firstElement(int arr[], int n, int k) { \nHashMap<Integer,Integer> map = new HashMap<>();\nint ans = -1;\nfor(int x:arr){\n if(map.containsKey(x)==false)\n { map.put(x,1);}\n else{\n map.put(x,map.get(x)+1);\n }\n}\nfor(int x:arr){\n if(map.get(x)==k){\n return x;\n }\n}\nreturn ans;\n }\n}"
},
{
"code": null,
"e": 2315,
"s": 2312,
"text": "+1"
},
{
"code": null,
"e": 2341,
"s": 2315,
"text": "ankitparashxr2 months ago"
},
{
"code": null,
"e": 2346,
"s": 2341,
"text": "java"
},
{
"code": null,
"e": 2855,
"s": 2346,
"text": " ArrayList<Integer> a = new ArrayList<>(); HashMap<Integer,Integer> hm = new HashMap<>(); for(int i:arr) { if(hm.containsKey(i)) { hm.put(i,hm.get(i)+1); } else { hm.put(i,1); } } for(int i:hm.keySet()) { if(hm.get(i)==k) { a.add(i); } } for(int i =0;i<n;i++) { if(a.contains(arr[i])) { return arr[i]; } } return -1;"
},
{
"code": null,
"e": 2858,
"s": 2855,
"text": "+1"
},
{
"code": null,
"e": 2881,
"s": 2858,
"text": "avinav26113 months ago"
},
{
"code": null,
"e": 2899,
"s": 2881,
"text": "Easy C++ Solution"
},
{
"code": null,
"e": 2904,
"s": 2901,
"text": "+1"
},
{
"code": null,
"e": 2931,
"s": 2904,
"text": "rohanpandey7494 months ago"
},
{
"code": null,
"e": 2950,
"s": 2931,
"text": "Easy C++ solution:"
},
{
"code": null,
"e": 3333,
"s": 2950,
"text": "class Solution{\n public:\n int firstElement(int arr[], int n, int k)\n {\n map<int,int>mp;\n for(int i=0;i<n;i++){\n mp[arr[i]]++;\n }\n for(int i=0;i<n;i++){\n if(mp.find(arr[i])!=mp.end()){\n if(mp[arr[i]]==k){\n return arr[i];\n }\n }\n }\n return -1;\n }\n};"
},
{
"code": null,
"e": 3336,
"s": 3333,
"text": "+1"
},
{
"code": null,
"e": 3361,
"s": 3336,
"text": "mishraadi7336 months ago"
},
{
"code": null,
"e": 3647,
"s": 3365,
"text": " HashMap <Integer, Integer> mp = new HashMap<>(); for(int i = 0; i<n; i++){ mp.put(arr[i],mp.getOrDefault(arr[i],0)+1); } for(int i = 0; i<n; i++){ if(mp.get(arr[i]) == k){ return arr[i]; } } return -1; "
},
{
"code": null,
"e": 3649,
"s": 3647,
"text": "0"
},
{
"code": null,
"e": 3671,
"s": 3649,
"text": "sahil01sn6 months ago"
},
{
"code": null,
"e": 3686,
"s": 3671,
"text": "Using HashMap "
},
{
"code": null,
"e": 4218,
"s": 3686,
"text": " static int firstElement(int num[], int n, int k) { \n HashMap<Integer , Integer> map = new HashMap<Integer , Integer>();\n \n for(int i = 0 ; i < n ; i++){\n int a = 0;\n if(map.get(num[i]) != null){\n a = map.get(num[i]);\n }\n map.put(num[i] , a + 1);\n }\n \n for(int i = 0 ; i < n ; i++){\n if(map.get(num[i]) == k){\n return num[i];\n }\n }\n return -1;\n \n \n \n }\n}"
},
{
"code": null,
"e": 4222,
"s": 4220,
"text": "0"
},
{
"code": null,
"e": 4248,
"s": 4222,
"text": "sudhanshu gupta1 year ago"
},
{
"code": null,
"e": 4264,
"s": 4248,
"text": "sudhanshu gupta"
},
{
"code": null,
"e": 4733,
"s": 4264,
"text": "int firstElement(int arr[], int n, int k) { unordered_map<int ,=\"\" int=\"\"> occ; unordered_set<int> s; for (int i = 0; i < n; i++) occ[arr[i]]++; for (auto i: occ){ if(k == (i.second)){ s.insert(i.first); } } if(s.size()>0){ for(int i=0;i<n;i++){ if(s.find(arr[i])!=\"s.end()){\" return=\"\" arr[i];=\"\" break;=\"\" }=\"\" }=\"\" }=\"\" else=\"\" return=\"\" -1;=\"\" }=\"\" <=\"\" b=\"\">"
},
{
"code": null,
"e": 4735,
"s": 4733,
"text": "0"
},
{
"code": null,
"e": 4754,
"s": 4735,
"text": "Mangalam1 year ago"
},
{
"code": null,
"e": 4763,
"s": 4754,
"text": "Mangalam"
},
{
"code": null,
"e": 4999,
"s": 4763,
"text": "LinkedHashMap<integer,integer> lhm= new LinkedHashMap<integer,integer>(); for(int i:arr){ if(lhm.containsKey(i)){ lhm.put(i,lhm.get(i)+1); } else lhm.put(i,1); }"
},
{
"code": null,
"e": 5176,
"s": 4999,
"text": " for(Map.Entry<integer, integer=\"\"> value:lhm.entrySet()){ if(value.getValue()==k){ return value.getKey(); } } return -1;"
},
{
"code": null,
"e": 5178,
"s": 5176,
"text": "0"
},
{
"code": null,
"e": 5201,
"s": 5178,
"text": "Hardik Gupta1 year ago"
},
{
"code": null,
"e": 5214,
"s": 5201,
"text": "Hardik Gupta"
},
{
"code": null,
"e": 5226,
"s": 5214,
"text": "My Approach"
},
{
"code": null,
"e": 5608,
"s": 5226,
"text": "class GFG { static int firstElement(int arr[], int n, int k) { int max = Integer.MIN_VALUE; for(int i: arr){ max = Math.max(max , i); } int [] hash = new int[max + 1]; for(int i: arr){ hash[i]++; } for(int i = 0; i < arr.length; i++){ int x = arr[i]; if(hash[x] == k){ return x; } } return -1; }}"
},
{
"code": null,
"e": 5754,
"s": 5608,
"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": 5790,
"s": 5754,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5800,
"s": 5790,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5810,
"s": 5800,
"text": "\nContest\n"
},
{
"code": null,
"e": 5873,
"s": 5810,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6021,
"s": 5873,
"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": 6229,
"s": 6021,
"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": 6335,
"s": 6229,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Arduino – base64 encode and decode
|
Arduino contains a library that helps with base64 encode and decode. You can download it from the Library Manager. Search for base64, and install the library by Densaugeo.
Now, open a new sketch and run the following sample code −
#include "base64.hpp"
unsigned char normal_text[20] = "Hello World";
unsigned char base64_text[20];
unsigned char decoded_text[20];
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
int base64_length = encode_base64(normal_text,12,base64_text);
Serial.print("Base64 Text: ");Serial.println((char *) base64_text);
Serial.print("Base64 Length: ");Serial.println(base64_length);
int decoded_length = decode_base64(base64_text,decoded_text);
Serial.print("Decoded Text: ");Serial.println((char *)decoded_text);
Serial.print("Decoded Length: ");Serial.println(decoded_length);
}
void loop() {
// put your main code here, to run repeatedly:
}
The Serial Monitor Output is shown below −
You can verify this output on websites like: https://base64.guru/converter/decode
As you can see, this library deals with unsigned character arrays. The base64_encode function takes three arguments −
The array to be converted
The array to be converted
The number of elements in the array to be converted
The number of elements in the array to be converted
The array in which to store the encoded values
The array in which to store the encoded values
It returns the length of the encoded array.
The base64_decode function takes in two arguments −
The array containing the encoded values
The array containing the encoded values
The array in which to store the decoded results
The array in which to store the decoded results
Since Serial.print() and its variations don't deal with unsigned char arrays, you need to cast it to a char array for printing.
|
[
{
"code": null,
"e": 1234,
"s": 1062,
"text": "Arduino contains a library that helps with base64 encode and decode. You can download it from the Library Manager. Search for base64, and install the library by Densaugeo."
},
{
"code": null,
"e": 1293,
"s": 1234,
"text": "Now, open a new sketch and run the following sample code −"
},
{
"code": null,
"e": 2010,
"s": 1293,
"text": "#include \"base64.hpp\"\n\nunsigned char normal_text[20] = \"Hello World\";\nunsigned char base64_text[20];\nunsigned char decoded_text[20];\n\nvoid setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n int base64_length = encode_base64(normal_text,12,base64_text);\n Serial.print(\"Base64 Text: \");Serial.println((char *) base64_text);\n Serial.print(\"Base64 Length: \");Serial.println(base64_length);\n\n int decoded_length = decode_base64(base64_text,decoded_text);\n Serial.print(\"Decoded Text: \");Serial.println((char *)decoded_text);\n Serial.print(\"Decoded Length: \");Serial.println(decoded_length);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 2053,
"s": 2010,
"text": "The Serial Monitor Output is shown below −"
},
{
"code": null,
"e": 2135,
"s": 2053,
"text": "You can verify this output on websites like: https://base64.guru/converter/decode"
},
{
"code": null,
"e": 2253,
"s": 2135,
"text": "As you can see, this library deals with unsigned character arrays. The base64_encode function takes three arguments −"
},
{
"code": null,
"e": 2279,
"s": 2253,
"text": "The array to be converted"
},
{
"code": null,
"e": 2305,
"s": 2279,
"text": "The array to be converted"
},
{
"code": null,
"e": 2357,
"s": 2305,
"text": "The number of elements in the array to be converted"
},
{
"code": null,
"e": 2409,
"s": 2357,
"text": "The number of elements in the array to be converted"
},
{
"code": null,
"e": 2456,
"s": 2409,
"text": "The array in which to store the encoded values"
},
{
"code": null,
"e": 2503,
"s": 2456,
"text": "The array in which to store the encoded values"
},
{
"code": null,
"e": 2547,
"s": 2503,
"text": "It returns the length of the encoded array."
},
{
"code": null,
"e": 2599,
"s": 2547,
"text": "The base64_decode function takes in two arguments −"
},
{
"code": null,
"e": 2639,
"s": 2599,
"text": "The array containing the encoded values"
},
{
"code": null,
"e": 2679,
"s": 2639,
"text": "The array containing the encoded values"
},
{
"code": null,
"e": 2727,
"s": 2679,
"text": "The array in which to store the decoded results"
},
{
"code": null,
"e": 2775,
"s": 2727,
"text": "The array in which to store the decoded results"
},
{
"code": null,
"e": 2903,
"s": 2775,
"text": "Since Serial.print() and its variations don't deal with unsigned char arrays, you need to cast it to a char array for printing."
}
] |
How to set the text direction with JavaScript?
|
To set the text direction, use the direction property with JavaScript. Set rtl for right-to-left or ltr for left-to-right text direction.
You can try to run the following code to set the text direction with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h1 id="myID">Heading 1</h1>
<p>Click below to set the direction of heading to Left-to-right</p>
<button type="button" onclick="display()">Click to change the direction</button>
<script>
function display() {
document.getElementById("myID").style.direction = "rtl";
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1200,
"s": 1062,
"text": "To set the text direction, use the direction property with JavaScript. Set rtl for right-to-left or ltr for left-to-right text direction."
},
{
"code": null,
"e": 1282,
"s": 1200,
"text": "You can try to run the following code to set the text direction with JavaScript −"
},
{
"code": null,
"e": 1292,
"s": 1282,
"text": "Live Demo"
},
{
"code": null,
"e": 1681,
"s": 1292,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <h1 id=\"myID\">Heading 1</h1>\n <p>Click below to set the direction of heading to Left-to-right</p>\n <button type=\"button\" onclick=\"display()\">Click to change the direction</button>\n <script>\n function display() {\n document.getElementById(\"myID\").style.direction = \"rtl\";\n }\n </script>\n </body>\n</html>"
}
] |
How can a binary semaphore implement mutual exclusion among n processes?
|
A semaphore is a shared variable which is used to implement mutual exclusion between
system processes. It is mainly helpful to solve critical section problems and is a
technique to achieve process synchronization.
Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1.
Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1.
Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N.
Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N.
P(s)
P(s)
CS
CS
V(s)
V(s)
Each of these operations is defined below −
Wait(P) − Whenever a process enters into CS, first it executes P operation where it decreases semaphore value and if after that s>=0 then enters into CS otherwise added to the waiting queue.
P(Semaphore s)
{
s = s - 1;
if (s < 0) {
block(p);
}
}
Signal(V) − When a process exists CS operation V is performed which increases the value of semaphore indicating another process can enter into CS which is currently blocked by P operation.
V(Semaphore s)
{
s = s + 1;
if (s >= 0) {
wakeup(p);
}
}
Now let see how binary semaphore can be used to implement mutual exclusion among n
processes.
We know that semaphore is a variable that can be used to control access by multiple
processes to a common resource in multitasking OS. As per the question suppose if there are
n processes that commonly share a semaphore to each process then process allocation
is organized based on the following algorithm.
do {
wait(mutex);
signal(mutex);
} while (true);
It is processed using a do-while loop that means it performs 'do' conditions until we get
satisfied while condition.
Here it performs wait and signal operations of mutex until it becomes true.
|
[
{
"code": null,
"e": 1276,
"s": 1062,
"text": "A semaphore is a shared variable which is used to implement mutual exclusion between\nsystem processes. It is mainly helpful to solve critical section problems and is a\ntechnique to achieve process synchronization."
},
{
"code": null,
"e": 1435,
"s": 1276,
"text": "Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1."
},
{
"code": null,
"e": 1594,
"s": 1435,
"text": "Binary semaphore − Can take only two values, 0 or 1 which means at a time only one process can enter into the critical section. Semaphore is initialized to 1."
},
{
"code": null,
"e": 1741,
"s": 1594,
"text": "Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N."
},
{
"code": null,
"e": 1888,
"s": 1741,
"text": "Counting semaphore − Can take any non-negative value N which means at a time at most N processes can enter into CS. Semaphore is initialized to N."
},
{
"code": null,
"e": 1893,
"s": 1888,
"text": "P(s)"
},
{
"code": null,
"e": 1898,
"s": 1893,
"text": "P(s)"
},
{
"code": null,
"e": 1901,
"s": 1898,
"text": "CS"
},
{
"code": null,
"e": 1904,
"s": 1901,
"text": "CS"
},
{
"code": null,
"e": 1909,
"s": 1904,
"text": "V(s)"
},
{
"code": null,
"e": 1914,
"s": 1909,
"text": "V(s)"
},
{
"code": null,
"e": 1958,
"s": 1914,
"text": "Each of these operations is defined below −"
},
{
"code": null,
"e": 2149,
"s": 1958,
"text": "Wait(P) − Whenever a process enters into CS, first it executes P operation where it decreases semaphore value and if after that s>=0 then enters into CS otherwise added to the waiting queue."
},
{
"code": null,
"e": 2219,
"s": 2149,
"text": "P(Semaphore s)\n{\n s = s - 1;\n if (s < 0) {\n block(p);\n }\n}"
},
{
"code": null,
"e": 2408,
"s": 2219,
"text": "Signal(V) − When a process exists CS operation V is performed which increases the value of semaphore indicating another process can enter into CS which is currently blocked by P operation."
},
{
"code": null,
"e": 2480,
"s": 2408,
"text": "V(Semaphore s)\n{\n s = s + 1;\n if (s >= 0) {\n wakeup(p);\n }\n}"
},
{
"code": null,
"e": 2574,
"s": 2480,
"text": "Now let see how binary semaphore can be used to implement mutual exclusion among n\nprocesses."
},
{
"code": null,
"e": 2881,
"s": 2574,
"text": "We know that semaphore is a variable that can be used to control access by multiple\nprocesses to a common resource in multitasking OS. As per the question suppose if there are\nn processes that commonly share a semaphore to each process then process allocation\nis organized based on the following algorithm."
},
{
"code": null,
"e": 2936,
"s": 2881,
"text": "do {\n wait(mutex);\n signal(mutex);\n} while (true);"
},
{
"code": null,
"e": 3053,
"s": 2936,
"text": "It is processed using a do-while loop that means it performs 'do' conditions until we get\nsatisfied while condition."
},
{
"code": null,
"e": 3129,
"s": 3053,
"text": "Here it performs wait and signal operations of mutex until it becomes true."
}
] |
How to do exponential and logarithmic curve fitting in Python?
|
21 Apr, 2021
In this article, we will learn how to do exponential and logarithmic curve fitting in Python. Firstly the question comes to our mind What is curve fitting?
Curve fitting is the process of constructing a curve or mathematical function, that has the best fit to a series of data points, possibly subject to constraints.
Logarithmic curve fitting: The logarithmic curve is the plot of the logarithmic function.
Exponential curve fitting: The exponential curve is the plot of the exponential function.
Let us consider two equations
y = alog(x) + b where a ,b are coefficients of that logarithmic equation.
y = e(ax)*e(b) where a ,b are coefficients of that exponential equation.
We will be fitting both curves on the above equation and find the best fit curve for it. For curve fitting in Python, we will be using some library functions
numpy
matplotlib.pyplot
We would also use numpy.polyfit() method for fitting the curve. This function takes on three parameters x, y and the polynomial degree(n) returns coefficients of nth degree polynomial.
Syntax: numpy.polyfit(x, y, deg)
Parameters:
x->x-coordinates
y->y-coordinates
deg -> Degree of the fitting polynomial. So, if deg is given one we get coefficients of linear polynomial or if it is 2 we get coefficients of a quadratic polynomial.
To do Logarithmic curve fitting, we have to follow some steps which are explained below with the implementation.
Python
import numpy as np # It is for ploting the curveimport matplotlib.pyplot as plt
As we have imported the required libraries we have to create two arrays named x and y. And after creating those two arrays we have to take the log of the values in x and y with the help of numpy.log() method.
Python3
# Points on X-axisx_data = np.array([11, 23, 31, 43, 51]) # Points on Y-axisy_data = np.array([2, 4, 6, 8, 10]) print(x_data)print(y_data) # Taking log of x valuesxlog_data = np.log(x_data) print(xlog_data)
Output:
After, getting the log values of x and y arrays, With the help of numpy.polyfit() we find the coefficient for our equation. As we took a linear equation hence in polyfit method we will pass 1 in degree parameter.
Python3
# Given log values of x , y as inputcurve = np.polyfit(log_x_data, y_data, 1) print(curve)
Output:
So we get the coefficients as [5.04, -10.79] with that we can get the equation of the curve which would be (y= a*log(x)+y, where a,b are coefficient)
y = 5.04*log(x) - 10.79
Python3
y = 5.04 * log_x_data - 10.79 print(y)
Output:
Now, let’s plot the graphs one with xlog_data, ylog_data, and another with xlog_data and y equation which we have obtained. For plotting graphs in python, we will take the help of Matplotlib.pyplot.plot() function.
Syntax: matplotlib.pyplot.plot(x-coordinates, y-coordinates)
Parameters:
x: horizontal coordinates of the data points
y: vertical coordinates of the data points
Python3
# Blue colorplt.plot(log_x_data, y_data) # Best fit in orangeplt.plot(log_x_data, y)
Output:
In the above graph yellow line represents the graph of original x and y coordinates and the blue line is the graph of coordinates that we have obtained through our calculations, and it is the best fit.
We will be repeating the same process as above, but the only difference is the logarithmic function is replaced by the exponential function.
First, let us create the data points
Python3
x_data = np.array([11, 19, 31, 39, 51])print(x_data) y_data = np.array([5, 8, 32, 84, 110])print(y_data)
Output:
Equation: y = e(ax)*e(b)
In this equation we will plot the graph and the a, b are coefficients which we can be obtained with numpy.polyfit() method. Now lets us find the coefficients of exponential function with degree .
Python3
ylog_data = np.log(y_data)print(ylog_data) curve_fit = np.polyfit(x_data, log_y_data, 1)print(curve_fit)
Output:
So, a = 0.69 and b = 0.085 these are the coefficients we can get the equation of the curve which would be (y = e(ax)*e(b), where a, b are coefficient)
y = e(0.69x)*e(0.085) final equation.
Python3
y = np.exp(0.69) * np.exp(0.085*x_data) print(y)
Output:
Now, let us plot the graphs with the help of Matplotlib.pyplot.plot() function.
Python3
# Blue plt.plot(x_data, y_data) # best fit in orangeplt.plot(x_data, y)
Output:
In the above graph blue line represents the graph of original x and y coordinates and the orange line is the graph of coordinates that we have obtained through our calculations, and it is the best fit.
Hence, this is the process of fitting exponential and logarithmic curves in Python with the help of NumPy and matplotlib.
Picked
Python-matplotlib
Python-numpy
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 184,
"s": 28,
"text": "In this article, we will learn how to do exponential and logarithmic curve fitting in Python. Firstly the question comes to our mind What is curve fitting?"
},
{
"code": null,
"e": 346,
"s": 184,
"text": "Curve fitting is the process of constructing a curve or mathematical function, that has the best fit to a series of data points, possibly subject to constraints."
},
{
"code": null,
"e": 436,
"s": 346,
"text": "Logarithmic curve fitting: The logarithmic curve is the plot of the logarithmic function."
},
{
"code": null,
"e": 526,
"s": 436,
"text": "Exponential curve fitting: The exponential curve is the plot of the exponential function."
},
{
"code": null,
"e": 557,
"s": 526,
"text": "Let us consider two equations "
},
{
"code": null,
"e": 632,
"s": 557,
"text": "y = alog(x) + b where a ,b are coefficients of that logarithmic equation."
},
{
"code": null,
"e": 708,
"s": 632,
"text": "y = e(ax)*e(b) where a ,b are coefficients of that exponential equation."
},
{
"code": null,
"e": 866,
"s": 708,
"text": "We will be fitting both curves on the above equation and find the best fit curve for it. For curve fitting in Python, we will be using some library functions"
},
{
"code": null,
"e": 872,
"s": 866,
"text": "numpy"
},
{
"code": null,
"e": 890,
"s": 872,
"text": "matplotlib.pyplot"
},
{
"code": null,
"e": 1075,
"s": 890,
"text": "We would also use numpy.polyfit() method for fitting the curve. This function takes on three parameters x, y and the polynomial degree(n) returns coefficients of nth degree polynomial."
},
{
"code": null,
"e": 1108,
"s": 1075,
"text": "Syntax: numpy.polyfit(x, y, deg)"
},
{
"code": null,
"e": 1120,
"s": 1108,
"text": "Parameters:"
},
{
"code": null,
"e": 1137,
"s": 1120,
"text": "x->x-coordinates"
},
{
"code": null,
"e": 1154,
"s": 1137,
"text": "y->y-coordinates"
},
{
"code": null,
"e": 1321,
"s": 1154,
"text": "deg -> Degree of the fitting polynomial. So, if deg is given one we get coefficients of linear polynomial or if it is 2 we get coefficients of a quadratic polynomial."
},
{
"code": null,
"e": 1434,
"s": 1321,
"text": "To do Logarithmic curve fitting, we have to follow some steps which are explained below with the implementation."
},
{
"code": null,
"e": 1441,
"s": 1434,
"text": "Python"
},
{
"code": "import numpy as np # It is for ploting the curveimport matplotlib.pyplot as plt",
"e": 1522,
"s": 1441,
"text": null
},
{
"code": null,
"e": 1731,
"s": 1522,
"text": "As we have imported the required libraries we have to create two arrays named x and y. And after creating those two arrays we have to take the log of the values in x and y with the help of numpy.log() method."
},
{
"code": null,
"e": 1739,
"s": 1731,
"text": "Python3"
},
{
"code": "# Points on X-axisx_data = np.array([11, 23, 31, 43, 51]) # Points on Y-axisy_data = np.array([2, 4, 6, 8, 10]) print(x_data)print(y_data) # Taking log of x valuesxlog_data = np.log(x_data) print(xlog_data)",
"e": 1969,
"s": 1739,
"text": null
},
{
"code": null,
"e": 1977,
"s": 1969,
"text": "Output:"
},
{
"code": null,
"e": 2190,
"s": 1977,
"text": "After, getting the log values of x and y arrays, With the help of numpy.polyfit() we find the coefficient for our equation. As we took a linear equation hence in polyfit method we will pass 1 in degree parameter."
},
{
"code": null,
"e": 2198,
"s": 2190,
"text": "Python3"
},
{
"code": "# Given log values of x , y as inputcurve = np.polyfit(log_x_data, y_data, 1) print(curve)",
"e": 2290,
"s": 2198,
"text": null
},
{
"code": null,
"e": 2298,
"s": 2290,
"text": "Output:"
},
{
"code": null,
"e": 2449,
"s": 2298,
"text": "So we get the coefficients as [5.04, -10.79] with that we can get the equation of the curve which would be (y= a*log(x)+y, where a,b are coefficient)"
},
{
"code": null,
"e": 2473,
"s": 2449,
"text": "y = 5.04*log(x) - 10.79"
},
{
"code": null,
"e": 2481,
"s": 2473,
"text": "Python3"
},
{
"code": "y = 5.04 * log_x_data - 10.79 print(y)",
"e": 2523,
"s": 2481,
"text": null
},
{
"code": null,
"e": 2531,
"s": 2523,
"text": "Output:"
},
{
"code": null,
"e": 2746,
"s": 2531,
"text": "Now, let’s plot the graphs one with xlog_data, ylog_data, and another with xlog_data and y equation which we have obtained. For plotting graphs in python, we will take the help of Matplotlib.pyplot.plot() function."
},
{
"code": null,
"e": 2807,
"s": 2746,
"text": "Syntax: matplotlib.pyplot.plot(x-coordinates, y-coordinates)"
},
{
"code": null,
"e": 2819,
"s": 2807,
"text": "Parameters:"
},
{
"code": null,
"e": 2864,
"s": 2819,
"text": "x: horizontal coordinates of the data points"
},
{
"code": null,
"e": 2907,
"s": 2864,
"text": "y: vertical coordinates of the data points"
},
{
"code": null,
"e": 2915,
"s": 2907,
"text": "Python3"
},
{
"code": "# Blue colorplt.plot(log_x_data, y_data) # Best fit in orangeplt.plot(log_x_data, y)",
"e": 3001,
"s": 2915,
"text": null
},
{
"code": null,
"e": 3009,
"s": 3001,
"text": "Output:"
},
{
"code": null,
"e": 3211,
"s": 3009,
"text": "In the above graph yellow line represents the graph of original x and y coordinates and the blue line is the graph of coordinates that we have obtained through our calculations, and it is the best fit."
},
{
"code": null,
"e": 3352,
"s": 3211,
"text": "We will be repeating the same process as above, but the only difference is the logarithmic function is replaced by the exponential function."
},
{
"code": null,
"e": 3389,
"s": 3352,
"text": "First, let us create the data points"
},
{
"code": null,
"e": 3397,
"s": 3389,
"text": "Python3"
},
{
"code": "x_data = np.array([11, 19, 31, 39, 51])print(x_data) y_data = np.array([5, 8, 32, 84, 110])print(y_data)",
"e": 3503,
"s": 3397,
"text": null
},
{
"code": null,
"e": 3511,
"s": 3503,
"text": "Output:"
},
{
"code": null,
"e": 3536,
"s": 3511,
"text": "Equation: y = e(ax)*e(b)"
},
{
"code": null,
"e": 3732,
"s": 3536,
"text": "In this equation we will plot the graph and the a, b are coefficients which we can be obtained with numpy.polyfit() method. Now lets us find the coefficients of exponential function with degree ."
},
{
"code": null,
"e": 3740,
"s": 3732,
"text": "Python3"
},
{
"code": "ylog_data = np.log(y_data)print(ylog_data) curve_fit = np.polyfit(x_data, log_y_data, 1)print(curve_fit)",
"e": 3846,
"s": 3740,
"text": null
},
{
"code": null,
"e": 3854,
"s": 3846,
"text": "Output:"
},
{
"code": null,
"e": 4005,
"s": 3854,
"text": "So, a = 0.69 and b = 0.085 these are the coefficients we can get the equation of the curve which would be (y = e(ax)*e(b), where a, b are coefficient)"
},
{
"code": null,
"e": 4045,
"s": 4005,
"text": "y = e(0.69x)*e(0.085) final equation. "
},
{
"code": null,
"e": 4053,
"s": 4045,
"text": "Python3"
},
{
"code": "y = np.exp(0.69) * np.exp(0.085*x_data) print(y)",
"e": 4103,
"s": 4053,
"text": null
},
{
"code": null,
"e": 4111,
"s": 4103,
"text": "Output:"
},
{
"code": null,
"e": 4191,
"s": 4111,
"text": "Now, let us plot the graphs with the help of Matplotlib.pyplot.plot() function."
},
{
"code": null,
"e": 4199,
"s": 4191,
"text": "Python3"
},
{
"code": "# Blue plt.plot(x_data, y_data) # best fit in orangeplt.plot(x_data, y)",
"e": 4272,
"s": 4199,
"text": null
},
{
"code": null,
"e": 4280,
"s": 4272,
"text": "Output:"
},
{
"code": null,
"e": 4482,
"s": 4280,
"text": "In the above graph blue line represents the graph of original x and y coordinates and the orange line is the graph of coordinates that we have obtained through our calculations, and it is the best fit."
},
{
"code": null,
"e": 4604,
"s": 4482,
"text": "Hence, this is the process of fitting exponential and logarithmic curves in Python with the help of NumPy and matplotlib."
},
{
"code": null,
"e": 4611,
"s": 4604,
"text": "Picked"
},
{
"code": null,
"e": 4629,
"s": 4611,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 4642,
"s": 4629,
"text": "Python-numpy"
},
{
"code": null,
"e": 4659,
"s": 4642,
"text": "Machine Learning"
},
{
"code": null,
"e": 4666,
"s": 4659,
"text": "Python"
},
{
"code": null,
"e": 4683,
"s": 4666,
"text": "Machine Learning"
},
{
"code": null,
"e": 4781,
"s": 4683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4822,
"s": 4781,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 4855,
"s": 4822,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4891,
"s": 4855,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4915,
"s": 4891,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4966,
"s": 4915,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 4994,
"s": 4966,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5016,
"s": 4994,
"text": "Python map() function"
},
{
"code": null,
"e": 5066,
"s": 5016,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5084,
"s": 5066,
"text": "Python Dictionary"
}
] |
How to Create a File in the Linux Using the Terminal?
|
09 Apr, 2021
In this article, we will learn to create a file in the Linux/Unix system using the terminal. In the Linux/Unix system, there are the following ways available to creating files.
Using the touch commandUsing the cat commandUsing redirection operatorUsing the echo commandUsing the heredocUsing the dd command
Using the touch command
Using the cat command
Using redirection operator
Using the echo command
Using the heredoc
Using the dd command
The touch command is used to create file/files without any content and update the access date or modification date of a file or directory in the Linux system. This is the simplest way to create a file in Linux/Unix using the terminal.
Syntax:
The general syntax of the touch command is as follows:
$ touch [option] ... FILE...
A brief description of options available in the touch command.
In this example, using the touch command we can create a file in the Linux system. Before executing the touch command, we will check that how many files available in our current directory using the below command.
$ ls -l
After using the below command a new file created newfile.txt in the current directory.
Example :
$ touch newfile.txt
To ensure that the file is created or not we will again execute the ls command to list the directory contents.
The cat (concatenate) command is used to create, view, concatenate files in the Linux operating system. The touch command is also used to create a file in a Linux system without content whereas the cat creates files with some content. The cat command reads the content of a file and prompts it.
The general syntax of the cat command is as follows:
$ cat [option]... FILE...
A brief description of options available in the cat command.
To create a file with some content, we use the cat command and file name after that write some content and press CTRL + C when writing is complete as shown below.
$ cat > file.txt
The cat command is also used to view the contents of the file. After using the cat command along with the file name contents of the file will be prompt as shown below.
In the Linux/Unix system a redirection operator is also used to create a file.
$ > file.txt
The echo command is also used to create a new file in the Linux system.
To create a file without contents, we use the echo command with a redirection operator followed by the file name as shown below.
$ echo > file.txt
To create a file with some contents, we use the echo command followed by the text, a redirection operator, and the file name as shown below.
heredoc stands for here document. The heredoc delimiter is a type of redirection. It allows passing multiple lines of input to a command.
The general syntax of heredoc. Important
Command << Heredoc_delimiter
multiple lines contents...
heredoc_delimiter
To create a file using heredoc, we use the cat command with heredoc delimiter in the Linux system as shown below.
$ cat << heredoc_delimiter < file_name
The dd command is mainly used to converts and copy files. To check more details about the dd command. We can also create a large file using the dd command.
To create a large file, we use the dd command as shown below.
$ dd if = /dev/zero of = file.test bs =1 count =0 seek = 2G
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 232,
"s": 54,
"text": "In this article, we will learn to create a file in the Linux/Unix system using the terminal. In the Linux/Unix system, there are the following ways available to creating files. "
},
{
"code": null,
"e": 362,
"s": 232,
"text": "Using the touch commandUsing the cat commandUsing redirection operatorUsing the echo commandUsing the heredocUsing the dd command"
},
{
"code": null,
"e": 386,
"s": 362,
"text": "Using the touch command"
},
{
"code": null,
"e": 408,
"s": 386,
"text": "Using the cat command"
},
{
"code": null,
"e": 435,
"s": 408,
"text": "Using redirection operator"
},
{
"code": null,
"e": 458,
"s": 435,
"text": "Using the echo command"
},
{
"code": null,
"e": 476,
"s": 458,
"text": "Using the heredoc"
},
{
"code": null,
"e": 497,
"s": 476,
"text": "Using the dd command"
},
{
"code": null,
"e": 733,
"s": 497,
"text": "The touch command is used to create file/files without any content and update the access date or modification date of a file or directory in the Linux system. This is the simplest way to create a file in Linux/Unix using the terminal. "
},
{
"code": null,
"e": 741,
"s": 733,
"text": "Syntax:"
},
{
"code": null,
"e": 796,
"s": 741,
"text": "The general syntax of the touch command is as follows:"
},
{
"code": null,
"e": 825,
"s": 796,
"text": "$ touch [option] ... FILE..."
},
{
"code": null,
"e": 888,
"s": 825,
"text": "A brief description of options available in the touch command."
},
{
"code": null,
"e": 1101,
"s": 888,
"text": "In this example, using the touch command we can create a file in the Linux system. Before executing the touch command, we will check that how many files available in our current directory using the below command."
},
{
"code": null,
"e": 1109,
"s": 1101,
"text": "$ ls -l"
},
{
"code": null,
"e": 1196,
"s": 1109,
"text": "After using the below command a new file created newfile.txt in the current directory."
},
{
"code": null,
"e": 1207,
"s": 1196,
"text": "Example : "
},
{
"code": null,
"e": 1227,
"s": 1207,
"text": "$ touch newfile.txt"
},
{
"code": null,
"e": 1340,
"s": 1227,
"text": "To ensure that the file is created or not we will again execute the ls command to list the directory contents. "
},
{
"code": null,
"e": 1636,
"s": 1340,
"text": "The cat (concatenate) command is used to create, view, concatenate files in the Linux operating system. The touch command is also used to create a file in a Linux system without content whereas the cat creates files with some content. The cat command reads the content of a file and prompts it. "
},
{
"code": null,
"e": 1689,
"s": 1636,
"text": "The general syntax of the cat command is as follows:"
},
{
"code": null,
"e": 1715,
"s": 1689,
"text": "$ cat [option]... FILE..."
},
{
"code": null,
"e": 1776,
"s": 1715,
"text": "A brief description of options available in the cat command."
},
{
"code": null,
"e": 1939,
"s": 1776,
"text": "To create a file with some content, we use the cat command and file name after that write some content and press CTRL + C when writing is complete as shown below."
},
{
"code": null,
"e": 1956,
"s": 1939,
"text": "$ cat > file.txt"
},
{
"code": null,
"e": 2124,
"s": 1956,
"text": "The cat command is also used to view the contents of the file. After using the cat command along with the file name contents of the file will be prompt as shown below."
},
{
"code": null,
"e": 2204,
"s": 2124,
"text": "In the Linux/Unix system a redirection operator is also used to create a file. "
},
{
"code": null,
"e": 2218,
"s": 2204,
"text": "$ > file.txt"
},
{
"code": null,
"e": 2291,
"s": 2218,
"text": "The echo command is also used to create a new file in the Linux system. "
},
{
"code": null,
"e": 2420,
"s": 2291,
"text": "To create a file without contents, we use the echo command with a redirection operator followed by the file name as shown below."
},
{
"code": null,
"e": 2438,
"s": 2420,
"text": "$ echo > file.txt"
},
{
"code": null,
"e": 2579,
"s": 2438,
"text": "To create a file with some contents, we use the echo command followed by the text, a redirection operator, and the file name as shown below."
},
{
"code": null,
"e": 2718,
"s": 2579,
"text": "heredoc stands for here document. The heredoc delimiter is a type of redirection. It allows passing multiple lines of input to a command. "
},
{
"code": null,
"e": 2759,
"s": 2718,
"text": "The general syntax of heredoc. Important"
},
{
"code": null,
"e": 2833,
"s": 2759,
"text": "Command << Heredoc_delimiter\nmultiple lines contents...\nheredoc_delimiter"
},
{
"code": null,
"e": 2947,
"s": 2833,
"text": "To create a file using heredoc, we use the cat command with heredoc delimiter in the Linux system as shown below."
},
{
"code": null,
"e": 2987,
"s": 2947,
"text": "$ cat << heredoc_delimiter < file_name"
},
{
"code": null,
"e": 3143,
"s": 2987,
"text": "The dd command is mainly used to converts and copy files. To check more details about the dd command. We can also create a large file using the dd command."
},
{
"code": null,
"e": 3206,
"s": 3143,
"text": "To create a large file, we use the dd command as shown below. "
},
{
"code": null,
"e": 3266,
"s": 3206,
"text": "$ dd if = /dev/zero of = file.test bs =1 count =0 seek = 2G"
},
{
"code": null,
"e": 3273,
"s": 3266,
"text": "How To"
},
{
"code": null,
"e": 3284,
"s": 3273,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3382,
"s": 3284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3431,
"s": 3382,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 3473,
"s": 3431,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 3512,
"s": 3473,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 3566,
"s": 3512,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 3624,
"s": 3566,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 3664,
"s": 3624,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 3704,
"s": 3664,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 3731,
"s": 3704,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 3766,
"s": 3731,
"text": "cut command in Linux with examples"
}
] |
Python | numpy.printoptions() method
|
03 Oct, 2019
With the help of numpy.printoptions() method, we can get the custom printing options like we can set the precisions of floating value by using numpy.printoptions() method.
Syntax : numpy.printoptions(precision=value)Return : Return the customized printing like precision.
Example #1 :In this example we can see that by using numpy.printoptions() method, we are able to get the customized printing options like we can set the precision values.
# import numpyimport numpy as np # using numpy.printoptions() methodwith np.printoptions(precision = 3): print(np.array([1, 2, 3])/2.38)
Output :
[0.42 0.84 1.261]
Example #2 :
# import numpyimport numpy as np # using numpy.printoptions() methodwith np.printoptions(precision = 5): print(np.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])/2.3865)
Output :
[[ 2.09512 4.19024 6.28536][ 8.38047 10.47559 12.57071][14.66583 16.76095 18.85607]]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "With the help of numpy.printoptions() method, we can get the custom printing options like we can set the precisions of floating value by using numpy.printoptions() method."
},
{
"code": null,
"e": 300,
"s": 200,
"text": "Syntax : numpy.printoptions(precision=value)Return : Return the customized printing like precision."
},
{
"code": null,
"e": 471,
"s": 300,
"text": "Example #1 :In this example we can see that by using numpy.printoptions() method, we are able to get the customized printing options like we can set the precision values."
},
{
"code": "# import numpyimport numpy as np # using numpy.printoptions() methodwith np.printoptions(precision = 3): print(np.array([1, 2, 3])/2.38)",
"e": 613,
"s": 471,
"text": null
},
{
"code": null,
"e": 622,
"s": 613,
"text": "Output :"
},
{
"code": null,
"e": 640,
"s": 622,
"text": "[0.42 0.84 1.261]"
},
{
"code": null,
"e": 653,
"s": 640,
"text": "Example #2 :"
},
{
"code": "# import numpyimport numpy as np # using numpy.printoptions() methodwith np.printoptions(precision = 5): print(np.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])/2.3865)",
"e": 829,
"s": 653,
"text": null
},
{
"code": null,
"e": 838,
"s": 829,
"text": "Output :"
},
{
"code": null,
"e": 923,
"s": 838,
"text": "[[ 2.09512 4.19024 6.28536][ 8.38047 10.47559 12.57071][14.66583 16.76095 18.85607]]"
},
{
"code": null,
"e": 936,
"s": 923,
"text": "Python-numpy"
},
{
"code": null,
"e": 943,
"s": 936,
"text": "Python"
}
] |
How to remove arrow in dropdown in Bootstrap ?
|
25 Jun, 2019
Dropdowns are one of the important components that are an integral part of any web application. Bootstrap provides its own interactive version of this component. Bootstrap dropdowns are toggled by clicking, not hovering as it was an intentional design decision. To use Dropdowns in a web project, include Popper.js into the project.
Every Bootstrap dropdown button or link has an ::after selector in CSS. ::after selector is often used to insert some text after the content of the element. In this case, the content is a dropdown arrow. To remove it, just make the content go ‘none’.
Syntax:
.my-dropdown-toggle::after {
content: none;
}
One can use this feature to create navigation menus in top navbars. Here’s the complete example showing how to do it.Example 1:
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" /> <title>Remove Dropdown Arrow</title> <style> .dropdown-toggle::after { content: none; } </style></head> <body> <div class="container"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown button </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#"> Action </a> <a class="dropdown-item" href="#"> Another action </a> <a class="dropdown-item" href="#"> Something else here </a> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script></body> </html>
Output:
Example 2: Remove arrow in dropdown with some changes in class name.
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" /> <title>Remove Dropdown Arrow</title> </head> <body> <div class="container"> <div class="dropdown"> <button class="btn btn-secondary" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown button </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#"> Action </a> <a class="dropdown-item" href="#"> Another action </a> <a class="dropdown-item" href="#"> Something else here </a> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script></body> </html>
Output:
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to make Bootstrap table with sticky table head?
How to Align modal content box to center of any screen?
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": 52,
"s": 24,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 385,
"s": 52,
"text": "Dropdowns are one of the important components that are an integral part of any web application. Bootstrap provides its own interactive version of this component. Bootstrap dropdowns are toggled by clicking, not hovering as it was an intentional design decision. To use Dropdowns in a web project, include Popper.js into the project."
},
{
"code": null,
"e": 636,
"s": 385,
"text": "Every Bootstrap dropdown button or link has an ::after selector in CSS. ::after selector is often used to insert some text after the content of the element. In this case, the content is a dropdown arrow. To remove it, just make the content go ‘none’."
},
{
"code": null,
"e": 644,
"s": 636,
"text": "Syntax:"
},
{
"code": null,
"e": 695,
"s": 644,
"text": ".my-dropdown-toggle::after {\n content: none;\n}\n"
},
{
"code": null,
"e": 823,
"s": 695,
"text": "One can use this feature to create navigation menus in top navbars. Here’s the complete example showing how to do it.Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" /> <title>Remove Dropdown Arrow</title> <style> .dropdown-toggle::after { content: none; } </style></head> <body> <div class=\"container\"> <div class=\"dropdown\"> <button class=\"btn btn-secondary dropdown-toggle\" type=\"button\" id=\"dropdownMenuButton\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"> Dropdown button </button> <div class=\"dropdown-menu\" aria-labelledby=\"dropdownMenuButton\"> <a class=\"dropdown-item\" href=\"#\"> Action </a> <a class=\"dropdown-item\" href=\"#\"> Another action </a> <a class=\"dropdown-item\" href=\"#\"> Something else here </a> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script></body> </html>",
"e": 2359,
"s": 823,
"text": null
},
{
"code": null,
"e": 2367,
"s": 2359,
"text": "Output:"
},
{
"code": null,
"e": 2436,
"s": 2367,
"text": "Example 2: Remove arrow in dropdown with some changes in class name."
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" /> <title>Remove Dropdown Arrow</title> </head> <body> <div class=\"container\"> <div class=\"dropdown\"> <button class=\"btn btn-secondary\" type=\"button\" id=\"dropdownMenuButton\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"> Dropdown button </button> <div class=\"dropdown-menu\" aria-labelledby=\"dropdownMenuButton\"> <a class=\"dropdown-item\" href=\"#\"> Action </a> <a class=\"dropdown-item\" href=\"#\"> Another action </a> <a class=\"dropdown-item\" href=\"#\"> Something else here </a> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"> </script></body> </html>",
"e": 3869,
"s": 2436,
"text": null
},
{
"code": null,
"e": 3877,
"s": 3869,
"text": "Output:"
},
{
"code": null,
"e": 3892,
"s": 3877,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 3899,
"s": 3892,
"text": "Picked"
},
{
"code": null,
"e": 3909,
"s": 3899,
"text": "Bootstrap"
},
{
"code": null,
"e": 3926,
"s": 3909,
"text": "Web Technologies"
},
{
"code": null,
"e": 4024,
"s": 3926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4065,
"s": 4024,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 4128,
"s": 4065,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 4161,
"s": 4128,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 4213,
"s": 4161,
"text": "How to make Bootstrap table with sticky table head?"
},
{
"code": null,
"e": 4269,
"s": 4213,
"text": "How to Align modal content box to center of any screen?"
},
{
"code": null,
"e": 4331,
"s": 4269,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4364,
"s": 4331,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4425,
"s": 4364,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4475,
"s": 4425,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to use the ErrorActionPreference variable in PowerShell?
|
ErrorActionPreference variable in PowerShell is to control the non-terminating errors by converting them to terminating errors. Error handling depends upon which value you assign to $ErrorActionPreference variable.
The values are as below.
Continue − This is the default value of the variable and when the error occurs, an error is displayed in the PowerShell console, and the script continues the execution.
Continue − This is the default value of the variable and when the error occurs, an error is displayed in the PowerShell console, and the script continues the execution.
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
Write-Host "Hello World"
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
Write-Host "Hello World"
Get-WmiObject : The RPC server is unavailable.
At line:2 char:1
+ Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject],
COMException
+ FullyQualifiedErrorId :
GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObj
ectCommand
Hello World
Stop − Error will not be displayed in the console and further pipeline execution is stopped. In the below example, there will be no output.
Stop − Error will not be displayed in the console and further pipeline execution is stopped. In the below example, there will be no output.
$ErrorActionPreference = "Stop"
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
Write-Host "Hello World"
SilentlyContinue − Error output will not be displayed and the script executes the next commands in the pipeline.
SilentlyContinue − Error output will not be displayed and the script executes the next commands in the pipeline.
$ErrorActionPreference = "SilentlyContinue"
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
Write-Host "`nHello World" -BackgroundColor DarkGreen
Output −
PS C:\WINDOWS\system32>> $ErrorActionPreference = "SilentlyContinue" Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist Write-Host "`nHello World" -BackgroundColor DarkGreen
Hello World
Inquire − It waits for user prompt if an error occurs and asks for continue. An error will be displayed.
Inquire − It waits for user prompt if an error occurs and asks for continue. An error will be displayed.
$ErrorActionPreference = "Inquire"
Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
Write-Host "`nHello World" -BackgroundColor DarkGreen
If you press “Yes/Yes to All” then error output will be displayed and “Halt Command/Suspend” will not display an error.
Suspend − This value is used in the PowerShell workflow to suspend workflow for investigation purposes and then resume.
Suspend − This value is used in the PowerShell workflow to suspend workflow for investigation purposes and then resume.
When you close the PowerShell session, the value of the $ErrorActionPreference will be set to default i.e. Continue.
|
[
{
"code": null,
"e": 1402,
"s": 1187,
"text": "ErrorActionPreference variable in PowerShell is to control the non-terminating errors by converting them to terminating errors. Error handling depends upon which value you assign to $ErrorActionPreference variable."
},
{
"code": null,
"e": 1427,
"s": 1402,
"text": "The values are as below."
},
{
"code": null,
"e": 1596,
"s": 1427,
"text": "Continue − This is the default value of the variable and when the error occurs, an error is displayed in the PowerShell console, and the script continues the execution."
},
{
"code": null,
"e": 1765,
"s": 1596,
"text": "Continue − This is the default value of the variable and when the error occurs, an error is displayed in the PowerShell console, and the script continues the execution."
},
{
"code": null,
"e": 1852,
"s": 1765,
"text": "Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist\nWrite-Host \"Hello World\""
},
{
"code": null,
"e": 2308,
"s": 1852,
"text": "Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist\nWrite-Host \"Hello World\"\nGet-WmiObject : The RPC server is unavailable.\nAt line:2 char:1\n+ Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject],\nCOMException\n+ FullyQualifiedErrorId :\nGetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObj\nectCommand\nHello World"
},
{
"code": null,
"e": 2448,
"s": 2308,
"text": "Stop − Error will not be displayed in the console and further pipeline execution is stopped. In the below example, there will be no output."
},
{
"code": null,
"e": 2588,
"s": 2448,
"text": "Stop − Error will not be displayed in the console and further pipeline execution is stopped. In the below example, there will be no output."
},
{
"code": null,
"e": 2707,
"s": 2588,
"text": "$ErrorActionPreference = \"Stop\"\nGet-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist\nWrite-Host \"Hello World\""
},
{
"code": null,
"e": 2820,
"s": 2707,
"text": "SilentlyContinue − Error output will not be displayed and the script executes the next commands in the pipeline."
},
{
"code": null,
"e": 2933,
"s": 2820,
"text": "SilentlyContinue − Error output will not be displayed and the script executes the next commands in the pipeline."
},
{
"code": null,
"e": 3093,
"s": 2933,
"text": "$ErrorActionPreference = \"SilentlyContinue\"\nGet-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist\nWrite-Host \"`nHello World\" -BackgroundColor DarkGreen"
},
{
"code": null,
"e": 3102,
"s": 3093,
"text": "Output −"
},
{
"code": null,
"e": 3300,
"s": 3102,
"text": "PS C:\\WINDOWS\\system32>> $ErrorActionPreference = \"SilentlyContinue\" Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist Write-Host \"`nHello World\" -BackgroundColor DarkGreen\n\nHello World"
},
{
"code": null,
"e": 3405,
"s": 3300,
"text": "Inquire − It waits for user prompt if an error occurs and asks for continue. An error will be displayed."
},
{
"code": null,
"e": 3510,
"s": 3405,
"text": "Inquire − It waits for user prompt if an error occurs and asks for continue. An error will be displayed."
},
{
"code": null,
"e": 3661,
"s": 3510,
"text": "$ErrorActionPreference = \"Inquire\"\nGet-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist\nWrite-Host \"`nHello World\" -BackgroundColor DarkGreen"
},
{
"code": null,
"e": 3781,
"s": 3661,
"text": "If you press “Yes/Yes to All” then error output will be displayed and “Halt Command/Suspend” will not display an error."
},
{
"code": null,
"e": 3901,
"s": 3781,
"text": "Suspend − This value is used in the PowerShell workflow to suspend workflow for investigation purposes and then resume."
},
{
"code": null,
"e": 4021,
"s": 3901,
"text": "Suspend − This value is used in the PowerShell workflow to suspend workflow for investigation purposes and then resume."
},
{
"code": null,
"e": 4138,
"s": 4021,
"text": "When you close the PowerShell session, the value of the $ErrorActionPreference will be set to default i.e. Continue."
}
] |
How to check if onClick exists on element in jQuery?
|
These codes might help you −
$('body').click(function(){ alert('test' )})
var foo = $.data( $('body').get(0), 'events' ).click
// you can query $.data( object, 'events' ) and get an object back, then see what events are attached to it.
$.each( foo, function(i,o) {
alert(i) // guid of the event
alert(o) // the function definition of the event handler
});
|
[
{
"code": null,
"e": 1216,
"s": 1187,
"text": "These codes might help you −"
},
{
"code": null,
"e": 1553,
"s": 1216,
"text": "$('body').click(function(){ alert('test' )})\n\nvar foo = $.data( $('body').get(0), 'events' ).click\n// you can query $.data( object, 'events' ) and get an object back, then see what events are attached to it.\n $.each( foo, function(i,o) {\n alert(i) // guid of the event\n alert(o) // the function definition of the event handler\n});"
}
] |
Python – Test Boolean Value of Dictionary
|
10 May, 2020
Sometimes, while working with data, we have a problem in which we need to accept or reject a dictionary on the basis of its true value, i.e all the keys are Boolean true or not. This kind of problem has possible applications in data preprocessing domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force method to solve this problem. In this, we iterate for each key and tag it as false if we find first occurrence of false value and break from loop.
# Python3 code to demonstrate working of # Test Boolean Value of Dictionary# Using loop # initializing dictionarytest_dict = {'gfg' : True, 'is' : False, 'best' : True} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Test Boolean Value of Dictionary# Using loopres = True for ele in test_dict: if not test_dict[ele]: res = False break # printing result print("Is Dictionary True ? : " + str(res))
The original dictionary is : {‘is’: False, ‘best’: True, ‘gfg’: True}Is Dictionary True ? : False
Method #2 : Using all() + values()This is a shorthand approach to solve this problem. In this, all() is used to check status of all values extracted using values().
# Python3 code to demonstrate working of # Test Boolean Value of Dictionary# Using all() + values() # initializing dictionarytest_dict = {'gfg' : True, 'is' : False, 'best' : True} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Test Boolean Value of Dictionary# Using all() + values()res = all(test_dict.values()) # printing result print("Is Dictionary True ? : " + str(res))
The original dictionary is : {‘is’: False, ‘best’: True, ‘gfg’: True}Is Dictionary True ? : False
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "Sometimes, while working with data, we have a problem in which we need to accept or reject a dictionary on the basis of its true value, i.e all the keys are Boolean true or not. This kind of problem has possible applications in data preprocessing domains. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 537,
"s": 348,
"text": "Method #1 : Using loopThis is brute force method to solve this problem. In this, we iterate for each key and tag it as false if we find first occurrence of false value and break from loop."
},
{
"code": "# Python3 code to demonstrate working of # Test Boolean Value of Dictionary# Using loop # initializing dictionarytest_dict = {'gfg' : True, 'is' : False, 'best' : True} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Test Boolean Value of Dictionary# Using loopres = True for ele in test_dict: if not test_dict[ele]: res = False break # printing result print(\"Is Dictionary True ? : \" + str(res)) ",
"e": 997,
"s": 537,
"text": null
},
{
"code": null,
"e": 1095,
"s": 997,
"text": "The original dictionary is : {‘is’: False, ‘best’: True, ‘gfg’: True}Is Dictionary True ? : False"
},
{
"code": null,
"e": 1262,
"s": 1097,
"text": "Method #2 : Using all() + values()This is a shorthand approach to solve this problem. In this, all() is used to check status of all values extracted using values()."
},
{
"code": "# Python3 code to demonstrate working of # Test Boolean Value of Dictionary# Using all() + values() # initializing dictionarytest_dict = {'gfg' : True, 'is' : False, 'best' : True} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Test Boolean Value of Dictionary# Using all() + values()res = all(test_dict.values()) # printing result print(\"Is Dictionary True ? : \" + str(res)) ",
"e": 1684,
"s": 1262,
"text": null
},
{
"code": null,
"e": 1782,
"s": 1684,
"text": "The original dictionary is : {‘is’: False, ‘best’: True, ‘gfg’: True}Is Dictionary True ? : False"
},
{
"code": null,
"e": 1809,
"s": 1782,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 1816,
"s": 1809,
"text": "Python"
},
{
"code": null,
"e": 1832,
"s": 1816,
"text": "Python Programs"
},
{
"code": null,
"e": 1930,
"s": 1832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1972,
"s": 1930,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1994,
"s": 1972,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2029,
"s": 1994,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2055,
"s": 2029,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2087,
"s": 2055,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2130,
"s": 2087,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2152,
"s": 2130,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2191,
"s": 2152,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2229,
"s": 2191,
"text": "Python | Convert a list to dictionary"
}
] |
Perl import Function
|
This function is an ordinary method (subroutine) defined (or inherited) by modules that wish to export names to another module. The use function calls the import method for the package used.
Following is the simple syntax for this function −
import LIST
This function does not return any value.
Following is the example code showing its basic usage −
#!/usr/bin/perl
package Util;
use base 'Exporter';
our @EXPORT_OK = ('foo', 'bar');
sub foo {
print "foo!";
}
sub bar {
print "bar!";
}
package Amy;
use Util 'foo'; # only import foo()
foo(); # works fine
bar(); # blows up
|
[
{
"code": null,
"e": 2545,
"s": 2354,
"text": "This function is an ordinary method (subroutine) defined (or inherited) by modules that wish to export names to another module. The use function calls the import method for the package used."
},
{
"code": null,
"e": 2596,
"s": 2545,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2609,
"s": 2596,
"text": "import LIST\n"
},
{
"code": null,
"e": 2650,
"s": 2609,
"text": "This function does not return any value."
},
{
"code": null,
"e": 2706,
"s": 2650,
"text": "Following is the example code showing its basic usage −"
}
] |
Python | Creating DataFrame from dict of narray/lists
|
22 Jun, 2021
As we know Pandas is all-time great tools for data analysis. One of the most important data type is dataframe. It is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss how to create Pandas dataframe using dictionary of ndarray (or lists).Let’s try to understand it better with few examples.Code #1:
Python3
# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Category':['Array', 'Stack', 'Queue'], 'Marks':[20, 21, 19]} # Create DataFramedf = pd.DataFrame(data) # Print the output.print(df )
Category Marks
0 Array 20
1 Stack 21
2 Queue 19
Note: To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length. Code #2:
Python3
# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Category':['Array', 'Stack', 'Queue'], 'Student_1':[20, 21, 19], 'Student_2':[15, 20, 14]} # Create DataFramedf = pd.DataFrame(data) # Print the output.print(df.transpose())
0 1 2
Category Array Stack Queue
Student_1 20 21 19
Student_2 15 20 14
Code #3: Providing index list to dataframe
Python3
# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Area':['Array', 'Stack', 'Queue'], 'Student_1':[20, 21, 19], 'Student_2':[15, 20, 14]} # Create DataFramedf = pd.DataFrame(data, index =['Cat_1', 'Cat_2', 'Cat_3']) # Print the output.print(df)
Area Student_1 Student_2
Cat_1 Array 20 15
Cat_2 Stack 21 20
Cat_3 Queue 19 14
adnanirshad158
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 480,
"s": 28,
"text": "As we know Pandas is all-time great tools for data analysis. One of the most important data type is dataframe. It is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used pandas object. Pandas DataFrame can be created in multiple ways. Let’s discuss how to create Pandas dataframe using dictionary of ndarray (or lists).Let’s try to understand it better with few examples.Code #1: "
},
{
"code": null,
"e": 488,
"s": 480,
"text": "Python3"
},
{
"code": "# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Category':['Array', 'Stack', 'Queue'], 'Marks':[20, 21, 19]} # Create DataFramedf = pd.DataFrame(data) # Print the output.print(df )",
"e": 778,
"s": 488,
"text": null
},
{
"code": null,
"e": 848,
"s": 778,
"text": "Category Marks\n0 Array 20\n1 Stack 21\n2 Queue 19"
},
{
"code": null,
"e": 1126,
"s": 850,
"text": "Note: To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the length index should be equal to the length of arrays. If no index is passed, then by default, index will be range(n) where n is the array length. Code #2: "
},
{
"code": null,
"e": 1134,
"s": 1126,
"text": "Python3"
},
{
"code": "# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Category':['Array', 'Stack', 'Queue'], 'Student_1':[20, 21, 19], 'Student_2':[15, 20, 14]} # Create DataFramedf = pd.DataFrame(data) # Print the output.print(df.transpose())",
"e": 1465,
"s": 1134,
"text": null
},
{
"code": null,
"e": 1588,
"s": 1465,
"text": " 0 1 2\nCategory Array Stack Queue\nStudent_1 20 21 19\nStudent_2 15 20 14"
},
{
"code": null,
"e": 1637,
"s": 1590,
"text": " Code #3: Providing index list to dataframe "
},
{
"code": null,
"e": 1645,
"s": 1637,
"text": "Python3"
},
{
"code": "# Python code demonstrate creating# DataFrame from dict narray / lists# By default addresses. import pandas as pd # initialise data of lists.data = {'Area':['Array', 'Stack', 'Queue'], 'Student_1':[20, 21, 19], 'Student_2':[15, 20, 14]} # Create DataFramedf = pd.DataFrame(data, index =['Cat_1', 'Cat_2', 'Cat_3']) # Print the output.print(df)",
"e": 1996,
"s": 1645,
"text": null
},
{
"code": null,
"e": 2136,
"s": 1996,
"text": " Area Student_1 Student_2\nCat_1 Array 20 15\nCat_2 Stack 21 20\nCat_3 Queue 19 14"
},
{
"code": null,
"e": 2153,
"s": 2138,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2178,
"s": 2153,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 2202,
"s": 2178,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2216,
"s": 2202,
"text": "Python-pandas"
},
{
"code": null,
"e": 2223,
"s": 2216,
"text": "Python"
},
{
"code": null,
"e": 2321,
"s": 2223,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2339,
"s": 2321,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2381,
"s": 2339,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2403,
"s": 2381,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2438,
"s": 2403,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2464,
"s": 2438,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2496,
"s": 2464,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2525,
"s": 2496,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2552,
"s": 2525,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2582,
"s": 2552,
"text": "Iterate over a list in Python"
}
] |
How to Rotate Container Background Image using CSS ?
|
13 May, 2020
The CSS background-image property is used to add an image to the background of an element. In this article, the task is to rotate the image which is used in the background.
Approach: The CSS transform property is used to apply two-dimensional or three-dimensional transformation to a element. This property can be used to rotate, scale, move or even skew an element.
Syntax:
.class_name { transform: value }
Example: We can use the CSS transform property to fix this issue and make rotations as given below:
<!DOCTYPE html><html> <head> <!-- Bootstrap CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <!-- CSS --> <style> .background-image { background-image: url('Geeksforgeeks_image.jpg'); background-repeat: no-repeat; height: 300px; } .rotated-background-image { background-image: url('Geeksforgeeks_image.jpg'); background-repeat: no-repeat; height: 100%; margin-top: 250px; transform: rotate(90deg); /* All browsers support */ -moz-transform: rotate(90deg); -webkit-transform: rotate(90deg); -o-transform: rotate(90deg); -ms-transform: rotate(90deg); } .custom { height: 100px; padding-top: 10px; } </style></head> <body> <!-- Normal image which is not rotated --> <div class="container custom"> <div class="background-image"> </div> </div> <!-- Rotated image --> <div class="container"> <div class="rotated-background-image"> </div> </div> </body> </html>
Output:
CSS-Misc
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 May, 2020"
},
{
"code": null,
"e": 201,
"s": 28,
"text": "The CSS background-image property is used to add an image to the background of an element. In this article, the task is to rotate the image which is used in the background."
},
{
"code": null,
"e": 395,
"s": 201,
"text": "Approach: The CSS transform property is used to apply two-dimensional or three-dimensional transformation to a element. This property can be used to rotate, scale, move or even skew an element."
},
{
"code": null,
"e": 403,
"s": 395,
"text": "Syntax:"
},
{
"code": null,
"e": 437,
"s": 403,
"text": ".class_name { transform: value } "
},
{
"code": null,
"e": 537,
"s": 437,
"text": "Example: We can use the CSS transform property to fix this issue and make rotations as given below:"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Bootstrap CDN --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\"> <!-- CSS --> <style> .background-image { background-image: url('Geeksforgeeks_image.jpg'); background-repeat: no-repeat; height: 300px; } .rotated-background-image { background-image: url('Geeksforgeeks_image.jpg'); background-repeat: no-repeat; height: 100%; margin-top: 250px; transform: rotate(90deg); /* All browsers support */ -moz-transform: rotate(90deg); -webkit-transform: rotate(90deg); -o-transform: rotate(90deg); -ms-transform: rotate(90deg); } .custom { height: 100px; padding-top: 10px; } </style></head> <body> <!-- Normal image which is not rotated --> <div class=\"container custom\"> <div class=\"background-image\"> </div> </div> <!-- Rotated image --> <div class=\"container\"> <div class=\"rotated-background-image\"> </div> </div> </body> </html>",
"e": 1755,
"s": 537,
"text": null
},
{
"code": null,
"e": 1763,
"s": 1755,
"text": "Output:"
},
{
"code": null,
"e": 1772,
"s": 1763,
"text": "CSS-Misc"
},
{
"code": null,
"e": 1779,
"s": 1772,
"text": "Picked"
},
{
"code": null,
"e": 1783,
"s": 1779,
"text": "CSS"
},
{
"code": null,
"e": 1800,
"s": 1783,
"text": "Web Technologies"
},
{
"code": null,
"e": 1827,
"s": 1800,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1925,
"s": 1827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1964,
"s": 1925,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2001,
"s": 1964,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2040,
"s": 2001,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2104,
"s": 2040,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 2165,
"s": 2104,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2198,
"s": 2165,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2259,
"s": 2198,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2302,
"s": 2259,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2374,
"s": 2302,
"text": "Differences between Functional Components and Class Components in React"
}
] |
How to Compress and Extract Files Using the tar Command on Linux
|
29 Jun, 2021
An archive is a special file that contains any number of files inside. It can be restored via special programs, for example, tar.inside.
.tar – archive files are usually not compressed.
.tar.gz – archive file compressed with gzip tool
.tar.bz2 – archive file compressed with bzip2 tool
Syntax:
tar options [archive_name.tar] files_to_archive
The tar command does not create a compressed archive, instead, it uses external utilities like gzip and bzip2.
Command functionality:
–diff
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
–delete
Showing the difference between archives
Delete file from the archive
Command parameters:
–verbose
–total
Show process information
Show final result
1) Compress one file using the tar command:
tar -czvf one-file-compressed.tar.gz hello_world
2) Compress directory using the tar command:
tar -czvf dir-compressed.tar.gz test_directory/
3) Show the archive content:
tar -tf archive.tar.gz
4) Add content to the existing archive:
tar -rvf existing-archive-name.tar file-directory-to-compress/
5) Update content in an archive:
6) Compress with bzip2:
tar -cjvf one-file-compressed.tar.bz2 hello_world
7) Extract files from a .tar archive:
tar -xf archive.tar.gz
The same with .tar.gz and .tar.bz2
Linux-file-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "An archive is a special file that contains any number of files inside. It can be restored via special programs, for example, tar.inside."
},
{
"code": null,
"e": 214,
"s": 165,
"text": ".tar – archive files are usually not compressed."
},
{
"code": null,
"e": 263,
"s": 214,
"text": ".tar.gz – archive file compressed with gzip tool"
},
{
"code": null,
"e": 314,
"s": 263,
"text": ".tar.bz2 – archive file compressed with bzip2 tool"
},
{
"code": null,
"e": 323,
"s": 314,
"text": "Syntax: "
},
{
"code": null,
"e": 371,
"s": 323,
"text": "tar options [archive_name.tar] files_to_archive"
},
{
"code": null,
"e": 482,
"s": 371,
"text": "The tar command does not create a compressed archive, instead, it uses external utilities like gzip and bzip2."
},
{
"code": null,
"e": 505,
"s": 482,
"text": "Command functionality:"
},
{
"code": null,
"e": 511,
"s": 505,
"text": "–diff"
},
{
"code": null,
"e": 520,
"s": 511,
"text": "Chapters"
},
{
"code": null,
"e": 547,
"s": 520,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 597,
"s": 547,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 620,
"s": 597,
"text": "captions off, selected"
},
{
"code": null,
"e": 628,
"s": 620,
"text": "English"
},
{
"code": null,
"e": 652,
"s": 628,
"text": "This is a modal window."
},
{
"code": null,
"e": 721,
"s": 652,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 743,
"s": 721,
"text": "End of dialog window."
},
{
"code": null,
"e": 751,
"s": 743,
"text": "–delete"
},
{
"code": null,
"e": 791,
"s": 751,
"text": "Showing the difference between archives"
},
{
"code": null,
"e": 820,
"s": 791,
"text": "Delete file from the archive"
},
{
"code": null,
"e": 840,
"s": 820,
"text": "Command parameters:"
},
{
"code": null,
"e": 849,
"s": 840,
"text": "–verbose"
},
{
"code": null,
"e": 856,
"s": 849,
"text": "–total"
},
{
"code": null,
"e": 881,
"s": 856,
"text": "Show process information"
},
{
"code": null,
"e": 900,
"s": 881,
"text": "Show final result "
},
{
"code": null,
"e": 944,
"s": 900,
"text": "1) Compress one file using the tar command:"
},
{
"code": null,
"e": 993,
"s": 944,
"text": "tar -czvf one-file-compressed.tar.gz hello_world"
},
{
"code": null,
"e": 1038,
"s": 993,
"text": "2) Compress directory using the tar command:"
},
{
"code": null,
"e": 1086,
"s": 1038,
"text": "tar -czvf dir-compressed.tar.gz test_directory/"
},
{
"code": null,
"e": 1115,
"s": 1086,
"text": "3) Show the archive content:"
},
{
"code": null,
"e": 1138,
"s": 1115,
"text": "tar -tf archive.tar.gz"
},
{
"code": null,
"e": 1178,
"s": 1138,
"text": "4) Add content to the existing archive:"
},
{
"code": null,
"e": 1241,
"s": 1178,
"text": "tar -rvf existing-archive-name.tar file-directory-to-compress/"
},
{
"code": null,
"e": 1275,
"s": 1241,
"text": "5) Update content in an archive: "
},
{
"code": null,
"e": 1299,
"s": 1275,
"text": "6) Compress with bzip2:"
},
{
"code": null,
"e": 1349,
"s": 1299,
"text": "tar -cjvf one-file-compressed.tar.bz2 hello_world"
},
{
"code": null,
"e": 1387,
"s": 1349,
"text": "7) Extract files from a .tar archive:"
},
{
"code": null,
"e": 1410,
"s": 1387,
"text": "tar -xf archive.tar.gz"
},
{
"code": null,
"e": 1445,
"s": 1410,
"text": "The same with .tar.gz and .tar.bz2"
},
{
"code": null,
"e": 1465,
"s": 1445,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 1472,
"s": 1465,
"text": "Picked"
},
{
"code": null,
"e": 1483,
"s": 1472,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1581,
"s": 1483,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1607,
"s": 1581,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1642,
"s": 1607,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1679,
"s": 1642,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1708,
"s": 1679,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1742,
"s": 1708,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1779,
"s": 1742,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1816,
"s": 1779,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1855,
"s": 1816,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 1895,
"s": 1855,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
Finding shortest path between any two nodes using Floyd Warshall Algorithm
|
18 Aug, 2021
Given a graph and two nodes u and v, the task is to print the shortest path between u and v using the Floyd Warshall algorithm.
Examples:
Input: u = 1, v = 3
Output: 1 -> 2 -> 3 Explanation: Shortest path from 1 to 3 is through vertex 2 with total cost 3. The first edge is 1 -> 2 with cost 2 and the second edge is 2 -> 3 with cost 1.
Input: u = 0, v = 2
Output: 0 -> 1 -> 2 Explanation: Shortest path from 0 to 2 is through vertex 1 with total cost = 5
Approach:
The main idea here is to use a matrix(2D array) that will keep track of the next node to point if the shortest path changes for any pair of nodes. Initially, the shortest path between any two nodes u and v is v (that is the direct edge from u -> v).
Initialising the Next array
If the path exists between two nodes then Next[u][v] = v else we set Next[u][v] = -1
Modification in Floyd Warshall Algorithm
Inside the if condition of Floyd Warshall Algorithm we’ll add a statement Next[i][j] = Next[i][k] (that means we found the shortest path between i, j through an intermediate node k).
This is how our if condition would look like
if(dis[i][j] > dis[i][k] + dis[k][j])
{
dis[i][j] = dis[i][k] + dis[k][j];
Next[i][j] = Next[i][k];
}
For constructing path using these nodes we’ll simply start looping through the node u while updating its value to next[u][v] until we reach node v.
path = [u]
while u != v:
u = Next[u][v]
path.append(u)
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find the shortest// path between any two nodes using// Floyd Warshall Algorithm.#include <bits/stdc++.h>using namespace std; #define MAXN 100// Infinite value for arrayconst int INF = 1e7; int dis[MAXN][MAXN];int Next[MAXN][MAXN]; // Initializing the distance and// Next arrayvoid initialise(int V, vector<vector<int> >& graph){ for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { dis[i][j] = graph[i][j]; // No edge between node // i and j if (graph[i][j] == INF) Next[i][j] = -1; else Next[i][j] = j; } }} // Function construct the shortest// path between u and vvector<int> constructPath(int u, int v){ // If there's no path between // node u and v, simply return // an empty array if (Next[u][v] == -1) return {}; // Storing the path in a vector vector<int> path = { u }; while (u != v) { u = Next[u][v]; path.push_back(u); } return path;} // Standard Floyd Warshall Algorithm// with little modification Now if we find// that dis[i][j] > dis[i][k] + dis[k][j]// then we modify next[i][j] = next[i][k]void floydWarshall(int V){ for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { // We cannot travel through // edge that doesn't exist if (dis[i][k] == INF || dis[k][j] == INF) continue; if (dis[i][j] > dis[i][k] + dis[k][j]) { dis[i][j] = dis[i][k] + dis[k][j]; Next[i][j] = Next[i][k]; } } } }} // Print the shortest pathvoid printPath(vector<int>& path){ int n = path.size(); for (int i = 0; i < n - 1; i++) cout << path[i] << " -> "; cout << path[n - 1] << endl;} // Driver codeint main(){ int V = 4; vector<vector<int> > graph = { { 0, 3, INF, 7 }, { 8, 0, 2, INF }, { 5, INF, 0, 1 }, { 2, INF, INF, 0 } }; // Function to initialise the // distance and Next array initialise(V, graph); // Calling Floyd Warshall Algorithm, // this will update the shortest // distance as well as Next array floydWarshall(V); vector<int> path; // Path from node 1 to 3 cout << "Shortest path from 1 to 3: "; path = constructPath(1, 3); printPath(path); // Path from node 0 to 2 cout << "Shortest path from 0 to 2: "; path = constructPath(0, 2); printPath(path); // path from node 3 to 2 cout << "Shortest path from 3 to 2: "; path = constructPath(3, 2); printPath(path); return 0;}
// Java program to find the shortest// path between any two nodes using// Floyd Warshall Algorithm.import java.util.*; class GFG{ static final int MAXN = 100; // Infinite value for arraystatic int INF = (int) 1e7; static int [][]dis = new int[MAXN][MAXN];static int [][]Next = new int[MAXN][MAXN]; // Initializing the distance and// Next arraystatic void initialise(int V, int [][] graph){ for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { dis[i][j] = graph[i][j]; // No edge between node // i and j if (graph[i][j] == INF) Next[i][j] = -1; else Next[i][j] = j; } }} // Function construct the shortest// path between u and vstatic Vector<Integer> constructPath(int u, int v){ // If there's no path between // node u and v, simply return // an empty array if (Next[u][v] == -1) return null; // Storing the path in a vector Vector<Integer> path = new Vector<Integer>(); path.add(u); while (u != v) { u = Next[u][v]; path.add(u); } return path;} // Standard Floyd Warshall Algorithm// with little modification Now if we find// that dis[i][j] > dis[i][k] + dis[k][j]// then we modify next[i][j] = next[i][k]static void floydWarshall(int V){ for(int k = 0; k < V; k++) { for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { // We cannot travel through // edge that doesn't exist if (dis[i][k] == INF || dis[k][j] == INF) continue; if (dis[i][j] > dis[i][k] + dis[k][j]) { dis[i][j] = dis[i][k] + dis[k][j]; Next[i][j] = Next[i][k]; } } } }} // Print the shortest pathstatic void printPath(Vector<Integer> path){ int n = path.size(); for(int i = 0; i < n - 1; i++) System.out.print(path.get(i) + " -> "); System.out.print(path.get(n - 1) + "\n");} // Driver codepublic static void main(String[] args){ int V = 4; int [][] graph = { { 0, 3, INF, 7 }, { 8, 0, 2, INF }, { 5, INF, 0, 1 }, { 2, INF, INF, 0 } }; // Function to initialise the // distance and Next array initialise(V, graph); // Calling Floyd Warshall Algorithm, // this will update the shortest // distance as well as Next array floydWarshall(V); Vector<Integer> path; // Path from node 1 to 3 System.out.print("Shortest path from 1 to 3: "); path = constructPath(1, 3); printPath(path); // Path from node 0 to 2 System.out.print("Shortest path from 0 to 2: "); path = constructPath(0, 2); printPath(path); // Path from node 3 to 2 System.out.print("Shortest path from 3 to 2: "); path = constructPath(3, 2); printPath(path);}} // This code is contributed by Amit Katiyar
# Python3 program to find the shortest# path between any two nodes using# Floyd Warshall Algorithm. # Initializing the distance and# Next arraydef initialise(V): global dis, Next for i in range(V): for j in range(V): dis[i][j] = graph[i][j] # No edge between node # i and j if (graph[i][j] == INF): Next[i][j] = -1 else: Next[i][j] = j # Function construct the shortest# path between u and vdef constructPath(u, v): global graph, Next # If there's no path between # node u and v, simply return # an empty array if (Next[u][v] == -1): return {} # Storing the path in a vector path = [u] while (u != v): u = Next[u][v] path.append(u) return path # Standard Floyd Warshall Algorithm# with little modification Now if we find# that dis[i][j] > dis[i][k] + dis[k][j]# then we modify next[i][j] = next[i][k]def floydWarshall(V): global dist, Next for k in range(V): for i in range(V): for j in range(V): # We cannot travel through # edge that doesn't exist if (dis[i][k] == INF or dis[k][j] == INF): continue if (dis[i][j] > dis[i][k] + dis[k][j]): dis[i][j] = dis[i][k] + dis[k][j] Next[i][j] = Next[i][k] # Print the shortest pathdef printPath(path): n = len(path) for i in range(n - 1): print(path[i], end=" -> ") print (path[n - 1]) # Driver codeif __name__ == '__main__': MAXM,INF = 100,10**7 dis = [[-1 for i in range(MAXM)] for i in range(MAXM)] Next = [[-1 for i in range(MAXM)] for i in range(MAXM)] V = 4 graph = [ [ 0, 3, INF, 7 ], [ 8, 0, 2, INF ], [ 5, INF, 0, 1 ], [ 2, INF, INF, 0 ] ] # Function to initialise the # distance and Next array initialise(V) # Calling Floyd Warshall Algorithm, # this will update the shortest # distance as well as Next array floydWarshall(V) path = [] # Path from node 1 to 3 print("Shortest path from 1 to 3: ", end = "") path = constructPath(1, 3) printPath(path) # Path from node 0 to 2 print("Shortest path from 0 to 2: ", end = "") path = constructPath(0, 2) printPath(path) # Path from node 3 to 2 print("Shortest path from 3 to 2: ", end = "") path = constructPath(3, 2) printPath(path) # This code is contributed by mohit kumar 29
// C# program to find the shortest// path between any two nodes using// Floyd Warshall Algorithm.using System;using System.Collections.Generic; class GFG{ static readonly int MAXN = 100; // Infinite value for arraystatic int INF = (int)1e7; static int [,]dis = new int[MAXN, MAXN];static int [,]Next = new int[MAXN, MAXN]; // Initializing the distance and// Next arraystatic void initialise(int V, int [,] graph){ for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { dis[i, j] = graph[i, j]; // No edge between node // i and j if (graph[i, j] == INF) Next[i, j] = -1; else Next[i, j] = j; } }} // Function construct the shortest// path between u and vstatic List<int> constructPath(int u, int v){ // If there's no path between // node u and v, simply return // an empty array if (Next[u, v] == -1) return null; // Storing the path in a vector List<int> path = new List<int>(); path.Add(u); while (u != v) { u = Next[u, v]; path.Add(u); } return path;} // Standard Floyd Warshall Algorithm// with little modification Now if we find// that dis[i,j] > dis[i,k] + dis[k,j]// then we modify next[i,j] = next[i,k]static void floydWarshall(int V){ for(int k = 0; k < V; k++) { for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { // We cannot travel through // edge that doesn't exist if (dis[i, k] == INF || dis[k, j] == INF) continue; if (dis[i, j] > dis[i, k] + dis[k, j]) { dis[i, j] = dis[i, k] + dis[k, j]; Next[i, j] = Next[i, k]; } } } }} // Print the shortest pathstatic void printPath(List<int> path){ int n = path.Count; for(int i = 0; i < n - 1; i++) Console.Write(path[i] + " -> "); Console.Write(path[n - 1] + "\n");} // Driver codepublic static void Main(String[] args){ int V = 4; int [,] graph = { { 0, 3, INF, 7 }, { 8, 0, 2, INF }, { 5, INF, 0, 1 }, { 2, INF, INF, 0 } }; // Function to initialise the // distance and Next array initialise(V, graph); // Calling Floyd Warshall Algorithm, // this will update the shortest // distance as well as Next array floydWarshall(V); List<int> path; // Path from node 1 to 3 Console.Write("Shortest path from 1 to 3: "); path = constructPath(1, 3); printPath(path); // Path from node 0 to 2 Console.Write("Shortest path from 0 to 2: "); path = constructPath(0, 2); printPath(path); // Path from node 3 to 2 Console.Write("Shortest path from 3 to 2: "); path = constructPath(3, 2); printPath(path);}} // This code is contributed by Amit Katiyar
<script> // Javascript program to find the shortest// path between any two nodes using// Floyd Warshall Algorithm.let MAXN = 100; // Infinite value for arraylet INF = 1e7;let dis = new Array(MAXN);let Next = new Array(MAXN);for(let i = 0; i < MAXN; i++){ dis[i] = new Array(MAXN); Next[i] = new Array(MAXN);} // Initializing the distance and// Next arrayfunction initialise(V, graph){ for(let i = 0; i < V; i++) { for(let j = 0; j < V; j++) { dis[i][j] = graph[i][j]; // No edge between node // i and j if (graph[i][j] == INF) Next[i][j] = -1; else Next[i][j] = j; } }} // Function construct the shortest// path between u and vfunction constructPath(u, v){ // If there's no path between // node u and v, simply return // an empty array if (Next[u][v] == -1) return null; // Storing the path in a vector let path = []; path.push(u); while (u != v) { u = Next[u][v]; path.push(u); } return path;} // Standard Floyd Warshall Algorithm// with little modification Now if we find// that dis[i][j] > dis[i][k] + dis[k][j]// then we modify next[i][j] = next[i][k]function floydWarshall(V){ for(let k = 0; k < V; k++) { for(let i = 0; i < V; i++) { for(let j = 0; j < V; j++) { // We cannot travel through // edge that doesn't exist if (dis[i][k] == INF || dis[k][j] == INF) continue; if (dis[i][j] > dis[i][k] + dis[k][j]) { dis[i][j] = dis[i][k] + dis[k][j]; Next[i][j] = Next[i][k]; } } } }} // Print the shortest pathfunction printPath(path){ let n = path.length; for(let i = 0; i < n - 1; i++) document.write(path[i] + " -> "); document.write(path[n - 1] + "<br>");} // Driver codelet V = 4;let graph = [ [ 0, 3, INF, 7 ], [ 8, 0, 2, INF ], [ 5, INF, 0, 1 ], [ 2, INF, INF, 0 ] ]; // Function to initialise the// distance and Next arrayinitialise(V, graph); // Calling Floyd Warshall Algorithm,// this will update the shortest// distance as well as Next arrayfloydWarshall(V);let path; // Path from node 1 to 3document.write("Shortest path from 1 to 3: ");path = constructPath(1, 3);printPath(path); // Path from node 0 to 2document.write("Shortest path from 0 to 2: ");path = constructPath(0, 2);printPath(path); // Path from node 3 to 2document.write("Shortest path from 3 to 2: ");path = constructPath(3, 2);printPath(path); // This code is contributed by unknown2108 </script>
Shortest path from 1 to 3: 1 -> 2 -> 3
Shortest path from 0 to 2: 0 -> 1 -> 2
Shortest path from 3 to 2: 3 -> 0 -> 1 -> 2
Complexity Analysis:
The time complexity for Floyd Warshall Algorithm is O(V3)
For finding shortest path time complexity is O(V) per query.
Note: It would be efficient to use the Floyd Warshall Algorithm when your graph contains a couple of hundred vertices and you need to answer multiple queries related to the shortest path.
amit143katiyar
mohit kumar 29
nidhi_biet
unknown2108
varshagumber28
anikakapoor
Algorithms-Graph Shortest Paths Quiz
Graph Shortest Paths Quiz
Advanced Data Structure
Algorithms
Dynamic Programming
Graph
Dynamic Programming
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
Segment Tree | Set 1 (Sum of given range)
Binary Indexed Tree or Fenwick Tree
AVL Tree | Set 2 (Deletion)
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
Difference between BFS and DFS
What is Hashing | A Complete Tutorial
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 180,
"s": 52,
"text": "Given a graph and two nodes u and v, the task is to print the shortest path between u and v using the Floyd Warshall algorithm."
},
{
"code": null,
"e": 190,
"s": 180,
"text": "Examples:"
},
{
"code": null,
"e": 212,
"s": 190,
"text": "Input: u = 1, v = 3 "
},
{
"code": null,
"e": 390,
"s": 212,
"text": "Output: 1 -> 2 -> 3 Explanation: Shortest path from 1 to 3 is through vertex 2 with total cost 3. The first edge is 1 -> 2 with cost 2 and the second edge is 2 -> 3 with cost 1."
},
{
"code": null,
"e": 412,
"s": 390,
"text": "Input: u = 0, v = 2 "
},
{
"code": null,
"e": 513,
"s": 412,
"text": "Output: 0 -> 1 -> 2 Explanation: Shortest path from 0 to 2 is through vertex 1 with total cost = 5 "
},
{
"code": null,
"e": 524,
"s": 513,
"text": "Approach: "
},
{
"code": null,
"e": 776,
"s": 524,
"text": "The main idea here is to use a matrix(2D array) that will keep track of the next node to point if the shortest path changes for any pair of nodes. Initially, the shortest path between any two nodes u and v is v (that is the direct edge from u -> v). "
},
{
"code": null,
"e": 804,
"s": 776,
"text": "Initialising the Next array"
},
{
"code": null,
"e": 891,
"s": 804,
"text": "If the path exists between two nodes then Next[u][v] = v else we set Next[u][v] = -1 "
},
{
"code": null,
"e": 932,
"s": 891,
"text": "Modification in Floyd Warshall Algorithm"
},
{
"code": null,
"e": 1117,
"s": 932,
"text": "Inside the if condition of Floyd Warshall Algorithm we’ll add a statement Next[i][j] = Next[i][k] (that means we found the shortest path between i, j through an intermediate node k). "
},
{
"code": null,
"e": 1162,
"s": 1117,
"text": "This is how our if condition would look like"
},
{
"code": null,
"e": 1276,
"s": 1162,
"text": "if(dis[i][j] > dis[i][k] + dis[k][j])\n{\n dis[i][j] = dis[i][k] + dis[k][j];\n Next[i][j] = Next[i][k]; \n}"
},
{
"code": null,
"e": 1424,
"s": 1276,
"text": "For constructing path using these nodes we’ll simply start looping through the node u while updating its value to next[u][v] until we reach node v."
},
{
"code": null,
"e": 1487,
"s": 1424,
"text": "path = [u]\nwhile u != v:\n u = Next[u][v]\n path.append(u)"
},
{
"code": null,
"e": 1540,
"s": 1487,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 1544,
"s": 1540,
"text": "C++"
},
{
"code": null,
"e": 1549,
"s": 1544,
"text": "Java"
},
{
"code": null,
"e": 1557,
"s": 1549,
"text": "Python3"
},
{
"code": null,
"e": 1560,
"s": 1557,
"text": "C#"
},
{
"code": null,
"e": 1571,
"s": 1560,
"text": "Javascript"
},
{
"code": "// C++ program to find the shortest// path between any two nodes using// Floyd Warshall Algorithm.#include <bits/stdc++.h>using namespace std; #define MAXN 100// Infinite value for arrayconst int INF = 1e7; int dis[MAXN][MAXN];int Next[MAXN][MAXN]; // Initializing the distance and// Next arrayvoid initialise(int V, vector<vector<int> >& graph){ for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { dis[i][j] = graph[i][j]; // No edge between node // i and j if (graph[i][j] == INF) Next[i][j] = -1; else Next[i][j] = j; } }} // Function construct the shortest// path between u and vvector<int> constructPath(int u, int v){ // If there's no path between // node u and v, simply return // an empty array if (Next[u][v] == -1) return {}; // Storing the path in a vector vector<int> path = { u }; while (u != v) { u = Next[u][v]; path.push_back(u); } return path;} // Standard Floyd Warshall Algorithm// with little modification Now if we find// that dis[i][j] > dis[i][k] + dis[k][j]// then we modify next[i][j] = next[i][k]void floydWarshall(int V){ for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { // We cannot travel through // edge that doesn't exist if (dis[i][k] == INF || dis[k][j] == INF) continue; if (dis[i][j] > dis[i][k] + dis[k][j]) { dis[i][j] = dis[i][k] + dis[k][j]; Next[i][j] = Next[i][k]; } } } }} // Print the shortest pathvoid printPath(vector<int>& path){ int n = path.size(); for (int i = 0; i < n - 1; i++) cout << path[i] << \" -> \"; cout << path[n - 1] << endl;} // Driver codeint main(){ int V = 4; vector<vector<int> > graph = { { 0, 3, INF, 7 }, { 8, 0, 2, INF }, { 5, INF, 0, 1 }, { 2, INF, INF, 0 } }; // Function to initialise the // distance and Next array initialise(V, graph); // Calling Floyd Warshall Algorithm, // this will update the shortest // distance as well as Next array floydWarshall(V); vector<int> path; // Path from node 1 to 3 cout << \"Shortest path from 1 to 3: \"; path = constructPath(1, 3); printPath(path); // Path from node 0 to 2 cout << \"Shortest path from 0 to 2: \"; path = constructPath(0, 2); printPath(path); // path from node 3 to 2 cout << \"Shortest path from 3 to 2: \"; path = constructPath(3, 2); printPath(path); return 0;}",
"e": 4393,
"s": 1571,
"text": null
},
{
"code": "// Java program to find the shortest// path between any two nodes using// Floyd Warshall Algorithm.import java.util.*; class GFG{ static final int MAXN = 100; // Infinite value for arraystatic int INF = (int) 1e7; static int [][]dis = new int[MAXN][MAXN];static int [][]Next = new int[MAXN][MAXN]; // Initializing the distance and// Next arraystatic void initialise(int V, int [][] graph){ for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { dis[i][j] = graph[i][j]; // No edge between node // i and j if (graph[i][j] == INF) Next[i][j] = -1; else Next[i][j] = j; } }} // Function construct the shortest// path between u and vstatic Vector<Integer> constructPath(int u, int v){ // If there's no path between // node u and v, simply return // an empty array if (Next[u][v] == -1) return null; // Storing the path in a vector Vector<Integer> path = new Vector<Integer>(); path.add(u); while (u != v) { u = Next[u][v]; path.add(u); } return path;} // Standard Floyd Warshall Algorithm// with little modification Now if we find// that dis[i][j] > dis[i][k] + dis[k][j]// then we modify next[i][j] = next[i][k]static void floydWarshall(int V){ for(int k = 0; k < V; k++) { for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { // We cannot travel through // edge that doesn't exist if (dis[i][k] == INF || dis[k][j] == INF) continue; if (dis[i][j] > dis[i][k] + dis[k][j]) { dis[i][j] = dis[i][k] + dis[k][j]; Next[i][j] = Next[i][k]; } } } }} // Print the shortest pathstatic void printPath(Vector<Integer> path){ int n = path.size(); for(int i = 0; i < n - 1; i++) System.out.print(path.get(i) + \" -> \"); System.out.print(path.get(n - 1) + \"\\n\");} // Driver codepublic static void main(String[] args){ int V = 4; int [][] graph = { { 0, 3, INF, 7 }, { 8, 0, 2, INF }, { 5, INF, 0, 1 }, { 2, INF, INF, 0 } }; // Function to initialise the // distance and Next array initialise(V, graph); // Calling Floyd Warshall Algorithm, // this will update the shortest // distance as well as Next array floydWarshall(V); Vector<Integer> path; // Path from node 1 to 3 System.out.print(\"Shortest path from 1 to 3: \"); path = constructPath(1, 3); printPath(path); // Path from node 0 to 2 System.out.print(\"Shortest path from 0 to 2: \"); path = constructPath(0, 2); printPath(path); // Path from node 3 to 2 System.out.print(\"Shortest path from 3 to 2: \"); path = constructPath(3, 2); printPath(path);}} // This code is contributed by Amit Katiyar",
"e": 7426,
"s": 4393,
"text": null
},
{
"code": "# Python3 program to find the shortest# path between any two nodes using# Floyd Warshall Algorithm. # Initializing the distance and# Next arraydef initialise(V): global dis, Next for i in range(V): for j in range(V): dis[i][j] = graph[i][j] # No edge between node # i and j if (graph[i][j] == INF): Next[i][j] = -1 else: Next[i][j] = j # Function construct the shortest# path between u and vdef constructPath(u, v): global graph, Next # If there's no path between # node u and v, simply return # an empty array if (Next[u][v] == -1): return {} # Storing the path in a vector path = [u] while (u != v): u = Next[u][v] path.append(u) return path # Standard Floyd Warshall Algorithm# with little modification Now if we find# that dis[i][j] > dis[i][k] + dis[k][j]# then we modify next[i][j] = next[i][k]def floydWarshall(V): global dist, Next for k in range(V): for i in range(V): for j in range(V): # We cannot travel through # edge that doesn't exist if (dis[i][k] == INF or dis[k][j] == INF): continue if (dis[i][j] > dis[i][k] + dis[k][j]): dis[i][j] = dis[i][k] + dis[k][j] Next[i][j] = Next[i][k] # Print the shortest pathdef printPath(path): n = len(path) for i in range(n - 1): print(path[i], end=\" -> \") print (path[n - 1]) # Driver codeif __name__ == '__main__': MAXM,INF = 100,10**7 dis = [[-1 for i in range(MAXM)] for i in range(MAXM)] Next = [[-1 for i in range(MAXM)] for i in range(MAXM)] V = 4 graph = [ [ 0, 3, INF, 7 ], [ 8, 0, 2, INF ], [ 5, INF, 0, 1 ], [ 2, INF, INF, 0 ] ] # Function to initialise the # distance and Next array initialise(V) # Calling Floyd Warshall Algorithm, # this will update the shortest # distance as well as Next array floydWarshall(V) path = [] # Path from node 1 to 3 print(\"Shortest path from 1 to 3: \", end = \"\") path = constructPath(1, 3) printPath(path) # Path from node 0 to 2 print(\"Shortest path from 0 to 2: \", end = \"\") path = constructPath(0, 2) printPath(path) # Path from node 3 to 2 print(\"Shortest path from 3 to 2: \", end = \"\") path = constructPath(3, 2) printPath(path) # This code is contributed by mohit kumar 29",
"e": 9950,
"s": 7426,
"text": null
},
{
"code": "// C# program to find the shortest// path between any two nodes using// Floyd Warshall Algorithm.using System;using System.Collections.Generic; class GFG{ static readonly int MAXN = 100; // Infinite value for arraystatic int INF = (int)1e7; static int [,]dis = new int[MAXN, MAXN];static int [,]Next = new int[MAXN, MAXN]; // Initializing the distance and// Next arraystatic void initialise(int V, int [,] graph){ for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { dis[i, j] = graph[i, j]; // No edge between node // i and j if (graph[i, j] == INF) Next[i, j] = -1; else Next[i, j] = j; } }} // Function construct the shortest// path between u and vstatic List<int> constructPath(int u, int v){ // If there's no path between // node u and v, simply return // an empty array if (Next[u, v] == -1) return null; // Storing the path in a vector List<int> path = new List<int>(); path.Add(u); while (u != v) { u = Next[u, v]; path.Add(u); } return path;} // Standard Floyd Warshall Algorithm// with little modification Now if we find// that dis[i,j] > dis[i,k] + dis[k,j]// then we modify next[i,j] = next[i,k]static void floydWarshall(int V){ for(int k = 0; k < V; k++) { for(int i = 0; i < V; i++) { for(int j = 0; j < V; j++) { // We cannot travel through // edge that doesn't exist if (dis[i, k] == INF || dis[k, j] == INF) continue; if (dis[i, j] > dis[i, k] + dis[k, j]) { dis[i, j] = dis[i, k] + dis[k, j]; Next[i, j] = Next[i, k]; } } } }} // Print the shortest pathstatic void printPath(List<int> path){ int n = path.Count; for(int i = 0; i < n - 1; i++) Console.Write(path[i] + \" -> \"); Console.Write(path[n - 1] + \"\\n\");} // Driver codepublic static void Main(String[] args){ int V = 4; int [,] graph = { { 0, 3, INF, 7 }, { 8, 0, 2, INF }, { 5, INF, 0, 1 }, { 2, INF, INF, 0 } }; // Function to initialise the // distance and Next array initialise(V, graph); // Calling Floyd Warshall Algorithm, // this will update the shortest // distance as well as Next array floydWarshall(V); List<int> path; // Path from node 1 to 3 Console.Write(\"Shortest path from 1 to 3: \"); path = constructPath(1, 3); printPath(path); // Path from node 0 to 2 Console.Write(\"Shortest path from 0 to 2: \"); path = constructPath(0, 2); printPath(path); // Path from node 3 to 2 Console.Write(\"Shortest path from 3 to 2: \"); path = constructPath(3, 2); printPath(path);}} // This code is contributed by Amit Katiyar",
"e": 13067,
"s": 9950,
"text": null
},
{
"code": "<script> // Javascript program to find the shortest// path between any two nodes using// Floyd Warshall Algorithm.let MAXN = 100; // Infinite value for arraylet INF = 1e7;let dis = new Array(MAXN);let Next = new Array(MAXN);for(let i = 0; i < MAXN; i++){ dis[i] = new Array(MAXN); Next[i] = new Array(MAXN);} // Initializing the distance and// Next arrayfunction initialise(V, graph){ for(let i = 0; i < V; i++) { for(let j = 0; j < V; j++) { dis[i][j] = graph[i][j]; // No edge between node // i and j if (graph[i][j] == INF) Next[i][j] = -1; else Next[i][j] = j; } }} // Function construct the shortest// path between u and vfunction constructPath(u, v){ // If there's no path between // node u and v, simply return // an empty array if (Next[u][v] == -1) return null; // Storing the path in a vector let path = []; path.push(u); while (u != v) { u = Next[u][v]; path.push(u); } return path;} // Standard Floyd Warshall Algorithm// with little modification Now if we find// that dis[i][j] > dis[i][k] + dis[k][j]// then we modify next[i][j] = next[i][k]function floydWarshall(V){ for(let k = 0; k < V; k++) { for(let i = 0; i < V; i++) { for(let j = 0; j < V; j++) { // We cannot travel through // edge that doesn't exist if (dis[i][k] == INF || dis[k][j] == INF) continue; if (dis[i][j] > dis[i][k] + dis[k][j]) { dis[i][j] = dis[i][k] + dis[k][j]; Next[i][j] = Next[i][k]; } } } }} // Print the shortest pathfunction printPath(path){ let n = path.length; for(let i = 0; i < n - 1; i++) document.write(path[i] + \" -> \"); document.write(path[n - 1] + \"<br>\");} // Driver codelet V = 4;let graph = [ [ 0, 3, INF, 7 ], [ 8, 0, 2, INF ], [ 5, INF, 0, 1 ], [ 2, INF, INF, 0 ] ]; // Function to initialise the// distance and Next arrayinitialise(V, graph); // Calling Floyd Warshall Algorithm,// this will update the shortest// distance as well as Next arrayfloydWarshall(V);let path; // Path from node 1 to 3document.write(\"Shortest path from 1 to 3: \");path = constructPath(1, 3);printPath(path); // Path from node 0 to 2document.write(\"Shortest path from 0 to 2: \");path = constructPath(0, 2);printPath(path); // Path from node 3 to 2document.write(\"Shortest path from 3 to 2: \");path = constructPath(3, 2);printPath(path); // This code is contributed by unknown2108 </script>",
"e": 15945,
"s": 13067,
"text": null
},
{
"code": null,
"e": 16067,
"s": 15945,
"text": "Shortest path from 1 to 3: 1 -> 2 -> 3\nShortest path from 0 to 2: 0 -> 1 -> 2\nShortest path from 3 to 2: 3 -> 0 -> 1 -> 2"
},
{
"code": null,
"e": 16091,
"s": 16069,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 16149,
"s": 16091,
"text": "The time complexity for Floyd Warshall Algorithm is O(V3)"
},
{
"code": null,
"e": 16212,
"s": 16149,
"text": "For finding shortest path time complexity is O(V) per query. "
},
{
"code": null,
"e": 16401,
"s": 16212,
"text": "Note: It would be efficient to use the Floyd Warshall Algorithm when your graph contains a couple of hundred vertices and you need to answer multiple queries related to the shortest path. "
},
{
"code": null,
"e": 16416,
"s": 16401,
"text": "amit143katiyar"
},
{
"code": null,
"e": 16431,
"s": 16416,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 16442,
"s": 16431,
"text": "nidhi_biet"
},
{
"code": null,
"e": 16454,
"s": 16442,
"text": "unknown2108"
},
{
"code": null,
"e": 16469,
"s": 16454,
"text": "varshagumber28"
},
{
"code": null,
"e": 16481,
"s": 16469,
"text": "anikakapoor"
},
{
"code": null,
"e": 16518,
"s": 16481,
"text": "Algorithms-Graph Shortest Paths Quiz"
},
{
"code": null,
"e": 16544,
"s": 16518,
"text": "Graph Shortest Paths Quiz"
},
{
"code": null,
"e": 16568,
"s": 16544,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 16579,
"s": 16568,
"text": "Algorithms"
},
{
"code": null,
"e": 16599,
"s": 16579,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 16605,
"s": 16599,
"text": "Graph"
},
{
"code": null,
"e": 16625,
"s": 16605,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 16631,
"s": 16625,
"text": "Graph"
},
{
"code": null,
"e": 16642,
"s": 16631,
"text": "Algorithms"
},
{
"code": null,
"e": 16740,
"s": 16642,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16774,
"s": 16740,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 16814,
"s": 16774,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 16856,
"s": 16814,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 16892,
"s": 16856,
"text": "Binary Indexed Tree or Fenwick Tree"
},
{
"code": null,
"e": 16920,
"s": 16892,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 16945,
"s": 16920,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 16994,
"s": 16945,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 17038,
"s": 16994,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 17069,
"s": 17038,
"text": "Difference between BFS and DFS"
}
] |
Derived Data Types in C++
|
26 Feb, 2020
Data types are means to identify the type of data and associated operations of handling it. There are three types of data types:
Pre-defined DataTypesDerived Data TypesUser-defined DataTypes
Pre-defined DataTypes
Derived Data Types
User-defined DataTypes
In this article, the Derived Data Type is explained:
The data-types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. These can be of four types namely:
Function
Array
Pointers
References
Let’s briefly understand each of the following derived datatypes:
Function: A function is a block of code or program-segment that is defined to perform a specific well-defined task. A function is generally defined to save the user from writing the same lines of code again and again for the same input. All the lines of code are put together inside a single function and this can be called anywhere required. main() is a default function that is defined in every program of C++.Syntax:FunctionType FunctionName(parameters)Example:// C++ program to demonstrate// Function Derived Type #include <iostream>using namespace std; // max here is a function derived typeint max(int x, int y){ if (x > y) return x; else return y;} // main is the default function derived typeint main(){ int a = 10, b = 20; // Calling above function to // find max of 'a' and 'b' int m = max(a, b); cout << "m is " << m; return 0;}Output:m is 20
Array: An array is a collection of items stored at continuous memory locations. The idea of array is to represent many instances in one variable.Syntax:DataType ArrayName[size_of_array];Example:// C++ program to demonstrate// Array Derived Type #include <iostream>using namespace std;int main(){ // Array Derived Type int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3]; return 0;}Output:5 2 -10 5
Pointers: Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the format:Syntax:datatype *var_name;Example:int *ptr;
ptr points to an address
which holds int dataExample:// C++ program to illustrate// Pointers Derived Type #include <bits/stdc++.h>using namespace std; void geeks(){ int var = 20; // Pointers Derived Type // declare pointer variable int* ptr; // note that data type of ptr // and var must be same ptr = &var; // assign the address of a variable // to a pointer cout << "Value at ptr = " << ptr << "\n"; cout << "Value at var = " << var << "\n"; cout << "Value at *ptr = " << *ptr << "\n";} // Driver programint main(){ geeks();}Output:Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20
Reference: When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.Example:// C++ program to illustrate// Reference Derived Type #include <iostream>using namespace std; int main(){ int x = 10; // Reference Derived Type // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << "x = " << x << endl; // Value of x is now changed to 30 x = 30; cout << "ref = " << ref << endl; return 0;}Output:x = 20
ref = 30
Function: A function is a block of code or program-segment that is defined to perform a specific well-defined task. A function is generally defined to save the user from writing the same lines of code again and again for the same input. All the lines of code are put together inside a single function and this can be called anywhere required. main() is a default function that is defined in every program of C++.Syntax:FunctionType FunctionName(parameters)Example:// C++ program to demonstrate// Function Derived Type #include <iostream>using namespace std; // max here is a function derived typeint max(int x, int y){ if (x > y) return x; else return y;} // main is the default function derived typeint main(){ int a = 10, b = 20; // Calling above function to // find max of 'a' and 'b' int m = max(a, b); cout << "m is " << m; return 0;}Output:m is 20
Syntax:
FunctionType FunctionName(parameters)
Example:
// C++ program to demonstrate// Function Derived Type #include <iostream>using namespace std; // max here is a function derived typeint max(int x, int y){ if (x > y) return x; else return y;} // main is the default function derived typeint main(){ int a = 10, b = 20; // Calling above function to // find max of 'a' and 'b' int m = max(a, b); cout << "m is " << m; return 0;}
m is 20
Array: An array is a collection of items stored at continuous memory locations. The idea of array is to represent many instances in one variable.Syntax:DataType ArrayName[size_of_array];Example:// C++ program to demonstrate// Array Derived Type #include <iostream>using namespace std;int main(){ // Array Derived Type int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3]; return 0;}Output:5 2 -10 5
Syntax:
DataType ArrayName[size_of_array];
Example:
// C++ program to demonstrate// Array Derived Type #include <iostream>using namespace std;int main(){ // Array Derived Type int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3]; return 0;}
5 2 -10 5
Pointers: Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the format:Syntax:datatype *var_name;Example:int *ptr;
ptr points to an address
which holds int dataExample:// C++ program to illustrate// Pointers Derived Type #include <bits/stdc++.h>using namespace std; void geeks(){ int var = 20; // Pointers Derived Type // declare pointer variable int* ptr; // note that data type of ptr // and var must be same ptr = &var; // assign the address of a variable // to a pointer cout << "Value at ptr = " << ptr << "\n"; cout << "Value at var = " << var << "\n"; cout << "Value at *ptr = " << *ptr << "\n";} // Driver programint main(){ geeks();}Output:Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20
Syntax:
datatype *var_name;
Example:
int *ptr;
ptr points to an address
which holds int data
Example:
// C++ program to illustrate// Pointers Derived Type #include <bits/stdc++.h>using namespace std; void geeks(){ int var = 20; // Pointers Derived Type // declare pointer variable int* ptr; // note that data type of ptr // and var must be same ptr = &var; // assign the address of a variable // to a pointer cout << "Value at ptr = " << ptr << "\n"; cout << "Value at var = " << var << "\n"; cout << "Value at *ptr = " << *ptr << "\n";} // Driver programint main(){ geeks();}
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20
Reference: When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.Example:// C++ program to illustrate// Reference Derived Type #include <iostream>using namespace std; int main(){ int x = 10; // Reference Derived Type // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << "x = " << x << endl; // Value of x is now changed to 30 x = 30; cout << "ref = " << ref << endl; return 0;}Output:x = 20
ref = 30
Example:
// C++ program to illustrate// Reference Derived Type #include <iostream>using namespace std; int main(){ int x = 10; // Reference Derived Type // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << "x = " << x << endl; // Value of x is now changed to 30 x = 30; cout << "ref = " << ref << endl; return 0;}
x = 20
ref = 30
saisarat_219
C Basics
C++
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++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Feb, 2020"
},
{
"code": null,
"e": 181,
"s": 52,
"text": "Data types are means to identify the type of data and associated operations of handling it. There are three types of data types:"
},
{
"code": null,
"e": 243,
"s": 181,
"text": "Pre-defined DataTypesDerived Data TypesUser-defined DataTypes"
},
{
"code": null,
"e": 265,
"s": 243,
"text": "Pre-defined DataTypes"
},
{
"code": null,
"e": 284,
"s": 265,
"text": "Derived Data Types"
},
{
"code": null,
"e": 307,
"s": 284,
"text": "User-defined DataTypes"
},
{
"code": null,
"e": 360,
"s": 307,
"text": "In this article, the Derived Data Type is explained:"
},
{
"code": null,
"e": 507,
"s": 360,
"text": "The data-types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. These can be of four types namely:"
},
{
"code": null,
"e": 516,
"s": 507,
"text": "Function"
},
{
"code": null,
"e": 522,
"s": 516,
"text": "Array"
},
{
"code": null,
"e": 531,
"s": 522,
"text": "Pointers"
},
{
"code": null,
"e": 542,
"s": 531,
"text": "References"
},
{
"code": null,
"e": 608,
"s": 542,
"text": "Let’s briefly understand each of the following derived datatypes:"
},
{
"code": null,
"e": 3592,
"s": 608,
"text": "Function: A function is a block of code or program-segment that is defined to perform a specific well-defined task. A function is generally defined to save the user from writing the same lines of code again and again for the same input. All the lines of code are put together inside a single function and this can be called anywhere required. main() is a default function that is defined in every program of C++.Syntax:FunctionType FunctionName(parameters)Example:// C++ program to demonstrate// Function Derived Type #include <iostream>using namespace std; // max here is a function derived typeint max(int x, int y){ if (x > y) return x; else return y;} // main is the default function derived typeint main(){ int a = 10, b = 20; // Calling above function to // find max of 'a' and 'b' int m = max(a, b); cout << \"m is \" << m; return 0;}Output:m is 20\nArray: An array is a collection of items stored at continuous memory locations. The idea of array is to represent many instances in one variable.Syntax:DataType ArrayName[size_of_array];Example:// C++ program to demonstrate// Array Derived Type #include <iostream>using namespace std;int main(){ // Array Derived Type int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout<<arr[0]<<\" \"<<arr[1]<<\" \"<<arr[2]<<\" \"<<arr[3]; return 0;}Output:5 2 -10 5\nPointers: Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the format:Syntax:datatype *var_name;Example:int *ptr; \n\nptr points to an address\nwhich holds int dataExample:// C++ program to illustrate// Pointers Derived Type #include <bits/stdc++.h>using namespace std; void geeks(){ int var = 20; // Pointers Derived Type // declare pointer variable int* ptr; // note that data type of ptr // and var must be same ptr = &var; // assign the address of a variable // to a pointer cout << \"Value at ptr = \" << ptr << \"\\n\"; cout << \"Value at var = \" << var << \"\\n\"; cout << \"Value at *ptr = \" << *ptr << \"\\n\";} // Driver programint main(){ geeks();}Output:Value at ptr = 0x7ffc10d7fd5c\nValue at var = 20\nValue at *ptr = 20\nReference: When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.Example:// C++ program to illustrate// Reference Derived Type #include <iostream>using namespace std; int main(){ int x = 10; // Reference Derived Type // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << \"x = \" << x << endl; // Value of x is now changed to 30 x = 30; cout << \"ref = \" << ref << endl; return 0;}Output:x = 20\nref = 30\n"
},
{
"code": null,
"e": 4492,
"s": 3592,
"text": "Function: A function is a block of code or program-segment that is defined to perform a specific well-defined task. A function is generally defined to save the user from writing the same lines of code again and again for the same input. All the lines of code are put together inside a single function and this can be called anywhere required. main() is a default function that is defined in every program of C++.Syntax:FunctionType FunctionName(parameters)Example:// C++ program to demonstrate// Function Derived Type #include <iostream>using namespace std; // max here is a function derived typeint max(int x, int y){ if (x > y) return x; else return y;} // main is the default function derived typeint main(){ int a = 10, b = 20; // Calling above function to // find max of 'a' and 'b' int m = max(a, b); cout << \"m is \" << m; return 0;}Output:m is 20\n"
},
{
"code": null,
"e": 4500,
"s": 4492,
"text": "Syntax:"
},
{
"code": null,
"e": 4538,
"s": 4500,
"text": "FunctionType FunctionName(parameters)"
},
{
"code": null,
"e": 4547,
"s": 4538,
"text": "Example:"
},
{
"code": "// C++ program to demonstrate// Function Derived Type #include <iostream>using namespace std; // max here is a function derived typeint max(int x, int y){ if (x > y) return x; else return y;} // main is the default function derived typeint main(){ int a = 10, b = 20; // Calling above function to // find max of 'a' and 'b' int m = max(a, b); cout << \"m is \" << m; return 0;}",
"e": 4968,
"s": 4547,
"text": null
},
{
"code": null,
"e": 4977,
"s": 4968,
"text": "m is 20\n"
},
{
"code": null,
"e": 5515,
"s": 4977,
"text": "Array: An array is a collection of items stored at continuous memory locations. The idea of array is to represent many instances in one variable.Syntax:DataType ArrayName[size_of_array];Example:// C++ program to demonstrate// Array Derived Type #include <iostream>using namespace std;int main(){ // Array Derived Type int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout<<arr[0]<<\" \"<<arr[1]<<\" \"<<arr[2]<<\" \"<<arr[3]; return 0;}Output:5 2 -10 5\n"
},
{
"code": null,
"e": 5523,
"s": 5515,
"text": "Syntax:"
},
{
"code": null,
"e": 5558,
"s": 5523,
"text": "DataType ArrayName[size_of_array];"
},
{
"code": null,
"e": 5567,
"s": 5558,
"text": "Example:"
},
{
"code": "// C++ program to demonstrate// Array Derived Type #include <iostream>using namespace std;int main(){ // Array Derived Type int arr[5]; arr[0] = 5; arr[2] = -10; // this is same as arr[1] = 2 arr[3 / 2] = 2; arr[3] = arr[0]; cout<<arr[0]<<\" \"<<arr[1]<<\" \"<<arr[2]<<\" \"<<arr[3]; return 0;}",
"e": 5894,
"s": 5567,
"text": null
},
{
"code": null,
"e": 5905,
"s": 5894,
"text": "5 2 -10 5\n"
},
{
"code": null,
"e": 6849,
"s": 5905,
"text": "Pointers: Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the format:Syntax:datatype *var_name;Example:int *ptr; \n\nptr points to an address\nwhich holds int dataExample:// C++ program to illustrate// Pointers Derived Type #include <bits/stdc++.h>using namespace std; void geeks(){ int var = 20; // Pointers Derived Type // declare pointer variable int* ptr; // note that data type of ptr // and var must be same ptr = &var; // assign the address of a variable // to a pointer cout << \"Value at ptr = \" << ptr << \"\\n\"; cout << \"Value at var = \" << var << \"\\n\"; cout << \"Value at *ptr = \" << *ptr << \"\\n\";} // Driver programint main(){ geeks();}Output:Value at ptr = 0x7ffc10d7fd5c\nValue at var = 20\nValue at *ptr = 20\n"
},
{
"code": null,
"e": 6857,
"s": 6849,
"text": "Syntax:"
},
{
"code": null,
"e": 6877,
"s": 6857,
"text": "datatype *var_name;"
},
{
"code": null,
"e": 6886,
"s": 6877,
"text": "Example:"
},
{
"code": null,
"e": 6946,
"s": 6886,
"text": "int *ptr; \n\nptr points to an address\nwhich holds int data"
},
{
"code": null,
"e": 6955,
"s": 6946,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// Pointers Derived Type #include <bits/stdc++.h>using namespace std; void geeks(){ int var = 20; // Pointers Derived Type // declare pointer variable int* ptr; // note that data type of ptr // and var must be same ptr = &var; // assign the address of a variable // to a pointer cout << \"Value at ptr = \" << ptr << \"\\n\"; cout << \"Value at var = \" << var << \"\\n\"; cout << \"Value at *ptr = \" << *ptr << \"\\n\";} // Driver programint main(){ geeks();}",
"e": 7502,
"s": 6955,
"text": null
},
{
"code": null,
"e": 7570,
"s": 7502,
"text": "Value at ptr = 0x7ffc10d7fd5c\nValue at var = 20\nValue at *ptr = 20\n"
},
{
"code": null,
"e": 8175,
"s": 7570,
"text": "Reference: When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.Example:// C++ program to illustrate// Reference Derived Type #include <iostream>using namespace std; int main(){ int x = 10; // Reference Derived Type // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << \"x = \" << x << endl; // Value of x is now changed to 30 x = 30; cout << \"ref = \" << ref << endl; return 0;}Output:x = 20\nref = 30\n"
},
{
"code": null,
"e": 8184,
"s": 8175,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// Reference Derived Type #include <iostream>using namespace std; int main(){ int x = 10; // Reference Derived Type // ref is a reference to x. int& ref = x; // Value of x is now changed to 20 ref = 20; cout << \"x = \" << x << endl; // Value of x is now changed to 30 x = 30; cout << \"ref = \" << ref << endl; return 0;}",
"e": 8574,
"s": 8184,
"text": null
},
{
"code": null,
"e": 8591,
"s": 8574,
"text": "x = 20\nref = 30\n"
},
{
"code": null,
"e": 8604,
"s": 8591,
"text": "saisarat_219"
},
{
"code": null,
"e": 8613,
"s": 8604,
"text": "C Basics"
},
{
"code": null,
"e": 8617,
"s": 8613,
"text": "C++"
},
{
"code": null,
"e": 8621,
"s": 8617,
"text": "CPP"
},
{
"code": null,
"e": 8719,
"s": 8621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8743,
"s": 8719,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 8763,
"s": 8743,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 8807,
"s": 8763,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8840,
"s": 8807,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 8865,
"s": 8840,
"text": "std::string class in C++"
},
{
"code": null,
"e": 8910,
"s": 8865,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 8927,
"s": 8910,
"text": "std::find in C++"
},
{
"code": null,
"e": 8975,
"s": 8927,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 9019,
"s": 8975,
"text": "List in C++ Standard Template Library (STL)"
}
] |
How to Install Apache Tomcat 8 on Linux?
|
06 Oct, 2021
Apache Tomcat (short for “Tomcat”) is a free and open-source Java Servlet, JavaServer Pages, Java Expression Language, and WebSocket implementation. [two] Tomcat is an HTTP web server that runs Java code in a “pure Java” environment.
Tomcat is developed and maintained by a free group of developers under the Apache Software Foundation’s auspices and is licensed under the Apache License 2.0. In this article, we are going to see how to install Apache Tomcat 8 on Linux systems.
Create a directory named tomcat in the /opt folder:
$ mkdir /opt/tomcat
Create a directory
Change directory to tomcat:
$ cd /opt/tomcat
Change directory to tomcat
Go to the Apache Tomcat 8 Download page by clicking this link. Place your cursor under 8.5.65 Binary Distributions, right-click on the tar file and select the copy link address from the menu that appears (as shown in the picture below). At the time of writing, Tomcat 8 is the most recent edition, but you are free to use whatever version is most current.
Next, use the wget command to download the tar from the URL you copied in the previous stage to the tomcat folder on your server:
$ sudo wget https://apachemirror.wuchna.com/tomcat/tomcat-8/v8.5.65/bin/apache-tomcat-8.5.65.tar.gz
Decompress the file in your tomcat folder after it has finished downloading:
$ tar xvzf apache-tomcat-8.5.65.tar.gz
Decompress the file
You must first install the Java Development Kit before you can use Tomcat (JDK). Check to see if Java is installed first:
$ apt-get install default-jdk
Installing the Java Development Kit
Now verify java installed properly:
$ java -version
Verify java installed properly
Use the following command to set the environment variables in .bashrc:
$ nano ~/.bashrc
Add the following lines to the file’s end:
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64
export CATALINA_HOME=/opt/tomcat/apache-tomcat-8.5.65
After you’ve saved your changes and exited the .bashrc file, run the following command to make the changes take effect:
$ . ~/.bashrc
Your server should now have Tomcat and Java enabled and configured. Run the following script to start Tomcat:
$ $CATALINA_HOME/bin/startup.sh
In a web browser, go to YourIPAddress:8080 to see if Tomcat is up and running. http://127.0.0.1:8080, for example.
how-to-install
Picked
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Install Git in VS Code?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 288,
"s": 54,
"text": "Apache Tomcat (short for “Tomcat”) is a free and open-source Java Servlet, JavaServer Pages, Java Expression Language, and WebSocket implementation. [two] Tomcat is an HTTP web server that runs Java code in a “pure Java” environment."
},
{
"code": null,
"e": 533,
"s": 288,
"text": "Tomcat is developed and maintained by a free group of developers under the Apache Software Foundation’s auspices and is licensed under the Apache License 2.0. In this article, we are going to see how to install Apache Tomcat 8 on Linux systems."
},
{
"code": null,
"e": 585,
"s": 533,
"text": "Create a directory named tomcat in the /opt folder:"
},
{
"code": null,
"e": 605,
"s": 585,
"text": "$ mkdir /opt/tomcat"
},
{
"code": null,
"e": 624,
"s": 605,
"text": "Create a directory"
},
{
"code": null,
"e": 652,
"s": 624,
"text": "Change directory to tomcat:"
},
{
"code": null,
"e": 669,
"s": 652,
"text": "$ cd /opt/tomcat"
},
{
"code": null,
"e": 696,
"s": 669,
"text": "Change directory to tomcat"
},
{
"code": null,
"e": 1052,
"s": 696,
"text": "Go to the Apache Tomcat 8 Download page by clicking this link. Place your cursor under 8.5.65 Binary Distributions, right-click on the tar file and select the copy link address from the menu that appears (as shown in the picture below). At the time of writing, Tomcat 8 is the most recent edition, but you are free to use whatever version is most current."
},
{
"code": null,
"e": 1182,
"s": 1052,
"text": "Next, use the wget command to download the tar from the URL you copied in the previous stage to the tomcat folder on your server:"
},
{
"code": null,
"e": 1282,
"s": 1182,
"text": "$ sudo wget https://apachemirror.wuchna.com/tomcat/tomcat-8/v8.5.65/bin/apache-tomcat-8.5.65.tar.gz"
},
{
"code": null,
"e": 1359,
"s": 1282,
"text": "Decompress the file in your tomcat folder after it has finished downloading:"
},
{
"code": null,
"e": 1398,
"s": 1359,
"text": "$ tar xvzf apache-tomcat-8.5.65.tar.gz"
},
{
"code": null,
"e": 1418,
"s": 1398,
"text": "Decompress the file"
},
{
"code": null,
"e": 1540,
"s": 1418,
"text": "You must first install the Java Development Kit before you can use Tomcat (JDK). Check to see if Java is installed first:"
},
{
"code": null,
"e": 1570,
"s": 1540,
"text": "$ apt-get install default-jdk"
},
{
"code": null,
"e": 1606,
"s": 1570,
"text": "Installing the Java Development Kit"
},
{
"code": null,
"e": 1642,
"s": 1606,
"text": "Now verify java installed properly:"
},
{
"code": null,
"e": 1658,
"s": 1642,
"text": "$ java -version"
},
{
"code": null,
"e": 1689,
"s": 1658,
"text": "Verify java installed properly"
},
{
"code": null,
"e": 1761,
"s": 1689,
"text": "Use the following command to set the environment variables in .bashrc: "
},
{
"code": null,
"e": 1778,
"s": 1761,
"text": "$ nano ~/.bashrc"
},
{
"code": null,
"e": 1821,
"s": 1778,
"text": "Add the following lines to the file’s end:"
},
{
"code": null,
"e": 1930,
"s": 1821,
"text": "export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64\nexport CATALINA_HOME=/opt/tomcat/apache-tomcat-8.5.65"
},
{
"code": null,
"e": 2050,
"s": 1930,
"text": "After you’ve saved your changes and exited the .bashrc file, run the following command to make the changes take effect:"
},
{
"code": null,
"e": 2064,
"s": 2050,
"text": "$ . ~/.bashrc"
},
{
"code": null,
"e": 2174,
"s": 2064,
"text": "Your server should now have Tomcat and Java enabled and configured. Run the following script to start Tomcat:"
},
{
"code": null,
"e": 2206,
"s": 2174,
"text": "$ $CATALINA_HOME/bin/startup.sh"
},
{
"code": null,
"e": 2321,
"s": 2206,
"text": "In a web browser, go to YourIPAddress:8080 to see if Tomcat is up and running. http://127.0.0.1:8080, for example."
},
{
"code": null,
"e": 2336,
"s": 2321,
"text": "how-to-install"
},
{
"code": null,
"e": 2343,
"s": 2336,
"text": "Picked"
},
{
"code": null,
"e": 2350,
"s": 2343,
"text": "How To"
},
{
"code": null,
"e": 2369,
"s": 2350,
"text": "Installation Guide"
},
{
"code": null,
"e": 2380,
"s": 2369,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2478,
"s": 2380,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2527,
"s": 2478,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2569,
"s": 2527,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2608,
"s": 2569,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2662,
"s": 2608,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 2693,
"s": 2662,
"text": "How to Install Git in VS Code?"
},
{
"code": null,
"e": 2726,
"s": 2693,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2761,
"s": 2726,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2803,
"s": 2761,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2842,
"s": 2803,
"text": "How to Install and Use NVM on Windows?"
}
] |
Find the percentage change in the area of a Rectangle
|
16 Apr, 2020
Given two integers P and Q which represents the percentage change in the length and breadth of the rectangle, the task is to print the percentage change in the area of the rectangle.
Examples:
Input: P = 10, Q = 20Output: 32Explanation:Let the initial length of the rectangle be 100 and breadth be 80.Initial area = 8000.New length = 110 and new breadth = 96. Therefore, the new area = 10560.The percentage change in the area = ((10560 – 8000) / 8000) * 100 = 32.
Input: P = 20, Q = -10Output: 8Let initial length of the rectangle be 100 and breadth be 80.Initial area = 8000.New length = 120 and new breadth = 72. Therefore, new area = 8640.The percentage change in the area = ((8640 – 8000) / 8000) * 100 = 8.
Approach:
Since the area of the rectangle is given by the formula:area = length * breadth
area = length * breadth
Let the initial length of the rectangle be L and the breadth of the rectangle be B. Therefore, the initial area is given by L * B.
Therefore, the new length and breadth are given as:L' = L + ((P/100)*L)
B' = B + ((Q/100)*B)
L' = L + ((P/100)*L)
B' = B + ((Q/100)*B)
Therefore, the new length and breadth are given as:new area = [L + ((C/100)*L)] * [B + ( ( D / 100) * B)]
new area = [L + ((C/100)*L)] * [B + ( ( D / 100) * B)]
The percentage change in the area is given by the formula:% change = ((new area – old area) / old area )*100
% change = ((new area – old area) / old area )*100
Below is the implementation of the above approach:
C++
Java
Python3
C#
// CPP implementation to find the percentage#include <bits/stdc++.h>using namespace std; // change in the area when the percentage change// in the length and breadth is given // Function to calculate percentage// change in area of rectangleint calculate_change(int length, int breadth){ int change = 0; change = length + breadth+((length * breadth)/100); return change; } // Driver codeint main(){ int cL = 20; int cB = -10; int cA = calculate_change(cL, cB); printf("%d",cA); return 0;}
// Java implementation to find the percentageimport java.util.*; class GFG{ // change in the area when the percentage change // in the length and breadth is given // Function to calculate percentage // change in area of rectangle static int calculate_change(int length, int breadth){ int change = 0; change = length + breadth+((length * breadth)/100); return change; } // Driver code public static void main(String args[]) { int cL = 20; int cB = -10; int cA = calculate_change(cL, cB); System.out.println(+ cA); }} // This code is contributed by AbhiThakur
# Python3 implementation to find the percentage# change in the area when the percentage change# in the length and breadth is given # Function to calculate percentage # change in area of rectangledef calculate_change(length, breadth): change = 0 change = length + breadth+((length * breadth)//100) return change # Driver codeif __name__ == "__main__": cL = 20 cB = -10 cA = calculate_change(cL, cB) print(cA) # This code is contributed by mohit kumar 29
// C# implementation to find the percentageusing System;using System.Collections.Generic;using System.Linq; class GFG { // change in the area when the percentage change// in the length and breadth is given // Function to calculate percentage// change in area of rectanglestatic int calculate_change(int length, int breadth){ int change = 0; change = length + breadth + ((length * breadth)/100); return change;} // Driver Codepublic static void Main(String[] args) { int cL = 20; int cB = -10; int cA = calculate_change(cL, cB); Console.Write(cA);}} // This code is contributed by shivanisinghss2110
8
Time Complexity: O(1)
mohit kumar 29
abhaysingh290895
shivanisinghss2110
area-volume-programs
square-rectangle
Aptitude
Geometric
Mathematical
School Programming
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Order and Ranking Questions & Answers
Puzzle | How much money did the man have before entering the bank?
Aptitude | Arithmetic Aptitude 2 | Question 8
Seating Arrangement | Aptitude
Aptitude | GATE CS 1998 | Question 48
Program for distance between two points on earth
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
How to check if two given line segments intersect?
Find if two rectangles overlap
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Apr, 2020"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "Given two integers P and Q which represents the percentage change in the length and breadth of the rectangle, the task is to print the percentage change in the area of the rectangle."
},
{
"code": null,
"e": 221,
"s": 211,
"text": "Examples:"
},
{
"code": null,
"e": 492,
"s": 221,
"text": "Input: P = 10, Q = 20Output: 32Explanation:Let the initial length of the rectangle be 100 and breadth be 80.Initial area = 8000.New length = 110 and new breadth = 96. Therefore, the new area = 10560.The percentage change in the area = ((10560 – 8000) / 8000) * 100 = 32."
},
{
"code": null,
"e": 740,
"s": 492,
"text": "Input: P = 20, Q = -10Output: 8Let initial length of the rectangle be 100 and breadth be 80.Initial area = 8000.New length = 120 and new breadth = 72. Therefore, new area = 8640.The percentage change in the area = ((8640 – 8000) / 8000) * 100 = 8."
},
{
"code": null,
"e": 750,
"s": 740,
"text": "Approach:"
},
{
"code": null,
"e": 831,
"s": 750,
"text": "Since the area of the rectangle is given by the formula:area = length * breadth\n"
},
{
"code": null,
"e": 856,
"s": 831,
"text": "area = length * breadth\n"
},
{
"code": null,
"e": 987,
"s": 856,
"text": "Let the initial length of the rectangle be L and the breadth of the rectangle be B. Therefore, the initial area is given by L * B."
},
{
"code": null,
"e": 1081,
"s": 987,
"text": "Therefore, the new length and breadth are given as:L' = L + ((P/100)*L)\nB' = B + ((Q/100)*B)\n"
},
{
"code": null,
"e": 1124,
"s": 1081,
"text": "L' = L + ((P/100)*L)\nB' = B + ((Q/100)*B)\n"
},
{
"code": null,
"e": 1230,
"s": 1124,
"text": "Therefore, the new length and breadth are given as:new area = [L + ((C/100)*L)] * [B + ( ( D / 100) * B)]"
},
{
"code": null,
"e": 1285,
"s": 1230,
"text": "new area = [L + ((C/100)*L)] * [B + ( ( D / 100) * B)]"
},
{
"code": null,
"e": 1394,
"s": 1285,
"text": "The percentage change in the area is given by the formula:% change = ((new area – old area) / old area )*100"
},
{
"code": null,
"e": 1445,
"s": 1394,
"text": "% change = ((new area – old area) / old area )*100"
},
{
"code": null,
"e": 1496,
"s": 1445,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1500,
"s": 1496,
"text": "C++"
},
{
"code": null,
"e": 1505,
"s": 1500,
"text": "Java"
},
{
"code": null,
"e": 1513,
"s": 1505,
"text": "Python3"
},
{
"code": null,
"e": 1516,
"s": 1513,
"text": "C#"
},
{
"code": "// CPP implementation to find the percentage#include <bits/stdc++.h>using namespace std; // change in the area when the percentage change// in the length and breadth is given // Function to calculate percentage// change in area of rectangleint calculate_change(int length, int breadth){ int change = 0; change = length + breadth+((length * breadth)/100); return change; } // Driver codeint main(){ int cL = 20; int cB = -10; int cA = calculate_change(cL, cB); printf(\"%d\",cA); return 0;}",
"e": 2024,
"s": 1516,
"text": null
},
{
"code": "// Java implementation to find the percentageimport java.util.*; class GFG{ // change in the area when the percentage change // in the length and breadth is given // Function to calculate percentage // change in area of rectangle static int calculate_change(int length, int breadth){ int change = 0; change = length + breadth+((length * breadth)/100); return change; } // Driver code public static void main(String args[]) { int cL = 20; int cB = -10; int cA = calculate_change(cL, cB); System.out.println(+ cA); }} // This code is contributed by AbhiThakur ",
"e": 2691,
"s": 2024,
"text": null
},
{
"code": "# Python3 implementation to find the percentage# change in the area when the percentage change# in the length and breadth is given # Function to calculate percentage # change in area of rectangledef calculate_change(length, breadth): change = 0 change = length + breadth+((length * breadth)//100) return change # Driver codeif __name__ == \"__main__\": cL = 20 cB = -10 cA = calculate_change(cL, cB) print(cA) # This code is contributed by mohit kumar 29",
"e": 3170,
"s": 2691,
"text": null
},
{
"code": "// C# implementation to find the percentageusing System;using System.Collections.Generic;using System.Linq; class GFG { // change in the area when the percentage change// in the length and breadth is given // Function to calculate percentage// change in area of rectanglestatic int calculate_change(int length, int breadth){ int change = 0; change = length + breadth + ((length * breadth)/100); return change;} // Driver Codepublic static void Main(String[] args) { int cL = 20; int cB = -10; int cA = calculate_change(cL, cB); Console.Write(cA);}} // This code is contributed by shivanisinghss2110",
"e": 3805,
"s": 3170,
"text": null
},
{
"code": null,
"e": 3808,
"s": 3805,
"text": "8\n"
},
{
"code": null,
"e": 3830,
"s": 3808,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 3845,
"s": 3830,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 3862,
"s": 3845,
"text": "abhaysingh290895"
},
{
"code": null,
"e": 3881,
"s": 3862,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 3902,
"s": 3881,
"text": "area-volume-programs"
},
{
"code": null,
"e": 3919,
"s": 3902,
"text": "square-rectangle"
},
{
"code": null,
"e": 3928,
"s": 3919,
"text": "Aptitude"
},
{
"code": null,
"e": 3938,
"s": 3928,
"text": "Geometric"
},
{
"code": null,
"e": 3951,
"s": 3938,
"text": "Mathematical"
},
{
"code": null,
"e": 3970,
"s": 3951,
"text": "School Programming"
},
{
"code": null,
"e": 3983,
"s": 3970,
"text": "Mathematical"
},
{
"code": null,
"e": 3993,
"s": 3983,
"text": "Geometric"
},
{
"code": null,
"e": 4091,
"s": 3993,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4129,
"s": 4091,
"text": "Order and Ranking Questions & Answers"
},
{
"code": null,
"e": 4196,
"s": 4129,
"text": "Puzzle | How much money did the man have before entering the bank?"
},
{
"code": null,
"e": 4242,
"s": 4196,
"text": "Aptitude | Arithmetic Aptitude 2 | Question 8"
},
{
"code": null,
"e": 4273,
"s": 4242,
"text": "Seating Arrangement | Aptitude"
},
{
"code": null,
"e": 4311,
"s": 4273,
"text": "Aptitude | GATE CS 1998 | Question 48"
},
{
"code": null,
"e": 4360,
"s": 4311,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 4418,
"s": 4360,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 4482,
"s": 4418,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 4533,
"s": 4482,
"text": "How to check if two given line segments intersect?"
}
] |
MATLAB - Data Output
|
Data export (or output) in MATLAB means to write into files. MATLAB allows you to use your data in another application that reads ASCII files. For this, MATLAB provides several data export options.
You can create the following type of files −
Rectangular, delimited ASCII data file from an array.
Rectangular, delimited ASCII data file from an array.
Diary (or log) file of keystrokes and the resulting text output.
Diary (or log) file of keystrokes and the resulting text output.
Specialized ASCII file using low-level functions such as fprintf.
Specialized ASCII file using low-level functions such as fprintf.
MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format.
MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format.
Apart from this, you can also export data to spreadsheets.
There are two ways to export a numeric array as a delimited ASCII data file −
Using the save function and specifying the -ascii qualifier
Using the save function and specifying the -ascii qualifier
Using the dlmwrite function
Using the dlmwrite function
Syntax for using the save function is −
save my_data.out num_array -ascii
where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the specifier.
Syntax for using the dlmwrite function is −
dlmwrite('my_data.out', num_array, 'dlm_char')
where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and dlm_char is the delimiter character.
The following example demonstrates the concept. Create a script file and type the following code −
num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];
save array_data1.out num_array -ascii;
type array_data1.out
dlmwrite('array_data2.out', num_array, ' ');
type array_data2.out
When you run the file, it displays the following result −
1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00
4.0000000e+00 5.0000000e+00 6.0000000e+00 7.0000000e+00
7.0000000e+00 8.0000000e+00 9.0000000e+00 0.0000000e+00
1 2 3 4
4 5 6 7
7 8 9 0
Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To create a delimited ASCII file from the contents of a cell array, you can
Either, convert the cell array to a matrix using the cell2mat function
Either, convert the cell array to a matrix using the cell2mat function
Or export the cell array using low-level file I/O functions.
Or export the cell array using low-level file I/O functions.
If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file.
For example, let us write the word 'hello' to a file −
h = 'hello';
save textdata.out h -ascii
type textdata.out
MATLAB executes the above statements and displays the following result. which is the characters of the string 'hello' in 8-digit ASCII format.
1.0400000e+02 1.0100000e+02 1.0800000e+02 1.0800000e+02 1.1100000e+02
Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session in a disk file, excluding graphics.
To turn on the diary function, type −
diary
Optionally, you can give the name of the log file, say −
diary logdata.out
To turn off the diary function −
diary off
You can open the diary file in a text editor.
So far, we have exported numeric arrays. However, you may need to create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes. For these purposes, MATLAB provides the low-level fprintf function.
As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission to write or append, such as 'w' or 'a'.
After processing the file, you need to close it with fclose(fid) function.
The following example demonstrates the concept −
Create a script file and type the following code in it −
% create a matrix y, with two rows
x = 0:10:100;
y = [x; log(x)];
% open a file for writing
fid = fopen('logtable.txt', 'w');
% Table Header
fprintf(fid, 'Log Function\n\n');
% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f %f\n', y);
fclose(fid);
% display the file created
type logtable.txt
When you run the file, it displays the following result −
|
[
{
"code": null,
"e": 2473,
"s": 2275,
"text": "Data export (or output) in MATLAB means to write into files. MATLAB allows you to use your data in another application that reads ASCII files. For this, MATLAB provides several data export options."
},
{
"code": null,
"e": 2518,
"s": 2473,
"text": "You can create the following type of files −"
},
{
"code": null,
"e": 2572,
"s": 2518,
"text": "Rectangular, delimited ASCII data file from an array."
},
{
"code": null,
"e": 2626,
"s": 2572,
"text": "Rectangular, delimited ASCII data file from an array."
},
{
"code": null,
"e": 2691,
"s": 2626,
"text": "Diary (or log) file of keystrokes and the resulting text output."
},
{
"code": null,
"e": 2756,
"s": 2691,
"text": "Diary (or log) file of keystrokes and the resulting text output."
},
{
"code": null,
"e": 2822,
"s": 2756,
"text": "Specialized ASCII file using low-level functions such as fprintf."
},
{
"code": null,
"e": 2888,
"s": 2822,
"text": "Specialized ASCII file using low-level functions such as fprintf."
},
{
"code": null,
"e": 2983,
"s": 2888,
"text": "MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format."
},
{
"code": null,
"e": 3078,
"s": 2983,
"text": "MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format."
},
{
"code": null,
"e": 3137,
"s": 3078,
"text": "Apart from this, you can also export data to spreadsheets."
},
{
"code": null,
"e": 3215,
"s": 3137,
"text": "There are two ways to export a numeric array as a delimited ASCII data file −"
},
{
"code": null,
"e": 3275,
"s": 3215,
"text": "Using the save function and specifying the -ascii qualifier"
},
{
"code": null,
"e": 3335,
"s": 3275,
"text": "Using the save function and specifying the -ascii qualifier"
},
{
"code": null,
"e": 3363,
"s": 3335,
"text": "Using the dlmwrite function"
},
{
"code": null,
"e": 3391,
"s": 3363,
"text": "Using the dlmwrite function"
},
{
"code": null,
"e": 3431,
"s": 3391,
"text": "Syntax for using the save function is −"
},
{
"code": null,
"e": 3466,
"s": 3431,
"text": "save my_data.out num_array -ascii\n"
},
{
"code": null,
"e": 3586,
"s": 3466,
"text": "where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the specifier."
},
{
"code": null,
"e": 3630,
"s": 3586,
"text": "Syntax for using the dlmwrite function is −"
},
{
"code": null,
"e": 3678,
"s": 3630,
"text": "dlmwrite('my_data.out', num_array, 'dlm_char')\n"
},
{
"code": null,
"e": 3810,
"s": 3678,
"text": "where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and dlm_char is the delimiter character."
},
{
"code": null,
"e": 3909,
"s": 3810,
"text": "The following example demonstrates the concept. Create a script file and type the following code −"
},
{
"code": null,
"e": 4078,
"s": 3909,
"text": "num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0];\nsave array_data1.out num_array -ascii;\ntype array_data1.out\ndlmwrite('array_data2.out', num_array, ' ');\ntype array_data2.out"
},
{
"code": null,
"e": 4136,
"s": 4078,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 4357,
"s": 4136,
"text": " 1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00\n 4.0000000e+00 5.0000000e+00 6.0000000e+00 7.0000000e+00\n 7.0000000e+00 8.0000000e+00 9.0000000e+00 0.0000000e+00\n\n1 2 3 4\n4 5 6 7\n7 8 9 0\n"
},
{
"code": null,
"e": 4541,
"s": 4357,
"text": "Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To create a delimited ASCII file from the contents of a cell array, you can"
},
{
"code": null,
"e": 4612,
"s": 4541,
"text": "Either, convert the cell array to a matrix using the cell2mat function"
},
{
"code": null,
"e": 4683,
"s": 4612,
"text": "Either, convert the cell array to a matrix using the cell2mat function"
},
{
"code": null,
"e": 4744,
"s": 4683,
"text": "Or export the cell array using low-level file I/O functions."
},
{
"code": null,
"e": 4805,
"s": 4744,
"text": "Or export the cell array using low-level file I/O functions."
},
{
"code": null,
"e": 4941,
"s": 4805,
"text": "If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file."
},
{
"code": null,
"e": 4996,
"s": 4941,
"text": "For example, let us write the word 'hello' to a file −"
},
{
"code": null,
"e": 5054,
"s": 4996,
"text": "h = 'hello';\nsave textdata.out h -ascii\ntype textdata.out"
},
{
"code": null,
"e": 5197,
"s": 5054,
"text": "MATLAB executes the above statements and displays the following result. which is the characters of the string 'hello' in 8-digit ASCII format."
},
{
"code": null,
"e": 5276,
"s": 5197,
"text": "1.0400000e+02 1.0100000e+02 1.0800000e+02 1.0800000e+02 1.1100000e+02\n"
},
{
"code": null,
"e": 5423,
"s": 5276,
"text": "Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session in a disk file, excluding graphics."
},
{
"code": null,
"e": 5461,
"s": 5423,
"text": "To turn on the diary function, type −"
},
{
"code": null,
"e": 5467,
"s": 5461,
"text": "diary"
},
{
"code": null,
"e": 5525,
"s": 5467,
"text": " Optionally, you can give the name of the log file, say −"
},
{
"code": null,
"e": 5544,
"s": 5525,
"text": "diary logdata.out\n"
},
{
"code": null,
"e": 5577,
"s": 5544,
"text": "To turn off the diary function −"
},
{
"code": null,
"e": 5588,
"s": 5577,
"text": "diary off\n"
},
{
"code": null,
"e": 5634,
"s": 5588,
"text": "You can open the diary file in a text editor."
},
{
"code": null,
"e": 5918,
"s": 5634,
"text": "So far, we have exported numeric arrays. However, you may need to create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes. For these purposes, MATLAB provides the low-level fprintf function."
},
{
"code": null,
"e": 6187,
"s": 5918,
"text": "As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission to write or append, such as 'w' or 'a'."
},
{
"code": null,
"e": 6262,
"s": 6187,
"text": "After processing the file, you need to close it with fclose(fid) function."
},
{
"code": null,
"e": 6311,
"s": 6262,
"text": "The following example demonstrates the concept −"
},
{
"code": null,
"e": 6368,
"s": 6311,
"text": "Create a script file and type the following code in it −"
},
{
"code": null,
"e": 6718,
"s": 6368,
"text": "% create a matrix y, with two rows\nx = 0:10:100;\ny = [x; log(x)];\n \n% open a file for writing\nfid = fopen('logtable.txt', 'w');\n \n% Table Header\nfprintf(fid, 'Log Function\\n\\n');\n \n% print values in column order\n% two values appear on each row of the file\nfprintf(fid, '%f %f\\n', y);\nfclose(fid);\n\n% display the file created\ntype logtable.txt"
}
] |
Lodash _.min() Method
|
02 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.min() method is used to find the minimum element from the array. If the array is empty then undefined is returned.
Syntax:
_.min( array )
Parameters: This method accepts a single parameter as mentioned above and described below:
array: It is the array that the method iterates over to get the minimum element.
Return Value: This method returns the minimum element from the array.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.min() method let min_val = _.min([]); // Printing the output console.log(min_val);
Output:
undefined
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.min() method let min_val = _.min([15, 7, 38, 46, 82]); // Printing the output console.log(min_val);
Output:
7
Example 3:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.min() method let min_val = _.min([-15, 7, 38, -46, -82]); // Printing the output console.log(min_val);
Output:
-82
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. "
},
{
"code": null,
"e": 290,
"s": 169,
"text": "The _.min() method is used to find the minimum element from the array. If the array is empty then undefined is returned."
},
{
"code": null,
"e": 298,
"s": 290,
"text": "Syntax:"
},
{
"code": null,
"e": 314,
"s": 298,
"text": "_.min( array )\n"
},
{
"code": null,
"e": 405,
"s": 314,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 486,
"s": 405,
"text": "array: It is the array that the method iterates over to get the minimum element."
},
{
"code": null,
"e": 556,
"s": 486,
"text": "Return Value: This method returns the minimum element from the array."
},
{
"code": null,
"e": 567,
"s": 556,
"text": "Example 1:"
},
{
"code": null,
"e": 578,
"s": 567,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.min() method let min_val = _.min([]); // Printing the output console.log(min_val);",
"e": 749,
"s": 578,
"text": null
},
{
"code": null,
"e": 757,
"s": 749,
"text": "Output:"
},
{
"code": null,
"e": 768,
"s": 757,
"text": "undefined\n"
},
{
"code": null,
"e": 779,
"s": 768,
"text": "Example 2:"
},
{
"code": null,
"e": 790,
"s": 779,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.min() method let min_val = _.min([15, 7, 38, 46, 82]); // Printing the output console.log(min_val);",
"e": 978,
"s": 790,
"text": null
},
{
"code": null,
"e": 986,
"s": 978,
"text": "Output:"
},
{
"code": null,
"e": 989,
"s": 986,
"text": "7\n"
},
{
"code": null,
"e": 1002,
"s": 989,
"text": "Example 3: "
},
{
"code": null,
"e": 1013,
"s": 1002,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.min() method let min_val = _.min([-15, 7, 38, -46, -82]); // Printing the output console.log(min_val);",
"e": 1204,
"s": 1013,
"text": null
},
{
"code": null,
"e": 1212,
"s": 1204,
"text": "Output:"
},
{
"code": null,
"e": 1217,
"s": 1212,
"text": "-82\n"
},
{
"code": null,
"e": 1235,
"s": 1217,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1246,
"s": 1235,
"text": "JavaScript"
},
{
"code": null,
"e": 1263,
"s": 1246,
"text": "Web Technologies"
},
{
"code": null,
"e": 1361,
"s": 1263,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1422,
"s": 1361,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1494,
"s": 1422,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1534,
"s": 1494,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1587,
"s": 1534,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 1628,
"s": 1587,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1661,
"s": 1628,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1723,
"s": 1661,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1784,
"s": 1723,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1834,
"s": 1784,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
HTML | controls Attribute
|
08 Jul, 2019
The HTML controls Attribute is used to specify that the audio and video controls must be displayed. It is a Boolean attribute and also new in HTML5. We can use this attribute in two tags <audio> and <video>
The controls attribute includes the following properties on <audio> tag:
Play
Pause
Seeking
Volume
The controls attribute includes the following properties on <video> tag:
Play
Pause
Seeking
Volume
Fullscreen toggle (for video only)
Captions/Subtitles (for video only, when available)
Track (for video only, when available)
Syntax:
<element controls>
Below example illustrates the use of controls attribute in <audio> element.
Example:
<!DOCTYPE html><html> <head> <title> HTML Audio controls Attribute </title></head> <body style="text-align: center"> <h1 style="color: green"> GeeksforGeeks </h1> <h2 style="font-family: Impact"> HTML Audio controls Attribute </h2> <br> <audio id="Test_Audio" controls autoplay> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg" type="audio/ogg"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.mp3" type="audio/mpeg"> </audio> </body> </html>
Output:
Below example illustrates the use of controls attribute in <video> element.
Example:
<!DOCTYPE html> <html> <head> <title>HTML video controls Attribute</title> </head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML video controls Attribute</h3> <video width="400" height="200" controls > <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4"> <source src= "https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg"> </video> </center> </body> </html>
Output:
Supported Browsers: The browser supported by HTML controls Attribute are listed below:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Safari 4.0
Opera 10.5
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2019"
},
{
"code": null,
"e": 235,
"s": 28,
"text": "The HTML controls Attribute is used to specify that the audio and video controls must be displayed. It is a Boolean attribute and also new in HTML5. We can use this attribute in two tags <audio> and <video>"
},
{
"code": null,
"e": 308,
"s": 235,
"text": "The controls attribute includes the following properties on <audio> tag:"
},
{
"code": null,
"e": 313,
"s": 308,
"text": "Play"
},
{
"code": null,
"e": 319,
"s": 313,
"text": "Pause"
},
{
"code": null,
"e": 327,
"s": 319,
"text": "Seeking"
},
{
"code": null,
"e": 334,
"s": 327,
"text": "Volume"
},
{
"code": null,
"e": 407,
"s": 334,
"text": "The controls attribute includes the following properties on <video> tag:"
},
{
"code": null,
"e": 412,
"s": 407,
"text": "Play"
},
{
"code": null,
"e": 418,
"s": 412,
"text": "Pause"
},
{
"code": null,
"e": 426,
"s": 418,
"text": "Seeking"
},
{
"code": null,
"e": 433,
"s": 426,
"text": "Volume"
},
{
"code": null,
"e": 468,
"s": 433,
"text": "Fullscreen toggle (for video only)"
},
{
"code": null,
"e": 520,
"s": 468,
"text": "Captions/Subtitles (for video only, when available)"
},
{
"code": null,
"e": 559,
"s": 520,
"text": "Track (for video only, when available)"
},
{
"code": null,
"e": 567,
"s": 559,
"text": "Syntax:"
},
{
"code": null,
"e": 587,
"s": 567,
"text": "<element controls> "
},
{
"code": null,
"e": 663,
"s": 587,
"text": "Below example illustrates the use of controls attribute in <audio> element."
},
{
"code": null,
"e": 672,
"s": 663,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML Audio controls Attribute </title></head> <body style=\"text-align: center\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h2 style=\"font-family: Impact\"> HTML Audio controls Attribute </h2> <br> <audio id=\"Test_Audio\" controls autoplay> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg\" type=\"audio/ogg\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.mp3\" type=\"audio/mpeg\"> </audio> </body> </html>",
"e": 1341,
"s": 672,
"text": null
},
{
"code": null,
"e": 1349,
"s": 1341,
"text": "Output:"
},
{
"code": null,
"e": 1425,
"s": 1349,
"text": "Below example illustrates the use of controls attribute in <video> element."
},
{
"code": null,
"e": 1434,
"s": 1425,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML video controls Attribute</title> </head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML video controls Attribute</h3> <video width=\"400\" height=\"200\" controls > <source src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4\" type=\"video/mp4\"> <source src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg\" type=\"video/ogg\"> </video> </center> </body> </html> ",
"e": 2043,
"s": 1434,
"text": null
},
{
"code": null,
"e": 2051,
"s": 2043,
"text": "Output:"
},
{
"code": null,
"e": 2138,
"s": 2051,
"text": "Supported Browsers: The browser supported by HTML controls Attribute are listed below:"
},
{
"code": null,
"e": 2156,
"s": 2138,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 2178,
"s": 2156,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 2190,
"s": 2178,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 2201,
"s": 2190,
"text": "Safari 4.0"
},
{
"code": null,
"e": 2212,
"s": 2201,
"text": "Opera 10.5"
},
{
"code": null,
"e": 2228,
"s": 2212,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 2233,
"s": 2228,
"text": "HTML"
},
{
"code": null,
"e": 2250,
"s": 2233,
"text": "Web Technologies"
},
{
"code": null,
"e": 2255,
"s": 2250,
"text": "HTML"
},
{
"code": null,
"e": 2353,
"s": 2255,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2401,
"s": 2353,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2425,
"s": 2401,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2475,
"s": 2425,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2514,
"s": 2475,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2551,
"s": 2514,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2584,
"s": 2551,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2645,
"s": 2584,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2688,
"s": 2645,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2760,
"s": 2688,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Compute the covariance matrix of two given NumPy arrays
|
29 Aug, 2020
In NumPy for computing the covariance matrix of two given arrays with help of numpy.cov(). In this, we will pass the two arrays and it will return the covariance matrix of two given arrays.
Syntax: numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)
Example 1:
Python
import numpy as np array1 = np.array([0, 1, 1])array2 = np.array([2, 2, 1]) # Original array1print(array1) # Original array2print(array2) # Covariance matrixprint("\nCovariance matrix of the said arrays:\n", np.cov(array1, array2))
Output:
[0 1 1]
[2 2 1]
Covariance matrix of the said arrays:
[[ 0.33333333 -0.16666667]
[-0.16666667 0.33333333]]
Example 2:
Python
import numpy as np array1 = np.array([2, 1, 1, 4])array2 = np.array([2, 2, 1, 1]) # Original array1print(array1) # Original array2print(array2) # Covariance matrixprint("\nCovariance matrix of the said arrays:\n", np.cov(array1, array2))
Output:
[2 1 1 4]
[2 2 1 1]
Covariance matrix of the said arrays:
[[ 2. -0.33333333]
[-0.33333333 0.33333333]]
Example 3:
Python
import numpy as np array1 = np.array([1, 2])array2 = np.array([1, 2]) # Original array1print(array1) # Original array2print(array2) # Covariance matrixprint("\nCovariance matrix of the said arrays:\n", np.cov(array1, array2))
Output
[1 2]
[1 2]
Covariance matrix of the said arrays:
[[0.5 0.5]
[0.5 0.5]]
Example 4:
Python
import numpy as np x = [1.23, 2.12, 3.34, 4.5] y = [2.56, 2.89, 3.76, 3.95] # find out covariance with respect # rows cov_mat = np.stack((x, y), axis = 1) print("shape of matrix x and y:", np.shape(cov_mat)) print("shape of covariance matrix:", np.shape(np.cov(cov_mat))) print(np.cov(cov_mat))
Output
shape of matrix x and y: (4, 2)
shape of covariance matrix: (4, 4)
[[ 0.88445 0.51205 0.2793 -0.36575]
[ 0.51205 0.29645 0.1617 -0.21175]
[ 0.2793 0.1617 0.0882 -0.1155 ]
[-0.36575 -0.21175 -0.1155 0.15125]]
Python numpy-Statistics Functions
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
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "In NumPy for computing the covariance matrix of two given arrays with help of numpy.cov(). In this, we will pass the two arrays and it will return the covariance matrix of two given arrays."
},
{
"code": null,
"e": 313,
"s": 218,
"text": "Syntax: numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)"
},
{
"code": null,
"e": 324,
"s": 313,
"text": "Example 1:"
},
{
"code": null,
"e": 331,
"s": 324,
"text": "Python"
},
{
"code": "import numpy as np array1 = np.array([0, 1, 1])array2 = np.array([2, 2, 1]) # Original array1print(array1) # Original array2print(array2) # Covariance matrixprint(\"\\nCovariance matrix of the said arrays:\\n\", np.cov(array1, array2))",
"e": 574,
"s": 331,
"text": null
},
{
"code": null,
"e": 582,
"s": 574,
"text": "Output:"
},
{
"code": null,
"e": 694,
"s": 582,
"text": "[0 1 1]\n[2 2 1]\n\nCovariance matrix of the said arrays:\n [[ 0.33333333 -0.16666667]\n [-0.16666667 0.33333333]]\n"
},
{
"code": null,
"e": 705,
"s": 694,
"text": "Example 2:"
},
{
"code": null,
"e": 712,
"s": 705,
"text": "Python"
},
{
"code": "import numpy as np array1 = np.array([2, 1, 1, 4])array2 = np.array([2, 2, 1, 1]) # Original array1print(array1) # Original array2print(array2) # Covariance matrixprint(\"\\nCovariance matrix of the said arrays:\\n\", np.cov(array1, array2))",
"e": 962,
"s": 712,
"text": null
},
{
"code": null,
"e": 970,
"s": 962,
"text": "Output:"
},
{
"code": null,
"e": 1086,
"s": 970,
"text": "[2 1 1 4]\n[2 2 1 1]\n\nCovariance matrix of the said arrays:\n [[ 2. -0.33333333]\n [-0.33333333 0.33333333]]\n"
},
{
"code": null,
"e": 1097,
"s": 1086,
"text": "Example 3:"
},
{
"code": null,
"e": 1104,
"s": 1097,
"text": "Python"
},
{
"code": "import numpy as np array1 = np.array([1, 2])array2 = np.array([1, 2]) # Original array1print(array1) # Original array2print(array2) # Covariance matrixprint(\"\\nCovariance matrix of the said arrays:\\n\", np.cov(array1, array2))",
"e": 1342,
"s": 1104,
"text": null
},
{
"code": null,
"e": 1349,
"s": 1342,
"text": "Output"
},
{
"code": null,
"e": 1425,
"s": 1349,
"text": "[1 2]\n[1 2]\n\nCovariance matrix of the said arrays:\n [[0.5 0.5]\n [0.5 0.5]]\n"
},
{
"code": null,
"e": 1436,
"s": 1425,
"text": "Example 4:"
},
{
"code": null,
"e": 1443,
"s": 1436,
"text": "Python"
},
{
"code": "import numpy as np x = [1.23, 2.12, 3.34, 4.5] y = [2.56, 2.89, 3.76, 3.95] # find out covariance with respect # rows cov_mat = np.stack((x, y), axis = 1) print(\"shape of matrix x and y:\", np.shape(cov_mat)) print(\"shape of covariance matrix:\", np.shape(np.cov(cov_mat))) print(np.cov(cov_mat))",
"e": 1766,
"s": 1443,
"text": null
},
{
"code": null,
"e": 1773,
"s": 1766,
"text": "Output"
},
{
"code": null,
"e": 1998,
"s": 1773,
"text": "shape of matrix x and y: (4, 2)\nshape of covariance matrix: (4, 4)\n[[ 0.88445 0.51205 0.2793 -0.36575]\n [ 0.51205 0.29645 0.1617 -0.21175]\n [ 0.2793 0.1617 0.0882 -0.1155 ]\n [-0.36575 -0.21175 -0.1155 0.15125]]\n"
},
{
"code": null,
"e": 2032,
"s": 1998,
"text": "Python numpy-Statistics Functions"
},
{
"code": null,
"e": 2045,
"s": 2032,
"text": "Python-numpy"
},
{
"code": null,
"e": 2052,
"s": 2045,
"text": "Python"
},
{
"code": null,
"e": 2150,
"s": 2052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2182,
"s": 2150,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2209,
"s": 2182,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2230,
"s": 2209,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2253,
"s": 2230,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2309,
"s": 2253,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2340,
"s": 2309,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2382,
"s": 2340,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2424,
"s": 2382,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2463,
"s": 2424,
"text": "Python | Get unique values from a list"
}
] |
Remove multiple elements from a list in Python
|
30 Jun, 2021
Given a list of numbers, write a Python program to remove multiple elements from a list based on the given condition.
Example:
Input: [12, 15, 3, 10]
Output: Remove = [12, 3], New_List = [15, 10]
Input: [11, 5, 17, 18, 23, 50]
Output: Remove = [1:5], New_list = [11, 50]
Multiple elements can be deleted from a list in Python, based on the knowledge we have about the data. Like, we just know the values to be deleted or also know the indexes of those values. Let’s see different examples based on different scenario.
Example #1: Let’s say we want to delete each element in the list which is divisible by 2 or all the even numbers.
Python3
# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # Iterate each element in list# and add them in variable totalfor ele in list1: if ele % 2 == 0: list1.remove(ele) # printing modified listprint("New list after removing all even numbers: ", list1)
Output:
New list after removing all even numbers: [11, 5, 17, 23]
Example #2: Using list comprehensionRemoving all even elements in a list is as good as only including all the elements which are not even( i.e. odd elements).
Python3
# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # will create a new list,# excluding all even numberslist1 = [ elem for elem in list1 if elem % 2 != 0] print(*list1)
Output:
11 5 17 23
Example #3: Remove adjacent elements using list slicingBelow Python code remove values from index 1 to 4.
Python3
# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # removes elements from index 1 to 4# i.e. 5, 17, 18, 23 will be deleteddel list1[1:5] print(*list1)
Output:
11 50
Example #4: Using list comprehensionLet’s say the elements to be deleted is known, instead of the indexes of those elements. In this case, we can directly eliminate those elements without caring about indexes which we will see in next example.
Python3
# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # items to be removedunwanted_num = {11, 5} list1 = [ele for ele in list1 if ele not in unwanted_num] # printing modified listprint("New list after removing unwanted numbers: ", list1)
Output:
New list after removing unwanted numbers: [17, 18, 23, 50]
Example #5: When index of elements is known.Though indexes of elements in known, deleting the elements randomly will change the values of indexes. Hence, it is always recommended to delete the largest indices first. Using this strategy, index of smaller values will not be changed. We can sort the list in reverse order and delete the elements of list in descending order.
Python3
# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # given index of elements# removes 11, 18, 23unwanted = [0, 3, 4] for ele in sorted(unwanted, reverse = True): del list1[ele] # printing modified listprint (*list1)
Output:
5 17 50
varshagumber28
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 170,
"s": 52,
"text": "Given a list of numbers, write a Python program to remove multiple elements from a list based on the given condition."
},
{
"code": null,
"e": 180,
"s": 170,
"text": "Example: "
},
{
"code": null,
"e": 325,
"s": 180,
"text": "Input: [12, 15, 3, 10]\nOutput: Remove = [12, 3], New_List = [15, 10]\n\nInput: [11, 5, 17, 18, 23, 50]\nOutput: Remove = [1:5], New_list = [11, 50]"
},
{
"code": null,
"e": 572,
"s": 325,
"text": "Multiple elements can be deleted from a list in Python, based on the knowledge we have about the data. Like, we just know the values to be deleted or also know the indexes of those values. Let’s see different examples based on different scenario."
},
{
"code": null,
"e": 687,
"s": 572,
"text": "Example #1: Let’s say we want to delete each element in the list which is divisible by 2 or all the even numbers. "
},
{
"code": null,
"e": 695,
"s": 687,
"text": "Python3"
},
{
"code": "# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # Iterate each element in list# and add them in variable totalfor ele in list1: if ele % 2 == 0: list1.remove(ele) # printing modified listprint(\"New list after removing all even numbers: \", list1)",
"e": 1010,
"s": 695,
"text": null
},
{
"code": null,
"e": 1019,
"s": 1010,
"text": "Output: "
},
{
"code": null,
"e": 1078,
"s": 1019,
"text": "New list after removing all even numbers: [11, 5, 17, 23]"
},
{
"code": null,
"e": 1238,
"s": 1078,
"text": "Example #2: Using list comprehensionRemoving all even elements in a list is as good as only including all the elements which are not even( i.e. odd elements). "
},
{
"code": null,
"e": 1246,
"s": 1238,
"text": "Python3"
},
{
"code": "# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # will create a new list,# excluding all even numberslist1 = [ elem for elem in list1 if elem % 2 != 0] print(*list1)",
"e": 1471,
"s": 1246,
"text": null
},
{
"code": null,
"e": 1480,
"s": 1471,
"text": "Output: "
},
{
"code": null,
"e": 1491,
"s": 1480,
"text": "11 5 17 23"
},
{
"code": null,
"e": 1597,
"s": 1491,
"text": "Example #3: Remove adjacent elements using list slicingBelow Python code remove values from index 1 to 4."
},
{
"code": null,
"e": 1605,
"s": 1597,
"text": "Python3"
},
{
"code": "# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # removes elements from index 1 to 4# i.e. 5, 17, 18, 23 will be deleteddel list1[1:5] print(*list1)",
"e": 1813,
"s": 1605,
"text": null
},
{
"code": null,
"e": 1822,
"s": 1813,
"text": "Output: "
},
{
"code": null,
"e": 1828,
"s": 1822,
"text": "11 50"
},
{
"code": null,
"e": 2073,
"s": 1828,
"text": "Example #4: Using list comprehensionLet’s say the elements to be deleted is known, instead of the indexes of those elements. In this case, we can directly eliminate those elements without caring about indexes which we will see in next example. "
},
{
"code": null,
"e": 2081,
"s": 2073,
"text": "Python3"
},
{
"code": "# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # items to be removedunwanted_num = {11, 5} list1 = [ele for ele in list1 if ele not in unwanted_num] # printing modified listprint(\"New list after removing unwanted numbers: \", list1)",
"e": 2373,
"s": 2081,
"text": null
},
{
"code": null,
"e": 2382,
"s": 2373,
"text": "Output: "
},
{
"code": null,
"e": 2442,
"s": 2382,
"text": "New list after removing unwanted numbers: [17, 18, 23, 50]"
},
{
"code": null,
"e": 2815,
"s": 2442,
"text": "Example #5: When index of elements is known.Though indexes of elements in known, deleting the elements randomly will change the values of indexes. Hence, it is always recommended to delete the largest indices first. Using this strategy, index of smaller values will not be changed. We can sort the list in reverse order and delete the elements of list in descending order."
},
{
"code": null,
"e": 2823,
"s": 2815,
"text": "Python3"
},
{
"code": "# Python program to remove multiple# elements from a list # creating a listlist1 = [11, 5, 17, 18, 23, 50] # given index of elements# removes 11, 18, 23unwanted = [0, 3, 4] for ele in sorted(unwanted, reverse = True): del list1[ele] # printing modified listprint (*list1)",
"e": 3098,
"s": 2823,
"text": null
},
{
"code": null,
"e": 3107,
"s": 3098,
"text": "Output: "
},
{
"code": null,
"e": 3115,
"s": 3107,
"text": "5 17 50"
},
{
"code": null,
"e": 3132,
"s": 3117,
"text": "varshagumber28"
},
{
"code": null,
"e": 3153,
"s": 3132,
"text": "Python list-programs"
},
{
"code": null,
"e": 3165,
"s": 3153,
"text": "python-list"
},
{
"code": null,
"e": 3172,
"s": 3165,
"text": "Python"
},
{
"code": null,
"e": 3188,
"s": 3172,
"text": "Python Programs"
},
{
"code": null,
"e": 3207,
"s": 3188,
"text": "School Programming"
},
{
"code": null,
"e": 3219,
"s": 3207,
"text": "python-list"
}
] |
Elbow Method for optimal value of k in KMeans
|
18 May, 2022
Prerequisites: K-Means ClusteringA fundamental step for any unsupervised algorithm is to determine the optimal number of clusters into which the data may be clustered. The Elbow Method is one of the most popular methods to determine this optimal value of k.We now demonstrate the given method using the K-Means clustering technique using the Sklearn library of python.
Step 1: Importing the required libraries
Python3
from sklearn.cluster import KMeansfrom sklearn import metricsfrom scipy.spatial.distance import cdistimport numpy as npimport matplotlib.pyplot as plt
Step 2: Creating and Visualizing the data
Python3
# Creating the datax1 = np.array([3, 1, 1, 2, 1, 6, 6, 6, 5, 6, 7, 8, 9, 8, 9, 9, 8])x2 = np.array([5, 4, 5, 6, 5, 8, 6, 7, 6, 7, 1, 2, 1, 2, 3, 2, 3])X = np.array(list(zip(x1, x2))).reshape(len(x1), 2) # Visualizing the dataplt.plot()plt.xlim([0, 10])plt.ylim([0, 10])plt.title('Dataset')plt.scatter(x1, x2)plt.show()
From the above visualization, we can see that the optimal number of clusters should be around 3. But visualizing the data alone cannot always give the right answer. Hence we demonstrate the following steps.We now define the following:-
Distortion: It is calculated as the average of the squared distances from the cluster centers of the respective clusters. Typically, the Euclidean distance metric is used.Inertia: It is the sum of squared distances of samples to their closest cluster center.
Distortion: It is calculated as the average of the squared distances from the cluster centers of the respective clusters. Typically, the Euclidean distance metric is used.
Inertia: It is the sum of squared distances of samples to their closest cluster center.
We iterate the values of k from 1 to 9 and calculate the values of distortions for each value of k and calculate the distortion and inertia for each value of k in the given range.Step 3: Building the clustering model and calculating the values of the Distortion and Inertia:
Python3
distortions = []inertias = []mapping1 = {}mapping2 = {}K = range(1, 10) for k in K: # Building and fitting the model kmeanModel = KMeans(n_clusters=k).fit(X) kmeanModel.fit(X) distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0]) inertias.append(kmeanModel.inertia_) mapping1[k] = sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0] mapping2[k] = kmeanModel.inertia_
Step 4: Tabulating and Visualizing the resultsa) Using the different values of Distortion:
Python3
for key, val in mapping1.items(): print(f'{key} : {val}')
Python3
plt.plot(K, distortions, 'bx-')plt.xlabel('Values of K')plt.ylabel('Distortion')plt.title('The Elbow Method using Distortion')plt.show()
b) Using the different values of Inertia:
Python3
for key, val in mapping2.items(): print(f'{key} : {val}')
Python3
plt.plot(K, inertias, 'bx-')plt.xlabel('Values of K')plt.ylabel('Inertia')plt.title('The Elbow Method using Inertia')plt.show()
To determine the optimal number of clusters, we have to select the value of k at the “elbow” ie the point after which the distortion/inertia start decreasing in a linear fashion. Thus for the given data, we conclude that the optimal number of clusters for the data is 3.The clustered data points for different value of k:-1. k = 1
2. k = 2
3. k = 3
4. k = 4
DipankarMajumder
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search Algorithms in AI
Decision Tree Introduction with example
Getting started with Machine Learning
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 422,
"s": 53,
"text": "Prerequisites: K-Means ClusteringA fundamental step for any unsupervised algorithm is to determine the optimal number of clusters into which the data may be clustered. The Elbow Method is one of the most popular methods to determine this optimal value of k.We now demonstrate the given method using the K-Means clustering technique using the Sklearn library of python."
},
{
"code": null,
"e": 463,
"s": 422,
"text": "Step 1: Importing the required libraries"
},
{
"code": null,
"e": 471,
"s": 463,
"text": "Python3"
},
{
"code": "from sklearn.cluster import KMeansfrom sklearn import metricsfrom scipy.spatial.distance import cdistimport numpy as npimport matplotlib.pyplot as plt",
"e": 622,
"s": 471,
"text": null
},
{
"code": null,
"e": 664,
"s": 622,
"text": "Step 2: Creating and Visualizing the data"
},
{
"code": null,
"e": 672,
"s": 664,
"text": "Python3"
},
{
"code": "# Creating the datax1 = np.array([3, 1, 1, 2, 1, 6, 6, 6, 5, 6, 7, 8, 9, 8, 9, 9, 8])x2 = np.array([5, 4, 5, 6, 5, 8, 6, 7, 6, 7, 1, 2, 1, 2, 3, 2, 3])X = np.array(list(zip(x1, x2))).reshape(len(x1), 2) # Visualizing the dataplt.plot()plt.xlim([0, 10])plt.ylim([0, 10])plt.title('Dataset')plt.scatter(x1, x2)plt.show()",
"e": 992,
"s": 672,
"text": null
},
{
"code": null,
"e": 1228,
"s": 992,
"text": "From the above visualization, we can see that the optimal number of clusters should be around 3. But visualizing the data alone cannot always give the right answer. Hence we demonstrate the following steps.We now define the following:-"
},
{
"code": null,
"e": 1487,
"s": 1228,
"text": "Distortion: It is calculated as the average of the squared distances from the cluster centers of the respective clusters. Typically, the Euclidean distance metric is used.Inertia: It is the sum of squared distances of samples to their closest cluster center."
},
{
"code": null,
"e": 1659,
"s": 1487,
"text": "Distortion: It is calculated as the average of the squared distances from the cluster centers of the respective clusters. Typically, the Euclidean distance metric is used."
},
{
"code": null,
"e": 1747,
"s": 1659,
"text": "Inertia: It is the sum of squared distances of samples to their closest cluster center."
},
{
"code": null,
"e": 2022,
"s": 1747,
"text": "We iterate the values of k from 1 to 9 and calculate the values of distortions for each value of k and calculate the distortion and inertia for each value of k in the given range.Step 3: Building the clustering model and calculating the values of the Distortion and Inertia:"
},
{
"code": null,
"e": 2030,
"s": 2022,
"text": "Python3"
},
{
"code": "distortions = []inertias = []mapping1 = {}mapping2 = {}K = range(1, 10) for k in K: # Building and fitting the model kmeanModel = KMeans(n_clusters=k).fit(X) kmeanModel.fit(X) distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0]) inertias.append(kmeanModel.inertia_) mapping1[k] = sum(np.min(cdist(X, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X.shape[0] mapping2[k] = kmeanModel.inertia_",
"e": 2580,
"s": 2030,
"text": null
},
{
"code": null,
"e": 2671,
"s": 2580,
"text": "Step 4: Tabulating and Visualizing the resultsa) Using the different values of Distortion:"
},
{
"code": null,
"e": 2679,
"s": 2671,
"text": "Python3"
},
{
"code": "for key, val in mapping1.items(): print(f'{key} : {val}')",
"e": 2740,
"s": 2679,
"text": null
},
{
"code": null,
"e": 2748,
"s": 2740,
"text": "Python3"
},
{
"code": "plt.plot(K, distortions, 'bx-')plt.xlabel('Values of K')plt.ylabel('Distortion')plt.title('The Elbow Method using Distortion')plt.show()",
"e": 2885,
"s": 2748,
"text": null
},
{
"code": null,
"e": 2927,
"s": 2885,
"text": "b) Using the different values of Inertia:"
},
{
"code": null,
"e": 2935,
"s": 2927,
"text": "Python3"
},
{
"code": "for key, val in mapping2.items(): print(f'{key} : {val}')",
"e": 2996,
"s": 2935,
"text": null
},
{
"code": null,
"e": 3004,
"s": 2996,
"text": "Python3"
},
{
"code": "plt.plot(K, inertias, 'bx-')plt.xlabel('Values of K')plt.ylabel('Inertia')plt.title('The Elbow Method using Inertia')plt.show()",
"e": 3132,
"s": 3004,
"text": null
},
{
"code": null,
"e": 3464,
"s": 3132,
"text": "To determine the optimal number of clusters, we have to select the value of k at the “elbow” ie the point after which the distortion/inertia start decreasing in a linear fashion. Thus for the given data, we conclude that the optimal number of clusters for the data is 3.The clustered data points for different value of k:-1. k = 1 "
},
{
"code": null,
"e": 3474,
"s": 3464,
"text": "2. k = 2 "
},
{
"code": null,
"e": 3484,
"s": 3474,
"text": "3. k = 3 "
},
{
"code": null,
"e": 3494,
"s": 3484,
"text": "4. k = 4 "
},
{
"code": null,
"e": 3511,
"s": 3494,
"text": "DipankarMajumder"
},
{
"code": null,
"e": 3528,
"s": 3511,
"text": "Machine Learning"
},
{
"code": null,
"e": 3535,
"s": 3528,
"text": "Python"
},
{
"code": null,
"e": 3552,
"s": 3535,
"text": "Machine Learning"
},
{
"code": null,
"e": 3650,
"s": 3552,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3674,
"s": 3650,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 3714,
"s": 3674,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 3752,
"s": 3714,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 3793,
"s": 3752,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 3829,
"s": 3793,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 3857,
"s": 3829,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3907,
"s": 3857,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3929,
"s": 3907,
"text": "Python map() function"
}
] |
How to count the number of NaN values in Pandas?
|
10 Jul, 2020
We might need to count the number of NaN values for each feature in the dataset so that we can decide how to deal with it. For example, if the number of missing values is quite low, then we may choose to drop those observations; or there might be a column where a lot of entries are missing, so we can decide whether to include that variable at all.
Method 1: Using describe()
We can use the describe() method which returns a table containing details about the dataset. The count property directly gives the count of non-NaN values in each column. So, we can get the count of NaN values, if we know the total number of observations.
import pandas as pd import numpy as np # dictionary of lists dict = { 'A':[1, 4, 6, 9], 'B':[np.NaN, 5, 8, np.NaN], 'C':[7, 3, np.NaN, 2], 'D':[1, np.NaN, np.NaN, np.NaN] } # creating dataframe from the# dictionary data = pd.DataFrame(dict) data.describe()
Output :
Method 2: Using sum()The isnull() function returns a dataset containing True and False values. Since, True is treated as a 1 and False as 0, calling the sum() method on the isnull() series returns the count of True values which actually corresponds to the number of NaN values.
Counting NaN in a column :
We can simply find the null values in the desired column, then get the sum.
import pandas as pdimport numpy as np # dictionary of lists dict = { 'A':[1, 4, 6, 9], 'B':[np.NaN, 5, 8, np.NaN], 'C':[7, 3, np.NaN, 2], 'D':[1, np.NaN, np.NaN, np.NaN] } # creating dataframe from the# dictionary data = pd.DataFrame(dict) # total NaN values in column 'B'print(data['B'].isnull().sum())
Output :
2
Counting NaN in a row :
The row can be selected using loc or iloc. Then we find the sum as before.
import pandas as pd import numpy as np # dictionary of lists dict = { 'A':[1, 4, 6, 9], 'B':[np.NaN, 5, 8, np.NaN], 'C':[7, 3, np.NaN, 2], 'D':[1, np.NaN, np.NaN, np.NaN] } # creating dataframe from the # dictionary data = pd.DataFrame(dict) # total NaN values in row index 1print(data.loc[1, :].isnull().sum())
Output :
1
Counting NaN in the entire DataFrame :To count NaN in the entire dataset, we just need to call the sum() function twice – once for getting the count in each column and again for finding the total sum of all the columns.
import pandas as pd import numpy as np # dictionary of lists dict = {'A':[1, 4, 6, 9], 'B':[np.NaN, 5, 8, np.NaN], 'C':[7, 3, np.NaN, 2], 'D':[1, np.NaN, np.NaN, np.NaN]} # creating dataframe from the# dictionary data = pd.DataFrame(dict) # total count of NaN valuesprint(data.isnull().sum().sum())
Output :
6
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 378,
"s": 28,
"text": "We might need to count the number of NaN values for each feature in the dataset so that we can decide how to deal with it. For example, if the number of missing values is quite low, then we may choose to drop those observations; or there might be a column where a lot of entries are missing, so we can decide whether to include that variable at all."
},
{
"code": null,
"e": 405,
"s": 378,
"text": "Method 1: Using describe()"
},
{
"code": null,
"e": 661,
"s": 405,
"text": "We can use the describe() method which returns a table containing details about the dataset. The count property directly gives the count of non-NaN values in each column. So, we can get the count of NaN values, if we know the total number of observations."
},
{
"code": "import pandas as pd import numpy as np # dictionary of lists dict = { 'A':[1, 4, 6, 9], 'B':[np.NaN, 5, 8, np.NaN], 'C':[7, 3, np.NaN, 2], 'D':[1, np.NaN, np.NaN, np.NaN] } # creating dataframe from the# dictionary data = pd.DataFrame(dict) data.describe()",
"e": 950,
"s": 661,
"text": null
},
{
"code": null,
"e": 959,
"s": 950,
"text": "Output :"
},
{
"code": null,
"e": 1237,
"s": 959,
"text": "Method 2: Using sum()The isnull() function returns a dataset containing True and False values. Since, True is treated as a 1 and False as 0, calling the sum() method on the isnull() series returns the count of True values which actually corresponds to the number of NaN values."
},
{
"code": null,
"e": 1264,
"s": 1237,
"text": "Counting NaN in a column :"
},
{
"code": null,
"e": 1340,
"s": 1264,
"text": "We can simply find the null values in the desired column, then get the sum."
},
{
"code": "import pandas as pdimport numpy as np # dictionary of lists dict = { 'A':[1, 4, 6, 9], 'B':[np.NaN, 5, 8, np.NaN], 'C':[7, 3, np.NaN, 2], 'D':[1, np.NaN, np.NaN, np.NaN] } # creating dataframe from the# dictionary data = pd.DataFrame(dict) # total NaN values in column 'B'print(data['B'].isnull().sum())",
"e": 1676,
"s": 1340,
"text": null
},
{
"code": null,
"e": 1685,
"s": 1676,
"text": "Output :"
},
{
"code": null,
"e": 1687,
"s": 1685,
"text": "2"
},
{
"code": null,
"e": 1711,
"s": 1687,
"text": "Counting NaN in a row :"
},
{
"code": null,
"e": 1786,
"s": 1711,
"text": "The row can be selected using loc or iloc. Then we find the sum as before."
},
{
"code": "import pandas as pd import numpy as np # dictionary of lists dict = { 'A':[1, 4, 6, 9], 'B':[np.NaN, 5, 8, np.NaN], 'C':[7, 3, np.NaN, 2], 'D':[1, np.NaN, np.NaN, np.NaN] } # creating dataframe from the # dictionary data = pd.DataFrame(dict) # total NaN values in row index 1print(data.loc[1, :].isnull().sum())",
"e": 2131,
"s": 1786,
"text": null
},
{
"code": null,
"e": 2140,
"s": 2131,
"text": "Output :"
},
{
"code": null,
"e": 2142,
"s": 2140,
"text": "1"
},
{
"code": null,
"e": 2362,
"s": 2142,
"text": "Counting NaN in the entire DataFrame :To count NaN in the entire dataset, we just need to call the sum() function twice – once for getting the count in each column and again for finding the total sum of all the columns."
},
{
"code": "import pandas as pd import numpy as np # dictionary of lists dict = {'A':[1, 4, 6, 9], 'B':[np.NaN, 5, 8, np.NaN], 'C':[7, 3, np.NaN, 2], 'D':[1, np.NaN, np.NaN, np.NaN]} # creating dataframe from the# dictionary data = pd.DataFrame(dict) # total count of NaN valuesprint(data.isnull().sum().sum())",
"e": 2691,
"s": 2362,
"text": null
},
{
"code": null,
"e": 2700,
"s": 2691,
"text": "Output :"
},
{
"code": null,
"e": 2702,
"s": 2700,
"text": "6"
},
{
"code": null,
"e": 2726,
"s": 2702,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2740,
"s": 2726,
"text": "Python-pandas"
},
{
"code": null,
"e": 2747,
"s": 2740,
"text": "Python"
},
{
"code": null,
"e": 2845,
"s": 2747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2877,
"s": 2845,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2904,
"s": 2877,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2925,
"s": 2904,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2948,
"s": 2925,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2979,
"s": 2948,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3035,
"s": 2979,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3077,
"s": 3035,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3119,
"s": 3077,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3158,
"s": 3119,
"text": "Python | Get unique values from a list"
}
] |
Search A pandas Column For A Value
|
17 Dec, 2020
Prerequisites: pandas
In this article let’s discuss how to search data frame for a given specific value using pandas.
where() -is used to check a data frame for one or more condition and return the result accordingly. By default, The rows not satisfying the condition are filled with NaN value.
dropna() -This method allows the user to analyze and drop Rows/Columns with Null values. In this article it is used to deal with the cases where the rows that will have value as NaN because they will not satisfy a certain condition.
Import modules
Create data
Traverse through the column looking for a specific value
If matched, select
There is a basic difference between selecting a specific values and selecting rows that have a specific value. For the later case the indices to be retrieved has to be stored in a list. Implementation of both cases is included in this article:
Data frame in use:
Example 1: Select tuple containing salary as 200
Python3
import pandas as pdx = pd.DataFrame([["A", 100, "D"], ["B", 200, "E"], ["C", 100, "F"]], columns=["Name", "Salary", "Department"]) # Searching in whole columnfor i in range(len(x.Name)): if 200 == x.Salary[i]: # indx will store the tuple having that # particular value in column. indx = i # below line will print that tuplex.iloc[indx]
Output:
Example 2: Search for people having salary of 100 and store the output in a dataframe again.
Python3
import pandas as pdx = pd.DataFrame([["A", 100, "D"], ["B", 200, "E"], ["C", 100, "F"]], columns=[ "Name", "Salary", "Department"]) # initialize the indx as a listindx = [] # Searching in whole columnfor i in range(len(x.Name)): if 100 == x.Salary[i]: # indx will store all the tuples having # that particular value in column. indx.append(i) # Final Dataframe having tuplesdf = pd.DataFrame() # this will append all tuples to the final# dataframe.for indexes in indx: df = df.append(x.iloc[indexes]) df = x.where(x.Salary == 100) # It will remove NaN rows.df.dropna()
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "Prerequisites: pandas"
},
{
"code": null,
"e": 146,
"s": 50,
"text": "In this article let’s discuss how to search data frame for a given specific value using pandas."
},
{
"code": null,
"e": 323,
"s": 146,
"text": "where() -is used to check a data frame for one or more condition and return the result accordingly. By default, The rows not satisfying the condition are filled with NaN value."
},
{
"code": null,
"e": 557,
"s": 323,
"text": "dropna() -This method allows the user to analyze and drop Rows/Columns with Null values. In this article it is used to deal with the cases where the rows that will have value as NaN because they will not satisfy a certain condition. "
},
{
"code": null,
"e": 572,
"s": 557,
"text": "Import modules"
},
{
"code": null,
"e": 584,
"s": 572,
"text": "Create data"
},
{
"code": null,
"e": 641,
"s": 584,
"text": "Traverse through the column looking for a specific value"
},
{
"code": null,
"e": 660,
"s": 641,
"text": "If matched, select"
},
{
"code": null,
"e": 904,
"s": 660,
"text": "There is a basic difference between selecting a specific values and selecting rows that have a specific value. For the later case the indices to be retrieved has to be stored in a list. Implementation of both cases is included in this article:"
},
{
"code": null,
"e": 923,
"s": 904,
"text": "Data frame in use:"
},
{
"code": null,
"e": 972,
"s": 923,
"text": "Example 1: Select tuple containing salary as 200"
},
{
"code": null,
"e": 980,
"s": 972,
"text": "Python3"
},
{
"code": "import pandas as pdx = pd.DataFrame([[\"A\", 100, \"D\"], [\"B\", 200, \"E\"], [\"C\", 100, \"F\"]], columns=[\"Name\", \"Salary\", \"Department\"]) # Searching in whole columnfor i in range(len(x.Name)): if 200 == x.Salary[i]: # indx will store the tuple having that # particular value in column. indx = i # below line will print that tuplex.iloc[indx]",
"e": 1369,
"s": 980,
"text": null
},
{
"code": null,
"e": 1377,
"s": 1369,
"text": "Output:"
},
{
"code": null,
"e": 1471,
"s": 1377,
"text": "Example 2: Search for people having salary of 100 and store the output in a dataframe again. "
},
{
"code": null,
"e": 1479,
"s": 1471,
"text": "Python3"
},
{
"code": "import pandas as pdx = pd.DataFrame([[\"A\", 100, \"D\"], [\"B\", 200, \"E\"], [\"C\", 100, \"F\"]], columns=[ \"Name\", \"Salary\", \"Department\"]) # initialize the indx as a listindx = [] # Searching in whole columnfor i in range(len(x.Name)): if 100 == x.Salary[i]: # indx will store all the tuples having # that particular value in column. indx.append(i) # Final Dataframe having tuplesdf = pd.DataFrame() # this will append all tuples to the final# dataframe.for indexes in indx: df = df.append(x.iloc[indexes]) df = x.where(x.Salary == 100) # It will remove NaN rows.df.dropna()",
"e": 2106,
"s": 1479,
"text": null
},
{
"code": null,
"e": 2114,
"s": 2106,
"text": "Output:"
},
{
"code": null,
"e": 2121,
"s": 2114,
"text": "Picked"
},
{
"code": null,
"e": 2145,
"s": 2121,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2168,
"s": 2145,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 2182,
"s": 2168,
"text": "Python-pandas"
},
{
"code": null,
"e": 2189,
"s": 2182,
"text": "Python"
},
{
"code": null,
"e": 2287,
"s": 2189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2319,
"s": 2287,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2346,
"s": 2319,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2367,
"s": 2346,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2390,
"s": 2367,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2446,
"s": 2390,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2477,
"s": 2446,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2519,
"s": 2477,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2561,
"s": 2519,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2600,
"s": 2561,
"text": "Python | Get unique values from a list"
}
] |
Port Address Translation (PAT) on Adaptive Security Appliance (ASA)
|
26 May, 2019
Port Address Translation (PAT) is a type of Network address translation (NAT) used when there is a shortage of public IP addresses .One of the public IP address of the same subnet or the interface address is used for translation.
Port Address Translation (PAT):This is also known as NAT overload. In this, many local (private) IP addresses get translated to single public IP address .Sometimes, the private addresses are translated into the interface address (single). In this, Port numbers are used to distinguish the traffic i.e which traffic belongs to which IP address.
Procedure:The procedure is almost same as done in Dynamic NAT but remember in PAT, more than one Private IP address is translated into a single public IP address.
Step-1: Configure the access-listBuild the access-list stating the permit condition i.e who should be permit and what protocol should be permit.
Step-2: Apply the access-list to an interfaceThe access-group command will be used to state the direction (out or in) in which the action (specified above) should be taken place.
Step-3: Create network group or network objectNetwork group will state the subnet or different subnets on which PAT will be applied. While the network object states a single subnet which can be further used in the PAT process for translation. It can be said that network group contains more than one network object.
Step-4: PAT statementThis step will specify the direction in which PAT should takes place and on what IP address (Public IP address) the private IP address should be translated.
Configuration:
Three routers namely Router1 (IP address – 10.1.1.1/24), Router2 (IP address – 11.1.1.1/24) and Router3 (IP address – 101.1.1.1) are connected to ASA (IP address- 10.1.1.2/24, name – INSIDE and security level – 100 on Gi0/0, IP address – 11.1.1.2/24, name – DMZ and security level – 50 on Gi0/1, IP address – 101.1.1.2/24, name-OUTSIDE and security level – 0 on Gi0/2) as shown in the above figure.
In this task, we will enable PAT for the traffic generating from INSIDE to OUTSIDE and for the traffic going from DMZ to OUTSIDE.
Configuring IP addresses on all routers and ASA.
Configure IP address on Router1:
Router1(config)#int fa0/0
Router1(config-if)#ip address 10.1.1.1 255.255.255.0
Router1(config-if)#no shut
Configuring IP address on Router2:
Router2(config)#int fa0/0
Router2(config-if)#ip address 11.1.1.1 255.255.255.0
Router2(config-if)#no shut
Configuring IP address on Router3:
Router3(config)#int fa0/0
Router3(config-if)#ip address 101.1.1.1 255.255.255.0
Router3(config-if)#no shut
Configuring IP address, name and security level on the interface of ASA:
asa(config)#int Gi0/0
asa(config-if)#no shut
asa(config-if)#ip address 10.1.1.2 255.255.255.0
asa(config-if)#nameif INSIDE
asa(config-if)#security level 100
asa(config-if)#exit
asa(config)#int Gi0/1
asa(config-if)#no shut
asa(config-if)#ip address 11.1.1.2 255.255.255.0
asa(config-if)#nameif DMZ
asa(config-if)#security level 50
asa(config-if)#exit
asa(config)#int Gi0/2
asa(config-if)#no shut
asa(config-if)#ip address 101.1.1.2 255.255.255.0
asa(config-if)#nameif OUTSIDE
asa(config-if)#security level 0
Now giving static routes to the routers. Configuring static route to Router1:
Router1(config)#ip route 0.0.0.0 0.0.0.0 10.1.1.2
Configuring static route to Router2:
Router2(config)#ip route 0.0.0.0 0.0.0.0 11.1.1.2
Configuring static route to Router3:
Router3(config)#ip route 0.0.0.0 0.0.0.0 101.1.1.2
At last configuring static route to ASA:
asa(config)#route INSIDE 10.1.1.0 255.255.255.0 10.1.1.1
asa(config)#route OUTSIDE 101.1.1.0 255.255.255.0 101.1.1.1
asa(config)#route DMZ 11.1.1.0 255.255.255.0 10.1.1.1
For ICMP, either inspect or use ACL to allow the ICMP echo reply from the lower security level to higher security level (This is to be done because by default, no traffic is allowed from lower security level to higher security level).
Configuring access-list:
asa(config)#access-list traffic_out permit icmp any any
asa(config)#access-list traffic_dmz permit icmp any any
Here, two access-list has been made.
First access-list name is traffic_out which will allow ICMP traffic from OUTSIDE to INSIDE (having any IP address any mask).Second access-list has been made named as traffic_dmz which will allow ICMP traffic from OUTSIDE to DMZ (having any IP address any mask) .
Apply these access-list to the ASA interfaces:
asa(config)#access-group traffic_out in interface OUTSIDE
asa(config)#access-group traffic_dmz in interface DMZ
First statement states that the access-list traffic_out is applied in the inwards direction to the OUTSIDE interfaceSecond statement states that the access-list traffic_dmz is applied in the inwards direction to the DMZ interface.INSIDE devices will be able to ping OUTSIDE and DMZ devices.
The task is to enable PAT on ASA whenever the whole subnet (10.1.1.0/24) traffic goes out from INSIDE to OUTSIDE and traffic of network (11.1.1.0/24) from DMZ to OUTSIDE, it should get translated into OUTSIDE interface address.
asa(config)#object network inside_nat
asa(config-network-object)#subnet 10.1.1.0 255.255.255.0
asa(config-network-object)#exit
First, specify that which subnet should get translated.
Direction of NAT translation will be specified:
asa(config)#nat (INSIDE, OUTSIDE) source dynamic INSIDE interface
Applying NAT for traffic going out from DMZ to OUTSIDE:
asa(config)#object network dmz_nat
asa(config-network-object)#subnet 11.1.1.0 255.255.255.0
asa(config-network-object)#exit
Creating NAT pool for this traffic:
asa(config)#object network dmz_nat_pool
asa(config-network-object)#range 120.1.1.1 120.1.1.4
asa(config-network-object)#exit
Tirection for nat translation is specified.
asa(config)#nat (DMZ, OUTSIDE) source dynamic DMZ interface
The above command specifies that the subnet in dmz_nat should get translated into the IP address of the DMZ interface using PAT. By this, the process of configuring PAT is almost similar to dynamic NAT. The main difference is that to configure the outside interface IP address instead of a NAT pool from which one of the IP address will get translated.
Advantages:This is most frequently used as it is cost effective as thousands of users can be connected to the Internet by using only one real global (public) IP address.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Differences between IPv4 and IPv6
GSM in Wireless Communication
Secure Socket Layer (SSL)
TCP 3-Way Handshake Process
Introduction of Mobile Ad hoc Network (MANET)
Difference between MANET and VANET
Advanced Encryption Standard (AES)
User Datagram Protocol (UDP)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2019"
},
{
"code": null,
"e": 258,
"s": 28,
"text": "Port Address Translation (PAT) is a type of Network address translation (NAT) used when there is a shortage of public IP addresses .One of the public IP address of the same subnet or the interface address is used for translation."
},
{
"code": null,
"e": 602,
"s": 258,
"text": "Port Address Translation (PAT):This is also known as NAT overload. In this, many local (private) IP addresses get translated to single public IP address .Sometimes, the private addresses are translated into the interface address (single). In this, Port numbers are used to distinguish the traffic i.e which traffic belongs to which IP address."
},
{
"code": null,
"e": 765,
"s": 602,
"text": "Procedure:The procedure is almost same as done in Dynamic NAT but remember in PAT, more than one Private IP address is translated into a single public IP address."
},
{
"code": null,
"e": 910,
"s": 765,
"text": "Step-1: Configure the access-listBuild the access-list stating the permit condition i.e who should be permit and what protocol should be permit."
},
{
"code": null,
"e": 1089,
"s": 910,
"text": "Step-2: Apply the access-list to an interfaceThe access-group command will be used to state the direction (out or in) in which the action (specified above) should be taken place."
},
{
"code": null,
"e": 1405,
"s": 1089,
"text": "Step-3: Create network group or network objectNetwork group will state the subnet or different subnets on which PAT will be applied. While the network object states a single subnet which can be further used in the PAT process for translation. It can be said that network group contains more than one network object."
},
{
"code": null,
"e": 1583,
"s": 1405,
"text": "Step-4: PAT statementThis step will specify the direction in which PAT should takes place and on what IP address (Public IP address) the private IP address should be translated."
},
{
"code": null,
"e": 1598,
"s": 1583,
"text": "Configuration:"
},
{
"code": null,
"e": 1997,
"s": 1598,
"text": "Three routers namely Router1 (IP address – 10.1.1.1/24), Router2 (IP address – 11.1.1.1/24) and Router3 (IP address – 101.1.1.1) are connected to ASA (IP address- 10.1.1.2/24, name – INSIDE and security level – 100 on Gi0/0, IP address – 11.1.1.2/24, name – DMZ and security level – 50 on Gi0/1, IP address – 101.1.1.2/24, name-OUTSIDE and security level – 0 on Gi0/2) as shown in the above figure."
},
{
"code": null,
"e": 2127,
"s": 1997,
"text": "In this task, we will enable PAT for the traffic generating from INSIDE to OUTSIDE and for the traffic going from DMZ to OUTSIDE."
},
{
"code": null,
"e": 2176,
"s": 2127,
"text": "Configuring IP addresses on all routers and ASA."
},
{
"code": null,
"e": 2209,
"s": 2176,
"text": "Configure IP address on Router1:"
},
{
"code": null,
"e": 2316,
"s": 2209,
"text": "Router1(config)#int fa0/0\nRouter1(config-if)#ip address 10.1.1.1 255.255.255.0\nRouter1(config-if)#no shut "
},
{
"code": null,
"e": 2351,
"s": 2316,
"text": "Configuring IP address on Router2:"
},
{
"code": null,
"e": 2458,
"s": 2351,
"text": "Router2(config)#int fa0/0\nRouter2(config-if)#ip address 11.1.1.1 255.255.255.0\nRouter2(config-if)#no shut "
},
{
"code": null,
"e": 2493,
"s": 2458,
"text": "Configuring IP address on Router3:"
},
{
"code": null,
"e": 2601,
"s": 2493,
"text": "Router3(config)#int fa0/0\nRouter3(config-if)#ip address 101.1.1.1 255.255.255.0\nRouter3(config-if)#no shut "
},
{
"code": null,
"e": 2674,
"s": 2601,
"text": "Configuring IP address, name and security level on the interface of ASA:"
},
{
"code": null,
"e": 3182,
"s": 2674,
"text": "asa(config)#int Gi0/0\nasa(config-if)#no shut\nasa(config-if)#ip address 10.1.1.2 255.255.255.0\nasa(config-if)#nameif INSIDE \nasa(config-if)#security level 100\nasa(config-if)#exit\nasa(config)#int Gi0/1\nasa(config-if)#no shut\nasa(config-if)#ip address 11.1.1.2 255.255.255.0\nasa(config-if)#nameif DMZ\nasa(config-if)#security level 50\nasa(config-if)#exit\nasa(config)#int Gi0/2\nasa(config-if)#no shut\nasa(config-if)#ip address 101.1.1.2 255.255.255.0\nasa(config-if)#nameif OUTSIDE\nasa(config-if)#security level 0"
},
{
"code": null,
"e": 3260,
"s": 3182,
"text": "Now giving static routes to the routers. Configuring static route to Router1:"
},
{
"code": null,
"e": 3311,
"s": 3260,
"text": "Router1(config)#ip route 0.0.0.0 0.0.0.0 10.1.1.2 "
},
{
"code": null,
"e": 3348,
"s": 3311,
"text": "Configuring static route to Router2:"
},
{
"code": null,
"e": 3399,
"s": 3348,
"text": "Router2(config)#ip route 0.0.0.0 0.0.0.0 11.1.1.2 "
},
{
"code": null,
"e": 3436,
"s": 3399,
"text": "Configuring static route to Router3:"
},
{
"code": null,
"e": 3488,
"s": 3436,
"text": "Router3(config)#ip route 0.0.0.0 0.0.0.0 101.1.1.2 "
},
{
"code": null,
"e": 3529,
"s": 3488,
"text": "At last configuring static route to ASA:"
},
{
"code": null,
"e": 3700,
"s": 3529,
"text": "asa(config)#route INSIDE 10.1.1.0 255.255.255.0 10.1.1.1\nasa(config)#route OUTSIDE 101.1.1.0 255.255.255.0 101.1.1.1\nasa(config)#route DMZ 11.1.1.0 255.255.255.0 10.1.1.1"
},
{
"code": null,
"e": 3935,
"s": 3700,
"text": "For ICMP, either inspect or use ACL to allow the ICMP echo reply from the lower security level to higher security level (This is to be done because by default, no traffic is allowed from lower security level to higher security level)."
},
{
"code": null,
"e": 3960,
"s": 3935,
"text": "Configuring access-list:"
},
{
"code": null,
"e": 4074,
"s": 3960,
"text": "asa(config)#access-list traffic_out permit icmp any any \nasa(config)#access-list traffic_dmz permit icmp any any "
},
{
"code": null,
"e": 4111,
"s": 4074,
"text": "Here, two access-list has been made."
},
{
"code": null,
"e": 4374,
"s": 4111,
"text": "First access-list name is traffic_out which will allow ICMP traffic from OUTSIDE to INSIDE (having any IP address any mask).Second access-list has been made named as traffic_dmz which will allow ICMP traffic from OUTSIDE to DMZ (having any IP address any mask) ."
},
{
"code": null,
"e": 4421,
"s": 4374,
"text": "Apply these access-list to the ASA interfaces:"
},
{
"code": null,
"e": 4534,
"s": 4421,
"text": "asa(config)#access-group traffic_out in interface OUTSIDE \nasa(config)#access-group traffic_dmz in interface DMZ"
},
{
"code": null,
"e": 4825,
"s": 4534,
"text": "First statement states that the access-list traffic_out is applied in the inwards direction to the OUTSIDE interfaceSecond statement states that the access-list traffic_dmz is applied in the inwards direction to the DMZ interface.INSIDE devices will be able to ping OUTSIDE and DMZ devices."
},
{
"code": null,
"e": 5053,
"s": 4825,
"text": "The task is to enable PAT on ASA whenever the whole subnet (10.1.1.0/24) traffic goes out from INSIDE to OUTSIDE and traffic of network (11.1.1.0/24) from DMZ to OUTSIDE, it should get translated into OUTSIDE interface address."
},
{
"code": null,
"e": 5180,
"s": 5053,
"text": "asa(config)#object network inside_nat\nasa(config-network-object)#subnet 10.1.1.0 255.255.255.0\nasa(config-network-object)#exit"
},
{
"code": null,
"e": 5236,
"s": 5180,
"text": "First, specify that which subnet should get translated."
},
{
"code": null,
"e": 5284,
"s": 5236,
"text": "Direction of NAT translation will be specified:"
},
{
"code": null,
"e": 5350,
"s": 5284,
"text": "asa(config)#nat (INSIDE, OUTSIDE) source dynamic INSIDE interface"
},
{
"code": null,
"e": 5406,
"s": 5350,
"text": "Applying NAT for traffic going out from DMZ to OUTSIDE:"
},
{
"code": null,
"e": 5530,
"s": 5406,
"text": "asa(config)#object network dmz_nat\nasa(config-network-object)#subnet 11.1.1.0 255.255.255.0\nasa(config-network-object)#exit"
},
{
"code": null,
"e": 5566,
"s": 5530,
"text": "Creating NAT pool for this traffic:"
},
{
"code": null,
"e": 5691,
"s": 5566,
"text": "asa(config)#object network dmz_nat_pool\nasa(config-network-object)#range 120.1.1.1 120.1.1.4\nasa(config-network-object)#exit"
},
{
"code": null,
"e": 5735,
"s": 5691,
"text": "Tirection for nat translation is specified."
},
{
"code": null,
"e": 5796,
"s": 5735,
"text": "asa(config)#nat (DMZ, OUTSIDE) source dynamic DMZ interface "
},
{
"code": null,
"e": 6149,
"s": 5796,
"text": "The above command specifies that the subnet in dmz_nat should get translated into the IP address of the DMZ interface using PAT. By this, the process of configuring PAT is almost similar to dynamic NAT. The main difference is that to configure the outside interface IP address instead of a NAT pool from which one of the IP address will get translated."
},
{
"code": null,
"e": 6319,
"s": 6149,
"text": "Advantages:This is most frequently used as it is cost effective as thousands of users can be connected to the Internet by using only one real global (public) IP address."
},
{
"code": null,
"e": 6337,
"s": 6319,
"text": "Computer Networks"
},
{
"code": null,
"e": 6355,
"s": 6337,
"text": "Computer Networks"
},
{
"code": null,
"e": 6453,
"s": 6355,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6483,
"s": 6453,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 6523,
"s": 6483,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 6557,
"s": 6523,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 6587,
"s": 6557,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 6613,
"s": 6587,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 6641,
"s": 6613,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 6687,
"s": 6641,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 6722,
"s": 6687,
"text": "Difference between MANET and VANET"
},
{
"code": null,
"e": 6757,
"s": 6722,
"text": "Advanced Encryption Standard (AES)"
}
] |
Python – Star or Asterisk operator ( * )
|
26 Nov, 2020
There are a many places you’ll see * and ** used in Python. Many Python Programmer even at the intermediate level is often puzzled when it comes to the asterisk ( * ) character in Python.
After studying this article, you will have a solid understanding of the asterisk ( * ) operator in Python and become a better coder in the process!
Multiplication :In Multiplication, we multiply two numbers using Asterisk / Star Operator as infix an Operator.
Python3
# using asteriskmul = 5 * 7print (mul)
Output:
35
Exponentiation :Using two(**) Start Operator we can get the exponential value of any integer value.
Python3
a = 5b = 3 # using asteriskresult = a ** bprint(result)
Output:
125
Multiplication of a list :With the help of ‘ * ‘ we can multiply elements of a list, it transforms the code into single line.
Python3
# using asterisklist = ['geeks '] * 3 print(list)
Output:
['geeks ', 'geeks ', 'geeks ']
Unpacking a function using positional argument.This method is very useful while printing your data in a raw format (without any comma and brackets ). Many of the programmer try to remove comma and bracket by using a convolution of functions, Hence this simple prefix asterisk can solve your problem in unpacking them.
Python3
arr = ['sunday', 'monday', 'tuesday', 'wednesday'] # without using asteriskprint(' '.join(map(str,arr))) # using asteriskprint (*arr)
Output:
sunday monday tuesday wednesday
sunday monday tuesday wednesday
Passing a Function Using with an arbitrary number of positional argumentHere single asterisk( * ) is also used in *args. It is used to pass a variable number of arguments to a function, it is mostly used to pass a non-key argument and variable-length argument list.It has many uses, one such example is illustrated below, we make an addition function that takes any number of arguments and able to add them all together using *args.
Python3
# using asteriskdef addition(*args): return sum(args) print(addition(5, 10, 20, 6))
Output:
41
Passing a Function Using with an arbitrary number of positional argumentHere double asterisk( ** ) is also used as **kwargs, the double asterisks allow passing keyword argument. This special symbol is used to pass a keyword arguments and variable-length argument list. It has many uses, one such example is illustrated below
Python3
# using asteriskdef food(**kwargs): for items in kwargs: print(f"{kwargs[items]} is a {items}") food(fruit = 'cherry', vegetable = 'potato', boy = 'srikrishna')
Output:
cherry is a fruit
potato is a vegetable
srikrishna is a boy
Just another example of using **kwargs, for much better understanding.
Python3
# using asteriskdef food(**kwargs): for items in kwargs: print(f"{kwargs[items]} is a {items}") dict = {'fruit' : 'cherry', 'vegetable' : 'potato', 'boy' : 'srikrishna'}# using asteriskfood(**dict)
Output:
cherry is a fruit
potato is a vegetable
srikrishna is a boy
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 241,
"s": 52,
"text": "There are a many places you’ll see * and ** used in Python. Many Python Programmer even at the intermediate level is often puzzled when it comes to the asterisk ( * ) character in Python. "
},
{
"code": null,
"e": 389,
"s": 241,
"text": "After studying this article, you will have a solid understanding of the asterisk ( * ) operator in Python and become a better coder in the process!"
},
{
"code": null,
"e": 502,
"s": 389,
"text": "Multiplication :In Multiplication, we multiply two numbers using Asterisk / Star Operator as infix an Operator."
},
{
"code": null,
"e": 510,
"s": 502,
"text": "Python3"
},
{
"code": "# using asteriskmul = 5 * 7print (mul)",
"e": 549,
"s": 510,
"text": null
},
{
"code": null,
"e": 557,
"s": 549,
"text": "Output:"
},
{
"code": null,
"e": 560,
"s": 557,
"text": "35"
},
{
"code": null,
"e": 660,
"s": 560,
"text": "Exponentiation :Using two(**) Start Operator we can get the exponential value of any integer value."
},
{
"code": null,
"e": 668,
"s": 660,
"text": "Python3"
},
{
"code": "a = 5b = 3 # using asteriskresult = a ** bprint(result)",
"e": 725,
"s": 668,
"text": null
},
{
"code": null,
"e": 733,
"s": 725,
"text": "Output:"
},
{
"code": null,
"e": 737,
"s": 733,
"text": "125"
},
{
"code": null,
"e": 864,
"s": 737,
"text": "Multiplication of a list :With the help of ‘ * ‘ we can multiply elements of a list, it transforms the code into single line."
},
{
"code": null,
"e": 872,
"s": 864,
"text": "Python3"
},
{
"code": "# using asterisklist = ['geeks '] * 3 print(list)",
"e": 923,
"s": 872,
"text": null
},
{
"code": null,
"e": 931,
"s": 923,
"text": "Output:"
},
{
"code": null,
"e": 962,
"s": 931,
"text": "['geeks ', 'geeks ', 'geeks ']"
},
{
"code": null,
"e": 1282,
"s": 962,
"text": "Unpacking a function using positional argument.This method is very useful while printing your data in a raw format (without any comma and brackets ). Many of the programmer try to remove comma and bracket by using a convolution of functions, Hence this simple prefix asterisk can solve your problem in unpacking them. "
},
{
"code": null,
"e": 1290,
"s": 1282,
"text": "Python3"
},
{
"code": "arr = ['sunday', 'monday', 'tuesday', 'wednesday'] # without using asteriskprint(' '.join(map(str,arr))) # using asteriskprint (*arr)",
"e": 1427,
"s": 1290,
"text": null
},
{
"code": null,
"e": 1435,
"s": 1427,
"text": "Output:"
},
{
"code": null,
"e": 1499,
"s": 1435,
"text": "sunday monday tuesday wednesday\nsunday monday tuesday wednesday"
},
{
"code": null,
"e": 1933,
"s": 1499,
"text": "Passing a Function Using with an arbitrary number of positional argumentHere single asterisk( * ) is also used in *args. It is used to pass a variable number of arguments to a function, it is mostly used to pass a non-key argument and variable-length argument list.It has many uses, one such example is illustrated below, we make an addition function that takes any number of arguments and able to add them all together using *args."
},
{
"code": null,
"e": 1941,
"s": 1933,
"text": "Python3"
},
{
"code": "# using asteriskdef addition(*args): return sum(args) print(addition(5, 10, 20, 6))",
"e": 2027,
"s": 1941,
"text": null
},
{
"code": null,
"e": 2035,
"s": 2027,
"text": "Output:"
},
{
"code": null,
"e": 2038,
"s": 2035,
"text": "41"
},
{
"code": null,
"e": 2365,
"s": 2038,
"text": "Passing a Function Using with an arbitrary number of positional argumentHere double asterisk( ** ) is also used as **kwargs, the double asterisks allow passing keyword argument. This special symbol is used to pass a keyword arguments and variable-length argument list. It has many uses, one such example is illustrated below "
},
{
"code": null,
"e": 2373,
"s": 2365,
"text": "Python3"
},
{
"code": "# using asteriskdef food(**kwargs): for items in kwargs: print(f\"{kwargs[items]} is a {items}\") food(fruit = 'cherry', vegetable = 'potato', boy = 'srikrishna')",
"e": 2549,
"s": 2373,
"text": null
},
{
"code": null,
"e": 2557,
"s": 2549,
"text": "Output:"
},
{
"code": null,
"e": 2617,
"s": 2557,
"text": "cherry is a fruit\npotato is a vegetable\nsrikrishna is a boy"
},
{
"code": null,
"e": 2688,
"s": 2617,
"text": "Just another example of using **kwargs, for much better understanding."
},
{
"code": null,
"e": 2696,
"s": 2688,
"text": "Python3"
},
{
"code": "# using asteriskdef food(**kwargs): for items in kwargs: print(f\"{kwargs[items]} is a {items}\") dict = {'fruit' : 'cherry', 'vegetable' : 'potato', 'boy' : 'srikrishna'}# using asteriskfood(**dict)",
"e": 2909,
"s": 2696,
"text": null
},
{
"code": null,
"e": 2917,
"s": 2909,
"text": "Output:"
},
{
"code": null,
"e": 2977,
"s": 2917,
"text": "cherry is a fruit\npotato is a vegetable\nsrikrishna is a boy"
},
{
"code": null,
"e": 2994,
"s": 2977,
"text": "Python-Operators"
},
{
"code": null,
"e": 3001,
"s": 2994,
"text": "Python"
}
] |
How to make Mergesort to perform O(n) comparisons in best case?
|
18 Sep, 2017
As we know, Mergesort is a divide and conquer algorithm that splits the array to halves recursively until it reaches an array of the size of 1, and after that it merges sorted subarrays until the original array is fully sorted. Typical implementation of merge sort works in O(n Log n) time in all three cases (best, average and worst).
We need to reduce the best case performance from O(n log n) to O(n).
The idea is to consider the case when array is already sorted. Before merging, just check if arr[mid] > arr[mid+1], because we are dealing with sorted subarrays. This will lead us to the recursive relation T(n) = 2*T(n/2) + 1 which can be resolved by the master’s theorem, so T(n) = n.
Examples:
Input : 1 2 3 4
Subarrays with size of 1:|1||2| |3||4|
Subarrays with size of 2: |1 2| |3 4|
Output : 1 2 3 4
Input : 1 2 3 4 5 6 7 8
Subarrays with size of 1: |1||2| |3||4| |5||6| |7||8|
Subarrays with size of 2: |1 2| |3 4| |5 6| |7 8|
Subarrays with size of 4: |1 2 3 4| |5 6 7 8|
Output : 1 2 3 4 5 6 7 8
// C program to implement merge sort that works// in O(n) time in best case.#include <stdio.h>#include <stdlib.h> void merge(int* arr, int low, int mid, int high); void mergesort(int* arr, int low, int high){ if (low < high) { int mid = (low + high) / 2; mergesort(arr, low, mid); mergesort(arr, mid + 1, high); // This is where we optimize for best // case. if (arr[mid] > arr[mid + 1]) merge(arr, low, mid, high); }} void merge(int* arr, int low, int mid, int high){ int i = low, j = mid + 1, k = 0; int* temp = (int*)calloc(high - low + 1, sizeof(int)); while ((i <= mid) && (j <= high)) if (arr[i] < arr[j]) temp[k++] = arr[i++]; else temp[k++] = arr[j++]; while (j <= high) // if( i>mid ) temp[k++] = arr[j++]; while (i <= mid) // j>high temp[k++] = arr[i++]; // copy temp[] to arr[] for (i = low, k = 0; i <= high; i++, k++) arr[i] = temp[k]; free(temp);} int main(){ int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; mergesort(a, 0, 7); for (int i = 0; i < 8; i++) printf("%d ", a[i]); return 0;}
Output:
1 2 3 4 5 6 7 8
This article is contributed by Shlomi Elhaiani. 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.
featured
Merge Sort
Sorting
Sorting
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Longest Common Prefix using Sorting
Sort a nearly sorted (or K sorted) array
Segregate 0s and 1s in an array
Sorting in Java
Quick Sort vs Merge Sort
Quickselect Algorithm
Stability in sorting algorithms
Find whether an array is subset of another array
Find all triplets with zero sum
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Sep, 2017"
},
{
"code": null,
"e": 390,
"s": 54,
"text": "As we know, Mergesort is a divide and conquer algorithm that splits the array to halves recursively until it reaches an array of the size of 1, and after that it merges sorted subarrays until the original array is fully sorted. Typical implementation of merge sort works in O(n Log n) time in all three cases (best, average and worst)."
},
{
"code": null,
"e": 459,
"s": 390,
"text": "We need to reduce the best case performance from O(n log n) to O(n)."
},
{
"code": null,
"e": 745,
"s": 459,
"text": "The idea is to consider the case when array is already sorted. Before merging, just check if arr[mid] > arr[mid+1], because we are dealing with sorted subarrays. This will lead us to the recursive relation T(n) = 2*T(n/2) + 1 which can be resolved by the master’s theorem, so T(n) = n."
},
{
"code": null,
"e": 755,
"s": 745,
"text": "Examples:"
},
{
"code": null,
"e": 1092,
"s": 755,
"text": "Input : 1 2 3 4\nSubarrays with size of 1:|1||2| |3||4|\nSubarrays with size of 2: |1 2| |3 4|\nOutput : 1 2 3 4\n\nInput : 1 2 3 4 5 6 7 8 \n Subarrays with size of 1: |1||2| |3||4| |5||6| |7||8|\n Subarrays with size of 2: |1 2| |3 4| |5 6| |7 8|\n Subarrays with size of 4: |1 2 3 4| |5 6 7 8|\nOutput : 1 2 3 4 5 6 7 8 \n"
},
{
"code": "// C program to implement merge sort that works// in O(n) time in best case.#include <stdio.h>#include <stdlib.h> void merge(int* arr, int low, int mid, int high); void mergesort(int* arr, int low, int high){ if (low < high) { int mid = (low + high) / 2; mergesort(arr, low, mid); mergesort(arr, mid + 1, high); // This is where we optimize for best // case. if (arr[mid] > arr[mid + 1]) merge(arr, low, mid, high); }} void merge(int* arr, int low, int mid, int high){ int i = low, j = mid + 1, k = 0; int* temp = (int*)calloc(high - low + 1, sizeof(int)); while ((i <= mid) && (j <= high)) if (arr[i] < arr[j]) temp[k++] = arr[i++]; else temp[k++] = arr[j++]; while (j <= high) // if( i>mid ) temp[k++] = arr[j++]; while (i <= mid) // j>high temp[k++] = arr[i++]; // copy temp[] to arr[] for (i = low, k = 0; i <= high; i++, k++) arr[i] = temp[k]; free(temp);} int main(){ int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; mergesort(a, 0, 7); for (int i = 0; i < 8; i++) printf(\"%d \", a[i]); return 0;}",
"e": 2251,
"s": 1092,
"text": null
},
{
"code": null,
"e": 2259,
"s": 2251,
"text": "Output:"
},
{
"code": null,
"e": 2277,
"s": 2259,
"text": " 1 2 3 4 5 6 7 8\n"
},
{
"code": null,
"e": 2580,
"s": 2277,
"text": "This article is contributed by Shlomi Elhaiani. 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": 2705,
"s": 2580,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2714,
"s": 2705,
"text": "featured"
},
{
"code": null,
"e": 2725,
"s": 2714,
"text": "Merge Sort"
},
{
"code": null,
"e": 2733,
"s": 2725,
"text": "Sorting"
},
{
"code": null,
"e": 2741,
"s": 2733,
"text": "Sorting"
},
{
"code": null,
"e": 2752,
"s": 2741,
"text": "Merge Sort"
},
{
"code": null,
"e": 2850,
"s": 2752,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2881,
"s": 2850,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 2917,
"s": 2881,
"text": "Longest Common Prefix using Sorting"
},
{
"code": null,
"e": 2958,
"s": 2917,
"text": "Sort a nearly sorted (or K sorted) array"
},
{
"code": null,
"e": 2990,
"s": 2958,
"text": "Segregate 0s and 1s in an array"
},
{
"code": null,
"e": 3006,
"s": 2990,
"text": "Sorting in Java"
},
{
"code": null,
"e": 3031,
"s": 3006,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 3053,
"s": 3031,
"text": "Quickselect Algorithm"
},
{
"code": null,
"e": 3085,
"s": 3053,
"text": "Stability in sorting algorithms"
},
{
"code": null,
"e": 3134,
"s": 3085,
"text": "Find whether an array is subset of another array"
}
] |
How to Replace a Character with the String in C#?
|
03 Dec, 2021
Given a string, now our task is to replace a specified character with the string. This task is performed with the help of Replace() method. This method is used to replace all the Unicode characters with the specified string and return a modified string.
Syntax:
string.Replace(character, new_string)
Here, string is the input string, a character is present in the string that is going to replace, and new_string is the string that replaces the character.
Examples:
Input: A portal in India
Replace A with Hello
Output: Hello portal in India
Input: Python is not equal to java
Replace is with was
Output: Python was not equal to java
Approach:
To replace a character with the specified string follow the following step:
Declare a string
Use Replace() function to replace the character(i.e., “A”) with string(i.e., “Geeks For Geeks”))
input_string.Replace("A", "Geeks For Geeks")
Display the modified string
Example:
C#
// C# program to replace a character// with a specified stringusing System; class GFG{ public static void Main(){ // Define string String input_string = "A portal in India"; Console.WriteLine("Actual String : " + input_string); // Replace the string 'A' with 'Geeks For Geeks' Console.WriteLine("Replaced String: " + input_string.Replace("A", "Geeks For Geeks"));}}
Output:
Actual String : A portal in India
Replaced String: Geeks For Geeks portal in India
surinderdawra388
CSharp-programs
CSharp-Strings-Programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 283,
"s": 28,
"text": "Given a string, now our task is to replace a specified character with the string. This task is performed with the help of Replace() method. This method is used to replace all the Unicode characters with the specified string and return a modified string. "
},
{
"code": null,
"e": 291,
"s": 283,
"text": "Syntax:"
},
{
"code": null,
"e": 329,
"s": 291,
"text": "string.Replace(character, new_string)"
},
{
"code": null,
"e": 484,
"s": 329,
"text": "Here, string is the input string, a character is present in the string that is going to replace, and new_string is the string that replaces the character."
},
{
"code": null,
"e": 494,
"s": 484,
"text": "Examples:"
},
{
"code": null,
"e": 663,
"s": 494,
"text": "Input: A portal in India\nReplace A with Hello\nOutput: Hello portal in India\n\nInput: Python is not equal to java\nReplace is with was\nOutput: Python was not equal to java"
},
{
"code": null,
"e": 673,
"s": 663,
"text": "Approach:"
},
{
"code": null,
"e": 749,
"s": 673,
"text": "To replace a character with the specified string follow the following step:"
},
{
"code": null,
"e": 766,
"s": 749,
"text": "Declare a string"
},
{
"code": null,
"e": 863,
"s": 766,
"text": "Use Replace() function to replace the character(i.e., “A”) with string(i.e., “Geeks For Geeks”))"
},
{
"code": null,
"e": 908,
"s": 863,
"text": "input_string.Replace(\"A\", \"Geeks For Geeks\")"
},
{
"code": null,
"e": 936,
"s": 908,
"text": "Display the modified string"
},
{
"code": null,
"e": 945,
"s": 936,
"text": "Example:"
},
{
"code": null,
"e": 948,
"s": 945,
"text": "C#"
},
{
"code": "// C# program to replace a character// with a specified stringusing System; class GFG{ public static void Main(){ // Define string String input_string = \"A portal in India\"; Console.WriteLine(\"Actual String : \" + input_string); // Replace the string 'A' with 'Geeks For Geeks' Console.WriteLine(\"Replaced String: \" + input_string.Replace(\"A\", \"Geeks For Geeks\"));}}",
"e": 1344,
"s": 948,
"text": null
},
{
"code": null,
"e": 1352,
"s": 1344,
"text": "Output:"
},
{
"code": null,
"e": 1435,
"s": 1352,
"text": "Actual String : A portal in India\nReplaced String: Geeks For Geeks portal in India"
},
{
"code": null,
"e": 1452,
"s": 1435,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1468,
"s": 1452,
"text": "CSharp-programs"
},
{
"code": null,
"e": 1492,
"s": 1468,
"text": "CSharp-Strings-Programs"
},
{
"code": null,
"e": 1499,
"s": 1492,
"text": "Picked"
},
{
"code": null,
"e": 1502,
"s": 1499,
"text": "C#"
}
] |
Python | Pandas Series.sort_values()
|
05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.sort_values() function is used to sort the given series object in ascending or descending order by some criterion. The function also provides the flexibility of choosing the sorting algorithm.
Syntax: Series.sort_values(axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
Parameter :axis : Axis to direct sorting.ascending : If True, sort values in ascending order, otherwise descending.inplace : If True, perform operation in-place.kind : Choice of sorting algorithm.na_position : Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.
Returns : Series
Example #1: Use Series.sort_values() function to sort the elements of the given series object in lexicographical order.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)
Output :
Now we will use Series.sort_values() function to sort the elements of the given series object in ascending order.
# sort the values in ascending ordersr.sort_values()
Output :
As we can see in the output, the Series.sort_values() function has successfully sorted the elements of the given series object in ascending order. Example #2: Use Series.sort_values() function to sort the elements of the given series object in descending order.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Print the seriesprint(sr)
Output :
Now we will use Series.sort_values() function to sort the elements of the given series object in descending order.
# sort the values in descending ordersr.sort_values(ascending = False)
Output :
As we can see in the output, the Series.sort_values() function has successfully sorted the elements of the given series object in descending order.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Feb, 2019"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 492,
"s": 285,
"text": "Pandas Series.sort_values() function is used to sort the given series object in ascending or descending order by some criterion. The function also provides the flexibility of choosing the sorting algorithm."
},
{
"code": null,
"e": 596,
"s": 492,
"text": "Syntax: Series.sort_values(axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)"
},
{
"code": null,
"e": 880,
"s": 596,
"text": "Parameter :axis : Axis to direct sorting.ascending : If True, sort values in ascending order, otherwise descending.inplace : If True, perform operation in-place.kind : Choice of sorting algorithm.na_position : Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end."
},
{
"code": null,
"e": 897,
"s": 880,
"text": "Returns : Series"
},
{
"code": null,
"e": 1017,
"s": 897,
"text": "Example #1: Use Series.sort_values() function to sort the elements of the given series object in lexicographical order."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)",
"e": 1369,
"s": 1017,
"text": null
},
{
"code": null,
"e": 1378,
"s": 1369,
"text": "Output :"
},
{
"code": null,
"e": 1492,
"s": 1378,
"text": "Now we will use Series.sort_values() function to sort the elements of the given series object in ascending order."
},
{
"code": "# sort the values in ascending ordersr.sort_values()",
"e": 1545,
"s": 1492,
"text": null
},
{
"code": null,
"e": 1554,
"s": 1545,
"text": "Output :"
},
{
"code": null,
"e": 1816,
"s": 1554,
"text": "As we can see in the output, the Series.sort_values() function has successfully sorted the elements of the given series object in ascending order. Example #2: Use Series.sort_values() function to sort the elements of the given series object in descending order."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002]) # Print the seriesprint(sr)",
"e": 1964,
"s": 1816,
"text": null
},
{
"code": null,
"e": 1973,
"s": 1964,
"text": "Output :"
},
{
"code": null,
"e": 2088,
"s": 1973,
"text": "Now we will use Series.sort_values() function to sort the elements of the given series object in descending order."
},
{
"code": "# sort the values in descending ordersr.sort_values(ascending = False)",
"e": 2159,
"s": 2088,
"text": null
},
{
"code": null,
"e": 2168,
"s": 2159,
"text": "Output :"
},
{
"code": null,
"e": 2316,
"s": 2168,
"text": "As we can see in the output, the Series.sort_values() function has successfully sorted the elements of the given series object in descending order."
},
{
"code": null,
"e": 2337,
"s": 2316,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2366,
"s": 2337,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2380,
"s": 2366,
"text": "Python-pandas"
},
{
"code": null,
"e": 2387,
"s": 2380,
"text": "Python"
},
{
"code": null,
"e": 2485,
"s": 2387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2503,
"s": 2485,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2545,
"s": 2503,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2567,
"s": 2545,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2602,
"s": 2567,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2628,
"s": 2602,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2660,
"s": 2628,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2689,
"s": 2660,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2716,
"s": 2689,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2746,
"s": 2716,
"text": "Iterate over a list in Python"
}
] |
Find politeness of a number
|
20 Apr, 2022
Given an integer n. Find politeness of number n. The politeness of a number is defined as the number of ways it can be expressed as the sum of consecutive integers.
Examples:
Input: n = 15
Output: 3
Explanation:
There are only three ways to express
15 as sum of consecutive integers i.e.,
15 = 1 + 2 + 3 + 4 + 5
15 = 4 + 5 + 6
15 = 7 + 8
Hence answer is 3
Input: n = 9;
Output: 2
There are two ways of representation:
9 = 2 + 3 + 4
9 = 4 + 5
Naive approach:
Run a loop one inside another and find the sum of every consecutive integer up to n. The time complexity of this approach will be O(n2) which will not be sufficient for large value of n.
Efficient Approach:
Use factorization. We factorize the number n and count the number of odd factors. A total number of odd factors (except 1) is equal to the politeness of the number. Refer this for proof of this fact. In general, if a number can be represented as ap * bq * cr ... where a, b, c, ... are prime factors of n. If a = 2 (even) then discard it and count total number of odd factors which can be written as [(q + 1) * (r + 1) * ...] – 1 (Here 1 is subtracted because single term in representation is not allowed). How does the above formula work? The fact is if a number is expressed as ap * bq * cr ... where a, b, c, ... are prime factors of n, then a number of divisors is (p+1)*(q+1)*(r+1) ...... To simplify, let there be one factor, and the number is expressed as ap. Divisors are 1, a, a2, .... ap. The count of divisors is p+1. Now let us take a slightly more complicated case apbp. The divisors are : 1, a, a2, .... ap b, ba, ba2, .... bap b2, b2a, b2a2, .... b2ap ................ ................ bq, bqa, bqa2, .... bqapThe count of the above terms is (p+1)*(q+1). Similarly, we can prove for more prime factors.Illustration : For n = 90, decomposition of prime factors will be as follows:- => 90 = 2 * 32 * 51. The power of odd prime factors 3, 5 are 2 and 1 respectively. Apply above formula as: (2 + 1) * (1 + 1) -1 = 5. Hence 5 will be the answer. We can crosscheck it. All odd factors are 3, 5, 9, 15 and 45.Below is the program of the above steps:
C++
Java
Python3
C#
PHP
Javascript
// C+ program to find politeness of number#include <iostream>using namespace std; // A function to count all odd prime factors// of a given number nint countOddPrimeFactors(int n){ int result = 1; // Eliminate all even prime // factor of number of n while (n % 2 == 0) n /= 2; // n must be odd at this point, // so iterate for only // odd numbers till sqrt(n) for (int i = 3; i * i <= n; i += 2) { int divCount = 0; // if i divides n, then start counting of // Odd divisors while (n % i == 0) { n /= i; ++divCount; } result *= divCount + 1; } // If n odd prime still remains then count it if (n > 2) result *= 2; return result;} int politeness(int n){ return countOddPrimeFactors(n) - 1;} // Driver program to test above functionint main(){ int n = 90; cout << "Politeness of " << n << " = " << politeness(n) << "\n"; n = 15; cout << "Politeness of " << n << " = " << politeness(n) << "\n"; return 0;}
// Java program to find politeness of a number public class Politeness { // A function to count all odd prime factors // of a given number n static int countOddPrimeFactors(int n) { int result = 1; // Eliminate all even prime // factor of number of n while (n % 2 == 0) n /= 2; // n must be odd at this point, so iterate // for only odd numbers till sqrt(n) for (int i = 3; i * i <= n; i += 2) { int divCount = 0; // if i divides n, then start counting of // Odd divisors while (n % i == 0) { n /= i; ++divCount; } result *= divCount + 1; } // If n odd prime still remains then count it if (n > 2) result *= 2; return result; } static int politeness(int n) { return countOddPrimeFactors(n) - 1; } public static void main(String[] args) { int n = 90; System.out.println("Politeness of " + n + " = " + politeness(n)); n = 15; System.out.println("Politeness of " + n + " = " + politeness(n)); }} // This code is contributed by Saket Kumar
# Python program to find politeness of number # A function to count all odd prime factors# of a given number ndef countOddPrimeFactors(n) : result = 1; # Eliminate all even prime factor of # number of n while (n % 2 == 0) : n //= 2 # n must be odd at this point, so iterate # for only odd numbers till sqrt(n) i = 3 while i * i <= n : divCount = 0 # if i divides n, then start counting # of Odd divisors while (n % i == 0) : n //= i divCount = divCount + 1 result = result * divCount + 1 i = i + 2 # If n odd prime still remains then count it if (n > 2) : result = result * 2 return result def politeness( n) : return countOddPrimeFactors(n) - 1; # Driver program to test above functionn = 90print ("Politeness of ", n, " = ", politeness(n))n = 15print ("Politeness of ", n, " = ", politeness(n)) # This code is contributed by Nikita Tiwari.
// C# program to find politeness of a number.using System; public class GFG { // A function to count all odd prime // factors of a given number n static int countOddPrimeFactors(int n) { int result = 1; // Eliminate all even prime factor // of number of n while (n % 2 == 0) n /= 2; // n must be odd at this point, so // iterate for only odd numbers // till sqrt(n) for (int i = 3; i * i <= n; i += 2) { int divCount = 0; // if i divides n, then start // counting of Odd divisors while (n % i == 0) { n /= i; ++divCount; } result *= divCount + 1; } // If n odd prime still remains // then count it if (n > 2) result *= 2; return result; } static int politeness(int n) { return countOddPrimeFactors(n) - 1; } // Driver code public static void Main() { int n = 90; Console.WriteLine("Politeness of " + n + " = " + politeness(n)); n = 15; Console.WriteLine("Politeness of " + n + " = " + politeness(n)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find// politeness of number // A function to count all// odd prime factors of a// given number nfunction countOddPrimeFactors($n){ $result = 1; // Eliminate all even prime // factor of number of n while($n % 2 == 0) $n /= 2; // n must be odd at this // point, so iterate for only // odd numbers till sqrt(n) for ($i = 3; $i * $i <= $n; $i += 2) { $divCount = 0; // if i divides n, then // start counting of // Odd divisors while($n % $i == 0) { $n /= $i; ++$divCount; } $result *= $divCount + 1; } // If n odd prime still // remains then count it if ($n > 2) $result *= 2; return $result;} function politeness($n){ return countOddPrimeFactors($n) - 1;} // Driver Code $n = 90; echo "Politeness of " , $n , " = " , politeness($n), "\n"; $n = 15; echo "Politeness of " , $n , " = " , politeness($n) ,"\n"; // This code is contributed by nitin mittal.?>
<script>// JavaScript program for the above approach // A function to count all odd prime // factors of a given number n function countOddPrimeFactors(n) { let result = 1; // Eliminate all even prime factor // of number of n while (n % 2 == 0) n /= 2; // n must be odd at this point, so // iterate for only odd numbers // till sqrt(n) for (let i = 3; i * i <= n; i += 2) { let divCount = 0; // if i divides n, then start // counting of Odd divisors while (n % i == 0) { n /= i; ++divCount; } result *= divCount + 1; } // If n odd prime still remains // then count it if (n > 2) result *= 2; return result; } function politeness(n) { return countOddPrimeFactors(n) - 1; } // Driver Code let n = 90; document.write("Politeness of " + n + " = " + politeness(n) + "<br />"); n = 15; document.write("Politeness of " + n + " = " + politeness(n)); // This code is contributed by splevel62.</script>
Output:
Politeness of 90 = 5
Politeness of 15 = 3
Time complexity: O(sqrt(n)) Auxiliary space: O(1)Reference: Wikipedia
Another Efficient approach:
Calculate if an AP can be generated for the given length domain [2, sqrt(2*n)]. The reason to calculate for length till sqrt(2*n) is-
max length will be for the AP 1, 2, 3...
Length for this AP is -
n= ( len * (len+1) ) / 2
len2 + len - (2*n) =0
so len≈sqrt(2*n)
so we can check for each len from 1 to sqrt(2*n) ,if AP can be generated with this len. The formula to get the first term of the AP is –
n= ( len/2) * ( (2*A1) + len-1 )
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program for the above approach#include <iostream>#include <math.h>using namespace std; // Function to find politenessint politness(int n){ int count = 0; // sqrt(2*n) as max length // will be when the sum starts // from 1 // which follows the equation n^2 - n - (2*sum) = 0 for (int i = 2; i <= sqrt(2 * n); i++) { int a; if ((2 * n) % i != 0) continue; a = 2 * n; a /= i; a -= (i - 1); if (a % 2 != 0) continue; a /= 2; if (a > 0) { count++; } } return count;} // Driver program to test above functionint main(){ int n = 90; cout << "Politness of " << n << " = " << politness(n) << "\n"; n = 15; cout << "Politness of " << n << " = " << politness(n) << "\n"; return 0;} // This code is contributed by Prajjwal Chittori
// Java program for the above approachimport java.lang.Math;public class Main { // Function to find politeness static int politness(int n) { int count = 0; // sqrt(2*n) as max length // will be when the sum // starts from 1 // which follows the // equation n^2 - n - (2*sum) = 0 for (int i = 2; i <= Math.sqrt(2 * n); i++) { int a; if ((2 * n) % i != 0) continue; a = 2 * n; a /= i; a -= (i - 1); if (a % 2 != 0) continue; a /= 2; if (a > 0) { count++; } } return count; } // Driver Code public static void main(String[] args) { int n = 90; System.out.println("Politness of " + n + " = " + politness(n)); n = 15; System.out.println("Politness of " + n + " = " + politness(n)); }} // This code is contributed by Prajjwal Chittori
# python program for the above approachimport math # Function to find politenessdef politness(n): count = 0 # sqrt(2*n) as max length will be # when the sum starts from 1 # which follows the equation # n^2 - n - (2*sum) = 0 for i in range(2, int(math.sqrt(2 * n)) + 1): if ((2 * n) % i != 0): continue a = 2 * n a = a // i a = a - (i - 1) if (a % 2 != 0): continue a //= 2 if (a > 0): count = count + 1 return count # Driver program to test above functionn = 90print ("Politness of ", n, " = ", politness(n))n = 15print ("Politness of ", n, " = ", politness(n)) # This code is contributed by Prajjwal Chittori
// C# program for the above approachusing System;public class GFG { // Function to find politeness static int politness(int n) { int count = 0; // sqrt(2*n) as max length // will be when the sum // starts from 1 // which follows the // equation n^2 - n - (2*sum) = 0 for (int i = 2; i <= Math.Sqrt(2 * n); i++) { int a; if ((2 * n) % i != 0) continue; a = 2 * n; a /= i; a -= (i - 1); if (a % 2 != 0) continue; a /= 2; if (a > 0) { count++; } } return count; } // Driver Code public static void Main(String[] args) { int n = 90; Console.WriteLine("Politness of " + n + " = " + politness(n)); n = 15; Console.WriteLine("Politness of " + n + " = " + politness(n)); }} // This code is contributed by gauravrajput1
<script> // JavaScript program for the above approach // Function to find politeness function politness(n) { let count = 0; // sqrt(2*n) as max length // will be when the sum // starts from 1 // which follows the // equation n^2 - n - (2*sum) = 0 for (let i = 2; i <= Math.sqrt(2 * n); i++) { let a; if ((2 * n) % i != 0) continue; a = 2 * n; a = Math.floor(a / i); a -= (i - 1); if (a % 2 != 0) continue; a = Math.floor(a / 2); if (a > 0) { count++; } } return count; } // Driver Code let n = 90; document.write("Politness of " + n + " = " + politness(n) + "<br/>"); n = 15; document.write("Politness of " + n + " = " + politness(n)); </script>
Politness of 90 = 5
Politness of 15 = 3
Time complexity: O(sqrt(2*n)) ≈ O(sqrt(n))
Auxiliary space: O(1)
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.
nitin mittal
rahulojhaiit
pjdurden
splevel62
sanjoy_62
GauravRajput1
surindertarika1234
amartyaghoshgfg
surinderdawra388
prime-factor
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
Program for Decimal to Binary Conversion
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 220,
"s": 54,
"text": "Given an integer n. Find politeness of number n. The politeness of a number is defined as the number of ways it can be expressed as the sum of consecutive integers. "
},
{
"code": null,
"e": 230,
"s": 220,
"text": "Examples:"
},
{
"code": null,
"e": 499,
"s": 230,
"text": "Input: n = 15\nOutput: 3\nExplanation:\nThere are only three ways to express\n15 as sum of consecutive integers i.e.,\n15 = 1 + 2 + 3 + 4 + 5\n15 = 4 + 5 + 6\n15 = 7 + 8\nHence answer is 3\n\nInput: n = 9;\nOutput: 2\nThere are two ways of representation:\n9 = 2 + 3 + 4\n9 = 4 + 5"
},
{
"code": null,
"e": 515,
"s": 499,
"text": "Naive approach:"
},
{
"code": null,
"e": 702,
"s": 515,
"text": "Run a loop one inside another and find the sum of every consecutive integer up to n. The time complexity of this approach will be O(n2) which will not be sufficient for large value of n."
},
{
"code": null,
"e": 722,
"s": 702,
"text": "Efficient Approach:"
},
{
"code": null,
"e": 2181,
"s": 722,
"text": "Use factorization. We factorize the number n and count the number of odd factors. A total number of odd factors (except 1) is equal to the politeness of the number. Refer this for proof of this fact. In general, if a number can be represented as ap * bq * cr ... where a, b, c, ... are prime factors of n. If a = 2 (even) then discard it and count total number of odd factors which can be written as [(q + 1) * (r + 1) * ...] – 1 (Here 1 is subtracted because single term in representation is not allowed). How does the above formula work? The fact is if a number is expressed as ap * bq * cr ... where a, b, c, ... are prime factors of n, then a number of divisors is (p+1)*(q+1)*(r+1) ...... To simplify, let there be one factor, and the number is expressed as ap. Divisors are 1, a, a2, .... ap. The count of divisors is p+1. Now let us take a slightly more complicated case apbp. The divisors are : 1, a, a2, .... ap b, ba, ba2, .... bap b2, b2a, b2a2, .... b2ap ................ ................ bq, bqa, bqa2, .... bqapThe count of the above terms is (p+1)*(q+1). Similarly, we can prove for more prime factors.Illustration : For n = 90, decomposition of prime factors will be as follows:- => 90 = 2 * 32 * 51. The power of odd prime factors 3, 5 are 2 and 1 respectively. Apply above formula as: (2 + 1) * (1 + 1) -1 = 5. Hence 5 will be the answer. We can crosscheck it. All odd factors are 3, 5, 9, 15 and 45.Below is the program of the above steps:"
},
{
"code": null,
"e": 2185,
"s": 2181,
"text": "C++"
},
{
"code": null,
"e": 2190,
"s": 2185,
"text": "Java"
},
{
"code": null,
"e": 2198,
"s": 2190,
"text": "Python3"
},
{
"code": null,
"e": 2201,
"s": 2198,
"text": "C#"
},
{
"code": null,
"e": 2205,
"s": 2201,
"text": "PHP"
},
{
"code": null,
"e": 2216,
"s": 2205,
"text": "Javascript"
},
{
"code": "// C+ program to find politeness of number#include <iostream>using namespace std; // A function to count all odd prime factors// of a given number nint countOddPrimeFactors(int n){ int result = 1; // Eliminate all even prime // factor of number of n while (n % 2 == 0) n /= 2; // n must be odd at this point, // so iterate for only // odd numbers till sqrt(n) for (int i = 3; i * i <= n; i += 2) { int divCount = 0; // if i divides n, then start counting of // Odd divisors while (n % i == 0) { n /= i; ++divCount; } result *= divCount + 1; } // If n odd prime still remains then count it if (n > 2) result *= 2; return result;} int politeness(int n){ return countOddPrimeFactors(n) - 1;} // Driver program to test above functionint main(){ int n = 90; cout << \"Politeness of \" << n << \" = \" << politeness(n) << \"\\n\"; n = 15; cout << \"Politeness of \" << n << \" = \" << politeness(n) << \"\\n\"; return 0;}",
"e": 3273,
"s": 2216,
"text": null
},
{
"code": "// Java program to find politeness of a number public class Politeness { // A function to count all odd prime factors // of a given number n static int countOddPrimeFactors(int n) { int result = 1; // Eliminate all even prime // factor of number of n while (n % 2 == 0) n /= 2; // n must be odd at this point, so iterate // for only odd numbers till sqrt(n) for (int i = 3; i * i <= n; i += 2) { int divCount = 0; // if i divides n, then start counting of // Odd divisors while (n % i == 0) { n /= i; ++divCount; } result *= divCount + 1; } // If n odd prime still remains then count it if (n > 2) result *= 2; return result; } static int politeness(int n) { return countOddPrimeFactors(n) - 1; } public static void main(String[] args) { int n = 90; System.out.println(\"Politeness of \" + n + \" = \" + politeness(n)); n = 15; System.out.println(\"Politeness of \" + n + \" = \" + politeness(n)); }} // This code is contributed by Saket Kumar",
"e": 4532,
"s": 3273,
"text": null
},
{
"code": "# Python program to find politeness of number # A function to count all odd prime factors# of a given number ndef countOddPrimeFactors(n) : result = 1; # Eliminate all even prime factor of # number of n while (n % 2 == 0) : n //= 2 # n must be odd at this point, so iterate # for only odd numbers till sqrt(n) i = 3 while i * i <= n : divCount = 0 # if i divides n, then start counting # of Odd divisors while (n % i == 0) : n //= i divCount = divCount + 1 result = result * divCount + 1 i = i + 2 # If n odd prime still remains then count it if (n > 2) : result = result * 2 return result def politeness( n) : return countOddPrimeFactors(n) - 1; # Driver program to test above functionn = 90print (\"Politeness of \", n, \" = \", politeness(n))n = 15print (\"Politeness of \", n, \" = \", politeness(n)) # This code is contributed by Nikita Tiwari.",
"e": 5519,
"s": 4532,
"text": null
},
{
"code": "// C# program to find politeness of a number.using System; public class GFG { // A function to count all odd prime // factors of a given number n static int countOddPrimeFactors(int n) { int result = 1; // Eliminate all even prime factor // of number of n while (n % 2 == 0) n /= 2; // n must be odd at this point, so // iterate for only odd numbers // till sqrt(n) for (int i = 3; i * i <= n; i += 2) { int divCount = 0; // if i divides n, then start // counting of Odd divisors while (n % i == 0) { n /= i; ++divCount; } result *= divCount + 1; } // If n odd prime still remains // then count it if (n > 2) result *= 2; return result; } static int politeness(int n) { return countOddPrimeFactors(n) - 1; } // Driver code public static void Main() { int n = 90; Console.WriteLine(\"Politeness of \" + n + \" = \" + politeness(n)); n = 15; Console.WriteLine(\"Politeness of \" + n + \" = \" + politeness(n)); }} // This code is contributed by nitin mittal.",
"e": 6814,
"s": 5519,
"text": null
},
{
"code": "<?php// PHP program to find// politeness of number // A function to count all// odd prime factors of a// given number nfunction countOddPrimeFactors($n){ $result = 1; // Eliminate all even prime // factor of number of n while($n % 2 == 0) $n /= 2; // n must be odd at this // point, so iterate for only // odd numbers till sqrt(n) for ($i = 3; $i * $i <= $n; $i += 2) { $divCount = 0; // if i divides n, then // start counting of // Odd divisors while($n % $i == 0) { $n /= $i; ++$divCount; } $result *= $divCount + 1; } // If n odd prime still // remains then count it if ($n > 2) $result *= 2; return $result;} function politeness($n){ return countOddPrimeFactors($n) - 1;} // Driver Code $n = 90; echo \"Politeness of \" , $n , \" = \" , politeness($n), \"\\n\"; $n = 15; echo \"Politeness of \" , $n , \" = \" , politeness($n) ,\"\\n\"; // This code is contributed by nitin mittal.?>",
"e": 7876,
"s": 6814,
"text": null
},
{
"code": "<script>// JavaScript program for the above approach // A function to count all odd prime // factors of a given number n function countOddPrimeFactors(n) { let result = 1; // Eliminate all even prime factor // of number of n while (n % 2 == 0) n /= 2; // n must be odd at this point, so // iterate for only odd numbers // till sqrt(n) for (let i = 3; i * i <= n; i += 2) { let divCount = 0; // if i divides n, then start // counting of Odd divisors while (n % i == 0) { n /= i; ++divCount; } result *= divCount + 1; } // If n odd prime still remains // then count it if (n > 2) result *= 2; return result; } function politeness(n) { return countOddPrimeFactors(n) - 1; } // Driver Code let n = 90; document.write(\"Politeness of \" + n + \" = \" + politeness(n) + \"<br />\"); n = 15; document.write(\"Politeness of \" + n + \" = \" + politeness(n)); // This code is contributed by splevel62.</script>",
"e": 9104,
"s": 7876,
"text": null
},
{
"code": null,
"e": 9154,
"s": 9104,
"text": "Output:\nPoliteness of 90 = 5\nPoliteness of 15 = 3"
},
{
"code": null,
"e": 9224,
"s": 9154,
"text": "Time complexity: O(sqrt(n)) Auxiliary space: O(1)Reference: Wikipedia"
},
{
"code": null,
"e": 9252,
"s": 9224,
"text": "Another Efficient approach:"
},
{
"code": null,
"e": 9386,
"s": 9252,
"text": "Calculate if an AP can be generated for the given length domain [2, sqrt(2*n)]. The reason to calculate for length till sqrt(2*n) is-"
},
{
"code": null,
"e": 9427,
"s": 9386,
"text": "max length will be for the AP 1, 2, 3..."
},
{
"code": null,
"e": 9519,
"s": 9427,
"text": "Length for this AP is -\n\nn= ( len * (len+1) ) / 2\n\nlen2 + len - (2*n) =0\n\nso len≈sqrt(2*n) "
},
{
"code": null,
"e": 9656,
"s": 9519,
"text": "so we can check for each len from 1 to sqrt(2*n) ,if AP can be generated with this len. The formula to get the first term of the AP is –"
},
{
"code": null,
"e": 9689,
"s": 9656,
"text": "n= ( len/2) * ( (2*A1) + len-1 )"
},
{
"code": null,
"e": 9740,
"s": 9689,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 9744,
"s": 9740,
"text": "C++"
},
{
"code": null,
"e": 9749,
"s": 9744,
"text": "Java"
},
{
"code": null,
"e": 9757,
"s": 9749,
"text": "Python3"
},
{
"code": null,
"e": 9760,
"s": 9757,
"text": "C#"
},
{
"code": null,
"e": 9771,
"s": 9760,
"text": "Javascript"
},
{
"code": "// CPP program for the above approach#include <iostream>#include <math.h>using namespace std; // Function to find politenessint politness(int n){ int count = 0; // sqrt(2*n) as max length // will be when the sum starts // from 1 // which follows the equation n^2 - n - (2*sum) = 0 for (int i = 2; i <= sqrt(2 * n); i++) { int a; if ((2 * n) % i != 0) continue; a = 2 * n; a /= i; a -= (i - 1); if (a % 2 != 0) continue; a /= 2; if (a > 0) { count++; } } return count;} // Driver program to test above functionint main(){ int n = 90; cout << \"Politness of \" << n << \" = \" << politness(n) << \"\\n\"; n = 15; cout << \"Politness of \" << n << \" = \" << politness(n) << \"\\n\"; return 0;} // This code is contributed by Prajjwal Chittori",
"e": 10653,
"s": 9771,
"text": null
},
{
"code": "// Java program for the above approachimport java.lang.Math;public class Main { // Function to find politeness static int politness(int n) { int count = 0; // sqrt(2*n) as max length // will be when the sum // starts from 1 // which follows the // equation n^2 - n - (2*sum) = 0 for (int i = 2; i <= Math.sqrt(2 * n); i++) { int a; if ((2 * n) % i != 0) continue; a = 2 * n; a /= i; a -= (i - 1); if (a % 2 != 0) continue; a /= 2; if (a > 0) { count++; } } return count; } // Driver Code public static void main(String[] args) { int n = 90; System.out.println(\"Politness of \" + n + \" = \" + politness(n)); n = 15; System.out.println(\"Politness of \" + n + \" = \" + politness(n)); }} // This code is contributed by Prajjwal Chittori",
"e": 11545,
"s": 10653,
"text": null
},
{
"code": "# python program for the above approachimport math # Function to find politenessdef politness(n): count = 0 # sqrt(2*n) as max length will be # when the sum starts from 1 # which follows the equation # n^2 - n - (2*sum) = 0 for i in range(2, int(math.sqrt(2 * n)) + 1): if ((2 * n) % i != 0): continue a = 2 * n a = a // i a = a - (i - 1) if (a % 2 != 0): continue a //= 2 if (a > 0): count = count + 1 return count # Driver program to test above functionn = 90print (\"Politness of \", n, \" = \", politness(n))n = 15print (\"Politness of \", n, \" = \", politness(n)) # This code is contributed by Prajjwal Chittori",
"e": 12264,
"s": 11545,
"text": null
},
{
"code": "// C# program for the above approachusing System;public class GFG { // Function to find politeness static int politness(int n) { int count = 0; // sqrt(2*n) as max length // will be when the sum // starts from 1 // which follows the // equation n^2 - n - (2*sum) = 0 for (int i = 2; i <= Math.Sqrt(2 * n); i++) { int a; if ((2 * n) % i != 0) continue; a = 2 * n; a /= i; a -= (i - 1); if (a % 2 != 0) continue; a /= 2; if (a > 0) { count++; } } return count; } // Driver Code public static void Main(String[] args) { int n = 90; Console.WriteLine(\"Politness of \" + n + \" = \" + politness(n)); n = 15; Console.WriteLine(\"Politness of \" + n + \" = \" + politness(n)); }} // This code is contributed by gauravrajput1",
"e": 13138,
"s": 12264,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find politeness function politness(n) { let count = 0; // sqrt(2*n) as max length // will be when the sum // starts from 1 // which follows the // equation n^2 - n - (2*sum) = 0 for (let i = 2; i <= Math.sqrt(2 * n); i++) { let a; if ((2 * n) % i != 0) continue; a = 2 * n; a = Math.floor(a / i); a -= (i - 1); if (a % 2 != 0) continue; a = Math.floor(a / 2); if (a > 0) { count++; } } return count; } // Driver Code let n = 90; document.write(\"Politness of \" + n + \" = \" + politness(n) + \"<br/>\"); n = 15; document.write(\"Politness of \" + n + \" = \" + politness(n)); </script>",
"e": 13941,
"s": 13138,
"text": null
},
{
"code": null,
"e": 13981,
"s": 13941,
"text": "Politness of 90 = 5\nPolitness of 15 = 3"
},
{
"code": null,
"e": 14143,
"s": 13981,
"text": " Time complexity: O(sqrt(2*n)) ≈ O(sqrt(n)) "
},
{
"code": null,
"e": 14316,
"s": 14143,
"text": " Auxiliary space: O(1) "
},
{
"code": null,
"e": 14738,
"s": 14316,
"text": "This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 14751,
"s": 14738,
"text": "nitin mittal"
},
{
"code": null,
"e": 14764,
"s": 14751,
"text": "rahulojhaiit"
},
{
"code": null,
"e": 14773,
"s": 14764,
"text": "pjdurden"
},
{
"code": null,
"e": 14783,
"s": 14773,
"text": "splevel62"
},
{
"code": null,
"e": 14793,
"s": 14783,
"text": "sanjoy_62"
},
{
"code": null,
"e": 14807,
"s": 14793,
"text": "GauravRajput1"
},
{
"code": null,
"e": 14826,
"s": 14807,
"text": "surindertarika1234"
},
{
"code": null,
"e": 14842,
"s": 14826,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 14859,
"s": 14842,
"text": "surinderdawra388"
},
{
"code": null,
"e": 14872,
"s": 14859,
"text": "prime-factor"
},
{
"code": null,
"e": 14885,
"s": 14872,
"text": "Mathematical"
},
{
"code": null,
"e": 14898,
"s": 14885,
"text": "Mathematical"
},
{
"code": null,
"e": 14996,
"s": 14898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15020,
"s": 14996,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 15041,
"s": 15020,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 15055,
"s": 15041,
"text": "Prime Numbers"
},
{
"code": null,
"e": 15108,
"s": 15055,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 15145,
"s": 15108,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 15177,
"s": 15145,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 15204,
"s": 15177,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 15247,
"s": 15204,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 15288,
"s": 15247,
"text": "Program for Decimal to Binary Conversion"
}
] |
How to set Text alignment in HTML?
|
To set text alignment in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property text-align for the center, left and right alignment. HTML5 do not support the align attribute of the <p> tag, so the CSS style is used to set text alignment.
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to set text alignment in HTML
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Document</title>
</head>
<body>
<h1>Tutorial</h1>
<p style="text-align:center;">Learn for free</p>
</body>
</html>
|
[
{
"code": null,
"e": 1405,
"s": 1062,
"text": "To set text alignment in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property text-align for the center, left and right alignment. HTML5 do not support the align attribute of the <p> tag, so the CSS style is used to set text alignment."
},
{
"code": null,
"e": 1567,
"s": 1405,
"text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet."
},
{
"code": null,
"e": 1635,
"s": 1567,
"text": "You can try to run the following code to set text alignment in HTML"
},
{
"code": null,
"e": 1645,
"s": 1635,
"text": "Live Demo"
},
{
"code": null,
"e": 1833,
"s": 1645,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Document</title>\n </head>\n\n <body>\n <h1>Tutorial</h1>\n <p style=\"text-align:center;\">Learn for free</p>\n </body>\n</html>"
}
] |
How to add new contacts in Android App?
|
This example demonstrate about How to add new contacts in Android App.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :layout_margin= "16dp"
android :orientation= "vertical"
tools :context= ".MainActivity" >
<EditText
android :id= "@+id/etContactName"
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :hint= "Contact name"
android :inputType= "text" />
<EditText
android :id= "@+id/etContactNumber"
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :hint= "Contact number"
android :inputType= "number" />
<Button
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :onClick= "addContact"
android :text= "ADD" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity
package app.tutorialspoint.com.sample ;
import android.app.Activity ;
import android.content.Intent ;
import android.os.Bundle ;
import android.provider.ContactsContract ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.EditText ;
import android.widget.Toast ;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
}
public void addContact (View view) {
EditText etContactName = findViewById(R.id. etContactName ) ;
EditText etContactNumber = findViewById(R.id. etContactNumber ) ;
String name = etContactName.getText().toString() ;
String phone = etContactNumber.getText().toString() ;
Intent contactIntent = new Intent(ContactsContract.Intents.Insert. ACTION ) ;
contactIntent.setType(ContactsContract.RawContacts. CONTENT_TYPE ) ;
contactIntent
.putExtra(ContactsContract.Intents.Insert. NAME , name)
.putExtra(ContactsContract.Intents.Insert. PHONE , phone) ;
startActivityForResult(contactIntent , 1 ) ;
}
@Override
protected void onActivityResult ( int requestCode , int resultCode , Intent intent) {
super .onActivityResult(requestCode , resultCode , intent) ;
if (requestCode == 1 ) {
if (resultCode == Activity. RESULT_OK ) {
Toast. makeText ( this, "Added Contact" , Toast. LENGTH_SHORT ).show() ;
}
if (resultCode == Activity. RESULT_CANCELED ) {
Toast. makeText ( this, "Cancelled Added Contact" ,
Toast. LENGTH_SHORT ).show() ;
}
}
}
}
Step 6 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package= "app.tutorialspoint.com.sample" >
<uses-permission android :name= "android.permission.CALL_PHONE" />
<application
android :allowBackup= "true"
android :icon= "@mipmap/ic_launcher"
android :label= "@string/app_name"
android :roundIcon= "@mipmap/ic_launcher_round"
android :supportsRtl= "true"
android :theme= "@style/AppTheme" >
<activity android :name= ".MainActivity" >
<intent-filter>
<action android :name= "android.intent.action.MAIN" />
<category android :name= "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android :name= ".DeviceAdmin"
android :description= "@string/app_description"
android :label= "@string/app_name"
android :permission= "android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android :name= "android.app.device_admin"
android :resource= "@xml/policies" />
<intent-filter>
<action android :name= "android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "This example demonstrate about How to add new contacts in Android App."
},
{
"code": null,
"e": 1262,
"s": 1133,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1326,
"s": 1262,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml"
},
{
"code": null,
"e": 2305,
"s": 1326,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<LinearLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n android :orientation= \"vertical\"\n tools :context= \".MainActivity\" >\n <EditText\n android :id= \"@+id/etContactName\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :hint= \"Contact name\"\n android :inputType= \"text\" />\n <EditText\n android :id= \"@+id/etContactNumber\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :hint= \"Contact number\"\n android :inputType= \"number\" />\n <Button\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :onClick= \"addContact\"\n android :text= \"ADD\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2357,
"s": 2305,
"text": "Step 3 − Add the following code to src/MainActivity"
},
{
"code": null,
"e": 4088,
"s": 2357,
"text": "package app.tutorialspoint.com.sample ;\nimport android.app.Activity ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.provider.ContactsContract ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.EditText ;\nimport android.widget.Toast ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void addContact (View view) {\n EditText etContactName = findViewById(R.id. etContactName ) ;\n EditText etContactNumber = findViewById(R.id. etContactNumber ) ;\n String name = etContactName.getText().toString() ;\n String phone = etContactNumber.getText().toString() ;\n Intent contactIntent = new Intent(ContactsContract.Intents.Insert. ACTION ) ;\n contactIntent.setType(ContactsContract.RawContacts. CONTENT_TYPE ) ;\n contactIntent\n .putExtra(ContactsContract.Intents.Insert. NAME , name)\n .putExtra(ContactsContract.Intents.Insert. PHONE , phone) ;\n startActivityForResult(contactIntent , 1 ) ;\n }\n @Override\n protected void onActivityResult ( int requestCode , int resultCode , Intent intent) {\n super .onActivityResult(requestCode , resultCode , intent) ;\n if (requestCode == 1 ) {\n if (resultCode == Activity. RESULT_OK ) {\n Toast. makeText ( this, \"Added Contact\" , Toast. LENGTH_SHORT ).show() ;\n }\n if (resultCode == Activity. RESULT_CANCELED ) {\n Toast. makeText ( this, \"Cancelled Added Contact\" ,\n Toast. LENGTH_SHORT ).show() ;\n }\n }\n }\n}"
},
{
"code": null,
"e": 4143,
"s": 4088,
"text": "Step 6 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5430,
"s": 4143,
"text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.CALL_PHONE\" />\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android :label= \"@string/app_name\"\n android :roundIcon= \"@mipmap/ic_launcher_round\"\n android :supportsRtl= \"true\"\n android :theme= \"@style/AppTheme\" >\n <activity android :name= \".MainActivity\" >\n <intent-filter>\n <action android :name= \"android.intent.action.MAIN\" />\n <category android :name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <receiver\n android :name= \".DeviceAdmin\"\n android :description= \"@string/app_description\"\n android :label= \"@string/app_name\"\n android :permission= \"android.permission.BIND_DEVICE_ADMIN\" >\n <meta-data\n android :name= \"android.app.device_admin\"\n android :resource= \"@xml/policies\" />\n <intent-filter>\n <action android :name= \"android.app.action.DEVICE_ADMIN_ENABLED\" />\n </intent-filter>\n </receiver>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5777,
"s": 5430,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
] |
How to set the background image for an element with JavaScript DOM?
|
To set the background image in JavaScript, use the backgroundImage property. It allows you to set the background image.
You can try to run the following code to learn how to set the background image with JavaScript −
Live Demo
<!DOCTYPE html>
<html>
<body>
<button onclick="display()">Click to Set background image</button>
<script>
function display() {
document.body.style.backgroundImage = "url('https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg')";
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "To set the background image in JavaScript, use the backgroundImage property. It allows you to set the background image."
},
{
"code": null,
"e": 1279,
"s": 1182,
"text": "You can try to run the following code to learn how to set the background image with JavaScript −"
},
{
"code": null,
"e": 1289,
"s": 1279,
"text": "Live Demo"
},
{
"code": null,
"e": 1610,
"s": 1289,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <button onclick=\"display()\">Click to Set background image</button>\n <script>\n function display() {\n document.body.style.backgroundImage = \"url('https://www.tutorialspoint.com/html5/images/html5-mini-logo.jpg')\";\n }\n </script>\n </body>\n</html>"
}
] |
Why do we need a wrapper class in Java?
|
A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc). In other words, wrapper classes provide a way to use primitive data types
(int, char, short, byte, etc) as objects. These wrapper classes come under java.util package.
Wrapper Class will convert primitive data types into objects. The objects are necessary if we wish to modify the arguments passed into the method (because primitive types are passed by value).
The classes in java.util package handles only objects and hence wrapper classes help in this case also.
Data
structures in the Collection framework such as ArrayList and Vector store only the objects (reference types) and not the primitive types.
The object is needed to support synchronization in multithreading.
Autoboxing is used to convert primitive data types into corresponding objects.
Live Demo
public class AutoBoxingTest {
public static void main(String args[]) {
int num = 10; // int primitive
Integer obj = Integer.valueOf(num); // creating a wrapper class object
System.out.println(num + " " + obj);
}
}
10 10
Unboxing is used to convert the Wrapper class object into corresponding primitive data types.
Live Demo
public class UnboxingTest {
public static void main(String args[]) {
Integer obj = new Integer(10); // Creating Wrapper class object
int num = obj.intValue(); // Converting the wrapper object to primitive datatype
System.out.println(num + " " + obj);
}
}
10 10
|
[
{
"code": null,
"e": 1328,
"s": 1062,
"text": "A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc). In other words, wrapper classes provide a way to use primitive data types\n(int, char, short, byte, etc) as objects. These wrapper classes come under java.util package."
},
{
"code": null,
"e": 1521,
"s": 1328,
"text": "Wrapper Class will convert primitive data types into objects. The objects are necessary if we wish to modify the arguments passed into the method (because primitive types are passed by value)."
},
{
"code": null,
"e": 1625,
"s": 1521,
"text": "The classes in java.util package handles only objects and hence wrapper classes help in this case also."
},
{
"code": null,
"e": 1768,
"s": 1625,
"text": "Data\nstructures in the Collection framework such as ArrayList and Vector store only the objects (reference types) and not the primitive types."
},
{
"code": null,
"e": 1835,
"s": 1768,
"text": "The object is needed to support synchronization in multithreading."
},
{
"code": null,
"e": 1914,
"s": 1835,
"text": "Autoboxing is used to convert primitive data types into corresponding objects."
},
{
"code": null,
"e": 1924,
"s": 1914,
"text": "Live Demo"
},
{
"code": null,
"e": 2162,
"s": 1924,
"text": "public class AutoBoxingTest {\n public static void main(String args[]) {\n int num = 10; // int primitive\n Integer obj = Integer.valueOf(num); // creating a wrapper class object\n System.out.println(num + \" \" + obj);\n }\n}"
},
{
"code": null,
"e": 2168,
"s": 2162,
"text": "10 10"
},
{
"code": null,
"e": 2262,
"s": 2168,
"text": "Unboxing is used to convert the Wrapper class object into corresponding primitive data types."
},
{
"code": null,
"e": 2272,
"s": 2262,
"text": "Live Demo"
},
{
"code": null,
"e": 2551,
"s": 2272,
"text": "public class UnboxingTest {\n public static void main(String args[]) {\n Integer obj = new Integer(10); // Creating Wrapper class object\n int num = obj.intValue(); // Converting the wrapper object to primitive datatype\n System.out.println(num + \" \" + obj);\n }\n}"
},
{
"code": null,
"e": 2557,
"s": 2551,
"text": "10 10"
}
] |
Display AM/PM time marker with SimpleDateFormat(“a”) in Java
|
You can display AM/PM time marker easily in Java using SimpleDateFormat(“a”).
Firstly, to work with SimpleDateFormat class in Java, import the following package.
import java.text.SimpleDateFormat;
Now, set the format with SimpleDateFormat(“a”) to display AM/PM marker −
Format f = new SimpleDateFormat(”a”);
Now, get the marker in a string −
String strMarker = f.format(new Date());
The following is an example −
Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
public static void main(String[] args) throws Exception {
// displaying current date and time
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s");
System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
// displaying hour
Format f = new SimpleDateFormat("H");
String strHour = f.format(new Date());
System.out.println("Current Hour = "+strHour);
// displaying minutes
f = new SimpleDateFormat("mm");
String strMinute = f.format(new Date());
System.out.println("Current Minutes = "+strMinute);
// displaying seconds in two-digits
f = new SimpleDateFormat("ss");
String strSeconds = f.format(new Date());
System.out.println("Current Seconds = "+strSeconds);
// displaying AM/ PM
f = new SimpleDateFormat("a");
String strMarker = f.format(new Date());
System.out.println("Current AM/PM Marker = "+strMarker);
}
}
Today's date = 26/November/2018 08:08:52
Current Hour = 8
Current Minutes = 08
Current Seconds = 52
Current AM/PM Marker = AM
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "You can display AM/PM time marker easily in Java using SimpleDateFormat(“a”)."
},
{
"code": null,
"e": 1224,
"s": 1140,
"text": "Firstly, to work with SimpleDateFormat class in Java, import the following package."
},
{
"code": null,
"e": 1259,
"s": 1224,
"text": "import java.text.SimpleDateFormat;"
},
{
"code": null,
"e": 1332,
"s": 1259,
"text": "Now, set the format with SimpleDateFormat(“a”) to display AM/PM marker −"
},
{
"code": null,
"e": 1370,
"s": 1332,
"text": "Format f = new SimpleDateFormat(”a”);"
},
{
"code": null,
"e": 1404,
"s": 1370,
"text": "Now, get the marker in a string −"
},
{
"code": null,
"e": 1445,
"s": 1404,
"text": "String strMarker = f.format(new Date());"
},
{
"code": null,
"e": 1475,
"s": 1445,
"text": "The following is an example −"
},
{
"code": null,
"e": 1486,
"s": 1475,
"text": " Live Demo"
},
{
"code": null,
"e": 2634,
"s": 1486,
"text": "import java.text.Format;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n // displaying current date and time\n Calendar cal = Calendar.getInstance();\n SimpleDateFormat simpleformat = new SimpleDateFormat(\"dd/MMMM/yyyy hh:mm:s\");\n System.out.println(\"Today's date = \"+simpleformat.format(cal.getTime()));\n // displaying hour\n Format f = new SimpleDateFormat(\"H\");\n String strHour = f.format(new Date());\n System.out.println(\"Current Hour = \"+strHour);\n // displaying minutes\n f = new SimpleDateFormat(\"mm\");\n String strMinute = f.format(new Date());\n System.out.println(\"Current Minutes = \"+strMinute);\n // displaying seconds in two-digits\n f = new SimpleDateFormat(\"ss\");\n String strSeconds = f.format(new Date());\n System.out.println(\"Current Seconds = \"+strSeconds);\n // displaying AM/ PM\n f = new SimpleDateFormat(\"a\");\n String strMarker = f.format(new Date());\n System.out.println(\"Current AM/PM Marker = \"+strMarker);\n }\n}"
},
{
"code": null,
"e": 2760,
"s": 2634,
"text": "Today's date = 26/November/2018 08:08:52\nCurrent Hour = 8\nCurrent Minutes = 08\nCurrent Seconds = 52\nCurrent AM/PM Marker = AM"
}
] |
Find next greater number with same set of digits - GeeksforGeeks
|
14 Jan, 2022
Given a number n, find the smallest number that has same set of digits as n and is greater than n. If n is the greatest possible number with its set of digits, then print “not possible”.
Examples: For simplicity of implementation, we have considered input number as a string.
Input: n = "218765"
Output: "251678"
Input: n = "1234"
Output: "1243"
Input: n = "4321"
Output: "Not Possible"
Input: n = "534976"
Output: "536479"
Following are few observations about the next greater number. 1) If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321. 2) If all digits are sorted in ascending order, then we need to swap last two digits. For example, 1234. 3) For other cases, we need to process the number from rightmost side (why? because we need to find the smallest of all greater numbers)
You can now try developing an algorithm yourself. Following is the algorithm for finding the next greater number. I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.
II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976′′, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.
III) Swap the above found two digits, we get 536974 in above example.
IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.
Following are the implementation of above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find the smallest number which greater than a given number// and has same set of digits as given number#include <iostream>#include <cstring>#include <algorithm>using namespace std; // Utility function to swap two digitsvoid swap(char *a, char *b){ char temp = *a; *a = *b; *b = temp;} // Given a number as a char array number[], this function finds the// next greater number. It modifies the same array to store the resultvoid findNext(char number[], int n){ int i, j; // I) Start from the right most digit and find the first digit that is // smaller than the digit next to it. for (i = n-1; i > 0; i--) if (number[i] > number[i-1]) break; // If no such digit is found, then all digits are in descending order // means there cannot be a greater number with same set of digits if (i==0) { cout << "Next number is not possible"; return; } // II) Find the smallest digit on right side of (i-1)'th digit that is // greater than number[i-1] int x = number[i-1], smallest = i; for (j = i+1; j < n; j++) if (number[j] > x && number[j] < number[smallest]) smallest = j; // III) Swap the above found smallest digit with number[i-1] swap(&number[smallest], &number[i-1]); // IV) Sort the digits after (i-1) in ascending order sort(number + i, number + n); cout << "Next number with same set of digits is " << number; return;} // Driver program to test above functionint main(){ char digits[] = "534976"; int n = strlen(digits); findNext(digits, n); return 0;}
// Java program to find next greater// number with same set of digits.import java.util.Arrays; public class nextGreater{ // Utility function to swap two digit static void swap(char ar[], int i, int j) { char temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } // Given a number as a char array number[], // this function finds the next greater number. // It modifies the same array to store the result static void findNext(char ar[], int n) { int i; // I) Start from the right most digit // and find the first digit that is smaller // than the digit next to it. for (i = n - 1; i > 0; i--) { if (ar[i] > ar[i - 1]) { break; } } // If no such digit is found, then all // digits are in descending order means // there cannot be a greater number with // same set of digits if (i == 0) { System.out.println("Not possible"); } else { int x = ar[i - 1], min = i; // II) Find the smallest digit on right // side of (i-1)'th digit that is greater // than number[i-1] for (int j = i + 1; j < n; j++) { if (ar[j] > x && ar[j] < ar[min]) { min = j; } } // III) Swap the above found smallest // digit with number[i-1] swap(ar, i - 1, min); // IV) Sort the digits after (i-1) // in ascending order Arrays.sort(ar, i, n); System.out.print("Next number with same" + " set of digits is "); for (i = 0; i < n; i++) System.out.print(ar[i]); } } public static void main(String[] args) { char digits[] = { '5','3','4','9','7','6' }; int n = digits.length; findNext(digits, n); }}
# Python program to find the smallest number which# is greater than a given no. has same set of# digits as given number # Given number as int array, this function finds the# greatest number and returns the number as integerdef findNext(number,n): # Start from the right most digit and find the first # digit that is smaller than the digit next to it for i in range(n-1,0,-1): if number[i] > number[i-1]: break # If no such digit found,then all numbers are in # descending order, no greater number is possible if i == 1 and number[i] <= number[i-1]: print ("Next number not possible") return # Find the smallest digit on the right side of # (i-1)'th digit that is greater than number[i-1] x = number[i-1] smallest = i for j in range(i+1,n): if number[j] > x and number[j] < number[smallest]: smallest = j # Swapping the above found smallest digit with (i-1)'th number[smallest],number[i-1] = number[i-1], number[smallest] # X is the final number, in integer datatype x = 0 # Converting list upto i-1 into number for j in range(i): x = x * 10 + number[j] # Sort the digits after i-1 in ascending order number = sorted(number[i:]) # converting the remaining sorted digits into number for j in range(n-i): x = x * 10 + number[j] print ("Next number with set of digits is",x) # Driver Program to test above functiondigits = "534976" # converting into integer array,# number becomes [5,3,4,9,7,6]number = list(map(int ,digits))findNext(number, len(digits)) # This code is contributed by Harshit Agrawal
// C# program to find next greater// number with same set of digits.using System; public class nextGreater{ // Utility function to swap two digit static void swap(char []ar, int i, int j) { char temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } // Given a number as a char array number[], // this function finds the next greater number. // It modifies the same array to store the result static void findNext(char []ar, int n) { int i; // I) Start from the right most digit // and find the first digit that is smaller // than the digit next to it. for (i = n - 1; i > 0; i--) { if (ar[i] > ar[i - 1]) { break; } } // If no such digit is found, then all // digits are in descending order means // there cannot be a greater number with // same set of digits if (i == 0) { Console.WriteLine("Not possible"); } else { int x = ar[i - 1], min = i; // II) Find the smallest digit on right // side of (i-1)'th digit that is greater // than number[i-1] for (int j = i + 1; j < n; j++) { if (ar[j] > x && ar[j] < ar[min]) { min = j; } } // III) Swap the above found smallest // digit with number[i-1] swap(ar, i - 1, min); // IV) Sort the digits after (i-1) // in ascending order Array.Sort(ar, i, n-i); Console.Write("Next number with same" + " set of digits is "); for (i = 0; i < n; i++) Console.Write(ar[i]); } } // Driver code public static void Main(String[] args) { char []digits = { '5','3','4','9','7','6' }; int n = digits.Length; findNext(digits, n); }} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find the// smallest number which is greater// than a given no. has same set of// digits as given number // Given number as int array, this// function finds the greatest number// and returns the number as integerfunction findNext(number, n){ // Start from the right most digit // and find the first digit that is // smaller than the digit next to it for(var i = n - 1; i >= 0; i--) { if (number[i] > number[i - 1]) break; } // If no such digit found,then all // numbers are in descending order, // no greater number is possible if (i == 1 && number[i] <= number[i - 1]) { document.write("Next number not possible"); return; } // Find the smallest digit on the // right side of (i-1)'th digit // that is greater than number[i-1] let x = number[i - 1]; let smallest = i; for(let j = i + 1; j < n; j++) { if (number[j] > x && number[j] < number[smallest]) smallest = j; } // Swapping the above found smallest // digit with (i-1)'th let temp = number[smallest]; number[smallest] = number[i - 1]; number[i - 1] = temp; // X is the final number, in integer datatype x = 0 // Converting list upto i-1 into number for(let j = 0; j < i; j++) x = x * 10 + number[j]; // Sort the digits after i-1 in ascending order number = number.slice(i, number.length + 1); number.sort() // Converting the remaining sorted // digits into number for(let j = 0; j < n - i; j++) x = x * 10 + number[j]; document.write("Next number with " + "set of digits is " + x);} // Driver codelet digits = "534976" // Converting into integer array,// number becomes [5,3,4,9,7,6]let number = []for(let i = 0; i < digits.length; i++) number[i] = Number(digits[i]); findNext(number, digits.length); // This code is contributed by rohan07 </script>
Next number with same set of digits is 536479
Time Complexity: O(N*logN) Auxiliary Space: O(1)
The above implementation can be optimized in following ways. 1) We can use binary search in step II instead of linear search. 2) In step IV, instead of doing simple sort, we can apply some clever technique to do it in linear time. Hint: We know that all digits are linearly sorted in reverse order except one digit which was swapped.With above optimizations, we can say that the time complexity of this method is O(n).
Optimised Approach :
1. Here instead of sorting the digits after (i-1) index, we are reversing the digits as mentioned in the above optimisation point.2. As they will be in decreasing order so to find the smallest element possible from the right part we just reverse them thus reducing time complexity.
Below is the implementation of the above approach:
C++14
Python3
Javascript
#include <bits/stdc++.h>using namespace std; vector<int> nextPermutation(int n, vector<int> arr){ // If number of digits is 1 then just return the vector if (n == 1) return arr; // Start from the right most digit and find the first // digit that is // smaller than the digit next to it. int i = 0; for (i = n - 1; i > 0; i--) { if (arr[i] > arr[i - 1]) break; } // If there is a possibility of a next greater element if (i != 0) { // Find the smallest digit on right side of (i-1)'th // digit that is // greater than number[i-1] for (int j = n - 1; j >= i; j--) { if (arr[i - 1] < arr[j]) { // Swap the found smallest digit i.e. arr[j] // with arr[i-1] swap(arr[i - 1], arr[j]); break; } } } // Reverse the digits after (i-1) because the digits // after (i-1) are in decreasing order and thus we will // get the smallest element possible from these digits reverse(arr.begin() + i, arr.end()); // If i is 0 that means elements are in decreasing order // Therefore, no greater element possible then we just // return the lowest possible // order/element formed from these digits by just // reversing the vector return arr;} int main(){ int n = 6; vector<int> v{ 5,3,4,9,7,6 }; vector<int> res; res = nextPermutation(n, v); for (int i = 0; i < res.size(); i++) { cout << res[i] << " "; }}
# A python program to find the next greatest numberdef nextPermutation(arr): # find the length of the array n = len(arr) # start from the right most digit and find the first # digit that is smaller than the digit next to it. k = n - 2 while k >= 0: if arr[k] < arr[k + 1]: break k -= 1 # reverse the list if the digit that is smaller than the # digit next to it is not found. if k < 0: arr = arr[::-1] else: # find the first greatest element than arr[k] from the # end of the list for l in range(n - 1, k, -1): if arr[l] > arr[k]: break # swap the elements at arr[k] and arr[l arr[l], arr[k] = arr[k], arr[l] # reverse the list from k + 1 to the end to find the # most nearest greater number to the given input number arr[k + 1:] = reversed(arr[k + 1:]) return arr # Driver codearr = [5, 3, 4, 9, 7, 6]print(*nextPermutation(arr)) # This code is contributed by Manish Thapa
<script> function nextPermutation(n, arr){ // If number of digits is 1 then just return the vector if (n == 1) return arr; // Start from the right most digit and find the first // digit that is // smaller than the digit next to it. let i = 0; for (i = n - 1; i > 0; i--) { if (arr[i] > arr[i - 1]) break; } // If there is a possibility of a next greater element if (i != 0) { // Find the smallest digit on right side of (i-1)'th // digit that is // greater than number[i-1] for (let j = n - 1; j >= i; j--) { if (arr[i - 1] < arr[j]) { // Swap the found smallest digit i.e. arr[j] // with arr[i-1] let temp = arr[i - 1]; arr[i - 1] = arr[j]; arr[j] = temp; break; } } } // Reverse the digits after (i-1) because the digits // after (i-1) are in decreasing order and thus we will // get the smallest element possible from these digits arr = arr.slice(0,i).concat(arr.slice(i,arr.length).reverse()); // If i is 0 that means elements are in decreasing order // Therefore, no greater element possible then we just // return the lowest possible // order/element formed from these digits by just // reversing the vector return arr;} let v = [5,3,4,9,7,6];let n = 6;let res = nextPermutation(n, v);for (let i = 0; i < res.length; i++) { document.write(res[i] + " ")} // This code is contributed by avanitrachhadiya2155</script>
5 3 6 4 7 9
Time Complexity: O(N)Auxiliary Space: O(1)
This article is contributed by Rahul Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
yogesh135
29AjayKumar
ChrisFedun
rohan07
vishalkharwar
avanitrachhadiya2155
iammanish041
amartyaghoshgfg
Adobe
Amazon
FactSet
Hike
MakeMyTrip
Microsoft
Morgan Stanley
number-digits
Oxigen Wallet
permutation
Qualcomm
Samsung
Snapdeal
Vizury Interactive Solutions
Zillious
Arrays
Mathematical
Searching
Morgan Stanley
Amazon
Microsoft
Samsung
Snapdeal
FactSet
Hike
MakeMyTrip
Adobe
Qualcomm
Zillious
Oxigen Wallet
Vizury Interactive Solutions
Arrays
Searching
Mathematical
permutation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Linked List vs Array
Queue | Set 1 (Introduction and Array Implementation)
Find the Missing Number
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25518,
"s": 25490,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 25705,
"s": 25518,
"text": "Given a number n, find the smallest number that has same set of digits as n and is greater than n. If n is the greatest possible number with its set of digits, then print “not possible”."
},
{
"code": null,
"e": 25795,
"s": 25705,
"text": "Examples: For simplicity of implementation, we have considered input number as a string. "
},
{
"code": null,
"e": 25948,
"s": 25795,
"text": "Input: n = \"218765\"\nOutput: \"251678\"\n\nInput: n = \"1234\"\nOutput: \"1243\"\n\nInput: n = \"4321\"\nOutput: \"Not Possible\"\n\nInput: n = \"534976\"\nOutput: \"536479\""
},
{
"code": null,
"e": 26354,
"s": 25948,
"text": "Following are few observations about the next greater number. 1) If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321. 2) If all digits are sorted in ascending order, then we need to swap last two digits. For example, 1234. 3) For other cases, we need to process the number from rightmost side (why? because we need to find the smallest of all greater numbers)"
},
{
"code": null,
"e": 26773,
"s": 26354,
"text": "You can now try developing an algorithm yourself. Following is the algorithm for finding the next greater number. I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”."
},
{
"code": null,
"e": 26960,
"s": 26773,
"text": "II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976′′, the right side of 4 contains “976”. The smallest digit greater than 4 is 6."
},
{
"code": null,
"e": 27030,
"s": 26960,
"text": "III) Swap the above found two digits, we get 536974 in above example."
},
{
"code": null,
"e": 27271,
"s": 27030,
"text": "IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976."
},
{
"code": null,
"e": 27324,
"s": 27271,
"text": "Following are the implementation of above approach. "
},
{
"code": null,
"e": 27328,
"s": 27324,
"text": "C++"
},
{
"code": null,
"e": 27333,
"s": 27328,
"text": "Java"
},
{
"code": null,
"e": 27341,
"s": 27333,
"text": "Python3"
},
{
"code": null,
"e": 27344,
"s": 27341,
"text": "C#"
},
{
"code": null,
"e": 27355,
"s": 27344,
"text": "Javascript"
},
{
"code": "// C++ program to find the smallest number which greater than a given number// and has same set of digits as given number#include <iostream>#include <cstring>#include <algorithm>using namespace std; // Utility function to swap two digitsvoid swap(char *a, char *b){ char temp = *a; *a = *b; *b = temp;} // Given a number as a char array number[], this function finds the// next greater number. It modifies the same array to store the resultvoid findNext(char number[], int n){ int i, j; // I) Start from the right most digit and find the first digit that is // smaller than the digit next to it. for (i = n-1; i > 0; i--) if (number[i] > number[i-1]) break; // If no such digit is found, then all digits are in descending order // means there cannot be a greater number with same set of digits if (i==0) { cout << \"Next number is not possible\"; return; } // II) Find the smallest digit on right side of (i-1)'th digit that is // greater than number[i-1] int x = number[i-1], smallest = i; for (j = i+1; j < n; j++) if (number[j] > x && number[j] < number[smallest]) smallest = j; // III) Swap the above found smallest digit with number[i-1] swap(&number[smallest], &number[i-1]); // IV) Sort the digits after (i-1) in ascending order sort(number + i, number + n); cout << \"Next number with same set of digits is \" << number; return;} // Driver program to test above functionint main(){ char digits[] = \"534976\"; int n = strlen(digits); findNext(digits, n); return 0;}",
"e": 28958,
"s": 27355,
"text": null
},
{
"code": "// Java program to find next greater// number with same set of digits.import java.util.Arrays; public class nextGreater{ // Utility function to swap two digit static void swap(char ar[], int i, int j) { char temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } // Given a number as a char array number[], // this function finds the next greater number. // It modifies the same array to store the result static void findNext(char ar[], int n) { int i; // I) Start from the right most digit // and find the first digit that is smaller // than the digit next to it. for (i = n - 1; i > 0; i--) { if (ar[i] > ar[i - 1]) { break; } } // If no such digit is found, then all // digits are in descending order means // there cannot be a greater number with // same set of digits if (i == 0) { System.out.println(\"Not possible\"); } else { int x = ar[i - 1], min = i; // II) Find the smallest digit on right // side of (i-1)'th digit that is greater // than number[i-1] for (int j = i + 1; j < n; j++) { if (ar[j] > x && ar[j] < ar[min]) { min = j; } } // III) Swap the above found smallest // digit with number[i-1] swap(ar, i - 1, min); // IV) Sort the digits after (i-1) // in ascending order Arrays.sort(ar, i, n); System.out.print(\"Next number with same\" + \" set of digits is \"); for (i = 0; i < n; i++) System.out.print(ar[i]); } } public static void main(String[] args) { char digits[] = { '5','3','4','9','7','6' }; int n = digits.length; findNext(digits, n); }}",
"e": 30973,
"s": 28958,
"text": null
},
{
"code": "# Python program to find the smallest number which# is greater than a given no. has same set of# digits as given number # Given number as int array, this function finds the# greatest number and returns the number as integerdef findNext(number,n): # Start from the right most digit and find the first # digit that is smaller than the digit next to it for i in range(n-1,0,-1): if number[i] > number[i-1]: break # If no such digit found,then all numbers are in # descending order, no greater number is possible if i == 1 and number[i] <= number[i-1]: print (\"Next number not possible\") return # Find the smallest digit on the right side of # (i-1)'th digit that is greater than number[i-1] x = number[i-1] smallest = i for j in range(i+1,n): if number[j] > x and number[j] < number[smallest]: smallest = j # Swapping the above found smallest digit with (i-1)'th number[smallest],number[i-1] = number[i-1], number[smallest] # X is the final number, in integer datatype x = 0 # Converting list upto i-1 into number for j in range(i): x = x * 10 + number[j] # Sort the digits after i-1 in ascending order number = sorted(number[i:]) # converting the remaining sorted digits into number for j in range(n-i): x = x * 10 + number[j] print (\"Next number with set of digits is\",x) # Driver Program to test above functiondigits = \"534976\" # converting into integer array,# number becomes [5,3,4,9,7,6]number = list(map(int ,digits))findNext(number, len(digits)) # This code is contributed by Harshit Agrawal",
"e": 32697,
"s": 30973,
"text": null
},
{
"code": "// C# program to find next greater// number with same set of digits.using System; public class nextGreater{ // Utility function to swap two digit static void swap(char []ar, int i, int j) { char temp = ar[i]; ar[i] = ar[j]; ar[j] = temp; } // Given a number as a char array number[], // this function finds the next greater number. // It modifies the same array to store the result static void findNext(char []ar, int n) { int i; // I) Start from the right most digit // and find the first digit that is smaller // than the digit next to it. for (i = n - 1; i > 0; i--) { if (ar[i] > ar[i - 1]) { break; } } // If no such digit is found, then all // digits are in descending order means // there cannot be a greater number with // same set of digits if (i == 0) { Console.WriteLine(\"Not possible\"); } else { int x = ar[i - 1], min = i; // II) Find the smallest digit on right // side of (i-1)'th digit that is greater // than number[i-1] for (int j = i + 1; j < n; j++) { if (ar[j] > x && ar[j] < ar[min]) { min = j; } } // III) Swap the above found smallest // digit with number[i-1] swap(ar, i - 1, min); // IV) Sort the digits after (i-1) // in ascending order Array.Sort(ar, i, n-i); Console.Write(\"Next number with same\" + \" set of digits is \"); for (i = 0; i < n; i++) Console.Write(ar[i]); } } // Driver code public static void Main(String[] args) { char []digits = { '5','3','4','9','7','6' }; int n = digits.Length; findNext(digits, n); }} // This code is contributed by 29AjayKumar",
"e": 34785,
"s": 32697,
"text": null
},
{
"code": "<script> // JavaScript program to find the// smallest number which is greater// than a given no. has same set of// digits as given number // Given number as int array, this// function finds the greatest number// and returns the number as integerfunction findNext(number, n){ // Start from the right most digit // and find the first digit that is // smaller than the digit next to it for(var i = n - 1; i >= 0; i--) { if (number[i] > number[i - 1]) break; } // If no such digit found,then all // numbers are in descending order, // no greater number is possible if (i == 1 && number[i] <= number[i - 1]) { document.write(\"Next number not possible\"); return; } // Find the smallest digit on the // right side of (i-1)'th digit // that is greater than number[i-1] let x = number[i - 1]; let smallest = i; for(let j = i + 1; j < n; j++) { if (number[j] > x && number[j] < number[smallest]) smallest = j; } // Swapping the above found smallest // digit with (i-1)'th let temp = number[smallest]; number[smallest] = number[i - 1]; number[i - 1] = temp; // X is the final number, in integer datatype x = 0 // Converting list upto i-1 into number for(let j = 0; j < i; j++) x = x * 10 + number[j]; // Sort the digits after i-1 in ascending order number = number.slice(i, number.length + 1); number.sort() // Converting the remaining sorted // digits into number for(let j = 0; j < n - i; j++) x = x * 10 + number[j]; document.write(\"Next number with \" + \"set of digits is \" + x);} // Driver codelet digits = \"534976\" // Converting into integer array,// number becomes [5,3,4,9,7,6]let number = []for(let i = 0; i < digits.length; i++) number[i] = Number(digits[i]); findNext(number, digits.length); // This code is contributed by rohan07 </script>",
"e": 36783,
"s": 34785,
"text": null
},
{
"code": null,
"e": 36829,
"s": 36783,
"text": "Next number with same set of digits is 536479"
},
{
"code": null,
"e": 36878,
"s": 36829,
"text": "Time Complexity: O(N*logN) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 37298,
"s": 36878,
"text": "The above implementation can be optimized in following ways. 1) We can use binary search in step II instead of linear search. 2) In step IV, instead of doing simple sort, we can apply some clever technique to do it in linear time. Hint: We know that all digits are linearly sorted in reverse order except one digit which was swapped.With above optimizations, we can say that the time complexity of this method is O(n). "
},
{
"code": null,
"e": 37320,
"s": 37298,
"text": "Optimised Approach : "
},
{
"code": null,
"e": 37602,
"s": 37320,
"text": "1. Here instead of sorting the digits after (i-1) index, we are reversing the digits as mentioned in the above optimisation point.2. As they will be in decreasing order so to find the smallest element possible from the right part we just reverse them thus reducing time complexity."
},
{
"code": null,
"e": 37653,
"s": 37602,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 37659,
"s": 37653,
"text": "C++14"
},
{
"code": null,
"e": 37667,
"s": 37659,
"text": "Python3"
},
{
"code": null,
"e": 37678,
"s": 37667,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; vector<int> nextPermutation(int n, vector<int> arr){ // If number of digits is 1 then just return the vector if (n == 1) return arr; // Start from the right most digit and find the first // digit that is // smaller than the digit next to it. int i = 0; for (i = n - 1; i > 0; i--) { if (arr[i] > arr[i - 1]) break; } // If there is a possibility of a next greater element if (i != 0) { // Find the smallest digit on right side of (i-1)'th // digit that is // greater than number[i-1] for (int j = n - 1; j >= i; j--) { if (arr[i - 1] < arr[j]) { // Swap the found smallest digit i.e. arr[j] // with arr[i-1] swap(arr[i - 1], arr[j]); break; } } } // Reverse the digits after (i-1) because the digits // after (i-1) are in decreasing order and thus we will // get the smallest element possible from these digits reverse(arr.begin() + i, arr.end()); // If i is 0 that means elements are in decreasing order // Therefore, no greater element possible then we just // return the lowest possible // order/element formed from these digits by just // reversing the vector return arr;} int main(){ int n = 6; vector<int> v{ 5,3,4,9,7,6 }; vector<int> res; res = nextPermutation(n, v); for (int i = 0; i < res.size(); i++) { cout << res[i] << \" \"; }}",
"e": 39199,
"s": 37678,
"text": null
},
{
"code": "# A python program to find the next greatest numberdef nextPermutation(arr): # find the length of the array n = len(arr) # start from the right most digit and find the first # digit that is smaller than the digit next to it. k = n - 2 while k >= 0: if arr[k] < arr[k + 1]: break k -= 1 # reverse the list if the digit that is smaller than the # digit next to it is not found. if k < 0: arr = arr[::-1] else: # find the first greatest element than arr[k] from the # end of the list for l in range(n - 1, k, -1): if arr[l] > arr[k]: break # swap the elements at arr[k] and arr[l arr[l], arr[k] = arr[k], arr[l] # reverse the list from k + 1 to the end to find the # most nearest greater number to the given input number arr[k + 1:] = reversed(arr[k + 1:]) return arr # Driver codearr = [5, 3, 4, 9, 7, 6]print(*nextPermutation(arr)) # This code is contributed by Manish Thapa",
"e": 40264,
"s": 39199,
"text": null
},
{
"code": "<script> function nextPermutation(n, arr){ // If number of digits is 1 then just return the vector if (n == 1) return arr; // Start from the right most digit and find the first // digit that is // smaller than the digit next to it. let i = 0; for (i = n - 1; i > 0; i--) { if (arr[i] > arr[i - 1]) break; } // If there is a possibility of a next greater element if (i != 0) { // Find the smallest digit on right side of (i-1)'th // digit that is // greater than number[i-1] for (let j = n - 1; j >= i; j--) { if (arr[i - 1] < arr[j]) { // Swap the found smallest digit i.e. arr[j] // with arr[i-1] let temp = arr[i - 1]; arr[i - 1] = arr[j]; arr[j] = temp; break; } } } // Reverse the digits after (i-1) because the digits // after (i-1) are in decreasing order and thus we will // get the smallest element possible from these digits arr = arr.slice(0,i).concat(arr.slice(i,arr.length).reverse()); // If i is 0 that means elements are in decreasing order // Therefore, no greater element possible then we just // return the lowest possible // order/element formed from these digits by just // reversing the vector return arr;} let v = [5,3,4,9,7,6];let n = 6;let res = nextPermutation(n, v);for (let i = 0; i < res.length; i++) { document.write(res[i] + \" \")} // This code is contributed by avanitrachhadiya2155</script>",
"e": 41874,
"s": 40264,
"text": null
},
{
"code": null,
"e": 41887,
"s": 41874,
"text": "5 3 6 4 7 9 "
},
{
"code": null,
"e": 41930,
"s": 41887,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 42098,
"s": 41930,
"text": "This article is contributed by Rahul Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 42108,
"s": 42098,
"text": "yogesh135"
},
{
"code": null,
"e": 42120,
"s": 42108,
"text": "29AjayKumar"
},
{
"code": null,
"e": 42131,
"s": 42120,
"text": "ChrisFedun"
},
{
"code": null,
"e": 42139,
"s": 42131,
"text": "rohan07"
},
{
"code": null,
"e": 42153,
"s": 42139,
"text": "vishalkharwar"
},
{
"code": null,
"e": 42174,
"s": 42153,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 42187,
"s": 42174,
"text": "iammanish041"
},
{
"code": null,
"e": 42203,
"s": 42187,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 42209,
"s": 42203,
"text": "Adobe"
},
{
"code": null,
"e": 42216,
"s": 42209,
"text": "Amazon"
},
{
"code": null,
"e": 42224,
"s": 42216,
"text": "FactSet"
},
{
"code": null,
"e": 42229,
"s": 42224,
"text": "Hike"
},
{
"code": null,
"e": 42240,
"s": 42229,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 42250,
"s": 42240,
"text": "Microsoft"
},
{
"code": null,
"e": 42265,
"s": 42250,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 42279,
"s": 42265,
"text": "number-digits"
},
{
"code": null,
"e": 42293,
"s": 42279,
"text": "Oxigen Wallet"
},
{
"code": null,
"e": 42305,
"s": 42293,
"text": "permutation"
},
{
"code": null,
"e": 42314,
"s": 42305,
"text": "Qualcomm"
},
{
"code": null,
"e": 42322,
"s": 42314,
"text": "Samsung"
},
{
"code": null,
"e": 42331,
"s": 42322,
"text": "Snapdeal"
},
{
"code": null,
"e": 42360,
"s": 42331,
"text": "Vizury Interactive Solutions"
},
{
"code": null,
"e": 42369,
"s": 42360,
"text": "Zillious"
},
{
"code": null,
"e": 42376,
"s": 42369,
"text": "Arrays"
},
{
"code": null,
"e": 42389,
"s": 42376,
"text": "Mathematical"
},
{
"code": null,
"e": 42399,
"s": 42389,
"text": "Searching"
},
{
"code": null,
"e": 42414,
"s": 42399,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 42421,
"s": 42414,
"text": "Amazon"
},
{
"code": null,
"e": 42431,
"s": 42421,
"text": "Microsoft"
},
{
"code": null,
"e": 42439,
"s": 42431,
"text": "Samsung"
},
{
"code": null,
"e": 42448,
"s": 42439,
"text": "Snapdeal"
},
{
"code": null,
"e": 42456,
"s": 42448,
"text": "FactSet"
},
{
"code": null,
"e": 42461,
"s": 42456,
"text": "Hike"
},
{
"code": null,
"e": 42472,
"s": 42461,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 42478,
"s": 42472,
"text": "Adobe"
},
{
"code": null,
"e": 42487,
"s": 42478,
"text": "Qualcomm"
},
{
"code": null,
"e": 42496,
"s": 42487,
"text": "Zillious"
},
{
"code": null,
"e": 42510,
"s": 42496,
"text": "Oxigen Wallet"
},
{
"code": null,
"e": 42539,
"s": 42510,
"text": "Vizury Interactive Solutions"
},
{
"code": null,
"e": 42546,
"s": 42539,
"text": "Arrays"
},
{
"code": null,
"e": 42556,
"s": 42546,
"text": "Searching"
},
{
"code": null,
"e": 42569,
"s": 42556,
"text": "Mathematical"
},
{
"code": null,
"e": 42581,
"s": 42569,
"text": "permutation"
},
{
"code": null,
"e": 42679,
"s": 42581,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42702,
"s": 42679,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 42747,
"s": 42702,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 42768,
"s": 42747,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 42822,
"s": 42768,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 42846,
"s": 42822,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 42876,
"s": 42846,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 42936,
"s": 42876,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 42951,
"s": 42936,
"text": "C++ Data Types"
},
{
"code": null,
"e": 42994,
"s": 42951,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Python Convert nested dictionary into flattened dictionary?
|
As the world embraces more unstructured data, we come across many formats of data where the data structure can be deeply nested like nested JSONS. Python has the ability to deal with nested data structure by concatenating the inner keys with outer keys to flatten the data. In this article we will take a nested dictionary and flattened it.
In this approach we design a function to recursively process each item in the dictionary. We pass the dictionary, design a place holder for the output dictionary, the key and separator as parameters. We use the isinstance to check if the next item itself is a dictionary and then pass it through the recursive call if it is also a dictionary.
dictA = {
"id": "0001",
"name": "hotdog",
"image":
{
"url": "images/0001.jpg",
"thumbnail":
{
"url": "images/thumbnails/0001.jpg",
"height,width": "2x4"
}
}
}
def dict_flatten(in_dict, dict_out=None, parent_key=None, separator="_"):
if dict_out is None:
dict_out = {}
for k, v in in_dict.items():
k = f"{parent_key}{separator}{k}" if parent_key else k
if isinstance(v, dict):
dict_flatten(in_dict=v, dict_out=dict_out, parent_key=k)
continue
dict_out[k] = v
return dict_out
final_dict = dict_flatten(dictA)
print(final_dict)
Running the above code gives us the following result −
{
'id': '0001',
'name': 'hotdog',
'image_url': 'images/0001.jpg',
'image_thumbnail_url': 'images/thumbnails/0001.jpg',
'image_thumbnail_height,width': '2x4'
}
This is a module which can be directly used by giving it the dictionary as input. The default separator is -.
from cherrypicker import CherryPicker
dictA = {
"id": "0001",
"name": "hotdog",
"image":
{
"url": "images/0001.jpg",
"thumbnail":
{
"url": "images/thumbnails/0001.jpg",
"height,width": "2x4"
}
}
}
picker = CherryPicker(dictA)
print(picker.flatten().get())
Running the above code gives us the following result −
{
'id': '0001',
'name': 'hotdog',
'image_url': 'images/0001.jpg',
'image_thumbnail_url': 'images/thumbnails/0001.jpg',
'image_thumbnail_height,
width': '2x4'
}
|
[
{
"code": null,
"e": 1403,
"s": 1062,
"text": "As the world embraces more unstructured data, we come across many formats of data where the data structure can be deeply nested like nested JSONS. Python has the ability to deal with nested data structure by concatenating the inner keys with outer keys to flatten the data. In this article we will take a nested dictionary and flattened it."
},
{
"code": null,
"e": 1746,
"s": 1403,
"text": "In this approach we design a function to recursively process each item in the dictionary. We pass the dictionary, design a place holder for the output dictionary, the key and separator as parameters. We use the isinstance to check if the next item itself is a dictionary and then pass it through the recursive call if it is also a dictionary."
},
{
"code": null,
"e": 2435,
"s": 1746,
"text": "dictA = {\n \"id\": \"0001\",\n \"name\": \"hotdog\",\n \"image\":\n {\n \"url\": \"images/0001.jpg\",\n\n \"thumbnail\":\n {\n \"url\": \"images/thumbnails/0001.jpg\",\n \"height,width\": \"2x4\"\n }\n }\n}\ndef dict_flatten(in_dict, dict_out=None, parent_key=None, separator=\"_\"):\n if dict_out is None:\n dict_out = {}\n\n for k, v in in_dict.items():\n k = f\"{parent_key}{separator}{k}\" if parent_key else k\n if isinstance(v, dict):\n dict_flatten(in_dict=v, dict_out=dict_out, parent_key=k)\n continue\n\n dict_out[k] = v\n\n return dict_out\n\nfinal_dict = dict_flatten(dictA)\nprint(final_dict)"
},
{
"code": null,
"e": 2490,
"s": 2435,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2664,
"s": 2490,
"text": "{\n 'id': '0001',\n 'name': 'hotdog',\n 'image_url': 'images/0001.jpg',\n 'image_thumbnail_url': 'images/thumbnails/0001.jpg',\n 'image_thumbnail_height,width': '2x4'\n}"
},
{
"code": null,
"e": 2774,
"s": 2664,
"text": "This is a module which can be directly used by giving it the dictionary as input. The default separator is -."
},
{
"code": null,
"e": 3141,
"s": 2774,
"text": "from cherrypicker import CherryPicker\n\ndictA = {\n \"id\": \"0001\",\n \"name\": \"hotdog\",\n \"image\":\n {\n \"url\": \"images/0001.jpg\",\n\n \"thumbnail\":\n {\n \"url\": \"images/thumbnails/0001.jpg\",\n \"height,width\": \"2x4\"\n }\n }\n}\n\npicker = CherryPicker(dictA)\nprint(picker.flatten().get())"
},
{
"code": null,
"e": 3196,
"s": 3141,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 3374,
"s": 3196,
"text": "{\n 'id': '0001',\n 'name': 'hotdog',\n 'image_url': 'images/0001.jpg',\n 'image_thumbnail_url': 'images/thumbnails/0001.jpg',\n 'image_thumbnail_height,\n width': '2x4'\n}"
}
] |
Permutations of a given string | Practice | GeeksforGeeks
|
Given a string S. The task is to print all permutations of a given string in lexicographically sorted order.
Example 1:
Input: ABC
Output:
ABC ACB BAC BCA CAB CBA
Explanation:
Given string ABC has permutations in 6
forms as ABC, ACB, BAC, BCA, CAB and CBA .
Example 2:
Input: ABSG
Output:
ABGS ABSG AGBS AGSB ASBG ASGB BAGS
BASG BGAS BGSA BSAG BSGA GABS GASB
GBAS GBSA GSAB GSBA SABG SAGB SBAG
SBGA SGAB SGBA
Explanation:
Given string ABSG has 24 permutations.
Your Task:
You don't need to read input or print anything. Your task is to complete the function find_permutaion() which takes the string S as input parameter and returns a vector of string in lexicographical order.
Expected Time Complexity: O(n! * n)
Expected Space Complexity: O(n)
Constraints:
1 <= length of string <= 5
0
ashok1si18ec0172 days ago
// { Driver Code Startsimport java.util.*;import java.lang.*;import java.io.*;class GFG{public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); while(t-->0) { String S = br.readLine().trim(); Solution obj = new Solution(); List<String> ans = obj.find_permutation(S); for( int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i)+" "); } System.out.println(); }}}
// } Driver Code Ends
class Solution { public List<String> find_permutation(String S) { // Code here List<String> res = new ArrayList<String>(); int i = 0; find(S, i, res); Collections.sort(res); return res; } public void find(String S, int i, List<String> res) { if(i >= S.length()) { res.add(S); return; } for(int j = i; j < S.length(); j++) { S = swap(S, i, j); find(S, i+1, res); S = swap(S, i, j); } } public String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); }}
0
vishalsavade3 days ago
// This code is contributed by SK
####################Method 1#######################
void permute(string s, int l, vector<string> &res){
if(l == s.size()){
res.push_back(s);
return;
}
for(int i = l; i < s.size(); i++){
swap(s[i], s[l]);
permute(s, l+1, res);
swap(s[l], s[i]);
}
}
vector<string>find_permutation(string s){
// Code here there
vector<string> res;
permute(S, 0, res);
sort(res.begin(), res.end());
return res;
}
###############METHOD 2#############################
vector<string>find_permutation(string s){
// Code here there
vector<string> res;
sort(s.begin(), s.end());
do{
res.push_back(s);
}while(next_permutation(s.begin(), s.end()));
sort(res.begin(), res.end());
return res;
}
0
ankitparashxr4 days ago
0.01 sec (java)
class Solution { void permutation(String str,String asf,List<String> ans) { if(str.length()==0) { ans.add(asf); return; } for(int i=0;i<str.length();i++) { char ch = str.charAt(i); String left = str.substring(0,i); String right = str.substring(i+1); String ros = left+right; permutation(ros,asf+ch,ans); } } public List<String> find_permutation(String s) { List<String> ans = new ArrayList<>(); permutation(s,"",ans); Collections.sort(ans); return ans; }}
0
sahilmalhan004 days ago
//Simple Java Solution using frequency map and backtracking
public List<String> find_permutation(String S) {
// Create a freq. map
Map<Character, Integer> fmap = new HashMap<>();
for(char ch : S.toCharArray()){
if(fmap.containsKey(ch)){
fmap.put(ch, fmap.get(ch) + 1);
} else {
fmap.put(ch, 1);
}
}
List<String> ans = new ArrayList<>();
generateWords(1, S.length(), fmap, "", ans);
//lexicographically increasing order
Collections.sort(ans);
return ans;
}
public void generateWords(int cs, int ts, Map<Character, Integer> fmap, String asf, List<String> ans){
//cs > ts means the entire string has been added to asf, then add asf to arrayList
if(cs > ts){
ans.add(asf);
return;
}
for(char ch : fmap.keySet()){
if(fmap.get(ch) > 0){
fmap.put(ch, fmap.get(ch) - 1);
generateWords(cs + 1, ts, fmap, asf + ch, ans);
fmap.put(ch, fmap.get(ch) + 1);
}
}
}
0
bhavdeepkaushal3925 days ago
void permut(string str,vector<string> &result , string ans =""){ if(str.length()==0){ result.push_back(ans); return ; } for(int i=0;i<str.length();i++){ char ch = str[i]; string ros = str.substr(0,i)+str.substr(i+1); permut(ros,result,ans+ch); }}
vector<string>find_permutation(string S){ vector<string> result; permut(S,result); return result;
}
0
anmoljandiyal12
This comment was deleted.
0
anmoljandiyal12
This comment was deleted.
0
yaswa7792 weeks ago
I am not getting any errors but due to order changing answer is wrong can anyone help me:(
class Solution{public: string res = ""; void permutation(vector<string>&result,string S,string res){ if(S.length()==0){ result.push_back(res); return; } for(int i=0;i<S.length();i++){ char ch = S[i]; string leftpart = S.substr(0,i); string rightpart = S.substr(i+1); string val = leftpart+rightpart; permutation(result,val,res+ch); } } vector<string>find_permutation(string S) { vector<string>result; permutation(result,S,res); return result; }};
0
shinu832 weeks ago
void solve(string &s,vector<string> &ans,int index){ if(index>=s.size()){ ans.push_back(s); return; } for(int j=index;j<s.size();j++){ swap(s[index],s[j]); solve(s,ans,index+1); swap(s[index],s[j]); }} vector<string>find_permutation(string S) { vector<string> ans; int index=0; solve(S,ans,index); sort(ans.begin(),ans.end()); return ans; }
0
sakesai302 weeks ago
class Solution { public List<String> find_permutation(String S) { ArrayList<String> kaka = new ArrayList<>(); stringPermutations(0,S.toCharArray(),S.length(),kaka); Collections.sort(kaka); return kaka; } static void stringPermutations(int index,char[] mama,int n,ArrayList<String> list) { if(index == n) { list.add(new String(mama)); return; } for(int i =index;i<n;i++) { swap(mama,i,index); stringPermutations(index+1, mama, n,list); swap(mama,i,index); } }static void swap(char[] ch,int lo,int hi) { char temp = ch[lo]; ch[lo] = ch[hi]; ch[hi] = temp;}}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 347,
"s": 238,
"text": "Given a string S. The task is to print all permutations of a given string in lexicographically sorted order."
},
{
"code": null,
"e": 360,
"s": 349,
"text": "Example 1:"
},
{
"code": null,
"e": 500,
"s": 360,
"text": "Input: ABC\nOutput:\nABC ACB BAC BCA CAB CBA\nExplanation:\nGiven string ABC has permutations in 6 \nforms as ABC, ACB, BAC, BCA, CAB and CBA .\n"
},
{
"code": null,
"e": 511,
"s": 500,
"text": "Example 2:"
},
{
"code": null,
"e": 707,
"s": 511,
"text": "Input: ABSG\nOutput:\nABGS ABSG AGBS AGSB ASBG ASGB BAGS \nBASG BGAS BGSA BSAG BSGA GABS GASB \nGBAS GBSA GSAB GSBA SABG SAGB SBAG \nSBGA SGAB SGBA\nExplanation:\nGiven string ABSG has 24 permutations.\n"
},
{
"code": null,
"e": 927,
"s": 709,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function find_permutaion() which takes the string S as input parameter and returns a vector of string in lexicographical order."
},
{
"code": null,
"e": 965,
"s": 929,
"text": "Expected Time Complexity: O(n! * n)"
},
{
"code": null,
"e": 997,
"s": 965,
"text": "Expected Space Complexity: O(n)"
},
{
"code": null,
"e": 1041,
"s": 999,
"text": "Constraints:\n1 <= length of string <= 5\n "
},
{
"code": null,
"e": 1045,
"s": 1043,
"text": "0"
},
{
"code": null,
"e": 1071,
"s": 1045,
"text": "ashok1si18ec0172 days ago"
},
{
"code": null,
"e": 1701,
"s": 1071,
"text": "// { Driver Code Startsimport java.util.*;import java.lang.*;import java.io.*;class GFG{public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); while(t-->0) { String S = br.readLine().trim(); Solution obj = new Solution(); List<String> ans = obj.find_permutation(S); for( int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i)+\" \"); } System.out.println(); }}}"
},
{
"code": null,
"e": 1723,
"s": 1701,
"text": "// } Driver Code Ends"
},
{
"code": null,
"e": 2483,
"s": 1723,
"text": "class Solution { public List<String> find_permutation(String S) { // Code here List<String> res = new ArrayList<String>(); int i = 0; find(S, i, res); Collections.sort(res); return res; } public void find(String S, int i, List<String> res) { if(i >= S.length()) { res.add(S); return; } for(int j = i; j < S.length(); j++) { S = swap(S, i, j); find(S, i+1, res); S = swap(S, i, j); } } public String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); }}"
},
{
"code": null,
"e": 2485,
"s": 2483,
"text": "0"
},
{
"code": null,
"e": 2508,
"s": 2485,
"text": "vishalsavade3 days ago"
},
{
"code": null,
"e": 3328,
"s": 2508,
"text": "// This code is contributed by SK\n####################Method 1#######################\nvoid permute(string s, int l, vector<string> &res){\n\t if(l == s.size()){\n\t res.push_back(s);\n\t return;\n\t }\n\t for(int i = l; i < s.size(); i++){\n\t swap(s[i], s[l]);\n\t permute(s, l+1, res);\n\t swap(s[l], s[i]);\n\t }\n\t }\nvector<string>find_permutation(string s){\n\t// Code here there\n\tvector<string> res;\n\tpermute(S, 0, res);\n\tsort(res.begin(), res.end());\n\treturn res;\n}\n###############METHOD 2#############################\nvector<string>find_permutation(string s){\n\t// Code here there\n\tvector<string> res;\n\tsort(s.begin(), s.end());\n\tdo{\n\t\tres.push_back(s);\n\t}while(next_permutation(s.begin(), s.end()));\n\tsort(res.begin(), res.end());\n\treturn res;\n}\n\n"
},
{
"code": null,
"e": 3330,
"s": 3328,
"text": "0"
},
{
"code": null,
"e": 3354,
"s": 3330,
"text": "ankitparashxr4 days ago"
},
{
"code": null,
"e": 3370,
"s": 3354,
"text": "0.01 sec (java)"
},
{
"code": null,
"e": 3989,
"s": 3370,
"text": "class Solution { void permutation(String str,String asf,List<String> ans) { if(str.length()==0) { ans.add(asf); return; } for(int i=0;i<str.length();i++) { char ch = str.charAt(i); String left = str.substring(0,i); String right = str.substring(i+1); String ros = left+right; permutation(ros,asf+ch,ans); } } public List<String> find_permutation(String s) { List<String> ans = new ArrayList<>(); permutation(s,\"\",ans); Collections.sort(ans); return ans; }}"
},
{
"code": null,
"e": 3991,
"s": 3989,
"text": "0"
},
{
"code": null,
"e": 4015,
"s": 3991,
"text": "sahilmalhan004 days ago"
},
{
"code": null,
"e": 5176,
"s": 4015,
"text": "//Simple Java Solution using frequency map and backtracking\n\npublic List<String> find_permutation(String S) {\n // Create a freq. map\n Map<Character, Integer> fmap = new HashMap<>();\n for(char ch : S.toCharArray()){\n if(fmap.containsKey(ch)){\n fmap.put(ch, fmap.get(ch) + 1);\n } else {\n fmap.put(ch, 1);\n }\n }\n \n List<String> ans = new ArrayList<>();\n generateWords(1, S.length(), fmap, \"\", ans);\n //lexicographically increasing order\n Collections.sort(ans);\n return ans;\n }\n \n public void generateWords(int cs, int ts, Map<Character, Integer> fmap, String asf, List<String> ans){\n //cs > ts means the entire string has been added to asf, then add asf to arrayList\n if(cs > ts){\n ans.add(asf);\n return;\n }\n \n for(char ch : fmap.keySet()){\n if(fmap.get(ch) > 0){\n fmap.put(ch, fmap.get(ch) - 1);\n generateWords(cs + 1, ts, fmap, asf + ch, ans);\n fmap.put(ch, fmap.get(ch) + 1);\n }\n }\n }"
},
{
"code": null,
"e": 5178,
"s": 5176,
"text": "0"
},
{
"code": null,
"e": 5207,
"s": 5178,
"text": "bhavdeepkaushal3925 days ago"
},
{
"code": null,
"e": 5495,
"s": 5207,
"text": "void permut(string str,vector<string> &result , string ans =\"\"){ if(str.length()==0){ result.push_back(ans); return ; } for(int i=0;i<str.length();i++){ char ch = str[i]; string ros = str.substr(0,i)+str.substr(i+1); permut(ros,result,ans+ch); }}"
},
{
"code": null,
"e": 5602,
"s": 5495,
"text": "vector<string>find_permutation(string S){ vector<string> result; permut(S,result); return result;"
},
{
"code": null,
"e": 5604,
"s": 5602,
"text": "}"
},
{
"code": null,
"e": 5606,
"s": 5604,
"text": "0"
},
{
"code": null,
"e": 5622,
"s": 5606,
"text": "anmoljandiyal12"
},
{
"code": null,
"e": 5648,
"s": 5622,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5650,
"s": 5648,
"text": "0"
},
{
"code": null,
"e": 5666,
"s": 5650,
"text": "anmoljandiyal12"
},
{
"code": null,
"e": 5692,
"s": 5666,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5694,
"s": 5692,
"text": "0"
},
{
"code": null,
"e": 5714,
"s": 5694,
"text": "yaswa7792 weeks ago"
},
{
"code": null,
"e": 5805,
"s": 5714,
"text": "I am not getting any errors but due to order changing answer is wrong can anyone help me:("
},
{
"code": null,
"e": 6368,
"s": 5807,
"text": "class Solution{public: string res = \"\"; void permutation(vector<string>&result,string S,string res){ if(S.length()==0){ result.push_back(res); return; } for(int i=0;i<S.length();i++){ char ch = S[i]; string leftpart = S.substr(0,i); string rightpart = S.substr(i+1); string val = leftpart+rightpart; permutation(result,val,res+ch); } } vector<string>find_permutation(string S) { vector<string>result; permutation(result,S,res); return result; }};"
},
{
"code": null,
"e": 6370,
"s": 6368,
"text": "0"
},
{
"code": null,
"e": 6389,
"s": 6370,
"text": "shinu832 weeks ago"
},
{
"code": null,
"e": 6790,
"s": 6389,
"text": "void solve(string &s,vector<string> &ans,int index){ if(index>=s.size()){ ans.push_back(s); return; } for(int j=index;j<s.size();j++){ swap(s[index],s[j]); solve(s,ans,index+1); swap(s[index],s[j]); }} vector<string>find_permutation(string S) { vector<string> ans; int index=0; solve(S,ans,index); sort(ans.begin(),ans.end()); return ans; }"
},
{
"code": null,
"e": 6792,
"s": 6790,
"text": "0"
},
{
"code": null,
"e": 6813,
"s": 6792,
"text": "sakesai302 weeks ago"
},
{
"code": null,
"e": 7409,
"s": 6813,
"text": "class Solution { public List<String> find_permutation(String S) { ArrayList<String> kaka = new ArrayList<>(); stringPermutations(0,S.toCharArray(),S.length(),kaka); Collections.sort(kaka); return kaka; } static void stringPermutations(int index,char[] mama,int n,ArrayList<String> list) { if(index == n) { list.add(new String(mama)); return; } for(int i =index;i<n;i++) { swap(mama,i,index); stringPermutations(index+1, mama, n,list); swap(mama,i,index); } }static void swap(char[] ch,int lo,int hi) { char temp = ch[lo]; ch[lo] = ch[hi]; ch[hi] = temp;}}"
},
{
"code": null,
"e": 7555,
"s": 7409,
"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": 7591,
"s": 7555,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7601,
"s": 7591,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7611,
"s": 7601,
"text": "\nContest\n"
},
{
"code": null,
"e": 7674,
"s": 7611,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7822,
"s": 7674,
"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": 8030,
"s": 7822,
"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": 8136,
"s": 8030,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Foundation - Combined Column/Row
|
The column and row classes are used on the same element to get the full-width column to use as container.
The following example demonstrates the use of combined column/row class in Foundation −
<!DOCTYPE html>
<html>
<head>
<title>Foundation Template</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<!-- Compressed CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous">
<!-- Compressed JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script>
</head>
<body>
<h3>Example of combined column and row</h3>
<div class = "column row" style = "background-color:#8BD6EE;">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type
specimen book.
</div>
</body>
</html>
Let us carry out the following steps to see how the above given code works −
Save the above given html code combined_row_column.html file.
Save the above given html code combined_row_column.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.
117 Lectures
5.5 hours
Shakthi Swaroop
61 Lectures
1.5 hours
Hans Weemaes
17 Lectures
4 hours
Stephen Kahuria
8 Lectures
50 mins
Zenva
28 Lectures
2 hours
Sandra L
16 Lectures
2.5 hours
GreyCampus Inc.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2344,
"s": 2238,
"text": "The column and row classes are used on the same element to get the full-width column to use as container."
},
{
"code": null,
"e": 2432,
"s": 2344,
"text": "The following example demonstrates the use of combined column/row class in Foundation −"
},
{
"code": null,
"e": 3852,
"s": 2432,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Foundation Template</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n\n <!-- Compressed CSS -->\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css\" integrity=\"sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==\" crossorigin=\"anonymous\">\n\n <!-- Compressed JavaScript -->\n <script src=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js\" integrity=\"sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==\" crossorigin=\"anonymous\"></script>\n </head>\n\n <body>\n <h3>Example of combined column and row</h3>\n\n <div class = \"column row\" style = \"background-color:#8BD6EE;\">\n Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,\n when an unknown printer took a galley of type and scrambled it to make a type\n specimen book.\n </div>\n\n </body>\n</html>"
},
{
"code": null,
"e": 3929,
"s": 3852,
"text": "Let us carry out the following steps to see how the above given code works −"
},
{
"code": null,
"e": 3991,
"s": 3929,
"text": "Save the above given html code combined_row_column.html file."
},
{
"code": null,
"e": 4053,
"s": 3991,
"text": "Save the above given html code combined_row_column.html file."
},
{
"code": null,
"e": 4126,
"s": 4053,
"text": "Open this HTML file in a browser, an output is displayed as shown below."
},
{
"code": null,
"e": 4199,
"s": 4126,
"text": "Open this HTML file in a browser, an output is displayed as shown below."
},
{
"code": null,
"e": 4235,
"s": 4199,
"text": "\n 117 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4252,
"s": 4235,
"text": " Shakthi Swaroop"
},
{
"code": null,
"e": 4287,
"s": 4252,
"text": "\n 61 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4301,
"s": 4287,
"text": " Hans Weemaes"
},
{
"code": null,
"e": 4334,
"s": 4301,
"text": "\n 17 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4351,
"s": 4334,
"text": " Stephen Kahuria"
},
{
"code": null,
"e": 4382,
"s": 4351,
"text": "\n 8 Lectures \n 50 mins\n"
},
{
"code": null,
"e": 4389,
"s": 4382,
"text": " Zenva"
},
{
"code": null,
"e": 4422,
"s": 4389,
"text": "\n 28 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4432,
"s": 4422,
"text": " Sandra L"
},
{
"code": null,
"e": 4467,
"s": 4432,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4484,
"s": 4467,
"text": " GreyCampus Inc."
},
{
"code": null,
"e": 4491,
"s": 4484,
"text": " Print"
},
{
"code": null,
"e": 4502,
"s": 4491,
"text": " Add Notes"
}
] |
Rearrange a string so that all same characters become atleast d distance away - GeeksforGeeks
|
12 Jun, 2021
Given a string and a positive integer d, rearrange characters of the given string such that the same characters become at-least d distance away from each other.
Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible, that should also be reported.
Expected time complexity is O(n) where n is length of input string.
Examples:
Input: "aaaabbbcc", d = 2
Output: "ababacabc"
Input: "aacbbc", d = 3
Output: "abcabc"
Input: "geeksforgeeks", d = 3
Output: egkesfegkeors
Input: "aaa", d = 2
Output: Cannot be rearranged
We have already discussed how to put same characters exactly d distance away. This is a extended version where same characters should be moved at-least d distance away.
The idea is to use extra space to store frequencies of all characters and maintain an array for inserting the values at correct distance. Following is the complete algorithm –
Let the given string be str and size of string be n and alphabet size is be assumed as 256 (a constant).We scan input string str and store frequencies of all characters in an array freq.We create an array dist[] for inserting the values at correct distance. dist[j] will store the least distance between current position and the next position we can use character ‘j’. If dist[j] <= 0, character ‘j’ can be inserted in current position.run a loop n times Search for next eligible character with maximum frequency and dist[j] <= 0.If we found such character, we put that character at next available position in output array, decrease its frequency and reset its distance as d. If we don’t find any character, string cannot be rearranged and we return false.As we move forward in output string, we decrement distance of all characters in dist[] by 1.
Let the given string be str and size of string be n and alphabet size is be assumed as 256 (a constant).
We scan input string str and store frequencies of all characters in an array freq.
We create an array dist[] for inserting the values at correct distance. dist[j] will store the least distance between current position and the next position we can use character ‘j’. If dist[j] <= 0, character ‘j’ can be inserted in current position.
run a loop n times Search for next eligible character with maximum frequency and dist[j] <= 0.If we found such character, we put that character at next available position in output array, decrease its frequency and reset its distance as d. If we don’t find any character, string cannot be rearranged and we return false.As we move forward in output string, we decrement distance of all characters in dist[] by 1.
Search for next eligible character with maximum frequency and dist[j] <= 0.
If we found such character, we put that character at next available position in output array, decrease its frequency and reset its distance as d. If we don’t find any character, string cannot be rearranged and we return false.
As we move forward in output string, we decrement distance of all characters in dist[] by 1.
Following is the implementation of above algorithm.
C++
Java
Python3
C#
Javascript
// C++ program to rearrange a string so that all same// characters become atleast d distance away#include <bits/stdc++.h>#define MAX_CHAR 256using namespace std; // The function returns next eligible character// with maximum frequency (Greedy!!) and// zero or negative distanceint nextChar(int freq[], int dist[]){ int max = INT_MIN; for (int i = 0; i < MAX_CHAR; i++) if (dist[i] <= 0 && freq[i] > 0 && (max == INT_MIN || freq[i] > freq[max])) max = i; return max;} // The main function that rearranges input string 'str'// such that two same characters become atleast d// distance awayint rearrange(char str[], char out[], int d){ // Find length of input string int n = strlen(str); // Create an array to store all characters and their // frequencies in str[] int freq[MAX_CHAR] = { 0 }; // Traverse the input string and store frequencies // of all characters in freq[] array. for (int i = 0; i < n; i++) freq[str[i]]++; // Create an array for inserting the values at // correct distance dist[j] stores the least distance // between current position and the next position we // can use character 'j' int dist[MAX_CHAR] = { 0 }; for (int i = 0; i < n; i++) { // find next eligible character int j = nextChar(freq, dist); // return 0 if string cannot be rearranged if (j == INT_MIN) return 0; // Put character j at next position out[i] = j; // decrease its frequency freq[j]--; // set distance as d dist[j] = d; // decrease distance of all characters by 1 for (int i = 0; i < MAX_CHAR; i++) dist[i]--; } // null terminate output string out[n] = '\0'; // return success return 1;} // Driver codeint main(){ char str[] = "aaaabbbcc"; int n = strlen(str); // To store output char out[n]; if (rearrange(str, out, 2)) cout << out; else cout << "Cannot be rearranged"; return 0;}
// Java program to rearrange a string so that all same// characters become atleast d distance awayimport java.util.*; class GFG{ static int MAX_CHAR = 256; // The function returns next eligible character// with maximum frequency (Greedy!!) and// zero or negative distancestatic int nextChar(int freq[], int dist[]){ int max = Integer.MIN_VALUE; for (int i = 0; i < MAX_CHAR; i++) if (dist[i] <= 0 && freq[i] > 0 && (max == Integer.MIN_VALUE || freq[i] > freq[max])) max = i; return max;} // The main function that rearranges input string 'str'// such that two same characters become atleast d// distance awaystatic int rearrange(char str[], char out[], int d){ // Find length of input string int n = str.length; // Create an array to store all characters and their // frequencies in str[] int []freq = new int[MAX_CHAR]; // Traverse the input string and store frequencies // of all characters in freq[] array. for (int i = 0; i < n; i++) freq[str[i]]++; // Create an array for inserting the values at // correct distance dist[j] stores the least distance // between current position and the next position we // can use character 'j' int []dist = new int[MAX_CHAR]; for (int i = 0; i < n; i++) { // find next eligible character int j = nextChar(freq, dist); // return 0 if string cannot be rearranged if (j == Integer.MIN_VALUE) return 0; // Put character j at next position out[i] = (char) j; // decrease its frequency freq[j]--; // set distance as d dist[j] = d; // decrease distance of all characters by 1 for (int k = 0; k < MAX_CHAR; k++) dist[k]--; } // null terminate output string Arrays.copyOfRange(out, 0, n); // out[n] = '\0'; // return success return 1;} // Driver codepublic static void main(String[] args){ char str[] = "aaaabbbcc".toCharArray(); int n = str.length; // To store output char []out = new char[n]; if (rearrange(str, out, 2)==1) System.out.println(String.valueOf(out)); else System.out.println("Cannot be rearranged");}} // This code is contributed by Rajput-Ji
# Python3 program to rearrange a string so that all# same characters become at least d distance awayMAX_CHAR = 256 # The function returns next eligible character# with maximum frequency (Greedy!!)# and zero or negative distancedef nextChar(freq, dist): Max = float('-inf') for i in range(0, MAX_CHAR): if (dist[i] <= 0 and freq[i] > 0 and (Max == float('-inf') or freq[i] > freq[Max])): Max = i return Max # The main function that rearranges input# string 'str' such that two same characters# become atleast d distance awaydef rearrange(string, out, d): # Find length of input string n = len(string) # Create an array to store all characters # and their frequencies in str[] freq = [0] * MAX_CHAR # Traverse the input string and store frequencies # of all characters in freq[] array. for i in range(0, n): freq[ord(string[i])] += 1 # Create an array for inserting the values at # correct distance dist[j] stores the least # distance between current position and the # we next position can use character 'j' dist = [0] * MAX_CHAR for i in range(0, n): # find next eligible character j = nextChar(freq, dist) # return 0 if string cannot be rearranged if j == float('-inf'): return 0 # Put character j at next position out[i] = chr(j) # decrease its frequency freq[j] -= 1 # set distance as d dist[j] = d # decrease distance of all characters by 1 for i in range(0, MAX_CHAR): dist[i] -= 1 # return success return 1 # Driver codeif __name__ == "__main__": string = "aaaabbbcc" n = len(string) # To store output out = [None] * n if rearrange(string, out, 2): print(''.join(out)) else: print("Cannot be rearranged") # This code is contributed by Rituraj Jain
// C# program to rearrange a string so that all same// characters become atleast d distance awayusing System; class GFG{ static int MAX_CHAR = 256; // The function returns next eligible character// with maximum frequency (Greedy!!) and// zero or negative distancestatic int nextChar(int []freq, int []dist){ int max = int.MinValue; for (int i = 0; i < MAX_CHAR; i++) if (dist[i] <= 0 && freq[i] > 0 && (max == int.MinValue || freq[i] > freq[max])) max = i; return max;} // The main function that rearranges input string 'str'// such that two same characters become atleast d// distance awaystatic int rearrange(char []str, char []ouT, int d){ // Find length of input string int n = str.Length; // Create an array to store all characters and their // frequencies in str[] int []freq = new int[MAX_CHAR]; // Traverse the input string and store frequencies // of all characters in freq[] array. for (int i = 0; i < n; i++) freq[str[i]]++; // Create an array for inserting the values at // correct distance dist[j] stores the least distance // between current position and the next position we // can use character 'j' int []dist = new int[MAX_CHAR]; for (int i = 0; i < n; i++) { // find next eligible character int j = nextChar(freq, dist); // return 0 if string cannot be rearranged if (j == int.MinValue) return 0; // Put character j at next position ouT[i] = (char) j; // decrease its frequency freq[j]--; // set distance as d dist[j] = d; // decrease distance of all characters by 1 for (int k = 0; k < MAX_CHAR; k++) dist[k]--; } // null terminate output string Array.Copy(ouT,ouT, n); // out[n] = '\0'; // return success return 1;} // Driver codepublic static void Main(String[] args){ char []str = "aaaabbbcc".ToCharArray(); int n = str.Length; // To store output char []ouT = new char[n]; if (rearrange(str, ouT, 2)==1) Console.WriteLine(String.Join("",ouT)); else Console.WriteLine("Cannot be rearranged");}} // This code is contributed by 29AjayKumar
<script> // Javascript program to rearrange a// string so that all same characters// become atleast d distance awaylet MAX_CHAR = 256; // The function returns next eligible// character with maximum frequency// (Greedy!!) and zero or negative distancefunction nextChar(freq, dist){ let max = Number.MIN_VALUE; for(let i = 0; i < MAX_CHAR; i++) if (dist[i] <= 0 && freq[i] > 0 && (max == Number.MIN_VALUE || freq[i] > freq[max])) max = i; return max;} // The main function that rearranges input// string 'str' such that two same characters// become atleast d distance awayfunction rearrange(str, out, d){ // Find length of input string let n = str.length; // Create an array to store all characters // and their frequencies in str[] let freq = new Array(MAX_CHAR); for(let i = 0; i < freq.length; i++) { freq[i] = 0; } // Traverse the input string and store // frequencies of all characters in // freq[] array. for(let i = 0; i < n; i++) freq[str[i].charCodeAt(0)]++; // Create an array for inserting the // values at correct distance dist[j] // stores the least distance between // current position and the next position // we can use character 'j' let dist = new Array(MAX_CHAR); for(let i = 0; i < dist.length; i++) { dist[i] = 0; } for(let i = 0; i < n; i++) { // Find next eligible character let j = nextChar(freq, dist); // return 0 if string cannot // be rearranged if (j == Number.MIN_VALUE) return 0; // Put character j at next position out[i] = String.fromCharCode (j); // Decrease its frequency freq[j]--; // Set distance as d dist[j] = d; // Decrease distance of all // characters by 1 for(let k = 0; k < MAX_CHAR; k++) dist[k]--; } // Null terminate output string // Arrays.copyOfRange(out, 0, n); // out[n] = '\0'; // Return success return 1;} // Driver codelet str= "aaaabbbcc".split("");let n = str.length; // To store outputlet out = new Array(n); if (rearrange(str, out, 2) == 1) document.write(out.join(""));else document.write("Cannot be rearranged"); // This code is contributed by rag2127 </script>
Output :
ababacabc
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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
rituraj_jain
Rajput-Ji
29AjayKumar
rag2127
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Vigenère Cipher
How to Append a Character to a String in C
Program to add two binary strings
Convert character array to string in C++
Return maximum occurring character in an input string
Naive algorithm for Pattern Searching
Hill Cipher
sprintf() in C
A Program to check if strings are rotations of each other or not
|
[
{
"code": null,
"e": 24461,
"s": 24433,
"text": "\n12 Jun, 2021"
},
{
"code": null,
"e": 24622,
"s": 24461,
"text": "Given a string and a positive integer d, rearrange characters of the given string such that the same characters become at-least d distance away from each other."
},
{
"code": null,
"e": 24798,
"s": 24622,
"text": "Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible, that should also be reported."
},
{
"code": null,
"e": 24866,
"s": 24798,
"text": "Expected time complexity is O(n) where n is length of input string."
},
{
"code": null,
"e": 24877,
"s": 24866,
"text": "Examples: "
},
{
"code": null,
"e": 25074,
"s": 24877,
"text": "Input: \"aaaabbbcc\", d = 2\nOutput: \"ababacabc\" \n\nInput: \"aacbbc\", d = 3\nOutput: \"abcabc\" \n\nInput: \"geeksforgeeks\", d = 3\nOutput: egkesfegkeors\n\nInput: \"aaa\", d = 2\nOutput: Cannot be rearranged "
},
{
"code": null,
"e": 25243,
"s": 25074,
"text": "We have already discussed how to put same characters exactly d distance away. This is a extended version where same characters should be moved at-least d distance away."
},
{
"code": null,
"e": 25420,
"s": 25243,
"text": "The idea is to use extra space to store frequencies of all characters and maintain an array for inserting the values at correct distance. Following is the complete algorithm – "
},
{
"code": null,
"e": 26269,
"s": 25420,
"text": "Let the given string be str and size of string be n and alphabet size is be assumed as 256 (a constant).We scan input string str and store frequencies of all characters in an array freq.We create an array dist[] for inserting the values at correct distance. dist[j] will store the least distance between current position and the next position we can use character ‘j’. If dist[j] <= 0, character ‘j’ can be inserted in current position.run a loop n times Search for next eligible character with maximum frequency and dist[j] <= 0.If we found such character, we put that character at next available position in output array, decrease its frequency and reset its distance as d. If we don’t find any character, string cannot be rearranged and we return false.As we move forward in output string, we decrement distance of all characters in dist[] by 1."
},
{
"code": null,
"e": 26374,
"s": 26269,
"text": "Let the given string be str and size of string be n and alphabet size is be assumed as 256 (a constant)."
},
{
"code": null,
"e": 26457,
"s": 26374,
"text": "We scan input string str and store frequencies of all characters in an array freq."
},
{
"code": null,
"e": 26708,
"s": 26457,
"text": "We create an array dist[] for inserting the values at correct distance. dist[j] will store the least distance between current position and the next position we can use character ‘j’. If dist[j] <= 0, character ‘j’ can be inserted in current position."
},
{
"code": null,
"e": 27121,
"s": 26708,
"text": "run a loop n times Search for next eligible character with maximum frequency and dist[j] <= 0.If we found such character, we put that character at next available position in output array, decrease its frequency and reset its distance as d. If we don’t find any character, string cannot be rearranged and we return false.As we move forward in output string, we decrement distance of all characters in dist[] by 1."
},
{
"code": null,
"e": 27197,
"s": 27121,
"text": "Search for next eligible character with maximum frequency and dist[j] <= 0."
},
{
"code": null,
"e": 27424,
"s": 27197,
"text": "If we found such character, we put that character at next available position in output array, decrease its frequency and reset its distance as d. If we don’t find any character, string cannot be rearranged and we return false."
},
{
"code": null,
"e": 27517,
"s": 27424,
"text": "As we move forward in output string, we decrement distance of all characters in dist[] by 1."
},
{
"code": null,
"e": 27570,
"s": 27517,
"text": "Following is the implementation of above algorithm. "
},
{
"code": null,
"e": 27574,
"s": 27570,
"text": "C++"
},
{
"code": null,
"e": 27579,
"s": 27574,
"text": "Java"
},
{
"code": null,
"e": 27587,
"s": 27579,
"text": "Python3"
},
{
"code": null,
"e": 27590,
"s": 27587,
"text": "C#"
},
{
"code": null,
"e": 27601,
"s": 27590,
"text": "Javascript"
},
{
"code": "// C++ program to rearrange a string so that all same// characters become atleast d distance away#include <bits/stdc++.h>#define MAX_CHAR 256using namespace std; // The function returns next eligible character// with maximum frequency (Greedy!!) and// zero or negative distanceint nextChar(int freq[], int dist[]){ int max = INT_MIN; for (int i = 0; i < MAX_CHAR; i++) if (dist[i] <= 0 && freq[i] > 0 && (max == INT_MIN || freq[i] > freq[max])) max = i; return max;} // The main function that rearranges input string 'str'// such that two same characters become atleast d// distance awayint rearrange(char str[], char out[], int d){ // Find length of input string int n = strlen(str); // Create an array to store all characters and their // frequencies in str[] int freq[MAX_CHAR] = { 0 }; // Traverse the input string and store frequencies // of all characters in freq[] array. for (int i = 0; i < n; i++) freq[str[i]]++; // Create an array for inserting the values at // correct distance dist[j] stores the least distance // between current position and the next position we // can use character 'j' int dist[MAX_CHAR] = { 0 }; for (int i = 0; i < n; i++) { // find next eligible character int j = nextChar(freq, dist); // return 0 if string cannot be rearranged if (j == INT_MIN) return 0; // Put character j at next position out[i] = j; // decrease its frequency freq[j]--; // set distance as d dist[j] = d; // decrease distance of all characters by 1 for (int i = 0; i < MAX_CHAR; i++) dist[i]--; } // null terminate output string out[n] = '\\0'; // return success return 1;} // Driver codeint main(){ char str[] = \"aaaabbbcc\"; int n = strlen(str); // To store output char out[n]; if (rearrange(str, out, 2)) cout << out; else cout << \"Cannot be rearranged\"; return 0;}",
"e": 29636,
"s": 27601,
"text": null
},
{
"code": "// Java program to rearrange a string so that all same// characters become atleast d distance awayimport java.util.*; class GFG{ static int MAX_CHAR = 256; // The function returns next eligible character// with maximum frequency (Greedy!!) and// zero or negative distancestatic int nextChar(int freq[], int dist[]){ int max = Integer.MIN_VALUE; for (int i = 0; i < MAX_CHAR; i++) if (dist[i] <= 0 && freq[i] > 0 && (max == Integer.MIN_VALUE || freq[i] > freq[max])) max = i; return max;} // The main function that rearranges input string 'str'// such that two same characters become atleast d// distance awaystatic int rearrange(char str[], char out[], int d){ // Find length of input string int n = str.length; // Create an array to store all characters and their // frequencies in str[] int []freq = new int[MAX_CHAR]; // Traverse the input string and store frequencies // of all characters in freq[] array. for (int i = 0; i < n; i++) freq[str[i]]++; // Create an array for inserting the values at // correct distance dist[j] stores the least distance // between current position and the next position we // can use character 'j' int []dist = new int[MAX_CHAR]; for (int i = 0; i < n; i++) { // find next eligible character int j = nextChar(freq, dist); // return 0 if string cannot be rearranged if (j == Integer.MIN_VALUE) return 0; // Put character j at next position out[i] = (char) j; // decrease its frequency freq[j]--; // set distance as d dist[j] = d; // decrease distance of all characters by 1 for (int k = 0; k < MAX_CHAR; k++) dist[k]--; } // null terminate output string Arrays.copyOfRange(out, 0, n); // out[n] = '\\0'; // return success return 1;} // Driver codepublic static void main(String[] args){ char str[] = \"aaaabbbcc\".toCharArray(); int n = str.length; // To store output char []out = new char[n]; if (rearrange(str, out, 2)==1) System.out.println(String.valueOf(out)); else System.out.println(\"Cannot be rearranged\");}} // This code is contributed by Rajput-Ji",
"e": 31897,
"s": 29636,
"text": null
},
{
"code": "# Python3 program to rearrange a string so that all# same characters become at least d distance awayMAX_CHAR = 256 # The function returns next eligible character# with maximum frequency (Greedy!!)# and zero or negative distancedef nextChar(freq, dist): Max = float('-inf') for i in range(0, MAX_CHAR): if (dist[i] <= 0 and freq[i] > 0 and (Max == float('-inf') or freq[i] > freq[Max])): Max = i return Max # The main function that rearranges input# string 'str' such that two same characters# become atleast d distance awaydef rearrange(string, out, d): # Find length of input string n = len(string) # Create an array to store all characters # and their frequencies in str[] freq = [0] * MAX_CHAR # Traverse the input string and store frequencies # of all characters in freq[] array. for i in range(0, n): freq[ord(string[i])] += 1 # Create an array for inserting the values at # correct distance dist[j] stores the least # distance between current position and the # we next position can use character 'j' dist = [0] * MAX_CHAR for i in range(0, n): # find next eligible character j = nextChar(freq, dist) # return 0 if string cannot be rearranged if j == float('-inf'): return 0 # Put character j at next position out[i] = chr(j) # decrease its frequency freq[j] -= 1 # set distance as d dist[j] = d # decrease distance of all characters by 1 for i in range(0, MAX_CHAR): dist[i] -= 1 # return success return 1 # Driver codeif __name__ == \"__main__\": string = \"aaaabbbcc\" n = len(string) # To store output out = [None] * n if rearrange(string, out, 2): print(''.join(out)) else: print(\"Cannot be rearranged\") # This code is contributed by Rituraj Jain",
"e": 33803,
"s": 31897,
"text": null
},
{
"code": "// C# program to rearrange a string so that all same// characters become atleast d distance awayusing System; class GFG{ static int MAX_CHAR = 256; // The function returns next eligible character// with maximum frequency (Greedy!!) and// zero or negative distancestatic int nextChar(int []freq, int []dist){ int max = int.MinValue; for (int i = 0; i < MAX_CHAR; i++) if (dist[i] <= 0 && freq[i] > 0 && (max == int.MinValue || freq[i] > freq[max])) max = i; return max;} // The main function that rearranges input string 'str'// such that two same characters become atleast d// distance awaystatic int rearrange(char []str, char []ouT, int d){ // Find length of input string int n = str.Length; // Create an array to store all characters and their // frequencies in str[] int []freq = new int[MAX_CHAR]; // Traverse the input string and store frequencies // of all characters in freq[] array. for (int i = 0; i < n; i++) freq[str[i]]++; // Create an array for inserting the values at // correct distance dist[j] stores the least distance // between current position and the next position we // can use character 'j' int []dist = new int[MAX_CHAR]; for (int i = 0; i < n; i++) { // find next eligible character int j = nextChar(freq, dist); // return 0 if string cannot be rearranged if (j == int.MinValue) return 0; // Put character j at next position ouT[i] = (char) j; // decrease its frequency freq[j]--; // set distance as d dist[j] = d; // decrease distance of all characters by 1 for (int k = 0; k < MAX_CHAR; k++) dist[k]--; } // null terminate output string Array.Copy(ouT,ouT, n); // out[n] = '\\0'; // return success return 1;} // Driver codepublic static void Main(String[] args){ char []str = \"aaaabbbcc\".ToCharArray(); int n = str.Length; // To store output char []ouT = new char[n]; if (rearrange(str, ouT, 2)==1) Console.WriteLine(String.Join(\"\",ouT)); else Console.WriteLine(\"Cannot be rearranged\");}} // This code is contributed by 29AjayKumar",
"e": 36038,
"s": 33803,
"text": null
},
{
"code": "<script> // Javascript program to rearrange a// string so that all same characters// become atleast d distance awaylet MAX_CHAR = 256; // The function returns next eligible// character with maximum frequency// (Greedy!!) and zero or negative distancefunction nextChar(freq, dist){ let max = Number.MIN_VALUE; for(let i = 0; i < MAX_CHAR; i++) if (dist[i] <= 0 && freq[i] > 0 && (max == Number.MIN_VALUE || freq[i] > freq[max])) max = i; return max;} // The main function that rearranges input// string 'str' such that two same characters// become atleast d distance awayfunction rearrange(str, out, d){ // Find length of input string let n = str.length; // Create an array to store all characters // and their frequencies in str[] let freq = new Array(MAX_CHAR); for(let i = 0; i < freq.length; i++) { freq[i] = 0; } // Traverse the input string and store // frequencies of all characters in // freq[] array. for(let i = 0; i < n; i++) freq[str[i].charCodeAt(0)]++; // Create an array for inserting the // values at correct distance dist[j] // stores the least distance between // current position and the next position // we can use character 'j' let dist = new Array(MAX_CHAR); for(let i = 0; i < dist.length; i++) { dist[i] = 0; } for(let i = 0; i < n; i++) { // Find next eligible character let j = nextChar(freq, dist); // return 0 if string cannot // be rearranged if (j == Number.MIN_VALUE) return 0; // Put character j at next position out[i] = String.fromCharCode (j); // Decrease its frequency freq[j]--; // Set distance as d dist[j] = d; // Decrease distance of all // characters by 1 for(let k = 0; k < MAX_CHAR; k++) dist[k]--; } // Null terminate output string // Arrays.copyOfRange(out, 0, n); // out[n] = '\\0'; // Return success return 1;} // Driver codelet str= \"aaaabbbcc\".split(\"\");let n = str.length; // To store outputlet out = new Array(n); if (rearrange(str, out, 2) == 1) document.write(out.join(\"\"));else document.write(\"Cannot be rearranged\"); // This code is contributed by rag2127 </script>",
"e": 38392,
"s": 36038,
"text": null
},
{
"code": null,
"e": 38402,
"s": 38392,
"text": "Output : "
},
{
"code": null,
"e": 38412,
"s": 38402,
"text": "ababacabc"
},
{
"code": null,
"e": 38802,
"s": 38412,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 38815,
"s": 38802,
"text": "rituraj_jain"
},
{
"code": null,
"e": 38825,
"s": 38815,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38837,
"s": 38825,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38845,
"s": 38837,
"text": "rag2127"
},
{
"code": null,
"e": 38853,
"s": 38845,
"text": "Strings"
},
{
"code": null,
"e": 38861,
"s": 38853,
"text": "Strings"
},
{
"code": null,
"e": 38959,
"s": 38861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38968,
"s": 38959,
"text": "Comments"
},
{
"code": null,
"e": 38981,
"s": 38968,
"text": "Old Comments"
},
{
"code": null,
"e": 39026,
"s": 38981,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 39043,
"s": 39026,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 39086,
"s": 39043,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 39120,
"s": 39086,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 39161,
"s": 39120,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 39215,
"s": 39161,
"text": "Return maximum occurring character in an input string"
},
{
"code": null,
"e": 39253,
"s": 39215,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 39265,
"s": 39253,
"text": "Hill Cipher"
},
{
"code": null,
"e": 39280,
"s": 39265,
"text": "sprintf() in C"
}
] |
HTTP headers | Expect - GeeksforGeeks
|
18 Oct, 2019
The HTTP headers Expect request-header field is used to indicate specific behaviors or expectations that the server needs to fulfill in order to respond to the client. Generally, Expect: 100-continue is the only expectation defined for the header field. If the data provided in the header field meets the expectation value, then the server responds with 100 indicating that it is a success, else it responds with status 417 specifying that the expectation has failed. The reason behind putting the Expect, that would be to work around broken web servers.
Syntax:
Expect: 100-continue
Directives:
100-continue: It means that the server has received the request header and in order to send the request body, the server must respond with status 100 to the client.
Note: There is no need to put a blank header if you are not going to put any Expect clause.
Example:
PUT /demo/program HTTP/1.1
Host: original.sample.com
Content-Type: video/h264
Content-Length: 2342564178765
Expect: 100-continue
The server now goes through the request headers and either responds with 100 indicating the client to send the request body or return status 417 if the expectations are not met.
Supported Browsers: The browsers compatibility for HTTP headers Expect is unknown right now.
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
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 create footer to stay at the bottom of a Web page?
How to Insert Form Data into Database using PHP ?
How to redirect to another page in ReactJS ?
How to execute PHP code using command line ?
|
[
{
"code": null,
"e": 24666,
"s": 24638,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 25221,
"s": 24666,
"text": "The HTTP headers Expect request-header field is used to indicate specific behaviors or expectations that the server needs to fulfill in order to respond to the client. Generally, Expect: 100-continue is the only expectation defined for the header field. If the data provided in the header field meets the expectation value, then the server responds with 100 indicating that it is a success, else it responds with status 417 specifying that the expectation has failed. The reason behind putting the Expect, that would be to work around broken web servers."
},
{
"code": null,
"e": 25229,
"s": 25221,
"text": "Syntax:"
},
{
"code": null,
"e": 25250,
"s": 25229,
"text": "Expect: 100-continue"
},
{
"code": null,
"e": 25262,
"s": 25250,
"text": "Directives:"
},
{
"code": null,
"e": 25427,
"s": 25262,
"text": "100-continue: It means that the server has received the request header and in order to send the request body, the server must respond with status 100 to the client."
},
{
"code": null,
"e": 25519,
"s": 25427,
"text": "Note: There is no need to put a blank header if you are not going to put any Expect clause."
},
{
"code": null,
"e": 25528,
"s": 25519,
"text": "Example:"
},
{
"code": null,
"e": 25657,
"s": 25528,
"text": "PUT /demo/program HTTP/1.1\nHost: original.sample.com\nContent-Type: video/h264\nContent-Length: 2342564178765\nExpect: 100-continue"
},
{
"code": null,
"e": 25835,
"s": 25657,
"text": "The server now goes through the request headers and either responds with 100 indicating the client to send the request body or return status 417 if the expectations are not met."
},
{
"code": null,
"e": 25928,
"s": 25835,
"text": "Supported Browsers: The browsers compatibility for HTTP headers Expect is unknown right now."
},
{
"code": null,
"e": 25941,
"s": 25928,
"text": "HTTP-headers"
},
{
"code": null,
"e": 25948,
"s": 25941,
"text": "Picked"
},
{
"code": null,
"e": 25965,
"s": 25948,
"text": "Web Technologies"
},
{
"code": null,
"e": 26063,
"s": 25965,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26072,
"s": 26063,
"text": "Comments"
},
{
"code": null,
"e": 26085,
"s": 26072,
"text": "Old Comments"
},
{
"code": null,
"e": 26127,
"s": 26085,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26170,
"s": 26127,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26214,
"s": 26170,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 26259,
"s": 26214,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26320,
"s": 26259,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26392,
"s": 26320,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26450,
"s": 26392,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26500,
"s": 26450,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26545,
"s": 26500,
"text": "How to redirect to another page in ReactJS ?"
}
] |
How to generate an UnsupportedOperationException in Java?
|
An UnsupportedOperationException is a subclass of RuntimException in Java and it can be thrown to indicate that the requested operation is not supported. The UnsupportedOperationException class is a member of the Java Collections Framework. This exception is thrown by almost all of the concrete collections like List, Queue, Set and Map.
public class UnsupportedOperationException extends RuntimeException
import java.util.*;
public class UnsupportedOperationExceptionTest {
public static void main(String[] args) {
List aList = new ArrayList();
aList.add('a');
aList.add('b');
List newList = Collections.unmodifiableList(aList);
newList.add('c');
}
}
In the above example, it will generate an UnsupportedOperationException. In order to avoid this, we need to use the object of the collection rather than using the view object for modification.
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
at UnsupportedOperationExceptionTest.main(UnsupportedOperationExceptionTest.java:9)
|
[
{
"code": null,
"e": 1401,
"s": 1062,
"text": "An UnsupportedOperationException is a subclass of RuntimException in Java and it can be thrown to indicate that the requested operation is not supported. The UnsupportedOperationException class is a member of the Java Collections Framework. This exception is thrown by almost all of the concrete collections like List, Queue, Set and Map."
},
{
"code": null,
"e": 1469,
"s": 1401,
"text": "public class UnsupportedOperationException extends RuntimeException"
},
{
"code": null,
"e": 1751,
"s": 1469,
"text": "import java.util.*;\npublic class UnsupportedOperationExceptionTest {\n public static void main(String[] args) {\n List aList = new ArrayList();\n aList.add('a');\n aList.add('b');\n List newList = Collections.unmodifiableList(aList);\n newList.add('c');\n }\n}"
},
{
"code": null,
"e": 1944,
"s": 1751,
"text": "In the above example, it will generate an UnsupportedOperationException. In order to avoid this, we need to use the object of the collection rather than using the view object for modification."
},
{
"code": null,
"e": 2177,
"s": 1944,
"text": "Exception in thread \"main\" java.lang.UnsupportedOperationException\n at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)\n at UnsupportedOperationExceptionTest.main(UnsupportedOperationExceptionTest.java:9)"
}
] |
“ TIME SERIES ANALYSIS USING NEURAL NETWORK ” | by Ashis Kumar Panda | Towards Data Science
|
Welcome to the Fourth Episode of Fastdotai where we will deal with Structured and time series data. Before we start , I would like to thank Jeremy Howard and Rachel Thomas for their efforts to democratize AI.
To make best out of this blog post Series , feel free to explore the first Part of this Series in the following order:-Dog Vs Cat Image Classification
Dog Breed Image ClassificationMulti-label Image ClassificationTime Series Analysis using Neural NetworkNLP- Sentiment Analysis on IMDB Movie DatasetBasic of Movie Recommendation SystemCollaborative Filtering from ScratchCollaborative Filtering using Neural NetworkWriting Philosophy like NietzschePerformance of Different Neural Network on Cifar-10 datasetML Model to detect the biggest object in an image Part-1ML Model to detect the biggest object in an image Part-2
Dog Breed Image Classification
Multi-label Image Classification
Time Series Analysis using Neural Network
NLP- Sentiment Analysis on IMDB Movie Dataset
Basic of Movie Recommendation System
Collaborative Filtering from Scratch
Collaborative Filtering using Neural Network
Writing Philosophy like Nietzsche
Performance of Different Neural Network on Cifar-10 dataset
ML Model to detect the biggest object in an image Part-1
ML Model to detect the biggest object in an image Part-2
The notebook that we will discuss is an implementation of the third place result in the Rossman Kaggle competition as detailed in Guo/Berkhahn’s [Entity Embeddings of Categorical Variables]. The code has been executed with the help of kaggle kernel . So there would be couple of extra stuffs which has been written so as the code would run smoothly on kaggle. These extra lines of code might not be necessary , if you run your code in any other cloud GPU platform . I will attach the kaggle kernel link at the end of this blog post.
As said in the above code snippets ,we will be having additional datasets which will help us to enrich the features and hence will help us to get better accuracy. These datasets which makes up the feature space are as mentioned below.
Feature Space Involves:
train: Contains store information on a daily basis, tracks things like sales, customers, whether that day was a holiday, etc.
store: List of stores. General information about the store including competition, etc.
store_states: Mapping of store to the German state they are in.
googletrend: Trend of certain google keywords over time, found by users to correlate well with given data.
weather: Weather conditions for each state.
test: Same as training table, without sales and customers.
Lets save these data file names in a specific list as shown below:-
We can use head() to get a quick look at the contents of each table:
Data Cleaning / Feature Engineering:-
In the following code snippets we will be doing Data Cleaning:-
Before moving forward lets have a look at googletrends data, as we will be doing Feature Engineering on this next.
Lets have a look at googletrend after Feature Engineering. Check out the new column Date ,State and changes made to State column.
The following step is really important for feature engineering:-
As we can see in the snapshot below, we have got so much more column added to googletrends which are formed out of Date column using the above command.
In the above code snippet , joined is our training data and joined_test is our test data. As we know a picture is worth 1000 words . Let me describe the flowchart of how we end up with train data — joined and test data — joined_test by merging multiple tables. The following snapshot is same for joined and joined_test .
COMPARISON OF BEFORE DROPPING AND AFTER DROPPING EXTRA VARIABLES
As we can see in the code below, we will fill in missing values that are present in train data — joined and test data — joined_test .
The output looks like :-
In the code below we are replacing the outliers and doing some more feature engineering .
Same feature engineering for Promo dates.
LET’S FOCUS ON DURATION:-
You are almost half way through this article . Great job. Keep going . Its gonna be interesting from here.
Now ,let’s focus on Categorical and Continuous variables.
DECIDING WHICH VARIABLE TO BE CATEGORICAL OR CONTINUOUS ?
In the code above , we have separated the columns which we will be considering as continuous and categorical . But How ? This needs a detailed explanation .
So a column/variable is said to be continuous or categorical based on the CARDINALITY of that column/variable. CARDINALITY is defined as number of levels in a category. e.g CARDINALITY for the days of a week =7
Whichever variables are already present in data in categorical form will be categorical variables in the models.
Rest for Continuous variables , we have to check for their cardinality . If their cardinality(number of distinct levels) is too high, it will be continuous else it will be converted into categorical variables.
A continuous variable should have a continuous and smoothish function . For e.g year , although a continuous variable but don’t have many distinct level, hence it would be better to make it as a categorical variable. In this case , continuous ones are the ones that are of type floating point or having int as data type.
We can bin a continuous variable and then convert it into a categorical variable. Sometimes binning can be very helpful.
Which variables are categorical and which are continuous variable is one of the modelling decision we have to make.
At this point of time , our data looks like this. It has some continuous , some Boolean , some categorical and so.
In the code above, Fastai has a function named as process_dataframe(proc_df) .
It pulls out the dependent variable i.e ‘Sales’ from the dataframe ‘joined_samp’ and stores it in a separate variable y .
The rest of the dataframe excluding the dependent variable ‘Sales’ is saved in df.
nas: returns a dictionary of which nas it created, and the associated median.
mapper: A DataFrameMapper which stores the mean and standard deviation of the corresponding continuous variables which is then used for scaling of during test-time.
It also handles missing values , so missing values in categorical variables become 0 and other categories becomes 1,2 3,4 and so on.
For continuous variables , it replaces missing values with median and creates a new column as boolean which says if its missing or not.
The output df has all the variable as continuous now. The categorical columns are represented by equivalent continuous values.Check out how the year and Assortment column changed before and after.
In this way we have all the columns as continuous .
The continuous columns remains the same . They have been changed to float32 as that’s standard numerical data type that pytorch accepts.
The Categorical column gets converted into equivalent Continuous type.
VALIDATION DATASET
The problem statement we have in Rossman data as per Kaggle is to predict next two weeks of Sales .Since its a Time -Series Data , our validation dataset isn’t random. Instead it is the most recent data as it would be in our real application.
DEEP LEARNING STARTS HERE .
As per the Kaggle rules of Rossman data Competition , we will be evaluated on the basis of RMSPE(Root Mean Square Percentage Error).
RMSPE will be the metrics instead of accuracy so we have formulated that in the code below:-
Lets create our model Data object :-
Earlier it was ImageClassifierData as we were dealing with Images back then . Now in this case, its ColumnarModelData as we are dealing with Columnar table data.
Instead of from_Paths we have from_data_frame .
PATH — where to store the model file.
val_idx — List of indexes of rows to be put in validation dataset.
df — data frame .
y1 — consist of the dependent variable.
cat_flds — Which all columns to be treated as Categorical variables , as by this time all the columns are converted into numerical.
bs — batch size.
APPLY EMBEDDINGS TO CATEGORICAL VARIABLES:
What the above code does is, it goes through every categorical variables (cat_vars) and prints out the number of distinct levels or categories it has .The +1 with categories in the code above , is reserved for missing values. Basically it prints the cardinality of each variable along with the variable name.
We use the cardinality of each variable to decide how large its embedding matrix should be .
In the code above we go by a rule of thumb which denotes that the embedding size is cardinality size//2 but no bigger than 50.
HOW EMBEDDING MATRICES WORKS?
When we create these matrices , it has random numbers . So we put them in a Neural Network and keep updating their values so as to reduce a Loss Function. These embedding matrices can be compared to a bunch of weights which updates themselves in such a way that reduces Loss. In this way we go from random values for these weights to an updated value that makes some sense.
To put things into perspective , an embedding matrix is something that can have value which is between 0 and the maximum number of levels in that category. We can then index that matrix to find a particular row and we append it to all of our continuous variables and everything after that is just the same as before .
PICTORIAL REPRESENTATION OF EMBEDDING MATRIX:-
APPLYING NEURAL NETWORK TO CONTINUOUS VARIABLES:-
The above diagram shows how Neural Network deals with continuous variables. Check out how the matrix multiplication works and results in the corresponding output. This is a 2 hidden layer Neural Network. Suppose there are 20 columns as inputs and we have designed the Neural Network so that the 1st hidden layer has 100 hidden units and the 2nd hidden layer has 50 hidden units. So our input [1,20] is multiplied with weight matrix of dimension [20,100] which will result to [1,100] . We then apply ReLU to this [1,100] dimension values, which results in activation of [1,100]. This [1,100] dimension activations are then multiplied with weights of dimension [100,50] , which results in activation with dimensions of [1,50]. This [1,50] activation is then multiplied with weight of dimension [50,1] which result in 1 output . We apply Softmax on the last layer to get the final output.
NOTE :- Never put ReLU in the last layer as Softmax needs negative values to create lower probabilities . ReLU function gets rid of the negative values . In this case of Rossman sales data , we are trying to predict Sales , hence we don’t need Softmax at the end .
Let’s create our learner . This is how we are setting up our Neural Network.
Parameters used in get_learner() .
emb_s — Use this embedding matrix for every categorical variable.
len(df.columns)-len(cat_vars) — Denotes the number of Continuous variables.
0.04 — Dropout at the very start.
1 — output of the last linear layer.
[1000,500] — Number of activation in the first and second linear layer.
[0.001,0.01] — Dropouts used in the first and second linear layer.
y_range=y_range — Has been described earlier.
tmp_name=f”{PATH_WRITE}tmp” — (optional) To be used only in kaggle kernels.
models_name=f”{PATH_WRITE}models” — (optional) To be used only in kaggle kernels.
??? ANY QUESTIONS ???
Qs 1 :- What does the four value in the week embedding denotes?
Initially we start with some random four values . It function the same way as the weights . So we update these values while minimizing the Loss . When the Loss has been minimized , we will end up with some updated four values. At this point of time , we will find that these particular parameters are human interpretable and are quite interesting.
Qs 2 :- Is there any way to initialize embedding matrices besides random initialization?
If there is an pre-trained embedding matrix for Cheese Sales at Rossman , we can use that embedding matrix for predicting liquor Sales. This technique is being used in instacart and pinterest .They have embedding matrix of products and stores that gets shared within the organization so that people don’t have to train new ones.
Qs 3 :- What’s the advantage of using Embedding matrices over One-Hot Encoding?
Take for e.g Sunday’s one hot encoded vector:-
[1 0 0 0 0 0 0]
The problem with the One-hot encoding representation of Sunday is that it represents a single floating point number. It represents a single thing. More of a linear behavior .
With embeddings , Sunday is a concept of 4-d space. What we get after updating these values are rich semantic concepts . For example , if it turns out that weekends have different behavior as compared to weekdays, then we see that certain value for Saturday and Sunday in this embedding matrix would be higher . By having these high dimensionality vector , we give a chance to the Neural Network to learn these underlying rich representations. It’s the rich representation that allows it to learn such interesting relationships. This idea of representing embedding is known as “distributed representation”. Neural Network has a high dimensional representation which is sometimes hard to interpret . These numbers in this matrix doesn’t have to have just one meaning . It could change its meaning with the context because its going through the rich non-linear functions.
Although one hot encoding is having more dimension in case of Days of Week , its not meaningfully high dimension . The use of Embedding matrix helps in reducing the size as well as represent the variable more appropriately.
Qs 3:- Are embeddings suitable for certain type of variables?
We use the concept of embedding when we come across Categorical Variables. But it won’t work when it comes to variables with high cardinality.
Qs 4:- How does the add_datepart() affects seasonality?
The fastai library has an add_datepart() function which takes a dataframe and its column which represents date . It optionally removes that date column and instead of that returns lots of columns which denotes useful information about that date. For e.g it replaces Date with dayOfWeek, MonthOfYear, Year, Month, Week, Day etc etc. So daysOFWeek can be represented now in a [8,4] embedding matrix. Conceptually , this allows the models to pick some interesting characteristics and patterns .
Suppose , there is something with a 7 day period cycle and that goes up in Monday and down on Thursday and only in Berlin , it can totally extract that pattern as it has all the information it needs. Its a nice way to deal with Time Series Models. We just need to make sure that the cycle indicator or periodicity in our time Series Model should exist as a column.
Develop the learner and get the best learning rate using the below commands.
As we can see the best learning rate is somewhere at 10^-3. So we will proceed with training our Neural Network with lr=10^-3.
m.fit(lr, 3, metrics=[exp_rmspe])[ 0. 0.02479 0.02205 0.19309] [ 1. 0.02044 0.01751 0.18301] [ 2. 0.01598 0.01571 0.17248]m.fit(lr, 5, metrics=[exp_rmspe], cycle_len=1)[ 0. 0.01258 0.01278 0.16 ] [ 1. 0.01147 0.01214 0.15758] [ 2. 0.01157 0.01157 0.15585] [ 3. 0.00984 0.01124 0.15251] [ 4. 0.00946 0.01094 0.15197]m.fit(lr, 2, metrics=[exp_rmspe], cycle_len=4)[ 0. 0.01179 0.01242 0.15512] [ 1. 0.00921 0.01098 0.15003] [ 2. 0.00771 0.01031 0.14431] [ 3. 0.00632 0.01016 0.14358] [ 4. 0.01003 0.01305 0.16574] [ 5. 0.00827 0.01087 0.14937] [ 6. 0.00628 0.01025 0.14506] [ 7. 0.0053 0.01 0.14449]
Note:- Switching from gradient boosting to deep learning is good as it requires less feature engineering and it is a simpler model which requires less maintenence . This is one of the big benifits of using an approach to deep learning Using this we can get SoTA results but with lots of less work.
SUMMARY:-
Step 1:- List categorical variables names and list continuous variable names and put them in data frame.
Step 2:- Create a list of row_indexes we want in validation set.
Step 3:- Creation of columnar model data object.
Step 4:- Create a list of how big we want the embedding matrix to be.
Step 5:- Call get_learner and use the exact parameters to get started with.
Step 6:- Call m.fit()
I’ve used the kernels mentioned in this blogpost by William Horton .
!!! Congratulations on completing another Lesson on fast.ai . Well done . !!!
If you like it , then ABC (Always be clapping . 👏 👏👏👏👏😃😃😃😃😃😃😃😃😃👏 👏👏👏👏👏)
If you have any questions, feel free to reach out on the fast.ai forums or on Twitter:@ashiskumarpanda
P.S. -This blog post will be updated and improved as I further continue with other lessons. For more interesting stuff , Feel free to checkout my Github account.
To make best out of this blog post Series , feel free to explore the first Part of this Series in the following order:-
Dog Vs Cat Image ClassificationDog Breed Image ClassificationMulti-label Image ClassificationTime Series Analysis using Neural NetworkNLP- Sentiment Analysis on IMDB Movie DatasetBasic of Movie Recommendation SystemCollaborative Filtering from ScratchCollaborative Filtering using Neural NetworkWriting Philosophy like NietzschePerformance of Different Neural Network on Cifar-10 datasetML Model to detect the biggest object in an image Part-1ML Model to detect the biggest object in an image Part-2
Dog Vs Cat Image Classification
Dog Breed Image Classification
Multi-label Image Classification
Time Series Analysis using Neural Network
NLP- Sentiment Analysis on IMDB Movie Dataset
Basic of Movie Recommendation System
Collaborative Filtering from Scratch
Collaborative Filtering using Neural Network
Writing Philosophy like Nietzsche
Performance of Different Neural Network on Cifar-10 dataset
ML Model to detect the biggest object in an image Part-1
ML Model to detect the biggest object in an image Part-2
Edit 1:- TFW Jeremy Howard approves of your post . 💖💖 🙌🙌🙌 💖💖 .
|
[
{
"code": null,
"e": 381,
"s": 172,
"text": "Welcome to the Fourth Episode of Fastdotai where we will deal with Structured and time series data. Before we start , I would like to thank Jeremy Howard and Rachel Thomas for their efforts to democratize AI."
},
{
"code": null,
"e": 532,
"s": 381,
"text": "To make best out of this blog post Series , feel free to explore the first Part of this Series in the following order:-Dog Vs Cat Image Classification"
},
{
"code": null,
"e": 1001,
"s": 532,
"text": "Dog Breed Image ClassificationMulti-label Image ClassificationTime Series Analysis using Neural NetworkNLP- Sentiment Analysis on IMDB Movie DatasetBasic of Movie Recommendation SystemCollaborative Filtering from ScratchCollaborative Filtering using Neural NetworkWriting Philosophy like NietzschePerformance of Different Neural Network on Cifar-10 datasetML Model to detect the biggest object in an image Part-1ML Model to detect the biggest object in an image Part-2"
},
{
"code": null,
"e": 1032,
"s": 1001,
"text": "Dog Breed Image Classification"
},
{
"code": null,
"e": 1065,
"s": 1032,
"text": "Multi-label Image Classification"
},
{
"code": null,
"e": 1107,
"s": 1065,
"text": "Time Series Analysis using Neural Network"
},
{
"code": null,
"e": 1153,
"s": 1107,
"text": "NLP- Sentiment Analysis on IMDB Movie Dataset"
},
{
"code": null,
"e": 1190,
"s": 1153,
"text": "Basic of Movie Recommendation System"
},
{
"code": null,
"e": 1227,
"s": 1190,
"text": "Collaborative Filtering from Scratch"
},
{
"code": null,
"e": 1272,
"s": 1227,
"text": "Collaborative Filtering using Neural Network"
},
{
"code": null,
"e": 1306,
"s": 1272,
"text": "Writing Philosophy like Nietzsche"
},
{
"code": null,
"e": 1366,
"s": 1306,
"text": "Performance of Different Neural Network on Cifar-10 dataset"
},
{
"code": null,
"e": 1423,
"s": 1366,
"text": "ML Model to detect the biggest object in an image Part-1"
},
{
"code": null,
"e": 1480,
"s": 1423,
"text": "ML Model to detect the biggest object in an image Part-2"
},
{
"code": null,
"e": 2013,
"s": 1480,
"text": "The notebook that we will discuss is an implementation of the third place result in the Rossman Kaggle competition as detailed in Guo/Berkhahn’s [Entity Embeddings of Categorical Variables]. The code has been executed with the help of kaggle kernel . So there would be couple of extra stuffs which has been written so as the code would run smoothly on kaggle. These extra lines of code might not be necessary , if you run your code in any other cloud GPU platform . I will attach the kaggle kernel link at the end of this blog post."
},
{
"code": null,
"e": 2248,
"s": 2013,
"text": "As said in the above code snippets ,we will be having additional datasets which will help us to enrich the features and hence will help us to get better accuracy. These datasets which makes up the feature space are as mentioned below."
},
{
"code": null,
"e": 2272,
"s": 2248,
"text": "Feature Space Involves:"
},
{
"code": null,
"e": 2398,
"s": 2272,
"text": "train: Contains store information on a daily basis, tracks things like sales, customers, whether that day was a holiday, etc."
},
{
"code": null,
"e": 2485,
"s": 2398,
"text": "store: List of stores. General information about the store including competition, etc."
},
{
"code": null,
"e": 2549,
"s": 2485,
"text": "store_states: Mapping of store to the German state they are in."
},
{
"code": null,
"e": 2656,
"s": 2549,
"text": "googletrend: Trend of certain google keywords over time, found by users to correlate well with given data."
},
{
"code": null,
"e": 2700,
"s": 2656,
"text": "weather: Weather conditions for each state."
},
{
"code": null,
"e": 2759,
"s": 2700,
"text": "test: Same as training table, without sales and customers."
},
{
"code": null,
"e": 2827,
"s": 2759,
"text": "Lets save these data file names in a specific list as shown below:-"
},
{
"code": null,
"e": 2896,
"s": 2827,
"text": "We can use head() to get a quick look at the contents of each table:"
},
{
"code": null,
"e": 2934,
"s": 2896,
"text": "Data Cleaning / Feature Engineering:-"
},
{
"code": null,
"e": 2998,
"s": 2934,
"text": "In the following code snippets we will be doing Data Cleaning:-"
},
{
"code": null,
"e": 3113,
"s": 2998,
"text": "Before moving forward lets have a look at googletrends data, as we will be doing Feature Engineering on this next."
},
{
"code": null,
"e": 3243,
"s": 3113,
"text": "Lets have a look at googletrend after Feature Engineering. Check out the new column Date ,State and changes made to State column."
},
{
"code": null,
"e": 3308,
"s": 3243,
"text": "The following step is really important for feature engineering:-"
},
{
"code": null,
"e": 3460,
"s": 3308,
"text": "As we can see in the snapshot below, we have got so much more column added to googletrends which are formed out of Date column using the above command."
},
{
"code": null,
"e": 3781,
"s": 3460,
"text": "In the above code snippet , joined is our training data and joined_test is our test data. As we know a picture is worth 1000 words . Let me describe the flowchart of how we end up with train data — joined and test data — joined_test by merging multiple tables. The following snapshot is same for joined and joined_test ."
},
{
"code": null,
"e": 3846,
"s": 3781,
"text": "COMPARISON OF BEFORE DROPPING AND AFTER DROPPING EXTRA VARIABLES"
},
{
"code": null,
"e": 3980,
"s": 3846,
"text": "As we can see in the code below, we will fill in missing values that are present in train data — joined and test data — joined_test ."
},
{
"code": null,
"e": 4005,
"s": 3980,
"text": "The output looks like :-"
},
{
"code": null,
"e": 4095,
"s": 4005,
"text": "In the code below we are replacing the outliers and doing some more feature engineering ."
},
{
"code": null,
"e": 4137,
"s": 4095,
"text": "Same feature engineering for Promo dates."
},
{
"code": null,
"e": 4163,
"s": 4137,
"text": "LET’S FOCUS ON DURATION:-"
},
{
"code": null,
"e": 4270,
"s": 4163,
"text": "You are almost half way through this article . Great job. Keep going . Its gonna be interesting from here."
},
{
"code": null,
"e": 4328,
"s": 4270,
"text": "Now ,let’s focus on Categorical and Continuous variables."
},
{
"code": null,
"e": 4386,
"s": 4328,
"text": "DECIDING WHICH VARIABLE TO BE CATEGORICAL OR CONTINUOUS ?"
},
{
"code": null,
"e": 4543,
"s": 4386,
"text": "In the code above , we have separated the columns which we will be considering as continuous and categorical . But How ? This needs a detailed explanation ."
},
{
"code": null,
"e": 4754,
"s": 4543,
"text": "So a column/variable is said to be continuous or categorical based on the CARDINALITY of that column/variable. CARDINALITY is defined as number of levels in a category. e.g CARDINALITY for the days of a week =7"
},
{
"code": null,
"e": 4867,
"s": 4754,
"text": "Whichever variables are already present in data in categorical form will be categorical variables in the models."
},
{
"code": null,
"e": 5077,
"s": 4867,
"text": "Rest for Continuous variables , we have to check for their cardinality . If their cardinality(number of distinct levels) is too high, it will be continuous else it will be converted into categorical variables."
},
{
"code": null,
"e": 5398,
"s": 5077,
"text": "A continuous variable should have a continuous and smoothish function . For e.g year , although a continuous variable but don’t have many distinct level, hence it would be better to make it as a categorical variable. In this case , continuous ones are the ones that are of type floating point or having int as data type."
},
{
"code": null,
"e": 5519,
"s": 5398,
"text": "We can bin a continuous variable and then convert it into a categorical variable. Sometimes binning can be very helpful."
},
{
"code": null,
"e": 5635,
"s": 5519,
"text": "Which variables are categorical and which are continuous variable is one of the modelling decision we have to make."
},
{
"code": null,
"e": 5750,
"s": 5635,
"text": "At this point of time , our data looks like this. It has some continuous , some Boolean , some categorical and so."
},
{
"code": null,
"e": 5829,
"s": 5750,
"text": "In the code above, Fastai has a function named as process_dataframe(proc_df) ."
},
{
"code": null,
"e": 5951,
"s": 5829,
"text": "It pulls out the dependent variable i.e ‘Sales’ from the dataframe ‘joined_samp’ and stores it in a separate variable y ."
},
{
"code": null,
"e": 6034,
"s": 5951,
"text": "The rest of the dataframe excluding the dependent variable ‘Sales’ is saved in df."
},
{
"code": null,
"e": 6112,
"s": 6034,
"text": "nas: returns a dictionary of which nas it created, and the associated median."
},
{
"code": null,
"e": 6277,
"s": 6112,
"text": "mapper: A DataFrameMapper which stores the mean and standard deviation of the corresponding continuous variables which is then used for scaling of during test-time."
},
{
"code": null,
"e": 6410,
"s": 6277,
"text": "It also handles missing values , so missing values in categorical variables become 0 and other categories becomes 1,2 3,4 and so on."
},
{
"code": null,
"e": 6546,
"s": 6410,
"text": "For continuous variables , it replaces missing values with median and creates a new column as boolean which says if its missing or not."
},
{
"code": null,
"e": 6743,
"s": 6546,
"text": "The output df has all the variable as continuous now. The categorical columns are represented by equivalent continuous values.Check out how the year and Assortment column changed before and after."
},
{
"code": null,
"e": 6795,
"s": 6743,
"text": "In this way we have all the columns as continuous ."
},
{
"code": null,
"e": 6932,
"s": 6795,
"text": "The continuous columns remains the same . They have been changed to float32 as that’s standard numerical data type that pytorch accepts."
},
{
"code": null,
"e": 7003,
"s": 6932,
"text": "The Categorical column gets converted into equivalent Continuous type."
},
{
"code": null,
"e": 7022,
"s": 7003,
"text": "VALIDATION DATASET"
},
{
"code": null,
"e": 7265,
"s": 7022,
"text": "The problem statement we have in Rossman data as per Kaggle is to predict next two weeks of Sales .Since its a Time -Series Data , our validation dataset isn’t random. Instead it is the most recent data as it would be in our real application."
},
{
"code": null,
"e": 7293,
"s": 7265,
"text": "DEEP LEARNING STARTS HERE ."
},
{
"code": null,
"e": 7426,
"s": 7293,
"text": "As per the Kaggle rules of Rossman data Competition , we will be evaluated on the basis of RMSPE(Root Mean Square Percentage Error)."
},
{
"code": null,
"e": 7519,
"s": 7426,
"text": "RMSPE will be the metrics instead of accuracy so we have formulated that in the code below:-"
},
{
"code": null,
"e": 7556,
"s": 7519,
"text": "Lets create our model Data object :-"
},
{
"code": null,
"e": 7718,
"s": 7556,
"text": "Earlier it was ImageClassifierData as we were dealing with Images back then . Now in this case, its ColumnarModelData as we are dealing with Columnar table data."
},
{
"code": null,
"e": 7766,
"s": 7718,
"text": "Instead of from_Paths we have from_data_frame ."
},
{
"code": null,
"e": 7804,
"s": 7766,
"text": "PATH — where to store the model file."
},
{
"code": null,
"e": 7871,
"s": 7804,
"text": "val_idx — List of indexes of rows to be put in validation dataset."
},
{
"code": null,
"e": 7889,
"s": 7871,
"text": "df — data frame ."
},
{
"code": null,
"e": 7929,
"s": 7889,
"text": "y1 — consist of the dependent variable."
},
{
"code": null,
"e": 8061,
"s": 7929,
"text": "cat_flds — Which all columns to be treated as Categorical variables , as by this time all the columns are converted into numerical."
},
{
"code": null,
"e": 8078,
"s": 8061,
"text": "bs — batch size."
},
{
"code": null,
"e": 8121,
"s": 8078,
"text": "APPLY EMBEDDINGS TO CATEGORICAL VARIABLES:"
},
{
"code": null,
"e": 8430,
"s": 8121,
"text": "What the above code does is, it goes through every categorical variables (cat_vars) and prints out the number of distinct levels or categories it has .The +1 with categories in the code above , is reserved for missing values. Basically it prints the cardinality of each variable along with the variable name."
},
{
"code": null,
"e": 8523,
"s": 8430,
"text": "We use the cardinality of each variable to decide how large its embedding matrix should be ."
},
{
"code": null,
"e": 8650,
"s": 8523,
"text": "In the code above we go by a rule of thumb which denotes that the embedding size is cardinality size//2 but no bigger than 50."
},
{
"code": null,
"e": 8680,
"s": 8650,
"text": "HOW EMBEDDING MATRICES WORKS?"
},
{
"code": null,
"e": 9054,
"s": 8680,
"text": "When we create these matrices , it has random numbers . So we put them in a Neural Network and keep updating their values so as to reduce a Loss Function. These embedding matrices can be compared to a bunch of weights which updates themselves in such a way that reduces Loss. In this way we go from random values for these weights to an updated value that makes some sense."
},
{
"code": null,
"e": 9372,
"s": 9054,
"text": "To put things into perspective , an embedding matrix is something that can have value which is between 0 and the maximum number of levels in that category. We can then index that matrix to find a particular row and we append it to all of our continuous variables and everything after that is just the same as before ."
},
{
"code": null,
"e": 9419,
"s": 9372,
"text": "PICTORIAL REPRESENTATION OF EMBEDDING MATRIX:-"
},
{
"code": null,
"e": 9469,
"s": 9419,
"text": "APPLYING NEURAL NETWORK TO CONTINUOUS VARIABLES:-"
},
{
"code": null,
"e": 10355,
"s": 9469,
"text": "The above diagram shows how Neural Network deals with continuous variables. Check out how the matrix multiplication works and results in the corresponding output. This is a 2 hidden layer Neural Network. Suppose there are 20 columns as inputs and we have designed the Neural Network so that the 1st hidden layer has 100 hidden units and the 2nd hidden layer has 50 hidden units. So our input [1,20] is multiplied with weight matrix of dimension [20,100] which will result to [1,100] . We then apply ReLU to this [1,100] dimension values, which results in activation of [1,100]. This [1,100] dimension activations are then multiplied with weights of dimension [100,50] , which results in activation with dimensions of [1,50]. This [1,50] activation is then multiplied with weight of dimension [50,1] which result in 1 output . We apply Softmax on the last layer to get the final output."
},
{
"code": null,
"e": 10620,
"s": 10355,
"text": "NOTE :- Never put ReLU in the last layer as Softmax needs negative values to create lower probabilities . ReLU function gets rid of the negative values . In this case of Rossman sales data , we are trying to predict Sales , hence we don’t need Softmax at the end ."
},
{
"code": null,
"e": 10697,
"s": 10620,
"text": "Let’s create our learner . This is how we are setting up our Neural Network."
},
{
"code": null,
"e": 10732,
"s": 10697,
"text": "Parameters used in get_learner() ."
},
{
"code": null,
"e": 10798,
"s": 10732,
"text": "emb_s — Use this embedding matrix for every categorical variable."
},
{
"code": null,
"e": 10874,
"s": 10798,
"text": "len(df.columns)-len(cat_vars) — Denotes the number of Continuous variables."
},
{
"code": null,
"e": 10908,
"s": 10874,
"text": "0.04 — Dropout at the very start."
},
{
"code": null,
"e": 10945,
"s": 10908,
"text": "1 — output of the last linear layer."
},
{
"code": null,
"e": 11017,
"s": 10945,
"text": "[1000,500] — Number of activation in the first and second linear layer."
},
{
"code": null,
"e": 11084,
"s": 11017,
"text": "[0.001,0.01] — Dropouts used in the first and second linear layer."
},
{
"code": null,
"e": 11130,
"s": 11084,
"text": "y_range=y_range — Has been described earlier."
},
{
"code": null,
"e": 11206,
"s": 11130,
"text": "tmp_name=f”{PATH_WRITE}tmp” — (optional) To be used only in kaggle kernels."
},
{
"code": null,
"e": 11288,
"s": 11206,
"text": "models_name=f”{PATH_WRITE}models” — (optional) To be used only in kaggle kernels."
},
{
"code": null,
"e": 11310,
"s": 11288,
"text": "??? ANY QUESTIONS ???"
},
{
"code": null,
"e": 11374,
"s": 11310,
"text": "Qs 1 :- What does the four value in the week embedding denotes?"
},
{
"code": null,
"e": 11722,
"s": 11374,
"text": "Initially we start with some random four values . It function the same way as the weights . So we update these values while minimizing the Loss . When the Loss has been minimized , we will end up with some updated four values. At this point of time , we will find that these particular parameters are human interpretable and are quite interesting."
},
{
"code": null,
"e": 11811,
"s": 11722,
"text": "Qs 2 :- Is there any way to initialize embedding matrices besides random initialization?"
},
{
"code": null,
"e": 12140,
"s": 11811,
"text": "If there is an pre-trained embedding matrix for Cheese Sales at Rossman , we can use that embedding matrix for predicting liquor Sales. This technique is being used in instacart and pinterest .They have embedding matrix of products and stores that gets shared within the organization so that people don’t have to train new ones."
},
{
"code": null,
"e": 12220,
"s": 12140,
"text": "Qs 3 :- What’s the advantage of using Embedding matrices over One-Hot Encoding?"
},
{
"code": null,
"e": 12267,
"s": 12220,
"text": "Take for e.g Sunday’s one hot encoded vector:-"
},
{
"code": null,
"e": 12283,
"s": 12267,
"text": "[1 0 0 0 0 0 0]"
},
{
"code": null,
"e": 12458,
"s": 12283,
"text": "The problem with the One-hot encoding representation of Sunday is that it represents a single floating point number. It represents a single thing. More of a linear behavior ."
},
{
"code": null,
"e": 13328,
"s": 12458,
"text": "With embeddings , Sunday is a concept of 4-d space. What we get after updating these values are rich semantic concepts . For example , if it turns out that weekends have different behavior as compared to weekdays, then we see that certain value for Saturday and Sunday in this embedding matrix would be higher . By having these high dimensionality vector , we give a chance to the Neural Network to learn these underlying rich representations. It’s the rich representation that allows it to learn such interesting relationships. This idea of representing embedding is known as “distributed representation”. Neural Network has a high dimensional representation which is sometimes hard to interpret . These numbers in this matrix doesn’t have to have just one meaning . It could change its meaning with the context because its going through the rich non-linear functions."
},
{
"code": null,
"e": 13552,
"s": 13328,
"text": "Although one hot encoding is having more dimension in case of Days of Week , its not meaningfully high dimension . The use of Embedding matrix helps in reducing the size as well as represent the variable more appropriately."
},
{
"code": null,
"e": 13614,
"s": 13552,
"text": "Qs 3:- Are embeddings suitable for certain type of variables?"
},
{
"code": null,
"e": 13757,
"s": 13614,
"text": "We use the concept of embedding when we come across Categorical Variables. But it won’t work when it comes to variables with high cardinality."
},
{
"code": null,
"e": 13813,
"s": 13757,
"text": "Qs 4:- How does the add_datepart() affects seasonality?"
},
{
"code": null,
"e": 14305,
"s": 13813,
"text": "The fastai library has an add_datepart() function which takes a dataframe and its column which represents date . It optionally removes that date column and instead of that returns lots of columns which denotes useful information about that date. For e.g it replaces Date with dayOfWeek, MonthOfYear, Year, Month, Week, Day etc etc. So daysOFWeek can be represented now in a [8,4] embedding matrix. Conceptually , this allows the models to pick some interesting characteristics and patterns ."
},
{
"code": null,
"e": 14670,
"s": 14305,
"text": "Suppose , there is something with a 7 day period cycle and that goes up in Monday and down on Thursday and only in Berlin , it can totally extract that pattern as it has all the information it needs. Its a nice way to deal with Time Series Models. We just need to make sure that the cycle indicator or periodicity in our time Series Model should exist as a column."
},
{
"code": null,
"e": 14747,
"s": 14670,
"text": "Develop the learner and get the best learning rate using the below commands."
},
{
"code": null,
"e": 14874,
"s": 14747,
"text": "As we can see the best learning rate is somewhere at 10^-3. So we will proceed with training our Neural Network with lr=10^-3."
},
{
"code": null,
"e": 15938,
"s": 14874,
"text": "m.fit(lr, 3, metrics=[exp_rmspe])[ 0. 0.02479 0.02205 0.19309] [ 1. 0.02044 0.01751 0.18301] [ 2. 0.01598 0.01571 0.17248]m.fit(lr, 5, metrics=[exp_rmspe], cycle_len=1)[ 0. 0.01258 0.01278 0.16 ] [ 1. 0.01147 0.01214 0.15758] [ 2. 0.01157 0.01157 0.15585] [ 3. 0.00984 0.01124 0.15251] [ 4. 0.00946 0.01094 0.15197]m.fit(lr, 2, metrics=[exp_rmspe], cycle_len=4)[ 0. 0.01179 0.01242 0.15512] [ 1. 0.00921 0.01098 0.15003] [ 2. 0.00771 0.01031 0.14431] [ 3. 0.00632 0.01016 0.14358] [ 4. 0.01003 0.01305 0.16574] [ 5. 0.00827 0.01087 0.14937] [ 6. 0.00628 0.01025 0.14506] [ 7. 0.0053 0.01 0.14449]"
},
{
"code": null,
"e": 16236,
"s": 15938,
"text": "Note:- Switching from gradient boosting to deep learning is good as it requires less feature engineering and it is a simpler model which requires less maintenence . This is one of the big benifits of using an approach to deep learning Using this we can get SoTA results but with lots of less work."
},
{
"code": null,
"e": 16246,
"s": 16236,
"text": "SUMMARY:-"
},
{
"code": null,
"e": 16351,
"s": 16246,
"text": "Step 1:- List categorical variables names and list continuous variable names and put them in data frame."
},
{
"code": null,
"e": 16416,
"s": 16351,
"text": "Step 2:- Create a list of row_indexes we want in validation set."
},
{
"code": null,
"e": 16465,
"s": 16416,
"text": "Step 3:- Creation of columnar model data object."
},
{
"code": null,
"e": 16535,
"s": 16465,
"text": "Step 4:- Create a list of how big we want the embedding matrix to be."
},
{
"code": null,
"e": 16611,
"s": 16535,
"text": "Step 5:- Call get_learner and use the exact parameters to get started with."
},
{
"code": null,
"e": 16633,
"s": 16611,
"text": "Step 6:- Call m.fit()"
},
{
"code": null,
"e": 16702,
"s": 16633,
"text": "I’ve used the kernels mentioned in this blogpost by William Horton ."
},
{
"code": null,
"e": 16780,
"s": 16702,
"text": "!!! Congratulations on completing another Lesson on fast.ai . Well done . !!!"
},
{
"code": null,
"e": 16852,
"s": 16780,
"text": "If you like it , then ABC (Always be clapping . 👏 👏👏👏👏😃😃😃😃😃😃😃😃😃👏 👏👏👏👏👏)"
},
{
"code": null,
"e": 16955,
"s": 16852,
"text": "If you have any questions, feel free to reach out on the fast.ai forums or on Twitter:@ashiskumarpanda"
},
{
"code": null,
"e": 17117,
"s": 16955,
"text": "P.S. -This blog post will be updated and improved as I further continue with other lessons. For more interesting stuff , Feel free to checkout my Github account."
},
{
"code": null,
"e": 17237,
"s": 17117,
"text": "To make best out of this blog post Series , feel free to explore the first Part of this Series in the following order:-"
},
{
"code": null,
"e": 17737,
"s": 17237,
"text": "Dog Vs Cat Image ClassificationDog Breed Image ClassificationMulti-label Image ClassificationTime Series Analysis using Neural NetworkNLP- Sentiment Analysis on IMDB Movie DatasetBasic of Movie Recommendation SystemCollaborative Filtering from ScratchCollaborative Filtering using Neural NetworkWriting Philosophy like NietzschePerformance of Different Neural Network on Cifar-10 datasetML Model to detect the biggest object in an image Part-1ML Model to detect the biggest object in an image Part-2"
},
{
"code": null,
"e": 17769,
"s": 17737,
"text": "Dog Vs Cat Image Classification"
},
{
"code": null,
"e": 17800,
"s": 17769,
"text": "Dog Breed Image Classification"
},
{
"code": null,
"e": 17833,
"s": 17800,
"text": "Multi-label Image Classification"
},
{
"code": null,
"e": 17875,
"s": 17833,
"text": "Time Series Analysis using Neural Network"
},
{
"code": null,
"e": 17921,
"s": 17875,
"text": "NLP- Sentiment Analysis on IMDB Movie Dataset"
},
{
"code": null,
"e": 17958,
"s": 17921,
"text": "Basic of Movie Recommendation System"
},
{
"code": null,
"e": 17995,
"s": 17958,
"text": "Collaborative Filtering from Scratch"
},
{
"code": null,
"e": 18040,
"s": 17995,
"text": "Collaborative Filtering using Neural Network"
},
{
"code": null,
"e": 18074,
"s": 18040,
"text": "Writing Philosophy like Nietzsche"
},
{
"code": null,
"e": 18134,
"s": 18074,
"text": "Performance of Different Neural Network on Cifar-10 dataset"
},
{
"code": null,
"e": 18191,
"s": 18134,
"text": "ML Model to detect the biggest object in an image Part-1"
},
{
"code": null,
"e": 18248,
"s": 18191,
"text": "ML Model to detect the biggest object in an image Part-2"
}
] |
PyViz: Simplifying the Data Visualisation process in Python. | by Parul Pandey | Towards Data Science
|
The purpose of visualization is insight, not pictures.―Ben Shneiderman
If you work with data, then Data Visualisation is a vital part of your daily routine. And if you use Python for your analysis, you ought to be overwhelmed by the sheer amount of choices present in the form of Data Visualisation libraries. Some libraries like Matplotlib are used for initial basic exploration but are not so useful for showing complex relationships in data. There are some which work well with large datasets while there are still others which mainly focus on 3D renderings. In fact, there isn’t a single visualization library which can be referred to as the best one. There are certain features in one that is better than the other and vice versa. In short, there are a lot of options and it is impossible to learn and try them all or maybe, get them all to work together. So how do we get our job done? PyViz may have an answer
The existing Python Data Visualisation system appears to be a confusing Mesh.
Now, to choose the best tool for our job from amongst all of these is a bit tricky and confusing. PyViz tries to plug this situation. It helps to streamline the process of working with small and large datasets (from a few points to billions) in a web browser, whether doing exploratory analysis, making simple widget-based tools or building full-featured dashboards
PyViz is a coordinated effort to make data visualization in Python easier to use, learn and more powerful. PyViz consists of a set of open-source Python packages to work effortlessly with both small and large datasets right in the web browsers. PyViz is just the choice for something as simple as mere EDA or something as complex as creating a widget enabled dashboard.
Here is the Python’s visualisation landscape with PyViz.
Some of the important goals of Pyviz are:
Emphasis should be on data of any size not coding
Full functionality and interactivity should be available right in the browsers(not desktops)
The focus should be more on people who are Python users and not web programmers.
Again focus should be more on 2D viz more than 3D.
Exploitation of general-purpose SciPy/PyData tools with which the Python users are already familiar.
The open-source libraries which constitute PyViz are:
HoloViews: Declarative objects for instantly visualizable data, building Bokeh plots from convenient high-level specifications
GeoViews: Visualizable geographic data that that can be mixed and matched with HoloViews objects
Bokeh: Interactive plotting in web browsers, running JavaScript but controlled by Python
Panel: Assembling objects from many different libraries into a layout or app, whether in a Jupyter notebook or in a standalone serveable dashboard
Datashader: Rasterizing huge datasets quickly as fixed-size images
hvPlot: Quickly return interactive HoloViews or GeoViews objects from your Pandas, Xarray, or other data structures
Param: Declaring user-relevant parameters, making it simple to work with widgets inside and outside of a notebook context
Apart from this, PyViz core tools can work seamlessly with the following libraries.
Also, Objects from nearly every other plotting library can be used with Panel, including specific support for all those listed here plus anything that can generate HTML, PNG, or SVG. HoloViews also supports Plotly for 3D visualizations.
PyViz provides examples, demos and training materials documenting how to solve visualization problems. This tutorial provides starting points for solving your own visualization problems. The entire tutorial material is also hosted at their Github Repository.
pyviz.org
Please consult pyviz.org for full instructions on installation of the software used in these tutorials. Here is the condensed version of those instructions, assuming you have already downloaded and installed Anaconda or Miniconda :
conda create -n pyviz-tutorial python=3.6conda activate pyviz-tutorialconda install -c pyviz/label/dev pyvizpyviz examplescd pyviz-examplesjupyter notebook
Once everything is installed, the following cell should print ‘1.11.0a4’ or later:
import holoviews as hvhv.__version__'1.11.0a11'hv.extension('bokeh', 'matplotlib')#should see the HoloViews, Bokeh, and Matplotlib logos#Import necessary librariesimport pandasimport datashaderimport daskimport geoviewsimport bokeh
If it completes without errors your environment should be ready to go.
In this section, we will see how different libraries are effective in bringing out different insights from data and their conjunction can really help to analyze data in a better way.
The dataset being used pertains to the number of cases of measles and pertussis recorded per, 100,000 people over time in each state of the US. The dataset comes pre-installed with the PyViz tutorial.
In any Data Science project, it is but natural to begin the exploration with pandas. Let us import and display the first few rows of our dataset.
import pandas as pddiseases_data = pd.read_csv('../data/diseases.csv.gz')diseases_data.head()
Numbers are good but a plot would give us a better idea about the patterns in the data.
%matplotlib inlinediseases_data.plot();
This doesn’t convey much. Let’s do some manipulations with pandas to get meaningful results.
import numpy as npdiseases_by_year = diseases_data[["Year","measles"]].groupby("Year").aggregate(np.sum)diseases_by_year.plot();
This makes much more sense. Here we can clearly infer that around 1970, something happened which brought down the rate of measles to almost nil. This is true since measles vaccines were introduced in the US around 1963[Wikipedia]
The plots above convey the right information but provide no interactivity. This is because they are static plots without the functionalities of the pan, hover or zoom in a web browser. However, we can achieve this interactive functionality by a mere import of the hvplot package.
import hvplot.pandasdiseases_by_year.hvplot()
What is returned by the call is called a HoloViews object (here Holoviews Curve)which displays as a Bokeh plot. Holoviews plots are much richer and make it easy to capture your understanding while exploring the data.
Let’s see what else can be done with HoloViews:
1963 was important with respect to measles and how about we record this point on the graph itself. This will also help us to compare the number of measles cases before and after the vaccine introduction.
import holoviews as hvvline = hv.VLine(1963).options(color='red')vaccination_introduced = diseases_by_year.hvplot() * vline * \ hv.Text(1963, 27000, "Measles Vaccine Introduced", halign='left')vaccination_introduced
Holoviews objects preserve the original data as opposed to other plotting libraries. For instance, it is possible to access the original data in tabular format.
print(vaccination_introduced)vaccination_introduced.Curve.I.data.head()
Here we were able to use the data that was used for making the plot. Also, it is now very easy to break data in many different ways.
measles_agg = diseases_data.groupby(['Year', 'State'])['measles'].sum()by_state = measles_agg.hvplot('Year', groupby='State', width=500, dynamic=False)by_state * vline
Instead of a dropdown, we can place charts side by side for better comparison.
by_state["Alabama"].relabel('Alabama') + by_state["Florida"].relabel('Florida')
We can also change the type of plots, say to a bar chart. Let us compare the measles pattern from 1980 to 1985 across four states.
states = ['New York', 'Alabama', 'California', 'Florida']measles_agg.loc[1980:1990, states].hvplot.bar('Year', by='State', rot=90)
It is quite evident from the examples above that by choosing HoloViews+Bokeh plots, we get the ability to explore data in our browser itself, with full interactivity and minimal code.
PyViz also enables working on very large datasets with ease. For such datasets, other members of PyViz suite come into the picture.
GeoViews
Datashader
Panel
Param
Colorcet for perceptually uniform colormaps for big data
To show you the capabilities of these libraries when handling voluminous amount of data, let’s work with the NYC taxi dataset which consists of data pertaining to a whopping 10 million taxi trips. Again this data is already provided in the tutorial.
#Importing the necessary librariesimport dask.dataframe as dd, geoviews as gv, cartopy.crs as crsfrom colorcet import firefrom holoviews.operation.datashader import datashadefrom geoviews.tile_sources import EsriImagery
Dask is a flexible library for parallel computing in Python. A Dask DataFrame is a large parallel DataFrame composed of many smaller Pandas DataFrames, split along the index. These Pandas DataFrames may live on disk for larger-than-memory computing on a single machine, or on many different machines in a cluster. One Dask DataFrame operation triggers many operations on the constituent Pandas DataFrames.
Cartopy is a Python package designed for geospatial data processing in order to produce maps and other geospatial data analyses.
topts = dict(width=700, height=600, bgcolor='black', xaxis=None, yaxis=None, show_grid=False)tiles = EsriImagery.clone(crs=crs.GOOGLE_MERCATOR).options(**topts)dopts = dict(width=1000, height=600, x_sampling=0.5, y_sampling=0.5)
Reading in and plotting the data:
taxi = dd.read_parquet('../data/nyc_taxi_wide.parq').persist()pts = hv.Points(taxi, ['pickup_x', 'pickup_y'])trips = datashade(pts, cmap=fire, **dopts)tiles * trips
We can also add widgets to control the selections. This can be either done in the notebook or in a standalone server by marking the servable objects with .servable() then running the .ipynb file through Bokeh Server or extracting the code to a separate .py file and doing the same thing:
import param, panel as pnfrom colorcet import paletteclass NYCTaxi(param.Parameterized): alpha = param.Magnitude(default=0.75, doc="Map tile opacity") cmap = param.ObjectSelector('fire', objects=['fire','bgy','bgyw','bmy','gray','kbc']) location = param.ObjectSelector(default='dropoff', objects=['dropoff', 'pickup']) def make_view(self, **kwargs): pts = hv.Points(taxi, [self.location+'_x', self.location+'_y']) trips = datashade(pts, cmap=palette[self.cmap], **dopts) return tiles.options(alpha=self.alpha) * tripsexplorer = NYCTaxi(name="Taxi explorer")pn.Row(explorer.param, explorer.make_view).servable()
Taxi explorer
The Notebook with all the running code can be accessed from here. However, the interactiveness does not render on GitHub but you can still access the notebook and run locally.
The PyViz tools help us to create beautiful visualisations even with a small amount of code. The PyViz tools bundle up together to build high-performance, scalable, flexible, and deployable visualizations, apps, and dashboards, without having to use JavaScript or other web technologies explicitly. This article is just a mere introduction to the multi useful PyViz ecosystem. Go through the entire tutorial to understand the intricacies and its usage for different types of data.
|
[
{
"code": null,
"e": 242,
"s": 171,
"text": "The purpose of visualization is insight, not pictures.―Ben Shneiderman"
},
{
"code": null,
"e": 1088,
"s": 242,
"text": "If you work with data, then Data Visualisation is a vital part of your daily routine. And if you use Python for your analysis, you ought to be overwhelmed by the sheer amount of choices present in the form of Data Visualisation libraries. Some libraries like Matplotlib are used for initial basic exploration but are not so useful for showing complex relationships in data. There are some which work well with large datasets while there are still others which mainly focus on 3D renderings. In fact, there isn’t a single visualization library which can be referred to as the best one. There are certain features in one that is better than the other and vice versa. In short, there are a lot of options and it is impossible to learn and try them all or maybe, get them all to work together. So how do we get our job done? PyViz may have an answer"
},
{
"code": null,
"e": 1166,
"s": 1088,
"text": "The existing Python Data Visualisation system appears to be a confusing Mesh."
},
{
"code": null,
"e": 1532,
"s": 1166,
"text": "Now, to choose the best tool for our job from amongst all of these is a bit tricky and confusing. PyViz tries to plug this situation. It helps to streamline the process of working with small and large datasets (from a few points to billions) in a web browser, whether doing exploratory analysis, making simple widget-based tools or building full-featured dashboards"
},
{
"code": null,
"e": 1902,
"s": 1532,
"text": "PyViz is a coordinated effort to make data visualization in Python easier to use, learn and more powerful. PyViz consists of a set of open-source Python packages to work effortlessly with both small and large datasets right in the web browsers. PyViz is just the choice for something as simple as mere EDA or something as complex as creating a widget enabled dashboard."
},
{
"code": null,
"e": 1959,
"s": 1902,
"text": "Here is the Python’s visualisation landscape with PyViz."
},
{
"code": null,
"e": 2001,
"s": 1959,
"text": "Some of the important goals of Pyviz are:"
},
{
"code": null,
"e": 2051,
"s": 2001,
"text": "Emphasis should be on data of any size not coding"
},
{
"code": null,
"e": 2144,
"s": 2051,
"text": "Full functionality and interactivity should be available right in the browsers(not desktops)"
},
{
"code": null,
"e": 2225,
"s": 2144,
"text": "The focus should be more on people who are Python users and not web programmers."
},
{
"code": null,
"e": 2276,
"s": 2225,
"text": "Again focus should be more on 2D viz more than 3D."
},
{
"code": null,
"e": 2377,
"s": 2276,
"text": "Exploitation of general-purpose SciPy/PyData tools with which the Python users are already familiar."
},
{
"code": null,
"e": 2431,
"s": 2377,
"text": "The open-source libraries which constitute PyViz are:"
},
{
"code": null,
"e": 2558,
"s": 2431,
"text": "HoloViews: Declarative objects for instantly visualizable data, building Bokeh plots from convenient high-level specifications"
},
{
"code": null,
"e": 2655,
"s": 2558,
"text": "GeoViews: Visualizable geographic data that that can be mixed and matched with HoloViews objects"
},
{
"code": null,
"e": 2744,
"s": 2655,
"text": "Bokeh: Interactive plotting in web browsers, running JavaScript but controlled by Python"
},
{
"code": null,
"e": 2891,
"s": 2744,
"text": "Panel: Assembling objects from many different libraries into a layout or app, whether in a Jupyter notebook or in a standalone serveable dashboard"
},
{
"code": null,
"e": 2958,
"s": 2891,
"text": "Datashader: Rasterizing huge datasets quickly as fixed-size images"
},
{
"code": null,
"e": 3074,
"s": 2958,
"text": "hvPlot: Quickly return interactive HoloViews or GeoViews objects from your Pandas, Xarray, or other data structures"
},
{
"code": null,
"e": 3196,
"s": 3074,
"text": "Param: Declaring user-relevant parameters, making it simple to work with widgets inside and outside of a notebook context"
},
{
"code": null,
"e": 3280,
"s": 3196,
"text": "Apart from this, PyViz core tools can work seamlessly with the following libraries."
},
{
"code": null,
"e": 3517,
"s": 3280,
"text": "Also, Objects from nearly every other plotting library can be used with Panel, including specific support for all those listed here plus anything that can generate HTML, PNG, or SVG. HoloViews also supports Plotly for 3D visualizations."
},
{
"code": null,
"e": 3776,
"s": 3517,
"text": "PyViz provides examples, demos and training materials documenting how to solve visualization problems. This tutorial provides starting points for solving your own visualization problems. The entire tutorial material is also hosted at their Github Repository."
},
{
"code": null,
"e": 3786,
"s": 3776,
"text": "pyviz.org"
},
{
"code": null,
"e": 4018,
"s": 3786,
"text": "Please consult pyviz.org for full instructions on installation of the software used in these tutorials. Here is the condensed version of those instructions, assuming you have already downloaded and installed Anaconda or Miniconda :"
},
{
"code": null,
"e": 4174,
"s": 4018,
"text": "conda create -n pyviz-tutorial python=3.6conda activate pyviz-tutorialconda install -c pyviz/label/dev pyvizpyviz examplescd pyviz-examplesjupyter notebook"
},
{
"code": null,
"e": 4257,
"s": 4174,
"text": "Once everything is installed, the following cell should print ‘1.11.0a4’ or later:"
},
{
"code": null,
"e": 4489,
"s": 4257,
"text": "import holoviews as hvhv.__version__'1.11.0a11'hv.extension('bokeh', 'matplotlib')#should see the HoloViews, Bokeh, and Matplotlib logos#Import necessary librariesimport pandasimport datashaderimport daskimport geoviewsimport bokeh"
},
{
"code": null,
"e": 4560,
"s": 4489,
"text": "If it completes without errors your environment should be ready to go."
},
{
"code": null,
"e": 4743,
"s": 4560,
"text": "In this section, we will see how different libraries are effective in bringing out different insights from data and their conjunction can really help to analyze data in a better way."
},
{
"code": null,
"e": 4944,
"s": 4743,
"text": "The dataset being used pertains to the number of cases of measles and pertussis recorded per, 100,000 people over time in each state of the US. The dataset comes pre-installed with the PyViz tutorial."
},
{
"code": null,
"e": 5090,
"s": 4944,
"text": "In any Data Science project, it is but natural to begin the exploration with pandas. Let us import and display the first few rows of our dataset."
},
{
"code": null,
"e": 5184,
"s": 5090,
"text": "import pandas as pddiseases_data = pd.read_csv('../data/diseases.csv.gz')diseases_data.head()"
},
{
"code": null,
"e": 5272,
"s": 5184,
"text": "Numbers are good but a plot would give us a better idea about the patterns in the data."
},
{
"code": null,
"e": 5312,
"s": 5272,
"text": "%matplotlib inlinediseases_data.plot();"
},
{
"code": null,
"e": 5405,
"s": 5312,
"text": "This doesn’t convey much. Let’s do some manipulations with pandas to get meaningful results."
},
{
"code": null,
"e": 5534,
"s": 5405,
"text": "import numpy as npdiseases_by_year = diseases_data[[\"Year\",\"measles\"]].groupby(\"Year\").aggregate(np.sum)diseases_by_year.plot();"
},
{
"code": null,
"e": 5764,
"s": 5534,
"text": "This makes much more sense. Here we can clearly infer that around 1970, something happened which brought down the rate of measles to almost nil. This is true since measles vaccines were introduced in the US around 1963[Wikipedia]"
},
{
"code": null,
"e": 6044,
"s": 5764,
"text": "The plots above convey the right information but provide no interactivity. This is because they are static plots without the functionalities of the pan, hover or zoom in a web browser. However, we can achieve this interactive functionality by a mere import of the hvplot package."
},
{
"code": null,
"e": 6090,
"s": 6044,
"text": "import hvplot.pandasdiseases_by_year.hvplot()"
},
{
"code": null,
"e": 6307,
"s": 6090,
"text": "What is returned by the call is called a HoloViews object (here Holoviews Curve)which displays as a Bokeh plot. Holoviews plots are much richer and make it easy to capture your understanding while exploring the data."
},
{
"code": null,
"e": 6355,
"s": 6307,
"text": "Let’s see what else can be done with HoloViews:"
},
{
"code": null,
"e": 6559,
"s": 6355,
"text": "1963 was important with respect to measles and how about we record this point on the graph itself. This will also help us to compare the number of measles cases before and after the vaccine introduction."
},
{
"code": null,
"e": 6778,
"s": 6559,
"text": "import holoviews as hvvline = hv.VLine(1963).options(color='red')vaccination_introduced = diseases_by_year.hvplot() * vline * \\ hv.Text(1963, 27000, \"Measles Vaccine Introduced\", halign='left')vaccination_introduced"
},
{
"code": null,
"e": 6939,
"s": 6778,
"text": "Holoviews objects preserve the original data as opposed to other plotting libraries. For instance, it is possible to access the original data in tabular format."
},
{
"code": null,
"e": 7011,
"s": 6939,
"text": "print(vaccination_introduced)vaccination_introduced.Curve.I.data.head()"
},
{
"code": null,
"e": 7144,
"s": 7011,
"text": "Here we were able to use the data that was used for making the plot. Also, it is now very easy to break data in many different ways."
},
{
"code": null,
"e": 7312,
"s": 7144,
"text": "measles_agg = diseases_data.groupby(['Year', 'State'])['measles'].sum()by_state = measles_agg.hvplot('Year', groupby='State', width=500, dynamic=False)by_state * vline"
},
{
"code": null,
"e": 7391,
"s": 7312,
"text": "Instead of a dropdown, we can place charts side by side for better comparison."
},
{
"code": null,
"e": 7471,
"s": 7391,
"text": "by_state[\"Alabama\"].relabel('Alabama') + by_state[\"Florida\"].relabel('Florida')"
},
{
"code": null,
"e": 7602,
"s": 7471,
"text": "We can also change the type of plots, say to a bar chart. Let us compare the measles pattern from 1980 to 1985 across four states."
},
{
"code": null,
"e": 7733,
"s": 7602,
"text": "states = ['New York', 'Alabama', 'California', 'Florida']measles_agg.loc[1980:1990, states].hvplot.bar('Year', by='State', rot=90)"
},
{
"code": null,
"e": 7917,
"s": 7733,
"text": "It is quite evident from the examples above that by choosing HoloViews+Bokeh plots, we get the ability to explore data in our browser itself, with full interactivity and minimal code."
},
{
"code": null,
"e": 8049,
"s": 7917,
"text": "PyViz also enables working on very large datasets with ease. For such datasets, other members of PyViz suite come into the picture."
},
{
"code": null,
"e": 8058,
"s": 8049,
"text": "GeoViews"
},
{
"code": null,
"e": 8069,
"s": 8058,
"text": "Datashader"
},
{
"code": null,
"e": 8075,
"s": 8069,
"text": "Panel"
},
{
"code": null,
"e": 8081,
"s": 8075,
"text": "Param"
},
{
"code": null,
"e": 8138,
"s": 8081,
"text": "Colorcet for perceptually uniform colormaps for big data"
},
{
"code": null,
"e": 8388,
"s": 8138,
"text": "To show you the capabilities of these libraries when handling voluminous amount of data, let’s work with the NYC taxi dataset which consists of data pertaining to a whopping 10 million taxi trips. Again this data is already provided in the tutorial."
},
{
"code": null,
"e": 8608,
"s": 8388,
"text": "#Importing the necessary librariesimport dask.dataframe as dd, geoviews as gv, cartopy.crs as crsfrom colorcet import firefrom holoviews.operation.datashader import datashadefrom geoviews.tile_sources import EsriImagery"
},
{
"code": null,
"e": 9014,
"s": 8608,
"text": "Dask is a flexible library for parallel computing in Python. A Dask DataFrame is a large parallel DataFrame composed of many smaller Pandas DataFrames, split along the index. These Pandas DataFrames may live on disk for larger-than-memory computing on a single machine, or on many different machines in a cluster. One Dask DataFrame operation triggers many operations on the constituent Pandas DataFrames."
},
{
"code": null,
"e": 9143,
"s": 9014,
"text": "Cartopy is a Python package designed for geospatial data processing in order to produce maps and other geospatial data analyses."
},
{
"code": null,
"e": 9372,
"s": 9143,
"text": "topts = dict(width=700, height=600, bgcolor='black', xaxis=None, yaxis=None, show_grid=False)tiles = EsriImagery.clone(crs=crs.GOOGLE_MERCATOR).options(**topts)dopts = dict(width=1000, height=600, x_sampling=0.5, y_sampling=0.5)"
},
{
"code": null,
"e": 9406,
"s": 9372,
"text": "Reading in and plotting the data:"
},
{
"code": null,
"e": 9574,
"s": 9406,
"text": "taxi = dd.read_parquet('../data/nyc_taxi_wide.parq').persist()pts = hv.Points(taxi, ['pickup_x', 'pickup_y'])trips = datashade(pts, cmap=fire, **dopts)tiles * trips"
},
{
"code": null,
"e": 9862,
"s": 9574,
"text": "We can also add widgets to control the selections. This can be either done in the notebook or in a standalone server by marking the servable objects with .servable() then running the .ipynb file through Bokeh Server or extracting the code to a separate .py file and doing the same thing:"
},
{
"code": null,
"e": 10508,
"s": 9862,
"text": "import param, panel as pnfrom colorcet import paletteclass NYCTaxi(param.Parameterized): alpha = param.Magnitude(default=0.75, doc=\"Map tile opacity\") cmap = param.ObjectSelector('fire', objects=['fire','bgy','bgyw','bmy','gray','kbc']) location = param.ObjectSelector(default='dropoff', objects=['dropoff', 'pickup']) def make_view(self, **kwargs): pts = hv.Points(taxi, [self.location+'_x', self.location+'_y']) trips = datashade(pts, cmap=palette[self.cmap], **dopts) return tiles.options(alpha=self.alpha) * tripsexplorer = NYCTaxi(name=\"Taxi explorer\")pn.Row(explorer.param, explorer.make_view).servable()"
},
{
"code": null,
"e": 10522,
"s": 10508,
"text": "Taxi explorer"
},
{
"code": null,
"e": 10698,
"s": 10522,
"text": "The Notebook with all the running code can be accessed from here. However, the interactiveness does not render on GitHub but you can still access the notebook and run locally."
}
] |
Tensorflow for Complete Beginners: Getting Started with Tensors | by Joyjit Chatterjee | Nov, 2020 | Towards Data Science
|
Tensorflow is a buzz word nowadays in this exciting world of Artificial Intelligence (AI), especially as Deep Learning continues to rapidly accelerate progress in AI. But for someone just starting with Tensorflow, the experience can be scary and daunting, as the terminologies and usage of the beautiful library can be confusing for complete beginners. When I first started learning Tensorflow, I faced similar challenges, and hope to simplify some of the intricacies through this article. This article requires a basic understanding of Python to get a clearer picture of Tensorflow.
How does Tensorflow work?
The basic (and simplest) way to describe Tensorflow is that it is a cool library in Python (and probably other programming languages as well) which allows us to create computational graphs to develop neural network models. The basic element which comprises Tensorflow objects is a Tensor, and all computations which are performed occur in these Tensors. So literally (in my words), these Tensors flow in an orderly manner when you develop any neural network model, and give rise to the final outputs when evaluated. So yes, learning what tensors really are and how we can use them is the first step to getting started with Tensorflow.
So what are Tensors?
We are all familiar with data types in programming, right? 1, 2, 3 etc. are integers, numbers with decimal points (1.5,3.141,5.2555 etc.) are floating point values and another common one is strings (such as “Hello. How are you today?”). When we have a collection of multiple elements together, we generally term that as a list (e.g. [1,4,7]).
A collection of lists can be used to develop a matrix/matrices like this one:
[[1,4,7], [5,8,12], [1,66,88]]
Now, let’s come to Tensors- they are basically higher dimensional representations/generalisations of conventional matrices and vectors. It could even be a 1-D matrix, a 2-D matrix, a 4-D matrix, or an n-dimensional matrix! So we can have multi-dimensional arrays beyond a single list in a Tensor. That’s it- that is what a tensor really is in the most basic sense. Just like we can assign variables values in conventional programming, we could do the same in Tensorflow. Just that there is a specialised way to do it. Similar, just like you could perform multiple operations on conventional variables (or constants) in programming, we can do that with Tensors. We can slice tensors and select a portion of its elements, have various data types for tensors (integers, floating point, strings etc.) and much more.
Getting started with using Tensorflow in Python
The very first step is to install the beautiful library! pip is all you need here. Note that if you’re using Google Colab (which is very similar to Jupyter notebooks in Python), you don’t even need to install this library as it is already installed and available ready for use. Thank you, Google!
#Install the tensorflow module (not required in Google Colab, but is needed in your local PC)!pip install tensorflow
As we are using Colab for this article, the message “requirement already satisfied” is shown in the output.
Requirement already satisfied: tensorflow in /usr/local/lib/python3.6/dist-packages (2.3.0)
Tensorflow, at present, has an older version of type 1.x, while the latest releases use 2.x. So let’s select the current tensorflow version.
#Here, we would go with the latest (2.x) release of tensorflow by selecting the version#Note: By default, Colab tends to use the 2.x version%tensorflow_version 2.x
Let’s import the tensorflow module using the golden keyword import! And yes, you could check what version of the library you’re using by simply printing its version attribute.
#import the tensorflow moduleimport tensorflow as tf#Display the tensorflow version we are usingprint(tf.version)
<module ‘tensorflow._api.v2.version’ from ‘/usr/local/lib/python3.6/dist-packages/tensorflow/_api/v2/version/__init__.py’>
Now, let’s get started with creating Tensors. We would create some for int, float and string here. Notice the specialised way of creating tensors using tf.Variable attribute. This means that we are creating a Tensor which would be a variable nature, so we can change/modify its values by performing specialised operations, just like we would do in conventional programming with variables. Note that while we would have used int, float and string to declare the corresponding variables for such data types in conventional programming, we will use tf.int16 (which means we are defining a 16 bit integer), tf.float32 (to define a 32 bit floating point value) and tf.string to do so in Tensorflow. Note that we could also use tf.float16, tf.int32 and so on, depending on the requirements for the value we want to store. If you have ever used C++, you would be aware of things like int, short int, long long int, float, double etc. used to declare variables with smaller (or larger) number of bits, so we just do something similar here in Tensorflow.
#The science (and art) of creating tensorsscalar_val = tf.Variable(123,tf.int16)floating_val = tf.Variable(123.456,tf.float32)string_val = tf.Variable(“hello everyone. Nice to learn tensorflow!”,tf.string)
And now, it’s very easy to print out the values of these Tensors!
#Let us display the values (print) these tensorsprint(scalar_val)print(floating_val)print(string_val)
<tf.Variable ‘Variable:0’ shape=() dtype=int32, numpy=123>
<tf.Variable ‘Variable:0’ shape=() dtype=float32, numpy=123.456> <tf.Variable ‘Variable:0’ shape=() dtype=string, numpy=b’hello everyone. Nice to learn tensorflow!’>
We can determine the shape and rank of the Tensors, like you might have heard in mathematics modules at school. If not, shape simply refers to the number of elements which are contained along each dimension of the tensor. While rank is the deepest level of nesting within the Tensor. Going into some code might make it more clear.
#The idea behind shape and rank of tensors#Shape: Describes the dimension of the tensor (total elements contained along each dimension)scalar_val_shap = tf.shape(scalar_val)print(scalar_val_shap)floating_val_shap = tf.shape(floating_val)print(floating_val_shap)
tf.Tensor([], shape=(0,), dtype=int32)
tf.Tensor([], shape=(0,), dtype=int32)
So we get a shape of 0 right? It just means that these are scalar values rather than lists or nested lists.
#Now, if we use e.g. lists/nested lists instead of just a “single” scalar valuelist_tensor1 = tf.Variable([1,3,5,6],tf.int16)print(list_tensor1)print(tf.shape(list_tensor1))list_tensor2 = tf.Variable([[1,2,3],[4,5,6]],tf.int16)print(list_tensor2)print(tf.shape(list_tensor2))#how about the rank? It describes the level of nesting within the tensor in simple words.print(tf.rank(list_tensor1))print(tf.rank(list_tensor2))
You can see that the list_tensor1 has 4 elements, so that’s what gives it a shape of (4,). Note that (4,) is nothing but (4,1), just showing 4 elements within a single list. Next, for list_tensor2, observe a shape of (2,3) signifying that we have a nested list- with 2 lists, each containing 3 elements.
<tf.Variable ‘Variable:0’ shape=(4,) dtype=int32, numpy=array([1, 3, 5, 6], dtype=int32)>
tf.Tensor([4], shape=(1,), dtype=int32)
<tf.Variable ‘Variable:0’ shape=(2, 3) dtype=int32, numpy=array([[1, 2, 3], [4, 5, 6]], dtype=int32)>
tf.Tensor([2 3], shape=(2,), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
Similarly, if you look at the rank, you see a rank of 1 for the list_tensor1, simply because we just have a single list, no nesting here! Now, for list_tensor2, you can see a rank of 2- signifying that we have a level 2 nesting i.e. a big list contains more lists. Had it been something like one big list, contains another small list, and that small list contains more smaller lists, we would have had a rank of 3. Hope this would make it clear.
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
We can change the shape of the tensors (of course, until it is mathematically valid) using tf.reshape. Again, note the specialised way to do this using Python.
#Reshaping tensorsreshaped_list_tensor2 = tf.reshape(list_tensor2,[6])print(reshaped_list_tensor2)list_tensor3 = tf.Variable([[1,2,3,1],[1,9,10,11],[1,5,11,22],[16,17,18,19]],tf.int16)print(list_tensor3)print(tf.rank(list_tensor3))print(tf.shape(list_tensor3))reshaped_list_tensor3 = tf.reshape(list_tensor3,[2,8,1])print(reshaped_list_tensor3)#or like thisreshaped_list_tensor3 = tf.reshape(list_tensor3,[8,2,1])print(reshaped_list_tensor3)#or automatically determine the shape by only giving one dimension!reshaped_list_tensor3 = tf.reshape(list_tensor3,[1,-1])print(reshaped_list_tensor3)
And you get the following outputs. It's too long to probably give a read, but I guess if you check out the Colab Notebook here, it would be clearer. The basic thing happening here is that if you specify [6] here for the shape, tensorflow would reshape your tensors to have 6 elements with a single dimension (so it would be simply a 1D list). If you do a [2,8,1], it would make 2 lists, each with 8 elements. You could also do [8,2,1]- creating 8 lists, each with 2 elements as you would see. If you don’t want to go into specifying the whole of dimensions for the reshape yourself, you could as well simply use a -1. So, a reshape of [1,-1] would reshape the list_tensor3 to create reshaped_list_tensor3, so 1 list with ??? Yes, 16 elements. So note that while you could use reshape however you want, it is essential to ensure that the total number of elements after reshape do not change during the process.
tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32)
<tf.Variable ‘Variable:0’ shape=(4, 4) dtype=int32, numpy=array([[ 1, 2, 3, 1], [ 1, 9, 10, 11], [ 1, 5, 11, 22], [16, 17, 18, 19]], dtype=int32)>
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor([4 4], shape=(2,), dtype=int32)
tf.Tensor( [[[ 1] [ 2] [ 3] [ 1] [ 1] [ 9] [10] [11]] [[ 1] [ 5] [11] [22] [16] [17] [18] [19]]], shape=(2, 8, 1), dtype=int32)
tf.Tensor( [[[ 1] [ 2]] [[ 3] [ 1]] [[ 1] [ 9]] [[10] [11]] [[ 1] [ 5]] [[11] [22]] [[16] [17]] [[18] [19]]], shape=(8, 2, 1), dtype=int32)
tf.Tensor([[ 1 2 3 1 1 9 10 11 1 5 11 22 16 17 18 19]], shape=(1, 16), dtype=int32)
You could create a Tensor full of 1s (or 0s) using special commands tf.ones or tf.zeros. And then, similar operations could be performed on them too.
Now, we come to slicing. Just like you could slice and extract some elements from a matrix or a Python list for instance, you could do the same with Tensors. See an example below, wherein, we first create a onefull tensor (my name for a tensor full of 1 values only) and another with zerofull. The dimensions of the tensors you want to create go within the square brackets [], so a [4,4,4,1] creates a 4D tensor, while a [5,5] creates a 2D tensor- with 5 rows and 5 columns (which is nothing but a matrix) in the simplest sense.
Some slicing operations are shown below for these created tensors. So that you can get the elements you like from the tensors and not consider those you don’t like :-)
#creating a tensor full of 1s (or 0s)tensor_onefull = tf.ones([4,4,4,1])print(tensor_onefull)tensor_zerofull = tf.zeros([5,5])print(tensor_zerofull)#extracting specific values from tensors (similar to slicing in conventional programming)tensor_sliced_onefull = tensor_onefull[0]print(tensor_sliced_onefull)tensor_sliced_zerofull = tensor_zerofull[0,1]print(tensor_sliced_zerofull)
And here is the nice output (better readable in the Colab notebook).
tf.Tensor( [[[[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.] [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.]] [[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]]]], shape=(4, 4, 4, 1), dtype=float32)
tf.Tensor( [[0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]], shape=(5, 5), dtype=float32)
tf.Tensor( [[[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]]], shape=(4, 4, 1), dtype=float32)
tf.Tensor(0.0, shape=(), dtype=float32)
#another example from previously created tensorprint(list_tensor3)tf_slicedexampleagain = list_tensor3[0,-2:]print(tf_slicedexampleagain)#selecting multiple rowstf_slicedexampleagain = list_tensor3[1::]print(tf_slicedexampleagain)
And again, some cool output (basic but yes, simplest things are the coolest).
<tf.Variable ‘Variable:0’ shape=(4, 4) dtype=int32, numpy=array([[ 1, 2, 3, 1], [ 1, 9, 10, 11], [ 1, 5, 11, 22], [16, 17, 18, 19]], dtype=int32)>
tf.Tensor([3 1], shape=(2,), dtype=int32)
tf.Tensor( [[ 1 9 10 11] [ 1 5 11 22] [16 17 18 19]], shape=(3, 4), dtype=int32)
You can find the complete Colab notebook for this article here on my Github https://github.com/joyjitchatterjee/DeepLearning-Tensorflow-Basics/blob/master/Tensorflow_Beginning.ipynb.
And that’s it. Hope you enjoyed reading this article. Thanks for the read, and apologies for any typos/bugs if any. I hope to cover more on Tensorflow in my next posts.
If you wish to, you can connect with me on LinkedIn at http://linkedin.com/in/joyjitchatterjee/
REFERENCES
Tensorflow documentation (https://www.tensorflow.org/guide)TensorFlow 2.0 Complete Course — Python Neural Networks for Beginners Tutorial (https://www.youtube.com/watch?v=tPYj3fFJGjk&list=PLYLyA78Q4izuAlaaOER3qwUZkqLTZf7qk)Get started with TensorFlow and Deep Learning (https://medium.com/@rishit.dagli/get-started-with-tensorflow-and-deep-learning-part-1-72c7d67f99fc)
Tensorflow documentation (https://www.tensorflow.org/guide)
TensorFlow 2.0 Complete Course — Python Neural Networks for Beginners Tutorial (https://www.youtube.com/watch?v=tPYj3fFJGjk&list=PLYLyA78Q4izuAlaaOER3qwUZkqLTZf7qk)
Get started with TensorFlow and Deep Learning (https://medium.com/@rishit.dagli/get-started-with-tensorflow-and-deep-learning-part-1-72c7d67f99fc)
|
[
{
"code": null,
"e": 755,
"s": 171,
"text": "Tensorflow is a buzz word nowadays in this exciting world of Artificial Intelligence (AI), especially as Deep Learning continues to rapidly accelerate progress in AI. But for someone just starting with Tensorflow, the experience can be scary and daunting, as the terminologies and usage of the beautiful library can be confusing for complete beginners. When I first started learning Tensorflow, I faced similar challenges, and hope to simplify some of the intricacies through this article. This article requires a basic understanding of Python to get a clearer picture of Tensorflow."
},
{
"code": null,
"e": 781,
"s": 755,
"text": "How does Tensorflow work?"
},
{
"code": null,
"e": 1416,
"s": 781,
"text": "The basic (and simplest) way to describe Tensorflow is that it is a cool library in Python (and probably other programming languages as well) which allows us to create computational graphs to develop neural network models. The basic element which comprises Tensorflow objects is a Tensor, and all computations which are performed occur in these Tensors. So literally (in my words), these Tensors flow in an orderly manner when you develop any neural network model, and give rise to the final outputs when evaluated. So yes, learning what tensors really are and how we can use them is the first step to getting started with Tensorflow."
},
{
"code": null,
"e": 1437,
"s": 1416,
"text": "So what are Tensors?"
},
{
"code": null,
"e": 1780,
"s": 1437,
"text": "We are all familiar with data types in programming, right? 1, 2, 3 etc. are integers, numbers with decimal points (1.5,3.141,5.2555 etc.) are floating point values and another common one is strings (such as “Hello. How are you today?”). When we have a collection of multiple elements together, we generally term that as a list (e.g. [1,4,7])."
},
{
"code": null,
"e": 1858,
"s": 1780,
"text": "A collection of lists can be used to develop a matrix/matrices like this one:"
},
{
"code": null,
"e": 1889,
"s": 1858,
"text": "[[1,4,7], [5,8,12], [1,66,88]]"
},
{
"code": null,
"e": 2701,
"s": 1889,
"text": "Now, let’s come to Tensors- they are basically higher dimensional representations/generalisations of conventional matrices and vectors. It could even be a 1-D matrix, a 2-D matrix, a 4-D matrix, or an n-dimensional matrix! So we can have multi-dimensional arrays beyond a single list in a Tensor. That’s it- that is what a tensor really is in the most basic sense. Just like we can assign variables values in conventional programming, we could do the same in Tensorflow. Just that there is a specialised way to do it. Similar, just like you could perform multiple operations on conventional variables (or constants) in programming, we can do that with Tensors. We can slice tensors and select a portion of its elements, have various data types for tensors (integers, floating point, strings etc.) and much more."
},
{
"code": null,
"e": 2749,
"s": 2701,
"text": "Getting started with using Tensorflow in Python"
},
{
"code": null,
"e": 3046,
"s": 2749,
"text": "The very first step is to install the beautiful library! pip is all you need here. Note that if you’re using Google Colab (which is very similar to Jupyter notebooks in Python), you don’t even need to install this library as it is already installed and available ready for use. Thank you, Google!"
},
{
"code": null,
"e": 3163,
"s": 3046,
"text": "#Install the tensorflow module (not required in Google Colab, but is needed in your local PC)!pip install tensorflow"
},
{
"code": null,
"e": 3271,
"s": 3163,
"text": "As we are using Colab for this article, the message “requirement already satisfied” is shown in the output."
},
{
"code": null,
"e": 3363,
"s": 3271,
"text": "Requirement already satisfied: tensorflow in /usr/local/lib/python3.6/dist-packages (2.3.0)"
},
{
"code": null,
"e": 3504,
"s": 3363,
"text": "Tensorflow, at present, has an older version of type 1.x, while the latest releases use 2.x. So let’s select the current tensorflow version."
},
{
"code": null,
"e": 3668,
"s": 3504,
"text": "#Here, we would go with the latest (2.x) release of tensorflow by selecting the version#Note: By default, Colab tends to use the 2.x version%tensorflow_version 2.x"
},
{
"code": null,
"e": 3844,
"s": 3668,
"text": "Let’s import the tensorflow module using the golden keyword import! And yes, you could check what version of the library you’re using by simply printing its version attribute."
},
{
"code": null,
"e": 3958,
"s": 3844,
"text": "#import the tensorflow moduleimport tensorflow as tf#Display the tensorflow version we are usingprint(tf.version)"
},
{
"code": null,
"e": 4081,
"s": 3958,
"text": "<module ‘tensorflow._api.v2.version’ from ‘/usr/local/lib/python3.6/dist-packages/tensorflow/_api/v2/version/__init__.py’>"
},
{
"code": null,
"e": 5127,
"s": 4081,
"text": "Now, let’s get started with creating Tensors. We would create some for int, float and string here. Notice the specialised way of creating tensors using tf.Variable attribute. This means that we are creating a Tensor which would be a variable nature, so we can change/modify its values by performing specialised operations, just like we would do in conventional programming with variables. Note that while we would have used int, float and string to declare the corresponding variables for such data types in conventional programming, we will use tf.int16 (which means we are defining a 16 bit integer), tf.float32 (to define a 32 bit floating point value) and tf.string to do so in Tensorflow. Note that we could also use tf.float16, tf.int32 and so on, depending on the requirements for the value we want to store. If you have ever used C++, you would be aware of things like int, short int, long long int, float, double etc. used to declare variables with smaller (or larger) number of bits, so we just do something similar here in Tensorflow."
},
{
"code": null,
"e": 5333,
"s": 5127,
"text": "#The science (and art) of creating tensorsscalar_val = tf.Variable(123,tf.int16)floating_val = tf.Variable(123.456,tf.float32)string_val = tf.Variable(“hello everyone. Nice to learn tensorflow!”,tf.string)"
},
{
"code": null,
"e": 5399,
"s": 5333,
"text": "And now, it’s very easy to print out the values of these Tensors!"
},
{
"code": null,
"e": 5501,
"s": 5399,
"text": "#Let us display the values (print) these tensorsprint(scalar_val)print(floating_val)print(string_val)"
},
{
"code": null,
"e": 5560,
"s": 5501,
"text": "<tf.Variable ‘Variable:0’ shape=() dtype=int32, numpy=123>"
},
{
"code": null,
"e": 5726,
"s": 5560,
"text": "<tf.Variable ‘Variable:0’ shape=() dtype=float32, numpy=123.456> <tf.Variable ‘Variable:0’ shape=() dtype=string, numpy=b’hello everyone. Nice to learn tensorflow!’>"
},
{
"code": null,
"e": 6057,
"s": 5726,
"text": "We can determine the shape and rank of the Tensors, like you might have heard in mathematics modules at school. If not, shape simply refers to the number of elements which are contained along each dimension of the tensor. While rank is the deepest level of nesting within the Tensor. Going into some code might make it more clear."
},
{
"code": null,
"e": 6319,
"s": 6057,
"text": "#The idea behind shape and rank of tensors#Shape: Describes the dimension of the tensor (total elements contained along each dimension)scalar_val_shap = tf.shape(scalar_val)print(scalar_val_shap)floating_val_shap = tf.shape(floating_val)print(floating_val_shap)"
},
{
"code": null,
"e": 6358,
"s": 6319,
"text": "tf.Tensor([], shape=(0,), dtype=int32)"
},
{
"code": null,
"e": 6397,
"s": 6358,
"text": "tf.Tensor([], shape=(0,), dtype=int32)"
},
{
"code": null,
"e": 6505,
"s": 6397,
"text": "So we get a shape of 0 right? It just means that these are scalar values rather than lists or nested lists."
},
{
"code": null,
"e": 6926,
"s": 6505,
"text": "#Now, if we use e.g. lists/nested lists instead of just a “single” scalar valuelist_tensor1 = tf.Variable([1,3,5,6],tf.int16)print(list_tensor1)print(tf.shape(list_tensor1))list_tensor2 = tf.Variable([[1,2,3],[4,5,6]],tf.int16)print(list_tensor2)print(tf.shape(list_tensor2))#how about the rank? It describes the level of nesting within the tensor in simple words.print(tf.rank(list_tensor1))print(tf.rank(list_tensor2))"
},
{
"code": null,
"e": 7230,
"s": 6926,
"text": "You can see that the list_tensor1 has 4 elements, so that’s what gives it a shape of (4,). Note that (4,) is nothing but (4,1), just showing 4 elements within a single list. Next, for list_tensor2, observe a shape of (2,3) signifying that we have a nested list- with 2 lists, each containing 3 elements."
},
{
"code": null,
"e": 7320,
"s": 7230,
"text": "<tf.Variable ‘Variable:0’ shape=(4,) dtype=int32, numpy=array([1, 3, 5, 6], dtype=int32)>"
},
{
"code": null,
"e": 7360,
"s": 7320,
"text": "tf.Tensor([4], shape=(1,), dtype=int32)"
},
{
"code": null,
"e": 7462,
"s": 7360,
"text": "<tf.Variable ‘Variable:0’ shape=(2, 3) dtype=int32, numpy=array([[1, 2, 3], [4, 5, 6]], dtype=int32)>"
},
{
"code": null,
"e": 7504,
"s": 7462,
"text": "tf.Tensor([2 3], shape=(2,), dtype=int32)"
},
{
"code": null,
"e": 7540,
"s": 7504,
"text": "tf.Tensor(1, shape=(), dtype=int32)"
},
{
"code": null,
"e": 7576,
"s": 7540,
"text": "tf.Tensor(2, shape=(), dtype=int32)"
},
{
"code": null,
"e": 8022,
"s": 7576,
"text": "Similarly, if you look at the rank, you see a rank of 1 for the list_tensor1, simply because we just have a single list, no nesting here! Now, for list_tensor2, you can see a rank of 2- signifying that we have a level 2 nesting i.e. a big list contains more lists. Had it been something like one big list, contains another small list, and that small list contains more smaller lists, we would have had a rank of 3. Hope this would make it clear."
},
{
"code": null,
"e": 8058,
"s": 8022,
"text": "tf.Tensor(1, shape=(), dtype=int32)"
},
{
"code": null,
"e": 8094,
"s": 8058,
"text": "tf.Tensor(2, shape=(), dtype=int32)"
},
{
"code": null,
"e": 8254,
"s": 8094,
"text": "We can change the shape of the tensors (of course, until it is mathematically valid) using tf.reshape. Again, note the specialised way to do this using Python."
},
{
"code": null,
"e": 8846,
"s": 8254,
"text": "#Reshaping tensorsreshaped_list_tensor2 = tf.reshape(list_tensor2,[6])print(reshaped_list_tensor2)list_tensor3 = tf.Variable([[1,2,3,1],[1,9,10,11],[1,5,11,22],[16,17,18,19]],tf.int16)print(list_tensor3)print(tf.rank(list_tensor3))print(tf.shape(list_tensor3))reshaped_list_tensor3 = tf.reshape(list_tensor3,[2,8,1])print(reshaped_list_tensor3)#or like thisreshaped_list_tensor3 = tf.reshape(list_tensor3,[8,2,1])print(reshaped_list_tensor3)#or automatically determine the shape by only giving one dimension!reshaped_list_tensor3 = tf.reshape(list_tensor3,[1,-1])print(reshaped_list_tensor3)"
},
{
"code": null,
"e": 9756,
"s": 8846,
"text": "And you get the following outputs. It's too long to probably give a read, but I guess if you check out the Colab Notebook here, it would be clearer. The basic thing happening here is that if you specify [6] here for the shape, tensorflow would reshape your tensors to have 6 elements with a single dimension (so it would be simply a 1D list). If you do a [2,8,1], it would make 2 lists, each with 8 elements. You could also do [8,2,1]- creating 8 lists, each with 2 elements as you would see. If you don’t want to go into specifying the whole of dimensions for the reshape yourself, you could as well simply use a -1. So, a reshape of [1,-1] would reshape the list_tensor3 to create reshaped_list_tensor3, so 1 list with ??? Yes, 16 elements. So note that while you could use reshape however you want, it is essential to ensure that the total number of elements after reshape do not change during the process."
},
{
"code": null,
"e": 9806,
"s": 9756,
"text": "tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32)"
},
{
"code": null,
"e": 9953,
"s": 9806,
"text": "<tf.Variable ‘Variable:0’ shape=(4, 4) dtype=int32, numpy=array([[ 1, 2, 3, 1], [ 1, 9, 10, 11], [ 1, 5, 11, 22], [16, 17, 18, 19]], dtype=int32)>"
},
{
"code": null,
"e": 9989,
"s": 9953,
"text": "tf.Tensor(2, shape=(), dtype=int32)"
},
{
"code": null,
"e": 10031,
"s": 9989,
"text": "tf.Tensor([4 4], shape=(2,), dtype=int32)"
},
{
"code": null,
"e": 10159,
"s": 10031,
"text": "tf.Tensor( [[[ 1] [ 2] [ 3] [ 1] [ 1] [ 9] [10] [11]] [[ 1] [ 5] [11] [22] [16] [17] [18] [19]]], shape=(2, 8, 1), dtype=int32)"
},
{
"code": null,
"e": 10299,
"s": 10159,
"text": "tf.Tensor( [[[ 1] [ 2]] [[ 3] [ 1]] [[ 1] [ 9]] [[10] [11]] [[ 1] [ 5]] [[11] [22]] [[16] [17]] [[18] [19]]], shape=(8, 2, 1), dtype=int32)"
},
{
"code": null,
"e": 10383,
"s": 10299,
"text": "tf.Tensor([[ 1 2 3 1 1 9 10 11 1 5 11 22 16 17 18 19]], shape=(1, 16), dtype=int32)"
},
{
"code": null,
"e": 10533,
"s": 10383,
"text": "You could create a Tensor full of 1s (or 0s) using special commands tf.ones or tf.zeros. And then, similar operations could be performed on them too."
},
{
"code": null,
"e": 11062,
"s": 10533,
"text": "Now, we come to slicing. Just like you could slice and extract some elements from a matrix or a Python list for instance, you could do the same with Tensors. See an example below, wherein, we first create a onefull tensor (my name for a tensor full of 1 values only) and another with zerofull. The dimensions of the tensors you want to create go within the square brackets [], so a [4,4,4,1] creates a 4D tensor, while a [5,5] creates a 2D tensor- with 5 rows and 5 columns (which is nothing but a matrix) in the simplest sense."
},
{
"code": null,
"e": 11230,
"s": 11062,
"text": "Some slicing operations are shown below for these created tensors. So that you can get the elements you like from the tensors and not consider those you don’t like :-)"
},
{
"code": null,
"e": 11611,
"s": 11230,
"text": "#creating a tensor full of 1s (or 0s)tensor_onefull = tf.ones([4,4,4,1])print(tensor_onefull)tensor_zerofull = tf.zeros([5,5])print(tensor_zerofull)#extracting specific values from tensors (similar to slicing in conventional programming)tensor_sliced_onefull = tensor_onefull[0]print(tensor_sliced_onefull)tensor_sliced_zerofull = tensor_zerofull[0,1]print(tensor_sliced_zerofull)"
},
{
"code": null,
"e": 11680,
"s": 11611,
"text": "And here is the nice output (better readable in the Colab notebook)."
},
{
"code": null,
"e": 12089,
"s": 11680,
"text": "tf.Tensor( [[[[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.] [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.]] [[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]]]], shape=(4, 4, 4, 1), dtype=float32)"
},
{
"code": null,
"e": 12217,
"s": 12089,
"text": "tf.Tensor( [[0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]], shape=(5, 5), dtype=float32)"
},
{
"code": null,
"e": 12351,
"s": 12217,
"text": "tf.Tensor( [[[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]] [[1.] [1.] [1.] [1.]]], shape=(4, 4, 1), dtype=float32)"
},
{
"code": null,
"e": 12391,
"s": 12351,
"text": "tf.Tensor(0.0, shape=(), dtype=float32)"
},
{
"code": null,
"e": 12622,
"s": 12391,
"text": "#another example from previously created tensorprint(list_tensor3)tf_slicedexampleagain = list_tensor3[0,-2:]print(tf_slicedexampleagain)#selecting multiple rowstf_slicedexampleagain = list_tensor3[1::]print(tf_slicedexampleagain)"
},
{
"code": null,
"e": 12700,
"s": 12622,
"text": "And again, some cool output (basic but yes, simplest things are the coolest)."
},
{
"code": null,
"e": 12847,
"s": 12700,
"text": "<tf.Variable ‘Variable:0’ shape=(4, 4) dtype=int32, numpy=array([[ 1, 2, 3, 1], [ 1, 9, 10, 11], [ 1, 5, 11, 22], [16, 17, 18, 19]], dtype=int32)>"
},
{
"code": null,
"e": 12889,
"s": 12847,
"text": "tf.Tensor([3 1], shape=(2,), dtype=int32)"
},
{
"code": null,
"e": 12970,
"s": 12889,
"text": "tf.Tensor( [[ 1 9 10 11] [ 1 5 11 22] [16 17 18 19]], shape=(3, 4), dtype=int32)"
},
{
"code": null,
"e": 13153,
"s": 12970,
"text": "You can find the complete Colab notebook for this article here on my Github https://github.com/joyjitchatterjee/DeepLearning-Tensorflow-Basics/blob/master/Tensorflow_Beginning.ipynb."
},
{
"code": null,
"e": 13322,
"s": 13153,
"text": "And that’s it. Hope you enjoyed reading this article. Thanks for the read, and apologies for any typos/bugs if any. I hope to cover more on Tensorflow in my next posts."
},
{
"code": null,
"e": 13418,
"s": 13322,
"text": "If you wish to, you can connect with me on LinkedIn at http://linkedin.com/in/joyjitchatterjee/"
},
{
"code": null,
"e": 13429,
"s": 13418,
"text": "REFERENCES"
},
{
"code": null,
"e": 13799,
"s": 13429,
"text": "Tensorflow documentation (https://www.tensorflow.org/guide)TensorFlow 2.0 Complete Course — Python Neural Networks for Beginners Tutorial (https://www.youtube.com/watch?v=tPYj3fFJGjk&list=PLYLyA78Q4izuAlaaOER3qwUZkqLTZf7qk)Get started with TensorFlow and Deep Learning (https://medium.com/@rishit.dagli/get-started-with-tensorflow-and-deep-learning-part-1-72c7d67f99fc)"
},
{
"code": null,
"e": 13859,
"s": 13799,
"text": "Tensorflow documentation (https://www.tensorflow.org/guide)"
},
{
"code": null,
"e": 14024,
"s": 13859,
"text": "TensorFlow 2.0 Complete Course — Python Neural Networks for Beginners Tutorial (https://www.youtube.com/watch?v=tPYj3fFJGjk&list=PLYLyA78Q4izuAlaaOER3qwUZkqLTZf7qk)"
}
] |
NLP | Sequence to Sequence Networks| Part 1| Processing text data | by Mohammed AL-Ma'amari | Towards Data Science
|
There are many benefits you can get by understanding NLP, you can make your own model to answer questions and use it in a chat bot, or you can make a translator to translate a text from your language to English language or the opposite, or maybe you make a text summarizer.
In this tutorial series, we will learn how to make a seq2seq network and train it to translate English text to French, or you can use it in another seq2seq purpose.
In this part of the series, we will learn about processing text data to feed it to the seq2seq network.
We will learn two methods to process texts
Character level processing
Word level processing ( using embedding)
I used a dataset of English → French sentences, You can get the dataset I used from [Here].
For other languages, you can get the datasets using [this] link
I explained the text processing steps in the next pictures :
So, to represent the word ball :
and, , to represent the sentence hello world! :
I hope that you got some intuition of the steps of processing the text data.
Now we will do some coding using python :
First, lets import numpy :
import numpy as np
Then, load the text file:
After that, split the samples and get the necessary dictionaries :
Make the needed dictionaries to convert characters to integers and the opposite :
Compute the length of the longest sample and some other variables:
Output :
Number of E Samples : 160872Number of D Samples : 160872Number of D Chars : 115Number of E Chars : 92The Longest D Sample has 351 CharsThe Longest E Sample has 286 Chars
E → the input text ( Will be encoded later )D → the output text ( Will be decoded later )
Next, we will One Hot Encode the samples by letters ex:
Hi — -> [[0,0,0,...,1,0,0,0],[0,0,0,...,0,1,0,0]] where we represent each sample as an array of zeros that has (n) rows and (j) columnsn = Number of Characters in the longest Samplej = number of chars in our dictionary
We will make three sets of data :1- Encoder Input Samples ( English sentences )2- Decoder Input Samples ( French sentences)3- Target ( French sentences)
Target will be the same data as Decoder Input but it will be one character ahead of it Ex : Decoder Input = ‘\tHow are yo’Target = ‘How are you’
[Output]:Shape of encoder_input_data : (160872, 286, 92) Shape of decoder_input_data : (160872, 351, 115) Shape of target_data : (160872, 351, 115)
Now, the data is ready to be used by a seq2seq model.
In this method, we do the same steps as the first method, but here instead of make a dictionary of characters, we make a dictionary of the words used in the text we want to process or sometimes we use the most frequent 10,000 words of the text’s language.
To make it easy to understand what we are going to do, we will :
Convert text to lowercaseClean data from digits and punctuation .append ‘SOS’ and ‘EOS’ to the target data:
Convert text to lowercase
Clean data from digits and punctuation .
append ‘SOS’ and ‘EOS’ to the target data:
SOS → Start of Sentience
EOS → End of Sentience
4. Make dictionaries to convert words to indexed numbers .
5. Use embedding layer to convert each word to a fixed length vector .
Word embeddings provide a dense representation of words and their relative meanings.
To learn more about word embeddings : [1] , [2], [3],[4]
6. Now, the data is ready to be used by seq2seq network.
Load the text data :
I will show the line where I used the embedding layer, the whole network will be explained in the next part of this tutorial series.
num_words : is the number of words in the dictionary we used to convert words to numbersvec_len : The length of the vector that will represent the words
In the next part [part 2] we will make the model and train it, then use it to translate English text to French.
All the references o this series will be at the end of the last part.
You can follow me on Twitter @ModMaamari
1- NLP | Sequence to Sequence Networks| Part 1| Processing text data
2- NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (Encoder Decoder Model)
AI Generates Taylor Swift’s Song Lyrics
Deep Neural Networks for Regression Problems
Machine Learning Crash Course with TensorFlow APIs Summary
How To Make A CNN Using Tensorflow and Keras
How to Choose the Best Machine Learning Model ?
|
[
{
"code": null,
"e": 445,
"s": 171,
"text": "There are many benefits you can get by understanding NLP, you can make your own model to answer questions and use it in a chat bot, or you can make a translator to translate a text from your language to English language or the opposite, or maybe you make a text summarizer."
},
{
"code": null,
"e": 610,
"s": 445,
"text": "In this tutorial series, we will learn how to make a seq2seq network and train it to translate English text to French, or you can use it in another seq2seq purpose."
},
{
"code": null,
"e": 714,
"s": 610,
"text": "In this part of the series, we will learn about processing text data to feed it to the seq2seq network."
},
{
"code": null,
"e": 757,
"s": 714,
"text": "We will learn two methods to process texts"
},
{
"code": null,
"e": 784,
"s": 757,
"text": "Character level processing"
},
{
"code": null,
"e": 825,
"s": 784,
"text": "Word level processing ( using embedding)"
},
{
"code": null,
"e": 917,
"s": 825,
"text": "I used a dataset of English → French sentences, You can get the dataset I used from [Here]."
},
{
"code": null,
"e": 981,
"s": 917,
"text": "For other languages, you can get the datasets using [this] link"
},
{
"code": null,
"e": 1042,
"s": 981,
"text": "I explained the text processing steps in the next pictures :"
},
{
"code": null,
"e": 1075,
"s": 1042,
"text": "So, to represent the word ball :"
},
{
"code": null,
"e": 1123,
"s": 1075,
"text": "and, , to represent the sentence hello world! :"
},
{
"code": null,
"e": 1200,
"s": 1123,
"text": "I hope that you got some intuition of the steps of processing the text data."
},
{
"code": null,
"e": 1242,
"s": 1200,
"text": "Now we will do some coding using python :"
},
{
"code": null,
"e": 1269,
"s": 1242,
"text": "First, lets import numpy :"
},
{
"code": null,
"e": 1288,
"s": 1269,
"text": "import numpy as np"
},
{
"code": null,
"e": 1314,
"s": 1288,
"text": "Then, load the text file:"
},
{
"code": null,
"e": 1381,
"s": 1314,
"text": "After that, split the samples and get the necessary dictionaries :"
},
{
"code": null,
"e": 1463,
"s": 1381,
"text": "Make the needed dictionaries to convert characters to integers and the opposite :"
},
{
"code": null,
"e": 1530,
"s": 1463,
"text": "Compute the length of the longest sample and some other variables:"
},
{
"code": null,
"e": 1539,
"s": 1530,
"text": "Output :"
},
{
"code": null,
"e": 1715,
"s": 1539,
"text": "Number of E Samples \t: 160872Number of D Samples \t: 160872Number of D Chars \t: 115Number of E Chars \t: 92The Longest D Sample has 351 CharsThe Longest E Sample has 286 Chars"
},
{
"code": null,
"e": 1805,
"s": 1715,
"text": "E → the input text ( Will be encoded later )D → the output text ( Will be decoded later )"
},
{
"code": null,
"e": 1861,
"s": 1805,
"text": "Next, we will One Hot Encode the samples by letters ex:"
},
{
"code": null,
"e": 2080,
"s": 1861,
"text": "Hi — -> [[0,0,0,...,1,0,0,0],[0,0,0,...,0,1,0,0]] where we represent each sample as an array of zeros that has (n) rows and (j) columnsn = Number of Characters in the longest Samplej = number of chars in our dictionary"
},
{
"code": null,
"e": 2233,
"s": 2080,
"text": "We will make three sets of data :1- Encoder Input Samples ( English sentences )2- Decoder Input Samples ( French sentences)3- Target ( French sentences)"
},
{
"code": null,
"e": 2378,
"s": 2233,
"text": "Target will be the same data as Decoder Input but it will be one character ahead of it Ex : Decoder Input = ‘\\tHow are yo’Target = ‘How are you’"
},
{
"code": null,
"e": 2533,
"s": 2378,
"text": "[Output]:Shape of encoder_input_data : (160872, 286, 92) Shape of decoder_input_data : (160872, 351, 115) Shape of target_data : (160872, 351, 115)"
},
{
"code": null,
"e": 2587,
"s": 2533,
"text": "Now, the data is ready to be used by a seq2seq model."
},
{
"code": null,
"e": 2843,
"s": 2587,
"text": "In this method, we do the same steps as the first method, but here instead of make a dictionary of characters, we make a dictionary of the words used in the text we want to process or sometimes we use the most frequent 10,000 words of the text’s language."
},
{
"code": null,
"e": 2908,
"s": 2843,
"text": "To make it easy to understand what we are going to do, we will :"
},
{
"code": null,
"e": 3016,
"s": 2908,
"text": "Convert text to lowercaseClean data from digits and punctuation .append ‘SOS’ and ‘EOS’ to the target data:"
},
{
"code": null,
"e": 3042,
"s": 3016,
"text": "Convert text to lowercase"
},
{
"code": null,
"e": 3083,
"s": 3042,
"text": "Clean data from digits and punctuation ."
},
{
"code": null,
"e": 3126,
"s": 3083,
"text": "append ‘SOS’ and ‘EOS’ to the target data:"
},
{
"code": null,
"e": 3151,
"s": 3126,
"text": "SOS → Start of Sentience"
},
{
"code": null,
"e": 3174,
"s": 3151,
"text": "EOS → End of Sentience"
},
{
"code": null,
"e": 3233,
"s": 3174,
"text": "4. Make dictionaries to convert words to indexed numbers ."
},
{
"code": null,
"e": 3304,
"s": 3233,
"text": "5. Use embedding layer to convert each word to a fixed length vector ."
},
{
"code": null,
"e": 3389,
"s": 3304,
"text": "Word embeddings provide a dense representation of words and their relative meanings."
},
{
"code": null,
"e": 3446,
"s": 3389,
"text": "To learn more about word embeddings : [1] , [2], [3],[4]"
},
{
"code": null,
"e": 3503,
"s": 3446,
"text": "6. Now, the data is ready to be used by seq2seq network."
},
{
"code": null,
"e": 3524,
"s": 3503,
"text": "Load the text data :"
},
{
"code": null,
"e": 3657,
"s": 3524,
"text": "I will show the line where I used the embedding layer, the whole network will be explained in the next part of this tutorial series."
},
{
"code": null,
"e": 3810,
"s": 3657,
"text": "num_words : is the number of words in the dictionary we used to convert words to numbersvec_len : The length of the vector that will represent the words"
},
{
"code": null,
"e": 3922,
"s": 3810,
"text": "In the next part [part 2] we will make the model and train it, then use it to translate English text to French."
},
{
"code": null,
"e": 3992,
"s": 3922,
"text": "All the references o this series will be at the end of the last part."
},
{
"code": null,
"e": 4033,
"s": 3992,
"text": "You can follow me on Twitter @ModMaamari"
},
{
"code": null,
"e": 4102,
"s": 4033,
"text": "1- NLP | Sequence to Sequence Networks| Part 1| Processing text data"
},
{
"code": null,
"e": 4187,
"s": 4102,
"text": "2- NLP | Sequence to Sequence Networks| Part 2|Seq2seq Model (Encoder Decoder Model)"
},
{
"code": null,
"e": 4227,
"s": 4187,
"text": "AI Generates Taylor Swift’s Song Lyrics"
},
{
"code": null,
"e": 4272,
"s": 4227,
"text": "Deep Neural Networks for Regression Problems"
},
{
"code": null,
"e": 4331,
"s": 4272,
"text": "Machine Learning Crash Course with TensorFlow APIs Summary"
},
{
"code": null,
"e": 4376,
"s": 4331,
"text": "How To Make A CNN Using Tensorflow and Keras"
}
] |
SciPy Graphs
|
Graphs are an essential data structure.
SciPy provides us with the module scipy.sparse.csgraph for working with
such data structures.
Adjacency matrix is a nxn matrix where n
is the number of elements in a graph.
And the values represents the connection between the elements.
Example:
For a graph like this, with elements A, B and C, the connections are:
A & B are connected with weight 1.
A & C are connected with weight 2.
C & B is not connected.
The Adjency Matrix would look like this:
A B C
A:[0 1 2]
B:[1 0 0]
C:[2 0 0]
Below follows some of the most used methods for working with adjacency matrices.
Use the dijkstra method to find the shortest path in a graph from one element to
another.
It takes following arguments:
return_predecessors: boolean (True to return whole path of traversal
otherwise False).
indices: index of the element to return all paths from that element only.
limit: max weight of path.
return_predecessors: boolean (True to return whole path of traversal
otherwise False).
indices: index of the element to return all paths from that element only.
limit: max weight of path.
Find the shortest path from element 1 to 2:
Use the floyd_warshall() method to find shortest path between all pairs of elements.
Find the shortest path between all pairs of elements:
The bellman_ford() method can also find the shortest path between all pairs of elements, but this method can handle negative weights as well.
Find shortest path from element 1 to 2 with given graph with a negative weight:
The depth_first_order() method returns a depth first traversal from a node.
This function takes following arguments:
the graph.
the starting element to traverse graph from.
the graph.
the starting element to traverse graph from.
Traverse the graph depth first for given adjacency matrix:
The breadth_first_order() method returns a breadth first traversal from a node.
This function takes following arguments:
the graph.
the starting element to traverse graph from.
the graph.
the starting element to traverse graph from.
Traverse the graph breadth first for given adjacency matrix:
Insert the missing method to find all the connected components:
import numpy as np
from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix
arr = np.array([
[0, 1, 2],
[1, 0, 0],
[2, 0, 0]
])
newarr = csr_matrix(arr)
print((newarr))
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 40,
"s": 0,
"text": "Graphs are an essential data structure."
},
{
"code": null,
"e": 135,
"s": 40,
"text": "SciPy provides us with the module scipy.sparse.csgraph for working with \nsuch data structures."
},
{
"code": null,
"e": 214,
"s": 135,
"text": "Adjacency matrix is a nxn matrix where n\nis the number of elements in a graph."
},
{
"code": null,
"e": 277,
"s": 214,
"text": "And the values represents the connection between the elements."
},
{
"code": null,
"e": 286,
"s": 277,
"text": "Example:"
},
{
"code": null,
"e": 356,
"s": 286,
"text": "For a graph like this, with elements A, B and C, the connections are:"
},
{
"code": null,
"e": 391,
"s": 356,
"text": "A & B are connected with weight 1."
},
{
"code": null,
"e": 426,
"s": 391,
"text": "A & C are connected with weight 2."
},
{
"code": null,
"e": 450,
"s": 426,
"text": "C & B is not connected."
},
{
"code": null,
"e": 491,
"s": 450,
"text": "The Adjency Matrix would look like this:"
},
{
"code": null,
"e": 547,
"s": 491,
"text": "\n A B C\n A:[0 1 2] \n B:[1 0 0]\n C:[2 0 0]\n\n"
},
{
"code": null,
"e": 628,
"s": 547,
"text": "Below follows some of the most used methods for working with adjacency matrices."
},
{
"code": null,
"e": 719,
"s": 628,
"text": "Use the dijkstra method to find the shortest path in a graph from one element to \nanother."
},
{
"code": null,
"e": 749,
"s": 719,
"text": "It takes following arguments:"
},
{
"code": null,
"e": 940,
"s": 749,
"text": "\nreturn_predecessors: boolean (True to return whole path of traversal \notherwise False).\nindices: index of the element to return all paths from that element only.\nlimit: max weight of path.\n"
},
{
"code": null,
"e": 1028,
"s": 940,
"text": "return_predecessors: boolean (True to return whole path of traversal \notherwise False)."
},
{
"code": null,
"e": 1102,
"s": 1028,
"text": "indices: index of the element to return all paths from that element only."
},
{
"code": null,
"e": 1129,
"s": 1102,
"text": "limit: max weight of path."
},
{
"code": null,
"e": 1173,
"s": 1129,
"text": "Find the shortest path from element 1 to 2:"
},
{
"code": null,
"e": 1258,
"s": 1173,
"text": "Use the floyd_warshall() method to find shortest path between all pairs of elements."
},
{
"code": null,
"e": 1312,
"s": 1258,
"text": "Find the shortest path between all pairs of elements:"
},
{
"code": null,
"e": 1454,
"s": 1312,
"text": "The bellman_ford() method can also find the shortest path between all pairs of elements, but this method can handle negative weights as well."
},
{
"code": null,
"e": 1534,
"s": 1454,
"text": "Find shortest path from element 1 to 2 with given graph with a negative weight:"
},
{
"code": null,
"e": 1610,
"s": 1534,
"text": "The depth_first_order() method returns a depth first traversal from a node."
},
{
"code": null,
"e": 1651,
"s": 1610,
"text": "This function takes following arguments:"
},
{
"code": null,
"e": 1709,
"s": 1651,
"text": "\nthe graph.\nthe starting element to traverse graph from.\n"
},
{
"code": null,
"e": 1720,
"s": 1709,
"text": "the graph."
},
{
"code": null,
"e": 1765,
"s": 1720,
"text": "the starting element to traverse graph from."
},
{
"code": null,
"e": 1824,
"s": 1765,
"text": "Traverse the graph depth first for given adjacency matrix:"
},
{
"code": null,
"e": 1904,
"s": 1824,
"text": "The breadth_first_order() method returns a breadth first traversal from a node."
},
{
"code": null,
"e": 1945,
"s": 1904,
"text": "This function takes following arguments:"
},
{
"code": null,
"e": 2003,
"s": 1945,
"text": "\nthe graph.\nthe starting element to traverse graph from.\n"
},
{
"code": null,
"e": 2014,
"s": 2003,
"text": "the graph."
},
{
"code": null,
"e": 2059,
"s": 2014,
"text": "the starting element to traverse graph from."
},
{
"code": null,
"e": 2120,
"s": 2059,
"text": "Traverse the graph breadth first for given adjacency matrix:"
},
{
"code": null,
"e": 2184,
"s": 2120,
"text": "Insert the missing method to find all the connected components:"
},
{
"code": null,
"e": 2396,
"s": 2184,
"text": "import numpy as np\nfrom scipy.sparse.csgraph import connected_components\nfrom scipy.sparse import csr_matrix\n\narr = np.array([\n [0, 1, 2],\n [1, 0, 0],\n [2, 0, 0]\n])\n\nnewarr = csr_matrix(arr)\n\nprint((newarr))\n"
},
{
"code": null,
"e": 2415,
"s": 2396,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2448,
"s": 2415,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2490,
"s": 2448,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2597,
"s": 2490,
"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": 2616,
"s": 2597,
"text": "help@w3schools.com"
}
] |
Hidden Form Field using Annotation | Java Servlet - GeeksforGeeks
|
26 May, 2021
Hidden form field is used to store session information of a client. In this method, we create a hidden form which passes the control to the servlet whose path is given in the form action area. Using this, the information of the user is stored and passed to the location where we want to send data. The main advantage of using Hidden form filed that it doesn’t depend on the browser. Even If the cookies are disabled or not hidden, form filed will work perfectly.
Example
Java
out.print("<form action='SecondServlet'>");out.print("<input type='hidden' name='username'value='" + n + "'>");out.print("<input type='submit' value='submit'>");out.print("</form>");
A complete example of Hidden form field method
In this method we are transferring the client detail from firstServlet to Second Servlet
Index.html
HTML
<!DOCTYPE html><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body> <form action="FirstServlet" method="Post"> <!-- Move the control to firstServlet --> Name:<input type="text" name="userName" /><br /> <input type="submit" value="submit" /> </form></body></html>
Output
FirstServlet.java
Java
// Java program to demonstrate// Hidden form field method package GeeksforGeeks; import java.io.*;import javax.servlet.*;import javax.servlet.annotation.WebServlet;import javax.servlet.http.*; @WebServlet("/FirstServlet") // this annotation is used for replacing xml filepublic class FirstServlet extends HttpServlet { // class name is FirstServlet which extends HttpServlet public void doPost(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); /* The response's character encoding is only set from the given content type if this method is called before getWriter is called. This method may be called repeatedly to change content type and character encoding. */ PrintWriter out = response.getWriter(); /* The Java PrintWriter class ( java.io.PrintWriter ) enables you to write formatted data to an underlying Writer . For instance, writing int, long and other primitive data formatted as text, rather than as their byte values */ String username = request.getParameter("userName"); /* request.getParameter takes the value from index.html file where name is username */ out.print("Welcome " + username); // out.println is used to print on the client web browser /* In the below code their is a hidden formfor maintaining session of user. this passes control to SecondServlet */ out.print("<form action='SecondServlet'>"); out.print("<input type='hidden' name='username' value='" + username + "'>"); out.print("<input type='submit' value='submit'>"); out.print("</form>"); out.close(); } catch (Exception e) { System.out.println(e); } }}
Output
SecondServlet
Java
// Java program to demonstrate// Hidden form field method package GeeksforGeeks; import java.io.*;import javax.servlet.*;import javax.servlet.annotation.WebServlet; // Importing annotationimport javax.servlet.http.*; // using this annotation we dont need// xml file for dispathing servlet@WebServlet("/SecondServlet") public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("text/html"); /* The response's character encoding is only set from the given content type if this method is called before getWriter is called. This method may be called repeatedly to change content type and character encoding. */ PrintWriter out = response.getWriter(); /* The Java PrintWriter class ( java.io.PrintWriter ) enables you to write formatted data to an underlying Writer . For instance, writing int, long and other primitive data formatted as text, rather than as their byte values */ // getting value from the query string String username = request.getParameter("username"); // taking the value of usename from First servlet using getparameter object out.print("WELCOME " + username); // out.println is used to print on the client web browser out.close(); } catch (Exception e) { System.out.println(e); } }}
Output
Step by Step processing of the code As you Deploy the project and run the code on the server following process goes on.
Control goes to index.html file and a form is generated on web browser and it will ask for your username.In index.html file form, action is FirstServlet so when you hit submit button, control goes to FirstServlet and your session is start.In FirstServlet request.getParameter(username), take the input from index.html where the field is username and print it on the browser.In firstServlet there is a hidden form field which again takes the input from browser and pass the control to second servlet.This method goes on for a number of different Servlet. Note : This is the main disadvantage of Hidden form field method that you have to fill the form again and again for maintaining a client session.In Second Servlet we again use request.getParameter for getting input from FirstServlet page.
Control goes to index.html file and a form is generated on web browser and it will ask for your username.
In index.html file form, action is FirstServlet so when you hit submit button, control goes to FirstServlet and your session is start.
In FirstServlet request.getParameter(username), take the input from index.html where the field is username and print it on the browser.
In firstServlet there is a hidden form field which again takes the input from browser and pass the control to second servlet.
This method goes on for a number of different Servlet. Note : This is the main disadvantage of Hidden form field method that you have to fill the form again and again for maintaining a client session.
In Second Servlet we again use request.getParameter for getting input from FirstServlet page.
Advantage and Applications
It can be used for anonymous session tracking.
Hidden form field is supported in every Browser. This method of session tracking does not need any special configuration of the browser.
All the information is stored in client browser, so it increases the security
Disadvantage :
It works only for a sequence of dynamically generated forms. This breaks down with static documents, emailed documents, bookmarked documents, and browser shutdowns.You need to submit an extra form on each request.It’s complex than URL rewriting.This method use only textual information.
It works only for a sequence of dynamically generated forms. This breaks down with static documents, emailed documents, bookmarked documents, and browser shutdowns.
You need to submit an extra form on each request.
It’s complex than URL rewriting.
This method use only textual information.
sweetyty
java-servlet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
Difference between Abstract Class and Interface in Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 24020,
"s": 23557,
"text": "Hidden form field is used to store session information of a client. In this method, we create a hidden form which passes the control to the servlet whose path is given in the form action area. Using this, the information of the user is stored and passed to the location where we want to send data. The main advantage of using Hidden form filed that it doesn’t depend on the browser. Even If the cookies are disabled or not hidden, form filed will work perfectly."
},
{
"code": null,
"e": 24029,
"s": 24020,
"text": "Example "
},
{
"code": null,
"e": 24034,
"s": 24029,
"text": "Java"
},
{
"code": "out.print(\"<form action='SecondServlet'>\");out.print(\"<input type='hidden' name='username'value='\" + n + \"'>\");out.print(\"<input type='submit' value='submit'>\");out.print(\"</form>\");",
"e": 24217,
"s": 24034,
"text": null
},
{
"code": null,
"e": 24266,
"s": 24219,
"text": "A complete example of Hidden form field method"
},
{
"code": null,
"e": 24356,
"s": 24266,
"text": "In this method we are transferring the client detail from firstServlet to Second Servlet "
},
{
"code": null,
"e": 24369,
"s": 24356,
"text": "Index.html "
},
{
"code": null,
"e": 24374,
"s": 24369,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Insert title here</title></head><body> <form action=\"FirstServlet\" method=\"Post\"> <!-- Move the control to firstServlet --> Name:<input type=\"text\" name=\"userName\" /><br /> <input type=\"submit\" value=\"submit\" /> </form></body></html>",
"e": 24706,
"s": 24374,
"text": null
},
{
"code": null,
"e": 24714,
"s": 24706,
"text": "Output "
},
{
"code": null,
"e": 24733,
"s": 24714,
"text": "FirstServlet.java "
},
{
"code": null,
"e": 24738,
"s": 24733,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Hidden form field method package GeeksforGeeks; import java.io.*;import javax.servlet.*;import javax.servlet.annotation.WebServlet;import javax.servlet.http.*; @WebServlet(\"/FirstServlet\") // this annotation is used for replacing xml filepublic class FirstServlet extends HttpServlet { // class name is FirstServlet which extends HttpServlet public void doPost(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType(\"text/html\"); /* The response's character encoding is only set from the given content type if this method is called before getWriter is called. This method may be called repeatedly to change content type and character encoding. */ PrintWriter out = response.getWriter(); /* The Java PrintWriter class ( java.io.PrintWriter ) enables you to write formatted data to an underlying Writer . For instance, writing int, long and other primitive data formatted as text, rather than as their byte values */ String username = request.getParameter(\"userName\"); /* request.getParameter takes the value from index.html file where name is username */ out.print(\"Welcome \" + username); // out.println is used to print on the client web browser /* In the below code their is a hidden formfor maintaining session of user. this passes control to SecondServlet */ out.print(\"<form action='SecondServlet'>\"); out.print(\"<input type='hidden' name='username' value='\" + username + \"'>\"); out.print(\"<input type='submit' value='submit'>\"); out.print(\"</form>\"); out.close(); } catch (Exception e) { System.out.println(e); } }}",
"e": 26730,
"s": 24738,
"text": null
},
{
"code": null,
"e": 26738,
"s": 26730,
"text": "Output "
},
{
"code": null,
"e": 26753,
"s": 26738,
"text": "SecondServlet "
},
{
"code": null,
"e": 26758,
"s": 26753,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Hidden form field method package GeeksforGeeks; import java.io.*;import javax.servlet.*;import javax.servlet.annotation.WebServlet; // Importing annotationimport javax.servlet.http.*; // using this annotation we dont need// xml file for dispathing servlet@WebServlet(\"/SecondServlet\") public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType(\"text/html\"); /* The response's character encoding is only set from the given content type if this method is called before getWriter is called. This method may be called repeatedly to change content type and character encoding. */ PrintWriter out = response.getWriter(); /* The Java PrintWriter class ( java.io.PrintWriter ) enables you to write formatted data to an underlying Writer . For instance, writing int, long and other primitive data formatted as text, rather than as their byte values */ // getting value from the query string String username = request.getParameter(\"username\"); // taking the value of usename from First servlet using getparameter object out.print(\"WELCOME \" + username); // out.println is used to print on the client web browser out.close(); } catch (Exception e) { System.out.println(e); } }}",
"e": 28337,
"s": 26758,
"text": null
},
{
"code": null,
"e": 28345,
"s": 28337,
"text": "Output "
},
{
"code": null,
"e": 28466,
"s": 28345,
"text": "Step by Step processing of the code As you Deploy the project and run the code on the server following process goes on. "
},
{
"code": null,
"e": 29259,
"s": 28466,
"text": "Control goes to index.html file and a form is generated on web browser and it will ask for your username.In index.html file form, action is FirstServlet so when you hit submit button, control goes to FirstServlet and your session is start.In FirstServlet request.getParameter(username), take the input from index.html where the field is username and print it on the browser.In firstServlet there is a hidden form field which again takes the input from browser and pass the control to second servlet.This method goes on for a number of different Servlet. Note : This is the main disadvantage of Hidden form field method that you have to fill the form again and again for maintaining a client session.In Second Servlet we again use request.getParameter for getting input from FirstServlet page."
},
{
"code": null,
"e": 29365,
"s": 29259,
"text": "Control goes to index.html file and a form is generated on web browser and it will ask for your username."
},
{
"code": null,
"e": 29500,
"s": 29365,
"text": "In index.html file form, action is FirstServlet so when you hit submit button, control goes to FirstServlet and your session is start."
},
{
"code": null,
"e": 29636,
"s": 29500,
"text": "In FirstServlet request.getParameter(username), take the input from index.html where the field is username and print it on the browser."
},
{
"code": null,
"e": 29762,
"s": 29636,
"text": "In firstServlet there is a hidden form field which again takes the input from browser and pass the control to second servlet."
},
{
"code": null,
"e": 29963,
"s": 29762,
"text": "This method goes on for a number of different Servlet. Note : This is the main disadvantage of Hidden form field method that you have to fill the form again and again for maintaining a client session."
},
{
"code": null,
"e": 30057,
"s": 29963,
"text": "In Second Servlet we again use request.getParameter for getting input from FirstServlet page."
},
{
"code": null,
"e": 30086,
"s": 30057,
"text": "Advantage and Applications "
},
{
"code": null,
"e": 30133,
"s": 30086,
"text": "It can be used for anonymous session tracking."
},
{
"code": null,
"e": 30270,
"s": 30133,
"text": "Hidden form field is supported in every Browser. This method of session tracking does not need any special configuration of the browser."
},
{
"code": null,
"e": 30348,
"s": 30270,
"text": "All the information is stored in client browser, so it increases the security"
},
{
"code": null,
"e": 30364,
"s": 30348,
"text": "Disadvantage : "
},
{
"code": null,
"e": 30651,
"s": 30364,
"text": "It works only for a sequence of dynamically generated forms. This breaks down with static documents, emailed documents, bookmarked documents, and browser shutdowns.You need to submit an extra form on each request.It’s complex than URL rewriting.This method use only textual information."
},
{
"code": null,
"e": 30816,
"s": 30651,
"text": "It works only for a sequence of dynamically generated forms. This breaks down with static documents, emailed documents, bookmarked documents, and browser shutdowns."
},
{
"code": null,
"e": 30866,
"s": 30816,
"text": "You need to submit an extra form on each request."
},
{
"code": null,
"e": 30899,
"s": 30866,
"text": "It’s complex than URL rewriting."
},
{
"code": null,
"e": 30941,
"s": 30899,
"text": "This method use only textual information."
},
{
"code": null,
"e": 30952,
"s": 30943,
"text": "sweetyty"
},
{
"code": null,
"e": 30965,
"s": 30952,
"text": "java-servlet"
},
{
"code": null,
"e": 30970,
"s": 30965,
"text": "Java"
},
{
"code": null,
"e": 30975,
"s": 30970,
"text": "Java"
},
{
"code": null,
"e": 31073,
"s": 30975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31082,
"s": 31073,
"text": "Comments"
},
{
"code": null,
"e": 31095,
"s": 31082,
"text": "Old Comments"
},
{
"code": null,
"e": 31125,
"s": 31095,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31140,
"s": 31125,
"text": "Stream In Java"
},
{
"code": null,
"e": 31161,
"s": 31140,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31207,
"s": 31161,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31226,
"s": 31207,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31243,
"s": 31226,
"text": "Generics in Java"
},
{
"code": null,
"e": 31286,
"s": 31243,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31302,
"s": 31286,
"text": "Strings in Java"
},
{
"code": null,
"e": 31358,
"s": 31302,
"text": "Difference between Abstract Class and Interface in Java"
}
] |
Java Program for Reverse a linked list - GeeksforGeeks
|
17 Jan, 2018
Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes.
Examples:
Input : Head of following linked list
1->2->3->4->NULL
Output : Linked list should be changed to,
4->3->2->1->NULL
Input : Head of following linked list
1->2->3->4->5->NULL
Output : Linked list should be changed to,
5->4->3->2->1->NULL
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
Iterative Method
// Java program for reversing the linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to reverse the linked list */ Node reverse(Node node) { Node prev = null; Node current = node; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; return node; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(85); list.head.next = new Node(15); list.head.next.next = new Node(4); list.head.next.next.next = new Node(20); System.out.println("Given Linked list"); list.printList(head); head = list.reverse(head); System.out.println(""); System.out.println("Reversed linked list "); list.printList(head); }} // This code has been contributed by Mayank Jaiswal
Recursive Method:
void recursiveReverse(struct Node** head_ref){ struct Node* first; struct Node* rest; /* empty list */ if (*head_ref == NULL) return; /* suppose first = {1, 2, 3}, rest = {2, 3} */ first = *head_ref; rest = first->next; /* List has only one node */ if (rest == NULL) return; /* reverse the rest list and put the first element at the end */ recursiveReverse(&rest); first->next->next = first; /* tricky step -- see the diagram */ first->next = NULL; /* fix the head pointer */ *head_ref = rest; }
A Simpler and Tail Recursive Method
// Java program for reversing the Linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } // A simple and tail recursive function to reverse // a linked list. prev is passed as NULL initially. Node reverseUtil(Node curr, Node prev) { /* If last node mark it head*/ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return null; } /* Save curr->next node for recursive call */ Node next1 = curr.next; /* and update next ..*/ curr.next = prev; reverseUtil(next1, curr); return head; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); list.head.next.next.next.next.next.next.next = new Node(8); System.out.println("Original Linked list "); list.printList(head); Node res = list.reverseUtil(head, null); System.out.println(""); System.out.println(""); System.out.println("Reversed linked list "); list.printList(res); }}// This code has been contributed by Mayank Jaiswal
Please refer complete article on Reverse a linked list for more details!
Java Programs
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Modulo or Remainder Operator in Java
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
|
[
{
"code": null,
"e": 24616,
"s": 24588,
"text": "\n17 Jan, 2018"
},
{
"code": null,
"e": 24766,
"s": 24616,
"text": "Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes."
},
{
"code": null,
"e": 24776,
"s": 24766,
"text": "Examples:"
},
{
"code": null,
"e": 25109,
"s": 24776,
"text": "Input : Head of following linked list \n 1->2->3->4->NULL\nOutput : Linked list should be changed to,\n 4->3->2->1->NULL\n\nInput : Head of following linked list \n 1->2->3->4->5->NULL\nOutput : Linked list should be changed to,\n 5->4->3->2->1->NULL\n\nInput : NULL\nOutput : NULL\n\nInput : 1->NULL\nOutput : 1->NULL\n"
},
{
"code": null,
"e": 25126,
"s": 25109,
"text": "Iterative Method"
},
{
"code": "// Java program for reversing the linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to reverse the linked list */ Node reverse(Node node) { Node prev = null; Node current = node; Node next = null; while (current != null) { next = current.next; current.next = prev; prev = current; current = next; } node = prev; return node; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(85); list.head.next = new Node(15); list.head.next.next = new Node(4); list.head.next.next.next = new Node(20); System.out.println(\"Given Linked list\"); list.printList(head); head = list.reverse(head); System.out.println(\"\"); System.out.println(\"Reversed linked list \"); list.printList(head); }} // This code has been contributed by Mayank Jaiswal",
"e": 26457,
"s": 25126,
"text": null
},
{
"code": null,
"e": 26475,
"s": 26457,
"text": "Recursive Method:"
},
{
"code": "void recursiveReverse(struct Node** head_ref){ struct Node* first; struct Node* rest; /* empty list */ if (*head_ref == NULL) return; /* suppose first = {1, 2, 3}, rest = {2, 3} */ first = *head_ref; rest = first->next; /* List has only one node */ if (rest == NULL) return; /* reverse the rest list and put the first element at the end */ recursiveReverse(&rest); first->next->next = first; /* tricky step -- see the diagram */ first->next = NULL; /* fix the head pointer */ *head_ref = rest; }",
"e": 27088,
"s": 26475,
"text": null
},
{
"code": null,
"e": 27124,
"s": 27088,
"text": "A Simpler and Tail Recursive Method"
},
{
"code": "// Java program for reversing the Linked list class LinkedList { static Node head; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } // A simple and tail recursive function to reverse // a linked list. prev is passed as NULL initially. Node reverseUtil(Node curr, Node prev) { /* If last node mark it head*/ if (curr.next == null) { head = curr; /* Update next to prev node */ curr.next = prev; return null; } /* Save curr->next node for recursive call */ Node next1 = curr.next; /* and update next ..*/ curr.next = prev; reverseUtil(next1, curr); return head; } // prints content of double linked list void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.head.next.next.next.next.next = new Node(6); list.head.next.next.next.next.next.next = new Node(7); list.head.next.next.next.next.next.next.next = new Node(8); System.out.println(\"Original Linked list \"); list.printList(head); Node res = list.reverseUtil(head, null); System.out.println(\"\"); System.out.println(\"\"); System.out.println(\"Reversed linked list \"); list.printList(res); }}// This code has been contributed by Mayank Jaiswal",
"e": 28929,
"s": 27124,
"text": null
},
{
"code": null,
"e": 29002,
"s": 28929,
"text": "Please refer complete article on Reverse a linked list for more details!"
},
{
"code": null,
"e": 29016,
"s": 29002,
"text": "Java Programs"
},
{
"code": null,
"e": 29028,
"s": 29016,
"text": "Linked List"
},
{
"code": null,
"e": 29040,
"s": 29028,
"text": "Linked List"
},
{
"code": null,
"e": 29138,
"s": 29040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29147,
"s": 29138,
"text": "Comments"
},
{
"code": null,
"e": 29160,
"s": 29147,
"text": "Old Comments"
},
{
"code": null,
"e": 29192,
"s": 29160,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 29240,
"s": 29192,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 29291,
"s": 29240,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 29325,
"s": 29291,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 29362,
"s": 29325,
"text": "Modulo or Remainder Operator in Java"
},
{
"code": null,
"e": 29397,
"s": 29362,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 29436,
"s": 29397,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 29458,
"s": 29436,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 29506,
"s": 29458,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Python Virtual Environment
|
Developers often deal with python projects where they have to use module and packages which were not part of the python standard library and they need it for this particular application only. Consider a case, where you have installed the current version of python (let’s assume its python-3.6) but your project requires specific python version--2.7 for this particular application, so it's not just the new packages but requirement may come for a particular version of your already installed application. Then the requirements are in conflict and installing either version 2.7 or 3.6 will leave one application unable to run.
One solution to resolve these circumstances is to create a virtual environment for your project. Virutalenv is a kind of tool that allows us to create isolated python environments. Virtualenv creates a self-contained folder which contains all the required executables to use the packages that a Python project would require in its project.
The main purpose of using virtualenv (virutal environment tool) is to resolve the issues of dependencies, versions (of python packages) and indirectly permissions.
First thing first, you need to have the python installed in your machine (not necessarily the latest version) and pip package manager. However, if you are using python 3.4 version or higher, pip is included by default (comes as python standard library). In case you don’t have any one of them, it’s recommended to installing it first.
Open your command prompt(type cmd in your run terminal). Now go to the directory path(location), where you want to install the virtual environment.
In case you are not using python 3.x, then you need to install the virtualenv tool with pip.
Shell
pip install virtualenv
In case virtualenv is already installed (either you are using python 3 version or you’re not aware of virtualenv installed already), then running above command will give you message something like,
>pip install virtualenv
Requirement already satisfied: virtualenv in c:\python\python361\lib\site-packages (15.1.0)
Start by creating a new folder to work with
Shell
mkdir python-virtual-environments && cd python-virtual-environments
After running above command, you are inside the newly created folder. Now create a new virtual environment inside the directory (the directory you created above).
Shell
#For python 2.x version −
virtualenv myenv
# For python 3.x version −
python -m venv myenv
Above script will create a new folder name myenv with a couple of directories and lots of files, with a directory structure similar to below -
├── Include
│ ├── abstract.h
│ ├── accu.h
│ ├── asdl.h
│ ├── ast.h
│ ├── bitset.h
.........
├── Lib
│ ├── __future__.py
│ ├── __pycache__
│ ├── _bootlocale.py
│ ├── _collections_abc.py
│ ├── _dummy_thread.py
│ ├── _weakrefset.py
│ ├── abc.py
│ ├── base64.py
│ ├── bisect.py
│ ├── codecs.py
......
├── pip-selfcheck.json
├── Scripts
│ ├── activate
│ ├── activate.bat
│ ├── activate.ps1
│ ├── activate_this.py
│ ├── deactivate.bat
│ ├── easy_install.exe
│ ├── easy_install-3.6.exe
│ ├── pip.exe
│ ├── pip3.6.exe
│ ├── pip3.exe
│ ├── python.exe
│ ├── python36.dll
│ ├── pythonw.exe
│ └── wheel.exe
Where −
Include (directory): C headers that compile the python package
Include (directory): C headers that compile the python package
Scripts(directory): files that interact with the virtual environment
Scripts(directory): files that interact with the virtual environment
Lib(directory): Contains the python version copy and site-packages directory where each dependency is installed.
Lib(directory): Contains the python version copy and site-packages directory where each dependency is installed.
One of the interesting files is the activate scripts in the scripts directory. The activate scripts used the environment’s python executables and its site-package by default to set up your shell.
However, to use this virtual environment “myenv” packages or resources in isolation, you need to “activate” it first. To activate your virtual environment run the command as shown in the screenshot.
Once the virtual environment is active, we can install all the project related packages and other dependencies isolated from the outside world. For example, if we are working with a data science project, we can install all the required packages and their dependencies at once simply, by typing below command like below −
(myenv) C:\Users\rajesh\python-virtual-environments>pip install numpy scipy matplotlib ipython jupyter pandas
Once we are done with our project, we can come out of the virtual environment simply by deactivating it.
(myenv) C:\Users\rajesh\python-virtual-environments>deactivate
C:\Users\rajesh\python-virtual-environments>
Now we are back in the windows command shell (like above).
|
[
{
"code": null,
"e": 1688,
"s": 1062,
"text": "Developers often deal with python projects where they have to use module and packages which were not part of the python standard library and they need it for this particular application only. Consider a case, where you have installed the current version of python (let’s assume its python-3.6) but your project requires specific python version--2.7 for this particular application, so it's not just the new packages but requirement may come for a particular version of your already installed application. Then the requirements are in conflict and installing either version 2.7 or 3.6 will leave one application unable to run."
},
{
"code": null,
"e": 2028,
"s": 1688,
"text": "One solution to resolve these circumstances is to create a virtual environment for your project. Virutalenv is a kind of tool that allows us to create isolated python environments. Virtualenv creates a self-contained folder which contains all the required executables to use the packages that a Python project would require in its project."
},
{
"code": null,
"e": 2192,
"s": 2028,
"text": "The main purpose of using virtualenv (virutal environment tool) is to resolve the issues of dependencies, versions (of python packages) and indirectly permissions."
},
{
"code": null,
"e": 2527,
"s": 2192,
"text": "First thing first, you need to have the python installed in your machine (not necessarily the latest version) and pip package manager. However, if you are using python 3.4 version or higher, pip is included by default (comes as python standard library). In case you don’t have any one of them, it’s recommended to installing it first."
},
{
"code": null,
"e": 2675,
"s": 2527,
"text": "Open your command prompt(type cmd in your run terminal). Now go to the directory path(location), where you want to install the virtual environment."
},
{
"code": null,
"e": 2768,
"s": 2675,
"text": "In case you are not using python 3.x, then you need to install the virtualenv tool with pip."
},
{
"code": null,
"e": 2774,
"s": 2768,
"text": "Shell"
},
{
"code": null,
"e": 2797,
"s": 2774,
"text": "pip install virtualenv"
},
{
"code": null,
"e": 2995,
"s": 2797,
"text": "In case virtualenv is already installed (either you are using python 3 version or you’re not aware of virtualenv installed already), then running above command will give you message something like,"
},
{
"code": null,
"e": 3111,
"s": 2995,
"text": ">pip install virtualenv\nRequirement already satisfied: virtualenv in c:\\python\\python361\\lib\\site-packages (15.1.0)"
},
{
"code": null,
"e": 3155,
"s": 3111,
"text": "Start by creating a new folder to work with"
},
{
"code": null,
"e": 3161,
"s": 3155,
"text": "Shell"
},
{
"code": null,
"e": 3229,
"s": 3161,
"text": "mkdir python-virtual-environments && cd python-virtual-environments"
},
{
"code": null,
"e": 3392,
"s": 3229,
"text": "After running above command, you are inside the newly created folder. Now create a new virtual environment inside the directory (the directory you created above)."
},
{
"code": null,
"e": 3398,
"s": 3392,
"text": "Shell"
},
{
"code": null,
"e": 3424,
"s": 3398,
"text": "#For python 2.x version −"
},
{
"code": null,
"e": 3441,
"s": 3424,
"text": "virtualenv myenv"
},
{
"code": null,
"e": 3468,
"s": 3441,
"text": "# For python 3.x version −"
},
{
"code": null,
"e": 3489,
"s": 3468,
"text": "python -m venv myenv"
},
{
"code": null,
"e": 3632,
"s": 3489,
"text": "Above script will create a new folder name myenv with a couple of directories and lots of files, with a directory structure similar to below -"
},
{
"code": null,
"e": 4227,
"s": 3632,
"text": "├── Include\n│ ├── abstract.h\n│ ├── accu.h\n│ ├── asdl.h\n│ ├── ast.h\n│ ├── bitset.h\n.........\n├── Lib\n│ ├── __future__.py\n│ ├── __pycache__\n│ ├── _bootlocale.py\n│ ├── _collections_abc.py\n│ ├── _dummy_thread.py\n│ ├── _weakrefset.py\n│ ├── abc.py\n│ ├── base64.py\n│ ├── bisect.py\n│ ├── codecs.py\n......\n├── pip-selfcheck.json\n├── Scripts\n│ ├── activate\n│ ├── activate.bat\n│ ├── activate.ps1\n│ ├── activate_this.py\n│ ├── deactivate.bat\n│ ├── easy_install.exe\n│ ├── easy_install-3.6.exe\n│ ├── pip.exe\n│ ├── pip3.6.exe\n│ ├── pip3.exe\n│ ├── python.exe\n│ ├── python36.dll\n│ ├── pythonw.exe\n│ └── wheel.exe"
},
{
"code": null,
"e": 4235,
"s": 4227,
"text": "Where −"
},
{
"code": null,
"e": 4298,
"s": 4235,
"text": "Include (directory): C headers that compile the python package"
},
{
"code": null,
"e": 4361,
"s": 4298,
"text": "Include (directory): C headers that compile the python package"
},
{
"code": null,
"e": 4430,
"s": 4361,
"text": "Scripts(directory): files that interact with the virtual environment"
},
{
"code": null,
"e": 4499,
"s": 4430,
"text": "Scripts(directory): files that interact with the virtual environment"
},
{
"code": null,
"e": 4612,
"s": 4499,
"text": "Lib(directory): Contains the python version copy and site-packages directory where each dependency is installed."
},
{
"code": null,
"e": 4725,
"s": 4612,
"text": "Lib(directory): Contains the python version copy and site-packages directory where each dependency is installed."
},
{
"code": null,
"e": 4921,
"s": 4725,
"text": "One of the interesting files is the activate scripts in the scripts directory. The activate scripts used the environment’s python executables and its site-package by default to set up your shell."
},
{
"code": null,
"e": 5120,
"s": 4921,
"text": "However, to use this virtual environment “myenv” packages or resources in isolation, you need to “activate” it first. To activate your virtual environment run the command as shown in the screenshot."
},
{
"code": null,
"e": 5441,
"s": 5120,
"text": "Once the virtual environment is active, we can install all the project related packages and other dependencies isolated from the outside world. For example, if we are working with a data science project, we can install all the required packages and their dependencies at once simply, by typing below command like below −"
},
{
"code": null,
"e": 5551,
"s": 5441,
"text": "(myenv) C:\\Users\\rajesh\\python-virtual-environments>pip install numpy scipy matplotlib ipython jupyter pandas"
},
{
"code": null,
"e": 5656,
"s": 5551,
"text": "Once we are done with our project, we can come out of the virtual environment simply by deactivating it."
},
{
"code": null,
"e": 5764,
"s": 5656,
"text": "(myenv) C:\\Users\\rajesh\\python-virtual-environments>deactivate\nC:\\Users\\rajesh\\python-virtual-environments>"
},
{
"code": null,
"e": 5823,
"s": 5764,
"text": "Now we are back in the windows command shell (like above)."
}
] |
What is .npy files and why you should use them... | by Peter Nistrup | Towards Data Science
|
First of all thanks a lot to my followers for sticking with me these last few months, I’ve been terribly busy and haven’t had a lot of time to pump out articles. I’ve decided that a partial remedy for this is to make some shorter and easier to digest articles which will be easier to produce! Therefore this is my first attempt at making a short-and-to-the-point article. I hope you find it useful!
Make sure to follow my profile if you enjoy this article and want to see more!
Reading a 10 million data-point file from storage:
This is by far the fastest method of loading in data.
Pandas proved that .csv files aren’t useless, but it’s still lacking in speed.
This is just so slow compared to the others that it’s painful.
If you’ve ever done any kind of data processing in Python you’ve undoubtedly come across Numpy and Pandas. These are the giants of Data Science in Python and stand as the foundation for a lot of other packages, namely Numpy provides the fundamental objects used by the likes of Scikit-Learn and Tensorflow!
So why am I talking about these packages and why Numpy in particular? Well as you might know, the “industry standard” with regard to data-files is .csv files. Now while convenient, these files are highly un-optimized when compared to the alternatives, like the .npy files provides as courtesy of Numpy.
“Who cares, let’s see the code and evidence!”
Right, on with the show!
Let’s start off by simply creating 10 million random points of data and save it as Comma Separated Values:
Now let’s load this by traditional means and do a simple reshaping of the data:
This is the output I get:
Now, you might think that the reshaping is preventing a faster load but even if we don’t do any reshaping we get a similar time!
np.save('data.npy', data_array)
Right, that was pretty easy right? So now that we have our array in .npy format let’s see how fast we can read it in:
Which gives me the following output:
A LOT faster, also notice that we didn’t need to reshape the data since that information was contained in the .npy file.
Another “minor” feature of using .npy files is the reduced storage the file occupies. In this case it’s more than a 50% reduction in size. This can wary a lot though but in general the .npy files are more storage friendly.
“What about Pandas and their .csv handling?”
First let’s create a proper .csv file for Pandas to read, this would be the most likely real-life scenario.
data = pd.DataFrame(data_array)data.to_csv('data.csv', index = None)
This simply saves the ‘data_array’ we created before as a standard .csv file without index.
Now let’s load it and see what kind of time we get:
Which gives me the following output:
Now you might think this is cheating because we’re also loading into a Pandas DataFrame, but it turns out that the time-loss for that is negligible, if we read in like this:
data_array = np.load('data.npy')data = pd.DataFrame(data_array)
And time it we get the following:
You’re probably used to loading and saving data as .csv but the next time you do a data-science project try getting into the habit of loading and saving to .npy files instead! It’ll save you a lot of downtime and annoyance when you’re waiting for the kernel to load your file!
I hope this very short piece was helpful to you!
If you want to see and learn more, be sure to follow me on Medium🔍 and Twitter 🐦
|
[
{
"code": null,
"e": 445,
"s": 46,
"text": "First of all thanks a lot to my followers for sticking with me these last few months, I’ve been terribly busy and haven’t had a lot of time to pump out articles. I’ve decided that a partial remedy for this is to make some shorter and easier to digest articles which will be easier to produce! Therefore this is my first attempt at making a short-and-to-the-point article. I hope you find it useful!"
},
{
"code": null,
"e": 524,
"s": 445,
"text": "Make sure to follow my profile if you enjoy this article and want to see more!"
},
{
"code": null,
"e": 575,
"s": 524,
"text": "Reading a 10 million data-point file from storage:"
},
{
"code": null,
"e": 629,
"s": 575,
"text": "This is by far the fastest method of loading in data."
},
{
"code": null,
"e": 708,
"s": 629,
"text": "Pandas proved that .csv files aren’t useless, but it’s still lacking in speed."
},
{
"code": null,
"e": 771,
"s": 708,
"text": "This is just so slow compared to the others that it’s painful."
},
{
"code": null,
"e": 1078,
"s": 771,
"text": "If you’ve ever done any kind of data processing in Python you’ve undoubtedly come across Numpy and Pandas. These are the giants of Data Science in Python and stand as the foundation for a lot of other packages, namely Numpy provides the fundamental objects used by the likes of Scikit-Learn and Tensorflow!"
},
{
"code": null,
"e": 1381,
"s": 1078,
"text": "So why am I talking about these packages and why Numpy in particular? Well as you might know, the “industry standard” with regard to data-files is .csv files. Now while convenient, these files are highly un-optimized when compared to the alternatives, like the .npy files provides as courtesy of Numpy."
},
{
"code": null,
"e": 1427,
"s": 1381,
"text": "“Who cares, let’s see the code and evidence!”"
},
{
"code": null,
"e": 1452,
"s": 1427,
"text": "Right, on with the show!"
},
{
"code": null,
"e": 1559,
"s": 1452,
"text": "Let’s start off by simply creating 10 million random points of data and save it as Comma Separated Values:"
},
{
"code": null,
"e": 1639,
"s": 1559,
"text": "Now let’s load this by traditional means and do a simple reshaping of the data:"
},
{
"code": null,
"e": 1665,
"s": 1639,
"text": "This is the output I get:"
},
{
"code": null,
"e": 1794,
"s": 1665,
"text": "Now, you might think that the reshaping is preventing a faster load but even if we don’t do any reshaping we get a similar time!"
},
{
"code": null,
"e": 1826,
"s": 1794,
"text": "np.save('data.npy', data_array)"
},
{
"code": null,
"e": 1944,
"s": 1826,
"text": "Right, that was pretty easy right? So now that we have our array in .npy format let’s see how fast we can read it in:"
},
{
"code": null,
"e": 1981,
"s": 1944,
"text": "Which gives me the following output:"
},
{
"code": null,
"e": 2102,
"s": 1981,
"text": "A LOT faster, also notice that we didn’t need to reshape the data since that information was contained in the .npy file."
},
{
"code": null,
"e": 2325,
"s": 2102,
"text": "Another “minor” feature of using .npy files is the reduced storage the file occupies. In this case it’s more than a 50% reduction in size. This can wary a lot though but in general the .npy files are more storage friendly."
},
{
"code": null,
"e": 2370,
"s": 2325,
"text": "“What about Pandas and their .csv handling?”"
},
{
"code": null,
"e": 2478,
"s": 2370,
"text": "First let’s create a proper .csv file for Pandas to read, this would be the most likely real-life scenario."
},
{
"code": null,
"e": 2547,
"s": 2478,
"text": "data = pd.DataFrame(data_array)data.to_csv('data.csv', index = None)"
},
{
"code": null,
"e": 2639,
"s": 2547,
"text": "This simply saves the ‘data_array’ we created before as a standard .csv file without index."
},
{
"code": null,
"e": 2691,
"s": 2639,
"text": "Now let’s load it and see what kind of time we get:"
},
{
"code": null,
"e": 2728,
"s": 2691,
"text": "Which gives me the following output:"
},
{
"code": null,
"e": 2902,
"s": 2728,
"text": "Now you might think this is cheating because we’re also loading into a Pandas DataFrame, but it turns out that the time-loss for that is negligible, if we read in like this:"
},
{
"code": null,
"e": 2966,
"s": 2902,
"text": "data_array = np.load('data.npy')data = pd.DataFrame(data_array)"
},
{
"code": null,
"e": 3000,
"s": 2966,
"text": "And time it we get the following:"
},
{
"code": null,
"e": 3277,
"s": 3000,
"text": "You’re probably used to loading and saving data as .csv but the next time you do a data-science project try getting into the habit of loading and saving to .npy files instead! It’ll save you a lot of downtime and annoyance when you’re waiting for the kernel to load your file!"
},
{
"code": null,
"e": 3326,
"s": 3277,
"text": "I hope this very short piece was helpful to you!"
}
] |
How To Join Multiple ggplot2 Plots with cowplot?
|
17 Oct, 2021
In this article, we are going to see how to join multiple ggplot2 plots with cowplot. To join multiple ggplot2 plots, we use the plot_grid() function of the cowplot package of R Language.
Syntax: plot_grid(plot1,plot2,label=<label-vector>, ncol, nrow)
Parameters:
plot1 and plot2 are plots that need to be joined.
<label-vector> is a vector that has a collection of labels for plots.
ncol is the number of columns canvas will be divided in.
nrow is the number of rows canvas will be divided in.
R
# Create sample dataset.seed(5642) sample_data1 <- data.frame( name = c("Geek1","Geek2","Geek3", "Geek4","Geeek5") , value=c(31,12,15,28,45)) sample_data2 <- data.frame(x = rnorm(400)) # Load ggplot2 and cowplotlibrary("ggplot2") library("cowplot") # Create both plot and store in variableplot1<-ggplot(sample_data1, aes(x = name, y = value)) +geom_point(size=4) plot2<-ggplot(sample_data2, aes(x = x)) +geom_density(alpha=0.8)plot_grid(plot1, plot2, labels = c('Plot1', 'Plot2'))
Output:
Output
To fix the number of columns we use ncol attribute of plot_grid() function.
R
# Create sample dataset.seed(5642) sample_data <- data.frame( name = c("Geek1","Geek2","Geek3", "Geek4","Geeek5") , value = c(31,12,15,28,45)) # Load ggplot2 and cowplotlibrary("ggplot2") library("cowplot") # Create both plot and store in variableplot1<-ggplot(sample_data, aes(x=name, y=value)) +geom_bar(stat = "identity") plot2<-ggplot(sample_data, aes(x = name, y=value)) +geom_segment( aes(x=name, xend=name, y=0, yend=value)) plot_grid(plot1,NULL, NULL, plot2, labels = c( 'Plot1','','', 'Plot2'), ncol=2)
Output:
Output
To create a plot with a shared legend, we create plots without a legend and create a separate legend and combine them.
R
# Create sample dataset.seed(5642) sample_data <- data.frame(name=c("Geek1","Geek2","Geek3", "Geek4","Geeek5") , value=c(31,12,15,28,45)) # Load ggplot2 and cowplotlibrary("ggplot2") library("cowplot") # Create both plot and store in variable without legendplot1<-ggplot(sample_data, aes(x=name, y=value, fill=name)) +geom_bar(stat = "identity") +theme(legend.position = "none") plot2<-ggplot(sample_data, aes(x = name, y=value, fill=name)) + geom_point(aes(colour = factor(name)), size = 6)+theme(legend.position = "none") # combine both plot using plot_grid()combined_plot<-plot_grid(plot1, plot2,ncol=2) # extract legend from plot2legend <- get_legend( plot1 + guides(color = guide_legend(nrow = 1)) + theme(legend.position = "bottom")) # Combine combined plot and legend using plot_grid()plot_grid(combined_plot, legend,ncol=1,rel_heights = c(1, .1))
Output:
Output
To create a plot with a shared title, we create plots without titles and create a separate title and combine them.
R
# Create sample dataset.seed(5642) sample_data <- data.frame(name=c("Geek1","Geek2", "Geek3","Geek4","Geeek5") , value=c(31,12,15,28,45)) # Load ggplot2 and cowplotlibrary("ggplot2") library("cowplot") # Create both plot and store in variable without legendplot1<-ggplot(sample_data, aes(x=name, y=value, fill=name)) +geom_bar(stat = "identity") +theme(legend.position = "none") plot2<-ggplot(sample_data, aes(x = name, y=value, fill=name)) + geom_point(aes(colour = factor(name)), size = 6)+theme(legend.position = "none") # combine both plot using plot_grid()combined_plot<-plot_grid(plot1, plot2,ncol=2) # create title for plottitle <- ggdraw() + draw_label( "Two Plots together with shared title", fontface = 'bold', x = 0, hjust = 0, size = 24, )# Combine combined plot and title using plot_grid()plot_grid(title, combined_plot ,ncol=1,rel_heights = c(0.1, 1))
Output:
Output
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Oct, 2021"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "In this article, we are going to see how to join multiple ggplot2 plots with cowplot. To join multiple ggplot2 plots, we use the plot_grid() function of the cowplot package of R Language."
},
{
"code": null,
"e": 280,
"s": 216,
"text": "Syntax: plot_grid(plot1,plot2,label=<label-vector>, ncol, nrow)"
},
{
"code": null,
"e": 292,
"s": 280,
"text": "Parameters:"
},
{
"code": null,
"e": 342,
"s": 292,
"text": "plot1 and plot2 are plots that need to be joined."
},
{
"code": null,
"e": 412,
"s": 342,
"text": "<label-vector> is a vector that has a collection of labels for plots."
},
{
"code": null,
"e": 469,
"s": 412,
"text": "ncol is the number of columns canvas will be divided in."
},
{
"code": null,
"e": 523,
"s": 469,
"text": "nrow is the number of rows canvas will be divided in."
},
{
"code": null,
"e": 525,
"s": 523,
"text": "R"
},
{
"code": "# Create sample dataset.seed(5642) sample_data1 <- data.frame( name = c(\"Geek1\",\"Geek2\",\"Geek3\", \"Geek4\",\"Geeek5\") , value=c(31,12,15,28,45)) sample_data2 <- data.frame(x = rnorm(400)) # Load ggplot2 and cowplotlibrary(\"ggplot2\") library(\"cowplot\") # Create both plot and store in variableplot1<-ggplot(sample_data1, aes(x = name, y = value)) +geom_point(size=4) plot2<-ggplot(sample_data2, aes(x = x)) +geom_density(alpha=0.8)plot_grid(plot1, plot2, labels = c('Plot1', 'Plot2'))",
"e": 1063,
"s": 525,
"text": null
},
{
"code": null,
"e": 1071,
"s": 1063,
"text": "Output:"
},
{
"code": null,
"e": 1078,
"s": 1071,
"text": "Output"
},
{
"code": null,
"e": 1154,
"s": 1078,
"text": "To fix the number of columns we use ncol attribute of plot_grid() function."
},
{
"code": null,
"e": 1156,
"s": 1154,
"text": "R"
},
{
"code": "# Create sample dataset.seed(5642) sample_data <- data.frame( name = c(\"Geek1\",\"Geek2\",\"Geek3\", \"Geek4\",\"Geeek5\") , value = c(31,12,15,28,45)) # Load ggplot2 and cowplotlibrary(\"ggplot2\") library(\"cowplot\") # Create both plot and store in variableplot1<-ggplot(sample_data, aes(x=name, y=value)) +geom_bar(stat = \"identity\") plot2<-ggplot(sample_data, aes(x = name, y=value)) +geom_segment( aes(x=name, xend=name, y=0, yend=value)) plot_grid(plot1,NULL, NULL, plot2, labels = c( 'Plot1','','', 'Plot2'), ncol=2)",
"e": 1714,
"s": 1156,
"text": null
},
{
"code": null,
"e": 1722,
"s": 1714,
"text": "Output:"
},
{
"code": null,
"e": 1729,
"s": 1722,
"text": "Output"
},
{
"code": null,
"e": 1848,
"s": 1729,
"text": "To create a plot with a shared legend, we create plots without a legend and create a separate legend and combine them."
},
{
"code": null,
"e": 1850,
"s": 1848,
"text": "R"
},
{
"code": "# Create sample dataset.seed(5642) sample_data <- data.frame(name=c(\"Geek1\",\"Geek2\",\"Geek3\", \"Geek4\",\"Geeek5\") , value=c(31,12,15,28,45)) # Load ggplot2 and cowplotlibrary(\"ggplot2\") library(\"cowplot\") # Create both plot and store in variable without legendplot1<-ggplot(sample_data, aes(x=name, y=value, fill=name)) +geom_bar(stat = \"identity\") +theme(legend.position = \"none\") plot2<-ggplot(sample_data, aes(x = name, y=value, fill=name)) + geom_point(aes(colour = factor(name)), size = 6)+theme(legend.position = \"none\") # combine both plot using plot_grid()combined_plot<-plot_grid(plot1, plot2,ncol=2) # extract legend from plot2legend <- get_legend( plot1 + guides(color = guide_legend(nrow = 1)) + theme(legend.position = \"bottom\")) # Combine combined plot and legend using plot_grid()plot_grid(combined_plot, legend,ncol=1,rel_heights = c(1, .1))",
"e": 2804,
"s": 1850,
"text": null
},
{
"code": null,
"e": 2812,
"s": 2804,
"text": "Output:"
},
{
"code": null,
"e": 2819,
"s": 2812,
"text": "Output"
},
{
"code": null,
"e": 2934,
"s": 2819,
"text": "To create a plot with a shared title, we create plots without titles and create a separate title and combine them."
},
{
"code": null,
"e": 2936,
"s": 2934,
"text": "R"
},
{
"code": "# Create sample dataset.seed(5642) sample_data <- data.frame(name=c(\"Geek1\",\"Geek2\", \"Geek3\",\"Geek4\",\"Geeek5\") , value=c(31,12,15,28,45)) # Load ggplot2 and cowplotlibrary(\"ggplot2\") library(\"cowplot\") # Create both plot and store in variable without legendplot1<-ggplot(sample_data, aes(x=name, y=value, fill=name)) +geom_bar(stat = \"identity\") +theme(legend.position = \"none\") plot2<-ggplot(sample_data, aes(x = name, y=value, fill=name)) + geom_point(aes(colour = factor(name)), size = 6)+theme(legend.position = \"none\") # combine both plot using plot_grid()combined_plot<-plot_grid(plot1, plot2,ncol=2) # create title for plottitle <- ggdraw() + draw_label( \"Two Plots together with shared title\", fontface = 'bold', x = 0, hjust = 0, size = 24, )# Combine combined plot and title using plot_grid()plot_grid(title, combined_plot ,ncol=1,rel_heights = c(0.1, 1))",
"e": 3911,
"s": 2936,
"text": null
},
{
"code": null,
"e": 3919,
"s": 3911,
"text": "Output:"
},
{
"code": null,
"e": 3926,
"s": 3919,
"text": "Output"
},
{
"code": null,
"e": 3933,
"s": 3926,
"text": "Picked"
},
{
"code": null,
"e": 3944,
"s": 3933,
"text": "R Language"
}
] |
Python Program To Remove all control characters
|
27 Dec, 2021
In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is an essential utility. In this article, we will discuss how to remove all those control characters.
Example:
Input : test_str = ‘Geeks\0\r for \n\bge\tee\0ks\f’
Output : Geeks for geeeks
Explanation : \n, \0, \f, \r, \b, \t being control characters are removed from string.
Input : test_str = ‘G\0\r\n\fg’
Output : Gfg
Explanation : \n, \0, \f, \r being control characters are removed from string, giving Gfg as output.
Method 1 : Using translate().
The logic applied here is that each non-control character is at the top 33 ASCII characters, hence translation is used to avoid all others except these via mapping.
Python3
# Python3 code to demonstrate working of# Remove all control characters# Using translate() # initializing stringtest_str = 'Geeks\0\r for \n\bge\tee\0ks\f' # printing original stringprint("The original string is : " + str(test_str)) # using translate() and fromkeys()# to escape all control charactersmapping = dict.fromkeys(range(32))res = test_str.translate(mapping) # printing resultprint("String after removal of control characters : " + str(res))
Output:
for original string is : Geeks
ge eeks
String after removal of control characters : Geeks for geeeks
Method 2: Using unicodedata library
In this, using unicodedata.category(), we can check each character starting with “C” is the control character and hence be avoided in the result string.
Python3
# Python3 code to demonstrate working of# Remove all control characters# Using unicodedata libraryimport unicodedata # initializing stringtest_str = 'Geeks\0\r for \n\bge\tee\0ks\f' # printing original stringprint("The original string is : " + str(test_str)) # surpassing all control characters# checking for starting with Cres = "".join(char for char in test_str if unicodedata.category(char)[0]!="C") # printing resultprint("String after removal of control characters : " + str(res))
Output:
for original string is : Geeks
ge eeks
String after removal of control characters : Geeks for geeeks
germanshephered48
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 427,
"s": 28,
"text": "In the telecommunication and computer domain, control characters are non-printable characters which are a part of the character set. These do not represent any written symbol. They are used in signaling to cause certain effects other than adding symbols to text. Removing these control characters is an essential utility. In this article, we will discuss how to remove all those control characters."
},
{
"code": null,
"e": 436,
"s": 427,
"text": "Example:"
},
{
"code": null,
"e": 488,
"s": 436,
"text": "Input : test_str = ‘Geeks\\0\\r for \\n\\bge\\tee\\0ks\\f’"
},
{
"code": null,
"e": 514,
"s": 488,
"text": "Output : Geeks for geeeks"
},
{
"code": null,
"e": 601,
"s": 514,
"text": "Explanation : \\n, \\0, \\f, \\r, \\b, \\t being control characters are removed from string."
},
{
"code": null,
"e": 633,
"s": 601,
"text": "Input : test_str = ‘G\\0\\r\\n\\fg’"
},
{
"code": null,
"e": 646,
"s": 633,
"text": "Output : Gfg"
},
{
"code": null,
"e": 747,
"s": 646,
"text": "Explanation : \\n, \\0, \\f, \\r being control characters are removed from string, giving Gfg as output."
},
{
"code": null,
"e": 777,
"s": 747,
"text": "Method 1 : Using translate()."
},
{
"code": null,
"e": 942,
"s": 777,
"text": "The logic applied here is that each non-control character is at the top 33 ASCII characters, hence translation is used to avoid all others except these via mapping."
},
{
"code": null,
"e": 950,
"s": 942,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove all control characters# Using translate() # initializing stringtest_str = 'Geeks\\0\\r for \\n\\bge\\tee\\0ks\\f' # printing original stringprint(\"The original string is : \" + str(test_str)) # using translate() and fromkeys()# to escape all control charactersmapping = dict.fromkeys(range(32))res = test_str.translate(mapping) # printing resultprint(\"String after removal of control characters : \" + str(res))",
"e": 1403,
"s": 950,
"text": null
},
{
"code": null,
"e": 1411,
"s": 1403,
"text": "Output:"
},
{
"code": null,
"e": 1516,
"s": 1411,
"text": " for original string is : Geeks\nge eeks\nString after removal of control characters : Geeks for geeeks"
},
{
"code": null,
"e": 1552,
"s": 1516,
"text": "Method 2: Using unicodedata library"
},
{
"code": null,
"e": 1705,
"s": 1552,
"text": "In this, using unicodedata.category(), we can check each character starting with “C” is the control character and hence be avoided in the result string."
},
{
"code": null,
"e": 1713,
"s": 1705,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Remove all control characters# Using unicodedata libraryimport unicodedata # initializing stringtest_str = 'Geeks\\0\\r for \\n\\bge\\tee\\0ks\\f' # printing original stringprint(\"The original string is : \" + str(test_str)) # surpassing all control characters# checking for starting with Cres = \"\".join(char for char in test_str if unicodedata.category(char)[0]!=\"C\") # printing resultprint(\"String after removal of control characters : \" + str(res))",
"e": 2199,
"s": 1713,
"text": null
},
{
"code": null,
"e": 2207,
"s": 2199,
"text": "Output:"
},
{
"code": null,
"e": 2312,
"s": 2207,
"text": " for original string is : Geeks\nge eeks\nString after removal of control characters : Geeks for geeeks"
},
{
"code": null,
"e": 2330,
"s": 2312,
"text": "germanshephered48"
},
{
"code": null,
"e": 2353,
"s": 2330,
"text": "Python string-programs"
},
{
"code": null,
"e": 2360,
"s": 2353,
"text": "Python"
},
{
"code": null,
"e": 2376,
"s": 2360,
"text": "Python Programs"
}
] |
Find the version of the Pandas and its dependencies
|
23 Jan, 2019
Pandas is one of the most important packages for data analysis in Python and that means frequent updates of the version of the Pandas. This leads to compatibility issues with other dependencies of Pandas. Let’s discuss the ways to check the version of the Pandas and its dependencies running on any system.
Find the version of the Pandas running on any system.
We can use pd.__version__ to check the version of the Pandas running on any system.
# importing pandas as pdimport pandas as pd # Check the versionprint(pd.__version__)
Output :
Find the version of the dependencies for the given version of the Pandas running on any system.
We can use the utility function pd.show_versions() to check the version of the dependencies.
# importing pandas as pdimport pandas as pd # Check the version of the dependenciespd.show_versions()
Output :
Python pandas-basics
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": "\n23 Jan, 2019"
},
{
"code": null,
"e": 335,
"s": 28,
"text": "Pandas is one of the most important packages for data analysis in Python and that means frequent updates of the version of the Pandas. This leads to compatibility issues with other dependencies of Pandas. Let’s discuss the ways to check the version of the Pandas and its dependencies running on any system."
},
{
"code": null,
"e": 389,
"s": 335,
"text": "Find the version of the Pandas running on any system."
},
{
"code": null,
"e": 473,
"s": 389,
"text": "We can use pd.__version__ to check the version of the Pandas running on any system."
},
{
"code": "# importing pandas as pdimport pandas as pd # Check the versionprint(pd.__version__)",
"e": 559,
"s": 473,
"text": null
},
{
"code": null,
"e": 568,
"s": 559,
"text": "Output :"
},
{
"code": null,
"e": 666,
"s": 570,
"text": "Find the version of the dependencies for the given version of the Pandas running on any system."
},
{
"code": null,
"e": 759,
"s": 666,
"text": "We can use the utility function pd.show_versions() to check the version of the dependencies."
},
{
"code": "# importing pandas as pdimport pandas as pd # Check the version of the dependenciespd.show_versions()",
"e": 862,
"s": 759,
"text": null
},
{
"code": null,
"e": 871,
"s": 862,
"text": "Output :"
},
{
"code": null,
"e": 892,
"s": 871,
"text": "Python pandas-basics"
},
{
"code": null,
"e": 906,
"s": 892,
"text": "Python-pandas"
},
{
"code": null,
"e": 913,
"s": 906,
"text": "Python"
}
] |
Count maximum points on same line
|
05 Jul, 2022
Given N point on a 2D plane as pair of (x, y) co-ordinates, we need to find maximum number of point which lie on the same line.
Examples:
Input : points[] = {-1, 1}, {0, 0}, {1, 1},
{2, 2}, {3, 3}, {3, 4}
Output : 4
Then maximum number of point which lie on same
line are 4, those point are {0, 0}, {1, 1}, {2, 2},
{3, 3}
We can solve above problem by following approach – For each point p, calculate its slope with other points and use a map to record how many points have same slope, by which we can find out how many points are on same line with p as their one point. For each point keep doing the same thing and update the maximum number of point count found so far.
Some things to note in implementation are:
if two point are (x1, y1) and (x2, y2) then their slope will be (y2 – y1) / (x2 – x1) which can be a double value and can cause precision problems. To get rid of the precision problems, we treat slope as pair ((y2 – y1), (x2 – x1)) instead of ratio and reduce pair by their gcd before inserting into map. In below code points which are vertical or repeated are treated separately.If we use unordered_map in c++ or HashMap in Java for storing the slope pair, then total time complexity of solution will be O(n^2) and space complexity will be O(n).
if two point are (x1, y1) and (x2, y2) then their slope will be (y2 – y1) / (x2 – x1) which can be a double value and can cause precision problems. To get rid of the precision problems, we treat slope as pair ((y2 – y1), (x2 – x1)) instead of ratio and reduce pair by their gcd before inserting into map. In below code points which are vertical or repeated are treated separately.
If we use unordered_map in c++ or HashMap in Java for storing the slope pair, then total time complexity of solution will be O(n^2) and space complexity will be O(n).
Implementation:
C++
Python3
Javascript
/* C/C++ program to find maximum number of pointwhich lie on same line */#include <bits/stdc++.h>#include <boost/functional/hash.hpp> using namespace std; // method to find maximum collinear pointint maxPointOnSameLine(vector< pair<int, int> > points){ int N = points.size(); if (N < 2) return N; int maxPoint = 0; int curMax, overlapPoints, verticalPoints; // here since we are using unordered_map // which is based on hash function //But by default we don't have hash function for pairs //so we'll use hash function defined in Boost library unordered_map<pair<int, int>, int,boost:: hash<pair<int, int> > > slopeMap; // looping for each point for (int i = 0; i < N; i++) { curMax = overlapPoints = verticalPoints = 0; // looping from i + 1 to ignore same pair again for (int j = i + 1; j < N; j++) { // If both point are equal then just // increase overlapPoint count if (points[i] == points[j]) overlapPoints++; // If x co-ordinate is same, then both // point are vertical to each other else if (points[i].first == points[j].first) verticalPoints++; else { int yDif = points[j].second - points[i].second; int xDif = points[j].first - points[i].first; int g = __gcd(xDif, yDif); // reducing the difference by their gcd yDif /= g; xDif /= g; // increasing the frequency of current slope // in map slopeMap[make_pair(yDif, xDif)]++; curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]); } curMax = max(curMax, verticalPoints); } // updating global maximum by current point's maximum maxPoint = max(maxPoint, curMax + overlapPoints + 1); // printf("maximum collinear point // which contains current point // are : %d\n", curMax + overlapPoints + 1); slopeMap.clear(); } return maxPoint;} // Driver codeint main(){ const int N = 6; int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2}, {3, 3}, {3, 4}}; vector< pair<int, int> > points; for (int i = 0; i < N; i++) points.push_back(make_pair(arr[i][0], arr[i][1])); cout << maxPointOnSameLine(points) << endl; return 0;}
# python3 program to find maximum number of 2D points that lie on the same line. from collections import defaultdictfrom math import gcdfrom typing import DefaultDict, List, Tuple IntPair = Tuple[int, int] def normalized_slope(a: IntPair, b: IntPair) -> IntPair: """ Returns normalized (rise, run) tuple. We won't return the actual rise/run result in order to avoid floating point math, which leads to faulty comparisons. See https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems """ run = b[0] - a[0] # normalize undefined slopes to (1, 0) if run == 0: return (1, 0) # normalize to left-to-right if run < 0: a, b = b, a run = b[0] - a[0] rise = b[1] - a[1] # Normalize by greatest common divisor. # math.gcd only works on positive numbers. gcd_ = gcd(abs(rise), run) return ( rise // gcd_, run // gcd_, ) def maximum_points_on_same_line(points: List[List[int]]) -> int: # You need at least 3 points to potentially have non-collinear points. # For [0, 2] points, all points are on the same line. if len(points) < 3: return len(points) # Note that every line we find will have at least 2 points. # There will be at least one line because len(points) >= 3. # Therefore, it's safe to initialize to 0. max_val = 0 for a_index in range(0, len(points) - 1): # All lines in this iteration go through point a. # Note that lines a-b and a-c cannot be parallel. # Therefore, if lines a-b and a-c have the same slope, they're the same # line. a = tuple(points[a_index]) # Fresh lines already have a, so default=1 slope_counts: DefaultDict[IntPair, int] = defaultdict(lambda: 1) for b_index in range(a_index + 1, len(points)): b = tuple(points[b_index]) slope_counts[normalized_slope(a, b)] += 1 max_val = max( max_val, max(slope_counts.values()), ) return max_val print(maximum_points_on_same_line([ [-1, 1], [0, 0], [1, 1], [2, 2], [3, 3], [3, 4],])) # This code is contributed by Jose Alvarado Torre
/* JavaScript program to find maximum number of pointwhich lie on same line */ // Function to find gcd of two numberslet gcd = function(a, b) { if (!b) { return a; } return gcd(b, a % b);} // method to find maximum collinear pointfunction maxPointOnSameLine(points){ let N = points.length; if (N < 2){ return N; } let maxPoint = 0; let curMax, overlapPoints, verticalPoints; // Creating a map for storing the data. let slopeMap = new Map(); // looping for each point for (let i = 0; i < N; i++) { curMax = 0; overlapPoints = 0; verticalPoints = 0; // looping from i + 1 to ignore same pair again for (let j = i + 1; j < N; j++) { // If both point are equal then just // increase overlapPoint count if (points[i] === points[j]){ overlapPoints++; } // If x co-ordinate is same, then both // point are vertical to each other else if (points[i][0] === points[j][0]){ verticalPoints++; } else{ let yDif = points[j][1] - points[i][1]; let xDif = points[j][0] - points[i][0]; let g = gcd(xDif, yDif); // reducing the difference by their gcd yDif = Math.floor(yDif/g); xDif = Math.floor(xDif/g); // increasing the frequency of current slope. let tmp = [yDif, xDif]; if(slopeMap.has(tmp.join(''))){ slopeMap.set(tmp.join(''), slopeMap.get(tmp.join('')) + 1); } else{ slopeMap.set(tmp.join(''), 1); } curMax = Math.max(curMax, slopeMap.get(tmp.join(''))); } curMax = Math.max(curMax, verticalPoints); } // updating global maximum by current point's maximum maxPoint = Math.max(maxPoint, curMax + overlapPoints + 1); // printf("maximum collinear point // which contains current point // are : %d\n", curMax + overlapPoints + 1); slopeMap.clear(); } return maxPoint;} // Driver code{ let N = 6; let arr = [[-1, 1], [0, 0], [1, 1], [2, 2], [3, 3], [3, 4]]; console.log(maxPointOnSameLine(arr));} // The code is contributed by Gautam goel (gautamgoel962)
4
Time Complexity: O(n2logn), where n denoting length of string.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.
PortgasDAce
RahulSingal
sagar0719kumar
josalvatorre
sweetyty
gautamgoel962
shivamanandrj9
hardikkoriintern
Amazon
Geometric
Hash
Mathematical
Amazon
Hash
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Find if two rectangles overlap
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Check whether triangle is valid or not if sides are given
Program for Point of Intersection of Two Lines
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Hashing | Set 1 (Introduction)
Internal Working of HashMap in Java
Longest Consecutive Subsequence
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 180,
"s": 52,
"text": "Given N point on a 2D plane as pair of (x, y) co-ordinates, we need to find maximum number of point which lie on the same line."
},
{
"code": null,
"e": 191,
"s": 180,
"text": "Examples: "
},
{
"code": null,
"e": 397,
"s": 191,
"text": "Input : points[] = {-1, 1}, {0, 0}, {1, 1}, \n {2, 2}, {3, 3}, {3, 4} \nOutput : 4\nThen maximum number of point which lie on same\nline are 4, those point are {0, 0}, {1, 1}, {2, 2},\n{3, 3}"
},
{
"code": null,
"e": 746,
"s": 397,
"text": "We can solve above problem by following approach – For each point p, calculate its slope with other points and use a map to record how many points have same slope, by which we can find out how many points are on same line with p as their one point. For each point keep doing the same thing and update the maximum number of point count found so far."
},
{
"code": null,
"e": 790,
"s": 746,
"text": "Some things to note in implementation are: "
},
{
"code": null,
"e": 1337,
"s": 790,
"text": "if two point are (x1, y1) and (x2, y2) then their slope will be (y2 – y1) / (x2 – x1) which can be a double value and can cause precision problems. To get rid of the precision problems, we treat slope as pair ((y2 – y1), (x2 – x1)) instead of ratio and reduce pair by their gcd before inserting into map. In below code points which are vertical or repeated are treated separately.If we use unordered_map in c++ or HashMap in Java for storing the slope pair, then total time complexity of solution will be O(n^2) and space complexity will be O(n)."
},
{
"code": null,
"e": 1718,
"s": 1337,
"text": "if two point are (x1, y1) and (x2, y2) then their slope will be (y2 – y1) / (x2 – x1) which can be a double value and can cause precision problems. To get rid of the precision problems, we treat slope as pair ((y2 – y1), (x2 – x1)) instead of ratio and reduce pair by their gcd before inserting into map. In below code points which are vertical or repeated are treated separately."
},
{
"code": null,
"e": 1885,
"s": 1718,
"text": "If we use unordered_map in c++ or HashMap in Java for storing the slope pair, then total time complexity of solution will be O(n^2) and space complexity will be O(n)."
},
{
"code": null,
"e": 1901,
"s": 1885,
"text": "Implementation:"
},
{
"code": null,
"e": 1905,
"s": 1901,
"text": "C++"
},
{
"code": null,
"e": 1913,
"s": 1905,
"text": "Python3"
},
{
"code": null,
"e": 1924,
"s": 1913,
"text": "Javascript"
},
{
"code": "/* C/C++ program to find maximum number of pointwhich lie on same line */#include <bits/stdc++.h>#include <boost/functional/hash.hpp> using namespace std; // method to find maximum collinear pointint maxPointOnSameLine(vector< pair<int, int> > points){ int N = points.size(); if (N < 2) return N; int maxPoint = 0; int curMax, overlapPoints, verticalPoints; // here since we are using unordered_map // which is based on hash function //But by default we don't have hash function for pairs //so we'll use hash function defined in Boost library unordered_map<pair<int, int>, int,boost:: hash<pair<int, int> > > slopeMap; // looping for each point for (int i = 0; i < N; i++) { curMax = overlapPoints = verticalPoints = 0; // looping from i + 1 to ignore same pair again for (int j = i + 1; j < N; j++) { // If both point are equal then just // increase overlapPoint count if (points[i] == points[j]) overlapPoints++; // If x co-ordinate is same, then both // point are vertical to each other else if (points[i].first == points[j].first) verticalPoints++; else { int yDif = points[j].second - points[i].second; int xDif = points[j].first - points[i].first; int g = __gcd(xDif, yDif); // reducing the difference by their gcd yDif /= g; xDif /= g; // increasing the frequency of current slope // in map slopeMap[make_pair(yDif, xDif)]++; curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]); } curMax = max(curMax, verticalPoints); } // updating global maximum by current point's maximum maxPoint = max(maxPoint, curMax + overlapPoints + 1); // printf(\"maximum collinear point // which contains current point // are : %d\\n\", curMax + overlapPoints + 1); slopeMap.clear(); } return maxPoint;} // Driver codeint main(){ const int N = 6; int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2}, {3, 3}, {3, 4}}; vector< pair<int, int> > points; for (int i = 0; i < N; i++) points.push_back(make_pair(arr[i][0], arr[i][1])); cout << maxPointOnSameLine(points) << endl; return 0;}",
"e": 4377,
"s": 1924,
"text": null
},
{
"code": "# python3 program to find maximum number of 2D points that lie on the same line. from collections import defaultdictfrom math import gcdfrom typing import DefaultDict, List, Tuple IntPair = Tuple[int, int] def normalized_slope(a: IntPair, b: IntPair) -> IntPair: \"\"\" Returns normalized (rise, run) tuple. We won't return the actual rise/run result in order to avoid floating point math, which leads to faulty comparisons. See https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems \"\"\" run = b[0] - a[0] # normalize undefined slopes to (1, 0) if run == 0: return (1, 0) # normalize to left-to-right if run < 0: a, b = b, a run = b[0] - a[0] rise = b[1] - a[1] # Normalize by greatest common divisor. # math.gcd only works on positive numbers. gcd_ = gcd(abs(rise), run) return ( rise // gcd_, run // gcd_, ) def maximum_points_on_same_line(points: List[List[int]]) -> int: # You need at least 3 points to potentially have non-collinear points. # For [0, 2] points, all points are on the same line. if len(points) < 3: return len(points) # Note that every line we find will have at least 2 points. # There will be at least one line because len(points) >= 3. # Therefore, it's safe to initialize to 0. max_val = 0 for a_index in range(0, len(points) - 1): # All lines in this iteration go through point a. # Note that lines a-b and a-c cannot be parallel. # Therefore, if lines a-b and a-c have the same slope, they're the same # line. a = tuple(points[a_index]) # Fresh lines already have a, so default=1 slope_counts: DefaultDict[IntPair, int] = defaultdict(lambda: 1) for b_index in range(a_index + 1, len(points)): b = tuple(points[b_index]) slope_counts[normalized_slope(a, b)] += 1 max_val = max( max_val, max(slope_counts.values()), ) return max_val print(maximum_points_on_same_line([ [-1, 1], [0, 0], [1, 1], [2, 2], [3, 3], [3, 4],])) # This code is contributed by Jose Alvarado Torre",
"e": 6555,
"s": 4377,
"text": null
},
{
"code": "/* JavaScript program to find maximum number of pointwhich lie on same line */ // Function to find gcd of two numberslet gcd = function(a, b) { if (!b) { return a; } return gcd(b, a % b);} // method to find maximum collinear pointfunction maxPointOnSameLine(points){ let N = points.length; if (N < 2){ return N; } let maxPoint = 0; let curMax, overlapPoints, verticalPoints; // Creating a map for storing the data. let slopeMap = new Map(); // looping for each point for (let i = 0; i < N; i++) { curMax = 0; overlapPoints = 0; verticalPoints = 0; // looping from i + 1 to ignore same pair again for (let j = i + 1; j < N; j++) { // If both point are equal then just // increase overlapPoint count if (points[i] === points[j]){ overlapPoints++; } // If x co-ordinate is same, then both // point are vertical to each other else if (points[i][0] === points[j][0]){ verticalPoints++; } else{ let yDif = points[j][1] - points[i][1]; let xDif = points[j][0] - points[i][0]; let g = gcd(xDif, yDif); // reducing the difference by their gcd yDif = Math.floor(yDif/g); xDif = Math.floor(xDif/g); // increasing the frequency of current slope. let tmp = [yDif, xDif]; if(slopeMap.has(tmp.join(''))){ slopeMap.set(tmp.join(''), slopeMap.get(tmp.join('')) + 1); } else{ slopeMap.set(tmp.join(''), 1); } curMax = Math.max(curMax, slopeMap.get(tmp.join(''))); } curMax = Math.max(curMax, verticalPoints); } // updating global maximum by current point's maximum maxPoint = Math.max(maxPoint, curMax + overlapPoints + 1); // printf(\"maximum collinear point // which contains current point // are : %d\\n\", curMax + overlapPoints + 1); slopeMap.clear(); } return maxPoint;} // Driver code{ let N = 6; let arr = [[-1, 1], [0, 0], [1, 1], [2, 2], [3, 3], [3, 4]]; console.log(maxPointOnSameLine(arr));} // The code is contributed by Gautam goel (gautamgoel962)",
"e": 9043,
"s": 6555,
"text": null
},
{
"code": null,
"e": 9045,
"s": 9043,
"text": "4"
},
{
"code": null,
"e": 9130,
"s": 9045,
"text": "Time Complexity: O(n2logn), where n denoting length of string.Auxiliary Space: O(n)."
},
{
"code": null,
"e": 9430,
"s": 9130,
"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. "
},
{
"code": null,
"e": 9442,
"s": 9430,
"text": "PortgasDAce"
},
{
"code": null,
"e": 9454,
"s": 9442,
"text": "RahulSingal"
},
{
"code": null,
"e": 9469,
"s": 9454,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 9482,
"s": 9469,
"text": "josalvatorre"
},
{
"code": null,
"e": 9491,
"s": 9482,
"text": "sweetyty"
},
{
"code": null,
"e": 9505,
"s": 9491,
"text": "gautamgoel962"
},
{
"code": null,
"e": 9520,
"s": 9505,
"text": "shivamanandrj9"
},
{
"code": null,
"e": 9537,
"s": 9520,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 9544,
"s": 9537,
"text": "Amazon"
},
{
"code": null,
"e": 9554,
"s": 9544,
"text": "Geometric"
},
{
"code": null,
"e": 9559,
"s": 9554,
"text": "Hash"
},
{
"code": null,
"e": 9572,
"s": 9559,
"text": "Mathematical"
},
{
"code": null,
"e": 9579,
"s": 9572,
"text": "Amazon"
},
{
"code": null,
"e": 9584,
"s": 9579,
"text": "Hash"
},
{
"code": null,
"e": 9597,
"s": 9584,
"text": "Mathematical"
},
{
"code": null,
"e": 9607,
"s": 9597,
"text": "Geometric"
},
{
"code": null,
"e": 9705,
"s": 9607,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9754,
"s": 9705,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 9785,
"s": 9754,
"text": "Find if two rectangles overlap"
},
{
"code": null,
"e": 9836,
"s": 9785,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 9894,
"s": 9836,
"text": "Check whether triangle is valid or not if sides are given"
},
{
"code": null,
"e": 9941,
"s": 9894,
"text": "Program for Point of Intersection of Two Lines"
},
{
"code": null,
"e": 10026,
"s": 9941,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 10064,
"s": 10026,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 10095,
"s": 10064,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 10131,
"s": 10095,
"text": "Internal Working of HashMap in Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.