title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Sensor Network Architecture - GeeksforGeeks | 30 Jan, 2020
Sensor Network Architecture is used in Wireless Sensor Network (WSN). It can be used in various places like schools, hospitals, buildings, roads, etc for various applications like disaster management, security management, crisis management, etc.
There are 2 types of architecture used in WSN: Layered Network Architecture, and Clustered Architecture. These are explained as following below.
1. Layered Network Architecture:Layered Network Architecture makes use of a few hundred sensor nodes and a single powerful base station. Network nodes are organized into concentric Layers.It consists of 5 layers and three cross layers.The 5 layers are:
1. Application Layer
2. Transport Layer
3. Network Layer
4. Data Link Layer
5. Physical Layer The cross layers consist of the following:Power Management PlaneMobility Management PlaneTask Management PlaneThe advantage of using Layered Network Architecture is that each node participates only in short-distance, low power transmissions to nodes of the neighbouing nodes because of which power consumption is less as compared to other Sensor Network Architecture. It is scalable and has a higher fault tolerance.2. Clustered Network Architecture:In Clustered Network Architecture, Sensor Nodes autonomously clubs into groups called clusters. It is based on the Leach Protocol which makes use of clusters. Leach Protocol stands for Low Energy Adaptive Clustering Hierarchy.Properties of Leach Protocol:It is a 2-tier hierarchy clustering architecture.It is a distributed algorithm for organizing the sensor nodes into groups called clusters.The cluster head nodes in each of the autonomously formed clusters create the Time-division multiple access (TDMA) schedules.It makes use of the concept called Data Fusion which makes it energy efficient.Here:Clustered Network Architecture is a very useful sensor network because of the property of Data Fusion. Inside each cluster, each node communicate with the cluster head to gather the information. All the clusters which are formed share their gathered information to the base station. The cluster formation and selection of cluster head inside each cluster is an independent and autonomous distributed process.My Personal Notes
arrow_drop_upSave
1. Application Layer
2. Transport Layer
3. Network Layer
4. Data Link Layer
5. Physical Layer
The cross layers consist of the following:
Power Management Plane
Mobility Management Plane
Task Management Plane
The advantage of using Layered Network Architecture is that each node participates only in short-distance, low power transmissions to nodes of the neighbouing nodes because of which power consumption is less as compared to other Sensor Network Architecture. It is scalable and has a higher fault tolerance.
2. Clustered Network Architecture:In Clustered Network Architecture, Sensor Nodes autonomously clubs into groups called clusters. It is based on the Leach Protocol which makes use of clusters. Leach Protocol stands for Low Energy Adaptive Clustering Hierarchy.
Properties of Leach Protocol:
It is a 2-tier hierarchy clustering architecture.
It is a distributed algorithm for organizing the sensor nodes into groups called clusters.
The cluster head nodes in each of the autonomously formed clusters create the Time-division multiple access (TDMA) schedules.
It makes use of the concept called Data Fusion which makes it energy efficient.
Here:
Clustered Network Architecture is a very useful sensor network because of the property of Data Fusion. Inside each cluster, each node communicate with the cluster head to gather the information. All the clusters which are formed share their gathered information to the base station. The cluster formation and selection of cluster head inside each cluster is an independent and autonomous distributed process.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Data encryption standard (DES) | Set 1
Differences between TCP and UDP
Socket Programming in Python
UDP Server-Client implementation in C
TCP 3-Way Handshake Process
Error Detection in Computer Networks
Differences between IPv4 and IPv6
Distance Vector Routing (DVR) Protocol | [
{
"code": null,
"e": 24446,
"s": 24418,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 24692,
"s": 24446,
"text": "Sensor Network Architecture is used in Wireless Sensor Network (WSN). It can be used in various places like schools, hospitals, buildings, roads, etc for various applications like disaster management, security management, crisis management, etc."
},
{
"code": null,
"e": 24837,
"s": 24692,
"text": "There are 2 types of architecture used in WSN: Layered Network Architecture, and Clustered Architecture. These are explained as following below."
},
{
"code": null,
"e": 25090,
"s": 24837,
"text": "1. Layered Network Architecture:Layered Network Architecture makes use of a few hundred sensor nodes and a single powerful base station. Network nodes are organized into concentric Layers.It consists of 5 layers and three cross layers.The 5 layers are:"
},
{
"code": null,
"e": 26681,
"s": 25090,
"text": "1. Application Layer\n2. Transport Layer\n3. Network Layer\n4. Data Link Layer\n5. Physical Layer The cross layers consist of the following:Power Management PlaneMobility Management PlaneTask Management PlaneThe advantage of using Layered Network Architecture is that each node participates only in short-distance, low power transmissions to nodes of the neighbouing nodes because of which power consumption is less as compared to other Sensor Network Architecture. It is scalable and has a higher fault tolerance.2. Clustered Network Architecture:In Clustered Network Architecture, Sensor Nodes autonomously clubs into groups called clusters. It is based on the Leach Protocol which makes use of clusters. Leach Protocol stands for Low Energy Adaptive Clustering Hierarchy.Properties of Leach Protocol:It is a 2-tier hierarchy clustering architecture.It is a distributed algorithm for organizing the sensor nodes into groups called clusters.The cluster head nodes in each of the autonomously formed clusters create the Time-division multiple access (TDMA) schedules.It makes use of the concept called Data Fusion which makes it energy efficient.Here:Clustered Network Architecture is a very useful sensor network because of the property of Data Fusion. Inside each cluster, each node communicate with the cluster head to gather the information. All the clusters which are formed share their gathered information to the base station. The cluster formation and selection of cluster head inside each cluster is an independent and autonomous distributed process.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 26776,
"s": 26681,
"text": "1. Application Layer\n2. Transport Layer\n3. Network Layer\n4. Data Link Layer\n5. Physical Layer "
},
{
"code": null,
"e": 26819,
"s": 26776,
"text": "The cross layers consist of the following:"
},
{
"code": null,
"e": 26842,
"s": 26819,
"text": "Power Management Plane"
},
{
"code": null,
"e": 26868,
"s": 26842,
"text": "Mobility Management Plane"
},
{
"code": null,
"e": 26890,
"s": 26868,
"text": "Task Management Plane"
},
{
"code": null,
"e": 27197,
"s": 26890,
"text": "The advantage of using Layered Network Architecture is that each node participates only in short-distance, low power transmissions to nodes of the neighbouing nodes because of which power consumption is less as compared to other Sensor Network Architecture. It is scalable and has a higher fault tolerance."
},
{
"code": null,
"e": 27458,
"s": 27197,
"text": "2. Clustered Network Architecture:In Clustered Network Architecture, Sensor Nodes autonomously clubs into groups called clusters. It is based on the Leach Protocol which makes use of clusters. Leach Protocol stands for Low Energy Adaptive Clustering Hierarchy."
},
{
"code": null,
"e": 27488,
"s": 27458,
"text": "Properties of Leach Protocol:"
},
{
"code": null,
"e": 27538,
"s": 27488,
"text": "It is a 2-tier hierarchy clustering architecture."
},
{
"code": null,
"e": 27629,
"s": 27538,
"text": "It is a distributed algorithm for organizing the sensor nodes into groups called clusters."
},
{
"code": null,
"e": 27755,
"s": 27629,
"text": "The cluster head nodes in each of the autonomously formed clusters create the Time-division multiple access (TDMA) schedules."
},
{
"code": null,
"e": 27835,
"s": 27755,
"text": "It makes use of the concept called Data Fusion which makes it energy efficient."
},
{
"code": null,
"e": 27841,
"s": 27835,
"text": "Here:"
},
{
"code": null,
"e": 28250,
"s": 27841,
"text": "Clustered Network Architecture is a very useful sensor network because of the property of Data Fusion. Inside each cluster, each node communicate with the cluster head to gather the information. All the clusters which are formed share their gathered information to the base station. The cluster formation and selection of cluster head inside each cluster is an independent and autonomous distributed process."
},
{
"code": null,
"e": 28268,
"s": 28250,
"text": "Computer Networks"
},
{
"code": null,
"e": 28286,
"s": 28268,
"text": "Computer Networks"
},
{
"code": null,
"e": 28384,
"s": 28286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28393,
"s": 28384,
"text": "Comments"
},
{
"code": null,
"e": 28406,
"s": 28393,
"text": "Old Comments"
},
{
"code": null,
"e": 28436,
"s": 28406,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 28474,
"s": 28436,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28513,
"s": 28474,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 28545,
"s": 28513,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 28574,
"s": 28545,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 28612,
"s": 28574,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28640,
"s": 28612,
"text": "TCP 3-Way Handshake Process"
},
{
"code": null,
"e": 28677,
"s": 28640,
"text": "Error Detection in Computer Networks"
},
{
"code": null,
"e": 28711,
"s": 28677,
"text": "Differences between IPv4 and IPv6"
}
]
|
WSDL - <types> Element | A web service needs to define its inputs and outputs and how they are mapped into and out of the services. WSDL <types> element takes care of defining the data types that are used by the web service. Types are XML documents, or document parts.
The types element describes all the data types used between the client and the server.
The types element describes all the data types used between the client and the server.
WSDL is not tied exclusively to a specific typing system.
WSDL is not tied exclusively to a specific typing system.
WSDL uses the W3C XML Schema specification as its default choice to define data types.
WSDL uses the W3C XML Schema specification as its default choice to define data types.
If the service uses only XML Schema built-in simple types, such as strings and integers, then types element is not required.
If the service uses only XML Schema built-in simple types, such as strings and integers, then types element is not required.
WSDL allows the types to be defined in separate elements so that the types are reusable with multiple web services.
WSDL allows the types to be defined in separate elements so that the types are reusable with multiple web services.
Here is a piece of code taken from W3C specification. This code depicts how a types element can be used within a WSDL.
<types>
<schema targetNamespace = "http://example.com/stockquote.xsd"
xmlns = "http://www.w3.org/2000/10/XMLSchema">
<element name = "TradePriceRequest">
<complexType>
<all>
<element name = "tickerSymbol" type = "string"/>
</all>
</complexType>
</element>
<element name = "TradePrice">
<complexType>
<all>
<element name = "price" type = "float"/>
</all>
</complexType>
</element>
</schema>
</types>
Data types address the problem of identifing the data types and the formats you intend to use with your web services. Type information is shared between the sender and the receiver. The recipients of messages therefore need access to the information you used to encode your data and must understand how to decode the data.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2048,
"s": 1804,
"text": "A web service needs to define its inputs and outputs and how they are mapped into and out of the services. WSDL <types> element takes care of defining the data types that are used by the web service. Types are XML documents, or document parts."
},
{
"code": null,
"e": 2135,
"s": 2048,
"text": "The types element describes all the data types used between the client and the server."
},
{
"code": null,
"e": 2222,
"s": 2135,
"text": "The types element describes all the data types used between the client and the server."
},
{
"code": null,
"e": 2280,
"s": 2222,
"text": "WSDL is not tied exclusively to a specific typing system."
},
{
"code": null,
"e": 2338,
"s": 2280,
"text": "WSDL is not tied exclusively to a specific typing system."
},
{
"code": null,
"e": 2425,
"s": 2338,
"text": "WSDL uses the W3C XML Schema specification as its default choice to define data types."
},
{
"code": null,
"e": 2512,
"s": 2425,
"text": "WSDL uses the W3C XML Schema specification as its default choice to define data types."
},
{
"code": null,
"e": 2637,
"s": 2512,
"text": "If the service uses only XML Schema built-in simple types, such as strings and integers, then types element is not required."
},
{
"code": null,
"e": 2762,
"s": 2637,
"text": "If the service uses only XML Schema built-in simple types, such as strings and integers, then types element is not required."
},
{
"code": null,
"e": 2878,
"s": 2762,
"text": "WSDL allows the types to be defined in separate elements so that the types are reusable with multiple web services."
},
{
"code": null,
"e": 2994,
"s": 2878,
"text": "WSDL allows the types to be defined in separate elements so that the types are reusable with multiple web services."
},
{
"code": null,
"e": 3113,
"s": 2994,
"text": "Here is a piece of code taken from W3C specification. This code depicts how a types element can be used within a WSDL."
},
{
"code": null,
"e": 3671,
"s": 3113,
"text": "<types>\n <schema targetNamespace = \"http://example.com/stockquote.xsd\"\n xmlns = \"http://www.w3.org/2000/10/XMLSchema\">\n\t\t\n <element name = \"TradePriceRequest\">\n <complexType>\n <all>\n <element name = \"tickerSymbol\" type = \"string\"/>\n </all>\n </complexType>\n </element>\n\t\t\n <element name = \"TradePrice\">\n <complexType>\n <all>\n <element name = \"price\" type = \"float\"/>\n </all>\n </complexType>\n </element>\n\t\t\n </schema>\n</types>"
},
{
"code": null,
"e": 3994,
"s": 3671,
"text": "Data types address the problem of identifing the data types and the formats you intend to use with your web services. Type information is shared between the sender and the receiver. The recipients of messages therefore need access to the information you used to encode your data and must understand how to decode the data."
},
{
"code": null,
"e": 4001,
"s": 3994,
"text": " Print"
},
{
"code": null,
"e": 4012,
"s": 4001,
"text": " Add Notes"
}
]
|
Filter the rows – Python Pandas | To filter the rows and fetch specific column value, use the Pandas contains() method. At first, let us import the required library with alias −
import pandas as pd
Read the CSV file using the read_csv(). Our CSV file is on the Desktop −
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
Now, let us filter the rows with specific text −
dataFrame = dataFrame[dataFrame['Car'].str.contains('Lamborghini')]
Following is the code
import pandas as pd
# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n",dataFrame)
# select rows containing text "Lamborghini"
dataFrame = dataFrame[dataFrame['Car'].str.contains('Lamborghini')]
print("\nFetching rows with text Lamborghini ...\n",dataFrame)
This will produce the following output −
DataFrame...
Car Place UnitsSold
0 Audi Bangalore 80
1 Porsche Mumbai 110
2 RollsRoyce Pune 100
3 BMW Delhi 95
4 Mercedes Hyderabad 80
5 Lamborghini Chandigarh 80
6 Audi Mumbai 100
7 Mercedes Pune 120
8 Lamborghini Delhi 100
Fetching rows with text Lamborghini ...
Car Place UnitsSold
5 Lamborghini Chandigarh 80
8 Lamborghini Delhi 100 | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "To filter the rows and fetch specific column value, use the Pandas contains() method. At first, let us import the required library with alias −"
},
{
"code": null,
"e": 1226,
"s": 1206,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1299,
"s": 1226,
"text": "Read the CSV file using the read_csv(). Our CSV file is on the Desktop −"
},
{
"code": null,
"e": 1369,
"s": 1299,
"text": "dataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\CarRecords.csv\")\n"
},
{
"code": null,
"e": 1418,
"s": 1369,
"text": "Now, let us filter the rows with specific text −"
},
{
"code": null,
"e": 1486,
"s": 1418,
"text": "dataFrame = dataFrame[dataFrame['Car'].str.contains('Lamborghini')]"
},
{
"code": null,
"e": 1508,
"s": 1486,
"text": "Following is the code"
},
{
"code": null,
"e": 1827,
"s": 1508,
"text": "import pandas as pd\n\n# reading csv file\ndataFrame = pd.read_csv(\"C:\\\\Users\\\\amit_\\\\Desktop\\\\CarRecords.csv\")\nprint(\"DataFrame...\\n\",dataFrame)\n\n# select rows containing text \"Lamborghini\"\ndataFrame = dataFrame[dataFrame['Car'].str.contains('Lamborghini')]\nprint(\"\\nFetching rows with text Lamborghini ...\\n\",dataFrame)"
},
{
"code": null,
"e": 1868,
"s": 1827,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2429,
"s": 1868,
"text": "DataFrame...\n Car Place UnitsSold\n0 Audi Bangalore 80\n1 Porsche Mumbai 110\n2 RollsRoyce Pune 100\n3 BMW Delhi 95\n4 Mercedes Hyderabad 80\n5 Lamborghini Chandigarh 80\n6 Audi Mumbai 100\n7 Mercedes Pune 120\n8 Lamborghini Delhi 100\n\nFetching rows with text Lamborghini ...\n Car Place UnitsSold\n5 Lamborghini Chandigarh 80\n8 Lamborghini Delhi 100"
}
]
|
verify - Unix, Linux Command | verify [generic Postfix daemon options]
Addresses are verified by injecting probe messages into the
Postfix queue. Probe messages are run through all the routing
and rewriting machinery except for final delivery, and are
discarded rather than being deferred or bounced.
Address verification relies on the answer from the nearest
MTA for the specified address, and will therefore not detect
all undeliverable addresses.
The verify(8) server is designed to run under control
by the Postfix
master server. It maintains an optional persistent database.
To avoid being interrupted by "postfix stop" in the middle
of a database update, the process runs in a separate process
group.
The verify(8) server implements the following requests:
The address verification server can be coerced to store
unlimited amounts of garbage. Limiting the cache size
trades one problem (disk space exhaustion) for another
one (poor response time to client requests).
If the persistent database ever gets corrupted then the world
comes to an end and human intervention is needed. This violates
a basic Postfix principle.
The text below provides only a parameter summary. See
postconf(5) for more details including examples.
smtpd(8), Postfix SMTP server
cleanup(8), enqueue Postfix message
postconf(5), configuration parameters
syslogd(5), system logging
ADDRESS_VERIFICATION_README, address verification howto
Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10618,
"s": 10577,
"text": "verify [generic Postfix daemon options]\n"
},
{
"code": null,
"e": 10850,
"s": 10618,
"text": "\nAddresses are verified by injecting probe messages into the\nPostfix queue. Probe messages are run through all the routing\nand rewriting machinery except for final delivery, and are\ndiscarded rather than being deferred or bounced.\n"
},
{
"code": null,
"e": 11001,
"s": 10850,
"text": "\nAddress verification relies on the answer from the nearest\nMTA for the specified address, and will therefore not detect\nall undeliverable addresses.\n"
},
{
"code": null,
"e": 11260,
"s": 11001,
"text": "\nThe verify(8) server is designed to run under control\nby the Postfix\nmaster server. It maintains an optional persistent database.\nTo avoid being interrupted by \"postfix stop\" in the middle\nof a database update, the process runs in a separate process\ngroup.\n"
},
{
"code": null,
"e": 11318,
"s": 11260,
"text": "\nThe verify(8) server implements the following requests:\n"
},
{
"code": null,
"e": 11532,
"s": 11320,
"text": "\nThe address verification server can be coerced to store\nunlimited amounts of garbage. Limiting the cache size\ntrades one problem (disk space exhaustion) for another\none (poor response time to client requests).\n"
},
{
"code": null,
"e": 11687,
"s": 11532,
"text": "\nIf the persistent database ever gets corrupted then the world\ncomes to an end and human intervention is needed. This violates\na basic Postfix principle.\n"
},
{
"code": null,
"e": 11794,
"s": 11689,
"text": "\nThe text below provides only a parameter summary. See\npostconf(5) for more details including examples.\n"
},
{
"code": null,
"e": 11932,
"s": 11800,
"text": "smtpd(8), Postfix SMTP server\ncleanup(8), enqueue Postfix message\npostconf(5), configuration parameters\nsyslogd(5), system logging\n"
},
{
"code": null,
"e": 11991,
"s": 11934,
"text": "ADDRESS_VERIFICATION_README, address verification howto\n"
},
{
"code": null,
"e": 12080,
"s": 11995,
"text": "Wietse Venema\nIBM T.J. Watson Research\nP.O. Box 704\nYorktown Heights, NY 10598, USA\n"
},
{
"code": null,
"e": 12097,
"s": 12080,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 12132,
"s": 12097,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 12160,
"s": 12132,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12194,
"s": 12160,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12211,
"s": 12194,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 12244,
"s": 12211,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12255,
"s": 12244,
"text": " Pradeep D"
},
{
"code": null,
"e": 12290,
"s": 12255,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 12306,
"s": 12290,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 12339,
"s": 12306,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12351,
"s": 12339,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 12383,
"s": 12351,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 12391,
"s": 12383,
"text": " Uplatz"
},
{
"code": null,
"e": 12398,
"s": 12391,
"text": " Print"
},
{
"code": null,
"e": 12409,
"s": 12398,
"text": " Add Notes"
}
]
|
What is JDBC Clob data type? how to store and read data from it? | CLOB stands for Character Large Object in general, an SQL Clob is a built-in datatype and is used to store large amount of textual data. Using this datatype, you can store data up to 2,147,483,647 characters.
The java.sql.Clob interface of the JDBC API represents the CLOB datatype. Since the Clob object in JDBC is implemented using an SQL locator, it holds a logical pointer to the SQL CLOB (not the data).
MYSQL database provides support for this datatype using four variables.
TINYTEXT: A CLOB type with a maximum of 28-1 (255) characters.
TINYTEXT: A CLOB type with a maximum of 28-1 (255) characters.
TEXT: A CLOB type with a maximum of 216-1 (65535) characters.
TEXT: A CLOB type with a maximum of 216-1 (65535) characters.
MEDIUMTEXT: A CLOB type with a maximum of 224-1 (16777215) characters.
MEDIUMTEXT: A CLOB type with a maximum of 224-1 (16777215) characters.
LONGTEXT: A CLOB type with a maximum of 232-1 (4294967295 ) characters.
LONGTEXT: A CLOB type with a maximum of 232-1 (4294967295 ) characters.
To store Clob datatype to database, using JDBC program follow the steps given below
You can connect to a database using the getConnection() method of the DriverManager class.
Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method.
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO Technologies(Name,
Type, Article ) VALUES (?, ?, ?)");
Set the values to the place holders using the setter methods of the PreparedStatement interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method.
And if it is of Clob type you can set value to it using the setCharacterStream() or setClob() methods. To these methods pass an integer variable representing the parameter index and an object of the Reader class as parameters.
pstmt.setString(1, "JavaFX");
pstmt.setString(2, "Java Library");
FileReader reader = new FileReader("E:\\images\\javafx.txt");
pstmt.setClob(3, reader);
pstmt.execute();
Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface.
The getClob() method of the ResultSet interface accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column and returns it in the form of a Clob object.
while(rs.next()) {
System.out.println(rs.getString("Name"));
System.out.println(rs.getString("Type"));
Clob clob = rs.getClob("Article");
}
The getCharacterStream() method of the Clob Interface retrieves the contents of the current Clob object and returns as a Reader object.
Using the getClob() method you can get the contents of the Clob as a Reader object and create text file with the retrieved contents, using the write() method of the FileOutputStream object.
Reader r = clob.getCharacterStream();
char cbuf[] = new char[r.read()];
r.read(cbuf);
FileOutputStream outPutStream = new
FileOutputStream("E:\\images\\clob_output"+i+".txt");
outPutStream.write(cbuf.toString().getBytes());
Following example creates a table in MySQL database with a Clob datatype in it. Inserts large text data from a file to it. Retrieves the text back and stores it in another text file.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class ClobExample {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a table
Statement stmt = con.createStatement();
stmt.execute("CREATE TABLE Technologies( Name VARCHAR(255), Type VARCHAR(255), Article LONGTEXT)");
System.out.println("Table Created......");
//Inserting values
String query = "INSERT INTO Technologies(Name, Type, Article ) VALUES (?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "JavaFX");
pstmt.setString(2, "Java Library");
FileReader reader = new FileReader("E:\\images\\javafx.txt");
pstmt.setClob(3, reader);
pstmt.execute();
pstmt.setString(1, "CoffeeScript");
pstmt.setString(2, "Scripting Language");
reader = new FileReader("E:\\images\\coffeescript.txt");
pstmt.setClob(3, reader);
pstmt.execute();
pstmt.setString(1, "Cassandra");
pstmt.setString(2, "NoSQL Database");
reader = new FileReader("E:\\images\\cassandra.txt");
pstmt.setClob(3, reader);
pstmt.execute();
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from Technologies");
int j = 0;
System.out.println("Contents of the table are: ");
while(rs.next()) {
System.out.println(rs.getString("Name"));
Clob clob = rs.getClob("Article");
Reader r = clob.getCharacterStream();
String filePath = "E:\\Data\\clob_output"+j+".txt";
FileWriter writer = new FileWriter(filePath);
int i;
while ((i=r.read())!=-1) {
writer.write(i);
}
writer.close();
System.out.println(filePath);
j++;
}
}
}
Connection established......
Table Created......
Contents of the table are:
JavaFX
Java Library
E:\images\clob_output1.txt
CoffeeScript
Scripting Language
E:\images\clob_output2.txt
Cassandra
NoSQL Database
E:\images\clob_output3.txt | [
{
"code": null,
"e": 1271,
"s": 1062,
"text": "CLOB stands for Character Large Object in general, an SQL Clob is a built-in datatype and is used to store large amount of textual data. Using this datatype, you can store data up to 2,147,483,647 characters."
},
{
"code": null,
"e": 1471,
"s": 1271,
"text": "The java.sql.Clob interface of the JDBC API represents the CLOB datatype. Since the Clob object in JDBC is implemented using an SQL locator, it holds a logical pointer to the SQL CLOB (not the data)."
},
{
"code": null,
"e": 1543,
"s": 1471,
"text": "MYSQL database provides support for this datatype using four variables."
},
{
"code": null,
"e": 1606,
"s": 1543,
"text": "TINYTEXT: A CLOB type with a maximum of 28-1 (255) characters."
},
{
"code": null,
"e": 1669,
"s": 1606,
"text": "TINYTEXT: A CLOB type with a maximum of 28-1 (255) characters."
},
{
"code": null,
"e": 1731,
"s": 1669,
"text": "TEXT: A CLOB type with a maximum of 216-1 (65535) characters."
},
{
"code": null,
"e": 1793,
"s": 1731,
"text": "TEXT: A CLOB type with a maximum of 216-1 (65535) characters."
},
{
"code": null,
"e": 1864,
"s": 1793,
"text": "MEDIUMTEXT: A CLOB type with a maximum of 224-1 (16777215) characters."
},
{
"code": null,
"e": 1935,
"s": 1864,
"text": "MEDIUMTEXT: A CLOB type with a maximum of 224-1 (16777215) characters."
},
{
"code": null,
"e": 2007,
"s": 1935,
"text": "LONGTEXT: A CLOB type with a maximum of 232-1 (4294967295 ) characters."
},
{
"code": null,
"e": 2079,
"s": 2007,
"text": "LONGTEXT: A CLOB type with a maximum of 232-1 (4294967295 ) characters."
},
{
"code": null,
"e": 2163,
"s": 2079,
"text": "To store Clob datatype to database, using JDBC program follow the steps given below"
},
{
"code": null,
"e": 2254,
"s": 2163,
"text": "You can connect to a database using the getConnection() method of the DriverManager class."
},
{
"code": null,
"e": 2456,
"s": 2254,
"text": "Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method."
},
{
"code": null,
"e": 2585,
"s": 2456,
"text": "String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\nConnection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");"
},
{
"code": null,
"e": 2758,
"s": 2585,
"text": "Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter."
},
{
"code": null,
"e": 2873,
"s": 2758,
"text": "PreparedStatement pstmt = con.prepareStatement(\"INSERT INTO Technologies(Name,\nType, Article ) VALUES (?, ?, ?)\");"
},
{
"code": null,
"e": 3151,
"s": 2873,
"text": "Set the values to the place holders using the setter methods of the PreparedStatement interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method."
},
{
"code": null,
"e": 3378,
"s": 3151,
"text": "And if it is of Clob type you can set value to it using the setCharacterStream() or setClob() methods. To these methods pass an integer variable representing the parameter index and an object of the Reader class as parameters."
},
{
"code": null,
"e": 3549,
"s": 3378,
"text": "pstmt.setString(1, \"JavaFX\");\npstmt.setString(2, \"Java Library\");\nFileReader reader = new FileReader(\"E:\\\\images\\\\javafx.txt\");\npstmt.setClob(3, reader);\npstmt.execute();"
},
{
"code": null,
"e": 3663,
"s": 3549,
"text": "Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface."
},
{
"code": null,
"e": 3917,
"s": 3663,
"text": "The getClob() method of the ResultSet interface accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column and returns it in the form of a Clob object."
},
{
"code": null,
"e": 4066,
"s": 3917,
"text": "while(rs.next()) {\n System.out.println(rs.getString(\"Name\"));\n System.out.println(rs.getString(\"Type\"));\n Clob clob = rs.getClob(\"Article\");\n}"
},
{
"code": null,
"e": 4202,
"s": 4066,
"text": "The getCharacterStream() method of the Clob Interface retrieves the contents of the current Clob object and returns as a Reader object."
},
{
"code": null,
"e": 4392,
"s": 4202,
"text": "Using the getClob() method you can get the contents of the Clob as a Reader object and create text file with the retrieved contents, using the write() method of the FileOutputStream object."
},
{
"code": null,
"e": 4616,
"s": 4392,
"text": "Reader r = clob.getCharacterStream();\nchar cbuf[] = new char[r.read()];\nr.read(cbuf);\nFileOutputStream outPutStream = new\nFileOutputStream(\"E:\\\\images\\\\clob_output\"+i+\".txt\");\noutPutStream.write(cbuf.toString().getBytes());"
},
{
"code": null,
"e": 4799,
"s": 4616,
"text": "Following example creates a table in MySQL database with a Clob datatype in it. Inserts large text data from a file to it. Retrieves the text back and stores it in another text file."
},
{
"code": null,
"e": 7108,
"s": 4799,
"text": "import java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.Reader;\nimport java.sql.Clob;\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class ClobExample {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a table\n Statement stmt = con.createStatement();\n stmt.execute(\"CREATE TABLE Technologies( Name VARCHAR(255), Type VARCHAR(255), Article LONGTEXT)\");\n System.out.println(\"Table Created......\");\n\n //Inserting values\n String query = \"INSERT INTO Technologies(Name, Type, Article ) VALUES (?, ?, ?)\";\n PreparedStatement pstmt = con.prepareStatement(query);\n pstmt.setString(1, \"JavaFX\");\n pstmt.setString(2, \"Java Library\");\n FileReader reader = new FileReader(\"E:\\\\images\\\\javafx.txt\");\n pstmt.setClob(3, reader);\n pstmt.execute();\n pstmt.setString(1, \"CoffeeScript\");\n pstmt.setString(2, \"Scripting Language\");\n reader = new FileReader(\"E:\\\\images\\\\coffeescript.txt\");\n pstmt.setClob(3, reader);\n pstmt.execute();\n pstmt.setString(1, \"Cassandra\");\n pstmt.setString(2, \"NoSQL Database\");\n reader = new FileReader(\"E:\\\\images\\\\cassandra.txt\");\n pstmt.setClob(3, reader);\n pstmt.execute();\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from Technologies\");\n int j = 0;\n System.out.println(\"Contents of the table are: \");\n while(rs.next()) {\n System.out.println(rs.getString(\"Name\"));\n Clob clob = rs.getClob(\"Article\");\n Reader r = clob.getCharacterStream();\n String filePath = \"E:\\\\Data\\\\clob_output\"+j+\".txt\";\n FileWriter writer = new FileWriter(filePath);\n int i;\n while ((i=r.read())!=-1) {\n writer.write(i);\n }\n writer.close();\n System.out.println(filePath);\n j++;\n }\n }\n}"
},
{
"code": null,
"e": 7342,
"s": 7108,
"text": "Connection established......\nTable Created......\nContents of the table are:\nJavaFX\nJava Library\nE:\\images\\clob_output1.txt\nCoffeeScript\nScripting Language\nE:\\images\\clob_output2.txt\nCassandra\nNoSQL Database\nE:\\images\\clob_output3.txt"
}
]
|
Command to check read/write ratio in MySQL? | To check the read/write ratio, you need to use SHOW STATUS command. This will give all the ratios.
Case 1 − The syntax is as follows to get the read/write ratio −
SHOW STATUS LIKE ‘Com_%’;
Case 2 − If you want the insert, update, select and delete ratio, use the below syntax −
SHOW GLOBAL STATUS WHERE Variable_name = 'Com_insert'
OR Variable_name = 'Com_select' OR
Variable_name = 'Com_Update' OR Variable_name = 'Com_delete';
Here is no need to do any changes in the above syntax. The query is as follows −
mysql> SHOW GLOBAL STATUS WHERE Variable_name = 'Com_insert' OR Variable_name
= 'Com_select' OR
-> Variable_name = 'Com_Update' OR Variable_name = 'Com_delete';
The following is the output −
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Com_delete | 5 |
| Com_insert | 340 |
| Com_select | 286 |
| Com_update | 13 |
+---------------+-------+
4 rows in set (0.00 sec)
If you want all the info then use the above syntax. The query is as follows −
mysql> Show status like 'Com_%';
The following is the output −
+-------------------------------------+-------+
| Variable_name | Value |
+-------------------------------------+-------+
| Com_admin_commands | 0 |
| Com_assign_to_keycache | 0 |
| Com_alter_db | 0 |
| Com_alter_event | 0 |
| Com_alter_function | 0 |
| Com_alter_instance | 0 |
| Com_alter_procedure | 0 |
| Com_alter_resource_group | 0 |
| Com_alter_server | 0 |
| Com_alter_table | 0 |
| Com_alter_tablespace | 0 |
| Com_alter_user | 0 |
| Com_alter_user_default_role | 0 |
| Com_analyze | 0 |
| Com_begin | 0 |
| Com_binlog | 0 |
| Com_call_procedure | 0 |
| Com_change_db | 1 |
| Com_change_master | 0 |
| Com_change_repl_filter | 0 |
| Com_check | 0 |
| Com_checksum | 0 |
| Com_clone | 0 |
| Com_commit | 0 |
| Com_create_db | 0 |
| Com_create_event | 0 |
| Com_create_function | 0 |
| Com_create_index | 0 |
| Com_create_procedure | 0 |
| Com_create_role | 0 |
| Com_create_server | 0 |
| Com_create_table | 6 |
| Com_create_resource_group | 0 |
| Com_create_trigger | 0 |
| Com_create_udf | 0 |
| Com_create_user | 0 |
| Com_create_view | 0 |
| Com_create_spatial_reference_system | 0 |
| Com_dealloc_sql | 0 |
| Com_delete | 0 |
| Com_delete_multi | 0 |
| Com_do | 0 |
| Com_drop_db | 0 |
| Com_drop_event | 0 |
| Com_drop_function | 0 |
| Com_drop_index | 0 |
| Com_drop_procedure | 0 |
| Com_drop_resource_group | 0 |
| Com_drop_role | 0 |
| Com_drop_server | 0 |
| Com_drop_spatial_reference_system | 0 |
| Com_drop_table | 0 |
| Com_drop_trigger | 0 |
| Com_drop_user | 0 |
| Com_drop_view | 0 |
| Com_empty_query | 0 |
| Com_execute_sql | 0 |
| Com_explain_other | 0 |
| Com_flush | 0 |
| Com_get_diagnostics | 0 |
| Com_grant | 0 |
| Com_grant_roles | 0 |
| Com_ha_close | 0 |
| Com_ha_open | 0 |
| Com_ha_read | 0 |
| Com_help | 0 |
| Com_import | 0 |
| Com_insert | 42 |
| Com_insert_select | 0 |
| Com_install_component | 0 |
| Com_install_plugin | 0 |
| Com_kill | 0 |
| Com_load | 0 |
| Com_lock_instance | 0 |
| Com_lock_tables | 0 |
| Com_optimize | 0 |
| Com_preload_keys | 0 |
| Com_prepare_sql | 0 |
| Com_purge | 0 |
| Com_purge_before_date | 0 |
| Com_release_savepoint | 0 |
| Com_rename_table | 0 |
| Com_rename_user | 0 |
| Com_repair | 0 |
| Com_replace | 0 |
| Com_replace_select | 0 |
| Com_reset | 0 |
| Com_resignal | 0 |
| Com_restart | 0 |
| Com_revoke | 0 |
| Com_revoke_all | 0 |
| Com_revoke_roles | 0 |
| Com_rollback | 0 |
| Com_rollback_to_savepoint | 0 |
| Com_savepoint | 0 |
| Com_select | 27 |
| Com_set_option | 3 |
| Com_set_password | 0 |
| Com_set_resource_group | 0 |
| Com_set_role | 0 |
| Com_signal | 0 |
| Com_show_binlog_events | 0 |
| Com_show_binlogs | 0 |
| Com_show_charsets | 0 |
| Com_show_collations | 0 |
| Com_show_create_db | 0 |
| Com_show_create_event | 0 |
| Com_show_create_func | 0 |
| Com_show_create_proc | 0 |
| Com_show_create_table | 0 |
| Com_show_create_trigger | 0 |
| Com_show_databases | 0 |
| Com_show_engine_logs | 0 |
| Com_show_engine_mutex | 0 |
| Com_show_engine_status | 0 |
| Com_show_events | 0 |
| Com_show_errors | 0 |
| Com_show_fields | 0 |
| Com_show_function_code | 0 |
| Com_show_function_status | 0 |
| Com_show_grants | 0 |
| Com_show_keys | 0 |
| Com_show_master_status | 0 |
| Com_show_open_tables | 0 |
| Com_show_plugins | 0 |
| Com_show_privileges | 0 |
| Com_show_procedure_code | 0 |
| Com_show_procedure_status | 0 |
| Com_show_processlist | 0 |
| Com_show_profile | 0 |
| Com_show_profiles | 0 |
| Com_show_relaylog_events | 0 |
| Com_show_slave_hosts | 0 |
| Com_show_slave_status | 0 |
| Com_show_status | 3 |
| Com_show_storage_engines | 0 |
| Com_show_table_status | 0 |
| Com_show_tables | 0 |
| Com_show_triggers | 0 |
| Com_show_variables | 2 |
| Com_show_warnings | 0 |
| Com_show_create_user | 0 |
| Com_shutdown | 0 |
| Com_slave_start | 0 |
| Com_slave_stop | 0 |
| Com_group_replication_start | 0 |
| Com_group_replication_stop | 0 |
| Com_stmt_execute | 0 |
| Com_stmt_close | 0 |
| Com_stmt_fetch | 0 |
| Com_stmt_prepare | 0 |
| Com_stmt_reset | 0 |
| Com_stmt_send_long_data | 0 |
| Com_truncate | 0 |
| Com_uninstall_component | 0 |
| Com_uninstall_plugin | 0 |
| Com_unlock_instance | 0 |
| Com_unlock_tables | 0 |
| Com_update | 0 |
| Com_update_multi | 0 |
| Com_xa_commit | 0 |
| Com_xa_end | 0 |
| Com_xa_prepare | 0 |
| Com_xa_recover | 0 |
| Com_xa_rollback | 0 |
| Com_xa_start | 0 |
| Com_stmt_reprepare | 0 |
| Compression | OFF |
+-------------------------------------+-------+
168 rows in set (0.04 sec) | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "To check the read/write ratio, you need to use SHOW STATUS command. This will give all the ratios."
},
{
"code": null,
"e": 1225,
"s": 1161,
"text": "Case 1 − The syntax is as follows to get the read/write ratio −"
},
{
"code": null,
"e": 1251,
"s": 1225,
"text": "SHOW STATUS LIKE ‘Com_%’;"
},
{
"code": null,
"e": 1340,
"s": 1251,
"text": "Case 2 − If you want the insert, update, select and delete ratio, use the below syntax −"
},
{
"code": null,
"e": 1491,
"s": 1340,
"text": "SHOW GLOBAL STATUS WHERE Variable_name = 'Com_insert'\nOR Variable_name = 'Com_select' OR\nVariable_name = 'Com_Update' OR Variable_name = 'Com_delete';"
},
{
"code": null,
"e": 1572,
"s": 1491,
"text": "Here is no need to do any changes in the above syntax. The query is as follows −"
},
{
"code": null,
"e": 1736,
"s": 1572,
"text": "mysql> SHOW GLOBAL STATUS WHERE Variable_name = 'Com_insert' OR Variable_name\n= 'Com_select' OR\n -> Variable_name = 'Com_Update' OR Variable_name = 'Com_delete';"
},
{
"code": null,
"e": 1766,
"s": 1736,
"text": "The following is the output −"
},
{
"code": null,
"e": 1999,
"s": 1766,
"text": "+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| Com_delete | 5 |\n| Com_insert | 340 |\n| Com_select | 286 |\n| Com_update | 13 |\n+---------------+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2077,
"s": 1999,
"text": "If you want all the info then use the above syntax. The query is as follows −"
},
{
"code": null,
"e": 2110,
"s": 2077,
"text": "mysql> Show status like 'Com_%';"
},
{
"code": null,
"e": 2140,
"s": 2110,
"text": "The following is the output −"
},
{
"code": null,
"e": 10423,
"s": 2140,
"text": "+-------------------------------------+-------+\n| Variable_name | Value |\n+-------------------------------------+-------+\n| Com_admin_commands | 0 |\n| Com_assign_to_keycache | 0 |\n| Com_alter_db | 0 |\n| Com_alter_event | 0 |\n| Com_alter_function | 0 |\n| Com_alter_instance | 0 |\n| Com_alter_procedure | 0 |\n| Com_alter_resource_group | 0 |\n| Com_alter_server | 0 |\n| Com_alter_table | 0 |\n| Com_alter_tablespace | 0 |\n| Com_alter_user | 0 |\n| Com_alter_user_default_role | 0 |\n| Com_analyze | 0 |\n| Com_begin | 0 |\n| Com_binlog | 0 |\n| Com_call_procedure | 0 |\n| Com_change_db | 1 |\n| Com_change_master | 0 |\n| Com_change_repl_filter | 0 |\n| Com_check | 0 |\n| Com_checksum | 0 |\n| Com_clone | 0 |\n| Com_commit | 0 |\n| Com_create_db | 0 |\n| Com_create_event | 0 |\n| Com_create_function | 0 |\n| Com_create_index | 0 |\n| Com_create_procedure | 0 |\n| Com_create_role | 0 |\n| Com_create_server | 0 |\n| Com_create_table | 6 |\n| Com_create_resource_group | 0 |\n| Com_create_trigger | 0 |\n| Com_create_udf | 0 |\n| Com_create_user | 0 |\n| Com_create_view | 0 |\n| Com_create_spatial_reference_system | 0 |\n| Com_dealloc_sql | 0 |\n| Com_delete | 0 |\n| Com_delete_multi | 0 |\n| Com_do | 0 |\n| Com_drop_db | 0 |\n| Com_drop_event | 0 |\n| Com_drop_function | 0 |\n| Com_drop_index | 0 |\n| Com_drop_procedure | 0 |\n| Com_drop_resource_group | 0 |\n| Com_drop_role | 0 |\n| Com_drop_server | 0 |\n| Com_drop_spatial_reference_system | 0 |\n| Com_drop_table | 0 |\n| Com_drop_trigger | 0 |\n| Com_drop_user | 0 |\n| Com_drop_view | 0 |\n| Com_empty_query | 0 |\n| Com_execute_sql | 0 |\n| Com_explain_other | 0 |\n| Com_flush | 0 |\n| Com_get_diagnostics | 0 |\n| Com_grant | 0 |\n| Com_grant_roles | 0 |\n| Com_ha_close | 0 |\n| Com_ha_open | 0 |\n| Com_ha_read | 0 |\n| Com_help | 0 |\n| Com_import | 0 |\n| Com_insert | 42 |\n| Com_insert_select | 0 |\n| Com_install_component | 0 |\n| Com_install_plugin | 0 |\n| Com_kill | 0 |\n| Com_load | 0 |\n| Com_lock_instance | 0 |\n| Com_lock_tables | 0 |\n| Com_optimize | 0 |\n| Com_preload_keys | 0 |\n| Com_prepare_sql | 0 |\n| Com_purge | 0 |\n| Com_purge_before_date | 0 |\n| Com_release_savepoint | 0 |\n| Com_rename_table | 0 |\n| Com_rename_user | 0 |\n| Com_repair | 0 |\n| Com_replace | 0 |\n| Com_replace_select | 0 |\n| Com_reset | 0 |\n| Com_resignal | 0 |\n| Com_restart | 0 |\n| Com_revoke | 0 |\n| Com_revoke_all | 0 |\n| Com_revoke_roles | 0 |\n| Com_rollback | 0 |\n| Com_rollback_to_savepoint | 0 |\n| Com_savepoint | 0 |\n| Com_select | 27 |\n| Com_set_option | 3 |\n| Com_set_password | 0 |\n| Com_set_resource_group | 0 |\n| Com_set_role | 0 |\n| Com_signal | 0 |\n| Com_show_binlog_events | 0 |\n| Com_show_binlogs | 0 |\n| Com_show_charsets | 0 |\n| Com_show_collations | 0 |\n| Com_show_create_db | 0 |\n| Com_show_create_event | 0 |\n| Com_show_create_func | 0 |\n| Com_show_create_proc | 0 |\n| Com_show_create_table | 0 |\n| Com_show_create_trigger | 0 |\n| Com_show_databases | 0 |\n| Com_show_engine_logs | 0 |\n| Com_show_engine_mutex | 0 |\n| Com_show_engine_status | 0 |\n| Com_show_events | 0 |\n| Com_show_errors | 0 |\n| Com_show_fields | 0 |\n| Com_show_function_code | 0 |\n| Com_show_function_status | 0 |\n| Com_show_grants | 0 |\n| Com_show_keys | 0 |\n| Com_show_master_status | 0 |\n| Com_show_open_tables | 0 |\n| Com_show_plugins | 0 |\n| Com_show_privileges | 0 |\n| Com_show_procedure_code | 0 |\n| Com_show_procedure_status | 0 |\n| Com_show_processlist | 0 |\n| Com_show_profile | 0 |\n| Com_show_profiles | 0 |\n| Com_show_relaylog_events | 0 |\n| Com_show_slave_hosts | 0 |\n| Com_show_slave_status | 0 |\n| Com_show_status | 3 |\n| Com_show_storage_engines | 0 |\n| Com_show_table_status | 0 |\n| Com_show_tables | 0 |\n| Com_show_triggers | 0 |\n| Com_show_variables | 2 |\n| Com_show_warnings | 0 |\n| Com_show_create_user | 0 |\n| Com_shutdown | 0 |\n| Com_slave_start | 0 |\n| Com_slave_stop | 0 |\n| Com_group_replication_start | 0 |\n| Com_group_replication_stop | 0 |\n| Com_stmt_execute | 0 |\n| Com_stmt_close | 0 |\n| Com_stmt_fetch | 0 |\n| Com_stmt_prepare | 0 |\n| Com_stmt_reset | 0 |\n| Com_stmt_send_long_data | 0 |\n| Com_truncate | 0 |\n| Com_uninstall_component | 0 |\n| Com_uninstall_plugin | 0 |\n| Com_unlock_instance | 0 |\n| Com_unlock_tables | 0 |\n| Com_update | 0 |\n| Com_update_multi | 0 |\n| Com_xa_commit | 0 |\n| Com_xa_end | 0 |\n| Com_xa_prepare | 0 |\n| Com_xa_recover | 0 |\n| Com_xa_rollback | 0 |\n| Com_xa_start | 0 |\n| Com_stmt_reprepare | 0 |\n| Compression | OFF |\n+-------------------------------------+-------+\n168 rows in set (0.04 sec)"
}
]
|
How to Write a Winning Data Science Resume | Towards Data Science | IntroductionAestheticGoalExperiencesSkillsEducation/ExtracurricularsSummaryReferences
Introduction
Aesthetic
Goal
Experiences
Skills
Education/Extracurriculars
Summary
References
Attracting top tech companies can not only be extremely difficult but intimidating as well. However, I am here to tell you that you can indeed do it, you can catch the eye of “FAAMG” — that is Facebook, Amazon, Apple, Microsoft, and Google. This is not to say that your improved resume will not also captivate other tech companies and startups.
The theme of this article will not center around what you need to change about your future, but what you will need to do to market your past better. There are plenty of well-qualified data scientists out in the job market, and some may simply not apply to positions at these companies because they are overwhelmed, not believing in their work, and more importantly, themselves. With most things in life, confidence is key. Even more critical, are the skills that drive that confidence. However, in terms of your resume, you will need to articulate your skills in a way that is short, yet detailed. It is easy to assume employers will know what you have been working on when you refer to your past in general, but you will need to instead focus on the clarity of what you did at whatever company it was.
Below, I will give you five ways to improve your resume so you can appeal to top-tier tech companies.
Let us start with a non-technical improvement on your resume. While this point may seem negligible to your chances of attracting companies to your resume, it is actually quite the opposite. It could probably be said that most people click on an article or blog because of the main image, the title, or clicking on a YouTube video that has an enticing, yet mysterious thumbnail.
There are reasons why the visual representation of your work on a resume should not be ignored.
As cliche as it sounds, ‘do not fit in, stand out’. Imagine you are are a technical recruiter and you see the same bland, white and black ink resume a few hundred times per day. What is going to attract you first? It will be the aesthetic, the layout, and the uniqueness of your resume. Just like forming your own data science brand, you should focus on branding your resume. As an employer, you could think of hiring someone who has put work into a professional, yet creative resume, over someone else, as it will be their first impression of you.
Let’s look at mine.
As vulnerable and scary as this is to post my own resume online like this, I believe it will show you how you do not need to be a UX/UI designer to be creatively successful, but a little more creative than the next person is always nice — anyone can do this formatting, it just takes a bit of rearranging and organization (or you can use a premade template — but I prefer the homemade version — your homemade version). Okay, yes, this version of mine has been changed a little (specifically, the text of the most recent roles and their respective company names). However, the layout is the same as my original resume, as well as the heading, main section titles, dates, goal, and skills. Check it out below.
So what is so great about this resume? The easiest way to look at why — is that it stands out. It might not be the best or the most creative, but it is something I created that matches my personality. You want to land a job at a company that fits your personality. If a company gets upset that your resume is blue, then they might not be a match for you — or vice versa, and the opposite could be said. When I posted this resume on LinkedIn as well as applied to jobs on their sites, I felt nervous, vulnerable, and different. I asked a few friends what they thought about it before submitting and some loved it and some did not.
There is no perfect resume, but there is a better way to show your work.
I trusted my gut and wanted to show off my ingenuity. Just like my friends, some companies did not like my eclectic resume. However, some companies loved it, and pointed it out (most of those companies were the FAAMG companies), as well as other reputable big tech companies. To me, there was something to be said about that — these successful companies a lot of data scientists want to work at, admired creativity and personality — it paid off.
Controversially, I have two pages to my resume. I have heard the ‘one-page’ rule so many times, but have gotten maybe 1% of employers who reached out about the resume length. If you have got it, flaunt it. Show the employers the amount of incredibly hard work you have done to get to this point. If they are going to read one full page of your resume, they will most likely read 1.68 pages of your resume as well. If not, then they are not giving you a chance most likely anyway. If you believe two pages for your resume is needed, then do include two pages.
All in all, the aesthetic of your resume can be highly influential in the application process. The choice is, of course, ultimately up to you how you design your layout and look.
Here are the key tips on your resume’s aesthetic:
* find something unique about you and apply it to your resume* organize the layout in a way that lets the reader focus on each section separately* group your thoughts and work into sections: goal, experiences, skills, education, and extracurricular/awards. * give some breaks between sections so that the eyes can rest (just like how I made these points with a dark background)* tell a story with your layout: what do you want? what have you done? how did you get there?
I actually received some advice from a former Facebook employee that has stuck with me whenever I update my resume or let others know about what to put first on their resume. That section is the ‘Goal’ section. A good way to improve your resume is to include this goal section because it shows employers what you are looking for, almost answering the ‘what do you expect to do in five years’ question, interviewers often asked. It shows you are thinking ahead and have a plan. Additionally, it will let the recruiter and/or employer know if you are a match right away.
The goal section should include which role you are looking for, you can be specific here. So in mine, I put Data Scientist, but you could put ‘seeking a natural language processing role in data science’. Make sure to include why you are in data science, and what you want to do with it. You can also include some important links or usernames to common platforms used in data science. For example, I linked my GitHub and blog username. Surprisingly, a lot of employers pointed out that it was nice to see where they could access more information on me related to data science.
Here are the summaized key ways to improve on this goal section:
what role are you looking for?
what type of role do you want?
what will you do with that role in the business?
additional links or information on your data science knowledge
The meatiest part of your resume is the experience section. Of course, try to avoid paragraphs upon paragraphs. But, include longer sentences where necessary. If you are too short, it might not be that enticing of a project to someone who is viewing it for the first time — an extra few words will be fine.
I have always stuck to the same rule when writing out points in the experience section for each company on my resume. This rule includes three easy and simple main points. The first point is outlining the tools or programming languages you used. The second point is highlighting what you actually did. The third point, lastly, is articulating the results of what you did. So, altogether is, what did you use to complete this project, and what were its results? For example, ‘Utilizing Python in a Jupyter Notebook to create a Decision Tree classifier that helped to automate a manual classification process by 50%’. I truly think this method of explaining your experience in each major project is the best way to attract employers. It will show, in the quickest way possible, to the employers, possible coworkers, and stakeholders, your impact on a business problem. That is the foundation of data science; aiding the business by solving complex problems with unique tools.
The other information that you should make sure to include in your experience section are the company, title, and date. For example, ‘Data Scientist at Google from August 2018 to the current date’.
Here are the summarized key ways to improve your experience section:
what did you use?
what did you do?
what was the result?
Short and sweet. This section is a no-brainer. You will simply lay out all of the most common skills you have used for data science. Keep in mind that you may want to include simple skills like Microsoft Office, because, although it may seem implied to you, you should not assume recruiters already know this knowledge. Similarly, depending on the type of data scientist you want to be, there are certain skills that should be highlighted over others. For example, if you want to focus on business intelligence and product management data science, you will highlight SQL, Jira, and Confluence. On the contrary, if you want to appeal to more machine learning data science, highlight skills like GCP, Airflow, and Kubernetes. Additionally, if you want to stand out even a little more, make sure your skills look well-presented and have some pattern to them.
Here are the summarized key ways to improve your skills section:
skills applicable to the type of data science
include very specific
but also some very general skills
Like the skills section, the education section does not need to be long. Include your undergraduate degree and graduate degree university, along with their dates as main focuses like majors, minors, and concentration. If you are a beginning data scientist, you may want to include your GPA.
In addition to education, are the extracurriculars. This section is where you could also include your GitHub information or a similar project sharing site. You can also outline key projects that were outside of your professional, career data science experience.
If you do not have any formal, professional data science experience, then in the experience section outline those same outside data science projects instead.
Examples of these projects would be completing a tutorial, certificate, Bootcamp, or online course (like Kaggle data science courses).
Here are the summarized key ways to improve your education/extracurriculars section:
include undergraduate and graduate degree (if applicable)
keep it short and simple
highlight unique projects and certificates you have achieved
If you have reached it this far in the article, thank you. I want to give the most applicable and easy advice to data scientists so that they can find work at their dream company. I included improvements in the aesthetic, goal, experiences, skills, and education/extracurriculars sections of your resume. While I cannot guarantee landing a job, I do think you will improve your resume and hopefully, attract your dream job.
Once again, take my recommendations with a grain a salt. The goal of my article is to not only give you advice on these main sections of your resume, but to also give you inspiration and motivation on what new ideas you can come up with yourself. To summarize, you should focus on being yourself, highlighting the proudest accomplishments of your career (because you interviewers will pick the projects to interview you on, so know them well), and finding something unique and creative that can make your resume stand out.
I can attest that my resume screenshot is mine and has gotten attention from top-tier companies like Google, Apple, Facebook, and Microsoft. Keep in mind that there are other wonderful companies too. Just because a company is not one of these bigger tech companies, does not mean it is of any less value, and a different company could be rather more fun and beneficial as an experience. Ultimately, the next part of the process after appealing to companies is the interview. I have written several articles on data science and interview process and will link one now if you want to check it out — it refers to common similarities and differences amongst data science and data analytics interview processes[4]:
towardsdatascience.com
I hope you found my article interesting and useful. I wish you luck on your resume journey and data science career. Feel free to comment down below. Thank you for reading!
[1] Photo by Alex Haney on Unsplash, (2019)
[2] M.Przybyla, screenshot of resume, (2020)
[3] Photo by Paweł Czerwiński on Unsplash, (2018)
[4] M.Przybyla, Data Scientist vs Data Analyst Interview. Here’s the Difference., (2020) | [
{
"code": null,
"e": 258,
"s": 172,
"text": "IntroductionAestheticGoalExperiencesSkillsEducation/ExtracurricularsSummaryReferences"
},
{
"code": null,
"e": 271,
"s": 258,
"text": "Introduction"
},
{
"code": null,
"e": 281,
"s": 271,
"text": "Aesthetic"
},
{
"code": null,
"e": 286,
"s": 281,
"text": "Goal"
},
{
"code": null,
"e": 298,
"s": 286,
"text": "Experiences"
},
{
"code": null,
"e": 305,
"s": 298,
"text": "Skills"
},
{
"code": null,
"e": 332,
"s": 305,
"text": "Education/Extracurriculars"
},
{
"code": null,
"e": 340,
"s": 332,
"text": "Summary"
},
{
"code": null,
"e": 351,
"s": 340,
"text": "References"
},
{
"code": null,
"e": 696,
"s": 351,
"text": "Attracting top tech companies can not only be extremely difficult but intimidating as well. However, I am here to tell you that you can indeed do it, you can catch the eye of “FAAMG” — that is Facebook, Amazon, Apple, Microsoft, and Google. This is not to say that your improved resume will not also captivate other tech companies and startups."
},
{
"code": null,
"e": 1499,
"s": 696,
"text": "The theme of this article will not center around what you need to change about your future, but what you will need to do to market your past better. There are plenty of well-qualified data scientists out in the job market, and some may simply not apply to positions at these companies because they are overwhelmed, not believing in their work, and more importantly, themselves. With most things in life, confidence is key. Even more critical, are the skills that drive that confidence. However, in terms of your resume, you will need to articulate your skills in a way that is short, yet detailed. It is easy to assume employers will know what you have been working on when you refer to your past in general, but you will need to instead focus on the clarity of what you did at whatever company it was."
},
{
"code": null,
"e": 1601,
"s": 1499,
"text": "Below, I will give you five ways to improve your resume so you can appeal to top-tier tech companies."
},
{
"code": null,
"e": 1979,
"s": 1601,
"text": "Let us start with a non-technical improvement on your resume. While this point may seem negligible to your chances of attracting companies to your resume, it is actually quite the opposite. It could probably be said that most people click on an article or blog because of the main image, the title, or clicking on a YouTube video that has an enticing, yet mysterious thumbnail."
},
{
"code": null,
"e": 2075,
"s": 1979,
"text": "There are reasons why the visual representation of your work on a resume should not be ignored."
},
{
"code": null,
"e": 2624,
"s": 2075,
"text": "As cliche as it sounds, ‘do not fit in, stand out’. Imagine you are are a technical recruiter and you see the same bland, white and black ink resume a few hundred times per day. What is going to attract you first? It will be the aesthetic, the layout, and the uniqueness of your resume. Just like forming your own data science brand, you should focus on branding your resume. As an employer, you could think of hiring someone who has put work into a professional, yet creative resume, over someone else, as it will be their first impression of you."
},
{
"code": null,
"e": 2644,
"s": 2624,
"text": "Let’s look at mine."
},
{
"code": null,
"e": 3352,
"s": 2644,
"text": "As vulnerable and scary as this is to post my own resume online like this, I believe it will show you how you do not need to be a UX/UI designer to be creatively successful, but a little more creative than the next person is always nice — anyone can do this formatting, it just takes a bit of rearranging and organization (or you can use a premade template — but I prefer the homemade version — your homemade version). Okay, yes, this version of mine has been changed a little (specifically, the text of the most recent roles and their respective company names). However, the layout is the same as my original resume, as well as the heading, main section titles, dates, goal, and skills. Check it out below."
},
{
"code": null,
"e": 3982,
"s": 3352,
"text": "So what is so great about this resume? The easiest way to look at why — is that it stands out. It might not be the best or the most creative, but it is something I created that matches my personality. You want to land a job at a company that fits your personality. If a company gets upset that your resume is blue, then they might not be a match for you — or vice versa, and the opposite could be said. When I posted this resume on LinkedIn as well as applied to jobs on their sites, I felt nervous, vulnerable, and different. I asked a few friends what they thought about it before submitting and some loved it and some did not."
},
{
"code": null,
"e": 4055,
"s": 3982,
"text": "There is no perfect resume, but there is a better way to show your work."
},
{
"code": null,
"e": 4501,
"s": 4055,
"text": "I trusted my gut and wanted to show off my ingenuity. Just like my friends, some companies did not like my eclectic resume. However, some companies loved it, and pointed it out (most of those companies were the FAAMG companies), as well as other reputable big tech companies. To me, there was something to be said about that — these successful companies a lot of data scientists want to work at, admired creativity and personality — it paid off."
},
{
"code": null,
"e": 5060,
"s": 4501,
"text": "Controversially, I have two pages to my resume. I have heard the ‘one-page’ rule so many times, but have gotten maybe 1% of employers who reached out about the resume length. If you have got it, flaunt it. Show the employers the amount of incredibly hard work you have done to get to this point. If they are going to read one full page of your resume, they will most likely read 1.68 pages of your resume as well. If not, then they are not giving you a chance most likely anyway. If you believe two pages for your resume is needed, then do include two pages."
},
{
"code": null,
"e": 5239,
"s": 5060,
"text": "All in all, the aesthetic of your resume can be highly influential in the application process. The choice is, of course, ultimately up to you how you design your layout and look."
},
{
"code": null,
"e": 5289,
"s": 5239,
"text": "Here are the key tips on your resume’s aesthetic:"
},
{
"code": null,
"e": 5760,
"s": 5289,
"text": "* find something unique about you and apply it to your resume* organize the layout in a way that lets the reader focus on each section separately* group your thoughts and work into sections: goal, experiences, skills, education, and extracurricular/awards. * give some breaks between sections so that the eyes can rest (just like how I made these points with a dark background)* tell a story with your layout: what do you want? what have you done? how did you get there?"
},
{
"code": null,
"e": 6329,
"s": 5760,
"text": "I actually received some advice from a former Facebook employee that has stuck with me whenever I update my resume or let others know about what to put first on their resume. That section is the ‘Goal’ section. A good way to improve your resume is to include this goal section because it shows employers what you are looking for, almost answering the ‘what do you expect to do in five years’ question, interviewers often asked. It shows you are thinking ahead and have a plan. Additionally, it will let the recruiter and/or employer know if you are a match right away."
},
{
"code": null,
"e": 6905,
"s": 6329,
"text": "The goal section should include which role you are looking for, you can be specific here. So in mine, I put Data Scientist, but you could put ‘seeking a natural language processing role in data science’. Make sure to include why you are in data science, and what you want to do with it. You can also include some important links or usernames to common platforms used in data science. For example, I linked my GitHub and blog username. Surprisingly, a lot of employers pointed out that it was nice to see where they could access more information on me related to data science."
},
{
"code": null,
"e": 6970,
"s": 6905,
"text": "Here are the summaized key ways to improve on this goal section:"
},
{
"code": null,
"e": 7001,
"s": 6970,
"text": "what role are you looking for?"
},
{
"code": null,
"e": 7032,
"s": 7001,
"text": "what type of role do you want?"
},
{
"code": null,
"e": 7081,
"s": 7032,
"text": "what will you do with that role in the business?"
},
{
"code": null,
"e": 7144,
"s": 7081,
"text": "additional links or information on your data science knowledge"
},
{
"code": null,
"e": 7451,
"s": 7144,
"text": "The meatiest part of your resume is the experience section. Of course, try to avoid paragraphs upon paragraphs. But, include longer sentences where necessary. If you are too short, it might not be that enticing of a project to someone who is viewing it for the first time — an extra few words will be fine."
},
{
"code": null,
"e": 8425,
"s": 7451,
"text": "I have always stuck to the same rule when writing out points in the experience section for each company on my resume. This rule includes three easy and simple main points. The first point is outlining the tools or programming languages you used. The second point is highlighting what you actually did. The third point, lastly, is articulating the results of what you did. So, altogether is, what did you use to complete this project, and what were its results? For example, ‘Utilizing Python in a Jupyter Notebook to create a Decision Tree classifier that helped to automate a manual classification process by 50%’. I truly think this method of explaining your experience in each major project is the best way to attract employers. It will show, in the quickest way possible, to the employers, possible coworkers, and stakeholders, your impact on a business problem. That is the foundation of data science; aiding the business by solving complex problems with unique tools."
},
{
"code": null,
"e": 8623,
"s": 8425,
"text": "The other information that you should make sure to include in your experience section are the company, title, and date. For example, ‘Data Scientist at Google from August 2018 to the current date’."
},
{
"code": null,
"e": 8692,
"s": 8623,
"text": "Here are the summarized key ways to improve your experience section:"
},
{
"code": null,
"e": 8710,
"s": 8692,
"text": "what did you use?"
},
{
"code": null,
"e": 8727,
"s": 8710,
"text": "what did you do?"
},
{
"code": null,
"e": 8748,
"s": 8727,
"text": "what was the result?"
},
{
"code": null,
"e": 9604,
"s": 8748,
"text": "Short and sweet. This section is a no-brainer. You will simply lay out all of the most common skills you have used for data science. Keep in mind that you may want to include simple skills like Microsoft Office, because, although it may seem implied to you, you should not assume recruiters already know this knowledge. Similarly, depending on the type of data scientist you want to be, there are certain skills that should be highlighted over others. For example, if you want to focus on business intelligence and product management data science, you will highlight SQL, Jira, and Confluence. On the contrary, if you want to appeal to more machine learning data science, highlight skills like GCP, Airflow, and Kubernetes. Additionally, if you want to stand out even a little more, make sure your skills look well-presented and have some pattern to them."
},
{
"code": null,
"e": 9669,
"s": 9604,
"text": "Here are the summarized key ways to improve your skills section:"
},
{
"code": null,
"e": 9715,
"s": 9669,
"text": "skills applicable to the type of data science"
},
{
"code": null,
"e": 9737,
"s": 9715,
"text": "include very specific"
},
{
"code": null,
"e": 9771,
"s": 9737,
"text": "but also some very general skills"
},
{
"code": null,
"e": 10062,
"s": 9771,
"text": "Like the skills section, the education section does not need to be long. Include your undergraduate degree and graduate degree university, along with their dates as main focuses like majors, minors, and concentration. If you are a beginning data scientist, you may want to include your GPA."
},
{
"code": null,
"e": 10324,
"s": 10062,
"text": "In addition to education, are the extracurriculars. This section is where you could also include your GitHub information or a similar project sharing site. You can also outline key projects that were outside of your professional, career data science experience."
},
{
"code": null,
"e": 10482,
"s": 10324,
"text": "If you do not have any formal, professional data science experience, then in the experience section outline those same outside data science projects instead."
},
{
"code": null,
"e": 10617,
"s": 10482,
"text": "Examples of these projects would be completing a tutorial, certificate, Bootcamp, or online course (like Kaggle data science courses)."
},
{
"code": null,
"e": 10702,
"s": 10617,
"text": "Here are the summarized key ways to improve your education/extracurriculars section:"
},
{
"code": null,
"e": 10760,
"s": 10702,
"text": "include undergraduate and graduate degree (if applicable)"
},
{
"code": null,
"e": 10785,
"s": 10760,
"text": "keep it short and simple"
},
{
"code": null,
"e": 10846,
"s": 10785,
"text": "highlight unique projects and certificates you have achieved"
},
{
"code": null,
"e": 11270,
"s": 10846,
"text": "If you have reached it this far in the article, thank you. I want to give the most applicable and easy advice to data scientists so that they can find work at their dream company. I included improvements in the aesthetic, goal, experiences, skills, and education/extracurriculars sections of your resume. While I cannot guarantee landing a job, I do think you will improve your resume and hopefully, attract your dream job."
},
{
"code": null,
"e": 11793,
"s": 11270,
"text": "Once again, take my recommendations with a grain a salt. The goal of my article is to not only give you advice on these main sections of your resume, but to also give you inspiration and motivation on what new ideas you can come up with yourself. To summarize, you should focus on being yourself, highlighting the proudest accomplishments of your career (because you interviewers will pick the projects to interview you on, so know them well), and finding something unique and creative that can make your resume stand out."
},
{
"code": null,
"e": 12503,
"s": 11793,
"text": "I can attest that my resume screenshot is mine and has gotten attention from top-tier companies like Google, Apple, Facebook, and Microsoft. Keep in mind that there are other wonderful companies too. Just because a company is not one of these bigger tech companies, does not mean it is of any less value, and a different company could be rather more fun and beneficial as an experience. Ultimately, the next part of the process after appealing to companies is the interview. I have written several articles on data science and interview process and will link one now if you want to check it out — it refers to common similarities and differences amongst data science and data analytics interview processes[4]:"
},
{
"code": null,
"e": 12526,
"s": 12503,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12698,
"s": 12526,
"text": "I hope you found my article interesting and useful. I wish you luck on your resume journey and data science career. Feel free to comment down below. Thank you for reading!"
},
{
"code": null,
"e": 12742,
"s": 12698,
"text": "[1] Photo by Alex Haney on Unsplash, (2019)"
},
{
"code": null,
"e": 12787,
"s": 12742,
"text": "[2] M.Przybyla, screenshot of resume, (2020)"
},
{
"code": null,
"e": 12838,
"s": 12787,
"text": "[3] Photo by Paweł Czerwiński on Unsplash, (2018)"
}
]
|
Python 3 - Number exp() Method | The exp() method returns exponential of x: ex.
Following is the syntax for the exp() method −
import math
math.exp( x )
Note − This function is not accessible directly. Therefore, we need to import the math module and then we need to call this function using the math static object.
x − This is a numeric expression.
This method returns exponential of x: ex.
The following example shows the usage of exp() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.exp(-45.17) : ", math.exp(-45.17))
print ("math.exp(100.12) : ", math.exp(100.12))
print ("math.exp(100.72) : ", math.exp(100.72))
print ("math.exp(math.pi) : ", math.exp(math.pi))
When we run the above program, it produces the following result −
math.exp(-45.17) : 2.4150062132629406e-20
math.exp(100.12) : 3.0308436140742566e+43
math.exp(100.72) : 5.522557130248187e+43
math.exp(math.pi) : 23.140692632779267
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2387,
"s": 2340,
"text": "The exp() method returns exponential of x: ex."
},
{
"code": null,
"e": 2434,
"s": 2387,
"text": "Following is the syntax for the exp() method −"
},
{
"code": null,
"e": 2462,
"s": 2434,
"text": "import math\n\nmath.exp( x )\n"
},
{
"code": null,
"e": 2625,
"s": 2462,
"text": "Note − This function is not accessible directly. Therefore, we need to import the math module and then we need to call this function using the math static object."
},
{
"code": null,
"e": 2659,
"s": 2625,
"text": "x − This is a numeric expression."
},
{
"code": null,
"e": 2701,
"s": 2659,
"text": "This method returns exponential of x: ex."
},
{
"code": null,
"e": 2756,
"s": 2701,
"text": "The following example shows the usage of exp() method."
},
{
"code": null,
"e": 3015,
"s": 2756,
"text": "#!/usr/bin/python3\nimport math # This will import math module\n\nprint (\"math.exp(-45.17) : \", math.exp(-45.17))\nprint (\"math.exp(100.12) : \", math.exp(100.12))\nprint (\"math.exp(100.72) : \", math.exp(100.72))\nprint (\"math.exp(math.pi) : \", math.exp(math.pi))"
},
{
"code": null,
"e": 3081,
"s": 3015,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3250,
"s": 3081,
"text": "math.exp(-45.17) : 2.4150062132629406e-20\nmath.exp(100.12) : 3.0308436140742566e+43\nmath.exp(100.72) : 5.522557130248187e+43\nmath.exp(math.pi) : 23.140692632779267\n"
},
{
"code": null,
"e": 3287,
"s": 3250,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3303,
"s": 3287,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3336,
"s": 3303,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3355,
"s": 3336,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3390,
"s": 3355,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3412,
"s": 3390,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3446,
"s": 3412,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3474,
"s": 3446,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3509,
"s": 3474,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3523,
"s": 3509,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3556,
"s": 3523,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3573,
"s": 3556,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3580,
"s": 3573,
"text": " Print"
},
{
"code": null,
"e": 3591,
"s": 3580,
"text": " Add Notes"
}
]
|
Python Program to Detect the Cycle in a Linked List | When it is required to detect a cycle in a linked list, a method to add elements to the linked list, and a method to get the element in the linked list are defined. Another method is defined that checks if the head and rear values are same or not. Based on this result, cycles are detected.
Below is a demonstration for the same −
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList_structure:
def __init__(self):
self.head = None
self.last_node = None
def add_vals(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def get_node_val(self, index):
curr = self.head
for i in range(index):
curr = curr.next
if curr is None:
return None
return curr
def check_cycle(my_list):
slow_val = my_list.head
fast_val = my_list.head
while (fast_val != None and fast_val.next != None):
slow_val = slow_val.next
fast_val = fast_val.next.next
if slow_val == fast_val:
return True
return False
my_linked_list = LinkedList_structure()
my_list = input('Enter the elements in the linked list ').split()
for elem in my_list:
my_linked_list.add_vals(int(elem))
my_len = len(my_list)
if my_len != 0:
vals = '0-' + str(my_len - 1)
last_ptr = input('Enter the index [' + vals + '] of the node' ' at which the last node has to point'' (Enter nothing to point to None): ').strip()
if last_ptr == '':
last_ptr = None
else:
last_ptr = my_linked_list.get_node_val(int(last_ptr))
my_linked_list.last_node.next = last_ptr
if check_cycle(my_linked_list):
print("The linked list has a cycle")
else:
print("The linked list doesn't have a cycle")
Enter the elements in the linked list 56 78 90 12 4
Enter the index [0-4] of the node at which the last node has to point (Enter nothing to point to
None):
The linked list doesn't have a cycle
The ‘Node’ class is created.
The ‘Node’ class is created.
Another ‘LinkedList_structure’ class with required attributes is created.
Another ‘LinkedList_structure’ class with required attributes is created.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.
It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’.
A method named ‘add_vals’ is defined, that helps add a value to the stack.
A method named ‘add_vals’ is defined, that helps add a value to the stack.
Another method named ‘get_node_val’ is defined, that helps get the value of the current node in the linked list.
Another method named ‘get_node_val’ is defined, that helps get the value of the current node in the linked list.
Another method named ‘check_cycle’ is defined, that helps find if the head and rear are same, which means this would be a cycle.
Another method named ‘check_cycle’ is defined, that helps find if the head and rear are same, which means this would be a cycle.
It returns True or False depending on the presence or absence of cycle.
It returns True or False depending on the presence or absence of cycle.
An instance of the ‘LinkedList_structure’ is created.
An instance of the ‘LinkedList_structure’ is created.
Elements are added to the linked list.
Elements are added to the linked list.
The ‘check_cycle’ method is called on this linked list.
The ‘check_cycle’ method is called on this linked list.
The output is displayed on the console.
The output is displayed on the console. | [
{
"code": null,
"e": 1353,
"s": 1062,
"text": "When it is required to detect a cycle in a linked list, a method to add elements to the linked list, and a method to get the element in the linked list are defined. Another method is defined that checks if the head and rear values are same or not. Based on this result, cycles are detected."
},
{
"code": null,
"e": 1393,
"s": 1353,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 2926,
"s": 1393,
"text": "class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList_structure:\n def __init__(self):\n self.head = None\n self.last_node = None\n\n def add_vals(self, data):\n if self.last_node is None:\n self.head = Node(data)\n self.last_node = self.head\n else:\n self.last_node.next = Node(data)\n self.last_node = self.last_node.next\n\ndef get_node_val(self, index):\n curr = self.head\n for i in range(index):\n curr = curr.next\n if curr is None:\n return None\n return curr\n\ndef check_cycle(my_list):\n slow_val = my_list.head\n fast_val = my_list.head\n while (fast_val != None and fast_val.next != None):\n slow_val = slow_val.next\n fast_val = fast_val.next.next\n if slow_val == fast_val:\n return True\n return False\n\nmy_linked_list = LinkedList_structure()\nmy_list = input('Enter the elements in the linked list ').split()\n for elem in my_list:\nmy_linked_list.add_vals(int(elem))\nmy_len = len(my_list)\nif my_len != 0:\n vals = '0-' + str(my_len - 1)\n last_ptr = input('Enter the index [' + vals + '] of the node' ' at which the last node has to point'' (Enter nothing to point to None): ').strip()\n if last_ptr == '':\n last_ptr = None\n else:\n last_ptr = my_linked_list.get_node_val(int(last_ptr))\n my_linked_list.last_node.next = last_ptr\n\nif check_cycle(my_linked_list):\n print(\"The linked list has a cycle\")\nelse:\n print(\"The linked list doesn't have a cycle\")"
},
{
"code": null,
"e": 3119,
"s": 2926,
"text": "Enter the elements in the linked list 56 78 90 12 4\nEnter the index [0-4] of the node at which the last node has to point (Enter nothing to point to\nNone):\nThe linked list doesn't have a cycle"
},
{
"code": null,
"e": 3148,
"s": 3119,
"text": "The ‘Node’ class is created."
},
{
"code": null,
"e": 3177,
"s": 3148,
"text": "The ‘Node’ class is created."
},
{
"code": null,
"e": 3251,
"s": 3177,
"text": "Another ‘LinkedList_structure’ class with required attributes is created."
},
{
"code": null,
"e": 3325,
"s": 3251,
"text": "Another ‘LinkedList_structure’ class with required attributes is created."
},
{
"code": null,
"e": 3423,
"s": 3325,
"text": "It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’."
},
{
"code": null,
"e": 3521,
"s": 3423,
"text": "It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’."
},
{
"code": null,
"e": 3596,
"s": 3521,
"text": "A method named ‘add_vals’ is defined, that helps add a value to the stack."
},
{
"code": null,
"e": 3671,
"s": 3596,
"text": "A method named ‘add_vals’ is defined, that helps add a value to the stack."
},
{
"code": null,
"e": 3784,
"s": 3671,
"text": "Another method named ‘get_node_val’ is defined, that helps get the value of the current node in the linked list."
},
{
"code": null,
"e": 3897,
"s": 3784,
"text": "Another method named ‘get_node_val’ is defined, that helps get the value of the current node in the linked list."
},
{
"code": null,
"e": 4026,
"s": 3897,
"text": "Another method named ‘check_cycle’ is defined, that helps find if the head and rear are same, which means this would be a cycle."
},
{
"code": null,
"e": 4155,
"s": 4026,
"text": "Another method named ‘check_cycle’ is defined, that helps find if the head and rear are same, which means this would be a cycle."
},
{
"code": null,
"e": 4227,
"s": 4155,
"text": "It returns True or False depending on the presence or absence of cycle."
},
{
"code": null,
"e": 4299,
"s": 4227,
"text": "It returns True or False depending on the presence or absence of cycle."
},
{
"code": null,
"e": 4353,
"s": 4299,
"text": "An instance of the ‘LinkedList_structure’ is created."
},
{
"code": null,
"e": 4407,
"s": 4353,
"text": "An instance of the ‘LinkedList_structure’ is created."
},
{
"code": null,
"e": 4446,
"s": 4407,
"text": "Elements are added to the linked list."
},
{
"code": null,
"e": 4485,
"s": 4446,
"text": "Elements are added to the linked list."
},
{
"code": null,
"e": 4541,
"s": 4485,
"text": "The ‘check_cycle’ method is called on this linked list."
},
{
"code": null,
"e": 4597,
"s": 4541,
"text": "The ‘check_cycle’ method is called on this linked list."
},
{
"code": null,
"e": 4637,
"s": 4597,
"text": "The output is displayed on the console."
},
{
"code": null,
"e": 4677,
"s": 4637,
"text": "The output is displayed on the console."
}
]
|
Geocoding Singapore Coordinates: OneMap API | by Shawn Tham | Towards Data Science | Geocoding with Google API is the widely known way. However, it costs money once you finish your free credits. As a data analyst who does geospatial visualisation regularly with Tableau and Python, coordinates are very essential for plotting. In this article, I will demonstrate how to geocode Singapore coordinates using a free and accurate geocoding API developed by the Singapore Land Authority (SLA).
Step 1: Importing the relevant packages
import pandas as pdimport requests
Step 2: Read the dataset with pandas and examine it
df = pd.read_csv(r"C:\Users\shawn\Downloads\hdb-property-information\hdb-property-information.csv")df.head()
The dataset I am using is from Data.gov.sg and it contains the location of existing Housing Development Board (HDB) blocks, highest floor level, year of completion, type of building and number of HDB flats (breakdown by flat type) per block etc. I start by reading the data with pandas and taking a look at the first 5 rows to see which columns I can use. For demonstration purposes and making it as realistic as possible, I will not clean the data to show how you can still use OneMap API.
Step 3: Creating an address list that can be inputted into the API
df['Address'] = df['blk_no'] + " " + df['street']addresslist = list(df['Address'])
As there isn’t an address column, I concatenate the columns which contains the block number and the street name and save it into a new column. Geocoding requires some form of address so this step is necessary to proceed on. Next, I convert the newly created column into a list which can then be run through OneMap API.
Step 4: Writing a function for geocoding
def getcoordinates(address): req = requests.get('https://developers.onemap.sg/commonapi/search?searchVal='+address+'&returnGeom=Y&getAddrDetails=Y&pageNum=1') resultsdict = eval(req.text) if len(resultsdict['results'])>0: return resultsdict['results'][0]['LATITUDE'], resultsdict['results'][0]['LONGITUDE'] else: pass
I start by defining the function as getcoordinates . Using the requests module, I will use it to search information on OneMap API. The address will have to be inserted as a string into the the given URL in order to retrieve information. Next, I use the eval() function to evaluate it as a Python expression. As not all addresses will have coordinates, I use an if else statement to only take those with results.
Step 5: Write a for loop with conditions
coordinateslist= []count = 0failed_count = 0for address in addresslist: try: if len(getcoordinates(address))>0: count = count + 1 print('Extracting',count,'out of',len(addresslist),'addresses') coordinateslist.append(getcoordinates(address)) except: count = count + 1 failed_count = failed_count + 1 print('Failed to extract',count,'out of',len(addresslist),'addresses') coordinateslist.append(None)print('Total Number of Addresses With No Coordinates',failed_count)
Now, I start by creating an empty list to append the extracted coordinates. Next, I put a count function. By doing so, I am able to know where the progress is currently at and the total number of addresses that doesn’t have coordinates. This will allow me to keep track easily. Next, I input a try else condition which will allow the for loop to run continuously even if one of the addresses fail to retrieve any coordinates from the API. This is particularly useful to ensure the loop runs smoothly, especially for dirty datasets that are not able to generate any results from the API. In addition, you are still able to attain the bulk of coordinates. You could then filter for the remaining dirty addresses and clean those, making your life easier since you have less to clean!
Step 6: Join the attained coordinates back to the original DataFrame
df_coordinates = pd.DataFrame(coordinateslist)df_combined = df.join(df_coordinates)df_combined = df_combined .rename(columns={0:'Latitude', 1:'Longitude'})
Lastly, I convert the list of coordinates into a DataFrame and join it to the original dataframe. As the index is still the same, it will join perfectly. I also renamed the column names as Latitude and Longitude to better reflect the data type in my dataframe.
Summary
Step 1: Importing the relevant packages
Step 2: Read the dataset with Pandas and examine it
Step 3: Creating an address list that can be inputted into the API
Step 4: Writing a function for geocoding
Step 5: Write a for loop with conditions
Step 6: Join the attained coordinates back to the original DataFrame
I hope you enjoy my article and that it convinced you to give this OneMap API a try! There are many great initiatives by the Singapore government to make datasets public and open. Thus, it is useful to explore and see what you can make out of it for data analytics projects. You can check out the full code on my Github here. | [
{
"code": null,
"e": 576,
"s": 172,
"text": "Geocoding with Google API is the widely known way. However, it costs money once you finish your free credits. As a data analyst who does geospatial visualisation regularly with Tableau and Python, coordinates are very essential for plotting. In this article, I will demonstrate how to geocode Singapore coordinates using a free and accurate geocoding API developed by the Singapore Land Authority (SLA)."
},
{
"code": null,
"e": 616,
"s": 576,
"text": "Step 1: Importing the relevant packages"
},
{
"code": null,
"e": 651,
"s": 616,
"text": "import pandas as pdimport requests"
},
{
"code": null,
"e": 703,
"s": 651,
"text": "Step 2: Read the dataset with pandas and examine it"
},
{
"code": null,
"e": 812,
"s": 703,
"text": "df = pd.read_csv(r\"C:\\Users\\shawn\\Downloads\\hdb-property-information\\hdb-property-information.csv\")df.head()"
},
{
"code": null,
"e": 1303,
"s": 812,
"text": "The dataset I am using is from Data.gov.sg and it contains the location of existing Housing Development Board (HDB) blocks, highest floor level, year of completion, type of building and number of HDB flats (breakdown by flat type) per block etc. I start by reading the data with pandas and taking a look at the first 5 rows to see which columns I can use. For demonstration purposes and making it as realistic as possible, I will not clean the data to show how you can still use OneMap API."
},
{
"code": null,
"e": 1370,
"s": 1303,
"text": "Step 3: Creating an address list that can be inputted into the API"
},
{
"code": null,
"e": 1453,
"s": 1370,
"text": "df['Address'] = df['blk_no'] + \" \" + df['street']addresslist = list(df['Address'])"
},
{
"code": null,
"e": 1772,
"s": 1453,
"text": "As there isn’t an address column, I concatenate the columns which contains the block number and the street name and save it into a new column. Geocoding requires some form of address so this step is necessary to proceed on. Next, I convert the newly created column into a list which can then be run through OneMap API."
},
{
"code": null,
"e": 1813,
"s": 1772,
"text": "Step 4: Writing a function for geocoding"
},
{
"code": null,
"e": 2157,
"s": 1813,
"text": "def getcoordinates(address): req = requests.get('https://developers.onemap.sg/commonapi/search?searchVal='+address+'&returnGeom=Y&getAddrDetails=Y&pageNum=1') resultsdict = eval(req.text) if len(resultsdict['results'])>0: return resultsdict['results'][0]['LATITUDE'], resultsdict['results'][0]['LONGITUDE'] else: pass"
},
{
"code": null,
"e": 2569,
"s": 2157,
"text": "I start by defining the function as getcoordinates . Using the requests module, I will use it to search information on OneMap API. The address will have to be inserted as a string into the the given URL in order to retrieve information. Next, I use the eval() function to evaluate it as a Python expression. As not all addresses will have coordinates, I use an if else statement to only take those with results."
},
{
"code": null,
"e": 2610,
"s": 2569,
"text": "Step 5: Write a for loop with conditions"
},
{
"code": null,
"e": 3162,
"s": 2610,
"text": "coordinateslist= []count = 0failed_count = 0for address in addresslist: try: if len(getcoordinates(address))>0: count = count + 1 print('Extracting',count,'out of',len(addresslist),'addresses') coordinateslist.append(getcoordinates(address)) except: count = count + 1 failed_count = failed_count + 1 print('Failed to extract',count,'out of',len(addresslist),'addresses') coordinateslist.append(None)print('Total Number of Addresses With No Coordinates',failed_count)"
},
{
"code": null,
"e": 3943,
"s": 3162,
"text": "Now, I start by creating an empty list to append the extracted coordinates. Next, I put a count function. By doing so, I am able to know where the progress is currently at and the total number of addresses that doesn’t have coordinates. This will allow me to keep track easily. Next, I input a try else condition which will allow the for loop to run continuously even if one of the addresses fail to retrieve any coordinates from the API. This is particularly useful to ensure the loop runs smoothly, especially for dirty datasets that are not able to generate any results from the API. In addition, you are still able to attain the bulk of coordinates. You could then filter for the remaining dirty addresses and clean those, making your life easier since you have less to clean!"
},
{
"code": null,
"e": 4012,
"s": 3943,
"text": "Step 6: Join the attained coordinates back to the original DataFrame"
},
{
"code": null,
"e": 4169,
"s": 4012,
"text": "df_coordinates = pd.DataFrame(coordinateslist)df_combined = df.join(df_coordinates)df_combined = df_combined .rename(columns={0:'Latitude', 1:'Longitude'})"
},
{
"code": null,
"e": 4430,
"s": 4169,
"text": "Lastly, I convert the list of coordinates into a DataFrame and join it to the original dataframe. As the index is still the same, it will join perfectly. I also renamed the column names as Latitude and Longitude to better reflect the data type in my dataframe."
},
{
"code": null,
"e": 4438,
"s": 4430,
"text": "Summary"
},
{
"code": null,
"e": 4478,
"s": 4438,
"text": "Step 1: Importing the relevant packages"
},
{
"code": null,
"e": 4530,
"s": 4478,
"text": "Step 2: Read the dataset with Pandas and examine it"
},
{
"code": null,
"e": 4597,
"s": 4530,
"text": "Step 3: Creating an address list that can be inputted into the API"
},
{
"code": null,
"e": 4638,
"s": 4597,
"text": "Step 4: Writing a function for geocoding"
},
{
"code": null,
"e": 4679,
"s": 4638,
"text": "Step 5: Write a for loop with conditions"
},
{
"code": null,
"e": 4748,
"s": 4679,
"text": "Step 6: Join the attained coordinates back to the original DataFrame"
}
]
|
DateTime.ToFileTimeUtc() Method in C# | The DateTime.ToFileTimeUtc() method in C# is used to convert the value of the current DateTime object to a Windows file time.
Following is the syntax −
public long ToFileTimeUtc ();
Let us now see an example to implement the DateTime.ToFileTimeUtc() method −
using System;
public class Demo {
public static void Main() {
DateTime d = new DateTime(2019, 05, 10, 6, 10, 25);
Console.WriteLine("Date = {0}", d);
long res = d.ToFileTimeUtc();
Console.WriteLine("Windows file time (Utc) = {0}", res);
}
}
This will produce the following output −
Date = 5/10/2019 6:10:25 AM
Windows file time (Utc) = 132019422250000000
Let us now see another example to implement the DateTime.ToFileTimeUtc() method −
using System;
public class Demo {
public static void Main() {
DateTime d = DateTime.Now;
Console.WriteLine("Date = {0}", d);
long res = d.ToFileTimeUtc();
Console.WriteLine("Windows file time (Utc) = {0}", res);
}
}
This will produce the following output −
Date = 10/16/2019 8:25:58 AM
Windows file time (Utc) = 132156879583999032 | [
{
"code": null,
"e": 1188,
"s": 1062,
"text": "The DateTime.ToFileTimeUtc() method in C# is used to convert the value of the current DateTime object to a Windows file time."
},
{
"code": null,
"e": 1214,
"s": 1188,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1244,
"s": 1214,
"text": "public long ToFileTimeUtc ();"
},
{
"code": null,
"e": 1321,
"s": 1244,
"text": "Let us now see an example to implement the DateTime.ToFileTimeUtc() method −"
},
{
"code": null,
"e": 1592,
"s": 1321,
"text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 05, 10, 6, 10, 25);\n Console.WriteLine(\"Date = {0}\", d);\n long res = d.ToFileTimeUtc();\n Console.WriteLine(\"Windows file time (Utc) = {0}\", res);\n }\n}"
},
{
"code": null,
"e": 1633,
"s": 1592,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1706,
"s": 1633,
"text": "Date = 5/10/2019 6:10:25 AM\nWindows file time (Utc) = 132019422250000000"
},
{
"code": null,
"e": 1788,
"s": 1706,
"text": "Let us now see another example to implement the DateTime.ToFileTimeUtc() method −"
},
{
"code": null,
"e": 2034,
"s": 1788,
"text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = DateTime.Now;\n Console.WriteLine(\"Date = {0}\", d);\n long res = d.ToFileTimeUtc();\n Console.WriteLine(\"Windows file time (Utc) = {0}\", res);\n }\n}"
},
{
"code": null,
"e": 2075,
"s": 2034,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2149,
"s": 2075,
"text": "Date = 10/16/2019 8:25:58 AM\nWindows file time (Utc) = 132156879583999032"
}
]
|
How to save a Python Dictionary to a CSV File? - GeeksforGeeks | 01 Jul, 2020
Prerequisites: Working with csv files in Python
CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same.
Import csv moduleimport csvCreating list of field namesfield_names= ['No', 'Company', 'Car Model']Creating a list of python dictionariescars = [{‘No’: 1, ‘Company’: ‘Ferrari’, ‘Car Model’: ‘488 GTB’},{‘No’: 2, ‘Company’: ‘Porsche’, ‘Car Model’: ‘918 Spyder’},{‘No’: 3, ‘Company’: ‘Bugatti’, ‘Car Model’: ‘La Voiture Noire’},{‘No’: 4, ‘Company’: ‘Rolls Royce’, ‘Car Model’: ‘Phantom’},{‘No’: 5, ‘Company’: ‘BMW’, ‘Car Model’: ‘BMW X7’},]Writing content of dictionaries to CSV filewith open('Names.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=field_names)
writer.writeheader()
writer.writerows(cars)Syntax:DictWriter( (filename), fieldnames = [list of field names] )In the above code snippet writer is an instance of csv.DictWriter class and uses two of its following methods:DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV filecsvwriter.writerows() method is used to write rows of data into the specified file.Note: To write a single dictionary in CSV file use writerow() method
Import csv moduleimport csv
import csv
Creating list of field namesfield_names= ['No', 'Company', 'Car Model']
field_names= ['No', 'Company', 'Car Model']
Creating a list of python dictionariescars = [{‘No’: 1, ‘Company’: ‘Ferrari’, ‘Car Model’: ‘488 GTB’},{‘No’: 2, ‘Company’: ‘Porsche’, ‘Car Model’: ‘918 Spyder’},{‘No’: 3, ‘Company’: ‘Bugatti’, ‘Car Model’: ‘La Voiture Noire’},{‘No’: 4, ‘Company’: ‘Rolls Royce’, ‘Car Model’: ‘Phantom’},{‘No’: 5, ‘Company’: ‘BMW’, ‘Car Model’: ‘BMW X7’},]
cars = [{‘No’: 1, ‘Company’: ‘Ferrari’, ‘Car Model’: ‘488 GTB’},{‘No’: 2, ‘Company’: ‘Porsche’, ‘Car Model’: ‘918 Spyder’},{‘No’: 3, ‘Company’: ‘Bugatti’, ‘Car Model’: ‘La Voiture Noire’},{‘No’: 4, ‘Company’: ‘Rolls Royce’, ‘Car Model’: ‘Phantom’},{‘No’: 5, ‘Company’: ‘BMW’, ‘Car Model’: ‘BMW X7’},]
Writing content of dictionaries to CSV filewith open('Names.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=field_names)
writer.writeheader()
writer.writerows(cars)Syntax:DictWriter( (filename), fieldnames = [list of field names] )In the above code snippet writer is an instance of csv.DictWriter class and uses two of its following methods:DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV filecsvwriter.writerows() method is used to write rows of data into the specified file.Note: To write a single dictionary in CSV file use writerow() method
with open('Names.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=field_names)
writer.writeheader()
writer.writerows(cars)
Syntax:
DictWriter( (filename), fieldnames = [list of field names] )
In the above code snippet writer is an instance of csv.DictWriter class and uses two of its following methods:
DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV filecsvwriter.writerows() method is used to write rows of data into the specified file.
DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV file
csvwriter.writerows() method is used to write rows of data into the specified file.
Note: To write a single dictionary in CSV file use writerow() method
Complete code to write python dictionaries in CSV file
import csv field_names = ['No', 'Company', 'Car Model'] cars = [{'No': 1, 'Company': 'Ferrari', 'Car Model': '488 GTB'},{'No': 2, 'Company': 'Porsche', 'Car Model': '918 Spyder'},{'No': 3, 'Company': 'Bugatti', 'Car Model': 'La Voiture Noire'},{'No': 4, 'Company': 'Rolls Royce', 'Car Model': 'Phantom'},{'No': 5, 'Company': 'BMW', 'Car Model': 'BMW X7'},] with open('Names.csv', 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames = field_names) writer.writeheader() writer.writerows(cars)
Output:
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 24774,
"s": 24746,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 24822,
"s": 24774,
"text": "Prerequisites: Working with csv files in Python"
},
{
"code": null,
"e": 25115,
"s": 24822,
"text": "CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same."
},
{
"code": null,
"e": 26177,
"s": 25115,
"text": "Import csv moduleimport csvCreating list of field namesfield_names= ['No', 'Company', 'Car Model']Creating a list of python dictionariescars = [{‘No’: 1, ‘Company’: ‘Ferrari’, ‘Car Model’: ‘488 GTB’},{‘No’: 2, ‘Company’: ‘Porsche’, ‘Car Model’: ‘918 Spyder’},{‘No’: 3, ‘Company’: ‘Bugatti’, ‘Car Model’: ‘La Voiture Noire’},{‘No’: 4, ‘Company’: ‘Rolls Royce’, ‘Car Model’: ‘Phantom’},{‘No’: 5, ‘Company’: ‘BMW’, ‘Car Model’: ‘BMW X7’},]Writing content of dictionaries to CSV filewith open('Names.csv', 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=field_names)\n writer.writeheader()\n writer.writerows(cars)Syntax:DictWriter( (filename), fieldnames = [list of field names] )In the above code snippet writer is an instance of csv.DictWriter class and uses two of its following methods:DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV filecsvwriter.writerows() method is used to write rows of data into the specified file.Note: To write a single dictionary in CSV file use writerow() method"
},
{
"code": null,
"e": 26205,
"s": 26177,
"text": "Import csv moduleimport csv"
},
{
"code": null,
"e": 26216,
"s": 26205,
"text": "import csv"
},
{
"code": null,
"e": 26288,
"s": 26216,
"text": "Creating list of field namesfield_names= ['No', 'Company', 'Car Model']"
},
{
"code": null,
"e": 26332,
"s": 26288,
"text": "field_names= ['No', 'Company', 'Car Model']"
},
{
"code": null,
"e": 26671,
"s": 26332,
"text": "Creating a list of python dictionariescars = [{‘No’: 1, ‘Company’: ‘Ferrari’, ‘Car Model’: ‘488 GTB’},{‘No’: 2, ‘Company’: ‘Porsche’, ‘Car Model’: ‘918 Spyder’},{‘No’: 3, ‘Company’: ‘Bugatti’, ‘Car Model’: ‘La Voiture Noire’},{‘No’: 4, ‘Company’: ‘Rolls Royce’, ‘Car Model’: ‘Phantom’},{‘No’: 5, ‘Company’: ‘BMW’, ‘Car Model’: ‘BMW X7’},]"
},
{
"code": null,
"e": 26972,
"s": 26671,
"text": "cars = [{‘No’: 1, ‘Company’: ‘Ferrari’, ‘Car Model’: ‘488 GTB’},{‘No’: 2, ‘Company’: ‘Porsche’, ‘Car Model’: ‘918 Spyder’},{‘No’: 3, ‘Company’: ‘Bugatti’, ‘Car Model’: ‘La Voiture Noire’},{‘No’: 4, ‘Company’: ‘Rolls Royce’, ‘Car Model’: ‘Phantom’},{‘No’: 5, ‘Company’: ‘BMW’, ‘Car Model’: ‘BMW X7’},]"
},
{
"code": null,
"e": 27598,
"s": 26972,
"text": "Writing content of dictionaries to CSV filewith open('Names.csv', 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=field_names)\n writer.writeheader()\n writer.writerows(cars)Syntax:DictWriter( (filename), fieldnames = [list of field names] )In the above code snippet writer is an instance of csv.DictWriter class and uses two of its following methods:DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV filecsvwriter.writerows() method is used to write rows of data into the specified file.Note: To write a single dictionary in CSV file use writerow() method"
},
{
"code": null,
"e": 27751,
"s": 27598,
"text": "with open('Names.csv', 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=field_names)\n writer.writeheader()\n writer.writerows(cars)"
},
{
"code": null,
"e": 27759,
"s": 27751,
"text": "Syntax:"
},
{
"code": null,
"e": 27820,
"s": 27759,
"text": "DictWriter( (filename), fieldnames = [list of field names] )"
},
{
"code": null,
"e": 27931,
"s": 27820,
"text": "In the above code snippet writer is an instance of csv.DictWriter class and uses two of its following methods:"
},
{
"code": null,
"e": 28117,
"s": 27931,
"text": "DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV filecsvwriter.writerows() method is used to write rows of data into the specified file."
},
{
"code": null,
"e": 28220,
"s": 28117,
"text": "DictWriter.writeheader() is used to write a row of column headings / field names to the given CSV file"
},
{
"code": null,
"e": 28304,
"s": 28220,
"text": "csvwriter.writerows() method is used to write rows of data into the specified file."
},
{
"code": null,
"e": 28373,
"s": 28304,
"text": "Note: To write a single dictionary in CSV file use writerow() method"
},
{
"code": null,
"e": 28428,
"s": 28373,
"text": "Complete code to write python dictionaries in CSV file"
},
{
"code": "import csv field_names = ['No', 'Company', 'Car Model'] cars = [{'No': 1, 'Company': 'Ferrari', 'Car Model': '488 GTB'},{'No': 2, 'Company': 'Porsche', 'Car Model': '918 Spyder'},{'No': 3, 'Company': 'Bugatti', 'Car Model': 'La Voiture Noire'},{'No': 4, 'Company': 'Rolls Royce', 'Car Model': 'Phantom'},{'No': 5, 'Company': 'BMW', 'Car Model': 'BMW X7'},] with open('Names.csv', 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames = field_names) writer.writeheader() writer.writerows(cars)",
"e": 28940,
"s": 28428,
"text": null
},
{
"code": null,
"e": 28948,
"s": 28940,
"text": "Output:"
},
{
"code": null,
"e": 28960,
"s": 28948,
"text": "python-dict"
},
{
"code": null,
"e": 28967,
"s": 28960,
"text": "Python"
},
{
"code": null,
"e": 28979,
"s": 28967,
"text": "python-dict"
},
{
"code": null,
"e": 29077,
"s": 28979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29095,
"s": 29077,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29130,
"s": 29095,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29152,
"s": 29130,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29184,
"s": 29152,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29214,
"s": 29184,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29256,
"s": 29214,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29299,
"s": 29256,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29343,
"s": 29299,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29372,
"s": 29343,
"text": "*args and **kwargs in Python"
}
]
|
C/C++ Programming to Count trailing zeroes in factorial of a number? | Counting the number of trailing zeroes in a factorial number is done by counting the number of 2s and 5s in the factors of the number. Because 2*5 gives 10 which is a trailing 0 in the factorial of a number.
Factorial of 7 = 5040, the number of trailing 0’s is 1.
Based on our logic 7! = 2*3*4*5*6*7, it has 3 2s and 1 5s so the number of trailing 0’s is 1.
#include <iostream>
using namespace std;
int main() {
int n = 45;
int count = 0;
for (int i = 5; n / i >= 1; i *= 5)
count += n / i;
cout<<"No of trailing 0s in " << n<< "! is " << count;
return 0;
}
No of trailing 0s in 24! is 10 | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "Counting the number of trailing zeroes in a factorial number is done by counting the number of 2s and 5s in the factors of the number. Because 2*5 gives 10 which is a trailing 0 in the factorial of a number."
},
{
"code": null,
"e": 1326,
"s": 1270,
"text": "Factorial of 7 = 5040, the number of trailing 0’s is 1."
},
{
"code": null,
"e": 1420,
"s": 1326,
"text": "Based on our logic 7! = 2*3*4*5*6*7, it has 3 2s and 1 5s so the number of trailing 0’s is 1."
},
{
"code": null,
"e": 1641,
"s": 1420,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int n = 45;\n int count = 0;\n for (int i = 5; n / i >= 1; i *= 5)\n count += n / i;\n cout<<\"No of trailing 0s in \" << n<< \"! is \" << count;\n return 0;\n}"
},
{
"code": null,
"e": 1672,
"s": 1641,
"text": "No of trailing 0s in 24! is 10"
}
]
|
What is the use of the Get-Error cmdlet in PowerShell? | Get-Error cmdlet was introduced in PowerShell v7. It displays the most recent error messages from the
current session.
When you check the get member of this command, its output is in the form of PSExtendedError so whatever the output is produced by this command is in a detailed manner and so this command is very helpful in troubleshooting error messages.
PS C:\> Get-Error | gm
TypeName: System.Management.Automation.ErrorRecord#PSExtendedError
We will write one command in the PowerShell console which is ultimately generate an error.
PS C:\> Get-ChildItem c:\notexist
Get-ChildItem: Cannot find path 'C:\notexist' because it does not exist.
The above directory does not exist. Let’s get a detailed view of this error using the Get-Error cmdlet.
PS C:\> Get-Error
Exception :
Type : System.Management.Automation.ItemNotFoundException
ErrorRecord :
Exception :
Type : System.Management.Automation.ParentContainsErrorRecordException
Message : Cannot find path 'C:\notexist' because it does not exist.
HResult : -2146233087
TargetObject : C:\notexist
CategoryInfo : ObjectNotFound: (C:\notexist:String) [],
ParentContainsErrorRecordException
FullyQualifiedErrorId : PathNotFound
ItemName : C:\notexist
SessionStateCategory : Drive
TargetSite :
Name : GetChildItems
DeclaringType : System.Management.Automation.SessionStateInternal,
System.Management.Automation, Version=7.0.3.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35
MemberType : Method
Module : System.Management.Automation.dll
StackTrace :
at System.Management.Automation.SessionStateInternal.GetChildItems(String path, Boolean
recurse, UInt32 depth, CmdletProviderContext context)
at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord()
Message : Cannot find path 'C:\notexist' because it does not exist.
Source : System.Management.Automation
HResult : -2146233087
TargetObject : C:\notexist
CategoryInfo : ObjectNotFound: (C:\notexist:String) [Get-ChildItem],
ItemNotFoundException
FullyQualifiedErrorId :
PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
InvocationInfo :
MyCommand : Get-ChildItem
ScriptLineNumber : 1
OffsetInLine : 1
HistoryId : 94
Line : Get-ChildItem c:\notexist
PositionMessage : At line:1 char:1
+ Get-ChildItem c:\notexist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
InvocationName : Get-ChildItem
CommandOrigin : Internal
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo :
As you can see in the above output that it contains the error messages, exception details, Invocation Name, Line number for the error, etc. You can access each section separately as well.
PS C:\> (Get-Error).InvocationInfo
MyCommand : Get-ChildItem
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 1
OffsetInLine : 1
HistoryId : 94
ScriptName :
Line : Get-ChildItem c:\notexist
PositionMessage : At line:1 char:1
+ Get-ChildItem c:\notexist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot :
PSCommandPath :
InvocationName : Get-ChildItem
PipelineLength : 0
PipelinePosition : 0
ExpectingInput : False
CommandOrigin : Internal
DisplayScriptPosition :
PS C:\> (Get-Error).InvocationInfo.PositionMessage
At line:1 char:1
+ Get-ChildItem c:\notexist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
You can also use Get-Error as the pipeline input and for that, you need to error input as the pipeline.The best way is to pass the $Error variable as the input object. It doesn’t matter in which view (Normal, Category, or Concise) the errors are, Get-Error command converts it to the precise view.
$error | Get-Error
You can also get the number of latest errors of the current console using -Newest parameter. For
example,
Get-Error -Newest 2
Whenever we use the above command, you can see the errors are separated by Error Index. In the above example, we have retrieved two latest errors so there will be two error indexes. ErrorIndex 0 and ErrorIndex 1. | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "Get-Error cmdlet was introduced in PowerShell v7. It displays the most recent error messages from the\ncurrent session."
},
{
"code": null,
"e": 1419,
"s": 1181,
"text": "When you check the get member of this command, its output is in the form of PSExtendedError so whatever the output is produced by this command is in a detailed manner and so this command is very helpful in troubleshooting error messages."
},
{
"code": null,
"e": 1509,
"s": 1419,
"text": "PS C:\\> Get-Error | gm\nTypeName: System.Management.Automation.ErrorRecord#PSExtendedError"
},
{
"code": null,
"e": 1600,
"s": 1509,
"text": "We will write one command in the PowerShell console which is ultimately generate an error."
},
{
"code": null,
"e": 1707,
"s": 1600,
"text": "PS C:\\> Get-ChildItem c:\\notexist\nGet-ChildItem: Cannot find path 'C:\\notexist' because it does not exist."
},
{
"code": null,
"e": 1811,
"s": 1707,
"text": "The above directory does not exist. Let’s get a detailed view of this error using the Get-Error cmdlet."
},
{
"code": null,
"e": 3464,
"s": 1811,
"text": "PS C:\\> Get-Error\nException :\nType : System.Management.Automation.ItemNotFoundException\nErrorRecord :\nException :\nType : System.Management.Automation.ParentContainsErrorRecordException\nMessage : Cannot find path 'C:\\notexist' because it does not exist.\nHResult : -2146233087\nTargetObject : C:\\notexist\nCategoryInfo : ObjectNotFound: (C:\\notexist:String) [],\nParentContainsErrorRecordException\nFullyQualifiedErrorId : PathNotFound\nItemName : C:\\notexist\nSessionStateCategory : Drive\nTargetSite :\nName : GetChildItems\nDeclaringType : System.Management.Automation.SessionStateInternal,\nSystem.Management.Automation, Version=7.0.3.0, Culture=neutral,\nPublicKeyToken=31bf3856ad364e35\nMemberType : Method\nModule : System.Management.Automation.dll\nStackTrace :\nat System.Management.Automation.SessionStateInternal.GetChildItems(String path, Boolean\nrecurse, UInt32 depth, CmdletProviderContext context)\nat Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord()\nMessage : Cannot find path 'C:\\notexist' because it does not exist.\nSource : System.Management.Automation\nHResult : -2146233087\nTargetObject : C:\\notexist\nCategoryInfo : ObjectNotFound: (C:\\notexist:String) [Get-ChildItem],\nItemNotFoundException\nFullyQualifiedErrorId :\nPathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand\nInvocationInfo :\nMyCommand : Get-ChildItem\nScriptLineNumber : 1\nOffsetInLine : 1\nHistoryId : 94\nLine : Get-ChildItem c:\\notexist\nPositionMessage : At line:1 char:1\n+ Get-ChildItem c:\\notexist\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~\nInvocationName : Get-ChildItem\nCommandOrigin : Internal\nScriptStackTrace : at <ScriptBlock>, <No file>: line 1\nPipelineIterationInfo :"
},
{
"code": null,
"e": 3652,
"s": 3464,
"text": "As you can see in the above output that it contains the error messages, exception details, Invocation Name, Line number for the error, etc. You can access each section separately as well."
},
{
"code": null,
"e": 4120,
"s": 3652,
"text": "PS C:\\> (Get-Error).InvocationInfo\nMyCommand : Get-ChildItem\nBoundParameters : {}\nUnboundArguments : {}\nScriptLineNumber : 1\nOffsetInLine : 1\nHistoryId : 94\nScriptName :\nLine : Get-ChildItem c:\\notexist\nPositionMessage : At line:1 char:1\n+ Get-ChildItem c:\\notexist\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~\nPSScriptRoot :\nPSCommandPath :\nInvocationName : Get-ChildItem\nPipelineLength : 0\nPipelinePosition : 0\nExpectingInput : False\nCommandOrigin : Internal\nDisplayScriptPosition :"
},
{
"code": null,
"e": 4244,
"s": 4120,
"text": "PS C:\\> (Get-Error).InvocationInfo.PositionMessage\nAt line:1 char:1\n+ Get-ChildItem c:\\notexist\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~"
},
{
"code": null,
"e": 4542,
"s": 4244,
"text": "You can also use Get-Error as the pipeline input and for that, you need to error input as the pipeline.The best way is to pass the $Error variable as the input object. It doesn’t matter in which view (Normal, Category, or Concise) the errors are, Get-Error command converts it to the precise view."
},
{
"code": null,
"e": 4562,
"s": 4542,
"text": "$error | Get-Error\n"
},
{
"code": null,
"e": 4668,
"s": 4562,
"text": "You can also get the number of latest errors of the current console using -Newest parameter. For\nexample,"
},
{
"code": null,
"e": 4688,
"s": 4668,
"text": "Get-Error -Newest 2"
},
{
"code": null,
"e": 4901,
"s": 4688,
"text": "Whenever we use the above command, you can see the errors are separated by Error Index. In the above example, we have retrieved two latest errors so there will be two error indexes. ErrorIndex 0 and ErrorIndex 1."
}
]
|
Socket.IO - Namespaces | Socket.IO allows you to "namespace" your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. Multiple namespaces actually share the same WebSockets connection thus saving us socket ports on the server.
Namespaces are created on the server side. However, they are joined by clients by sending a request to the server.
The root namespace '/' is the default namespace, which is joined by clients if a namespace is not specified by the client while connecting to the server. All connections to the server using the socket-object client side are made to the default namespace. For example −
var socket = io();
This will connect the client to the default namespace. All events on this namespace connection will be handled by the io object on the server. All the previous examples were utilizing default namespaces to communicate with the server and back.
We can create our own custom namespaces. To set up a custom namespace, we can call the 'of' function on the server side −
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile('E:/test/index.html');});
var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
console.log('someone connected');
nsp.emit('hi', 'Hello everyone!');
});
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
Now, to connect a client to this namespace, you need to provide the namespace as an argument to the io constructor call to create a connection and a socket object on client side.
For example, to connect to the above namespace, use the following HTML −
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('/my-namespace');
socket.on('hi',function(data){
document.body.innerHTML = '';
document.write(data);
});
</script>
<body></body>
</html>
Every time someone connects to this namespace, they will receive a 'hi' event displaying the message "Hello everyone!".
35 Lectures
2.5 hours
Nicholas Lever
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2288,
"s": 1865,
"text": "Socket.IO allows you to \"namespace\" your sockets, which essentially means assigning different endpoints or paths. This is a useful feature to minimize the number of resources (TCP connections) and at the same time separate concerns within your application by introducing separation between communication channels. Multiple namespaces actually share the same WebSockets connection thus saving us socket ports on the server."
},
{
"code": null,
"e": 2403,
"s": 2288,
"text": "Namespaces are created on the server side. However, they are joined by clients by sending a request to the server."
},
{
"code": null,
"e": 2672,
"s": 2403,
"text": "The root namespace '/' is the default namespace, which is joined by clients if a namespace is not specified by the client while connecting to the server. All connections to the server using the socket-object client side are made to the default namespace. For example −"
},
{
"code": null,
"e": 2692,
"s": 2672,
"text": "var socket = io();\n"
},
{
"code": null,
"e": 2936,
"s": 2692,
"text": "This will connect the client to the default namespace. All events on this namespace connection will be handled by the io object on the server. All the previous examples were utilizing default namespaces to communicate with the server and back."
},
{
"code": null,
"e": 3058,
"s": 2936,
"text": "We can create our own custom namespaces. To set up a custom namespace, we can call the 'of' function on the server side −"
},
{
"code": null,
"e": 3480,
"s": 3058,
"text": "var app = require('express')();\nvar http = require('http').Server(app);\nvar io = require('socket.io')(http);\n\napp.get('/', function(req, res){\n res.sendFile('E:/test/index.html');});\n \nvar nsp = io.of('/my-namespace');\nnsp.on('connection', function(socket){\n console.log('someone connected');\n nsp.emit('hi', 'Hello everyone!');\n});\nhttp.listen(3000, function(){\n console.log('listening on localhost:3000');\n});"
},
{
"code": null,
"e": 3659,
"s": 3480,
"text": "Now, to connect a client to this namespace, you need to provide the namespace as an argument to the io constructor call to create a connection and a socket object on client side."
},
{
"code": null,
"e": 3732,
"s": 3659,
"text": "For example, to connect to the above namespace, use the following HTML −"
},
{
"code": null,
"e": 4057,
"s": 3732,
"text": "<!DOCTYPE html>\n<html>\n <head><title>Hello world</title></head>\n <script src=\"/socket.io/socket.io.js\"></script>\n <script>\n var socket = io('/my-namespace');\n socket.on('hi',function(data){\n document.body.innerHTML = '';\n document.write(data);\n });\n </script>\n <body></body>\n </html>"
},
{
"code": null,
"e": 4177,
"s": 4057,
"text": "Every time someone connects to this namespace, they will receive a 'hi' event displaying the message \"Hello everyone!\"."
},
{
"code": null,
"e": 4212,
"s": 4177,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4228,
"s": 4212,
"text": " Nicholas Lever"
},
{
"code": null,
"e": 4235,
"s": 4228,
"text": " Print"
},
{
"code": null,
"e": 4246,
"s": 4235,
"text": " Add Notes"
}
]
|
Check if a string contains an anagram of another string as its substring - GeeksforGeeks | 03 Jun, 2021
Given two strings S1 and S2, the task is to check if S2 contains an anagram of S1 as its substring.
Examples:
Input: S1 = “ab”, S2 = “bbpobac”Output: YesExplanation: String S2 contains anagram “ba” of S1 (“ba”).
Input: S1 = “ab”, S2 = “cbddaoo”Output: No
Approach: Follow the steps below to solve the problem:
Initialize two Hashmaps s1hash and s2hash, to store the frequency of alphabets of the two strings.If the length of S1 is greater than the length of S2, then print “NO”.Iterate over the characters of the string S1 and update s1hash.Iterate over the characters of the string S2 using the Sliding Window technique and update the HashMap accordingly.For any substring of S2 of length equal to the length of S1, if both the Hashmaps are found to be equal, print “YES”.Otherwise, print “NO”.
Initialize two Hashmaps s1hash and s2hash, to store the frequency of alphabets of the two strings.
If the length of S1 is greater than the length of S2, then print “NO”.
Iterate over the characters of the string S1 and update s1hash.
Iterate over the characters of the string S2 using the Sliding Window technique and update the HashMap accordingly.
For any substring of S2 of length equal to the length of S1, if both the Hashmaps are found to be equal, print “YES”.
Otherwise, print “NO”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if string s2// contains anagram of the string// s1 as its substringbool checkAnagram(string s1, string s2){ // Stores frequencies of // characters in substrings of s2 vector<int> s2hash(26, 0); // Stores frequencies of // characters in s1 vector<int> s1hash(26, 0); int s1len = s1.size(); int s2len = s2.size(); // If length of s2 exceeds length of s1 if (s1len > s2len) return false; int left = 0, right = 0; // Store frequencies of characters in first // substring of length s1len in string s2 while (right < s1len) { s1hash[s1[right] - 'a'] += 1; s2hash[s2[right] - 'a'] += 1; right++; } right -= 1; // Perform Sliding Window technique while (right < s2len) { // If hashmaps are found to be // identical for any substring if (s1hash == s2hash) return true; right++; if (right != s2len) s2hash[s2[right] - 'a'] += 1; s2hash[s2[left] - 'a'] -= 1; left++; } return false;} // Driver Codeint main(){ string s1 = "ab"; string s2 = "bbpobac"; if (checkAnagram(s1, s2)) cout << "YES\n"; else cout << "No\n"; return 0;}
// Java program for the above approachimport java.io.*;import java.util.*;class GFG{ // Function to check if string s2 // contains anagram of the string // s1 as its substring public static boolean checkAnagram(String s1, String s2) { // Stores frequencies of // characters in substrings of s2 int s2hash[] = new int[26]; // Stores frequencies of // characters in s1 int s1hash[] = new int[26]; int s1len = s1.length(); int s2len = s2.length(); // If length of s2 exceeds length of s1 if (s1len > s2len) return false; int left = 0, right = 0; // Store frequencies of characters in first // substring of length s1len in string s2 while (right < s1len) { s1hash[s1.charAt(right) - 'a'] += 1; s2hash[s2.charAt(right) - 'a'] += 1; right++; } right -= 1; // Perform Sliding Window technique while (right < s2len) { // If hashmaps are found to be // identical for any substring if (Arrays.equals(s1hash, s2hash)) return true; right++; if (right != s2len) s2hash[s2.charAt(right) - 'a'] += 1; s2hash[s2.charAt(left) - 'a'] -= 1; left++; } return false; } // Driver Code public static void main(String[] args) { String s1 = "ab"; String s2 = "bbpobac"; if (checkAnagram(s1, s2)) System.out.println("YES"); else System.out.println("No"); }} // This code is contributed by kingash.
# Python 3 Program to implement# the above approach # Function to check if string s2# contains anagram of the string# s1 as its substringdef checkAnagram(s1, s2): # Stores frequencies of # characters in substrings of s2 s2hash = [0 for i in range(26)] # Stores frequencies of # characters in s1 s1hash = [0 for i in range(26)] s1len = len(s1) s2len = len(s2) # If length of s2 exceeds length of s1 if (s1len > s2len): return False left = 0 right = 0 # Store frequencies of characters in first # substring of length s1len in string s2 while (right < s1len): s1hash[ord(s1[right]) - 97] += 1 s2hash[ord(s2[right]) - 97] += 1 right += 1 right -= 1 # Perform Sliding Window technique while (right < s2len): # If hashmaps are found to be # identical for any substring if (s1hash == s2hash): return True right += 1 if (right != s2len): s2hash[ord(s2[right]) - 97] += 1 s2hash[ord(s2[left]) - 97] -= 1 left += 1 return False # Driver Codeif __name__ == '__main__': s1 = "ab" s2 = "bbpobac" if (checkAnagram(s1, s2)): print("YES") else: print("No") # This code is contributed by ipg2016107
// C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to check if string s2// contains anagram of the string// s1 as its substringstatic bool checkAnagram(string s1, string s2){ // Stores frequencies of // characters in substrings of s2 List<int> s2hash = new List<int>(); for(int i=0;i<26;i++) s2hash.Add(0); // Stores frequencies of // characters in s1 List<int> s1hash = new List<int>(); for(int i=0;i<26;i++) s1hash.Add(0); int s1len = s1.Length; int s2len = s2.Length; // If length of s2 exceeds length of s1 if (s1len > s2len) return false; int left = 0, right = 0; // Store frequencies of characters in first // substring of length s1len in string s2 while (right < s1len) { s1hash[s1[right] - 'a'] += 1; s2hash[s2[right] - 'a'] += 1; right++; } right -= 1; // Perform Sliding Window technique while (right < s2len) { // If hashmaps are found to be // identical for any substring if (s1hash == s2hash) return true; right++; if(right != s2len) s2hash[s2[right] - 'a'] += 1; s2hash[s2[left] - 'a'] -= 1; left++; } return false;} // Driver Codepublic static void Main(){ string s1 = "ab"; string s2 = "bbpobac"; if (checkAnagram(s1, s2)==true) Console.WriteLine("NO"); else Console.WriteLine("YES");}} // This code is contributed by bgangawar59.
<script> // Javascript Program to implement// the above approach // Function to check if string s2// contains anagram of the string// s1 as its substringfunction checkAnagram(s1, s2){ // Stores frequencies of // characters in substrings of s2 var s2hash = Array(26).fill(0); // Stores frequencies of // characters in s1 var s1hash = Array(26).fill(0); var s1len = s1.length; var s2len = s2.length; // If length of s2 exceeds length of s1 if (s1len > s2len) return false; var left = 0, right = 0; // Store frequencies of characters in first // substring of length s1len in string s2 while (right < s1len) { s1hash[s1[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; s2hash[s2[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; right++; } right -= 1; // Perform Sliding Window technique while (right < s2len) { var ans = true; // If hashmaps are found to be // identical for any substring for(var i =0; i<26; i++) { if(s1hash[i]!=s2hash[i]) { ans = false; } } if(ans) return true; right++; if (right != s2len) s2hash[s2[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; s2hash[s2[left].charCodeAt(0) - 'a'.charCodeAt(0)] -= 1; left++; } return false;} // Driver Codevar s1 = "ab";var s2 = "bbpobac";if (checkAnagram(s1, s2)) document.write( "YES");else document.write( "No"); // This code is contributed by importantly.</script>
YES
Time Complexity: O(26 * len(S2))Auxiliary Space: O(26)
ipg2016107
bgangwar59
Kingash
importantly
anagram
frequency-counting
sliding-window
substring
Technical Scripter 2020
Hash
Searching
Strings
Technical Scripter
sliding-window
Searching
Hash
Strings
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Quadratic Probing in Hashing
Rearrange an array such that arr[i] = i
Hashing in Java
Practice Problems on Hashing
Hash Functions and list/types of Hash functions
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1 | [
{
"code": null,
"e": 25158,
"s": 25130,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 25258,
"s": 25158,
"text": "Given two strings S1 and S2, the task is to check if S2 contains an anagram of S1 as its substring."
},
{
"code": null,
"e": 25270,
"s": 25258,
"text": "Examples: "
},
{
"code": null,
"e": 25372,
"s": 25270,
"text": "Input: S1 = “ab”, S2 = “bbpobac”Output: YesExplanation: String S2 contains anagram “ba” of S1 (“ba”)."
},
{
"code": null,
"e": 25415,
"s": 25372,
"text": "Input: S1 = “ab”, S2 = “cbddaoo”Output: No"
},
{
"code": null,
"e": 25474,
"s": 25419,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25962,
"s": 25476,
"text": "Initialize two Hashmaps s1hash and s2hash, to store the frequency of alphabets of the two strings.If the length of S1 is greater than the length of S2, then print “NO”.Iterate over the characters of the string S1 and update s1hash.Iterate over the characters of the string S2 using the Sliding Window technique and update the HashMap accordingly.For any substring of S2 of length equal to the length of S1, if both the Hashmaps are found to be equal, print “YES”.Otherwise, print “NO”."
},
{
"code": null,
"e": 26061,
"s": 25962,
"text": "Initialize two Hashmaps s1hash and s2hash, to store the frequency of alphabets of the two strings."
},
{
"code": null,
"e": 26132,
"s": 26061,
"text": "If the length of S1 is greater than the length of S2, then print “NO”."
},
{
"code": null,
"e": 26196,
"s": 26132,
"text": "Iterate over the characters of the string S1 and update s1hash."
},
{
"code": null,
"e": 26312,
"s": 26196,
"text": "Iterate over the characters of the string S2 using the Sliding Window technique and update the HashMap accordingly."
},
{
"code": null,
"e": 26430,
"s": 26312,
"text": "For any substring of S2 of length equal to the length of S1, if both the Hashmaps are found to be equal, print “YES”."
},
{
"code": null,
"e": 26453,
"s": 26430,
"text": "Otherwise, print “NO”."
},
{
"code": null,
"e": 26505,
"s": 26453,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26509,
"s": 26505,
"text": "C++"
},
{
"code": null,
"e": 26514,
"s": 26509,
"text": "Java"
},
{
"code": null,
"e": 26522,
"s": 26514,
"text": "Python3"
},
{
"code": null,
"e": 26525,
"s": 26522,
"text": "C#"
},
{
"code": null,
"e": 26536,
"s": 26525,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if string s2// contains anagram of the string// s1 as its substringbool checkAnagram(string s1, string s2){ // Stores frequencies of // characters in substrings of s2 vector<int> s2hash(26, 0); // Stores frequencies of // characters in s1 vector<int> s1hash(26, 0); int s1len = s1.size(); int s2len = s2.size(); // If length of s2 exceeds length of s1 if (s1len > s2len) return false; int left = 0, right = 0; // Store frequencies of characters in first // substring of length s1len in string s2 while (right < s1len) { s1hash[s1[right] - 'a'] += 1; s2hash[s2[right] - 'a'] += 1; right++; } right -= 1; // Perform Sliding Window technique while (right < s2len) { // If hashmaps are found to be // identical for any substring if (s1hash == s2hash) return true; right++; if (right != s2len) s2hash[s2[right] - 'a'] += 1; s2hash[s2[left] - 'a'] -= 1; left++; } return false;} // Driver Codeint main(){ string s1 = \"ab\"; string s2 = \"bbpobac\"; if (checkAnagram(s1, s2)) cout << \"YES\\n\"; else cout << \"No\\n\"; return 0;}",
"e": 27867,
"s": 26536,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*;class GFG{ // Function to check if string s2 // contains anagram of the string // s1 as its substring public static boolean checkAnagram(String s1, String s2) { // Stores frequencies of // characters in substrings of s2 int s2hash[] = new int[26]; // Stores frequencies of // characters in s1 int s1hash[] = new int[26]; int s1len = s1.length(); int s2len = s2.length(); // If length of s2 exceeds length of s1 if (s1len > s2len) return false; int left = 0, right = 0; // Store frequencies of characters in first // substring of length s1len in string s2 while (right < s1len) { s1hash[s1.charAt(right) - 'a'] += 1; s2hash[s2.charAt(right) - 'a'] += 1; right++; } right -= 1; // Perform Sliding Window technique while (right < s2len) { // If hashmaps are found to be // identical for any substring if (Arrays.equals(s1hash, s2hash)) return true; right++; if (right != s2len) s2hash[s2.charAt(right) - 'a'] += 1; s2hash[s2.charAt(left) - 'a'] -= 1; left++; } return false; } // Driver Code public static void main(String[] args) { String s1 = \"ab\"; String s2 = \"bbpobac\"; if (checkAnagram(s1, s2)) System.out.println(\"YES\"); else System.out.println(\"No\"); }} // This code is contributed by kingash.",
"e": 29317,
"s": 27867,
"text": null
},
{
"code": "# Python 3 Program to implement# the above approach # Function to check if string s2# contains anagram of the string# s1 as its substringdef checkAnagram(s1, s2): # Stores frequencies of # characters in substrings of s2 s2hash = [0 for i in range(26)] # Stores frequencies of # characters in s1 s1hash = [0 for i in range(26)] s1len = len(s1) s2len = len(s2) # If length of s2 exceeds length of s1 if (s1len > s2len): return False left = 0 right = 0 # Store frequencies of characters in first # substring of length s1len in string s2 while (right < s1len): s1hash[ord(s1[right]) - 97] += 1 s2hash[ord(s2[right]) - 97] += 1 right += 1 right -= 1 # Perform Sliding Window technique while (right < s2len): # If hashmaps are found to be # identical for any substring if (s1hash == s2hash): return True right += 1 if (right != s2len): s2hash[ord(s2[right]) - 97] += 1 s2hash[ord(s2[left]) - 97] -= 1 left += 1 return False # Driver Codeif __name__ == '__main__': s1 = \"ab\" s2 = \"bbpobac\" if (checkAnagram(s1, s2)): print(\"YES\") else: print(\"No\") # This code is contributed by ipg2016107",
"e": 30607,
"s": 29317,
"text": null
},
{
"code": "// C# Program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to check if string s2// contains anagram of the string// s1 as its substringstatic bool checkAnagram(string s1, string s2){ // Stores frequencies of // characters in substrings of s2 List<int> s2hash = new List<int>(); for(int i=0;i<26;i++) s2hash.Add(0); // Stores frequencies of // characters in s1 List<int> s1hash = new List<int>(); for(int i=0;i<26;i++) s1hash.Add(0); int s1len = s1.Length; int s2len = s2.Length; // If length of s2 exceeds length of s1 if (s1len > s2len) return false; int left = 0, right = 0; // Store frequencies of characters in first // substring of length s1len in string s2 while (right < s1len) { s1hash[s1[right] - 'a'] += 1; s2hash[s2[right] - 'a'] += 1; right++; } right -= 1; // Perform Sliding Window technique while (right < s2len) { // If hashmaps are found to be // identical for any substring if (s1hash == s2hash) return true; right++; if(right != s2len) s2hash[s2[right] - 'a'] += 1; s2hash[s2[left] - 'a'] -= 1; left++; } return false;} // Driver Codepublic static void Main(){ string s1 = \"ab\"; string s2 = \"bbpobac\"; if (checkAnagram(s1, s2)==true) Console.WriteLine(\"NO\"); else Console.WriteLine(\"YES\");}} // This code is contributed by bgangawar59.",
"e": 32139,
"s": 30607,
"text": null
},
{
"code": "<script> // Javascript Program to implement// the above approach // Function to check if string s2// contains anagram of the string// s1 as its substringfunction checkAnagram(s1, s2){ // Stores frequencies of // characters in substrings of s2 var s2hash = Array(26).fill(0); // Stores frequencies of // characters in s1 var s1hash = Array(26).fill(0); var s1len = s1.length; var s2len = s2.length; // If length of s2 exceeds length of s1 if (s1len > s2len) return false; var left = 0, right = 0; // Store frequencies of characters in first // substring of length s1len in string s2 while (right < s1len) { s1hash[s1[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; s2hash[s2[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; right++; } right -= 1; // Perform Sliding Window technique while (right < s2len) { var ans = true; // If hashmaps are found to be // identical for any substring for(var i =0; i<26; i++) { if(s1hash[i]!=s2hash[i]) { ans = false; } } if(ans) return true; right++; if (right != s2len) s2hash[s2[right].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; s2hash[s2[left].charCodeAt(0) - 'a'.charCodeAt(0)] -= 1; left++; } return false;} // Driver Codevar s1 = \"ab\";var s2 = \"bbpobac\";if (checkAnagram(s1, s2)) document.write( \"YES\");else document.write( \"No\"); // This code is contributed by importantly.</script>",
"e": 33714,
"s": 32139,
"text": null
},
{
"code": null,
"e": 33721,
"s": 33717,
"text": "YES"
},
{
"code": null,
"e": 33780,
"s": 33725,
"text": "Time Complexity: O(26 * len(S2))Auxiliary Space: O(26)"
},
{
"code": null,
"e": 33793,
"s": 33782,
"text": "ipg2016107"
},
{
"code": null,
"e": 33804,
"s": 33793,
"text": "bgangwar59"
},
{
"code": null,
"e": 33812,
"s": 33804,
"text": "Kingash"
},
{
"code": null,
"e": 33824,
"s": 33812,
"text": "importantly"
},
{
"code": null,
"e": 33832,
"s": 33824,
"text": "anagram"
},
{
"code": null,
"e": 33851,
"s": 33832,
"text": "frequency-counting"
},
{
"code": null,
"e": 33866,
"s": 33851,
"text": "sliding-window"
},
{
"code": null,
"e": 33876,
"s": 33866,
"text": "substring"
},
{
"code": null,
"e": 33900,
"s": 33876,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 33905,
"s": 33900,
"text": "Hash"
},
{
"code": null,
"e": 33915,
"s": 33905,
"text": "Searching"
},
{
"code": null,
"e": 33923,
"s": 33915,
"text": "Strings"
},
{
"code": null,
"e": 33942,
"s": 33923,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33957,
"s": 33942,
"text": "sliding-window"
},
{
"code": null,
"e": 33967,
"s": 33957,
"text": "Searching"
},
{
"code": null,
"e": 33972,
"s": 33967,
"text": "Hash"
},
{
"code": null,
"e": 33980,
"s": 33972,
"text": "Strings"
},
{
"code": null,
"e": 33988,
"s": 33980,
"text": "anagram"
},
{
"code": null,
"e": 34086,
"s": 33988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34095,
"s": 34086,
"text": "Comments"
},
{
"code": null,
"e": 34108,
"s": 34095,
"text": "Old Comments"
},
{
"code": null,
"e": 34137,
"s": 34108,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 34177,
"s": 34137,
"text": "Rearrange an array such that arr[i] = i"
},
{
"code": null,
"e": 34193,
"s": 34177,
"text": "Hashing in Java"
},
{
"code": null,
"e": 34222,
"s": 34193,
"text": "Practice Problems on Hashing"
},
{
"code": null,
"e": 34270,
"s": 34222,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 34284,
"s": 34270,
"text": "Binary Search"
},
{
"code": null,
"e": 34298,
"s": 34284,
"text": "Linear Search"
},
{
"code": null,
"e": 34366,
"s": 34298,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34390,
"s": 34366,
"text": "Find the Missing Number"
}
]
|
Python program to find number of days between two given dates | 31 Aug, 2021
Given two dates, Write a Python program to find the total number of days between them.
Examples:
Input : dt1 = 13/12/2018, dt2 = 25/2/2019
Output : 74 days
Input : dt1 = 01/01/2004, dt2 = 01/01/2005
Output : 366 days
Naive Approach: One Naive Solution is to start from dt1 and keep counting days till dt2 is reached. This solution requires more than O(1) time.
A Better and Simple solution is to count the total number of days before dt1 from i.e., total days from 00/00/0000 to dt1, then count the total number of days before dt2. Finally, return the difference between the two counts.
Python3
# Python3 program two find number of# days between two given dates # A date has day 'd', month 'm' and year 'y' class Date: def __init__(self, d, m, y): self.d = d self.m = m self.y = y # To store number of days in all months from# January to Dec.monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # This function counts number of leap years# before the given date def countLeapYears(d): years = d.y # Check if the current year needs to be considered # for the count of leap years or not if (d.m <= 2): years -= 1 # An year is a leap year if it is a multiple of 4, # multiple of 400 and not a multiple of 100. return int(years / 4) - int(years / 100) + int(years / 400) # This function returns number of days between two# given datesdef getDifference(dt1, dt2): # COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' # initialize count using years and day n1 = dt1.y * 365 + dt1.d # Add days for months in given date for i in range(0, dt1.m - 1): n1 += monthDays[i] # Since every leap year is of 366 days, # Add a day for every leap year n1 += countLeapYears(dt1) # SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' n2 = dt2.y * 365 + dt2.d for i in range(0, dt2.m - 1): n2 += monthDays[i] n2 += countLeapYears(dt2) # return difference between two counts return (n2 - n1) # Driver programdt1 = Date(13, 12, 2018)dt2 = Date(25, 2, 2019) print(getDifference(dt1, dt2), "days")
74 days
Using Python datetime module:
Python comes with an inbuilt datetime module that helps us to solve various datetime related problems. In order to find the difference between two dates we simply input the two dates with date type and subtract them, which in turn provides us the number of days between the two dates.
Python3
# Python3 program to find number of days# between two given datesfrom datetime import date def numOfDays(date1, date2): return (date2-date1).days # Driver programdate1 = date(2018, 12, 13)date2 = date(2019, 2, 25)print(numOfDays(date1, date2), "days")
74 days
chirags_30
tanishkthomas
date-time-program
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 140,
"s": 52,
"text": "Given two dates, Write a Python program to find the total number of days between them. "
},
{
"code": null,
"e": 151,
"s": 140,
"text": "Examples: "
},
{
"code": null,
"e": 273,
"s": 151,
"text": "Input : dt1 = 13/12/2018, dt2 = 25/2/2019\nOutput : 74 days\n\nInput : dt1 = 01/01/2004, dt2 = 01/01/2005\nOutput : 366 days "
},
{
"code": null,
"e": 418,
"s": 273,
"text": "Naive Approach: One Naive Solution is to start from dt1 and keep counting days till dt2 is reached. This solution requires more than O(1) time. "
},
{
"code": null,
"e": 646,
"s": 418,
"text": "A Better and Simple solution is to count the total number of days before dt1 from i.e., total days from 00/00/0000 to dt1, then count the total number of days before dt2. Finally, return the difference between the two counts. "
},
{
"code": null,
"e": 654,
"s": 646,
"text": "Python3"
},
{
"code": "# Python3 program two find number of# days between two given dates # A date has day 'd', month 'm' and year 'y' class Date: def __init__(self, d, m, y): self.d = d self.m = m self.y = y # To store number of days in all months from# January to Dec.monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # This function counts number of leap years# before the given date def countLeapYears(d): years = d.y # Check if the current year needs to be considered # for the count of leap years or not if (d.m <= 2): years -= 1 # An year is a leap year if it is a multiple of 4, # multiple of 400 and not a multiple of 100. return int(years / 4) - int(years / 100) + int(years / 400) # This function returns number of days between two# given datesdef getDifference(dt1, dt2): # COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' # initialize count using years and day n1 = dt1.y * 365 + dt1.d # Add days for months in given date for i in range(0, dt1.m - 1): n1 += monthDays[i] # Since every leap year is of 366 days, # Add a day for every leap year n1 += countLeapYears(dt1) # SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' n2 = dt2.y * 365 + dt2.d for i in range(0, dt2.m - 1): n2 += monthDays[i] n2 += countLeapYears(dt2) # return difference between two counts return (n2 - n1) # Driver programdt1 = Date(13, 12, 2018)dt2 = Date(25, 2, 2019) print(getDifference(dt1, dt2), \"days\")",
"e": 2173,
"s": 654,
"text": null
},
{
"code": null,
"e": 2181,
"s": 2173,
"text": "74 days"
},
{
"code": null,
"e": 2213,
"s": 2183,
"text": "Using Python datetime module:"
},
{
"code": null,
"e": 2499,
"s": 2213,
"text": "Python comes with an inbuilt datetime module that helps us to solve various datetime related problems. In order to find the difference between two dates we simply input the two dates with date type and subtract them, which in turn provides us the number of days between the two dates. "
},
{
"code": null,
"e": 2507,
"s": 2499,
"text": "Python3"
},
{
"code": "# Python3 program to find number of days# between two given datesfrom datetime import date def numOfDays(date1, date2): return (date2-date1).days # Driver programdate1 = date(2018, 12, 13)date2 = date(2019, 2, 25)print(numOfDays(date1, date2), \"days\")",
"e": 2766,
"s": 2507,
"text": null
},
{
"code": null,
"e": 2774,
"s": 2766,
"text": "74 days"
},
{
"code": null,
"e": 2787,
"s": 2776,
"text": "chirags_30"
},
{
"code": null,
"e": 2801,
"s": 2787,
"text": "tanishkthomas"
},
{
"code": null,
"e": 2819,
"s": 2801,
"text": "date-time-program"
},
{
"code": null,
"e": 2826,
"s": 2819,
"text": "Python"
},
{
"code": null,
"e": 2842,
"s": 2826,
"text": "Python Programs"
},
{
"code": null,
"e": 2940,
"s": 2842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2982,
"s": 2940,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3004,
"s": 2982,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3036,
"s": 3004,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3065,
"s": 3036,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3092,
"s": 3065,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3114,
"s": 3092,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3153,
"s": 3114,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3191,
"s": 3153,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3228,
"s": 3191,
"text": "Python Program for Fibonacci numbers"
}
]
|
Delete a Git Branch Locally and Remotely | 23 Jun, 2021
It is common for a git repo to have different branches. They are a good way to work on different features and fixes while isolating the new code from the main codebase. Repos often have a master branch or a main branch for the main codebase and developers create other branches with names of their choice (or as required by the organization) to work on different features or fixes. Most of the time you might have to delete a git branch, because of some irreversible changes, security issues, or when a particular feature of the related project has been built. In most cases, it is simple to delete a git branch. In this article, I’ll guide you through the entire process of how to delete a git branch securely. To get started I have already created a new branch in my repo using:
git checkout -b <branch-name>
Here <branch-name> is test. To check which is the current working branch you can use the git branch command.
we can see that we are in the test branch
and the following is a snapshot of my Github repository with the test branch in the remote.
Git won’t allow you to delete the branch you are currently working on. So you must make sure to checkout to a branch that you are NOT deleting. For this use the command:
git checkout <branch-name>
Here we will check out our main branch from my test branch.
Now in order to delete the test branch locally, we use the command :
git branch -d <branch-name>
We will delete my test branch as an example.
Note: The -d option will delete the branch only if it has already been pushed and merged with the remote branch. If you want to forcefully delete a branch you will have to use the -D option instead. The -D flag is synonymous with –delete –force. This will forcefully delete the branch even if it hasn’t been pushed or merged with the remote. the full command is:
git branch -D <branch-name>
With this, we can successfully delete a local branch.
You can’t use the git branch command to delete a remote branch. Instead, you have to use the git push command with the –delete flag, followed by the name of the branch that we want to delete. You also need to specify the remote name (origin in this case) after “git push”. The command is as follows:
git push <remote-name> --delete <branch-name>
Here I will delete my test branch in my remote repository as shown below.
This command will delete the branch remotely. You can also use the shorthand:
git push <remote-name> :<branch-name>
As you can see my remote branch is no more in my GitHub repo:
With this, we have successfully deleted our remote branch. A common error faced by many in this step is:
error: unable to push to unqualified destination: remoteBranchName The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref. error: failed to push some refs to ‘git@repository_name’
This means that someone has already deleted the branch that you want to delete. If this happens you can use the following command to synchronize your branch list in the local environment:
git fetch -p
The -p flag here means “prune”. After fetching the branches which no longer exist in remote will be deleted in your local working environment.
Picked
Git
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 810,
"s": 28,
"text": "It is common for a git repo to have different branches. They are a good way to work on different features and fixes while isolating the new code from the main codebase. Repos often have a master branch or a main branch for the main codebase and developers create other branches with names of their choice (or as required by the organization) to work on different features or fixes. Most of the time you might have to delete a git branch, because of some irreversible changes, security issues, or when a particular feature of the related project has been built. In most cases, it is simple to delete a git branch. In this article, I’ll guide you through the entire process of how to delete a git branch securely. To get started I have already created a new branch in my repo using:"
},
{
"code": null,
"e": 841,
"s": 810,
"text": "git checkout -b <branch-name> "
},
{
"code": null,
"e": 950,
"s": 841,
"text": "Here <branch-name> is test. To check which is the current working branch you can use the git branch command."
},
{
"code": null,
"e": 992,
"s": 950,
"text": "we can see that we are in the test branch"
},
{
"code": null,
"e": 1084,
"s": 992,
"text": "and the following is a snapshot of my Github repository with the test branch in the remote."
},
{
"code": null,
"e": 1254,
"s": 1084,
"text": "Git won’t allow you to delete the branch you are currently working on. So you must make sure to checkout to a branch that you are NOT deleting. For this use the command:"
},
{
"code": null,
"e": 1281,
"s": 1254,
"text": "git checkout <branch-name>"
},
{
"code": null,
"e": 1341,
"s": 1281,
"text": "Here we will check out our main branch from my test branch."
},
{
"code": null,
"e": 1410,
"s": 1341,
"text": "Now in order to delete the test branch locally, we use the command :"
},
{
"code": null,
"e": 1438,
"s": 1410,
"text": "git branch -d <branch-name>"
},
{
"code": null,
"e": 1483,
"s": 1438,
"text": "We will delete my test branch as an example."
},
{
"code": null,
"e": 1846,
"s": 1483,
"text": "Note: The -d option will delete the branch only if it has already been pushed and merged with the remote branch. If you want to forcefully delete a branch you will have to use the -D option instead. The -D flag is synonymous with –delete –force. This will forcefully delete the branch even if it hasn’t been pushed or merged with the remote. the full command is:"
},
{
"code": null,
"e": 1874,
"s": 1846,
"text": "git branch -D <branch-name>"
},
{
"code": null,
"e": 1928,
"s": 1874,
"text": "With this, we can successfully delete a local branch."
},
{
"code": null,
"e": 2228,
"s": 1928,
"text": "You can’t use the git branch command to delete a remote branch. Instead, you have to use the git push command with the –delete flag, followed by the name of the branch that we want to delete. You also need to specify the remote name (origin in this case) after “git push”. The command is as follows:"
},
{
"code": null,
"e": 2274,
"s": 2228,
"text": "git push <remote-name> --delete <branch-name>"
},
{
"code": null,
"e": 2348,
"s": 2274,
"text": "Here I will delete my test branch in my remote repository as shown below."
},
{
"code": null,
"e": 2426,
"s": 2348,
"text": "This command will delete the branch remotely. You can also use the shorthand:"
},
{
"code": null,
"e": 2464,
"s": 2426,
"text": "git push <remote-name> :<branch-name>"
},
{
"code": null,
"e": 2526,
"s": 2464,
"text": "As you can see my remote branch is no more in my GitHub repo:"
},
{
"code": null,
"e": 2631,
"s": 2526,
"text": "With this, we have successfully deleted our remote branch. A common error faced by many in this step is:"
},
{
"code": null,
"e": 2909,
"s": 2631,
"text": "error: unable to push to unqualified destination: remoteBranchName The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref. error: failed to push some refs to ‘git@repository_name’"
},
{
"code": null,
"e": 3097,
"s": 2909,
"text": "This means that someone has already deleted the branch that you want to delete. If this happens you can use the following command to synchronize your branch list in the local environment:"
},
{
"code": null,
"e": 3110,
"s": 3097,
"text": "git fetch -p"
},
{
"code": null,
"e": 3254,
"s": 3110,
"text": "The -p flag here means “prune”. After fetching the branches which no longer exist in remote will be deleted in your local working environment. "
},
{
"code": null,
"e": 3261,
"s": 3254,
"text": "Picked"
},
{
"code": null,
"e": 3265,
"s": 3261,
"text": "Git"
}
]
|
TextView widget in Android using Java with Examples | 01 Oct, 2021
Widget refers to the elements of the UI (User Interface) that helps user interacts with the Android App. TextView is one of many such widgets which can be used to improve the UI of the app.
TextView refers to the widget which displays some text on the screen based on the layout, size, colour, etc set for that particular TextView. It optionally allows us to modify or edit itself as well.
Class Syntax:
public class TextView
extends View
implements ViewTreeObserver.OnPreDrawListener
Class Hierarchy:
java.lang.Object
↳ android.view.View
↳ android.widget.TextView
Syntax:
<SomeLayout>
.
.
<TextView>
android:SomeAttribute1 = "Value of attribute1"
android:SomeAttribute2 = "Value of attribute2"
.
.
android:SomeAttributeN = "Value of attributeN"
</TextView>
.
.
</SomeLayout>
Here the layout can be any layout like Relative, Linear, etc (Refer this article to learn more about layouts). And the attributes can be many among the table given below in this article.
Example:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view_id"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="GeeksforGeeks" />
</LinearLayout>
How to include a TextView in an Android App:
First of all, create a new Android app, or take an existing app to edit it. In both the case, there must be an XML layout activity file and a Java class file linked to this activity.Open the Activity file and include a TextView in this file. The code for the TextView will be:
Now in the Java file, link this layout file with the below code:@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
where activity_main is the name of the layout file to be attached.In the Java file, we will try to change the Text displayed on the TextView upon touching along with a Toast message.The complete code of the layout file and the Java file is given below.
First of all, create a new Android app, or take an existing app to edit it. In both the case, there must be an XML layout activity file and a Java class file linked to this activity.
Open the Activity file and include a TextView in this file. The code for the TextView will be:
Now in the Java file, link this layout file with the below code:@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
where activity_main is the name of the layout file to be attached.
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
where activity_main is the name of the layout file to be attached.
In the Java file, we will try to change the Text displayed on the TextView upon touching along with a Toast message.
The complete code of the layout file and the Java file is given below.
Below is the implementation of the above approach:
activity_main.xml
MainActivity.java
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:gravity="center"> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome To" android:textSize="26sp" android:textStyle="bold" android:textColor="@color/colorPrimary" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </RelativeLayout>
package com.project.textview; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.TextView;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Creating the instance of the TextView created private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Linking the activity file to this Java file setContentView(R.layout.activity_main); // Get the TextView with the id // mentioned in the layout file textView = (TextView)findViewById(R.id.textview); // Try to change the text of the Textview upon touch // and also display a Toast message textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Changing text textView.setText("GeeksforGeeks"); // Displaying Toast message Toast .makeText(MainActivity.this, "Welcome to GeeksforGeeks", Toast.LENGTH_SHORT) .show(); } }); }}
Output:
khushboogoyal499
android
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 243,
"s": 53,
"text": "Widget refers to the elements of the UI (User Interface) that helps user interacts with the Android App. TextView is one of many such widgets which can be used to improve the UI of the app."
},
{
"code": null,
"e": 443,
"s": 243,
"text": "TextView refers to the widget which displays some text on the screen based on the layout, size, colour, etc set for that particular TextView. It optionally allows us to modify or edit itself as well."
},
{
"code": null,
"e": 457,
"s": 443,
"text": "Class Syntax:"
},
{
"code": null,
"e": 544,
"s": 457,
"text": "public class TextView\n extends View \n implements ViewTreeObserver.OnPreDrawListener\n"
},
{
"code": null,
"e": 561,
"s": 544,
"text": "Class Hierarchy:"
},
{
"code": null,
"e": 632,
"s": 561,
"text": "java.lang.Object\n ↳ android.view.View\n ↳ android.widget.TextView\n"
},
{
"code": null,
"e": 640,
"s": 632,
"text": "Syntax:"
},
{
"code": null,
"e": 908,
"s": 640,
"text": "<SomeLayout>\n .\n .\n <TextView>\n android:SomeAttribute1 = \"Value of attribute1\"\n android:SomeAttribute2 = \"Value of attribute2\"\n .\n .\n android:SomeAttributeN = \"Value of attributeN\"\n </TextView>\n .\n .\n</SomeLayout>\n"
},
{
"code": null,
"e": 1095,
"s": 908,
"text": "Here the layout can be any layout like Relative, Linear, etc (Refer this article to learn more about layouts). And the attributes can be many among the table given below in this article."
},
{
"code": null,
"e": 1104,
"s": 1095,
"text": "Example:"
},
{
"code": null,
"e": 1472,
"s": 1104,
"text": " <LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n\n <TextView\n android:id=\"@+id/text_view_id\"\n android:layout_height=\"wrap_content\"\n android:layout_width=\"wrap_content\"\n android:text=\"GeeksforGeeks\" />\n\n </LinearLayout>\n"
},
{
"code": null,
"e": 1517,
"s": 1472,
"text": "How to include a TextView in an Android App:"
},
{
"code": null,
"e": 2260,
"s": 1517,
"text": "First of all, create a new Android app, or take an existing app to edit it. In both the case, there must be an XML layout activity file and a Java class file linked to this activity.Open the Activity file and include a TextView in this file. The code for the TextView will be:\nNow in the Java file, link this layout file with the below code:@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n}\nwhere activity_main is the name of the layout file to be attached.In the Java file, we will try to change the Text displayed on the TextView upon touching along with a Toast message.The complete code of the layout file and the Java file is given below."
},
{
"code": null,
"e": 2443,
"s": 2260,
"text": "First of all, create a new Android app, or take an existing app to edit it. In both the case, there must be an XML layout activity file and a Java class file linked to this activity."
},
{
"code": null,
"e": 2539,
"s": 2443,
"text": "Open the Activity file and include a TextView in this file. The code for the TextView will be:\n"
},
{
"code": null,
"e": 2821,
"s": 2541,
"text": "Now in the Java file, link this layout file with the below code:@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n}\nwhere activity_main is the name of the layout file to be attached."
},
{
"code": null,
"e": 2971,
"s": 2821,
"text": "@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n}\n"
},
{
"code": null,
"e": 3038,
"s": 2971,
"text": "where activity_main is the name of the layout file to be attached."
},
{
"code": null,
"e": 3155,
"s": 3038,
"text": "In the Java file, we will try to change the Text displayed on the TextView upon touching along with a Toast message."
},
{
"code": null,
"e": 3226,
"s": 3155,
"text": "The complete code of the layout file and the Java file is given below."
},
{
"code": null,
"e": 3277,
"s": 3226,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3295,
"s": 3277,
"text": "activity_main.xml"
},
{
"code": null,
"e": 3313,
"s": 3295,
"text": "MainActivity.java"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" android:gravity=\"center\"> <TextView android:id=\"@+id/textview\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Welcome To\" android:textSize=\"26sp\" android:textStyle=\"bold\" android:textColor=\"@color/colorPrimary\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </RelativeLayout>",
"e": 4186,
"s": 3313,
"text": null
},
{
"code": "package com.project.textview; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.TextView;import android.widget.Toast; public class MainActivity extends AppCompatActivity { // Creating the instance of the TextView created private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Linking the activity file to this Java file setContentView(R.layout.activity_main); // Get the TextView with the id // mentioned in the layout file textView = (TextView)findViewById(R.id.textview); // Try to change the text of the Textview upon touch // and also display a Toast message textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Changing text textView.setText(\"GeeksforGeeks\"); // Displaying Toast message Toast .makeText(MainActivity.this, \"Welcome to GeeksforGeeks\", Toast.LENGTH_SHORT) .show(); } }); }}",
"e": 5477,
"s": 4186,
"text": null
},
{
"code": null,
"e": 5485,
"s": 5477,
"text": "Output:"
},
{
"code": null,
"e": 5502,
"s": 5485,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 5510,
"s": 5502,
"text": "android"
},
{
"code": null,
"e": 5523,
"s": 5510,
"text": "Android-View"
},
{
"code": null,
"e": 5531,
"s": 5523,
"text": "Android"
},
{
"code": null,
"e": 5536,
"s": 5531,
"text": "Java"
},
{
"code": null,
"e": 5541,
"s": 5536,
"text": "Java"
},
{
"code": null,
"e": 5549,
"s": 5541,
"text": "Android"
}
]
|
Generate all cyclic permutations of a number | 03 May, 2022
Given a number N, our task is to generate all the possible cyclic permutations of the number. A cyclic permutation shifts all the elements of a set by a fixed offset. For a set with elements , , ..., , a cyclic permutation of one place to the left would yield , ..., , , and a cyclic permutation of one place to the right would yield , , , ....Examples:
Input : 123
Output : 123
312
231
Input : 5674
Output : 5674
4567
7456
6745
The idea is to generate next permutation of a number using below formula.
rem = num % 10;
div = num / 10;
num = (pow(10, n - 1)) * rem + div;
While repeating above steps, if we come back to original number, we stop and return.
C++
Java
Python3
C#
PHP
Javascript
// Program to generate all cyclic permutations// of number#include <bits/stdc++.h>using namespace std; // Function to count the total number of digits// in a number.int countdigits(int N){ int count = 0; while (N) { count++; N = N / 10; } return count;} // Function to generate all cyclic permutations// of a numbervoid cyclic(int N){ int num = N; int n = countdigits(N); while (1) { cout << num << endl; // Following three lines generates a // circular permutation of a number. int rem = num % 10; int div = num / 10; num = (pow(10, n - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; }} // Driver Programint main(){ int N = 5674; cyclic(N); return 0;}
// Java Program to generate all// cyclic permutations of numberclass GFG{ // Function to count the total number // of digits in a number. static int countdigits(int N) { int count = 0; while (N>0) { count++; N = N / 10; } return count; } // Function to generate all cyclic // permutations of a number static void cyclic(int N) { int num = N; int n = countdigits(N); while (true) { System.out.println(num); // Following three lines generates a // circular permutation of a number. int rem = num % 10; int dev = num / 10; num = (int)((Math.pow(10, n - 1)) * rem + dev); // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) break; } } // Driver Program public static void main (String[] args) { int N = 5674; cyclic(N); }} /* This code is contributed by Mr. Somesh Awasthi */
# Python3 Program to# generate all cyclic# permutations of numberimport math # Function to count the# total number of digits# in a number.def countdigits(N): count = 0; while (N): count = count + 1; N = int(math.floor(N / 10)); return count; # Function to generate# all cyclic permutations# of a numberdef cyclic(N): num = N; n = countdigits(N); while (1): print(int(num)); # Following three lines # generates a circular # permutation of a number. rem = num % 10; div = math.floor(num / 10); num = ((math.pow(10, n - 1)) * rem + div); # If all the permutations # are checked and we obtain # original number exit from loop. if (num == N): break; # Driver CodeN = 5674;cyclic(N); # This code is contributed by mits
// C# Program to generate all// cyclic permutations of numberusing System; class GFG{ // Function to count the total number // of digits in a number. static int countdigits(int N) { int count = 0; while (N > 0) { count++; N = N / 10; } return count; } // Function to generate all cyclic // permutations of a number static void cyclic(int N) { int num = N; int n = countdigits(N); while (true) { Console.WriteLine(num); // Following three lines generates a // circular permutation of a number. int rem = num % 10; int dev = num / 10; num = (int)((Math.Pow(10, n - 1)) * rem + dev); // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) break; } } // Driver Program public static void Main () { int N = 5674; cyclic(N); }} // This code is contributed by nitin mittal
<?php// PHP Program to generate all// cyclic permutations of number // Function to count the total// number of digits in a number.function countdigits($N){ $count = 0; while ($N) { $count++; $N = floor($N / 10); } return $count;} // Function to generate all// cyclic permutations of a numberfunction cyclic($N){ $num = $N; $n = countdigits($N); while (1) { echo ($num); echo "\n" ; // Following three lines generates a // circular permutation of a number. $rem = $num % 10; $div = floor($num / 10); $num = (pow(10, $n - 1)) * $rem + $div; // If all the permutations are checked // and we obtain original number exit // from loop. if ($num == $N) break; }} // Driver Code $N = 5674; cyclic($N); // This code is contributed by nitin mittal?>
<script> // javascript Program to generate all// cyclic permutations of number // Function to count the total number// of digits in a number. function countdigits(N){ var count = 0; while (N>0) { count++; N = parseInt(N / 10); } return count;} // Function to generate all cyclic// permutations of a numberfunction cyclic(N){ var num = N; var n = countdigits(N); while (true) { document.write(num+"<br>"); // Following three lines generates a // circular permutation of a number. var rem = num % 10; var dev = parseInt(num / 10); num = parseInt(((Math.pow(10, n - 1)) * rem + dev)); // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) break; }} // Driver Programvar N = 5674;cyclic(N); // This code is contributed by Amit Katiyar</script>
Output:
5674
4567
7456
6745
Time Complexity: O(N), where N is the number of digitsAuxiliary Space: O(1)
This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Mithun Kumar
amit143katiyar
singhh3010
simmytarika5
number-digits
Combinatorial
Mathematical
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 May, 2022"
},
{
"code": null,
"e": 409,
"s": 53,
"text": "Given a number N, our task is to generate all the possible cyclic permutations of the number. A cyclic permutation shifts all the elements of a set by a fixed offset. For a set with elements , , ..., , a cyclic permutation of one place to the left would yield , ..., , , and a cyclic permutation of one place to the right would yield , , , ....Examples: "
},
{
"code": null,
"e": 532,
"s": 409,
"text": "Input : 123\nOutput : 123\n 312\n 231\n\nInput : 5674\nOutput : 5674\n 4567\n 7456\n 6745"
},
{
"code": null,
"e": 610,
"s": 534,
"text": "The idea is to generate next permutation of a number using below formula. "
},
{
"code": null,
"e": 690,
"s": 610,
"text": " rem = num % 10;\n div = num / 10;\n num = (pow(10, n - 1)) * rem + div;"
},
{
"code": null,
"e": 777,
"s": 690,
"text": "While repeating above steps, if we come back to original number, we stop and return. "
},
{
"code": null,
"e": 781,
"s": 777,
"text": "C++"
},
{
"code": null,
"e": 786,
"s": 781,
"text": "Java"
},
{
"code": null,
"e": 794,
"s": 786,
"text": "Python3"
},
{
"code": null,
"e": 797,
"s": 794,
"text": "C#"
},
{
"code": null,
"e": 801,
"s": 797,
"text": "PHP"
},
{
"code": null,
"e": 812,
"s": 801,
"text": "Javascript"
},
{
"code": "// Program to generate all cyclic permutations// of number#include <bits/stdc++.h>using namespace std; // Function to count the total number of digits// in a number.int countdigits(int N){ int count = 0; while (N) { count++; N = N / 10; } return count;} // Function to generate all cyclic permutations// of a numbervoid cyclic(int N){ int num = N; int n = countdigits(N); while (1) { cout << num << endl; // Following three lines generates a // circular permutation of a number. int rem = num % 10; int div = num / 10; num = (pow(10, n - 1)) * rem + div; // If all the permutations are checked // and we obtain original number exit // from loop. if (num == N) break; }} // Driver Programint main(){ int N = 5674; cyclic(N); return 0;}",
"e": 1685,
"s": 812,
"text": null
},
{
"code": "// Java Program to generate all// cyclic permutations of numberclass GFG{ // Function to count the total number // of digits in a number. static int countdigits(int N) { int count = 0; while (N>0) { count++; N = N / 10; } return count; } // Function to generate all cyclic // permutations of a number static void cyclic(int N) { int num = N; int n = countdigits(N); while (true) { System.out.println(num); // Following three lines generates a // circular permutation of a number. int rem = num % 10; int dev = num / 10; num = (int)((Math.pow(10, n - 1)) * rem + dev); // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) break; } } // Driver Program public static void main (String[] args) { int N = 5674; cyclic(N); }} /* This code is contributed by Mr. Somesh Awasthi */",
"e": 2795,
"s": 1685,
"text": null
},
{
"code": "# Python3 Program to# generate all cyclic# permutations of numberimport math # Function to count the# total number of digits# in a number.def countdigits(N): count = 0; while (N): count = count + 1; N = int(math.floor(N / 10)); return count; # Function to generate# all cyclic permutations# of a numberdef cyclic(N): num = N; n = countdigits(N); while (1): print(int(num)); # Following three lines # generates a circular # permutation of a number. rem = num % 10; div = math.floor(num / 10); num = ((math.pow(10, n - 1)) * rem + div); # If all the permutations # are checked and we obtain # original number exit from loop. if (num == N): break; # Driver CodeN = 5674;cyclic(N); # This code is contributed by mits",
"e": 3688,
"s": 2795,
"text": null
},
{
"code": "// C# Program to generate all// cyclic permutations of numberusing System; class GFG{ // Function to count the total number // of digits in a number. static int countdigits(int N) { int count = 0; while (N > 0) { count++; N = N / 10; } return count; } // Function to generate all cyclic // permutations of a number static void cyclic(int N) { int num = N; int n = countdigits(N); while (true) { Console.WriteLine(num); // Following three lines generates a // circular permutation of a number. int rem = num % 10; int dev = num / 10; num = (int)((Math.Pow(10, n - 1)) * rem + dev); // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) break; } } // Driver Program public static void Main () { int N = 5674; cyclic(N); }} // This code is contributed by nitin mittal",
"e": 4799,
"s": 3688,
"text": null
},
{
"code": "<?php// PHP Program to generate all// cyclic permutations of number // Function to count the total// number of digits in a number.function countdigits($N){ $count = 0; while ($N) { $count++; $N = floor($N / 10); } return $count;} // Function to generate all// cyclic permutations of a numberfunction cyclic($N){ $num = $N; $n = countdigits($N); while (1) { echo ($num); echo \"\\n\" ; // Following three lines generates a // circular permutation of a number. $rem = $num % 10; $div = floor($num / 10); $num = (pow(10, $n - 1)) * $rem + $div; // If all the permutations are checked // and we obtain original number exit // from loop. if ($num == $N) break; }} // Driver Code $N = 5674; cyclic($N); // This code is contributed by nitin mittal?>",
"e": 5696,
"s": 4799,
"text": null
},
{
"code": "<script> // javascript Program to generate all// cyclic permutations of number // Function to count the total number// of digits in a number. function countdigits(N){ var count = 0; while (N>0) { count++; N = parseInt(N / 10); } return count;} // Function to generate all cyclic// permutations of a numberfunction cyclic(N){ var num = N; var n = countdigits(N); while (true) { document.write(num+\"<br>\"); // Following three lines generates a // circular permutation of a number. var rem = num % 10; var dev = parseInt(num / 10); num = parseInt(((Math.pow(10, n - 1)) * rem + dev)); // If all the permutations are // checked and we obtain original // number exit from loop. if (num == N) break; }} // Driver Programvar N = 5674;cyclic(N); // This code is contributed by Amit Katiyar</script>",
"e": 6637,
"s": 5696,
"text": null
},
{
"code": null,
"e": 6647,
"s": 6637,
"text": "Output: "
},
{
"code": null,
"e": 6671,
"s": 6647,
"text": " 5674\n 4567\n 7456\n 6745"
},
{
"code": null,
"e": 6749,
"s": 6671,
"text": "Time Complexity: O(N), where N is the number of digitsAuxiliary Space: O(1) "
},
{
"code": null,
"e": 7170,
"s": 6749,
"text": "This article is contributed by Vineet Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7183,
"s": 7170,
"text": "nitin mittal"
},
{
"code": null,
"e": 7196,
"s": 7183,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7211,
"s": 7196,
"text": "amit143katiyar"
},
{
"code": null,
"e": 7222,
"s": 7211,
"text": "singhh3010"
},
{
"code": null,
"e": 7235,
"s": 7222,
"text": "simmytarika5"
},
{
"code": null,
"e": 7249,
"s": 7235,
"text": "number-digits"
},
{
"code": null,
"e": 7263,
"s": 7249,
"text": "Combinatorial"
},
{
"code": null,
"e": 7276,
"s": 7263,
"text": "Mathematical"
},
{
"code": null,
"e": 7289,
"s": 7276,
"text": "Mathematical"
},
{
"code": null,
"e": 7303,
"s": 7289,
"text": "Combinatorial"
}
]
|
Data Structures | Binary Search Trees | Question 1 | 02 Feb, 2013
What is the worst case time complexity for search, insert and delete operations in a general Binary Search Tree?(A) O(n) for all(B) O(Logn) for all(C) O(Logn) for search and insert, and O(n) for delete(D) O(Logn) for search, and O(n) for insert and deleteAnswer: (A)Explanation: In skewed Binary Search Tree (BST), all three operations can take O(n). See the following example BST and operations.
10
/
20
/
30
/
40
Search 40.
Delete 40
Insert 50.
Binary Search Trees
Data Structures
Data Structures-Binary Search Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2013"
},
{
"code": null,
"e": 425,
"s": 28,
"text": "What is the worst case time complexity for search, insert and delete operations in a general Binary Search Tree?(A) O(n) for all(B) O(Logn) for all(C) O(Logn) for search and insert, and O(n) for delete(D) O(Logn) for search, and O(n) for insert and deleteAnswer: (A)Explanation: In skewed Binary Search Tree (BST), all three operations can take O(n). See the following example BST and operations."
},
{
"code": null,
"e": 522,
"s": 425,
"text": " 10\n /\n 20\n /\n 30\n / \n 40\n\nSearch 40. \nDelete 40\nInsert 50.\n"
},
{
"code": null,
"e": 542,
"s": 522,
"text": "Binary Search Trees"
},
{
"code": null,
"e": 558,
"s": 542,
"text": "Data Structures"
},
{
"code": null,
"e": 594,
"s": 558,
"text": "Data Structures-Binary Search Trees"
},
{
"code": null,
"e": 610,
"s": 594,
"text": "Data Structures"
},
{
"code": null,
"e": 626,
"s": 610,
"text": "Data Structures"
}
]
|
Bootstrap .form-control-static class | Use the class .form-control-static on a <p> when you need to place plain text next to a form label within a horizontal form.
You can try to run the following code to implement the .form-control-static class −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<form class = "form-horizontal" role = "form">
<div class = "form-group">
<label class = "col-sm-2 control-label">Email:</label>
<div class = "col-sm-10">
<p class = "form-control-static">[email protected]</p>
</div>
</div>
<div class = "form-group">
<label for = "inputPassword" class = "col-sm-2 control-label">Password:</label>
<div class = "col-sm-10">
<input type = "password" class = "form-control" id = "inputPassword" placeholder = "Password">
</div>
</div>
</form>
</body>
</html> | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "Use the class .form-control-static on a <p> when you need to place plain text next to a form label within a horizontal form."
},
{
"code": null,
"e": 1271,
"s": 1187,
"text": "You can try to run the following code to implement the .form-control-static class −"
},
{
"code": null,
"e": 1281,
"s": 1271,
"text": "Live Demo"
},
{
"code": null,
"e": 2413,
"s": 1281,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <form class = \"form-horizontal\" role = \"form\">\n <div class = \"form-group\">\n <label class = \"col-sm-2 control-label\">Email:</label>\n <div class = \"col-sm-10\">\n <p class = \"form-control-static\">[email protected]</p>\n </div>\n </div>\n <div class = \"form-group\">\n <label for = \"inputPassword\" class = \"col-sm-2 control-label\">Password:</label>\n <div class = \"col-sm-10\">\n <input type = \"password\" class = \"form-control\" id = \"inputPassword\" placeholder = \"Password\">\n </div>\n </div>\n </form>\n </body>\n</html>"
}
]
|
What are unreachable catch blocks in Java? | A block of statements to which the control can never reach under any case can be called as unreachable blocks. Unreachable blocks are not supported by Java. The catch block mentioned with the reference of Exception class should and must be always last catch block because Exception is the superclass of all exceptions. When we are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e subclasses of Exception must come first and superclasses later. If we keep superclasses first and subclasses later, the compiler will throw an unreachable catch block error.
try {
// statements
} catch(Exception e) {
System.out.println(e);
} catch(NumberFormatException nfe) { //unreachable block. Not supported by Java, leads to an error.
System.out.println(nfe);
}
A catch clause is considered reachable by the compiler if both of the following conditions are true
A checked exception that is thrown in the try block is assignable to the parameter of C.
There is no previous catch clause whose parameter type is equal to or a supertype of the parameter type of C
A catch clause is considered reachable by the compiler can be unreachable if both of the following conditions are true
The catch clause parameter type E does not include any unchecked exceptions.
All exceptions that are thrown in the try block whose type is a (strict) subtype of E are already handled by previous catch clauses.
Live Demo
public class UnreachableBlock{
public static void main(String[] args) {
try {
int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
} catch(NumberFormatException nfe) {
System.out.println("This block handles NumberFormatException");
} catch(Exception e) {
System.out.println("This block handles all exception types");
} catch (Throwable t) {
System.out.println("Throwable is super class of Exception");
}
}
}
This block handles NumberFormatException | [
{
"code": null,
"e": 1677,
"s": 1062,
"text": "A block of statements to which the control can never reach under any case can be called as unreachable blocks. Unreachable blocks are not supported by Java. The catch block mentioned with the reference of Exception class should and must be always last catch block because Exception is the superclass of all exceptions. When we are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones. i.e subclasses of Exception must come first and superclasses later. If we keep superclasses first and subclasses later, the compiler will throw an unreachable catch block error."
},
{
"code": null,
"e": 1879,
"s": 1677,
"text": "try {\n // statements\n} catch(Exception e) {\n System.out.println(e);\n} catch(NumberFormatException nfe) { //unreachable block. Not supported by Java, leads to an error.\n System.out.println(nfe);\n}"
},
{
"code": null,
"e": 1979,
"s": 1879,
"text": "A catch clause is considered reachable by the compiler if both of the following conditions are true"
},
{
"code": null,
"e": 2068,
"s": 1979,
"text": "A checked exception that is thrown in the try block is assignable to the parameter of C."
},
{
"code": null,
"e": 2177,
"s": 2068,
"text": "There is no previous catch clause whose parameter type is equal to or a supertype of the parameter type of C"
},
{
"code": null,
"e": 2296,
"s": 2177,
"text": "A catch clause is considered reachable by the compiler can be unreachable if both of the following conditions are true"
},
{
"code": null,
"e": 2373,
"s": 2296,
"text": "The catch clause parameter type E does not include any unchecked exceptions."
},
{
"code": null,
"e": 2506,
"s": 2373,
"text": "All exceptions that are thrown in the try block whose type is a (strict) subtype of E are already handled by previous catch clauses."
},
{
"code": null,
"e": 2516,
"s": 2506,
"text": "Live Demo"
},
{
"code": null,
"e": 3022,
"s": 2516,
"text": "public class UnreachableBlock{\n public static void main(String[] args) {\n try {\n int i = Integer.parseInt(\"abc\"); //This statement throws NumberFormatException\n } catch(NumberFormatException nfe) {\n System.out.println(\"This block handles NumberFormatException\");\n } catch(Exception e) {\n System.out.println(\"This block handles all exception types\");\n } catch (Throwable t) {\n System.out.println(\"Throwable is super class of Exception\");\n }\n }\n}"
},
{
"code": null,
"e": 3063,
"s": 3022,
"text": "This block handles NumberFormatException"
}
]
|
Create a New Maven Project from Command Prompt - GeeksforGeeks | 14 Dec, 2020
Maven is a powerful project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT.In short, maven is a tool that can be used for building and managing any Java-based project. Maven makes the day-to-day work of Java developers easier and generally help with the comprehension of any Java-based project.
Steps for creating a New Maven Project from Command Prompt:
Step 1: Open Run and type ‘cmd‘ to open Command Prompt.
Step 2: Using ‘cd’ command, you have to browse to the folder where you want to set up your project and then type the below command:
mvn archetype:generate -DgroupId=ToolsQA -DartifactId=DemoMavenProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
In the above command, you are using ‘DartifactId‘ i.e. your project name and ‘DarchetypeArtifactId‘ is the type of Maven project. There are different types of maven projects like web projects, java projects, etc.
Once you press Enter after typing the above command, it will start creating the Maven project
Step 3: After successfully building, once go to the project location to see the newly created maven project. Now open the pom.xml file, which resides in the project folder. By default, the POM is generated like this:
HTML
<!---contributed by sambhav228------><project xmlns="https://maven.apache.org/POM/3.2.3"xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/3.2.3 http://maven.apache.org/maven-v3_2_3.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ToolsQA</groupId> <artifactId>DemoMavenProject</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>DemoMavenProject</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies></project>
Step 4: In the folder structure of the Maven project you can find your DemoMavenProject.
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
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 redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to pass data from child component to its parent in ReactJS ?
How to execute PHP code using command line ?
REST API (Introduction) | [
{
"code": null,
"e": 24525,
"s": 24497,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 24974,
"s": 24525,
"text": "Maven is a powerful project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT.In short, maven is a tool that can be used for building and managing any Java-based project. Maven makes the day-to-day work of Java developers easier and generally help with the comprehension of any Java-based project."
},
{
"code": null,
"e": 25034,
"s": 24974,
"text": "Steps for creating a New Maven Project from Command Prompt:"
},
{
"code": null,
"e": 25090,
"s": 25034,
"text": "Step 1: Open Run and type ‘cmd‘ to open Command Prompt."
},
{
"code": null,
"e": 25222,
"s": 25090,
"text": "Step 2: Using ‘cd’ command, you have to browse to the folder where you want to set up your project and then type the below command:"
},
{
"code": null,
"e": 25366,
"s": 25222,
"text": "mvn archetype:generate -DgroupId=ToolsQA -DartifactId=DemoMavenProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false"
},
{
"code": null,
"e": 25579,
"s": 25366,
"text": "In the above command, you are using ‘DartifactId‘ i.e. your project name and ‘DarchetypeArtifactId‘ is the type of Maven project. There are different types of maven projects like web projects, java projects, etc."
},
{
"code": null,
"e": 25673,
"s": 25579,
"text": "Once you press Enter after typing the above command, it will start creating the Maven project"
},
{
"code": null,
"e": 25890,
"s": 25673,
"text": "Step 3: After successfully building, once go to the project location to see the newly created maven project. Now open the pom.xml file, which resides in the project folder. By default, the POM is generated like this:"
},
{
"code": null,
"e": 25895,
"s": 25890,
"text": "HTML"
},
{
"code": "<!---contributed by sambhav228------><project xmlns=\"https://maven.apache.org/POM/3.2.3\"xmlns:xsi=\"https://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"https://maven.apache.org/POM/3.2.3 http://maven.apache.org/maven-v3_2_3.xsd\"> <modelVersion>4.0.0</modelVersion> <groupId>ToolsQA</groupId> <artifactId>DemoMavenProject</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>DemoMavenProject</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies></project>",
"e": 26621,
"s": 25895,
"text": null
},
{
"code": null,
"e": 26710,
"s": 26621,
"text": "Step 4: In the folder structure of the Maven project you can find your DemoMavenProject."
},
{
"code": null,
"e": 26727,
"s": 26710,
"text": "Web Technologies"
},
{
"code": null,
"e": 26825,
"s": 26727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26834,
"s": 26825,
"text": "Comments"
},
{
"code": null,
"e": 26847,
"s": 26834,
"text": "Old Comments"
},
{
"code": null,
"e": 26903,
"s": 26847,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26946,
"s": 26903,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27007,
"s": 26946,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27052,
"s": 27007,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27124,
"s": 27052,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27169,
"s": 27124,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 27219,
"s": 27169,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27284,
"s": 27219,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 27329,
"s": 27284,
"text": "How to execute PHP code using command line ?"
}
]
|
Chef - Overview | Chef is an open source technology developed by Opscode. Adam Jacob, co-founder of Opscode is known as the founder of Chef. This technology uses Ruby encoding to develop basic building blocks like recipe and cookbooks. Chef is used in infrastructure automation and helps in reducing manual and repetitive tasks for infrastructure management.
Chef have got its own convention for different building blocks, which are required to manage and automate infrastructure.
Chef is a configuration management technology used to automate the infrastructure provisioning. It is developed on the basis of Ruby DSL language. It is used to streamline the task of configuration and managing the company’s server. It has the capability to get integrated with any of the cloud technology.
In DevOps, we use Chef to deploy and manage servers and applications in-house and on the cloud.
Following are the most prominent features of Chef −
Chef uses popular Ruby language to create a domain-specific language.
Chef uses popular Ruby language to create a domain-specific language.
Chef does not make assumptions on the current status of a node. It uses its mechanisms to get the current status of machine.
Chef does not make assumptions on the current status of a node. It uses its mechanisms to get the current status of machine.
Chef is ideal for deploying and managing the cloud server, storage, and software.
Chef is ideal for deploying and managing the cloud server, storage, and software.
Chef offers the following advantages −
Lower barrier for entry − As Chef uses native Ruby language for configuration, a standard configuration language it can be easily picked up by anyone having some development experience.
Lower barrier for entry − As Chef uses native Ruby language for configuration, a standard configuration language it can be easily picked up by anyone having some development experience.
Excellent integration with cloud − Using the knife utility, it can be easily integrated with any of the cloud technologies. It is the best tool for an organization that wishes to distribute its infrastructure on multi-cloud environment.
Excellent integration with cloud − Using the knife utility, it can be easily integrated with any of the cloud technologies. It is the best tool for an organization that wishes to distribute its infrastructure on multi-cloud environment.
Some of the major drawbacks of Chef are as follows −
One of the huge disadvantages of Chef is the way cookbooks are controlled. It needs constant babying so that people who are working should not mess up with others cookbooks.
One of the huge disadvantages of Chef is the way cookbooks are controlled. It needs constant babying so that people who are working should not mess up with others cookbooks.
Only Chef solo is available.
Only Chef solo is available.
In the current situation, it is only a good fit for AWS cloud.
In the current situation, it is only a good fit for AWS cloud.
It is not very easy to learn if the person is not familiar with Ruby.
It is not very easy to learn if the person is not familiar with Ruby.
Documentation is still lacking.
Documentation is still lacking.
It can be defined as a collection of attributes which are used to manage the infrastructure. These attributes which are present in the recipe are used to change the existing state or setting a particular infrastructure node. They are loaded during Chef client run and comparted with the existing attribute of the node (machine). It then gets to the status which is defined in the node resource of the recipe. It is the main workhorse of the cookbook.
A cookbook is a collection of recipes. They are the basic building blocks which get uploaded to Chef server. When Chef run takes place, it ensures that the recipes present inside it gets a given infrastructure to the desired state as listed in the recipe.
It is the basic component of a recipe used to manage the infrastructure with different kind of states. There can be multiple resources in a recipe, which will help in configuring and managing the infrastructure. For example −
package − Manages the packages on a node
package − Manages the packages on a node
service − Manages the services on a node
service − Manages the services on a node
user − Manages the users on the node
user − Manages the users on the node
group − Manages groups
group − Manages groups
template − Manages the files with embedded Ruby template
template − Manages the files with embedded Ruby template
cookbook_file − Transfers the files from the files subdirectory in the cookbook to a location on the node
cookbook_file − Transfers the files from the files subdirectory in the cookbook to a location on the node
file − Manages the contents of a file on the node
file − Manages the contents of a file on the node
directory − Manages the directories on the node
directory − Manages the directories on the node
execute − Executes a command on the node
execute − Executes a command on the node
cron − Edits an existing cron file on the node
cron − Edits an existing cron file on the node
They are basically settings. They can be thought of as a key value pair of anything which one wants to use in the cookbook. There are several different kinds of attributes that can be applied, with a different level of precedence over the final settings that the node operates under.
It’s a subdirectory within the cookbook that contains any static file which will be placed on the nodes that uses the cookbooks. A recipe then can be declared as a resource that moves the files from that directory to the final node.
They are similar to files, but they are not static. Template files end with the .ebr extension, which means they contain embedded Ruby. They are mainly used to substitute an attribute value into the files to create the final file version that will be placed on the node.
It is used to manage the metadata about the package. This includes details like the name and details of the package. It also includes things such as dependency information that tells which cookbooks this cookbook needs to operate. This allows the Chef server to build the run-list of the node correctly and ensures that all of the pieces are transferred correctly.
C:\chef\cookbooks\nginx>tree
Folder PATH listing for volume Local Disk
Volume serial number is BE8B-6427
C: ├───attributes
├───definitions
├───files
│ └───default
├───libraries
├───providers
├───recipes
├───resources
└───templates
└───default
Following is the list of Chef related technologies.
Puppet provides a standard way of delivering and operating software, no matter where it runs. It is an automated administrative engine for Linux, Unix, and Windows system that performs administrative tasks based on centralized specification.
The primary features of Puppet are as follows −
Implementing new systems with a uniform configuration.
Updating the systems and upgrading the security and software packages.
Incorporating new features and adding dexterous capabilities.
Customizing configurations for ensuring the availability of data sources.
Optimizing the available resources and minimizing the cost.
Simplifying the roles and enabling the team to focus on core and productive issues.
Getting a bird’s eye view of the available infrastructure.
Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications — automate in a language that approaches plain English, using SSH, with no agents to install on remote systems.
The primary features of Ansible are as follows −
Simple and easy to learn
Written in Python
Agentless
YAML-based Playbooks
Ansible galaxy
SaltStack is used for data-driven configuration. It is a new approach of infrastructure management built on dynamic communication bus. It is used for data-driven orchestration, remote execution for any infrastructure, and configuration management for any app stack.
Fabric is a Python-based programming language, which is developed as an API of Python which needs to be imported in Python code in order to configure and manage an infrastructure.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2721,
"s": 2380,
"text": "Chef is an open source technology developed by Opscode. Adam Jacob, co-founder of Opscode is known as the founder of Chef. This technology uses Ruby encoding to develop basic building blocks like recipe and cookbooks. Chef is used in infrastructure automation and helps in reducing manual and repetitive tasks for infrastructure management."
},
{
"code": null,
"e": 2843,
"s": 2721,
"text": "Chef have got its own convention for different building blocks, which are required to manage and automate infrastructure."
},
{
"code": null,
"e": 3150,
"s": 2843,
"text": "Chef is a configuration management technology used to automate the infrastructure provisioning. It is developed on the basis of Ruby DSL language. It is used to streamline the task of configuration and managing the company’s server. It has the capability to get integrated with any of the cloud technology."
},
{
"code": null,
"e": 3246,
"s": 3150,
"text": "In DevOps, we use Chef to deploy and manage servers and applications in-house and on the cloud."
},
{
"code": null,
"e": 3298,
"s": 3246,
"text": "Following are the most prominent features of Chef −"
},
{
"code": null,
"e": 3368,
"s": 3298,
"text": "Chef uses popular Ruby language to create a domain-specific language."
},
{
"code": null,
"e": 3438,
"s": 3368,
"text": "Chef uses popular Ruby language to create a domain-specific language."
},
{
"code": null,
"e": 3563,
"s": 3438,
"text": "Chef does not make assumptions on the current status of a node. It uses its mechanisms to get the current status of machine."
},
{
"code": null,
"e": 3688,
"s": 3563,
"text": "Chef does not make assumptions on the current status of a node. It uses its mechanisms to get the current status of machine."
},
{
"code": null,
"e": 3770,
"s": 3688,
"text": "Chef is ideal for deploying and managing the cloud server, storage, and software."
},
{
"code": null,
"e": 3852,
"s": 3770,
"text": "Chef is ideal for deploying and managing the cloud server, storage, and software."
},
{
"code": null,
"e": 3891,
"s": 3852,
"text": "Chef offers the following advantages −"
},
{
"code": null,
"e": 4077,
"s": 3891,
"text": "Lower barrier for entry − As Chef uses native Ruby language for configuration, a standard configuration language it can be easily picked up by anyone having some development experience."
},
{
"code": null,
"e": 4263,
"s": 4077,
"text": "Lower barrier for entry − As Chef uses native Ruby language for configuration, a standard configuration language it can be easily picked up by anyone having some development experience."
},
{
"code": null,
"e": 4500,
"s": 4263,
"text": "Excellent integration with cloud − Using the knife utility, it can be easily integrated with any of the cloud technologies. It is the best tool for an organization that wishes to distribute its infrastructure on multi-cloud environment."
},
{
"code": null,
"e": 4737,
"s": 4500,
"text": "Excellent integration with cloud − Using the knife utility, it can be easily integrated with any of the cloud technologies. It is the best tool for an organization that wishes to distribute its infrastructure on multi-cloud environment."
},
{
"code": null,
"e": 4790,
"s": 4737,
"text": "Some of the major drawbacks of Chef are as follows −"
},
{
"code": null,
"e": 4964,
"s": 4790,
"text": "One of the huge disadvantages of Chef is the way cookbooks are controlled. It needs constant babying so that people who are working should not mess up with others cookbooks."
},
{
"code": null,
"e": 5138,
"s": 4964,
"text": "One of the huge disadvantages of Chef is the way cookbooks are controlled. It needs constant babying so that people who are working should not mess up with others cookbooks."
},
{
"code": null,
"e": 5167,
"s": 5138,
"text": "Only Chef solo is available."
},
{
"code": null,
"e": 5196,
"s": 5167,
"text": "Only Chef solo is available."
},
{
"code": null,
"e": 5259,
"s": 5196,
"text": "In the current situation, it is only a good fit for AWS cloud."
},
{
"code": null,
"e": 5322,
"s": 5259,
"text": "In the current situation, it is only a good fit for AWS cloud."
},
{
"code": null,
"e": 5392,
"s": 5322,
"text": "It is not very easy to learn if the person is not familiar with Ruby."
},
{
"code": null,
"e": 5462,
"s": 5392,
"text": "It is not very easy to learn if the person is not familiar with Ruby."
},
{
"code": null,
"e": 5494,
"s": 5462,
"text": "Documentation is still lacking."
},
{
"code": null,
"e": 5526,
"s": 5494,
"text": "Documentation is still lacking."
},
{
"code": null,
"e": 5977,
"s": 5526,
"text": "It can be defined as a collection of attributes which are used to manage the infrastructure. These attributes which are present in the recipe are used to change the existing state or setting a particular infrastructure node. They are loaded during Chef client run and comparted with the existing attribute of the node (machine). It then gets to the status which is defined in the node resource of the recipe. It is the main workhorse of the cookbook."
},
{
"code": null,
"e": 6233,
"s": 5977,
"text": "A cookbook is a collection of recipes. They are the basic building blocks which get uploaded to Chef server. When Chef run takes place, it ensures that the recipes present inside it gets a given infrastructure to the desired state as listed in the recipe."
},
{
"code": null,
"e": 6459,
"s": 6233,
"text": "It is the basic component of a recipe used to manage the infrastructure with different kind of states. There can be multiple resources in a recipe, which will help in configuring and managing the infrastructure. For example −"
},
{
"code": null,
"e": 6500,
"s": 6459,
"text": "package − Manages the packages on a node"
},
{
"code": null,
"e": 6541,
"s": 6500,
"text": "package − Manages the packages on a node"
},
{
"code": null,
"e": 6582,
"s": 6541,
"text": "service − Manages the services on a node"
},
{
"code": null,
"e": 6623,
"s": 6582,
"text": "service − Manages the services on a node"
},
{
"code": null,
"e": 6660,
"s": 6623,
"text": "user − Manages the users on the node"
},
{
"code": null,
"e": 6697,
"s": 6660,
"text": "user − Manages the users on the node"
},
{
"code": null,
"e": 6720,
"s": 6697,
"text": "group − Manages groups"
},
{
"code": null,
"e": 6743,
"s": 6720,
"text": "group − Manages groups"
},
{
"code": null,
"e": 6800,
"s": 6743,
"text": "template − Manages the files with embedded Ruby template"
},
{
"code": null,
"e": 6857,
"s": 6800,
"text": "template − Manages the files with embedded Ruby template"
},
{
"code": null,
"e": 6963,
"s": 6857,
"text": "cookbook_file − Transfers the files from the files subdirectory in the cookbook to a location on the node"
},
{
"code": null,
"e": 7069,
"s": 6963,
"text": "cookbook_file − Transfers the files from the files subdirectory in the cookbook to a location on the node"
},
{
"code": null,
"e": 7119,
"s": 7069,
"text": "file − Manages the contents of a file on the node"
},
{
"code": null,
"e": 7169,
"s": 7119,
"text": "file − Manages the contents of a file on the node"
},
{
"code": null,
"e": 7217,
"s": 7169,
"text": "directory − Manages the directories on the node"
},
{
"code": null,
"e": 7265,
"s": 7217,
"text": "directory − Manages the directories on the node"
},
{
"code": null,
"e": 7306,
"s": 7265,
"text": "execute − Executes a command on the node"
},
{
"code": null,
"e": 7347,
"s": 7306,
"text": "execute − Executes a command on the node"
},
{
"code": null,
"e": 7394,
"s": 7347,
"text": "cron − Edits an existing cron file on the node"
},
{
"code": null,
"e": 7441,
"s": 7394,
"text": "cron − Edits an existing cron file on the node"
},
{
"code": null,
"e": 7725,
"s": 7441,
"text": "They are basically settings. They can be thought of as a key value pair of anything which one wants to use in the cookbook. There are several different kinds of attributes that can be applied, with a different level of precedence over the final settings that the node operates under."
},
{
"code": null,
"e": 7958,
"s": 7725,
"text": "It’s a subdirectory within the cookbook that contains any static file which will be placed on the nodes that uses the cookbooks. A recipe then can be declared as a resource that moves the files from that directory to the final node."
},
{
"code": null,
"e": 8229,
"s": 7958,
"text": "They are similar to files, but they are not static. Template files end with the .ebr extension, which means they contain embedded Ruby. They are mainly used to substitute an attribute value into the files to create the final file version that will be placed on the node."
},
{
"code": null,
"e": 8594,
"s": 8229,
"text": "It is used to manage the metadata about the package. This includes details like the name and details of the package. It also includes things such as dependency information that tells which cookbooks this cookbook needs to operate. This allows the Chef server to build the run-list of the node correctly and ensures that all of the pieces are transferred correctly."
},
{
"code": null,
"e": 8857,
"s": 8594,
"text": "C:\\chef\\cookbooks\\nginx>tree \nFolder PATH listing for volume Local Disk \nVolume serial number is BE8B-6427 \nC: ├───attributes \n├───definitions \n├───files \n│ └───default \n├───libraries \n├───providers \n├───recipes \n├───resources \n└───templates \n └───default \n"
},
{
"code": null,
"e": 8909,
"s": 8857,
"text": "Following is the list of Chef related technologies."
},
{
"code": null,
"e": 9151,
"s": 8909,
"text": "Puppet provides a standard way of delivering and operating software, no matter where it runs. It is an automated administrative engine for Linux, Unix, and Windows system that performs administrative tasks based on centralized specification."
},
{
"code": null,
"e": 9199,
"s": 9151,
"text": "The primary features of Puppet are as follows −"
},
{
"code": null,
"e": 9254,
"s": 9199,
"text": "Implementing new systems with a uniform configuration."
},
{
"code": null,
"e": 9325,
"s": 9254,
"text": "Updating the systems and upgrading the security and software packages."
},
{
"code": null,
"e": 9387,
"s": 9325,
"text": "Incorporating new features and adding dexterous capabilities."
},
{
"code": null,
"e": 9461,
"s": 9387,
"text": "Customizing configurations for ensuring the availability of data sources."
},
{
"code": null,
"e": 9521,
"s": 9461,
"text": "Optimizing the available resources and minimizing the cost."
},
{
"code": null,
"e": 9605,
"s": 9521,
"text": "Simplifying the roles and enabling the team to focus on core and productive issues."
},
{
"code": null,
"e": 9664,
"s": 9605,
"text": "Getting a bird’s eye view of the available infrastructure."
},
{
"code": null,
"e": 9964,
"s": 9664,
"text": "Ansible is a radically simple IT automation platform that makes your applications and systems easier to deploy. Avoid writing scripts or custom code to deploy and update your applications — automate in a language that approaches plain English, using SSH, with no agents to install on remote systems."
},
{
"code": null,
"e": 10013,
"s": 9964,
"text": "The primary features of Ansible are as follows −"
},
{
"code": null,
"e": 10038,
"s": 10013,
"text": "Simple and easy to learn"
},
{
"code": null,
"e": 10056,
"s": 10038,
"text": "Written in Python"
},
{
"code": null,
"e": 10066,
"s": 10056,
"text": "Agentless"
},
{
"code": null,
"e": 10087,
"s": 10066,
"text": "YAML-based Playbooks"
},
{
"code": null,
"e": 10102,
"s": 10087,
"text": "Ansible galaxy"
},
{
"code": null,
"e": 10368,
"s": 10102,
"text": "SaltStack is used for data-driven configuration. It is a new approach of infrastructure management built on dynamic communication bus. It is used for data-driven orchestration, remote execution for any infrastructure, and configuration management for any app stack."
},
{
"code": null,
"e": 10548,
"s": 10368,
"text": "Fabric is a Python-based programming language, which is developed as an API of Python which needs to be imported in Python code in order to configure and manage an infrastructure."
},
{
"code": null,
"e": 10555,
"s": 10548,
"text": " Print"
},
{
"code": null,
"e": 10566,
"s": 10555,
"text": " Add Notes"
}
]
|
Count Leaves in Binary Tree | Practice | GeeksforGeeks | Given a Binary Tree of size N , You have to count leaves in it. For example, there are two leaves in following tree
1
/ \
10 39
/
5
Example 1:
Input:
Given Tree is
4
/ \
8 10
/ / \
7 5 1
/
3
Output:
3
Explanation:
Three leaves are 3 , 5 and 1.
Your Task:
You don't have to take input. Complete the function countLeaves() that takes root node of given tree as parameter and returns the count of leaves in tree . The printing is done by the driver code.
Constraints:
1<= N <= 104
Note:The Input/Ouput format and Example given below is used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console, and should not print anything on stdout/console. The task is to complete the function specified, and not to write the full code.
0
kashifahmad5993 days ago
When I submit the code, it's showing wrong answer for test case 3 4 2 but when I run this test case in custom input the output I get is correct.
int c=0;int count(Node* root){ if(root==NULL) return 0; int lh = count(root->left); int rh = count(root->right); if(lh==0 && rh==0) { c++; } return root->data;}int countLeaves(Node* root){ count(root); return c;}
0
yaswa7792 weeks ago
Why some test cases are not running
int x=0,y=0;int countLeaves(Node* root){ if(root){ x = countLeaves(root->left); y = countLeaves(root->right); return x+y+1; } return 0; }
0
harshscode2 weeks ago
int cnt=0; if(!root) return cnt; cnt=(!root->left && !root->right)?(cnt=cnt+1):(countLeaves(root->left)+countLeaves(root->right)); return cnt;
0
bheniavedant2 weeks ago
Can anyone show me, a non recursive approach for this question in python?
0
shailendramaheshwari172 weeks ago
C++
int countLeaves(Node* root)
{
// Your code here
if(root == NULL) return 0;
int left = countLeaves(root->left);
int right = countLeaves(root->right);
if(left == 0 && right == 0) return (left+right+1);
return (left+right);
}
0
anshsangwan1232 weeks ago
if(root->left ==NULL && root->right==NULL){ count++;}
0
anshulgupta966263 weeks ago
queue<Node*> q;
int count = 0;
q.push(root);
while(!q.empty()){
Node *front = q.front();
q.pop();
if(front->left == NULL && front->right == NULL){
count++;
}
if(front->left != NULL){
q.push(front->left);
}
if(front->right != NULL){
q.push(front->right);
}
}
return count;
0
dipanshusharma93133 weeks ago
// java solution
class Tree{ static int x = 0; int countLeaves(Node node) { // Your code if(node == null){ return 0; } int x = 0; if(node.left == null && node.right == null){ x++; } x = x + countLeaves(node.left); x = x + countLeaves(node.right); return x; }}
0
shubhamtripathy3 weeks ago
Easy Python Approach
def countLeaves(root):
# Code here
if root is None:
return 0
if root.left is None and root.right is None:
return 1
return countLeaves(root.left)+countLeaves(root.right)
0
00thirt13n3 weeks ago
C++ Solution:
int countLeaves(Node* root){
if(!root) return 0;
if(!root->left && !root->right) return 1;
return countLeaves(root->left)+countLeaves(root->right);
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 354,
"s": 238,
"text": "Given a Binary Tree of size N , You have to count leaves in it. For example, there are two leaves in following tree"
},
{
"code": null,
"e": 401,
"s": 354,
"text": " 1\n / \\\n 10 39\n /\n5\n\n "
},
{
"code": null,
"e": 412,
"s": 401,
"text": "Example 1:"
},
{
"code": null,
"e": 615,
"s": 412,
"text": "\nInput:\nGiven Tree is \n 4\n / \\\n 8 10\n / / \\\n 7 5 1\n /\n 3 \nOutput:\n3\nExplanation: \nThree leaves are 3 , 5 and 1."
},
{
"code": null,
"e": 827,
"s": 617,
"text": "Your Task:\nYou don't have to take input. Complete the function countLeaves() that takes root node of given tree as parameter and returns the count of leaves in tree . The printing is done by the driver code.\n "
},
{
"code": null,
"e": 853,
"s": 827,
"text": "Constraints:\n1<= N <= 104"
},
{
"code": null,
"e": 1218,
"s": 855,
"text": "Note:The Input/Ouput format and Example given below is used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console, and should not print anything on stdout/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1220,
"s": 1218,
"text": "0"
},
{
"code": null,
"e": 1245,
"s": 1220,
"text": "kashifahmad5993 days ago"
},
{
"code": null,
"e": 1390,
"s": 1245,
"text": "When I submit the code, it's showing wrong answer for test case 3 4 2 but when I run this test case in custom input the output I get is correct."
},
{
"code": null,
"e": 1651,
"s": 1392,
"text": " int c=0;int count(Node* root){ if(root==NULL) return 0; int lh = count(root->left); int rh = count(root->right); if(lh==0 && rh==0) { c++; } return root->data;}int countLeaves(Node* root){ count(root); return c;}"
},
{
"code": null,
"e": 1653,
"s": 1651,
"text": "0"
},
{
"code": null,
"e": 1673,
"s": 1653,
"text": "yaswa7792 weeks ago"
},
{
"code": null,
"e": 1709,
"s": 1673,
"text": "Why some test cases are not running"
},
{
"code": null,
"e": 1871,
"s": 1709,
"text": "int x=0,y=0;int countLeaves(Node* root){ if(root){ x = countLeaves(root->left); y = countLeaves(root->right); return x+y+1; } return 0; }"
},
{
"code": null,
"e": 1873,
"s": 1871,
"text": "0"
},
{
"code": null,
"e": 1895,
"s": 1873,
"text": "harshscode2 weeks ago"
},
{
"code": null,
"e": 2046,
"s": 1895,
"text": "int cnt=0; if(!root) return cnt; cnt=(!root->left && !root->right)?(cnt=cnt+1):(countLeaves(root->left)+countLeaves(root->right)); return cnt;"
},
{
"code": null,
"e": 2048,
"s": 2046,
"text": "0"
},
{
"code": null,
"e": 2072,
"s": 2048,
"text": "bheniavedant2 weeks ago"
},
{
"code": null,
"e": 2147,
"s": 2072,
"text": "Can anyone show me, a non recursive approach for this question in python? "
},
{
"code": null,
"e": 2149,
"s": 2147,
"text": "0"
},
{
"code": null,
"e": 2183,
"s": 2149,
"text": "shailendramaheshwari172 weeks ago"
},
{
"code": null,
"e": 2416,
"s": 2183,
"text": "C++\nint countLeaves(Node* root)\n{\n // Your code here\n if(root == NULL) return 0;\n int left = countLeaves(root->left);\n int right = countLeaves(root->right);\n if(left == 0 && right == 0) return (left+right+1);\n return (left+right);\n}"
},
{
"code": null,
"e": 2418,
"s": 2416,
"text": "0"
},
{
"code": null,
"e": 2444,
"s": 2418,
"text": "anshsangwan1232 weeks ago"
},
{
"code": null,
"e": 2498,
"s": 2444,
"text": "if(root->left ==NULL && root->right==NULL){ count++;}"
},
{
"code": null,
"e": 2500,
"s": 2498,
"text": "0"
},
{
"code": null,
"e": 2528,
"s": 2500,
"text": "anshulgupta966263 weeks ago"
},
{
"code": null,
"e": 2939,
"s": 2528,
"text": "queue<Node*> q;\n int count = 0;\n q.push(root);\n while(!q.empty()){\n Node *front = q.front();\n q.pop();\n \n if(front->left == NULL && front->right == NULL){\n count++;\n }\n \n if(front->left != NULL){\n q.push(front->left);\n }\n if(front->right != NULL){\n q.push(front->right);\n }\n }\n return count; "
},
{
"code": null,
"e": 2941,
"s": 2939,
"text": "0"
},
{
"code": null,
"e": 2971,
"s": 2941,
"text": "dipanshusharma93133 weeks ago"
},
{
"code": null,
"e": 2988,
"s": 2971,
"text": "// java solution"
},
{
"code": null,
"e": 3326,
"s": 2988,
"text": "class Tree{ static int x = 0; int countLeaves(Node node) { // Your code if(node == null){ return 0; } int x = 0; if(node.left == null && node.right == null){ x++; } x = x + countLeaves(node.left); x = x + countLeaves(node.right); return x; }}"
},
{
"code": null,
"e": 3328,
"s": 3326,
"text": "0"
},
{
"code": null,
"e": 3355,
"s": 3328,
"text": "shubhamtripathy3 weeks ago"
},
{
"code": null,
"e": 3376,
"s": 3355,
"text": "Easy Python Approach"
},
{
"code": null,
"e": 3577,
"s": 3378,
"text": "def countLeaves(root):\n # Code here\n if root is None:\n return 0\n if root.left is None and root.right is None:\n return 1\n \n return countLeaves(root.left)+countLeaves(root.right)"
},
{
"code": null,
"e": 3579,
"s": 3577,
"text": "0"
},
{
"code": null,
"e": 3601,
"s": 3579,
"text": "00thirt13n3 weeks ago"
},
{
"code": null,
"e": 3615,
"s": 3601,
"text": "C++ Solution:"
},
{
"code": null,
"e": 3771,
"s": 3615,
"text": "int countLeaves(Node* root){\n if(!root) return 0;\n if(!root->left && !root->right) return 1;\n return countLeaves(root->left)+countLeaves(root->right);\n}"
},
{
"code": null,
"e": 3917,
"s": 3771,
"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": 3953,
"s": 3917,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3963,
"s": 3953,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3973,
"s": 3963,
"text": "\nContest\n"
},
{
"code": null,
"e": 4036,
"s": 3973,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4184,
"s": 4036,
"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": 4392,
"s": 4184,
"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": 4498,
"s": 4392,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
C# Program For Hierarchical Inheritance - GeeksforGeeks | 30 Sep, 2021
Inheritance is a basic aspect of object-oriented programming. A superclass, also known as a base class, is a class whose members are inherited, whereas a subclass, also known as a derived class, is a class that inherits from a superclass. They are also known as the parent and child classes, respectively. In the same way that a child inherits the traits of his or her parents, and parents inherit the characteristics of their predecessors, inheritance in programming languages works in the same way.
It is a way of transmitting features from a parent class to a base, child, or subclass in terms of technical terms and the object-oriented aspect. The parent class or superclass is the class from which the properties are taken, i.e. the features are inherited. Hierarchical inheritance describes a situation in which a parent class is inherited by multiple subclasses. A type of inheritance in which more than one class is inherited from a single parent or base class is known as hierarchical inheritance. The base class shares many of the same properties as the parent class, especially those that are common in the parent class. A single base class gives rise to many classes. It’s like having several children, each with their own set of characteristics acquired from their parents. For example, In the diagram below, class A acts as the base class(parent class) for the child classes B, C, and D.
Example 1:
The base class in the following example is Father, and the derived classes are ChildFirst and ChildSecond. We’ve created objects from both derived classes and are calling the same base class function.
C#
// C# program to illustrate the above conceptusing System; // Base Classpublic class Father { public string FatherName() { return "Ravi"; }} // Derived Classpublic class ChildFirst : Father { public string ChildDName() { return "Rohan"; }} // Derived Classpublic class ChildSecond : Father { public string ChildDName() { return "Nikhil"; }} class GFG{ static public void Main(){ ChildFirst first = new ChildFirst(); // Displaying Child Name and Father Name for // ChildFirst Console.WriteLine("My name is " + first.ChildDName() + ". My father name is " + first.FatherName() + "."); ChildSecond second = new ChildSecond(); // Displaying Child Name and Father Name for // ChildSecond Console.WriteLine("My name is " + second.ChildDName() + ". My father name is " + second.FatherName() + ".");}}
My name is Rohan. My father name is Ravi.
My name is Nikhil. My father name is Ravi.
Example 2:
In the following code, we created three classes: Person, Teacher, and Doctor. In this example, the Person class was inherited by both the Teacher and Doctor classes. A constructor in every class is used to initialize data members. Then we created Teacher and Doctor objects and used TeacherDetails() and DoctorDetails() to produce information for the Teacher and Doctor respectively.
C#
// C# program to illustrate the above conceptusing System; // Base Classclass Person { public string name; public int aadhar_id; public int age; public Person(int aadhar_id, int age, string name) { this.aadhar_id = aadhar_id; this.name = name; this.age = age; }} // Derived Classclass Teacher : Person { public int teacher_salary; public Teacher(int aadhar_id, int salary, string name, int age) : base(aadhar_id, age, name) { teacher_salary = salary; } public void TeacherDetails() { Console.WriteLine("teacher ID: " + aadhar_id); Console.WriteLine("teacher Name: " + name); Console.WriteLine("teacher Salary: " + teacher_salary); Console.WriteLine("teacher Age: " + age); }} // Derived Classclass Doctor : Person { public int doctor_fees; public Doctor(int aadhar_id, int fees, string name, int age) : base(aadhar_id, age, name) { doctor_fees = fees; } public void DoctorDetails() { Console.WriteLine("Doctor ID: " + aadhar_id); Console.WriteLine("Doctor Name: " + name); Console.WriteLine("Doctor Fees: " + doctor_fees); Console.WriteLine("Doctor Age: " + age); }} class GFG{ static public void Main(){ // Creating objects Teacher t = new Teacher(25054, 50000, "Sanjay", 28); Doctor d = new Doctor(25045, 750, "Rohit", 32); t.TeacherDetails(); Console.WriteLine( "-----------------------------------"); d.DoctorDetails();}}
teacher ID: 25054
teacher Name: Sanjay
teacher Salary: 50000
teacher Age: 28
-----------------------------------
Doctor ID: 25045
Doctor Name: Rohit
Doctor Fees: 750
Doctor Age: 32
CSharp-Inheritance
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
C# | List Class
Partial Classes in C#
Convert String to Character Array in C#
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 24803,
"s": 24302,
"text": "Inheritance is a basic aspect of object-oriented programming. A superclass, also known as a base class, is a class whose members are inherited, whereas a subclass, also known as a derived class, is a class that inherits from a superclass. They are also known as the parent and child classes, respectively. In the same way that a child inherits the traits of his or her parents, and parents inherit the characteristics of their predecessors, inheritance in programming languages works in the same way."
},
{
"code": null,
"e": 25704,
"s": 24803,
"text": "It is a way of transmitting features from a parent class to a base, child, or subclass in terms of technical terms and the object-oriented aspect. The parent class or superclass is the class from which the properties are taken, i.e. the features are inherited. Hierarchical inheritance describes a situation in which a parent class is inherited by multiple subclasses. A type of inheritance in which more than one class is inherited from a single parent or base class is known as hierarchical inheritance. The base class shares many of the same properties as the parent class, especially those that are common in the parent class. A single base class gives rise to many classes. It’s like having several children, each with their own set of characteristics acquired from their parents. For example, In the diagram below, class A acts as the base class(parent class) for the child classes B, C, and D."
},
{
"code": null,
"e": 25715,
"s": 25704,
"text": "Example 1:"
},
{
"code": null,
"e": 25916,
"s": 25715,
"text": "The base class in the following example is Father, and the derived classes are ChildFirst and ChildSecond. We’ve created objects from both derived classes and are calling the same base class function."
},
{
"code": null,
"e": 25919,
"s": 25916,
"text": "C#"
},
{
"code": "// C# program to illustrate the above conceptusing System; // Base Classpublic class Father { public string FatherName() { return \"Ravi\"; }} // Derived Classpublic class ChildFirst : Father { public string ChildDName() { return \"Rohan\"; }} // Derived Classpublic class ChildSecond : Father { public string ChildDName() { return \"Nikhil\"; }} class GFG{ static public void Main(){ ChildFirst first = new ChildFirst(); // Displaying Child Name and Father Name for // ChildFirst Console.WriteLine(\"My name is \" + first.ChildDName() + \". My father name is \" + first.FatherName() + \".\"); ChildSecond second = new ChildSecond(); // Displaying Child Name and Father Name for // ChildSecond Console.WriteLine(\"My name is \" + second.ChildDName() + \". My father name is \" + second.FatherName() + \".\");}}",
"e": 26898,
"s": 25919,
"text": null
},
{
"code": null,
"e": 26983,
"s": 26898,
"text": "My name is Rohan. My father name is Ravi.\nMy name is Nikhil. My father name is Ravi."
},
{
"code": null,
"e": 26994,
"s": 26983,
"text": "Example 2:"
},
{
"code": null,
"e": 27378,
"s": 26994,
"text": "In the following code, we created three classes: Person, Teacher, and Doctor. In this example, the Person class was inherited by both the Teacher and Doctor classes. A constructor in every class is used to initialize data members. Then we created Teacher and Doctor objects and used TeacherDetails() and DoctorDetails() to produce information for the Teacher and Doctor respectively."
},
{
"code": null,
"e": 27381,
"s": 27378,
"text": "C#"
},
{
"code": "// C# program to illustrate the above conceptusing System; // Base Classclass Person { public string name; public int aadhar_id; public int age; public Person(int aadhar_id, int age, string name) { this.aadhar_id = aadhar_id; this.name = name; this.age = age; }} // Derived Classclass Teacher : Person { public int teacher_salary; public Teacher(int aadhar_id, int salary, string name, int age) : base(aadhar_id, age, name) { teacher_salary = salary; } public void TeacherDetails() { Console.WriteLine(\"teacher ID: \" + aadhar_id); Console.WriteLine(\"teacher Name: \" + name); Console.WriteLine(\"teacher Salary: \" + teacher_salary); Console.WriteLine(\"teacher Age: \" + age); }} // Derived Classclass Doctor : Person { public int doctor_fees; public Doctor(int aadhar_id, int fees, string name, int age) : base(aadhar_id, age, name) { doctor_fees = fees; } public void DoctorDetails() { Console.WriteLine(\"Doctor ID: \" + aadhar_id); Console.WriteLine(\"Doctor Name: \" + name); Console.WriteLine(\"Doctor Fees: \" + doctor_fees); Console.WriteLine(\"Doctor Age: \" + age); }} class GFG{ static public void Main(){ // Creating objects Teacher t = new Teacher(25054, 50000, \"Sanjay\", 28); Doctor d = new Doctor(25045, 750, \"Rohit\", 32); t.TeacherDetails(); Console.WriteLine( \"-----------------------------------\"); d.DoctorDetails();}}",
"e": 29066,
"s": 27381,
"text": null
},
{
"code": null,
"e": 29275,
"s": 29066,
"text": "teacher ID: 25054\nteacher Name: Sanjay\nteacher Salary: 50000\nteacher Age: 28\n-----------------------------------\nDoctor ID: 25045\nDoctor Name: Rohit\nDoctor Fees: 750\nDoctor Age: 32"
},
{
"code": null,
"e": 29294,
"s": 29275,
"text": "CSharp-Inheritance"
},
{
"code": null,
"e": 29310,
"s": 29294,
"text": "CSharp-programs"
},
{
"code": null,
"e": 29317,
"s": 29310,
"text": "Picked"
},
{
"code": null,
"e": 29320,
"s": 29317,
"text": "C#"
},
{
"code": null,
"e": 29418,
"s": 29320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29427,
"s": 29418,
"text": "Comments"
},
{
"code": null,
"e": 29440,
"s": 29427,
"text": "Old Comments"
},
{
"code": null,
"e": 29463,
"s": 29440,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29491,
"s": 29463,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29531,
"s": 29491,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29574,
"s": 29531,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 29591,
"s": 29574,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 29607,
"s": 29591,
"text": "C# | List Class"
},
{
"code": null,
"e": 29629,
"s": 29607,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29669,
"s": 29629,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 29694,
"s": 29669,
"text": "Lambda Expressions in C#"
}
]
|
Flask App for Data Science. Data scientists generally work in the... | by Kayli Leung | Towards Data Science | Data scientists generally work in the back end. Building an interactive app is not a strength of mine, but it can be a great way to show off the work that you can do. In this post, I will discuss some tips for creating a Flask App that I have learned while building a website for my Travel Recommendation System.
Before we even start thinking about beautifying our app, you should have all your functions in a separate py file as opposed to within a Jupyter Notebook. This step is necessary as Flask cannot communicate with Jupyter, but it can communicate with py files.
The organization of your repository will be important for deployment to a website. Upon entering your repository there should be a folder that has the same name as the repository. In this folder should be everything that your app will need. For example, a recommend.py was necessary for my app, but a scrape.py was not because it was only used to collect data.
The other file you will need in this folder is __init__.py. This can be an empty file, but this allows the code to be run when the package is imported. Finally, you will need a web_app folder. This folder will contain the files needed to run your app including bootstrap static and template folders.
travel_destination_recommendation travel_destination_recommendation __init__.py recommend.py web_app __init__.py static templates app.py
When you want to run/test your app you will use the following code in the command line while you are in the highest directory:
FLASK_APP = travel_destination_recommendation.web_app.app.py
In app.py you can import your custom functions with:
from ..recommend import custom_functions
In the app.py file is where we import from flask. There are some tools you want to import:
Flask
request (allows for communication with Javascript)
render_template (creates the template from HTML)
jsonify (everything needs to be returned in JSON format)
from flask import Flask, request, render_template, jsonifyapp = Flask(__name__, static_url_path="")
There needs to be something for your app to show up on. This is where your first function will be. Any function that communicates with the HTML, starts with the decorator @app.route(‘/’). Within the parenthesis is the tag of the HTML that we want to interact with. The / on its own represents the homepage.
@app.route('/')def index(): """Return the main page.""" return render_template('theme.html')
I would recommend, especially for a first app, to start without any design. I start with this function. It takes in text from a text box and returns a prediction.
with open('model.pkl', 'rb') as f: model = model.load(f)@app.route('/predict', methods=['GET','POST'])def predict(): """Return a random prediction.""" data = request.json prediction = model.predict_proba([data['user_input']]) return jsonify({'probability': prediction[0][1]})
The piece of code above connects to the following bit of HTML that creates one text box, and a button that is labeled “Predict!”
<html> <head> <title>Predict</title> <script type="text/javascript" src="brython.js"></script> <script type="text/javascript" src="brython_stdlib.js"></script> </head> <body onload="brython(1)"> <script type="text/python3"> from browser import document, ajax import json import warnings def show_results(response): if response.status==200: document["result"].html = response.text else: warnings.warn(response.text) def get_prediction(ev): """Get the predicted probability.""" req = ajax.ajax() req.bind('complete', show_results) req.open('POST', '/predict', True) req.set_header('content-type','application/json') data = json.dumps({'user_input': document['user_input'].value}) req.send(data) document["predict_button"].bind("click", get_prediction) </script> <textarea id="user_input"></textarea> <button id="predict_button">Predict!</button> <div id="result"></div> </body></html>
So that is quite a bit of code. Let’s break it down. The first thing we want to make sure we do is set the script to brython. Brython stands for browser python and allows for the use of python in the Javascript environment. Set this in both the script as well as the body.
In the script of the body is where we want our code to be. We need to have two separate functions to collect data and to show results. In show_results we only want to a result, if one exists. In the if statement, we reference the HTML document’s div id “result” because this is where we want the result to be shown.
In get_predication, we have the parameter ev which means event. This means that the function will be called when a particular event occurs (we’ll come back to this later).
The req.bind(‘complete’, show_results) line connects this function to the show_results function.
The next line req.open(‘POST’, ‘/predict’, True) connects this function to the function we created in our app.py file through the decorator.
The data is what we can communicate to the app.py file. Notice that the results should be dumped into JSON format. There are two “user_input” noted in this line. The one in the dictionary is the key, which is referenced in the app.py function as part of the data. This data is sent to the app.py function through the req.send(data) line. The document[“user_input”] is the id of the text box.
Now that the function is complete, we need to have the event that triggers the function. We want the make a prediction when the predict button is clicked. The last line in the script connects the button with a specific id and binds a “click” to the function get_prediction.
This is a very basic Flask app. By making small changes over time we can create a beautiful app. As a Data Scientist, you don’t need to be a master of web development, but it can be a fun tool to show off what your model can do.
Thanks to my coach for my Flask starting point, check out his Spam predictor here. To check out a detailed Flask app, take a look at my repository. | [
{
"code": null,
"e": 485,
"s": 172,
"text": "Data scientists generally work in the back end. Building an interactive app is not a strength of mine, but it can be a great way to show off the work that you can do. In this post, I will discuss some tips for creating a Flask App that I have learned while building a website for my Travel Recommendation System."
},
{
"code": null,
"e": 743,
"s": 485,
"text": "Before we even start thinking about beautifying our app, you should have all your functions in a separate py file as opposed to within a Jupyter Notebook. This step is necessary as Flask cannot communicate with Jupyter, but it can communicate with py files."
},
{
"code": null,
"e": 1104,
"s": 743,
"text": "The organization of your repository will be important for deployment to a website. Upon entering your repository there should be a folder that has the same name as the repository. In this folder should be everything that your app will need. For example, a recommend.py was necessary for my app, but a scrape.py was not because it was only used to collect data."
},
{
"code": null,
"e": 1404,
"s": 1104,
"text": "The other file you will need in this folder is __init__.py. This can be an empty file, but this allows the code to be run when the package is imported. Finally, you will need a web_app folder. This folder will contain the files needed to run your app including bootstrap static and template folders."
},
{
"code": null,
"e": 1620,
"s": 1404,
"text": "travel_destination_recommendation travel_destination_recommendation __init__.py recommend.py web_app __init__.py static templates app.py"
},
{
"code": null,
"e": 1747,
"s": 1620,
"text": "When you want to run/test your app you will use the following code in the command line while you are in the highest directory:"
},
{
"code": null,
"e": 1808,
"s": 1747,
"text": "FLASK_APP = travel_destination_recommendation.web_app.app.py"
},
{
"code": null,
"e": 1861,
"s": 1808,
"text": "In app.py you can import your custom functions with:"
},
{
"code": null,
"e": 1902,
"s": 1861,
"text": "from ..recommend import custom_functions"
},
{
"code": null,
"e": 1993,
"s": 1902,
"text": "In the app.py file is where we import from flask. There are some tools you want to import:"
},
{
"code": null,
"e": 1999,
"s": 1993,
"text": "Flask"
},
{
"code": null,
"e": 2050,
"s": 1999,
"text": "request (allows for communication with Javascript)"
},
{
"code": null,
"e": 2099,
"s": 2050,
"text": "render_template (creates the template from HTML)"
},
{
"code": null,
"e": 2156,
"s": 2099,
"text": "jsonify (everything needs to be returned in JSON format)"
},
{
"code": null,
"e": 2256,
"s": 2156,
"text": "from flask import Flask, request, render_template, jsonifyapp = Flask(__name__, static_url_path=\"\")"
},
{
"code": null,
"e": 2563,
"s": 2256,
"text": "There needs to be something for your app to show up on. This is where your first function will be. Any function that communicates with the HTML, starts with the decorator @app.route(‘/’). Within the parenthesis is the tag of the HTML that we want to interact with. The / on its own represents the homepage."
},
{
"code": null,
"e": 2662,
"s": 2563,
"text": "@app.route('/')def index(): \"\"\"Return the main page.\"\"\" return render_template('theme.html')"
},
{
"code": null,
"e": 2825,
"s": 2662,
"text": "I would recommend, especially for a first app, to start without any design. I start with this function. It takes in text from a text box and returns a prediction."
},
{
"code": null,
"e": 3137,
"s": 2825,
"text": "with open('model.pkl', 'rb') as f: model = model.load(f)@app.route('/predict', methods=['GET','POST'])def predict(): \"\"\"Return a random prediction.\"\"\" data = request.json prediction = model.predict_proba([data['user_input']]) return jsonify({'probability': prediction[0][1]})"
},
{
"code": null,
"e": 3266,
"s": 3137,
"text": "The piece of code above connects to the following bit of HTML that creates one text box, and a button that is labeled “Predict!”"
},
{
"code": null,
"e": 4483,
"s": 3266,
"text": "<html> <head> <title>Predict</title> <script type=\"text/javascript\" src=\"brython.js\"></script> <script type=\"text/javascript\" src=\"brython_stdlib.js\"></script> </head> <body onload=\"brython(1)\"> <script type=\"text/python3\"> from browser import document, ajax import json import warnings def show_results(response): if response.status==200: document[\"result\"].html = response.text else: warnings.warn(response.text) def get_prediction(ev): \"\"\"Get the predicted probability.\"\"\" req = ajax.ajax() req.bind('complete', show_results) req.open('POST', '/predict', True) req.set_header('content-type','application/json') data = json.dumps({'user_input': document['user_input'].value}) req.send(data) document[\"predict_button\"].bind(\"click\", get_prediction) </script> <textarea id=\"user_input\"></textarea> <button id=\"predict_button\">Predict!</button> <div id=\"result\"></div> </body></html>"
},
{
"code": null,
"e": 4756,
"s": 4483,
"text": "So that is quite a bit of code. Let’s break it down. The first thing we want to make sure we do is set the script to brython. Brython stands for browser python and allows for the use of python in the Javascript environment. Set this in both the script as well as the body."
},
{
"code": null,
"e": 5072,
"s": 4756,
"text": "In the script of the body is where we want our code to be. We need to have two separate functions to collect data and to show results. In show_results we only want to a result, if one exists. In the if statement, we reference the HTML document’s div id “result” because this is where we want the result to be shown."
},
{
"code": null,
"e": 5244,
"s": 5072,
"text": "In get_predication, we have the parameter ev which means event. This means that the function will be called when a particular event occurs (we’ll come back to this later)."
},
{
"code": null,
"e": 5341,
"s": 5244,
"text": "The req.bind(‘complete’, show_results) line connects this function to the show_results function."
},
{
"code": null,
"e": 5482,
"s": 5341,
"text": "The next line req.open(‘POST’, ‘/predict’, True) connects this function to the function we created in our app.py file through the decorator."
},
{
"code": null,
"e": 5874,
"s": 5482,
"text": "The data is what we can communicate to the app.py file. Notice that the results should be dumped into JSON format. There are two “user_input” noted in this line. The one in the dictionary is the key, which is referenced in the app.py function as part of the data. This data is sent to the app.py function through the req.send(data) line. The document[“user_input”] is the id of the text box."
},
{
"code": null,
"e": 6148,
"s": 5874,
"text": "Now that the function is complete, we need to have the event that triggers the function. We want the make a prediction when the predict button is clicked. The last line in the script connects the button with a specific id and binds a “click” to the function get_prediction."
},
{
"code": null,
"e": 6377,
"s": 6148,
"text": "This is a very basic Flask app. By making small changes over time we can create a beautiful app. As a Data Scientist, you don’t need to be a master of web development, but it can be a fun tool to show off what your model can do."
}
]
|
PHP | Spreadsheet_Excel_Writer | setBold() Function - GeeksforGeeks | 04 Oct, 2021
The setBold() function is an inbuilt function in PHP | Spreadsheet_Excel_Writer which is used to set the boldness of the text.
Syntax:
void Format::setBold( $weight = 1 )
Parameters: This function accepts a single parameter $weight which is used to set the weight of the text. The default value of text weight is 1 (700). It ranges from 100 to 1000.
Return Value: This function returns TRUE on success and PEAR_ERROR on failure.
Example 1:
PHP
<?phprequire_once 'Spreadsheet/Excel/Writer.php'; // Create Spreadsheet_Excel_Writer Object$workbook = new Spreadsheet_Excel_Writer(); // Add Worksheet$worksheet =& $workbook->addWorksheet(); // Set Font Family Times New Roman$format_setBold =& $workbook->addFormat();$format_setBold->setFontFamily('Times New Roman'); // Set Bold Property$format_setBold->setBold(); // Set Shadow to text$format_setBold->setShadow(); // Write to Worksheet$worksheet->write(0, 0, "Information");$worksheet->write(1, 0, "Website Name", $format_setBold);$worksheet->write(1, 1, "Address", $format_setBold);$worksheet->write(2, 0, "GeeksforGeeks", $format_setBold);$worksheet->write(2, 1, "https://www.geeksforgeeks.org/", $format_setBold);$workbook->send('test.xls'); $workbook->close();?>
Output:
Example 2:
PHP
<?phprequire_once 'Spreadsheet/Excel/Writer.php'; // Add Workbook$workbook = new Spreadsheet_Excel_Writer(); // Add Format to spreadsheet$format_bold =& $workbook->addFormat(); // Set Bold$format_bold->setBold(); // Add Worksheet to Spreadsheet$worksheet =& $workbook->addWorksheet(); // Write to Worksheet$worksheet->write(0, 0, "Details of GeeksforGeeks Contributors", $format_bold);$worksheet->write(1, 0, "Author", $format_bold);$worksheet->write(1, 1, "User Handle", $format_bold);$worksheet->write(2, 0, "Sarthak", $format_bold);$worksheet->write(2, 1, "sarthak_ishu11", $format_bold); // Send .xlsx file to header$workbook->send('test.xls'); // Close Workbook Object$workbook->close();?>
Output:
Reference: https://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.spreadsheet-excel-writer-format.setbold.php
ruhelaa48
PHP-function
PHP-Spreadsheet
PHP
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 ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
How to generate PDF file using PHP ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24998,
"s": 24970,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 25125,
"s": 24998,
"text": "The setBold() function is an inbuilt function in PHP | Spreadsheet_Excel_Writer which is used to set the boldness of the text."
},
{
"code": null,
"e": 25134,
"s": 25125,
"text": "Syntax: "
},
{
"code": null,
"e": 25170,
"s": 25134,
"text": "void Format::setBold( $weight = 1 )"
},
{
"code": null,
"e": 25349,
"s": 25170,
"text": "Parameters: This function accepts a single parameter $weight which is used to set the weight of the text. The default value of text weight is 1 (700). It ranges from 100 to 1000."
},
{
"code": null,
"e": 25429,
"s": 25349,
"text": "Return Value: This function returns TRUE on success and PEAR_ERROR on failure. "
},
{
"code": null,
"e": 25442,
"s": 25429,
"text": "Example 1: "
},
{
"code": null,
"e": 25446,
"s": 25442,
"text": "PHP"
},
{
"code": "<?phprequire_once 'Spreadsheet/Excel/Writer.php'; // Create Spreadsheet_Excel_Writer Object$workbook = new Spreadsheet_Excel_Writer(); // Add Worksheet$worksheet =& $workbook->addWorksheet(); // Set Font Family Times New Roman$format_setBold =& $workbook->addFormat();$format_setBold->setFontFamily('Times New Roman'); // Set Bold Property$format_setBold->setBold(); // Set Shadow to text$format_setBold->setShadow(); // Write to Worksheet$worksheet->write(0, 0, \"Information\");$worksheet->write(1, 0, \"Website Name\", $format_setBold);$worksheet->write(1, 1, \"Address\", $format_setBold);$worksheet->write(2, 0, \"GeeksforGeeks\", $format_setBold);$worksheet->write(2, 1, \"https://www.geeksforgeeks.org/\", $format_setBold);$workbook->send('test.xls'); $workbook->close();?>",
"e": 26254,
"s": 25446,
"text": null
},
{
"code": null,
"e": 26263,
"s": 26254,
"text": "Output: "
},
{
"code": null,
"e": 26276,
"s": 26263,
"text": "Example 2: "
},
{
"code": null,
"e": 26280,
"s": 26276,
"text": "PHP"
},
{
"code": "<?phprequire_once 'Spreadsheet/Excel/Writer.php'; // Add Workbook$workbook = new Spreadsheet_Excel_Writer(); // Add Format to spreadsheet$format_bold =& $workbook->addFormat(); // Set Bold$format_bold->setBold(); // Add Worksheet to Spreadsheet$worksheet =& $workbook->addWorksheet(); // Write to Worksheet$worksheet->write(0, 0, \"Details of GeeksforGeeks Contributors\", $format_bold);$worksheet->write(1, 0, \"Author\", $format_bold);$worksheet->write(1, 1, \"User Handle\", $format_bold);$worksheet->write(2, 0, \"Sarthak\", $format_bold);$worksheet->write(2, 1, \"sarthak_ishu11\", $format_bold); // Send .xlsx file to header$workbook->send('test.xls'); // Close Workbook Object$workbook->close();?>",
"e": 27000,
"s": 26280,
"text": null
},
{
"code": null,
"e": 27009,
"s": 27000,
"text": "Output: "
},
{
"code": null,
"e": 27141,
"s": 27009,
"text": "Reference: https://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.spreadsheet-excel-writer-format.setbold.php "
},
{
"code": null,
"e": 27151,
"s": 27141,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27164,
"s": 27151,
"text": "PHP-function"
},
{
"code": null,
"e": 27180,
"s": 27164,
"text": "PHP-Spreadsheet"
},
{
"code": null,
"e": 27184,
"s": 27180,
"text": "PHP"
},
{
"code": null,
"e": 27201,
"s": 27184,
"text": "Web Technologies"
},
{
"code": null,
"e": 27205,
"s": 27201,
"text": "PHP"
},
{
"code": null,
"e": 27303,
"s": 27205,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27385,
"s": 27303,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27436,
"s": 27385,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 27510,
"s": 27436,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 27552,
"s": 27510,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27589,
"s": 27552,
"text": "How to generate PDF file using PHP ?"
},
{
"code": null,
"e": 27631,
"s": 27589,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27664,
"s": 27631,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27707,
"s": 27664,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27769,
"s": 27707,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
curl command in Linux with Examples - GeeksforGeeks | 10 Mar, 2022
curl is a command-line tool to transfer data to or from a server, using any of the supported protocols (HTTP, FTP, IMAP, POP3, SCP, SFTP, SMTP, TFTP, TELNET, LDAP, or FILE). curl is powered by Libcurl. This tool is preferred for automation since it is designed to work without user interaction. curl can transfer multiple files at once. Syntax:
curl [options] [URL...]
URL: The most basic use of curl is typing the command followed by the URL.
curl https://www.geeksforgeeks.org
This should display the content of the URL on the terminal. The URL syntax is protocol dependent and multiple URLs can be written as sets like:
curl http://site.{one, two, three}.com
URLs with numeric sequence series can be written as:
curl ftp://ftp.example.com/file[1-20].jpeg
Progress Meter: curl displays a progress meter during use to indicate the transfer rate, amount of data transferred, time left, etc.
curl -# -O ftp://ftp.example.com/file.zip
curl --silent ftp://ftp.example.com/file.zip
If you like a progress bar instead of a meter, you can use the -# option as in the example above, or –silent if you want to disable it completely.
Example:
-o: saves the downloaded file on the local machine with the name provided in the parameters. Syntax:
curl -o [file_name] [URL...]
Example:
curl -o hello.zip ftp://speedtest.tele2.net/1MB.zip
Output:
The above example downloads the file from the FTP server and saves it with the name hello.zip.
-O: This option downloads the file and saves it with the same name as in the URL. Syntax:
curl -O [URL...]
Example:
curl -O ftp://speedtest.tele2.net/1MB.zip
Output:
-C -: This option resumes download which has been stopped due to some reason. This is useful when downloading large files and was interrupted. Syntax:
curl -C - [URL...]
Example:
curl -C - -O ftp://speedtest.tele2.net/1MB.zip
Output:
–limit-rate: This option limits the upper bound of the rate of data transfer and keeps it around the given value in bytes. Syntax:
curl --limit-rate [value] [URL]
Example:
curl --limit-rate 1000K -O ftp://speedtest.tele2.net/1MB.zip
Output:
The command limits the download to 1000K bytes.
-u: curl also provides options to download files from user authenticated FTP servers. Syntax:
curl -u {username}:{password} [FTP_URL]
Example:
curl -u demo:password -O ftp://test.rebex.net/readme.txt
Output:
-T: This option helps to upload a file to the FTP server. Syntax:
curl -u {username}:{password} -T {filename} {FTP_Location}
If you want to append an already existing FTP file you can use the -a or –append option.
–libcurl: This option is very useful from a developer’s perspective. If this option is appended to any cURL command, it outputs the C source code that uses libcurl for the specified option. It is a code similar to the command line implementation. Syntax:
curl [URL...] --libcurl [filename]
Example:
curl https://www.geeksforgeeks.org > log.html --libcurl code.c
Output:
The above example downloads the HTML and saves it into log.html and the code in code.c file. The next command shows the first 30 lines of the code.
-x, –proxy: curl also lets us use a proxy to access the URL. Syntax:
curl -x [proxy_name]:[port] [URL...]
If the proxy requires authentication, it can be used with the command:
curl -u [user]:[password] -x [proxy_name]:[port] [URL...]
Sending mail: As curl can transfer data over different protocols, including SMTP, we can use curl to send mails. Syntax:
curl –url [SMTP URL] –mail-from [sender_mail] –mail-rcpt [receiver_mail] -n –ssl-reqd -u {email}:{password} -T [Mail text file]
DICT protocol: The Libcurl defines the DICT protocol which can be used to easily get the definition or meaning of any word directly from the command line. Syntax:
curl [protocol:[dictionary_URL]:[word]
Example:
curl dict://dict.org/d:overclock
Output:
Note: There are a number of other options provided by cURL which can be checked on the main page. The libcurl library has been ported into various programming languages. It’s advisable to visit the individual project site for documentation.
griffinmp05
linux-command
Linux-networking-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
Tail command in Linux with examples
Compiling with g++
Thread functions in C/C++ | [
{
"code": null,
"e": 23958,
"s": 23930,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 24305,
"s": 23958,
"text": "curl is a command-line tool to transfer data to or from a server, using any of the supported protocols (HTTP, FTP, IMAP, POP3, SCP, SFTP, SMTP, TFTP, TELNET, LDAP, or FILE). curl is powered by Libcurl. This tool is preferred for automation since it is designed to work without user interaction. curl can transfer multiple files at once. Syntax: "
},
{
"code": null,
"e": 24329,
"s": 24305,
"text": "curl [options] [URL...]"
},
{
"code": null,
"e": 24406,
"s": 24329,
"text": "URL: The most basic use of curl is typing the command followed by the URL. "
},
{
"code": null,
"e": 24441,
"s": 24406,
"text": "curl https://www.geeksforgeeks.org"
},
{
"code": null,
"e": 24586,
"s": 24441,
"text": "This should display the content of the URL on the terminal. The URL syntax is protocol dependent and multiple URLs can be written as sets like: "
},
{
"code": null,
"e": 24625,
"s": 24586,
"text": "curl http://site.{one, two, three}.com"
},
{
"code": null,
"e": 24679,
"s": 24625,
"text": "URLs with numeric sequence series can be written as: "
},
{
"code": null,
"e": 24722,
"s": 24679,
"text": "curl ftp://ftp.example.com/file[1-20].jpeg"
},
{
"code": null,
"e": 24856,
"s": 24722,
"text": "Progress Meter: curl displays a progress meter during use to indicate the transfer rate, amount of data transferred, time left, etc. "
},
{
"code": null,
"e": 24943,
"s": 24856,
"text": "curl -# -O ftp://ftp.example.com/file.zip\ncurl --silent ftp://ftp.example.com/file.zip"
},
{
"code": null,
"e": 25091,
"s": 24943,
"text": "If you like a progress bar instead of a meter, you can use the -# option as in the example above, or –silent if you want to disable it completely. "
},
{
"code": null,
"e": 25100,
"s": 25091,
"text": "Example:"
},
{
"code": null,
"e": 25201,
"s": 25100,
"text": "-o: saves the downloaded file on the local machine with the name provided in the parameters. Syntax:"
},
{
"code": null,
"e": 25230,
"s": 25201,
"text": "curl -o [file_name] [URL...]"
},
{
"code": null,
"e": 25239,
"s": 25230,
"text": "Example:"
},
{
"code": null,
"e": 25291,
"s": 25239,
"text": "curl -o hello.zip ftp://speedtest.tele2.net/1MB.zip"
},
{
"code": null,
"e": 25299,
"s": 25291,
"text": "Output:"
},
{
"code": null,
"e": 25394,
"s": 25299,
"text": "The above example downloads the file from the FTP server and saves it with the name hello.zip."
},
{
"code": null,
"e": 25484,
"s": 25394,
"text": "-O: This option downloads the file and saves it with the same name as in the URL. Syntax:"
},
{
"code": null,
"e": 25501,
"s": 25484,
"text": "curl -O [URL...]"
},
{
"code": null,
"e": 25510,
"s": 25501,
"text": "Example:"
},
{
"code": null,
"e": 25552,
"s": 25510,
"text": "curl -O ftp://speedtest.tele2.net/1MB.zip"
},
{
"code": null,
"e": 25560,
"s": 25552,
"text": "Output:"
},
{
"code": null,
"e": 25711,
"s": 25560,
"text": "-C -: This option resumes download which has been stopped due to some reason. This is useful when downloading large files and was interrupted. Syntax:"
},
{
"code": null,
"e": 25730,
"s": 25711,
"text": "curl -C - [URL...]"
},
{
"code": null,
"e": 25739,
"s": 25730,
"text": "Example:"
},
{
"code": null,
"e": 25786,
"s": 25739,
"text": "curl -C - -O ftp://speedtest.tele2.net/1MB.zip"
},
{
"code": null,
"e": 25794,
"s": 25786,
"text": "Output:"
},
{
"code": null,
"e": 25925,
"s": 25794,
"text": "–limit-rate: This option limits the upper bound of the rate of data transfer and keeps it around the given value in bytes. Syntax:"
},
{
"code": null,
"e": 25957,
"s": 25925,
"text": "curl --limit-rate [value] [URL]"
},
{
"code": null,
"e": 25966,
"s": 25957,
"text": "Example:"
},
{
"code": null,
"e": 26027,
"s": 25966,
"text": "curl --limit-rate 1000K -O ftp://speedtest.tele2.net/1MB.zip"
},
{
"code": null,
"e": 26035,
"s": 26027,
"text": "Output:"
},
{
"code": null,
"e": 26083,
"s": 26035,
"text": "The command limits the download to 1000K bytes."
},
{
"code": null,
"e": 26177,
"s": 26083,
"text": "-u: curl also provides options to download files from user authenticated FTP servers. Syntax:"
},
{
"code": null,
"e": 26217,
"s": 26177,
"text": "curl -u {username}:{password} [FTP_URL]"
},
{
"code": null,
"e": 26226,
"s": 26217,
"text": "Example:"
},
{
"code": null,
"e": 26283,
"s": 26226,
"text": "curl -u demo:password -O ftp://test.rebex.net/readme.txt"
},
{
"code": null,
"e": 26292,
"s": 26283,
"text": "Output: "
},
{
"code": null,
"e": 26358,
"s": 26292,
"text": "-T: This option helps to upload a file to the FTP server. Syntax:"
},
{
"code": null,
"e": 26417,
"s": 26358,
"text": "curl -u {username}:{password} -T {filename} {FTP_Location}"
},
{
"code": null,
"e": 26506,
"s": 26417,
"text": "If you want to append an already existing FTP file you can use the -a or –append option."
},
{
"code": null,
"e": 26762,
"s": 26506,
"text": "–libcurl: This option is very useful from a developer’s perspective. If this option is appended to any cURL command, it outputs the C source code that uses libcurl for the specified option. It is a code similar to the command line implementation. Syntax: "
},
{
"code": null,
"e": 26797,
"s": 26762,
"text": "curl [URL...] --libcurl [filename]"
},
{
"code": null,
"e": 26806,
"s": 26797,
"text": "Example:"
},
{
"code": null,
"e": 26869,
"s": 26806,
"text": "curl https://www.geeksforgeeks.org > log.html --libcurl code.c"
},
{
"code": null,
"e": 26877,
"s": 26869,
"text": "Output:"
},
{
"code": null,
"e": 27025,
"s": 26877,
"text": "The above example downloads the HTML and saves it into log.html and the code in code.c file. The next command shows the first 30 lines of the code."
},
{
"code": null,
"e": 27094,
"s": 27025,
"text": "-x, –proxy: curl also lets us use a proxy to access the URL. Syntax:"
},
{
"code": null,
"e": 27131,
"s": 27094,
"text": "curl -x [proxy_name]:[port] [URL...]"
},
{
"code": null,
"e": 27203,
"s": 27131,
"text": "If the proxy requires authentication, it can be used with the command: "
},
{
"code": null,
"e": 27261,
"s": 27203,
"text": "curl -u [user]:[password] -x [proxy_name]:[port] [URL...]"
},
{
"code": null,
"e": 27383,
"s": 27261,
"text": "Sending mail: As curl can transfer data over different protocols, including SMTP, we can use curl to send mails. Syntax: "
},
{
"code": null,
"e": 27512,
"s": 27383,
"text": "curl –url [SMTP URL] –mail-from [sender_mail] –mail-rcpt [receiver_mail] -n –ssl-reqd -u {email}:{password} -T [Mail text file] "
},
{
"code": null,
"e": 27676,
"s": 27512,
"text": "DICT protocol: The Libcurl defines the DICT protocol which can be used to easily get the definition or meaning of any word directly from the command line. Syntax: "
},
{
"code": null,
"e": 27715,
"s": 27676,
"text": "curl [protocol:[dictionary_URL]:[word]"
},
{
"code": null,
"e": 27724,
"s": 27715,
"text": "Example:"
},
{
"code": null,
"e": 27757,
"s": 27724,
"text": "curl dict://dict.org/d:overclock"
},
{
"code": null,
"e": 27765,
"s": 27757,
"text": "Output:"
},
{
"code": null,
"e": 28006,
"s": 27765,
"text": "Note: There are a number of other options provided by cURL which can be checked on the main page. The libcurl library has been ported into various programming languages. It’s advisable to visit the individual project site for documentation."
},
{
"code": null,
"e": 28018,
"s": 28006,
"text": "griffinmp05"
},
{
"code": null,
"e": 28032,
"s": 28018,
"text": "linux-command"
},
{
"code": null,
"e": 28058,
"s": 28032,
"text": "Linux-networking-commands"
},
{
"code": null,
"e": 28065,
"s": 28058,
"text": "Picked"
},
{
"code": null,
"e": 28089,
"s": 28065,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 28100,
"s": 28089,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28119,
"s": 28100,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28217,
"s": 28119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28226,
"s": 28217,
"text": "Comments"
},
{
"code": null,
"e": 28239,
"s": 28226,
"text": "Old Comments"
},
{
"code": null,
"e": 28274,
"s": 28239,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 28312,
"s": 28274,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28350,
"s": 28312,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 28385,
"s": 28350,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 28421,
"s": 28385,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 28458,
"s": 28421,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 28502,
"s": 28458,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 28538,
"s": 28502,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 28557,
"s": 28538,
"text": "Compiling with g++"
}
]
|
Python - Ways to convert array of strings to array of floats | String literals in python are surrounded by either single quotation marks, or double quotation marks. Assigning a string to a variable is done with the variable name followed by an equal sign and the string. You can assign a multiline string to a variable by using three quotes.
Live Demo
# array of strings to array of floats using astype
import numpy as np
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.astype
res = ini_array.astype(np.float)
# printing final result
print ("final array", str(res))
# array of strings to array of floats using fromstring
import numpy as np
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.fromstring
ini_array = ', '.join(ini_array)
ini_array = np.fromstring(ini_array, dtype = np.float, sep =', ' )
# printing final result
print ("final array", str(ini_array))
# converting array of strings to array of floats using asarray
import numpy as np
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.asarray
final_array = b = np.asarray(ini_array,
dtype = np.float64, order ='C')
# printing final result
print ("final array", str(final_array))
('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')
('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')
('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]') | [
{
"code": null,
"e": 1341,
"s": 1062,
"text": "String literals in python are surrounded by either single quotation marks, or double quotation marks. Assigning a string to a variable is done with the variable name followed by an equal sign and the string. You can assign a multiline string to a variable by using three quotes."
},
{
"code": null,
"e": 1352,
"s": 1341,
"text": " Live Demo"
},
{
"code": null,
"e": 2535,
"s": 1352,
"text": "# array of strings to array of floats using astype\nimport numpy as np\n# initialising array\nini_array = np.array([\"1.1\", \"1.5\", \"2.7\", \"8.9\"])\n# printing initial array\nprint (\"initial array\", str(ini_array))\n# conerting to array of floats\n# using np.astype\nres = ini_array.astype(np.float)\n# printing final result\nprint (\"final array\", str(res))\n# array of strings to array of floats using fromstring \nimport numpy as np \n# initialising array\nini_array = np.array([\"1.1\", \"1.5\", \"2.7\", \"8.9\"])\n# printing initial array\nprint (\"initial array\", str(ini_array))\n# conerting to array of floats\n# using np.fromstring\nini_array = ', '.join(ini_array)\nini_array = np.fromstring(ini_array, dtype = np.float, sep =', ' )\n# printing final result\nprint (\"final array\", str(ini_array))\n# converting array of strings to array of floats using asarray\nimport numpy as np\n# initialising array\nini_array = np.array([\"1.1\", \"1.5\", \"2.7\", \"8.9\"])\n# printing initial array\nprint (\"initial array\", str(ini_array))\n# conerting to array of floats\n# using np.asarray\nfinal_array = b = np.asarray(ini_array,\n dtype = np.float64, order ='C')\n# printing final result\nprint (\"final array\", str(final_array))"
},
{
"code": null,
"e": 2790,
"s": 2535,
"text": "('initial array', \"['1.1' '1.5' '2.7' '8.9']\")\n('final array', '[ 1.1 1.5 2.7 8.9]')\n('initial array', \"['1.1' '1.5' '2.7' '8.9']\")\n('final array', '[ 1.1 1.5 2.7 8.9]')\n('initial array', \"['1.1' '1.5' '2.7' '8.9']\")\n('final array', '[ 1.1 1.5 2.7 8.9]')"
}
]
|
Find minimum element of HashSet in Java | To get the minimum element of HashSet, use the Collections.min() method.
Declare the HashSet −
Set<Integer> hs = new HashSet<Integer>();
Now let us add the elements −
hs.add(29);
hs.add(879);
hs.add(88);
hs.add(788);
hs.add(456);
Let us now get the minimum element −
Object obj = Collections.min(hs);
The following is an example to find the minimum element of HashSet −
Live Demo
import java.util.*;
public class Demo {
public static void main(String args[]) {
// create hash set
Set<Integer> hs = new HashSet<Integer>();
hs.add(29);
hs.add(879);
hs.add(88);
hs.add(788);
hs.add(456);
System.out.println("Elements in set = "+hs);
// finding minimum element
Object obj = Collections.min(hs);
System.out.println("Minimum Element = "+obj);
}
}
Elements in set = [788, 88, 456, 29, 879]
Minimum Element = 29 | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To get the minimum element of HashSet, use the Collections.min() method."
},
{
"code": null,
"e": 1157,
"s": 1135,
"text": "Declare the HashSet −"
},
{
"code": null,
"e": 1199,
"s": 1157,
"text": "Set<Integer> hs = new HashSet<Integer>();"
},
{
"code": null,
"e": 1229,
"s": 1199,
"text": "Now let us add the elements −"
},
{
"code": null,
"e": 1292,
"s": 1229,
"text": "hs.add(29);\nhs.add(879);\nhs.add(88);\nhs.add(788);\nhs.add(456);"
},
{
"code": null,
"e": 1329,
"s": 1292,
"text": "Let us now get the minimum element −"
},
{
"code": null,
"e": 1363,
"s": 1329,
"text": "Object obj = Collections.min(hs);"
},
{
"code": null,
"e": 1432,
"s": 1363,
"text": "The following is an example to find the minimum element of HashSet −"
},
{
"code": null,
"e": 1443,
"s": 1432,
"text": " Live Demo"
},
{
"code": null,
"e": 1876,
"s": 1443,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n // create hash set\n Set<Integer> hs = new HashSet<Integer>();\n hs.add(29);\n hs.add(879);\n hs.add(88);\n hs.add(788);\n hs.add(456);\n System.out.println(\"Elements in set = \"+hs);\n // finding minimum element\n Object obj = Collections.min(hs);\n System.out.println(\"Minimum Element = \"+obj);\n }\n}"
},
{
"code": null,
"e": 1939,
"s": 1876,
"text": "Elements in set = [788, 88, 456, 29, 879]\nMinimum Element = 29"
}
]
|
How to find minimum element in an array using linear search in C language? | C programming language provides two types of searching techniques. They are as follows −
Linear search
Binary search
Searching for the key element is done in a linear fashion.
It is the simplest searching technique.
It does not expect the list to be sorted.
Limitation − It consumes more time and reduce the power of system.
Input (i/p): Unsorted list of elements, key.
Output (o/p):
Success – If key is found.
Unsuccessful – Otherwise.
Following is the C program to find minimum element in an array by using linear search −
Live Demo
#include<stdio.h>
int main (){
int a[50], n, i, key, flag = 0;
printf("enter the no: of elements");
scanf ("%d",&n);
printf("enter the elements:");
for (i=0; i<n; i++)
scanf( "%d", &a[i]);
printf("enter a key element:");
scanf ("%d", &key);
for (i=0; i<n; i++){
if (a[i] == key){
flag = 1;
break;
}
}
if (flag == 1)
printf("search is successful:");
else
printf("search is unsuccessfull:");
return 0;
}
When the above program is executed, it produces the following result −
enter the no: of elements 5
enter the elements:
12
34
56
78
89
enter a key element:56
search is successful:
Given below is another program to find the minimum element in array by using liner search −
Live Demo
#include <stdio.h>
int min_ele(int numbers[], int n){
int min = numbers[0];
int i;
for (i = 1; i <= n; i++){
if (min > numbers[i])
min = numbers[i];
}
return min;
}
int main(){
int n;
printf("Enter no: of elements in an array: ");
scanf("%d",&n);
int numbers[n];
int i;
int min ;
printf("Enter %d numbers : ", n);
printf("\n");
for (i = 0; i < n; i++){
scanf("%d", &numbers[i]);
}
min = min_ele(numbers,n);
printf("\In an array the minimum number is: %d\n", min);
return 0;
}
When the above program is executed, it produces the following result −
Enter no: of elements in an array: 5
Enter 5 numbers:
23
56
78
9
20
In an array the minimum number is: 9 | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "C programming language provides two types of searching techniques. They are as follows −"
},
{
"code": null,
"e": 1165,
"s": 1151,
"text": "Linear search"
},
{
"code": null,
"e": 1179,
"s": 1165,
"text": "Binary search"
},
{
"code": null,
"e": 1238,
"s": 1179,
"text": "Searching for the key element is done in a linear fashion."
},
{
"code": null,
"e": 1278,
"s": 1238,
"text": "It is the simplest searching technique."
},
{
"code": null,
"e": 1320,
"s": 1278,
"text": "It does not expect the list to be sorted."
},
{
"code": null,
"e": 1387,
"s": 1320,
"text": "Limitation − It consumes more time and reduce the power of system."
},
{
"code": null,
"e": 1446,
"s": 1387,
"text": "Input (i/p): Unsorted list of elements, key.\nOutput (o/p):"
},
{
"code": null,
"e": 1473,
"s": 1446,
"text": "Success – If key is found."
},
{
"code": null,
"e": 1499,
"s": 1473,
"text": "Unsuccessful – Otherwise."
},
{
"code": null,
"e": 1587,
"s": 1499,
"text": "Following is the C program to find minimum element in an array by using linear search −"
},
{
"code": null,
"e": 1598,
"s": 1587,
"text": " Live Demo"
},
{
"code": null,
"e": 2084,
"s": 1598,
"text": "#include<stdio.h>\nint main (){\n int a[50], n, i, key, flag = 0;\n printf(\"enter the no: of elements\");\n scanf (\"%d\",&n);\n printf(\"enter the elements:\");\n for (i=0; i<n; i++)\n scanf( \"%d\", &a[i]);\n printf(\"enter a key element:\");\n scanf (\"%d\", &key);\n for (i=0; i<n; i++){\n if (a[i] == key){\n flag = 1;\n break;\n }\n }\n if (flag == 1)\n printf(\"search is successful:\");\n else\n printf(\"search is unsuccessfull:\");\n return 0;\n}"
},
{
"code": null,
"e": 2155,
"s": 2084,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2263,
"s": 2155,
"text": "enter the no: of elements 5\nenter the elements:\n12\n34\n56\n78\n89\nenter a key element:56\nsearch is successful:"
},
{
"code": null,
"e": 2355,
"s": 2263,
"text": "Given below is another program to find the minimum element in array by using liner search −"
},
{
"code": null,
"e": 2366,
"s": 2355,
"text": " Live Demo"
},
{
"code": null,
"e": 2914,
"s": 2366,
"text": "#include <stdio.h>\nint min_ele(int numbers[], int n){\n int min = numbers[0];\n int i;\n for (i = 1; i <= n; i++){\n if (min > numbers[i])\n min = numbers[i];\n }\n return min;\n}\nint main(){\n int n;\n printf(\"Enter no: of elements in an array: \");\n scanf(\"%d\",&n);\n int numbers[n];\n int i;\n int min ;\n printf(\"Enter %d numbers : \", n);\n printf(\"\\n\");\n for (i = 0; i < n; i++){\n scanf(\"%d\", &numbers[i]);\n }\n min = min_ele(numbers,n);\n printf(\"\\In an array the minimum number is: %d\\n\", min);\n return 0;\n}"
},
{
"code": null,
"e": 2985,
"s": 2914,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3090,
"s": 2985,
"text": "Enter no: of elements in an array: 5\nEnter 5 numbers:\n23\n56\n78\n9\n20\nIn an array the minimum number is: 9"
}
]
|
Gold Mine Problem - GeeksforGeeks | 27 Apr, 2022
Given a gold mine of n*m dimensions. Each field in this mine contains a positive integer which is the amount of gold in tons. Initially the miner is at first column but can be at any row. He can move only (right->,right up /,right down\) that is from a given cell, the miner can move to the cell diagonally up towards the right or right or diagonally down towards the right. Find out maximum amount of gold he can collect. Examples:
Input : mat[][] = {{1, 3, 3},
{2, 1, 4},
{0, 6, 4}};
Output : 12
{(1,0)->(2,1)->(1,2)}
Input: mat[][] = { {1, 3, 1, 5},
{2, 2, 4, 1},
{5, 0, 2, 3},
{0, 6, 1, 2}};
Output : 16
(2,0) -> (1,1) -> (1,2) -> (0,3) OR
(2,0) -> (3,1) -> (2,2) -> (2,3)
Input : mat[][] = {{10, 33, 13, 15},
{22, 21, 04, 1},
{5, 0, 2, 3},
{0, 6, 14, 2}};
Output : 83
Source Flipkart Interview
Method 1: Recursion
A simple method that is a direct recursive implementation
C++
Java
Python3
Javascript
// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std; int collectGold(vector<vector<int>> gold, int r, int c, int n, int m) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } // Right upper diagonal int rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m); // right int right = collectGold(gold, r, c + 1, n, m); // Lower right diagonal int rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m); // Return the maximum and store the value return gold[r] + max(max(rightUpperDiagonal, rightLowerDiagonal), right); } int getMaxGold(vector<vector<int>> gold, int n, int m){ int maxGold = 0; for (int i = 0; i < n; i++) { // Recursive function call for ith row. int goldCollected = collectGold(gold, i, 0, n, m); maxGold = max(maxGold, goldCollected); } return maxGold;} // Driver Codeint main(){ vector<vector<int>> gold { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; cout << getMaxGold(gold, n, m); return 0;}
// Java program to solve Gold Mine problemclass GFG { static int collectGold(int[][] gold, int r, int c, int n, int m) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } // Right upper diagonal int rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m); // right int right = collectGold(gold, r, c + 1, n, m); // Lower right diagonal int rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m); // Return the maximum and store the value return gold[r] + Math.max(Math.max(rightUpperDiagonal, rightLowerDiagonal), right); } static int getMaxGold(int[][] gold, int n, int m) { int maxGold = 0; for (int i = 0; i < n; i++) { // Recursive function call for ith row. int goldCollected = collectGold(gold, i, 0, n, m); maxGold = Math.max(maxGold, goldCollected); } return maxGold; } public static void main(String[] args) { int[][] gold = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 0, 6, 1, 2 } }; int m = 4, n = 4; System.out.println(getMaxGold(gold, n, m)); }} // This code is contributed by Karandeep Singh.
# Python program to solve Gold Mine problemdef collectGold(gold, r, c, n, m): # Base condition. if ((r < 0) or (r == n) or (c == m)): return 0 # Right upper diagonal rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m) # right right = collectGold(gold, r, c + 1, n, m) # Lower right diagonal rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m) # Return the maximum and store the value return gold[r] + max(max(rightUpperDiagonal, rightLowerDiagonal), right) def getMaxGold(gold,n,m): maxGold = 0 for i in range(n): # Recursive function call for ith row. goldCollected = collectGold(gold, i, 0, n, m) maxGold = max(maxGold, goldCollected) return maxGold # Driver Codegold = [[1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2]] m,n = 4,4print(getMaxGold(gold, n, m)) # This code is contributed by shinjanpatra.
<script> // JavaScript program to solve Gold Mine problem function collectGold(gold,r,c,n,m) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } // Right upper diagonal let rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m); // right let right = collectGold(gold, r, c + 1, n, m); // Lower right diagonal let rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m); // Return the maximum and store the value return gold[r] + Math.max(Math.max(rightUpperDiagonal, rightLowerDiagonal), right); } function getMaxGold(gold,n,m){ maxGold = 0; for (i = 0; i < n; i++) { // Recursive function call for ith row. goldCollected = collectGold(gold, i, 0, n, m); maxGold = Math.max(maxGold, goldCollected); } return maxGold;} // Driver Code let gold = [[1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2]]; let m = 4, n = 4;document.write(getMaxGold(gold, n, m)); // This code is contributed by shinjanpatra.</script>
16
Time complexity: O(3N*M)
Auxiliary Space: O(N*M)
Method 2: Memoization
Bottom-Up Approach: The second way is to take an extra space of size m*n and start computing values of states
of right, right upper diagonal, and right bottom diagonal and store it in the 2d array.
C++
Java
// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std; int collectGold(vector<vector<int>> gold, int r, int c, int n, int m, vector<vector<int>> &dp) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } if(dp[r] != -1){ return dp[r] ; } // Right upper diagonal int rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m, dp); // right int right = collectGold(gold, r, c + 1, n, m, dp); // Lower right diagonal int rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m, dp); // Return the maximum and store the value return dp[r] = gold[r] + max(max(rightUpperDiagonal, rightLowerDiagonal), right); } int getMaxGold(vector<vector<int>> gold, int n, int m){ int maxGold = 0; // Initialize the dp vector vector<vector<int>> dp(n, vector<int>(m, -1)) ; for (int i = 0; i < n; i++) { // Recursive function call for ith row. int goldCollected = collectGold(gold, i, 0, n, m, dp); maxGold = max(maxGold, goldCollected); } return maxGold;} // Driver Codeint main(){ vector<vector<int>> gold { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; cout << getMaxGold(gold, n, m); return 0;}
// Java program to solve Gold Mine problemimport java.util.*;class Gold { static int collectGold(int[][] gold, int r, int c, int n, int m, int[][] dp) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } if (dp[r] != -1) { return dp[r]; } // Right upper diagonal int rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m, dp); // right int right = collectGold(gold, r, c + 1, n, m, dp); // Lower right diagonal int rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m, dp); // Return the maximum and store the value return gold[r] + Math.max(Math.max(rightUpperDiagonal, rightLowerDiagonal), right); } static int getMaxGold(int[][] gold, int n, int m) { int maxGold = 0; int[][] dp = new int[n][m]; for (int row = 0; row < n; row++) { Arrays.fill(dp[row], -1); } for (int i = 0; i < n; i++) { // Recursive function call for ith row. int goldCollected = collectGold(gold, i, 0, n, m, dp); maxGold = Math.max(maxGold, goldCollected); } return maxGold; } public static void main(String[] args) { int[][] gold = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 0, 6, 1, 2 } }; int m = 4, n = 4; System.out.println(getMaxGold(gold, n, m)); }} // This code is contributed by Karandeep Singh.
16
Time Complexity :O(m*n)
Space Complexity :O(m*n)
Method 3: Using Dp, TabulationCreate a 2-D matrix goldTable[][]) of the same as given matrix mat[][]. If we observe the question closely, we can notice following.
Amount of gold is positive, so we would like to cover maximum cells of maximum values under given constraints.In every move, we move one step toward right side. So we always end up in last column. If we are at the last column, then we are unable to move right
Amount of gold is positive, so we would like to cover maximum cells of maximum values under given constraints.
In every move, we move one step toward right side. So we always end up in last column. If we are at the last column, then we are unable to move right
If we are at the first row or last column, then we are unable to move right-up so just assign 0 otherwise assign the value of goldTable[row-1][col+1] to right_up. If we are at the last row or last column, then we are unable to move right down so just assign 0 otherwise assign the value of goldTable[row+1][col+1] to right up. Now find the maximum of right, right_up, and right_down and then add it with that mat[row][col]. At last, find the maximum of all rows and first column and return it.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std; const int MAX = 100; // Returns maximum amount of gold that can be collected// when journey started from first column and moves// allowed are right, right-up and right-downint getMaxGold(int gold[][MAX], int m, int n){ // Create a table for storing intermediate results // and initialize all cells to 0. The first row of // goldMineTable gives the maximum gold that the miner // can collect when starts that row int goldTable[m][n]; memset(goldTable, 0, sizeof(goldTable)); for (int col=n-1; col>=0; col--) { for (int row=0; row<m; row++) { // Gold collected on going to the cell on the right(->) int right = (col==n-1)? 0: goldTable[row][col+1]; // Gold collected on going to the cell to right up (/) int right_up = (row==0 || col==n-1)? 0: goldTable[row-1][col+1]; // Gold collected on going to the cell to right down (\) int right_down = (row==m-1 || col==n-1)? 0: goldTable[row+1][col+1]; // Max gold collected from taking either of the // above 3 paths goldTable[row][col] = gold[row][col] + max(right, max(right_up, right_down)); } } // The max amount of gold collected will be the max // value in first column of all rows int res = goldTable[0][0]; for (int i=1; i<m; i++) res = max(res, goldTable[i][0]); return res;} // Driver Codeint main(){ int gold[MAX][MAX]= { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; cout << getMaxGold(gold, m, n); return 0;}
// Java program to solve Gold Mine problemimport java.util.Arrays; class GFG { static final int MAX = 100; // Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed // are right, right-up and right-down static int getMaxGold(int gold[][], int m, int n) { // Create a table for storing // intermediate results and initialize // all cells to 0. The first row of // goldMineTable gives the maximum // gold that the miner can collect // when starts that row int goldTable[][] = new int[m][n]; for(int[] rows:goldTable) Arrays.fill(rows, 0); for (int col = n-1; col >= 0; col--) { for (int row = 0; row < m; row++) { // Gold collected on going to // the cell on the right(->) int right = (col == n-1) ? 0 : goldTable[row][col+1]; // Gold collected on going to // the cell to right up (/) int right_up = (row == 0 || col == n-1) ? 0 : goldTable[row-1][col+1]; // Gold collected on going to // the cell to right down (\) int right_down = (row == m-1 || col == n-1) ? 0 : goldTable[row+1][col+1]; // Max gold collected from taking // either of the above 3 paths goldTable[row][col] = gold[row][col] + Math.max(right, Math.max(right_up, right_down)); } } // The max amount of gold collected will be // the max value in first column of all rows int res = goldTable[0][0]; for (int i = 1; i < m; i++) res = Math.max(res, goldTable[i][0]); return res; } //driver code public static void main(String arg[]) { int gold[][]= { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; System.out.print(getMaxGold(gold, m, n)); }} // This code is contributed by Anant Agarwal.
# Python program to solve# Gold Mine problem MAX = 100 # Returns maximum amount of# gold that can be collected# when journey started from# first column and moves# allowed are right, right-up# and right-downdef getMaxGold(gold, m, n): # Create a table for storing # intermediate results # and initialize all cells to 0. # The first row of # goldMineTable gives the # maximum gold that the miner # can collect when starts that row goldTable = [[0 for i in range(n)] for j in range(m)] for col in range(n-1, -1, -1): for row in range(m): # Gold collected on going to # the cell on the right(->) if (col == n-1): right = 0 else: right = goldTable[row][col+1] # Gold collected on going to # the cell to right up (/) if (row == 0 or col == n-1): right_up = 0 else: right_up = goldTable[row-1][col+1] # Gold collected on going to # the cell to right down (\) if (row == m-1 or col == n-1): right_down = 0 else: right_down = goldTable[row+1][col+1] # Max gold collected from taking # either of the above 3 paths goldTable[row][col] = gold[row][col] + max(right, right_up, right_down) # The max amount of gold # collected will be the max # value in first column of all rows res = goldTable[0][0] for i in range(1, m): res = max(res, goldTable[i][0]) return res # Driver codegold = [[1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2]] m = 4n = 4 print(getMaxGold(gold, m, n)) # This code is contributed# by Soumen Ghosh.
// C# program to solve Gold Mine problemusing System; class GFG{ static int MAX = 100; // Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed are // right, right-up and right-down static int getMaxGold(int[,] gold, int m, int n) { // Create a table for storing intermediate // results and initialize all cells to 0. // The first row of goldMineTable gives // the maximum gold that the miner // can collect when starts that row int[,] goldTable = new int[m, n]; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) goldTable[i, j] = 0; for (int col = n - 1; col >= 0; col--) { for (int row = 0; row < m; row++) { // Gold collected on going to // the cell on the right(->) int right = (col == n - 1) ? 0 : goldTable[row, col + 1]; // Gold collected on going to // the cell to right up (/) int right_up = (row == 0 || col == n - 1) ? 0 : goldTable[row-1,col+1]; // Gold collected on going // to the cell to right down (\) int right_down = (row == m - 1 || col == n - 1) ? 0 : goldTable[row + 1, col + 1]; // Max gold collected from taking // either of the above 3 paths goldTable[row, col] = gold[row, col] + Math.Max(right, Math.Max(right_up, right_down)); } } // The max amount of gold collected will be the max // value in first column of all rows int res = goldTable[0, 0]; for (int i = 1; i < m; i++) res = Math.Max(res, goldTable[i, 0]); return res; } // Driver Code static void Main() { int[,] gold = new int[,]{{1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; Console.Write(getMaxGold(gold, m, n)); }} // This code is contributed by DrRoot_
<?php// Php program to solve Gold Mine problem // Returns maximum amount of gold that// can be collected when journey started// from first column and moves allowed are// right, right-up and right-downfunction getMaxGold($gold, $m, $n){ $MAX = 100 ; // Create a table for storing intermediate // results and initialize all cells to 0. // The first row of goldMineTable gives the // maximum gold that the miner can collect // when starts that row $goldTable = array(array()); for ($i = 0; $i < $m ; $i ++) for($j = 0; $j < $n ; $j ++) $goldTable[$i][$j] = 0 ; for ($col = $n - 1; $col >= 0 ; $col--) { for ($row = 0 ; $row < $m ; $row++) { // Gold collected on going to // the cell on the right(->) if ($col == $n - 1) $right = 0 ; else $right = $goldTable[$row][$col + 1]; // Gold collected on going to // the cell to right up (/) if ($row == 0 or $col == $n - 1) $right_up = 0 ; else $right_up = $goldTable[$row - 1][$col + 1]; // Gold collected on going to // the cell to right down (\) if ($row == $m - 1 or $col == $n - 1) $right_down = 0 ; else $right_down = $goldTable[$row + 1][$col + 1]; // Max gold collected from taking // either of the above 3 paths $goldTable[$row][$col] = $gold[$row][$col] + max($right, $right_up, $right_down); } } // The max amount of gold collected will be the // max value in first column of all rows $res = $goldTable[0][0] ; for ($i = 0; $i < $m; $i++) $res = max($res, $goldTable[$i][0]); return $res;} // Driver code$gold = array(array(1, 3, 1, 5), array(2, 2, 4, 1), array(5, 0, 2, 3), array(0, 6, 1, 2)); $m = 4 ;$n = 4 ; echo getMaxGold($gold, $m, $n) ; // This code is contributed by Ryuga?>
<script> // JavaScript program to solve Gold Mine problem let MAX = 100; // Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed // are right, right-up and right-down function getMaxGold(gold, m, n) { // Create a table for storing // intermediate results and initialize // all cells to 0. The first row of // goldMineTable gives the maximum // gold that the miner can collect // when starts that row let goldTable = new Array(m); for(let i = 0; i < m; i++) { goldTable[i] = new Array(n); for(let j = 0; j < n; j++) { goldTable[i][j] = 0; } } for (let col = n-1; col >= 0; col--) { for (let row = 0; row < m; row++) { // Gold collected on going to // the cell on the right(->) let right = (col == n-1) ? 0 : goldTable[row][col+1]; // Gold collected on going to // the cell to right up (/) let right_up = (row == 0 || col == n-1) ? 0 : goldTable[row-1][col+1]; // Gold collected on going to // the cell to right down (\) let right_down = (row == m-1 || col == n-1) ? 0 : goldTable[row+1][col+1]; // Max gold collected from taking // either of the above 3 paths goldTable[row][col] = gold[row][col] + Math.max(right, Math.max(right_up, right_down)); } } // The max amount of gold collected will be // the max value in first column of all rows let res = goldTable[0][0]; for (let i = 1; i < m; i++) res = Math.max(res, goldTable[i][0]); return res; } let gold = [ [1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2] ]; let m = 4, n = 4; document.write(getMaxGold(gold, m, n)); </script>
16
Time Complexity :O(m*n) Space Complexity :O(m*n)This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ankthon
DrRoot_
nirala96
kushwahp1234
divyeshrabadiya07
mara18cs
surindertarika1234
surinderdawra388
prasanna1995
shinjanpatra
karandeep1234
Amazon
Flipkart
Dynamic Programming
Matrix
Flipkart
Amazon
Dynamic Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Overlapping Subproblems Property in Dynamic Programming | DP-1
Edit Distance | DP-5
Program to find largest element in an array
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Rat in a Maze | Backtracking-2
Print a given matrix in spiral form
Sudoku | Backtracking-7 | [
{
"code": null,
"e": 24580,
"s": 24552,
"text": "\n27 Apr, 2022"
},
{
"code": null,
"e": 25015,
"s": 24580,
"text": "Given a gold mine of n*m dimensions. Each field in this mine contains a positive integer which is the amount of gold in tons. Initially the miner is at first column but can be at any row. He can move only (right->,right up /,right down\\) that is from a given cell, the miner can move to the cell diagonally up towards the right or right or diagonally down towards the right. Find out maximum amount of gold he can collect. Examples: "
},
{
"code": null,
"e": 25506,
"s": 25015,
"text": "Input : mat[][] = {{1, 3, 3},\n {2, 1, 4},\n {0, 6, 4}};\nOutput : 12 \n{(1,0)->(2,1)->(1,2)}\n\nInput: mat[][] = { {1, 3, 1, 5},\n {2, 2, 4, 1},\n {5, 0, 2, 3},\n {0, 6, 1, 2}};\nOutput : 16\n(2,0) -> (1,1) -> (1,2) -> (0,3) OR\n(2,0) -> (3,1) -> (2,2) -> (2,3)\n\nInput : mat[][] = {{10, 33, 13, 15},\n {22, 21, 04, 1},\n {5, 0, 2, 3},\n {0, 6, 14, 2}};\nOutput : 83"
},
{
"code": null,
"e": 25534,
"s": 25506,
"text": "Source Flipkart Interview "
},
{
"code": null,
"e": 25554,
"s": 25534,
"text": "Method 1: Recursion"
},
{
"code": null,
"e": 25613,
"s": 25554,
"text": "A simple method that is a direct recursive implementation "
},
{
"code": null,
"e": 25617,
"s": 25613,
"text": "C++"
},
{
"code": null,
"e": 25622,
"s": 25617,
"text": "Java"
},
{
"code": null,
"e": 25630,
"s": 25622,
"text": "Python3"
},
{
"code": null,
"e": 25641,
"s": 25630,
"text": "Javascript"
},
{
"code": "// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std; int collectGold(vector<vector<int>> gold, int r, int c, int n, int m) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } // Right upper diagonal int rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m); // right int right = collectGold(gold, r, c + 1, n, m); // Lower right diagonal int rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m); // Return the maximum and store the value return gold[r] + max(max(rightUpperDiagonal, rightLowerDiagonal), right); } int getMaxGold(vector<vector<int>> gold, int n, int m){ int maxGold = 0; for (int i = 0; i < n; i++) { // Recursive function call for ith row. int goldCollected = collectGold(gold, i, 0, n, m); maxGold = max(maxGold, goldCollected); } return maxGold;} // Driver Codeint main(){ vector<vector<int>> gold { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; cout << getMaxGold(gold, n, m); return 0;}",
"e": 26768,
"s": 25641,
"text": null
},
{
"code": "// Java program to solve Gold Mine problemclass GFG { static int collectGold(int[][] gold, int r, int c, int n, int m) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } // Right upper diagonal int rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m); // right int right = collectGold(gold, r, c + 1, n, m); // Lower right diagonal int rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m); // Return the maximum and store the value return gold[r] + Math.max(Math.max(rightUpperDiagonal, rightLowerDiagonal), right); } static int getMaxGold(int[][] gold, int n, int m) { int maxGold = 0; for (int i = 0; i < n; i++) { // Recursive function call for ith row. int goldCollected = collectGold(gold, i, 0, n, m); maxGold = Math.max(maxGold, goldCollected); } return maxGold; } public static void main(String[] args) { int[][] gold = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 0, 6, 1, 2 } }; int m = 4, n = 4; System.out.println(getMaxGold(gold, n, m)); }} // This code is contributed by Karandeep Singh.",
"e": 28047,
"s": 26768,
"text": null
},
{
"code": "# Python program to solve Gold Mine problemdef collectGold(gold, r, c, n, m): # Base condition. if ((r < 0) or (r == n) or (c == m)): return 0 # Right upper diagonal rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m) # right right = collectGold(gold, r, c + 1, n, m) # Lower right diagonal rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m) # Return the maximum and store the value return gold[r] + max(max(rightUpperDiagonal, rightLowerDiagonal), right) def getMaxGold(gold,n,m): maxGold = 0 for i in range(n): # Recursive function call for ith row. goldCollected = collectGold(gold, i, 0, n, m) maxGold = max(maxGold, goldCollected) return maxGold # Driver Codegold = [[1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2]] m,n = 4,4print(getMaxGold(gold, n, m)) # This code is contributed by shinjanpatra.",
"e": 28976,
"s": 28047,
"text": null
},
{
"code": "<script> // JavaScript program to solve Gold Mine problem function collectGold(gold,r,c,n,m) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } // Right upper diagonal let rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m); // right let right = collectGold(gold, r, c + 1, n, m); // Lower right diagonal let rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m); // Return the maximum and store the value return gold[r] + Math.max(Math.max(rightUpperDiagonal, rightLowerDiagonal), right); } function getMaxGold(gold,n,m){ maxGold = 0; for (i = 0; i < n; i++) { // Recursive function call for ith row. goldCollected = collectGold(gold, i, 0, n, m); maxGold = Math.max(maxGold, goldCollected); } return maxGold;} // Driver Code let gold = [[1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2]]; let m = 4, n = 4;document.write(getMaxGold(gold, n, m)); // This code is contributed by shinjanpatra.</script>",
"e": 30028,
"s": 28976,
"text": null
},
{
"code": null,
"e": 30031,
"s": 30028,
"text": "16"
},
{
"code": null,
"e": 30058,
"s": 30031,
"text": " Time complexity: O(3N*M)"
},
{
"code": null,
"e": 30084,
"s": 30058,
"text": " Auxiliary Space: O(N*M)"
},
{
"code": null,
"e": 30106,
"s": 30084,
"text": "Method 2: Memoization"
},
{
"code": null,
"e": 30217,
"s": 30106,
"text": "Bottom-Up Approach: The second way is to take an extra space of size m*n and start computing values of states "
},
{
"code": null,
"e": 30305,
"s": 30217,
"text": "of right, right upper diagonal, and right bottom diagonal and store it in the 2d array."
},
{
"code": null,
"e": 30309,
"s": 30305,
"text": "C++"
},
{
"code": null,
"e": 30314,
"s": 30309,
"text": "Java"
},
{
"code": "// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std; int collectGold(vector<vector<int>> gold, int r, int c, int n, int m, vector<vector<int>> &dp) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } if(dp[r] != -1){ return dp[r] ; } // Right upper diagonal int rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m, dp); // right int right = collectGold(gold, r, c + 1, n, m, dp); // Lower right diagonal int rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m, dp); // Return the maximum and store the value return dp[r] = gold[r] + max(max(rightUpperDiagonal, rightLowerDiagonal), right); } int getMaxGold(vector<vector<int>> gold, int n, int m){ int maxGold = 0; // Initialize the dp vector vector<vector<int>> dp(n, vector<int>(m, -1)) ; for (int i = 0; i < n; i++) { // Recursive function call for ith row. int goldCollected = collectGold(gold, i, 0, n, m, dp); maxGold = max(maxGold, goldCollected); } return maxGold;} // Driver Codeint main(){ vector<vector<int>> gold { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; cout << getMaxGold(gold, n, m); return 0;}",
"e": 31617,
"s": 30314,
"text": null
},
{
"code": "// Java program to solve Gold Mine problemimport java.util.*;class Gold { static int collectGold(int[][] gold, int r, int c, int n, int m, int[][] dp) { // Base condition. if ((r < 0) || (r == n) || (c == m)) { return 0; } if (dp[r] != -1) { return dp[r]; } // Right upper diagonal int rightUpperDiagonal = collectGold(gold, r - 1, c + 1, n, m, dp); // right int right = collectGold(gold, r, c + 1, n, m, dp); // Lower right diagonal int rightLowerDiagonal = collectGold(gold, r + 1, c + 1, n, m, dp); // Return the maximum and store the value return gold[r] + Math.max(Math.max(rightUpperDiagonal, rightLowerDiagonal), right); } static int getMaxGold(int[][] gold, int n, int m) { int maxGold = 0; int[][] dp = new int[n][m]; for (int row = 0; row < n; row++) { Arrays.fill(dp[row], -1); } for (int i = 0; i < n; i++) { // Recursive function call for ith row. int goldCollected = collectGold(gold, i, 0, n, m, dp); maxGold = Math.max(maxGold, goldCollected); } return maxGold; } public static void main(String[] args) { int[][] gold = { { 1, 3, 1, 5 }, { 2, 2, 4, 1 }, { 5, 0, 2, 3 }, { 0, 6, 1, 2 } }; int m = 4, n = 4; System.out.println(getMaxGold(gold, n, m)); }} // This code is contributed by Karandeep Singh.",
"e": 33096,
"s": 31617,
"text": null
},
{
"code": null,
"e": 33099,
"s": 33096,
"text": "16"
},
{
"code": null,
"e": 33123,
"s": 33099,
"text": "Time Complexity :O(m*n)"
},
{
"code": null,
"e": 33148,
"s": 33123,
"text": "Space Complexity :O(m*n)"
},
{
"code": null,
"e": 33313,
"s": 33148,
"text": "Method 3: Using Dp, TabulationCreate a 2-D matrix goldTable[][]) of the same as given matrix mat[][]. If we observe the question closely, we can notice following. "
},
{
"code": null,
"e": 33573,
"s": 33313,
"text": "Amount of gold is positive, so we would like to cover maximum cells of maximum values under given constraints.In every move, we move one step toward right side. So we always end up in last column. If we are at the last column, then we are unable to move right"
},
{
"code": null,
"e": 33684,
"s": 33573,
"text": "Amount of gold is positive, so we would like to cover maximum cells of maximum values under given constraints."
},
{
"code": null,
"e": 33834,
"s": 33684,
"text": "In every move, we move one step toward right side. So we always end up in last column. If we are at the last column, then we are unable to move right"
},
{
"code": null,
"e": 34329,
"s": 33834,
"text": "If we are at the first row or last column, then we are unable to move right-up so just assign 0 otherwise assign the value of goldTable[row-1][col+1] to right_up. If we are at the last row or last column, then we are unable to move right down so just assign 0 otherwise assign the value of goldTable[row+1][col+1] to right up. Now find the maximum of right, right_up, and right_down and then add it with that mat[row][col]. At last, find the maximum of all rows and first column and return it. "
},
{
"code": null,
"e": 34333,
"s": 34329,
"text": "C++"
},
{
"code": null,
"e": 34338,
"s": 34333,
"text": "Java"
},
{
"code": null,
"e": 34346,
"s": 34338,
"text": "Python3"
},
{
"code": null,
"e": 34349,
"s": 34346,
"text": "C#"
},
{
"code": null,
"e": 34353,
"s": 34349,
"text": "PHP"
},
{
"code": null,
"e": 34364,
"s": 34353,
"text": "Javascript"
},
{
"code": "// C++ program to solve Gold Mine problem#include<bits/stdc++.h>using namespace std; const int MAX = 100; // Returns maximum amount of gold that can be collected// when journey started from first column and moves// allowed are right, right-up and right-downint getMaxGold(int gold[][MAX], int m, int n){ // Create a table for storing intermediate results // and initialize all cells to 0. The first row of // goldMineTable gives the maximum gold that the miner // can collect when starts that row int goldTable[m][n]; memset(goldTable, 0, sizeof(goldTable)); for (int col=n-1; col>=0; col--) { for (int row=0; row<m; row++) { // Gold collected on going to the cell on the right(->) int right = (col==n-1)? 0: goldTable[row][col+1]; // Gold collected on going to the cell to right up (/) int right_up = (row==0 || col==n-1)? 0: goldTable[row-1][col+1]; // Gold collected on going to the cell to right down (\\) int right_down = (row==m-1 || col==n-1)? 0: goldTable[row+1][col+1]; // Max gold collected from taking either of the // above 3 paths goldTable[row][col] = gold[row][col] + max(right, max(right_up, right_down)); } } // The max amount of gold collected will be the max // value in first column of all rows int res = goldTable[0][0]; for (int i=1; i<m; i++) res = max(res, goldTable[i][0]); return res;} // Driver Codeint main(){ int gold[MAX][MAX]= { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; cout << getMaxGold(gold, m, n); return 0;}",
"e": 36189,
"s": 34364,
"text": null
},
{
"code": "// Java program to solve Gold Mine problemimport java.util.Arrays; class GFG { static final int MAX = 100; // Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed // are right, right-up and right-down static int getMaxGold(int gold[][], int m, int n) { // Create a table for storing // intermediate results and initialize // all cells to 0. The first row of // goldMineTable gives the maximum // gold that the miner can collect // when starts that row int goldTable[][] = new int[m][n]; for(int[] rows:goldTable) Arrays.fill(rows, 0); for (int col = n-1; col >= 0; col--) { for (int row = 0; row < m; row++) { // Gold collected on going to // the cell on the right(->) int right = (col == n-1) ? 0 : goldTable[row][col+1]; // Gold collected on going to // the cell to right up (/) int right_up = (row == 0 || col == n-1) ? 0 : goldTable[row-1][col+1]; // Gold collected on going to // the cell to right down (\\) int right_down = (row == m-1 || col == n-1) ? 0 : goldTable[row+1][col+1]; // Max gold collected from taking // either of the above 3 paths goldTable[row][col] = gold[row][col] + Math.max(right, Math.max(right_up, right_down)); } } // The max amount of gold collected will be // the max value in first column of all rows int res = goldTable[0][0]; for (int i = 1; i < m; i++) res = Math.max(res, goldTable[i][0]); return res; } //driver code public static void main(String arg[]) { int gold[][]= { {1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; System.out.print(getMaxGold(gold, m, n)); }} // This code is contributed by Anant Agarwal.",
"e": 38701,
"s": 36189,
"text": null
},
{
"code": "# Python program to solve# Gold Mine problem MAX = 100 # Returns maximum amount of# gold that can be collected# when journey started from# first column and moves# allowed are right, right-up# and right-downdef getMaxGold(gold, m, n): # Create a table for storing # intermediate results # and initialize all cells to 0. # The first row of # goldMineTable gives the # maximum gold that the miner # can collect when starts that row goldTable = [[0 for i in range(n)] for j in range(m)] for col in range(n-1, -1, -1): for row in range(m): # Gold collected on going to # the cell on the right(->) if (col == n-1): right = 0 else: right = goldTable[row][col+1] # Gold collected on going to # the cell to right up (/) if (row == 0 or col == n-1): right_up = 0 else: right_up = goldTable[row-1][col+1] # Gold collected on going to # the cell to right down (\\) if (row == m-1 or col == n-1): right_down = 0 else: right_down = goldTable[row+1][col+1] # Max gold collected from taking # either of the above 3 paths goldTable[row][col] = gold[row][col] + max(right, right_up, right_down) # The max amount of gold # collected will be the max # value in first column of all rows res = goldTable[0][0] for i in range(1, m): res = max(res, goldTable[i][0]) return res # Driver codegold = [[1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2]] m = 4n = 4 print(getMaxGold(gold, m, n)) # This code is contributed# by Soumen Ghosh. ",
"e": 40546,
"s": 38701,
"text": null
},
{
"code": "// C# program to solve Gold Mine problemusing System; class GFG{ static int MAX = 100; // Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed are // right, right-up and right-down static int getMaxGold(int[,] gold, int m, int n) { // Create a table for storing intermediate // results and initialize all cells to 0. // The first row of goldMineTable gives // the maximum gold that the miner // can collect when starts that row int[,] goldTable = new int[m, n]; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) goldTable[i, j] = 0; for (int col = n - 1; col >= 0; col--) { for (int row = 0; row < m; row++) { // Gold collected on going to // the cell on the right(->) int right = (col == n - 1) ? 0 : goldTable[row, col + 1]; // Gold collected on going to // the cell to right up (/) int right_up = (row == 0 || col == n - 1) ? 0 : goldTable[row-1,col+1]; // Gold collected on going // to the cell to right down (\\) int right_down = (row == m - 1 || col == n - 1) ? 0 : goldTable[row + 1, col + 1]; // Max gold collected from taking // either of the above 3 paths goldTable[row, col] = gold[row, col] + Math.Max(right, Math.Max(right_up, right_down)); } } // The max amount of gold collected will be the max // value in first column of all rows int res = goldTable[0, 0]; for (int i = 1; i < m; i++) res = Math.Max(res, goldTable[i, 0]); return res; } // Driver Code static void Main() { int[,] gold = new int[,]{{1, 3, 1, 5}, {2, 2, 4, 1}, {5, 0, 2, 3}, {0, 6, 1, 2} }; int m = 4, n = 4; Console.Write(getMaxGold(gold, m, n)); }} // This code is contributed by DrRoot_",
"e": 42963,
"s": 40546,
"text": null
},
{
"code": "<?php// Php program to solve Gold Mine problem // Returns maximum amount of gold that// can be collected when journey started// from first column and moves allowed are// right, right-up and right-downfunction getMaxGold($gold, $m, $n){ $MAX = 100 ; // Create a table for storing intermediate // results and initialize all cells to 0. // The first row of goldMineTable gives the // maximum gold that the miner can collect // when starts that row $goldTable = array(array()); for ($i = 0; $i < $m ; $i ++) for($j = 0; $j < $n ; $j ++) $goldTable[$i][$j] = 0 ; for ($col = $n - 1; $col >= 0 ; $col--) { for ($row = 0 ; $row < $m ; $row++) { // Gold collected on going to // the cell on the right(->) if ($col == $n - 1) $right = 0 ; else $right = $goldTable[$row][$col + 1]; // Gold collected on going to // the cell to right up (/) if ($row == 0 or $col == $n - 1) $right_up = 0 ; else $right_up = $goldTable[$row - 1][$col + 1]; // Gold collected on going to // the cell to right down (\\) if ($row == $m - 1 or $col == $n - 1) $right_down = 0 ; else $right_down = $goldTable[$row + 1][$col + 1]; // Max gold collected from taking // either of the above 3 paths $goldTable[$row][$col] = $gold[$row][$col] + max($right, $right_up, $right_down); } } // The max amount of gold collected will be the // max value in first column of all rows $res = $goldTable[0][0] ; for ($i = 0; $i < $m; $i++) $res = max($res, $goldTable[$i][0]); return $res;} // Driver code$gold = array(array(1, 3, 1, 5), array(2, 2, 4, 1), array(5, 0, 2, 3), array(0, 6, 1, 2)); $m = 4 ;$n = 4 ; echo getMaxGold($gold, $m, $n) ; // This code is contributed by Ryuga?>",
"e": 45093,
"s": 42963,
"text": null
},
{
"code": "<script> // JavaScript program to solve Gold Mine problem let MAX = 100; // Returns maximum amount of gold that // can be collected when journey started // from first column and moves allowed // are right, right-up and right-down function getMaxGold(gold, m, n) { // Create a table for storing // intermediate results and initialize // all cells to 0. The first row of // goldMineTable gives the maximum // gold that the miner can collect // when starts that row let goldTable = new Array(m); for(let i = 0; i < m; i++) { goldTable[i] = new Array(n); for(let j = 0; j < n; j++) { goldTable[i][j] = 0; } } for (let col = n-1; col >= 0; col--) { for (let row = 0; row < m; row++) { // Gold collected on going to // the cell on the right(->) let right = (col == n-1) ? 0 : goldTable[row][col+1]; // Gold collected on going to // the cell to right up (/) let right_up = (row == 0 || col == n-1) ? 0 : goldTable[row-1][col+1]; // Gold collected on going to // the cell to right down (\\) let right_down = (row == m-1 || col == n-1) ? 0 : goldTable[row+1][col+1]; // Max gold collected from taking // either of the above 3 paths goldTable[row][col] = gold[row][col] + Math.max(right, Math.max(right_up, right_down)); } } // The max amount of gold collected will be // the max value in first column of all rows let res = goldTable[0][0]; for (let i = 1; i < m; i++) res = Math.max(res, goldTable[i][0]); return res; } let gold = [ [1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2] ]; let m = 4, n = 4; document.write(getMaxGold(gold, m, n)); </script>",
"e": 47513,
"s": 45093,
"text": null
},
{
"code": null,
"e": 47516,
"s": 47513,
"text": "16"
},
{
"code": null,
"e": 47985,
"s": 47516,
"text": "Time Complexity :O(m*n) Space Complexity :O(m*n)This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 47993,
"s": 47985,
"text": "ankthon"
},
{
"code": null,
"e": 48001,
"s": 47993,
"text": "DrRoot_"
},
{
"code": null,
"e": 48010,
"s": 48001,
"text": "nirala96"
},
{
"code": null,
"e": 48023,
"s": 48010,
"text": "kushwahp1234"
},
{
"code": null,
"e": 48041,
"s": 48023,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 48050,
"s": 48041,
"text": "mara18cs"
},
{
"code": null,
"e": 48069,
"s": 48050,
"text": "surindertarika1234"
},
{
"code": null,
"e": 48086,
"s": 48069,
"text": "surinderdawra388"
},
{
"code": null,
"e": 48099,
"s": 48086,
"text": "prasanna1995"
},
{
"code": null,
"e": 48112,
"s": 48099,
"text": "shinjanpatra"
},
{
"code": null,
"e": 48126,
"s": 48112,
"text": "karandeep1234"
},
{
"code": null,
"e": 48133,
"s": 48126,
"text": "Amazon"
},
{
"code": null,
"e": 48142,
"s": 48133,
"text": "Flipkart"
},
{
"code": null,
"e": 48162,
"s": 48142,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 48169,
"s": 48162,
"text": "Matrix"
},
{
"code": null,
"e": 48178,
"s": 48169,
"text": "Flipkart"
},
{
"code": null,
"e": 48185,
"s": 48178,
"text": "Amazon"
},
{
"code": null,
"e": 48205,
"s": 48185,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 48212,
"s": 48205,
"text": "Matrix"
},
{
"code": null,
"e": 48310,
"s": 48212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48341,
"s": 48310,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 48374,
"s": 48341,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 48442,
"s": 48374,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 48505,
"s": 48442,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 48526,
"s": 48505,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 48570,
"s": 48526,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 48632,
"s": 48570,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 48663,
"s": 48632,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 48699,
"s": 48663,
"text": "Print a given matrix in spiral form"
}
]
|
pushd Command in Linux with Examples - GeeksforGeeks | 02 Nov, 2020
pushd is a shell built-in command which allows us to easily manipulate the directory stack. This appends a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the present working directory. The “d” in pushd stands for the directory as it pushes the directory path onto the stack. The directory stack increases in size after each pushd command. This stack is based on the Last In First Out (LIFO) principle. This command has an exit status 0 i.e, it returns success unless an invalid argument is supplied or the directory change fails.
Syntax of pushd command:
pushd [directory]
the type command shows that pushd is a shell built-in command.
How pushd command functions?
When pushd [directory] command is executed, the directory specified becomes the present working directory.
The path and name of the directory are added to the top of the directory stack.
The directory stack is displayed as a space-separated list of directories.
If pushd command is executed without any directory name, then the directory at the top of the stack becomes the current working directory i.e, the first two directories exchange their position in the directory stack.
Advantage of pushd command over cd command
It is a very powerful tool for operation on directories as it stores the directories in the stack. Consider nested directories. We can navigate between the dictionaries using the cd command. But suppose, you are in the fourth directory. Then to navigate to the second directory, the cd command has to be used twice. But by using pushd command, it can be achieved in one step. In one step, we can navigate from any directory in the stack to another directory in the stack. Directory manipulation becomes easier and efficient.
pushd command pushes directories onto a stack. Execute the following commands:
pushd ~/Desktop
Now, Desktop becomes the present working directory and is pushed onto the stack and the list of directories is displayed. The same operations will be performed for the other commands below.
pushd ~/Templates
pushd ~/Videos
pushd ~/Downloads
pushd ~/Music
pushd ~/Downloads
It can be observed that after each pushd command the directory specified becomes the new directory. It can be seen that ‘Downloads’ has been added to the directory stack twice but there was no error as the directory stack allows duplicate directories. The directory stack can be displayed using the following command. It can be observed that the command which is entered at the beginning is displayed at the last position and the most recent directory added is displayed at the top.
dir -v -l
Whenever a new directory is added onto the stack, the current directory is changed to the new one. But a new directory can be added keeping the current directory unchanged using “-n” along with pushd command. This command will push the directory to the second spot and the present directory remains unchanged at the first spot rotated. The syntax for the command is:
pushd -n [Directory]
We can use numeric parameters along with pushd command to move to any directory present in the stack. Here the numeric parameter represents the position of the directory in the stack. The directory at that position becomes the current directory and the stack is rotated. pushd +n counts n from the top of the directory stack. pushd -n counts n from the bottom of the directory stack.
pushd +N #N is a numeric parameter
pushd -N #N is a numeric parameter
linux-command
Linux-directory-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
chown command in Linux with Examples
mv command in Linux with examples
Named Pipe or FIFO with example C program
SED command in Linux | Set 2
scp command in Linux with Examples
Docker - COPY Instruction | [
{
"code": null,
"e": 24431,
"s": 24403,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 25013,
"s": 24431,
"text": "pushd is a shell built-in command which allows us to easily manipulate the directory stack. This appends a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the present working directory. The “d” in pushd stands for the directory as it pushes the directory path onto the stack. The directory stack increases in size after each pushd command. This stack is based on the Last In First Out (LIFO) principle. This command has an exit status 0 i.e, it returns success unless an invalid argument is supplied or the directory change fails."
},
{
"code": null,
"e": 25038,
"s": 25013,
"text": "Syntax of pushd command:"
},
{
"code": null,
"e": 25057,
"s": 25038,
"text": "pushd [directory]\n"
},
{
"code": null,
"e": 25121,
"s": 25057,
"text": "the type command shows that pushd is a shell built-in command. "
},
{
"code": null,
"e": 25150,
"s": 25121,
"text": "How pushd command functions?"
},
{
"code": null,
"e": 25257,
"s": 25150,
"text": "When pushd [directory] command is executed, the directory specified becomes the present working directory."
},
{
"code": null,
"e": 25337,
"s": 25257,
"text": "The path and name of the directory are added to the top of the directory stack."
},
{
"code": null,
"e": 25412,
"s": 25337,
"text": "The directory stack is displayed as a space-separated list of directories."
},
{
"code": null,
"e": 25629,
"s": 25412,
"text": "If pushd command is executed without any directory name, then the directory at the top of the stack becomes the current working directory i.e, the first two directories exchange their position in the directory stack."
},
{
"code": null,
"e": 25672,
"s": 25629,
"text": "Advantage of pushd command over cd command"
},
{
"code": null,
"e": 26197,
"s": 25672,
"text": "It is a very powerful tool for operation on directories as it stores the directories in the stack. Consider nested directories. We can navigate between the dictionaries using the cd command. But suppose, you are in the fourth directory. Then to navigate to the second directory, the cd command has to be used twice. But by using pushd command, it can be achieved in one step. In one step, we can navigate from any directory in the stack to another directory in the stack. Directory manipulation becomes easier and efficient."
},
{
"code": null,
"e": 26277,
"s": 26197,
"text": "pushd command pushes directories onto a stack. Execute the following commands:"
},
{
"code": null,
"e": 26294,
"s": 26277,
"text": "pushd ~/Desktop\n"
},
{
"code": null,
"e": 26484,
"s": 26294,
"text": "Now, Desktop becomes the present working directory and is pushed onto the stack and the list of directories is displayed. The same operations will be performed for the other commands below."
},
{
"code": null,
"e": 26568,
"s": 26484,
"text": "pushd ~/Templates\npushd ~/Videos\npushd ~/Downloads\npushd ~/Music\npushd ~/Downloads\n"
},
{
"code": null,
"e": 27053,
"s": 26568,
"text": "It can be observed that after each pushd command the directory specified becomes the new directory. It can be seen that ‘Downloads’ has been added to the directory stack twice but there was no error as the directory stack allows duplicate directories. The directory stack can be displayed using the following command. It can be observed that the command which is entered at the beginning is displayed at the last position and the most recent directory added is displayed at the top. "
},
{
"code": null,
"e": 27064,
"s": 27053,
"text": "dir -v -l\n"
},
{
"code": null,
"e": 27431,
"s": 27064,
"text": "Whenever a new directory is added onto the stack, the current directory is changed to the new one. But a new directory can be added keeping the current directory unchanged using “-n” along with pushd command. This command will push the directory to the second spot and the present directory remains unchanged at the first spot rotated. The syntax for the command is:"
},
{
"code": null,
"e": 27453,
"s": 27431,
"text": "pushd -n [Directory]\n"
},
{
"code": null,
"e": 27837,
"s": 27453,
"text": "We can use numeric parameters along with pushd command to move to any directory present in the stack. Here the numeric parameter represents the position of the directory in the stack. The directory at that position becomes the current directory and the stack is rotated. pushd +n counts n from the top of the directory stack. pushd -n counts n from the bottom of the directory stack."
},
{
"code": null,
"e": 27908,
"s": 27837,
"text": "pushd +N #N is a numeric parameter\npushd -N #N is a numeric parameter\n"
},
{
"code": null,
"e": 27922,
"s": 27908,
"text": "linux-command"
},
{
"code": null,
"e": 27947,
"s": 27922,
"text": "Linux-directory-commands"
},
{
"code": null,
"e": 27958,
"s": 27947,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28056,
"s": 27958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28065,
"s": 28056,
"text": "Comments"
},
{
"code": null,
"e": 28078,
"s": 28065,
"text": "Old Comments"
},
{
"code": null,
"e": 28104,
"s": 28078,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 28139,
"s": 28104,
"text": "Basic Operators in Shell Scripting"
},
{
"code": null,
"e": 28176,
"s": 28139,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28216,
"s": 28176,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 28253,
"s": 28216,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28287,
"s": 28253,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28329,
"s": 28287,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28358,
"s": 28329,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 28393,
"s": 28358,
"text": "scp command in Linux with Examples"
}
]
|
JavaScript Chart.js | Chart.js is an open source JavaScript library. Using Chart.js, add animated, interactive graphs on your website.
Following is the code for Chart.js library in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</script>
</head>
<body>
<canvas id="myChart" width="500" height="300"></canvas>
<script type="text/javascript">
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["2005", "2007" , "2009" , "2012", "2014"],
datasets: [
{ label: 'HouseHold income',
data: [5000,8000,10000,1200,15000],
backgroundColor :['rgba(255, 129, 102, 1)',
'rgba(234, 162, 235, 1)',
'rgba(255, 206, 36, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
],
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
</body>
</html> | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "Chart.js is an open source JavaScript library. Using Chart.js, add animated, interactive graphs on your website."
},
{
"code": null,
"e": 1234,
"s": 1175,
"text": "Following is the code for Chart.js library in JavaScript −"
},
{
"code": null,
"e": 1245,
"s": 1234,
"text": " Live Demo"
},
{
"code": null,
"e": 2198,
"s": 1245,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script\n<script src=\"https://cdn.jsdelivr.net/npm/[email protected]\"></script>\n</script>\n</head>\n<body>\n<canvas id=\"myChart\" width=\"500\" height=\"300\"></canvas>\n<script type=\"text/javascript\">\n var ctx = document.getElementById(\"myChart\");\n var myChart = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: [\"2005\", \"2007\" , \"2009\" , \"2012\", \"2014\"],\n datasets: [\n { label: 'HouseHold income',\n data: [5000,8000,10000,1200,15000],\n backgroundColor :['rgba(255, 129, 102, 1)',\n 'rgba(234, 162, 235, 1)',\n 'rgba(255, 206, 36, 1)',\n 'rgba(75, 192, 192, 1)',\n 'rgba(153, 102, 255, 1)',\n ],\n }\n ]\n },\n options: {\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero:true\n }\n }]\n }\n }\n});\n</script>\n</body>\n</html>"
}
]
|
Machine Learning on GCP — Choosing GPUs to Train Your Models | by Komal Venkatesh Ganesan | Towards Data Science | Google cloud platform offers a wide range of GPU options to choose from. GPUs can boost your ML processing, especially when it comes to matrix computations. The CPU on our machine, however, isn’t optimized for this. They struggle with image or video processing and can often delay the model training process.
In Tensorflow/Keras, the convolutional networks with NCHW (channels first) input require GPUs to run.
Most of my ML experiments revolve around AI gaming using NEAT, Deep-Q reinforcement learning or similar techniques. These involve intense matrix manipulations of game frames which CPUs struggle with.
After making the switch to GCP GPUs, the gaming models that took around weeks to train on CPU finished within a few days on GPU. And because they run on the cloud, it makes it easier to monitor your models without logging in by simply exposing your Tensorboard using an external IP.
Here are the GPU options available at the moment (Aug 10th, 2020) and how much they cost: —
NVIDIA® Tesla® T4: $255.50/month NVIDIA® Tesla® K80: $328.50/monthNVIDIA® Tesla® P4: $438.00/monthNVIDIA® Tesla® P100: $1,065.80/monthNVIDIA® Tesla® V100: $1,810.40/month
More information here: https://cloud.google.com/compute/docs/gpus
This assessment covers only Tesla T4, K80 and P4. The P100 and V100 have been excluded simply because they are overkill and too expensive for small projects and hobbyists.
Note: Not all GPUs are available in all GCP regions. You might want to change the region depending on the GPU you are after.
Tesla T4 is the holy grail — it’s both cheap and efficient. It has become my first choice while setting up GCP environments for any ML models.
Here’s the Tensorboard output from running DDQN on Breakout using Tensorflow 2.2.0-rc0 (on Tesla T4): Max Score Achieved: 406
Model: "sequential"_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d (Conv2D) (None, 32, 20, 20) 8224 _________________________________________________________________conv2d_1 (Conv2D) (None, 64, 9, 9) 32832 _________________________________________________________________conv2d_2 (Conv2D) (None, 64, 7, 7) 36928 _________________________________________________________________flatten (Flatten) (None, 3136) 0 _________________________________________________________________dense (Dense) (None, 512) 1606144 _________________________________________________________________dense_1 (Dense) (None, 4) 2052 =================================================================
Link to Tensorboard:https://tensorboard.dev/experiment/1yrW70A0QHertoJDVZk1ig/#scalars&tagFilter=rew
You can observe that the training process achieved scores nearing 300 in the game of breakout in just ~2 days.
Another great aspect to Tesla T4 is that you can afford to run them a little longer to grab sustained discounts because they are cheap(discussed later).
The Tesla T4 is a relatively new model compared to both K80, P4.
Launch dates: Tesla T4 — September 2018 Tesla P4— September 2016Tesla K80s — November 2014
How these would have performed under Tensorflow distributed training on multiple GPUs has not been assessed here.
But as far as the performance goes, the DDQN for models for Atari Breakout took a similar time to complete on all 3 GPUs with no major difference in performance.
Github Link to my project: https://github.com/komal-SkyNET/ai-neural-networks/tree/master/ai-atari
Sustained discounts offer a significant discount just to keeping your instances running a little longer. This is calculated monthly.
In the image shown, notice that you can score almost 80$ sustained discount just for running a VM with Tesla T4.
More information here: https://cloud.google.com/compute/docs/sustained-use-discounts
Here’s a comparison with/without sustained discounts from running GPU workloads for a month. Notice the charts.
Note that GPU options are based on regions. If you find a particular GPU option missing in the drop-down, you might want to try a different region/zone.
Tesla T4 is both cheap and efficient and would easily be the first choice, followed by K80 and P4. However, their performance in distributed training (using multiple GPUs) might differ and is not covered in this assessment.
Sustained discounts: You can score huge discounts for just running your workloads a little longer. A forecast estimate is usually shown while provisioning the virtual machines. | [
{
"code": null,
"e": 481,
"s": 172,
"text": "Google cloud platform offers a wide range of GPU options to choose from. GPUs can boost your ML processing, especially when it comes to matrix computations. The CPU on our machine, however, isn’t optimized for this. They struggle with image or video processing and can often delay the model training process."
},
{
"code": null,
"e": 583,
"s": 481,
"text": "In Tensorflow/Keras, the convolutional networks with NCHW (channels first) input require GPUs to run."
},
{
"code": null,
"e": 783,
"s": 583,
"text": "Most of my ML experiments revolve around AI gaming using NEAT, Deep-Q reinforcement learning or similar techniques. These involve intense matrix manipulations of game frames which CPUs struggle with."
},
{
"code": null,
"e": 1066,
"s": 783,
"text": "After making the switch to GCP GPUs, the gaming models that took around weeks to train on CPU finished within a few days on GPU. And because they run on the cloud, it makes it easier to monitor your models without logging in by simply exposing your Tensorboard using an external IP."
},
{
"code": null,
"e": 1158,
"s": 1066,
"text": "Here are the GPU options available at the moment (Aug 10th, 2020) and how much they cost: —"
},
{
"code": null,
"e": 1329,
"s": 1158,
"text": "NVIDIA® Tesla® T4: $255.50/month NVIDIA® Tesla® K80: $328.50/monthNVIDIA® Tesla® P4: $438.00/monthNVIDIA® Tesla® P100: $1,065.80/monthNVIDIA® Tesla® V100: $1,810.40/month"
},
{
"code": null,
"e": 1395,
"s": 1329,
"text": "More information here: https://cloud.google.com/compute/docs/gpus"
},
{
"code": null,
"e": 1567,
"s": 1395,
"text": "This assessment covers only Tesla T4, K80 and P4. The P100 and V100 have been excluded simply because they are overkill and too expensive for small projects and hobbyists."
},
{
"code": null,
"e": 1692,
"s": 1567,
"text": "Note: Not all GPUs are available in all GCP regions. You might want to change the region depending on the GPU you are after."
},
{
"code": null,
"e": 1835,
"s": 1692,
"text": "Tesla T4 is the holy grail — it’s both cheap and efficient. It has become my first choice while setting up GCP environments for any ML models."
},
{
"code": null,
"e": 1961,
"s": 1835,
"text": "Here’s the Tensorboard output from running DDQN on Breakout using Tensorflow 2.2.0-rc0 (on Tesla T4): Max Score Achieved: 406"
},
{
"code": null,
"e": 2956,
"s": 1961,
"text": "Model: \"sequential\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================conv2d (Conv2D) (None, 32, 20, 20) 8224 _________________________________________________________________conv2d_1 (Conv2D) (None, 64, 9, 9) 32832 _________________________________________________________________conv2d_2 (Conv2D) (None, 64, 7, 7) 36928 _________________________________________________________________flatten (Flatten) (None, 3136) 0 _________________________________________________________________dense (Dense) (None, 512) 1606144 _________________________________________________________________dense_1 (Dense) (None, 4) 2052 ================================================================="
},
{
"code": null,
"e": 3057,
"s": 2956,
"text": "Link to Tensorboard:https://tensorboard.dev/experiment/1yrW70A0QHertoJDVZk1ig/#scalars&tagFilter=rew"
},
{
"code": null,
"e": 3168,
"s": 3057,
"text": "You can observe that the training process achieved scores nearing 300 in the game of breakout in just ~2 days."
},
{
"code": null,
"e": 3321,
"s": 3168,
"text": "Another great aspect to Tesla T4 is that you can afford to run them a little longer to grab sustained discounts because they are cheap(discussed later)."
},
{
"code": null,
"e": 3386,
"s": 3321,
"text": "The Tesla T4 is a relatively new model compared to both K80, P4."
},
{
"code": null,
"e": 3477,
"s": 3386,
"text": "Launch dates: Tesla T4 — September 2018 Tesla P4— September 2016Tesla K80s — November 2014"
},
{
"code": null,
"e": 3591,
"s": 3477,
"text": "How these would have performed under Tensorflow distributed training on multiple GPUs has not been assessed here."
},
{
"code": null,
"e": 3753,
"s": 3591,
"text": "But as far as the performance goes, the DDQN for models for Atari Breakout took a similar time to complete on all 3 GPUs with no major difference in performance."
},
{
"code": null,
"e": 3852,
"s": 3753,
"text": "Github Link to my project: https://github.com/komal-SkyNET/ai-neural-networks/tree/master/ai-atari"
},
{
"code": null,
"e": 3985,
"s": 3852,
"text": "Sustained discounts offer a significant discount just to keeping your instances running a little longer. This is calculated monthly."
},
{
"code": null,
"e": 4098,
"s": 3985,
"text": "In the image shown, notice that you can score almost 80$ sustained discount just for running a VM with Tesla T4."
},
{
"code": null,
"e": 4183,
"s": 4098,
"text": "More information here: https://cloud.google.com/compute/docs/sustained-use-discounts"
},
{
"code": null,
"e": 4295,
"s": 4183,
"text": "Here’s a comparison with/without sustained discounts from running GPU workloads for a month. Notice the charts."
},
{
"code": null,
"e": 4448,
"s": 4295,
"text": "Note that GPU options are based on regions. If you find a particular GPU option missing in the drop-down, you might want to try a different region/zone."
},
{
"code": null,
"e": 4672,
"s": 4448,
"text": "Tesla T4 is both cheap and efficient and would easily be the first choice, followed by K80 and P4. However, their performance in distributed training (using multiple GPUs) might differ and is not covered in this assessment."
}
]
|
Find the Kth number which is not divisible by N - GeeksforGeeks | 14 Jun, 2021
Given two integers N and K, the task is to find the Kth number which is not divisible by N.Note: The value of N is greater than 1, because every number is divisible by 1.
Examples:
Input: N = 3, K = 6 Output: 8 Explanation: Numbers which is not divisible by N = 3 – {1, 2, 4, 5, 7, 8, 10} 6th non-divisible number by 3 is 8.
Input: N = 7, K = 97 Output: 113 Explanation: Numbers which is not divisible by N = 7 – {1, 2, 4, 5, 6, ....} 97th non-divisible number by 7 is 113.
Naive Approach: A simple solution is to iterate over a loop to find the Kth non-divisible number by N. Below is the steps to find the Kth number:
Initialize the count of non-divisible number and current number to 0.
Iterate using a while loop until the count of the non-divisible number is not equal to K.
Increment the count of the non-divisible number by 1, If the current number is not divisible by N.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find// the K'th non divisible// number by N #include <bits/stdc++.h> using namespace std; // Function to find// the K'th non divisible// number by Nint kthNonDivisible(int N, int K){ int find = 0; int j = 0; // Loop to find the K non // divisible number by N while (find != K) { j++; if (j % N != 0) find++; } return j;} // Driver Codeint main(){ int N = 3; int K = 6; cout << kthNonDivisible(N, K); return 0;}
// Java implementation to find// the K'th non divisible// number by Nclass GFG{ // Function to find// the K'th non divisible// number by Nstatic int kthNonDivisible(int N, int K){ int find = 0; int j = 0; // Loop to find the K non // divisible number by N while (find != K) { j++; if (j % N != 0) find++; } return j;} // Driver codepublic static void main(String[] args){ int N = 3; int K = 6; System.out.print(kthNonDivisible(N, K));}} // This code is contributed by shivanisinghss2110
# Python3 implementation to find# the K'th non divisible# number of Nimport math # Function to find the Kth# not divisible by Ndef kthNonDivisible(n, K): find = 0 j = 0 # Loop to find the K non # divisible number by N while find != K: j = j + 1 if j % N != 0: find = find + 1 return j # Driver CodeN = 3K = 6 # Function Callprint(kthNonDivisible(N, K)) # This code is contributed by ishayadav181
// C# implementation to find the// K'th non-divisible number by Nusing System; class GFG { // Function to find the K'th// non divisible number by Nstatic int kthNonDivisible(int N, int K){ int find = 0; int j = 0; // Loop to find the K non // divisible number by N while (find != K) { j++; if (j % N != 0) find++; } return j;} // Driver codepublic static void Main(String[] args){ int N = 3; int K = 6; Console.Write(kthNonDivisible(N, K));}} // This code is contributed by shivanisinghss2110
<script> // Javascript implementation to find the // K'th non-divisible number by N // Function to find the K'th // non divisible number by N function kthNonDivisible(N, K) { let find = 0; let j = 0; // Loop to find the K non // divisible number by N while (find != K) { j++; if (j % N != 0) find++; } return j; } let N = 3; let K = 6; document.write(kthNonDivisible(N, K)); // This code is contributed by decode2207.</script>
8
Another Approach – Using Binary Search The idea is to use Binary Search to solve this problem. The search space for this problem will be from 1 to the maximum integer value and the middle value is computed as the difference of the middle of search space and multiples of the N.
If the middle value is greater than K, then update the value of the H as middle-1.
Otherwise, If the middle value is greater than K, then update the value of the L as middle – 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation for// above approach#include <bits/stdc++.h>using namespace std; // Function to find the Kth// not divisible by Nvoid kthNonDivisible(int N, int K){ // Lowest possible value int L = 1; // Highest possible value int H = INT_MAX; // To store the Kth non // divisible number of N int ans = 0; // Using binary search while (L <= H) { // Calculating mid value int mid = (L + H) / 2; // Sol would have the value // by subtracting all // multiples of n till mid int sol = mid - mid / N; // Check if sol is greater than k if (sol > K) { // H should be reduced to find // minimum possible value H = mid - 1; } // Check if sol is less than k // then L will be mid+1 else if (sol < K) { L = mid + 1; } // Check if sol is equal to k else { // ans will be mid ans = mid; // H would be reduced to find any // more possible value H = mid - 1; } } // Print the answer cout << ans;} // Driver Codeint main(){ int N = 3; int K = 7; // Function Call kthNonDivisible(N, K); return 0;}
// Java implementation for// above approachclass GFG{ // Function to find the Kth// not divisible by Npublic static void kthNonDivisible(int N, int K){ // Lowest possible value int L = 1; // Highest possible value int H = Integer.MAX_VALUE; // To store the Kth non // divisible number of N int ans = 0; // Using binary search while (L <= H) { // Calculating mid value int mid = (L + H) / 2; // Sol would have the value // by subtracting all // multiples of n till mid int sol = mid - mid / N; // Check if sol is greater than k if (sol > K) { // H should be reduced to find // minimum possible value H = mid - 1; } // Check if sol is less than k // then L will be mid+1 else if (sol < K) { L = mid + 1; } // Check if sol is equal to k else { // ans will be mid ans = mid; // H would be reduced to find any // more possible value H = mid - 1; } } // Print the answer System.out.print(ans);} // Driver codepublic static void main(String[] args){ int N = 3; int K = 7; // Function Call kthNonDivisible(N, K);}} // This code is contributed by divyeshrabadiya07
# Python3 implementation for# above approachimport sys # Function to find the Kth# not divisible by Ndef kthNonDivisible(N, K): # Lowest possible value L = 1 # Highest possible value H = sys.maxsize # To store the Kth non # divisible number of N ans = 0 # Using binary search while (L <= H): # Calculating mid value mid = (L + H) // 2 # Sol would have the value # by subtracting all # multiples of n till mid sol = mid - mid // N # Check if sol is greater than k if (sol > K): # H should be reduced to find # minimum possible value H = mid - 1 # Check if sol is less than k # then L will be mid+1 elif (sol < K): L = mid + 1 # Check if sol is equal to k else: # ans will be mid ans = mid # H would be reduced to find any # more possible value H = mid - 1 # Print the answer print(ans) # Driver CodeN = 3K = 7 # Function callkthNonDivisible(N, K) # This code is contributed by ANKITKUMAR34
// C# implementation for// above approachusing System; class GFG{ // Function to find the Kth// not divisible by Nstatic void kthNonDivisible(int N, int K){ // Lowest possible value int L = 1; // Highest possible value int H = Int32.MaxValue; // To store the Kth non // divisible number of N int ans = 0; // Using binary search while (L <= H) { // Calculating mid value int mid = (L + H) / 2; // Sol would have the value // by subtracting all // multiples of n till mid int sol = mid - mid / N; // Check if sol is greater than k if (sol > K) { // H should be reduced to find // minimum possible value H = mid - 1; } // Check if sol is less than k // then L will be mid+1 else if (sol < K) { L = mid + 1; } // Check if sol is equal to k else { // ans will be mid ans = mid; // H would be reduced to find // any more possible value H = mid - 1; } } // Print the answer Console.Write(ans);} // Driver codestatic void Main(){ int N = 3; int K = 7; // Function Call kthNonDivisible(N, K);}} // This code is contributed by divyesh072019
<script> // Javascript implementation for above approach // Function to find the Kth // not divisible by N function kthNonDivisible(N, K) { // Lowest possible value let L = 1; // Highest possible value let H = 2147483647; // To store the Kth non // divisible number of N let ans = 0; // Using binary search while (L <= H) { // Calculating mid value let mid = parseInt((L + H) / 2, 10); // Sol would have the value // by subtracting all // multiples of n till mid let sol = mid - parseInt(mid / N, 10); // Check if sol is greater than k if (sol > K) { // H should be reduced to find // minimum possible value H = mid - 1; } // Check if sol is less than k // then L will be mid+1 else if (sol < K) { L = mid + 1; } // Check if sol is equal to k else { // ans will be mid ans = mid; // H would be reduced to find // any more possible value H = mid - 1; } } // Print the answer document.write(ans); } let N = 3; let K = 7; // Function Call kthNonDivisible(N, K); // This code is contributed by mukesh07.</script>
10
Time Complexity: O(logN)
Efficient Approach: The key observation in the problem is that every number from 1 to N-1 is not divisible by N and then Similarly, N + 1 to 2*N – 1 is also not divisible by N. Keeping this in mind, the Kth number not divisible by N will be:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find// the K'th non-divisible// number of N #include <bits/stdc++.h> using namespace std;// Function to find the Kth// not divisible by Nint kthNonDivisible(int N, int K){ return K + floor((K - 1) / (N - 1));} // Driver Codeint main(){ int N = 3; int K = 6; // Function Call cout << kthNonDivisible(N, K); return 0;}
// Java implementation to find the// K'th non-divisible number of Nclass GFG{ // Function to find the Kth// not divisible by Nstatic int kthNonDivisible(int N, int K){ return (int) (K + Math.floor((K - 1) / (N - 1)));} // Driver Codepublic static void main(String[] args){ int N = 3; int K = 6; // Function Call System.out.print(kthNonDivisible(N, K));}} // This code is contributed by amal kumar choubey
# Python3 implementation to find# the K'th non-divisible# number of Nimport math # Function to find the Kth# not divisible by Ndef kthNonDivisible(N, K): return K + math.floor((K - 1) / (N - 1)) # Driver CodeN = 3K = 6 # Function Callprint(kthNonDivisible(N, K)) # This code is contributed by ishayadav181
// C# implementation to find the// K'th non-divisible number of Nusing System; class GFG{ // Function to find the Kth// not divisible by Nstatic int kthNonDivisible(int N, int K){ return (int) (K + Math.Floor((double)(K - 1) / (N - 1)));} // Driver Codepublic static void Main(String[] args){ int N = 3; int K = 6; // Function Call Console.Write(kthNonDivisible(N, K));}} // This code is contributed by amal kumar choubey
<script> // Javascript implementation to find// the K'th non-divisible// number of N // Function to find the Kth// not divisible by Nfunction kthNonDivisible(N, K){ return K + parseInt( Math.floor((K - 1) / (N - 1)), 10);} // Driver codelet N = 3;let K = 6; // Function Calldocument.write(kthNonDivisible(N, K)); // This code is contributed by suresh07 </script>
8
ishayadav181
shivanisinghss2110
Amal Kumar Choubey
mishrapriyanshu557
ANKITKUMAR34
khushboogoyal499
divyeshrabadiya07
divyesh072019
suresh07
decode2207
mukesh07
divisibility
Numbers
Competitive Programming
Mathematical
Mathematical
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
How to begin with Competitive Programming?
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": 24918,
"s": 24890,
"text": "\n14 Jun, 2021"
},
{
"code": null,
"e": 25090,
"s": 24918,
"text": "Given two integers N and K, the task is to find the Kth number which is not divisible by N.Note: The value of N is greater than 1, because every number is divisible by 1. "
},
{
"code": null,
"e": 25100,
"s": 25090,
"text": "Examples:"
},
{
"code": null,
"e": 25245,
"s": 25100,
"text": "Input: N = 3, K = 6 Output: 8 Explanation: Numbers which is not divisible by N = 3 – {1, 2, 4, 5, 7, 8, 10} 6th non-divisible number by 3 is 8. "
},
{
"code": null,
"e": 25394,
"s": 25245,
"text": "Input: N = 7, K = 97 Output: 113 Explanation: Numbers which is not divisible by N = 7 – {1, 2, 4, 5, 6, ....} 97th non-divisible number by 7 is 113."
},
{
"code": null,
"e": 25541,
"s": 25394,
"text": "Naive Approach: A simple solution is to iterate over a loop to find the Kth non-divisible number by N. Below is the steps to find the Kth number: "
},
{
"code": null,
"e": 25611,
"s": 25541,
"text": "Initialize the count of non-divisible number and current number to 0."
},
{
"code": null,
"e": 25701,
"s": 25611,
"text": "Iterate using a while loop until the count of the non-divisible number is not equal to K."
},
{
"code": null,
"e": 25800,
"s": 25701,
"text": "Increment the count of the non-divisible number by 1, If the current number is not divisible by N."
},
{
"code": null,
"e": 25851,
"s": 25800,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25855,
"s": 25851,
"text": "C++"
},
{
"code": null,
"e": 25860,
"s": 25855,
"text": "Java"
},
{
"code": null,
"e": 25868,
"s": 25860,
"text": "Python3"
},
{
"code": null,
"e": 25871,
"s": 25868,
"text": "C#"
},
{
"code": null,
"e": 25882,
"s": 25871,
"text": "Javascript"
},
{
"code": "// C++ implementation to find// the K'th non divisible// number by N #include <bits/stdc++.h> using namespace std; // Function to find// the K'th non divisible// number by Nint kthNonDivisible(int N, int K){ int find = 0; int j = 0; // Loop to find the K non // divisible number by N while (find != K) { j++; if (j % N != 0) find++; } return j;} // Driver Codeint main(){ int N = 3; int K = 6; cout << kthNonDivisible(N, K); return 0;}",
"e": 26377,
"s": 25882,
"text": null
},
{
"code": "// Java implementation to find// the K'th non divisible// number by Nclass GFG{ // Function to find// the K'th non divisible// number by Nstatic int kthNonDivisible(int N, int K){ int find = 0; int j = 0; // Loop to find the K non // divisible number by N while (find != K) { j++; if (j % N != 0) find++; } return j;} // Driver codepublic static void main(String[] args){ int N = 3; int K = 6; System.out.print(kthNonDivisible(N, K));}} // This code is contributed by shivanisinghss2110",
"e": 26924,
"s": 26377,
"text": null
},
{
"code": "# Python3 implementation to find# the K'th non divisible# number of Nimport math # Function to find the Kth# not divisible by Ndef kthNonDivisible(n, K): find = 0 j = 0 # Loop to find the K non # divisible number by N while find != K: j = j + 1 if j % N != 0: find = find + 1 return j # Driver CodeN = 3K = 6 # Function Callprint(kthNonDivisible(N, K)) # This code is contributed by ishayadav181",
"e": 27381,
"s": 26924,
"text": null
},
{
"code": "// C# implementation to find the// K'th non-divisible number by Nusing System; class GFG { // Function to find the K'th// non divisible number by Nstatic int kthNonDivisible(int N, int K){ int find = 0; int j = 0; // Loop to find the K non // divisible number by N while (find != K) { j++; if (j % N != 0) find++; } return j;} // Driver codepublic static void Main(String[] args){ int N = 3; int K = 6; Console.Write(kthNonDivisible(N, K));}} // This code is contributed by shivanisinghss2110",
"e": 27943,
"s": 27381,
"text": null
},
{
"code": "<script> // Javascript implementation to find the // K'th non-divisible number by N // Function to find the K'th // non divisible number by N function kthNonDivisible(N, K) { let find = 0; let j = 0; // Loop to find the K non // divisible number by N while (find != K) { j++; if (j % N != 0) find++; } return j; } let N = 3; let K = 6; document.write(kthNonDivisible(N, K)); // This code is contributed by decode2207.</script>",
"e": 28517,
"s": 27943,
"text": null
},
{
"code": null,
"e": 28519,
"s": 28517,
"text": "8"
},
{
"code": null,
"e": 28797,
"s": 28519,
"text": "Another Approach – Using Binary Search The idea is to use Binary Search to solve this problem. The search space for this problem will be from 1 to the maximum integer value and the middle value is computed as the difference of the middle of search space and multiples of the N."
},
{
"code": null,
"e": 28880,
"s": 28797,
"text": "If the middle value is greater than K, then update the value of the H as middle-1."
},
{
"code": null,
"e": 28976,
"s": 28880,
"text": "Otherwise, If the middle value is greater than K, then update the value of the L as middle – 1."
},
{
"code": null,
"e": 29028,
"s": 28976,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 29032,
"s": 29028,
"text": "C++"
},
{
"code": null,
"e": 29037,
"s": 29032,
"text": "Java"
},
{
"code": null,
"e": 29045,
"s": 29037,
"text": "Python3"
},
{
"code": null,
"e": 29048,
"s": 29045,
"text": "C#"
},
{
"code": null,
"e": 29059,
"s": 29048,
"text": "Javascript"
},
{
"code": "// C++ implementation for// above approach#include <bits/stdc++.h>using namespace std; // Function to find the Kth// not divisible by Nvoid kthNonDivisible(int N, int K){ // Lowest possible value int L = 1; // Highest possible value int H = INT_MAX; // To store the Kth non // divisible number of N int ans = 0; // Using binary search while (L <= H) { // Calculating mid value int mid = (L + H) / 2; // Sol would have the value // by subtracting all // multiples of n till mid int sol = mid - mid / N; // Check if sol is greater than k if (sol > K) { // H should be reduced to find // minimum possible value H = mid - 1; } // Check if sol is less than k // then L will be mid+1 else if (sol < K) { L = mid + 1; } // Check if sol is equal to k else { // ans will be mid ans = mid; // H would be reduced to find any // more possible value H = mid - 1; } } // Print the answer cout << ans;} // Driver Codeint main(){ int N = 3; int K = 7; // Function Call kthNonDivisible(N, K); return 0;}",
"e": 30408,
"s": 29059,
"text": null
},
{
"code": "// Java implementation for// above approachclass GFG{ // Function to find the Kth// not divisible by Npublic static void kthNonDivisible(int N, int K){ // Lowest possible value int L = 1; // Highest possible value int H = Integer.MAX_VALUE; // To store the Kth non // divisible number of N int ans = 0; // Using binary search while (L <= H) { // Calculating mid value int mid = (L + H) / 2; // Sol would have the value // by subtracting all // multiples of n till mid int sol = mid - mid / N; // Check if sol is greater than k if (sol > K) { // H should be reduced to find // minimum possible value H = mid - 1; } // Check if sol is less than k // then L will be mid+1 else if (sol < K) { L = mid + 1; } // Check if sol is equal to k else { // ans will be mid ans = mid; // H would be reduced to find any // more possible value H = mid - 1; } } // Print the answer System.out.print(ans);} // Driver codepublic static void main(String[] args){ int N = 3; int K = 7; // Function Call kthNonDivisible(N, K);}} // This code is contributed by divyeshrabadiya07",
"e": 31876,
"s": 30408,
"text": null
},
{
"code": "# Python3 implementation for# above approachimport sys # Function to find the Kth# not divisible by Ndef kthNonDivisible(N, K): # Lowest possible value L = 1 # Highest possible value H = sys.maxsize # To store the Kth non # divisible number of N ans = 0 # Using binary search while (L <= H): # Calculating mid value mid = (L + H) // 2 # Sol would have the value # by subtracting all # multiples of n till mid sol = mid - mid // N # Check if sol is greater than k if (sol > K): # H should be reduced to find # minimum possible value H = mid - 1 # Check if sol is less than k # then L will be mid+1 elif (sol < K): L = mid + 1 # Check if sol is equal to k else: # ans will be mid ans = mid # H would be reduced to find any # more possible value H = mid - 1 # Print the answer print(ans) # Driver CodeN = 3K = 7 # Function callkthNonDivisible(N, K) # This code is contributed by ANKITKUMAR34",
"e": 33061,
"s": 31876,
"text": null
},
{
"code": "// C# implementation for// above approachusing System; class GFG{ // Function to find the Kth// not divisible by Nstatic void kthNonDivisible(int N, int K){ // Lowest possible value int L = 1; // Highest possible value int H = Int32.MaxValue; // To store the Kth non // divisible number of N int ans = 0; // Using binary search while (L <= H) { // Calculating mid value int mid = (L + H) / 2; // Sol would have the value // by subtracting all // multiples of n till mid int sol = mid - mid / N; // Check if sol is greater than k if (sol > K) { // H should be reduced to find // minimum possible value H = mid - 1; } // Check if sol is less than k // then L will be mid+1 else if (sol < K) { L = mid + 1; } // Check if sol is equal to k else { // ans will be mid ans = mid; // H would be reduced to find // any more possible value H = mid - 1; } } // Print the answer Console.Write(ans);} // Driver codestatic void Main(){ int N = 3; int K = 7; // Function Call kthNonDivisible(N, K);}} // This code is contributed by divyesh072019",
"e": 34480,
"s": 33061,
"text": null
},
{
"code": "<script> // Javascript implementation for above approach // Function to find the Kth // not divisible by N function kthNonDivisible(N, K) { // Lowest possible value let L = 1; // Highest possible value let H = 2147483647; // To store the Kth non // divisible number of N let ans = 0; // Using binary search while (L <= H) { // Calculating mid value let mid = parseInt((L + H) / 2, 10); // Sol would have the value // by subtracting all // multiples of n till mid let sol = mid - parseInt(mid / N, 10); // Check if sol is greater than k if (sol > K) { // H should be reduced to find // minimum possible value H = mid - 1; } // Check if sol is less than k // then L will be mid+1 else if (sol < K) { L = mid + 1; } // Check if sol is equal to k else { // ans will be mid ans = mid; // H would be reduced to find // any more possible value H = mid - 1; } } // Print the answer document.write(ans); } let N = 3; let K = 7; // Function Call kthNonDivisible(N, K); // This code is contributed by mukesh07.</script>",
"e": 35984,
"s": 34480,
"text": null
},
{
"code": null,
"e": 35987,
"s": 35984,
"text": "10"
},
{
"code": null,
"e": 36012,
"s": 35987,
"text": "Time Complexity: O(logN)"
},
{
"code": null,
"e": 36254,
"s": 36012,
"text": "Efficient Approach: The key observation in the problem is that every number from 1 to N-1 is not divisible by N and then Similarly, N + 1 to 2*N – 1 is also not divisible by N. Keeping this in mind, the Kth number not divisible by N will be:"
},
{
"code": null,
"e": 36305,
"s": 36254,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 36309,
"s": 36305,
"text": "C++"
},
{
"code": null,
"e": 36314,
"s": 36309,
"text": "Java"
},
{
"code": null,
"e": 36322,
"s": 36314,
"text": "Python3"
},
{
"code": null,
"e": 36325,
"s": 36322,
"text": "C#"
},
{
"code": null,
"e": 36336,
"s": 36325,
"text": "Javascript"
},
{
"code": "// C++ implementation to find// the K'th non-divisible// number of N #include <bits/stdc++.h> using namespace std;// Function to find the Kth// not divisible by Nint kthNonDivisible(int N, int K){ return K + floor((K - 1) / (N - 1));} // Driver Codeint main(){ int N = 3; int K = 6; // Function Call cout << kthNonDivisible(N, K); return 0;}",
"e": 36697,
"s": 36336,
"text": null
},
{
"code": "// Java implementation to find the// K'th non-divisible number of Nclass GFG{ // Function to find the Kth// not divisible by Nstatic int kthNonDivisible(int N, int K){ return (int) (K + Math.floor((K - 1) / (N - 1)));} // Driver Codepublic static void main(String[] args){ int N = 3; int K = 6; // Function Call System.out.print(kthNonDivisible(N, K));}} // This code is contributed by amal kumar choubey",
"e": 37122,
"s": 36697,
"text": null
},
{
"code": "# Python3 implementation to find# the K'th non-divisible# number of Nimport math # Function to find the Kth# not divisible by Ndef kthNonDivisible(N, K): return K + math.floor((K - 1) / (N - 1)) # Driver CodeN = 3K = 6 # Function Callprint(kthNonDivisible(N, K)) # This code is contributed by ishayadav181",
"e": 37440,
"s": 37122,
"text": null
},
{
"code": "// C# implementation to find the// K'th non-divisible number of Nusing System; class GFG{ // Function to find the Kth// not divisible by Nstatic int kthNonDivisible(int N, int K){ return (int) (K + Math.Floor((double)(K - 1) / (N - 1)));} // Driver Codepublic static void Main(String[] args){ int N = 3; int K = 6; // Function Call Console.Write(kthNonDivisible(N, K));}} // This code is contributed by amal kumar choubey",
"e": 37922,
"s": 37440,
"text": null
},
{
"code": "<script> // Javascript implementation to find// the K'th non-divisible// number of N // Function to find the Kth// not divisible by Nfunction kthNonDivisible(N, K){ return K + parseInt( Math.floor((K - 1) / (N - 1)), 10);} // Driver codelet N = 3;let K = 6; // Function Calldocument.write(kthNonDivisible(N, K)); // This code is contributed by suresh07 </script>",
"e": 38297,
"s": 37922,
"text": null
},
{
"code": null,
"e": 38299,
"s": 38297,
"text": "8"
},
{
"code": null,
"e": 38312,
"s": 38299,
"text": "ishayadav181"
},
{
"code": null,
"e": 38331,
"s": 38312,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 38350,
"s": 38331,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 38369,
"s": 38350,
"text": "mishrapriyanshu557"
},
{
"code": null,
"e": 38382,
"s": 38369,
"text": "ANKITKUMAR34"
},
{
"code": null,
"e": 38399,
"s": 38382,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 38417,
"s": 38399,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 38431,
"s": 38417,
"text": "divyesh072019"
},
{
"code": null,
"e": 38440,
"s": 38431,
"text": "suresh07"
},
{
"code": null,
"e": 38451,
"s": 38440,
"text": "decode2207"
},
{
"code": null,
"e": 38460,
"s": 38451,
"text": "mukesh07"
},
{
"code": null,
"e": 38473,
"s": 38460,
"text": "divisibility"
},
{
"code": null,
"e": 38481,
"s": 38473,
"text": "Numbers"
},
{
"code": null,
"e": 38505,
"s": 38481,
"text": "Competitive Programming"
},
{
"code": null,
"e": 38518,
"s": 38505,
"text": "Mathematical"
},
{
"code": null,
"e": 38531,
"s": 38518,
"text": "Mathematical"
},
{
"code": null,
"e": 38539,
"s": 38531,
"text": "Numbers"
},
{
"code": null,
"e": 38637,
"s": 38539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38646,
"s": 38637,
"text": "Comments"
},
{
"code": null,
"e": 38659,
"s": 38646,
"text": "Old Comments"
},
{
"code": null,
"e": 38737,
"s": 38659,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 38775,
"s": 38737,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 38800,
"s": 38775,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 38848,
"s": 38800,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 38891,
"s": 38848,
"text": "How to begin with Competitive Programming?"
},
{
"code": null,
"e": 38921,
"s": 38891,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38981,
"s": 38921,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38996,
"s": 38981,
"text": "C++ Data Types"
},
{
"code": null,
"e": 39039,
"s": 38996,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Text Animation with changing the color of the text using HTML & CSS - GeeksforGeeks | 11 Jun, 2020
Text animation is the creation of beautiful and colourful letters, words and paragraphs with a decorative movable effect. The movement can be seen in some fashion within the area or across the screen following some regular pattern.
HTML Code: In this section, the basic structure of the code is designed by using HTML. Text animation is created with changing the color of the text by using some CSS properties .
html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Text Animation</title> <link rel="stylesheet" href="style.css"></head><body> <div class="container"> <div class="row"> <span class="text1">Hello!</span> <span class="text2">GeeksforGeeks</span> </div> </div></body></html>
CSS Code: In this section, CSS properties are used to create Text Animation.@keyframes are used which defines the code for animation. The animation is created by gradually changing from one set of CSS styles to another. The change of styles or transformations are taking place in percentages, or by using keywords “from” and “to”, which is actually 0% and 100%. The set of CSS styles can be changed many times.
Syntax for @keyframes:
@keyframes animationname {keyframes-selector {css-styles;}}
css
*{ padding: 0; margin: 0; font-family: sans-serif;}body{ background: yellowgreen;}.container{ text-align: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%;}.container span{ display: block;}.text1{ color: white; font-size: 70px; font-weight: 700; letter-spacing: 8px; margin-bottom: 20px; background: yellowgreen; position: relative; animation: text 3s 1;}.text2{ font-size: 30px; color: darkgreen; font-family: Georgia, serif;}@keyframes text{ 0%{ color: black; margin-bottom: -40px; } 30%{ letter-spacing: 25px; margin-bottom: -40px; } 85%{ letter-spacing: 8px; margin-bottom: -40px; }}
Complete Code: It is the combination of above two code sections.
html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Text Animation</title> <style> * { padding: 0; margin: 0; font-family: sans-serif; } body { background: yellowgreen; } .container { text-align: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%; } .container span { display: block; } .text1 { color: white; font-size: 70px; font-weight: 700; letter-spacing: 8px; margin-bottom: 20px; background: yellowgreen; position: relative; animation: text 3s 1; } .text2 { font-size: 30px; color: darkgreen; font-family: Georgia, serif; } @keyframes text { 0% { color: black; margin-bottom: -40px; } 30% { letter-spacing: 25px; margin-bottom: -40px; } 85% { letter-spacing: 8px; margin-bottom: -40px; } } </style></head> <body> <div class="container"> <div class="row"> <span class="text1">Hello!</span> <span class="text2">GeeksforGeeks</span> </div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
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 ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
HTML Cheat Sheet - A Basic Guide to HTML
How to update Node.js and NPM to next version ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 24788,
"s": 24760,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 25020,
"s": 24788,
"text": "Text animation is the creation of beautiful and colourful letters, words and paragraphs with a decorative movable effect. The movement can be seen in some fashion within the area or across the screen following some regular pattern."
},
{
"code": null,
"e": 25200,
"s": 25020,
"text": "HTML Code: In this section, the basic structure of the code is designed by using HTML. Text animation is created with changing the color of the text by using some CSS properties ."
},
{
"code": null,
"e": 25205,
"s": 25200,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Text Animation</title> <link rel=\"stylesheet\" href=\"style.css\"></head><body> <div class=\"container\"> <div class=\"row\"> <span class=\"text1\">Hello!</span> <span class=\"text2\">GeeksforGeeks</span> </div> </div></body></html>",
"e": 25608,
"s": 25205,
"text": null
},
{
"code": null,
"e": 26019,
"s": 25608,
"text": "CSS Code: In this section, CSS properties are used to create Text Animation.@keyframes are used which defines the code for animation. The animation is created by gradually changing from one set of CSS styles to another. The change of styles or transformations are taking place in percentages, or by using keywords “from” and “to”, which is actually 0% and 100%. The set of CSS styles can be changed many times."
},
{
"code": null,
"e": 26042,
"s": 26019,
"text": "Syntax for @keyframes:"
},
{
"code": null,
"e": 26103,
"s": 26042,
"text": "@keyframes animationname {keyframes-selector {css-styles;}} "
},
{
"code": null,
"e": 26109,
"s": 26105,
"text": "css"
},
{
"code": "*{ padding: 0; margin: 0; font-family: sans-serif;}body{ background: yellowgreen;}.container{ text-align: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%;}.container span{ display: block;}.text1{ color: white; font-size: 70px; font-weight: 700; letter-spacing: 8px; margin-bottom: 20px; background: yellowgreen; position: relative; animation: text 3s 1;}.text2{ font-size: 30px; color: darkgreen; font-family: Georgia, serif;}@keyframes text{ 0%{ color: black; margin-bottom: -40px; } 30%{ letter-spacing: 25px; margin-bottom: -40px; } 85%{ letter-spacing: 8px; margin-bottom: -40px; }}",
"e": 26873,
"s": 26109,
"text": null
},
{
"code": null,
"e": 26940,
"s": 26873,
"text": "Complete Code: It is the combination of above two code sections. "
},
{
"code": null,
"e": 26945,
"s": 26940,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Text Animation</title> <style> * { padding: 0; margin: 0; font-family: sans-serif; } body { background: yellowgreen; } .container { text-align: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100%; } .container span { display: block; } .text1 { color: white; font-size: 70px; font-weight: 700; letter-spacing: 8px; margin-bottom: 20px; background: yellowgreen; position: relative; animation: text 3s 1; } .text2 { font-size: 30px; color: darkgreen; font-family: Georgia, serif; } @keyframes text { 0% { color: black; margin-bottom: -40px; } 30% { letter-spacing: 25px; margin-bottom: -40px; } 85% { letter-spacing: 8px; margin-bottom: -40px; } } </style></head> <body> <div class=\"container\"> <div class=\"row\"> <span class=\"text1\">Hello!</span> <span class=\"text2\">GeeksforGeeks</span> </div> </div></body> </html>",
"e": 28522,
"s": 26945,
"text": null
},
{
"code": null,
"e": 28530,
"s": 28522,
"text": "Output:"
},
{
"code": null,
"e": 28667,
"s": 28530,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28676,
"s": 28667,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28686,
"s": 28676,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28690,
"s": 28686,
"text": "CSS"
},
{
"code": null,
"e": 28695,
"s": 28690,
"text": "HTML"
},
{
"code": null,
"e": 28712,
"s": 28695,
"text": "Web Technologies"
},
{
"code": null,
"e": 28739,
"s": 28712,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28744,
"s": 28739,
"text": "HTML"
},
{
"code": null,
"e": 28842,
"s": 28744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28890,
"s": 28842,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28927,
"s": 28890,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28991,
"s": 28927,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29030,
"s": 28991,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29067,
"s": 29030,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29127,
"s": 29067,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29168,
"s": 29127,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 29216,
"s": 29168,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29269,
"s": 29216,
"text": "Hide or show elements in HTML using display property"
}
]
|
Add a new column and set values in it on the basis of conditions in MySQL? | To set values on the basis of conditions, use IF() method. Let us first create a table −
mysql> create table DemoTable
-> (
-> Age int
-> );
Query OK, 0 rows affected (0.55 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(19);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(16);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(17);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(22);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+
| Age |
+------+
| 19 |
| 16 |
| 17 |
| 22 |
+------+
4 rows in set (0.00 sec)
Following is the query to set values on the basis of condition −
mysql> select Age,if(Age > 18,'You are qualified!','Sorry, you are rejected!') AS Result from
DemoTable;
This will produce the following output −
+------+-------------------------+
| Age | Result |
+------+-------------------------+
| 19 | You are qualified! |
| 16 | Sorry, you are rejected!|
| 17 | Sorry, you are rejected!|
| 22 | You are qualified! |
+------+-------------------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To set values on the basis of conditions, use IF() method. Let us first create a table −"
},
{
"code": null,
"e": 1249,
"s": 1151,
"text": "mysql> create table DemoTable\n -> (\n -> Age int\n -> );\nQuery OK, 0 rows affected (0.55 sec)"
},
{
"code": null,
"e": 1305,
"s": 1249,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1616,
"s": 1305,
"text": "mysql> insert into DemoTable values(19);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DemoTable values(16);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable values(17);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DemoTable values(22);\nQuery OK, 1 row affected (0.19 sec)"
},
{
"code": null,
"e": 1676,
"s": 1616,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1707,
"s": 1676,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1748,
"s": 1707,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1845,
"s": 1748,
"text": "+------+\n| Age |\n+------+\n| 19 |\n| 16 |\n| 17 |\n| 22 |\n+------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1910,
"s": 1845,
"text": "Following is the query to set values on the basis of condition −"
},
{
"code": null,
"e": 2015,
"s": 1910,
"text": "mysql> select Age,if(Age > 18,'You are qualified!','Sorry, you are rejected!') AS Result from\nDemoTable;"
},
{
"code": null,
"e": 2056,
"s": 2015,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2361,
"s": 2056,
"text": "+------+-------------------------+\n| Age | Result |\n+------+-------------------------+\n| 19 | You are qualified! |\n| 16 | Sorry, you are rejected!|\n| 17 | Sorry, you are rejected!|\n| 22 | You are qualified! |\n+------+-------------------------+\n4 rows in set (0.00 sec)"
}
]
|
C++ Program to Check the Connectivity of Undirected Graph Using BFS | To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected.
For the undirected graph, we will select one node and traverse from it.
In this case the traversal algorithm is recursive BFS traversal.
Input − Adjacency matrix of a graph
Output − The Graph is connected.
Input − The start node s and the visited node to mark which node is visited.
Output − Traverse all connected vertices.
Begin
mark s as visited
insert s into a queue Q
until the Q is not empty, do
u = node that is taken out from the queue
for each node v of the graph, do
if the u and v are connected, then
if u is not visited, then
mark u as visited
insert u into the queue Q.
done
done
End
Input − The graph.
Output − True if the graph is connected.
Begin
define visited array
for all vertices u in the graph, do
make all nodes unvisited
traverse(u, visited)
if any unvisited node is still remaining, then
return false
done
return true
End
Live Demo
#include<iostream>
#include<queue>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 1, 0, 0},
{1, 0, 1, 1, 0},
{1, 1, 0, 1, 1},
{0, 1, 1, 0, 1},
{0, 0, 1, 1, 0}};
void traverse(int s, bool visited[]) {
visited[s] = true; //mark v as visited
queue<int> que;
que.push(s);//insert s into queue
while(!que.empty()) {
int u = que.front(); //delete from queue and print
que.pop();
for(int i = 0; i < NODE; i++) {
if(graph[i][u]) {
//when the node is non-visited
if(!visited[i]) {
visited[i] = true;
que.push(i);
}
}
}
}
}
bool isConnected() {
bool *vis = new bool[NODE];
//for all vertex u as start point, check whether all nodes are visible or not
for(int u; u < NODE; u++) {
for(int i = 0; i < NODE; i++)
vis[i] = false; //initialize as no node is visited
traverse(u, vis);
for(int i = 0; i < NODE; i++) {
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
}
return true;
}
int main() {
if(isConnected())
cout << "The Graph is connected.";
else
cout << "The Graph is not connected.";
}
The Graph is connected. | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected."
},
{
"code": null,
"e": 1342,
"s": 1270,
"text": "For the undirected graph, we will select one node and traverse from it."
},
{
"code": null,
"e": 1407,
"s": 1342,
"text": "In this case the traversal algorithm is recursive BFS traversal."
},
{
"code": null,
"e": 1443,
"s": 1407,
"text": "Input − Adjacency matrix of a graph"
},
{
"code": null,
"e": 1476,
"s": 1443,
"text": "Output − The Graph is connected."
},
{
"code": null,
"e": 1553,
"s": 1476,
"text": "Input − The start node s and the visited node to mark which node is visited."
},
{
"code": null,
"e": 1595,
"s": 1553,
"text": "Output − Traverse all connected vertices."
},
{
"code": null,
"e": 1930,
"s": 1595,
"text": "Begin\n mark s as visited\n insert s into a queue Q\n until the Q is not empty, do\n u = node that is taken out from the queue\n for each node v of the graph, do\n if the u and v are connected, then\n if u is not visited, then\n mark u as visited\n insert u into the queue Q.\n done\n done\nEnd"
},
{
"code": null,
"e": 1949,
"s": 1930,
"text": "Input − The graph."
},
{
"code": null,
"e": 1990,
"s": 1949,
"text": "Output − True if the graph is connected."
},
{
"code": null,
"e": 2219,
"s": 1990,
"text": "Begin\n define visited array\n for all vertices u in the graph, do\n make all nodes unvisited\n traverse(u, visited)\n if any unvisited node is still remaining, then\n return false\n done\n return true\nEnd"
},
{
"code": null,
"e": 2230,
"s": 2219,
"text": " Live Demo"
},
{
"code": null,
"e": 3508,
"s": 2230,
"text": "#include<iostream>\n#include<queue>\n#define NODE 5\nusing namespace std;\nint graph[NODE][NODE] = {\n {0, 1, 1, 0, 0},\n {1, 0, 1, 1, 0},\n {1, 1, 0, 1, 1},\n {0, 1, 1, 0, 1},\n {0, 0, 1, 1, 0}};\nvoid traverse(int s, bool visited[]) {\n visited[s] = true; //mark v as visited\n queue<int> que;\n que.push(s);//insert s into queue\n while(!que.empty()) {\n int u = que.front(); //delete from queue and print\n que.pop();\n for(int i = 0; i < NODE; i++) {\n if(graph[i][u]) {\n //when the node is non-visited\n if(!visited[i]) {\n visited[i] = true;\n que.push(i);\n }\n }\n }\n }\n}\nbool isConnected() {\n bool *vis = new bool[NODE];\n //for all vertex u as start point, check whether all nodes are visible or not\n for(int u; u < NODE; u++) {\n for(int i = 0; i < NODE; i++)\n vis[i] = false; //initialize as no node is visited\n traverse(u, vis);\n for(int i = 0; i < NODE; i++) {\n if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected\n return false;\n }\n }\n return true;\n}\nint main() {\n if(isConnected())\n cout << \"The Graph is connected.\";\n else\n cout << \"The Graph is not connected.\";\n}"
},
{
"code": null,
"e": 3532,
"s": 3508,
"text": "The Graph is connected."
}
]
|
Check if URL is valid or not in Java - GeeksforGeeks | 30 May, 2018
Given a URL as string, we need to find if the given URL is valid or not.
Input : str = "https://www.geeksforgeeks.org/"
Output : Yes
Input : str = "https:// www.geeksforgeeks.org/"
Output : No
Note that there is a space after https://
Using java.net.urlWe can use java.net.url class to validate a URL. The idea is to create a URL object from the specified String representation. If we do not get exception while creating the object, we return true. Else we return false.
// Java program to check if a URL is valid // using java.net.urlimport java.net.URL; class Test { /* Returns true if url is valid */ public static boolean isValid(String url) { /* Try creating a valid URL */ try { new URL(url).toURI(); return true; } // If there was an Exception // while creating URL object catch (Exception e) { return false; } } /*driver function*/ public static void main(String[] args) { String url1 = "https://www.geeksforgeeks.org/"; if (isValid(url1)) System.out.println("Yes"); else System.out.println("No"); String url2 = "http:// www.geeksforgeeks.org/"; if (isValid(url2)) System.out.println("Yes"); else System.out.println("No"); }}
Output:
Yes
No
This article is contributed by Pranav . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
java-regular-expression
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 25347,
"s": 25319,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 25420,
"s": 25347,
"text": "Given a URL as string, we need to find if the given URL is valid or not."
},
{
"code": null,
"e": 25585,
"s": 25420,
"text": "Input : str = \"https://www.geeksforgeeks.org/\"\nOutput : Yes\n\n\nInput : str = \"https:// www.geeksforgeeks.org/\"\nOutput : No\nNote that there is a space after https://\n"
},
{
"code": null,
"e": 25821,
"s": 25585,
"text": "Using java.net.urlWe can use java.net.url class to validate a URL. The idea is to create a URL object from the specified String representation. If we do not get exception while creating the object, we return true. Else we return false."
},
{
"code": "// Java program to check if a URL is valid // using java.net.urlimport java.net.URL; class Test { /* Returns true if url is valid */ public static boolean isValid(String url) { /* Try creating a valid URL */ try { new URL(url).toURI(); return true; } // If there was an Exception // while creating URL object catch (Exception e) { return false; } } /*driver function*/ public static void main(String[] args) { String url1 = \"https://www.geeksforgeeks.org/\"; if (isValid(url1)) System.out.println(\"Yes\"); else System.out.println(\"No\"); String url2 = \"http:// www.geeksforgeeks.org/\"; if (isValid(url2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 26736,
"s": 25821,
"text": null
},
{
"code": null,
"e": 26744,
"s": 26736,
"text": "Output:"
},
{
"code": null,
"e": 26752,
"s": 26744,
"text": "Yes\nNo\n"
},
{
"code": null,
"e": 27047,
"s": 26752,
"text": "This article is contributed by Pranav . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27172,
"s": 27047,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27196,
"s": 27172,
"text": "java-regular-expression"
},
{
"code": null,
"e": 27201,
"s": 27196,
"text": "Java"
},
{
"code": null,
"e": 27206,
"s": 27201,
"text": "Java"
},
{
"code": null,
"e": 27304,
"s": 27206,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27319,
"s": 27304,
"text": "Stream In Java"
},
{
"code": null,
"e": 27338,
"s": 27319,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27359,
"s": 27338,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27389,
"s": 27359,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27435,
"s": 27389,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27452,
"s": 27435,
"text": "Generics in Java"
},
{
"code": null,
"e": 27473,
"s": 27452,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27516,
"s": 27473,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27538,
"s": 27516,
"text": "PriorityQueue in Java"
}
]
|
How to retrieve android API version programmatically? | This example demonstrates how do I retrieve android API version programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_above="@id/button"
android:layout_centerInParent="true"
android:layout_marginBottom="12sp"
android:textSize="24sp"
android:textStyle="bold|italic" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold"
android:text="Get Android API Version" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
int androidVersion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
androidVersion = Build.VERSION.SDK_INT;
switch (androidVersion) {
case 14:
textView.setText("15, Ice Cream Sandwich");
break;
case 15:
textView.setText("15, Ice Cream Sandwich");
break;
case 16:
textView.setText("16, Jelly Bean");
break;
case 17:
textView.setText("17, Jelly Bean");
break;
case 18:
textView.setText("18, Jelly Bean");
break;
case 19:
textView.setText("19, KitKat");
break;
case 21:
textView.setText("21, Lollipop");
break;
case 22:
textView.setText("22, Lollipop");
break;
case 23:
textView.setText("23, Marshmallow");
break;
case 24:
textView.setText("24, Nougat");
break;
case 25:
textView.setText("25, Nougat");
break;
case 26:
textView.setText("26, Oreo");
break;
default:
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_LONG).show();
break;
}
}
});
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − | [
{
"code": null,
"e": 1144,
"s": 1062,
"text": "This example demonstrates how do I retrieve android API version programmatically."
},
{
"code": null,
"e": 1273,
"s": 1144,
"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": 1338,
"s": 1273,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2263,
"s": 1338,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"\"\n android:layout_above=\"@id/button\"\n android:layout_centerInParent=\"true\"\n android:layout_marginBottom=\"12sp\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold|italic\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:text=\"Get Android API Version\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2320,
"s": 2263,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4483,
"s": 2320,
"text": "import android.os.Build;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n TextView textView;\n int androidVersion;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n androidVersion = Build.VERSION.SDK_INT;\n switch (androidVersion) {\n case 14:\n textView.setText(\"15, Ice Cream Sandwich\");\n break;\n case 15:\n textView.setText(\"15, Ice Cream Sandwich\");\n break;\n case 16:\n textView.setText(\"16, Jelly Bean\");\n break;\n case 17:\n textView.setText(\"17, Jelly Bean\");\n break;\n case 18:\n textView.setText(\"18, Jelly Bean\");\n break;\n case 19:\n textView.setText(\"19, KitKat\");\n break;\n case 21:\n textView.setText(\"21, Lollipop\");\n break;\n case 22:\n textView.setText(\"22, Lollipop\");\n break;\n case 23:\n textView.setText(\"23, Marshmallow\");\n break;\n case 24:\n textView.setText(\"24, Nougat\");\n break;\n case 25:\n textView.setText(\"25, Nougat\");\n break;\n case 26:\n textView.setText(\"26, Oreo\");\n break;\n default:\n Toast.makeText(MainActivity.this, \"Not Found\", Toast.LENGTH_LONG).show();\n break;\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 4538,
"s": 4483,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5244,
"s": 4538,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5590,
"s": 5244,
"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 −"
}
]
|
Count Full Prime numbers in a given range - GeeksforGeeks | 08 Feb, 2022
Given two integers L and R, the task is to count the number of full prime numbers that are present in the given range.
A number is said to be Full prime if the number itself is prime and all its digits are also prime.
Examples:
53 is Full Prime because it is prime and all its digits (5 and 3) are also prime.
13 is not Full Prime because it has a non-prime digit ( 1 is not prime).
Examples:
Input: L = 1, R = 100Output : 8Explanations: 2 3 5 7 23 37 53 73 are the Full Prime numbers between 1 and 100. Therefore, the count is 8.
Input: L = 200, R = 300Output: 5Explanation: 223 227 233 257 277 are the Full Prime numbers between 200 and 300. Therefore, the count is 5.
Approach: Follow the steps below to solve the problem:
Simply traverse the range from L to R.
For every number i in the range, check if it is divisible by any number from the range [2, sqrt(i)]. If found to be true, then it is not a prime. Proceed to the next number.
Otherwise, check if all its digits are prime or not. If found to be true, increase count.
Finally, after complete traversal of the range, print the value of count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a// number is prime or notbool isPrime(int num){ if (num <= 1) return false; for (int i = 2; i * i <= num; i++) // If a divisor of n exists if (num % i == 0) return false; return true;} // Function to check if a// number is Full Prime or notbool isFulPrime(int n){ // If n is not a prime if (!isPrime(n)) return false; // Otherwise else { while (n > 0) { // Extract digit int rem = n % 10; // If any digit of n // is non-prime if (!(rem == 2 || rem == 3 || rem == 5 || rem == 7)) return false; n = n / 10; } } return true;} // Function to print count of// Full Primes in a range [L, R]int countFulPrime(int L, int R){ // Stores count of full primes int cnt = 0; for (int i = L; i <= R; i++) { // Check if i is full prime if ((i % 2) != 0 && isFulPrime(i)) { cnt++; } } return cnt;} // Driver Codeint main(){ int L = 1, R = 100; // Stores count of full primes int ans = 0; if (L < 3) ans++; cout << ans + countFulPrime(L, R); return 0;}
// Java program to implement// the above approachimport java.io.*;import java.util.*; class GFG{ // Function to check if a// number is prime or notstatic boolean isPrime(int num){ if (num <= 1) return false; for(int i = 2; i * i <= num; i++) // If a divisor of n exists if (num % i == 0) return false; return true;} // Function to check if a// number is Full Prime or notstatic boolean isFulPrime(int n){ // If n is not a prime if (!isPrime(n)) return false; // Otherwise else { while (n > 0) { // Extract digit int rem = n % 10; // If any digit of n // is non-prime if (!(rem == 2 || rem == 3 || rem == 5 || rem == 7)) return false; n = n / 10; } } return true;} // Function to print count of// Full Primes in a range [L, R]static int countFulPrime(int L, int R){ // Stores count of full primes int cnt = 0; for(int i = L; i <= R; i++) { // Check if i is full prime if ((i % 2) != 0 && isFulPrime(i)) { cnt++; } } return cnt;} // Driver Codepublic static void main (String[] args){ int L = 1, R = 100; // Stores count of full primes int ans = 0; if (L < 3) ans++; System.out.println(ans + countFulPrime(L, R));}} // This code is contributed by sanjoy_62
# Python3 program to implement# the above approach # Function to check if a# number is prime or notdef isPrime(num): if (num <= 1): return False for i in range(2, num + 1): if i * i > num: break # If a divisor of n exists if (num % i == 0): return False return True # Function to check if a# number is Full Prime or notdef isFulPrime(n): # If n is not a prime if (not isPrime(n)): return False # Otherwise else: while (n > 0): # Extract digit rem = n % 10 # If any digit of n # is non-prime if (not (rem == 2 or rem == 3 or rem == 5 or rem == 7)): return False n = n // 10 return True # Function to print count of# Full Primes in a range [L, R]def countFulPrime(L, R): # Stores count of full primes cnt = 0 for i in range(L, R + 1): # Check if i is full prime if ((i % 2) != 0 and isFulPrime(i)): cnt += 1 return cnt # Driver Codeif __name__ == '__main__': L = 1 R = 100 # Stores count of full primes ans = 0 if (L < 3): ans += 1 print(ans + countFulPrime(L, R)) # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System; class GFG{ // Function to check if a// number is prime or notstatic bool isPrime(int num){ if (num <= 1) return false; for(int i = 2; i * i <= num; i++) // If a divisor of n exists if (num % i == 0) return false; return true;} // Function to check if a// number is Full Prime or notstatic bool isFulPrime(int n){ // If n is not a prime if (!isPrime(n)) return false; // Otherwise else { while (n > 0) { // Extract digit int rem = n % 10; // If any digit of n // is non-prime if (!(rem == 2 || rem == 3 || rem == 5 || rem == 7)) return false; n = n / 10; } } return true;} // Function to print count of// Full Primes in a range [L, R]static int countFulPrime(int L, int R){ // Stores count of full primes int cnt = 0; for(int i = L; i <= R; i++) { // Check if i is full prime if ((i % 2) != 0 && isFulPrime(i)) { cnt++; } } return cnt;} // Driver Codepublic static void Main (String[] args){ int L = 1, R = 100; // Stores count of full primes int ans = 0; if (L < 3) ans++; Console.WriteLine(ans + countFulPrime(L, R));}} // This code is contributed by math_lover
<script> // Javascript Program to implement// the above approach // Function to check if a// number is prime or notfunction isPrime(num){ if (num <= 1) return false; for(let i = 2; i * i <= num; i++) // If a divisor of n exists if (num % i == 0) return false; return true;} // Function to check if a// number is Full Prime or notfunction isFulPrime(n){ // If n is not a prime if (!isPrime(n)) return false; // Otherwise else { while (n > 0) { // Extract digit let rem = n % 10; // If any digit of n // is non-prime if (!(rem == 2 || rem == 3 || rem == 5 || rem == 7)) return false; n = Math.floor(n / 10); } } return true;} // Function to print count of// Full Primes in a range [L, R]function countFulPrime(L, R){ // Stores count of full primes let cnt = 0; for(let i = L; i <= R; i++) { // Check if i is full prime if ((i % 2) != 0 && isFulPrime(i)) { cnt++; } } return cnt;} // Driver codelet L = 1, R = 100; // Stores count of full primeslet ans = 0; if (L < 3) ans++; document.write(ans + countFulPrime(L, R)); // This code is contributed by splevel62 </script>
8
Time Complexity: O(N3/2)Auxiliary Space: O(1)
mohit kumar 29
sanjoy_62
math_lover
splevel62
simmytarika5
surinderdawra388
divisibility
number-digits
Prime Number
Mathematical
Searching
Searching
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number | [
{
"code": null,
"e": 26695,
"s": 26667,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 26814,
"s": 26695,
"text": "Given two integers L and R, the task is to count the number of full prime numbers that are present in the given range."
},
{
"code": null,
"e": 26914,
"s": 26814,
"text": "A number is said to be Full prime if the number itself is prime and all its digits are also prime. "
},
{
"code": null,
"e": 26925,
"s": 26914,
"text": "Examples: "
},
{
"code": null,
"e": 27007,
"s": 26925,
"text": "53 is Full Prime because it is prime and all its digits (5 and 3) are also prime."
},
{
"code": null,
"e": 27080,
"s": 27007,
"text": "13 is not Full Prime because it has a non-prime digit ( 1 is not prime)."
},
{
"code": null,
"e": 27090,
"s": 27080,
"text": "Examples:"
},
{
"code": null,
"e": 27228,
"s": 27090,
"text": "Input: L = 1, R = 100Output : 8Explanations: 2 3 5 7 23 37 53 73 are the Full Prime numbers between 1 and 100. Therefore, the count is 8."
},
{
"code": null,
"e": 27368,
"s": 27228,
"text": "Input: L = 200, R = 300Output: 5Explanation: 223 227 233 257 277 are the Full Prime numbers between 200 and 300. Therefore, the count is 5."
},
{
"code": null,
"e": 27423,
"s": 27368,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27462,
"s": 27423,
"text": "Simply traverse the range from L to R."
},
{
"code": null,
"e": 27636,
"s": 27462,
"text": "For every number i in the range, check if it is divisible by any number from the range [2, sqrt(i)]. If found to be true, then it is not a prime. Proceed to the next number."
},
{
"code": null,
"e": 27726,
"s": 27636,
"text": "Otherwise, check if all its digits are prime or not. If found to be true, increase count."
},
{
"code": null,
"e": 27800,
"s": 27726,
"text": "Finally, after complete traversal of the range, print the value of count."
},
{
"code": null,
"e": 27851,
"s": 27800,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27855,
"s": 27851,
"text": "C++"
},
{
"code": null,
"e": 27860,
"s": 27855,
"text": "Java"
},
{
"code": null,
"e": 27868,
"s": 27860,
"text": "Python3"
},
{
"code": null,
"e": 27871,
"s": 27868,
"text": "C#"
},
{
"code": null,
"e": 27882,
"s": 27871,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a// number is prime or notbool isPrime(int num){ if (num <= 1) return false; for (int i = 2; i * i <= num; i++) // If a divisor of n exists if (num % i == 0) return false; return true;} // Function to check if a// number is Full Prime or notbool isFulPrime(int n){ // If n is not a prime if (!isPrime(n)) return false; // Otherwise else { while (n > 0) { // Extract digit int rem = n % 10; // If any digit of n // is non-prime if (!(rem == 2 || rem == 3 || rem == 5 || rem == 7)) return false; n = n / 10; } } return true;} // Function to print count of// Full Primes in a range [L, R]int countFulPrime(int L, int R){ // Stores count of full primes int cnt = 0; for (int i = L; i <= R; i++) { // Check if i is full prime if ((i % 2) != 0 && isFulPrime(i)) { cnt++; } } return cnt;} // Driver Codeint main(){ int L = 1, R = 100; // Stores count of full primes int ans = 0; if (L < 3) ans++; cout << ans + countFulPrime(L, R); return 0;}",
"e": 29194,
"s": 27882,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.io.*;import java.util.*; class GFG{ // Function to check if a// number is prime or notstatic boolean isPrime(int num){ if (num <= 1) return false; for(int i = 2; i * i <= num; i++) // If a divisor of n exists if (num % i == 0) return false; return true;} // Function to check if a// number is Full Prime or notstatic boolean isFulPrime(int n){ // If n is not a prime if (!isPrime(n)) return false; // Otherwise else { while (n > 0) { // Extract digit int rem = n % 10; // If any digit of n // is non-prime if (!(rem == 2 || rem == 3 || rem == 5 || rem == 7)) return false; n = n / 10; } } return true;} // Function to print count of// Full Primes in a range [L, R]static int countFulPrime(int L, int R){ // Stores count of full primes int cnt = 0; for(int i = L; i <= R; i++) { // Check if i is full prime if ((i % 2) != 0 && isFulPrime(i)) { cnt++; } } return cnt;} // Driver Codepublic static void main (String[] args){ int L = 1, R = 100; // Stores count of full primes int ans = 0; if (L < 3) ans++; System.out.println(ans + countFulPrime(L, R));}} // This code is contributed by sanjoy_62",
"e": 30704,
"s": 29194,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if a# number is prime or notdef isPrime(num): if (num <= 1): return False for i in range(2, num + 1): if i * i > num: break # If a divisor of n exists if (num % i == 0): return False return True # Function to check if a# number is Full Prime or notdef isFulPrime(n): # If n is not a prime if (not isPrime(n)): return False # Otherwise else: while (n > 0): # Extract digit rem = n % 10 # If any digit of n # is non-prime if (not (rem == 2 or rem == 3 or rem == 5 or rem == 7)): return False n = n // 10 return True # Function to print count of# Full Primes in a range [L, R]def countFulPrime(L, R): # Stores count of full primes cnt = 0 for i in range(L, R + 1): # Check if i is full prime if ((i % 2) != 0 and isFulPrime(i)): cnt += 1 return cnt # Driver Codeif __name__ == '__main__': L = 1 R = 100 # Stores count of full primes ans = 0 if (L < 3): ans += 1 print(ans + countFulPrime(L, R)) # This code is contributed by mohit kumar 29",
"e": 32073,
"s": 30704,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ // Function to check if a// number is prime or notstatic bool isPrime(int num){ if (num <= 1) return false; for(int i = 2; i * i <= num; i++) // If a divisor of n exists if (num % i == 0) return false; return true;} // Function to check if a// number is Full Prime or notstatic bool isFulPrime(int n){ // If n is not a prime if (!isPrime(n)) return false; // Otherwise else { while (n > 0) { // Extract digit int rem = n % 10; // If any digit of n // is non-prime if (!(rem == 2 || rem == 3 || rem == 5 || rem == 7)) return false; n = n / 10; } } return true;} // Function to print count of// Full Primes in a range [L, R]static int countFulPrime(int L, int R){ // Stores count of full primes int cnt = 0; for(int i = L; i <= R; i++) { // Check if i is full prime if ((i % 2) != 0 && isFulPrime(i)) { cnt++; } } return cnt;} // Driver Codepublic static void Main (String[] args){ int L = 1, R = 100; // Stores count of full primes int ans = 0; if (L < 3) ans++; Console.WriteLine(ans + countFulPrime(L, R));}} // This code is contributed by math_lover",
"e": 33552,
"s": 32073,
"text": null
},
{
"code": "<script> // Javascript Program to implement// the above approach // Function to check if a// number is prime or notfunction isPrime(num){ if (num <= 1) return false; for(let i = 2; i * i <= num; i++) // If a divisor of n exists if (num % i == 0) return false; return true;} // Function to check if a// number is Full Prime or notfunction isFulPrime(n){ // If n is not a prime if (!isPrime(n)) return false; // Otherwise else { while (n > 0) { // Extract digit let rem = n % 10; // If any digit of n // is non-prime if (!(rem == 2 || rem == 3 || rem == 5 || rem == 7)) return false; n = Math.floor(n / 10); } } return true;} // Function to print count of// Full Primes in a range [L, R]function countFulPrime(L, R){ // Stores count of full primes let cnt = 0; for(let i = L; i <= R; i++) { // Check if i is full prime if ((i % 2) != 0 && isFulPrime(i)) { cnt++; } } return cnt;} // Driver codelet L = 1, R = 100; // Stores count of full primeslet ans = 0; if (L < 3) ans++; document.write(ans + countFulPrime(L, R)); // This code is contributed by splevel62 </script>",
"e": 34957,
"s": 33552,
"text": null
},
{
"code": null,
"e": 34959,
"s": 34957,
"text": "8"
},
{
"code": null,
"e": 35007,
"s": 34961,
"text": "Time Complexity: O(N3/2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 35024,
"s": 35009,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35034,
"s": 35024,
"text": "sanjoy_62"
},
{
"code": null,
"e": 35045,
"s": 35034,
"text": "math_lover"
},
{
"code": null,
"e": 35055,
"s": 35045,
"text": "splevel62"
},
{
"code": null,
"e": 35068,
"s": 35055,
"text": "simmytarika5"
},
{
"code": null,
"e": 35085,
"s": 35068,
"text": "surinderdawra388"
},
{
"code": null,
"e": 35098,
"s": 35085,
"text": "divisibility"
},
{
"code": null,
"e": 35112,
"s": 35098,
"text": "number-digits"
},
{
"code": null,
"e": 35125,
"s": 35112,
"text": "Prime Number"
},
{
"code": null,
"e": 35138,
"s": 35125,
"text": "Mathematical"
},
{
"code": null,
"e": 35148,
"s": 35138,
"text": "Searching"
},
{
"code": null,
"e": 35158,
"s": 35148,
"text": "Searching"
},
{
"code": null,
"e": 35171,
"s": 35158,
"text": "Mathematical"
},
{
"code": null,
"e": 35184,
"s": 35171,
"text": "Prime Number"
},
{
"code": null,
"e": 35282,
"s": 35184,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35306,
"s": 35282,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 35349,
"s": 35306,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 35363,
"s": 35349,
"text": "Prime Numbers"
},
{
"code": null,
"e": 35405,
"s": 35363,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 35478,
"s": 35405,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 35492,
"s": 35478,
"text": "Binary Search"
},
{
"code": null,
"e": 35560,
"s": 35492,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35574,
"s": 35560,
"text": "Linear Search"
},
{
"code": null,
"e": 35622,
"s": 35574,
"text": "Search an element in a sorted and rotated array"
}
]
|
Binomial Coefficient | DP-9 - GeeksforGeeks | 28 Mar, 2022
The following are the common definitions of Binomial Coefficients.
A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n.
A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects more formally, the number of k-element subsets (or k-combinations) of a n-element set.
The Problem Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). For example, your function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2.
1) Optimal Substructure The value of C(n, k) can be recursively calculated using the following standard formula for Binomial Coefficients.
C(n, k) = C(n-1, k-1) + C(n-1, k)
C(n, 0) = C(n, n) = 1
Following is a simple recursive implementation that simply follows the recursive structure mentioned above.
C++
C
Java
Python3
C#
PHP
Javascript
// A naive recursive C++ implementation#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);} /* Driver code*/int main(){ int n = 5, k = 2; cout << "Value of C(" << n << ", " << k << ") is " << binomialCoeff(n, k); return 0;} // This is code is contributed by rathbhupendra
// A Naive Recursive Implementation#include <stdio.h> // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);} /* Driver program to test above function*/int main(){ int n = 5, k = 2; printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k)); return 0;}
// JAVA Code for Dynamic Programming |// Set 9 (Binomial Coefficient)import java.util.*; class GFG { // Returns value of Binomial // Coefficient C(n, k) static int binomialCoeff(int n, int k) { // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k); } /* Driver program to test above function */ public static void main(String[] args) { int n = 5, k = 2; System.out.printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k)); }} // This code is contributed by Arnav Kr. Mandal.
# A naive recursive Python implementation def binomialCoeff(n, k): if k > n: return 0 if k == 0 or k == n: return 1 # Recursive Call return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k) # Driver Program to test ht above functionn = 5k = 2print ("Value of C(%d,%d) is (%d)" % (n, k, binomialCoeff(n, k))) # This code is contributed by Nikhil Kumar Singh (nickzuck_007)
// C# Code for Dynamic Programming |// Set 9 (Binomial Coefficient)using System; class GFG { // Returns value of Binomial // Coefficient C(n, k) static int binomialCoeff(int n, int k) { // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k); } /* Driver program to test above function */ public static void Main() { int n = 5, k = 2; Console.Write("Value of C(" + n + "," + k + ") is " + binomialCoeff(n, k)); }} // This code is contributed by Sam007.
<?php// PHP Code for Dynamic Programming |// Set 9 (Binomial Coefficient) // Returns value of// Binomial Coefficient C(n, k)function binomialCoeff($n, $k){ // Base Cases if ($k > $n) return 0; if ($k==0 || $k==$n) return 1; // Recur return binomialCoeff($n - 1, $k - 1) + binomialCoeff($n - 1, $k);} // Driver Code $n = 5; $k = 2; echo "Value of C","(",$n ,$k,") is " , binomialCoeff($n, $k); // This code is contributed by aj_36?>
<script>// javascript Code for Dynamic Programming |// Set 9 (Binomial Coefficient) // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n , k){ // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);} /* Driver program to test above function */var n = 5, k = 2;document.write("Value of C("+n+", "+k+") is "+binomialCoeff(n, k)); // This code is contributed by Amit Katiyar</script>
Value of C(5, 2) is 10
Time Complexity: O(n*max(k,n-k))
Auxiliary Space: O(n*max(k,n-k))
2) Overlapping Subproblems It should be noted that the above function computes the same subproblems again and again. See the following recursion tree for n = 5 an k = 2. The function C(3, 1) is called two times. For large values of n, there will be many common subproblems.
Binomial Coefficients Recursion tree for C(5,2)
Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So the Binomial Coefficient problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of the same subproblems can be avoided by constructing a temporary 2D-array C[][] in a bottom-up manner. Following is Dynamic Programming-based implementation.
C++
C
Java
Python3
C#
PHP
Javascript
// A Dynamic Programming based solution that uses// table C[][] to calculate the Binomial Coefficient#include <bits/stdc++.h>using namespace std; // Prototype of a utility function that// returns minimum of two integersint min(int a, int b); // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // A utility function to return// minimum of two integersint min(int a, int b) { return (a < b) ? a : b; } // Driver Codeint main(){ int n = 5, k = 2; cout << "Value of C[" << n << "][" << k << "] is " << binomialCoeff(n, k);} // This code is contributed by Shivi_Aggarwal
// A Dynamic Programming based solution// that uses table C[][] to// calculate the Binomial Coefficient#include <stdio.h> // Prototype of a utility function that// returns minimum of two integersint min(int a, int b); // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // A utility function to return// minimum of two integersint min(int a, int b) { return (a < b) ? a : b; } /* Drier program to test above function*/int main(){ int n = 5, k = 2; printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k)); return 0;}
// A Dynamic Programming based// solution that uses table C[][] to// calculate the Binomial Coefficient class BinomialCoefficient { // Returns value of Binomial // Coefficient C(n, k) static int binomialCoeff(int n, int k) { int C[][] = new int[n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // A utility function to return // minimum of two integers static int min(int a, int b) { return (a < b) ? a : b; } /* Driver program to test above function*/ public static void main(String args[]) { int n = 5, k = 2; System.out.println("Value of C(" + n + "," + k + ") is " + binomialCoeff(n, k)); }}/*This code is contributed by Rajat Mishra*/
# A Dynamic Programming based Python# Program that uses table C[][]# to calculate the Binomial Coefficient # Returns value of Binomial Coefficient C(n, k) def binomialCoef(n, k): C = [[0 for x in range(k+1)] for x in range(n+1)] # Calculate value of Binomial # Coefficient in bottom up manner for i in range(n+1): for j in range(min(i, k)+1): # Base Cases if j == 0 or j == i: C[i][j] = 1 # Calculate value using # previously stored values else: C[i][j] = C[i-1][j-1] + C[i-1][j] return C[n][k] # Driver program to test above functionn = 5k = 2print("Value of C[" + str(n) + "][" + str(k) + "] is " + str(binomialCoef(n, k))) # This code is contributed by Bhavya Jain
// A Dynamic Programming based solution that// uses table C[][] to calculate the Binomial// Coefficientusing System; class GFG { // Returns value of Binomial Coefficient // C(n, k) static int binomialCoeff(int n, int k) { int[, ] C = new int[n + 1, k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n, k]; } // A utility function to return minimum // of two integers static int min(int a, int b) { return (a < b) ? a : b; } /* Driver program to test above function*/ public static void Main() { int n = 5, k = 2; Console.WriteLine("Value of C(" + n + "," + k + ") is " + binomialCoeff(n, k)); }} // This code is contributed by anuj_67.
<?php// A Dynamic Programming based// solution that uses table C[][] to// calculate the Binomial Coefficient // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff( $n, $k){ $C = array(array()); $i; $j; // Calculate value of Binomial // Coefficient in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $k); $j++) { // Base Cases if ($j == 0 || $j == $i) $C[$i][$j] = 1; // Calculate value using // previously stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } return $C[$n][$k];} // Driver Code $n = 5; $k = 2; echo "Value of C(" ,$n," ",$k, ") is"," " , binomialCoeff($n, $k) ; // This code is contributed by anuj_67.?>
<script> // A Dynamic Programming based// solution that uses table C to// calculate the Binomial Coefficient // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n, k){ var C = Array(n + 1).fill(0).map( x => Array(k + 1).fill(0));; var i, j; // Calculate value of Binomial // Coefficient in bottom up manner for(i = 0; i <= n; i++) { for(j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // A utility function to return// minimum of two integersfunction min(a, b){ return (a < b) ? a : b;} // Driver codevar n = 5, k = 2;document.write("Value of C(" + n + "," + k + ") is " + binomialCoeff(n, k)); // This code is contributed by 29AjayKumar </script>
Value of C[5][2] is 10
Time Complexity: O(n*k) Auxiliary Space: O(n*k)
Following is a space-optimized version of the above code. The following code only uses O(k). Thanks to AK for suggesting this method.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for space optimized Dynamic Programming// Solution of Binomial Coefficient#include <bits/stdc++.h>using namespace std; int binomialCoeff(int n, int k){ int C[k + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle using // the previous row for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} /* Driver code*/int main(){ int n = 5, k = 2; cout << "Value of C(" << n << "," << k << ")"<< "is " <<binomialCoeff(n, k); return 0;} // This code is contributed by shivanisinghss2110
// C++ program for space optimized Dynamic Programming// Solution of Binomial Coefficient#include <stdio.h> int binomialCoeff(int n, int k){ int C[k + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle using // the previous row for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} /* Driver code*/int main(){ int n = 5, k = 2; printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k)); return 0;}
// JAVA Code for Dynamic Programming |// Set 9 (Binomial Coefficient)import java.util.*; class GFG { static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } /* Driver code */ public static void main(String[] args) { int n = 5, k = 2; System.out.printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k)); }}
# Python program for Optimized# Dynamic Programming solution to# Binomial Coefficient. This one# uses the concept of pascal# Triangle and less memory def binomialCoeff(n, k): # Declaring an empty array C = [0 for i in range(k+1)] C[0] = 1 # since nC0 is 1 for i in range(1, n+1): # Compute next row of pascal triangle using # the previous row j = min(i, k) while (j > 0): C[j] = C[j] + C[j-1] j -= 1 return C[k] # Driver Coden = 5k = 2print ("Value of C(%d,%d) is %d" % (n, k, binomialCoeff(n, k))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# Code for Dynamic Programming |// Set 9 (Binomial Coefficient)using System; class GFG { static int binomialCoeff(int n, int k) { int[] C = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous // row for (int j = Math.Min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } /* Driver Code */ public static void Main() { int n = 5, k = 2; Console.WriteLine("Value of C(" + n + " " + k + ") is " + binomialCoeff(n, k)); }} // This code is contributed by anuj_67.
<?php// PHP program for space optimized// Dynamic Programming Solution of// Binomial Coefficientfunction binomialCoeff($n, $k){ $C = array_fill(0, $k + 1, 0); $C[0] = 1; // nC0 is 1 for ($i = 1; $i <= $n; $i++) { // Compute next row of pascal // triangle using the previous row for ($j = min($i, $k); $j > 0; $j--) $C[$j] = $C[$j] + $C[$j - 1]; } return $C[$k];} // Driver Code$n = 5; $k = 2;echo "Value of C[$n, $k] is ". binomialCoeff($n, $k); // This code is contributed by mits.?>
<script> // Javascript program for space optimized// Dynamic Programming// Solution of Binomial Coefficientfunction binomialCoeff(n, k){ let C = new Array(k + 1); C.fill(0); // nC0 is 1 C[0] = 1; for(let i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous // row for(let j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Driver codelet n = 5, k = 2;document.write("Value of C(" + n + " " + k + ") is " + binomialCoeff(n, k)); // This code is contributed by divyesh072019 </script>
Value of C(5, 2) is 10
Time Complexity: O(n*k) Auxiliary Space: O(k)
Explanation: 1==========>> n = 0, C(0,0) = 1 1–1========>> n = 1, C(1,0) = 1, C(1,1) = 1 1–2–1======>> n = 2, C(2,0) = 1, C(2,1) = 2, C(2,2) = 1 1–3–3–1====>> n = 3, C(3,0) = 1, C(3,1) = 3, C(3,2) = 3, C(3,3)=1 1–4–6–4–1==>> n = 4, C(4,0) = 1, C(4,1) = 4, C(4,2) = 6, C(4,3)=4, C(4,4)=1 So here every loop on i, builds i’th row of pascal triangle, using (i-1)th rowAt any time, every element of array C will have some value (ZERO or more) and in the next iteration, the value for those elements comes from the previous iteration. In statement, C[j] = C[j] + C[j-1] The right-hand side represents the value coming from the previous iteration (A row of Pascal’s triangle depends on the previous row). The left-Hand side represents the value of the current iteration which will be obtained by this statement.
Let's say we want to calculate C(4, 3),
i.e. n=4, k=3:
All elements of array C of size 4 (k+1) are
initialized to ZERO.
i.e. C[0] = C[1] = C[2] = C[3] = C[4] = 0;
Then C[0] is set to 1
For i = 1:
C[1] = C[1] + C[0] = 0 + 1 = 1 ==>> C(1,1) = 1
For i = 2:
C[2] = C[2] + C[1] = 0 + 1 = 1 ==>> C(2,2) = 1
C[1] = C[1] + C[0] = 1 + 1 = 2 ==>> C(2,1) = 2
For i=3:
C[3] = C[3] + C[2] = 0 + 1 = 1 ==>> C(3,3) = 1
C[2] = C[2] + C[1] = 1 + 2 = 3 ==>> C(3,2) = 3
C[1] = C[1] + C[0] = 2 + 1 = 3 ==>> C(3,1) = 3
For i=4:
C[4] = C[4] + C[3] = 0 + 1 = 1 ==>> C(4,4) = 1
C[3] = C[3] + C[2] = 1 + 3 = 4 ==>> C(4,3) = 4
C[2] = C[2] + C[1] = 3 + 3 = 6 ==>> C(4,2) = 6
C[1] = C[1] + C[0] = 3 + 1 = 4 ==>> C(4,1) = 4
C(4,3) = 4 is would be the answer in our example.
Memoization Approach: The idea is to create a lookup table and follow the recursive top-down approach. Before computing any value, we check if it is already in the lookup table. If yes, we return the value. Else we compute the value and store it in the lookup table. Following is the Top-down approach of dynamic programming to finding the value of the Binomial Coefficient.
C++
Java
Python3
C#
Javascript
// A Dynamic Programming based// solution that uses// table dp[][] to calculate// the Binomial Coefficient// A naive recursive approach// with table C++ implementation#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeffUtil(int n, int k, int** dp){ // If value in lookup table then return if (dp[n][k] != -1) // return dp[n][k]; // store value in a table before return if (k == 0) { dp[n][k] = 1; return dp[n][k]; } // store value in table before return if (k == n) { dp[n][k] = 1; return dp[n][k]; } // save value in lookup table before return dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp); return dp[n][k];} int binomialCoeff(int n, int k){ int** dp; // make a temporary lookup table dp = new int*[n + 1]; // loop to create table dynamically for (int i = 0; i < (n + 1); i++) { dp[i] = new int[k + 1]; } // nested loop to initialise the table with -1 for (int i = 0; i < (n + 1); i++) { for (int j = 0; j < (k + 1); j++) { dp[i][j] = -1; } } return binomialCoeffUtil(n, k, dp);} /* Driver code*/int main(){ int n = 5, k = 2; cout << "Value of C(" << n << ", " << k << ") is " << binomialCoeff(n, k) << endl; return 0;} // This is code is contributed by MOHAMMAD MUDASSIR
// A Dynamic Programming based// solution that uses// table dp[][] to calculate// the Binomial Coefficient// A naive recursive approach// with table Java implementationimport java.util.*;class GFG{ // Returns value of Binomial// Coefficient C(n, k)static int binomialCoeffUtil(int n, int k, Vector<Integer> []dp){ // If value in lookup table // then return if (dp[n].get(k) != -1) return dp[n].get(k); // store value in a table // before return if (k == 0) { dp[n].add(k, 1); return dp[n].get(k); } // store value in table // before return if (k == n) { dp[n].add(k, 1); return dp[n].get(k); } // save value in lookup table // before return dp[n].add(k, binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp)); return dp[n].get(k);} static int binomialCoeff(int n, int k){ // Make a temporary lookup table Vector<Integer> []dp = new Vector[n+1]; // Loop to create table dynamically for (int i = 0; i < (n + 1); i++) { dp[i] = new Vector<Integer>(); for(int j = 0; j <= k; j++) dp[i].add(-1); } return binomialCoeffUtil(n, k, dp);} // Driver codepublic static void main(String[] args){ int n = 5, k = 2; System.out.print("Value of C(" + n + ", " + k + ") is " + binomialCoeff(n, k) + "\n");}} // This code is contributed by Rajput-Ji
# A Dynamic Programming based solution# that uses table dp[][] to calculate# the Binomial Coefficient. A naive# recursive approach with table# Python3 implementation # Returns value of Binomial# Coefficient C(n, k)def binomialCoeffUtil(n, k, dp): # If value in lookup table then return if dp[n][k] != -1: return dp[n][k] # Store value in a table before return if k == 0: dp[n][k] = 1 return dp[n][k] # Store value in table before return if k == n: dp[n][k] = 1 return dp[n][k] # Save value in lookup table before return dp[n][k] = (binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp)) return dp[n][k] def binomialCoeff(n, k): # Make a temporary lookup table dp = [ [ -1 for y in range(k + 1) ] for x in range(n + 1) ] return binomialCoeffUtil(n, k, dp) # Driver coden = 5k = 2 print("Value of C(" + str(n) + ", " + str(k) + ") is", binomialCoeff(n, k)) # This is code is contributed by Prateek Gupta
// C# program for the// above approach // A Dynamic Programming based// solution that uses// table [,]dp to calculate// the Binomial Coefficient// A naive recursive approach// with table C# implementationusing System;using System.Collections.Generic;class GFG{ // Returns value of Binomial// Coefficient C(n, k)static int binomialCoeffUtil(int n, int k, List<int> []dp){ // If value in lookup table // then return if (dp[n][k] != -1) return dp[n][k]; // store value in a table // before return if (k == 0) { dp[n][k] = 1; return dp[n][k]; } // store value in table // before return if (k == n) { dp[n][k] = 1; return dp[n][k]; } // save value in lookup table // before return dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp); return dp[n][k];} static int binomialCoeff(int n, int k){ // Make a temporary lookup table List<int> []dp = new List<int>[n + 1]; // Loop to create table dynamically for (int i = 0; i < (n + 1); i++) { dp[i] = new List<int>(); for(int j = 0; j <= k; j++) dp[i].Add(-1); } return binomialCoeffUtil(n, k, dp);} // Driver codepublic static void Main(String[] args){ int n = 5, k = 2; Console.Write("Value of C(" + n + ", " + k + ") is " + binomialCoeff(n, k) + "\n");}} // This code is contributed by 29AjayKumar
<script> // A Dynamic Programming based solution that// uses table dp[][] to calculate the// Binomial Coefficient. A naive recursive// approach with table Javascript implementation // Returns value of Binomial// Coefficient C(n, k)function binomialCoeffUtil(n, k, dp){ // If value in lookup table // then return if (dp[n][k] != -1) return dp[n][k]; // Store value in a table // before return if (k == 0) { dp[n][k] = 1; return dp[n][k]; } // Store value in table // before return if (k == n) { dp[n][k] = 1; return dp[n][k]; } // Save value in lookup table // before return dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp); return dp[n][k];} function binomialCoeff(n, k){ // Make a temporary lookup table let dp = new Array(n + 1); // Loop to create table dynamically for(let i = 0; i < (n + 1); i++) { dp[i] = []; for(let j = 0; j <= k; j++) dp[i].push(-1); } return binomialCoeffUtil(n, k, dp);} // Driver codelet n = 5, k = 2;document.write("Value of C(" + n + ", " + k + ") is " + binomialCoeff(n, k) + "\n"); // This code is contributed by avanitrachhadiya2155 </script>
Time Complexity: O(max(n,n-k))
Auxiliary Space: O(n*k)
Value of C(5, 2) is 10
Cancellation of factors between numerator and denominator:
nCr = (n-r+1)*(n-r+2)*....*n / (r!)
Create an array arr of numbers from n-r+1 to n which will be of size r. As nCr is always an integer, all numbers in the denominator should cancel with the product of the numerator (represented by arr).
for i = 1 to i = r,
search arr, if arr[j] and i have gcd>1, divide both by the gcd and when i becomes 1, stop the search
Now, the answer is just the product of arr, whose value mod 10^9+7 can be found using a single pass and the formula use (a*b)%mod = (a%mod * b%mod)%mod
C++
Java
Python3
C#
Javascript
// C++ program to find gcd of// two numbers in O(log(min(a,b))) #include <bits/stdc++.h>using namespace std; int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} int nCr(int n, int r){ // base case if (r > n) return 0; // C(n,r) = C(n,n-r) if (r > n - r) r = n - r; int mod = 1000000007; // array of elements from n-r+1 to n int arr[r]; for (int i = n - r + 1; i <= n; i++) { arr[i + r - n - 1] = i; } long int ans = 1; // for numbers from 1 to r find arr[j], // such that gcd(i,arr[j])>1 for (int k = 1; k < r + 1; k++) { int j = 0, i = k; while (j < r) { int x = gcd(i, arr[j]); if (x > 1) { // if gcd>1, divide both by gcd arr[j] /= x; i /= x; } // if i becomes 1, no need to search arr if (i == 1) break; j += 1; } } // single pass to multiply the numerator for (int i : arr) ans = (ans * i) % mod; return (int)ans;} int main(){ int n = 5, r = 2; cout << "Value of C(" << n << ", " << r << ") is " << nCr(n, r) << "\n"; return 0;} // This code is contributed by rajsanghavi9.
import java.util.*;class GFG{ static int gcd(int a, int b) // function to find gcd of two numbers in O(log(min(a,b))) { if(b==0) return a; return gcd(b,a%b); } static int nCr(int n, int r) { if(r>n) // base case return 0; if(r>n-r) // C(n,r) = C(n,n-r) better time complexity for lesser r value r = n-r; int mod = 1000000007; int[] arr = new int[r]; // array of elements from n-r+1 to n for(int i=n-r+1; i<=n; i++) { arr[i+r-n-1] = i; } long ans = 1; for(int k=1;k<r+1;k++) // for numbers from 1 to r find arr[j] such that gcd(i,arr[j])>1 { int j=0, i=k; while(j<arr.length) { int x = gcd(i,arr[j]); if(x>1) { arr[j] /= x; // if gcd>1, divide both by gcd i /= x; } if(i==1) break; // if i becomes 1, no need to search arr j += 1; } } for(int i : arr) // single pass to multiply the numerator ans = (ans*i)%mod; return (int)ans; } // Driver code public static void main(String[] args) { int n = 5, r = 2; System.out.print("Value of C(" + n+ ", " + r+ ") is " +nCr(n, r) +"\n"); }}// This code is contributed by Gautam Wadhwani
import mathclass GFG: def nCr(self, n, r): def gcd(a,b): # function to find gcd of two numbers in O(log(min(a,b))) if b==0: # base case return a return gcd(b,a%b) if r>n: return 0 if r>n-r: # C(n,r) = C(n,n-r) better time complexity for lesser r value r = n-r mod = 10**9 + 7 arr = list(range(n-r+1,n+1)) # array of elements from n-r+1 to n ans = 1 for i in range(1,r+1): # for numbers from 1 to r find arr[j] such that gcd(i,arr[j])>1 j=0 while j<len(arr): x = gcd(i,arr[j]) if x>1: arr[j] //= x # if gcd>1, divide both by gcd i //= x if arr[j]==1: # if element becomes 1, its of no use anymore so delete from arr del arr[j] j -= 1 if i==1: break # if i becomes 1, no need to search arr j += 1 for i in arr: # single pass to multiply the numerator ans = (ans*i)%mod return ans # Driver coden = 5k = 2ob = GFG()print("Value of C(" + str(n) + ", " + str(k) + ") is", ob.nCr(n, k)) # This is code is contributed by Gautam Wadhwani
using System; class GFG{ // Function to find gcd of two numbers// in O(log(min(a,b))) static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} static int nCr(int n, int r){ // Base case if (r > n) return 0; // C(n,r) = C(n,n-r) better time // complexity for lesser r value if (r > n - r) r = n - r; int mod = 1000000007; // Array of elements from n-r+1 to n int[] arr = new int[r]; for(int i = n - r + 1; i <= n; i++) { arr[i + r - n - 1] = i; } long ans = 1; // For numbers from 1 to r find arr[j] // such that gcd(i,arr[j])>1 for(int k = 1; k < r + 1; k++) { int j = 0, i = k; while (j < arr.Length) { int x = gcd(i,arr[j]); if (x > 1) { // If gcd>1, divide both by gcd arr[j] /= x; i /= x; } if (i == 1) // If i becomes 1, no need // to search arr break; j += 1; } } // Single pass to multiply the numerator foreach(int i in arr) ans = (ans * i) % mod; return (int)ans;} // Driver codestatic public void Main(){ int n = 5, r = 2; Console.WriteLine("Value of C(" + n + ", " + r + ") is " + nCr(n, r) + "\n");}} // This code is contributed by rag2127
<script> // Javascript program to find gcd of// two numbers in O(log(min(a,b)))function gcd(a, b){ if (b == 0) return a; return gcd(b, a % b);} function nCr(n, r){ // Base case if (r > n) return 0; // C(n,r) = C(n,n-r) better time // complexity for lesser r value if (r > n - r) r = n - r; mod = 1000000007; // Array of elements from n-r+1 to n var arr = new Array(r); for(var i = n - r + 1; i <= n; i++) { arr[i + r - n - 1] = i; } var ans = 1; // For numbers from 1 to r find arr[j] // such that gcd(i,arr[j])>1 for(var k = 1; k < r + 1 ; k++) { var j = 0, i = k; while (j < arr.length) { var x = gcd(i, arr[j]); if (x > 1) { // If gcd>1, divide both by gcd arr[j] /= x; i /= x; } // If i becomes 1, no need to search arr if (i == 1) break; j += 1; } } // Single pass to multiply the numerator arr.forEach(function (i) { ans = (ans * i) % mod; }); return ans;} // Driver codevar n = 5, r = 2;document.write("Value of C(" + n + ", " + r + ") is " + nCr(n, r) + "\n"); // This code is contributed by shivanisinghss2110 </script>
Value of C(5, 2) is 10
Time Complexity: O(( min(r, n-r)^2 ) * log(n)), useful when n >> r or n >> (n-r)
Auxiliary Space: O(min(r, n-r))
See this for GCD in logarithmic time
Prime factorization of every number from 1 to n using Sieve of Eratosthenes :
1. Create an array SPF of size n+1 to the smallest prime factor of each number from 1 to n
Set SPF[i] = i for all i = 1 to i = n
2. Use Sieve of Eratosthenes:
for i = 2 to i = n:
if i is prime,
for all multiples j of i, j<=n:
if SPF[j] equals j, set SPF[j] = i
3. Once, we know the SPF of each number from 1 to n, we can find the prime factorization of any number from 1 to n in O(log(n)) time using recursive division by SPF until the number becomes 1
Now, nCr = (n-r+1)*(r+2)* ... *(n) / (r)!
4. Create a dictionary (or hashmap) to store the frequency of each prime in the prime factorization of the actual value of nCr.
5. So, just calculate the frequency of each prime in nCr and multiply them raised to the power of their frequency.
6. For the numerator, iterate through i = n-r+1 to i = n, and for all prime factors of i, store their frequency in a dictionary.
( prime_pow[prime_factor] += freq_in_i )
7. For the denominator, iterate through i = 1 to i = r and now subtract the frequency instead of adding.
8. Now, traverse the dictionary and multiply the answer to (prime ^ prime_pow[prime]) % (10^9 + 7)
ans = (ans * pow(prime, prime_pow[prime], mod) ) % mod
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // pow(base,exp,mod) is used to find// (base^exp)%mod fast -> O(log(exp))long int pow(long int b, long int exp, long int mod){ long int ret = 1; while (exp > 0) { if ((exp & 1) > 0) ret = (ret * b) % mod; b = (b * b) % mod; exp >>= 1; } return ret;} int nCr(int n, int r){ // base case if (r > n) return 0; // C(n,r) = C(n,n-r) Complexity for // this code is lesser for lower n-r if (n - r > r) r = n - r; // list to smallest prime factor // of each number from 1 to n int SPF[n + 1]; // set smallest prime factor of each // number as itself for (int i = 1; i <= n; i++) SPF[i] = i; // set smallest prime factor of all // even numbers as 2 for (int i = 4; i <= n; i += 2) SPF[i] = 2; for (int i = 3; i * i < n + 1; i += 2) { // Check if i is prime if (SPF[i] == i) { // All multiples of i are // composite (and divisible by // i) so add i to their prime // factorization getpow(j,i) // times for (int j = i * i; j < n + 1; j += i) if (SPF[j] == j) { SPF[j] = i; } } } // Hash Map to store power of // each prime in C(n,r) map<int, int> prime_pow; // For numerator count frequency of each prime factor for (int i = r + 1; i < n + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { if (!prime_pow[SPF[t]]) { prime_pow[SPF[t]] = 1; } else prime_pow[SPF[t]]++; // prime_pow.put(SPF[t], // prime_pow.getOrDefault(SPF[t], 0) // + 1); t /= SPF[t]; } } // For denominator subtract the power of // each prime factor for (int i = 1; i < n - r + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { prime_pow[SPF[t]]--; // prime_pow.put(SPF[t], // prime_pow.get(SPF[t]) - 1); t /= SPF[t]; } } // long because mod is large and a%mod // * b%mod can overflow int long int ans = 1, mod = 1000000007; // use (a*b)%mod = (a%mod * b%mod)%mod for (auto it : prime_pow) // pow(base,exp,mod) is used to // find (base^exp)%mod fast ans = (ans * pow(it.first, prime_pow[it.first], mod)) % mod; return (int)ans;} int main(){ int n = 5, r = 2; cout << "Value of C(" << n << ", " << r << ") is " << nCr(n, r) << "\n"; return 0;} // This code is contributed by rajsanghavi9.
import java.util.*;class GFG { // pow(base,exp,mod) is used to find // (base^exp)%mod fast -> O(log(exp)) static long pow(long b, long exp, long mod) { long ret = 1; while (exp > 0) { if ((exp & 1) > 0) ret = (ret * b) % mod; b = (b * b) % mod; exp >>= 1; } return ret; } static int nCr(int n, int r) { if (r > n) // base case return 0; // C(n,r) = C(n,n-r) Complexity for // this code is lesser for lower n-r if (n - r > r) r = n - r; // list to smallest prime factor // of each number from 1 to n int[] SPF = new int[n + 1]; // set smallest prime factor of each // number as itself for (int i = 1; i <= n; i++) SPF[i] = i; // set smallest prime factor of all // even numbers as 2 for (int i = 4; i <= n; i += 2) SPF[i] = 2; for (int i = 3; i * i < n + 1; i += 2) { // Check if i is prime if (SPF[i] == i) { // All multiples of i are // composite (and divisible by // i) so add i to their prime // factorization getpow(j,i) // times for (int j = i * i; j < n + 1; j += i) if (SPF[j] == j) { SPF[j] = i; } } } // Hash Map to store power of // each prime in C(n,r) Map<Integer, Integer> prime_pow = new HashMap<>(); // For numerator count frequency of each prime factor for (int i = r + 1; i < n + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { prime_pow.put(SPF[t], prime_pow.getOrDefault(SPF[t], 0) + 1); t /= SPF[t]; } } // For denominator subtract the power of // each prime factor for (int i = 1; i < n - r + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { prime_pow.put(SPF[t], prime_pow.get(SPF[t]) - 1); t /= SPF[t]; } } // long because mod is large and a%mod // * b%mod can overflow int long ans = 1, mod = 1000000007; // use (a*b)%mod = (a%mod * b%mod)%mod for (int i : prime_pow.keySet()) // pow(base,exp,mod) is used to // find (base^exp)%mod fast ans = (ans * pow(i, prime_pow.get(i), mod)) % mod; return (int)ans; } // Driver code public static void main(String[] args) { int n = 5, r = 2; System.out.print("Value of C(" + n + ", " + r + ") is " + nCr(n, r) + "\n"); }}// This code is contributed by Gautam Wadhwani
# Python code for the above approachimport math class GFG: def nCr(self, n, r): # Base case if r > n: return 0 # C(n,r) = C(n,n-r) Complexity for this # code is lesser for lower n-r if n - r > r: r = n - r # List to store smallest prime factor # of every number from 1 to n SPF = [i for i in range(n+1)] for i in range(4, n+1, 2): # set smallest prime factor of # all even numbers as 2 SPF[i] = 2 for i in range(3, n+1, 2): if i*i > n: break # Check if i is prime if SPF[i] == i: # All multiples of i are composite # (and divisible by i) so add i to # their prime factorization getpow(j,i) times for j in range(i*i, n+1, i): if SPF[j] == j: # set smallest prime factor # of j to i only if it is # not previously set SPF[j] = i # dictionary to store power of each prime in C(n,r) prime_pow = {} # For numerator count frequency # of each prime factor for i in range(r+1, n+1): t = i # Recursive division to # find prime factorization of i while t > 1: if not SPF[t] in prime_pow: prime_pow[SPF[t]] = 1 else: prime_pow[SPF[t]] += 1 t //= SPF[t] # For denominator subtract the # power of each prime factor for i in range(1, n-r+1): t = i # Recursive division to # find prime factorization of i while t > 1: prime_pow[SPF[t]] -= 1 t //= SPF[t] ans = 1 mod = 10**9 + 7 # Use (a*b)%mod = (a%mod * b%mod)%mod for i in prime_pow: # pow(base,exp,mod) is used to # find (base^exp)%mod fast ans = (ans*pow(i, prime_pow[i], mod)) % mod return ans # Driver coden = 5k = 2ob = GFG()print("Value of C(" + str(n) + ", " + str(k) + ") is", ob.nCr(n, k)) # This is code is contributed by Gautam Wadhwani
using System;using System.Collections.Generic; public class GFG { // pow(base,exp,mod) is used to find // (base^exp)%mod fast -> O(log(exp)) static long pow(long b, long exp, long mod) { long ret = 1; while (exp > 0) { if ((exp & 1) > 0) ret = (ret * b) % mod; b = (b * b) % mod; exp >>= 1; } return ret; } static int nCr(int n, int r) { if (r > n) // base case return 0; // C(n,r) = C(n,n-r) Complexity for // this code is lesser for lower n-r if (n - r > r) r = n - r; // list to smallest prime factor // of each number from 1 to n int[] SPF = new int[n + 1]; // set smallest prime factor of each // number as itself for (int i = 1; i <= n; i++) SPF[i] = i; // set smallest prime factor of all // even numbers as 2 for (int i = 4; i <= n; i += 2) SPF[i] = 2; for (int i = 3; i * i < n + 1; i += 2) { // Check if i is prime if (SPF[i] == i) { // All multiples of i are // composite (and divisible by // i) so add i to their prime // factorization getpow(j,i) // times for (int j = i * i; j < n + 1; j += i) if (SPF[j] == j) { SPF[j] = i; } } } // Hash Map to store power of // each prime in C(n,r) Dictionary<int, int> prime_pow = new Dictionary<int, int>(); // For numerator count frequency of each prime // factor for (int i = r + 1; i < n + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { if (prime_pow.ContainsKey(SPF[t])) { prime_pow[SPF[t]] = prime_pow[SPF[t]] + 1; } else { prime_pow.Add(SPF[t], 1); } t /= SPF[t]; } } // For denominator subtract the power of // each prime factor for (int i = 1; i < n - r + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { if (prime_pow.ContainsKey(SPF[t])) { prime_pow[SPF[t]] = prime_pow[SPF[t]] - 1; } t /= SPF[t]; } } // long because mod is large and a%mod // * b%mod can overflow int long ans = 1, mod = 1000000007; // use (a*b)%mod = (a%mod * b%mod)%mod foreach(int i in prime_pow.Keys) // pow(base,exp,mod) is used to // find (base^exp)%mod fast ans = (ans * pow(i, prime_pow[i], mod)) % mod; return (int)ans; } // Driver code public static void Main(String[] args) { int n = 5, r = 2; Console.Write("Value of C(" + n + ", " + r + ") is " + nCr(n, r) + "\n"); }} // This code contributed by gauravrajput1
<script> // Javascript program to find gcd of// two numbers in O(log(min(a,b))) function gcd(a, b){ if (b == 0) return a; return gcd(b, a % b);} function nCr(n, r){ // base case if (r > n) return 0; // C(n,r) = C(n,n-r) if (r > n - r) r = n - r; var mod = 1000000007; // array of elements from n-r+1 to n var arr = new Array(r); for (var i = n - r + 1; i <= n; i++) { arr[i + r - n - 1] = i; } var ans = 1; // for numbers from 1 to r find arr[j], // such that gcd(i,arr[j])>1 for (var k = 1; k < r + 1; k++) { var j = 0; var i = k; do { var x = gcd(i, arr[j]); if (x > 1) { // if gcd>1, divide both by gcd arr[j] /= x; i /= x; } // if i becomes 1, no need to search arr if (i == 1) break; j += 1; } while (j < r); } // single pass to multiply the numerator arr.forEach(function (i, index) { ans = (ans * i) % mod; }); return ans;} var n = 5;var r = 2;document.write("Value of C(" + n + ", " + r + ") is " + nCr(n, r) + "<br>"); // This code is contributed by shivani. </script>
Value of C(5, 2) is 10
Time Complexity: O(n*log(n)), so useful when r->n/2
Auxiliary Space: O(n)
See this for Prime factorization in O(log(n))
Another Approach: (Modular Inversion technique)
1. The general formula of nCr is ( n*(n-1)*(n-2)* ... *(n-r+1) ) / (r!). We can directly use this formula to find nCr. But that will overflow out of bound. We need to find nCr mod m so that it doesn’t overflow. We can easily do it with modular arithmetic formula.
for the n*(n-1)*(n-2)* ... *(n-r+1) part we can use the formula,
(a*b) mod m = ((a % m) * (b % m)) % m
2. and for the 1/r! part, we need to find the modular inverse of every number from 1 to r. Then use the same formula above with a modular inverse of 1 to r. We can find modular inverse in O(r) time using the formula,
inv[1] = 1
inv[i] = − ⌊m/i⌋ * inv[m mod i] mod m
To use this formula, m has to be a prime.
In the practice problem, we need to show the answer with modulo 1000000007 which is a prime.
So, this technique will work.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find binomial// coefficientint binomialCoeff(int n, int r){ if (r > n) return 0; long long int m = 1000000007; long long int inv[r + 1] = { 0 }; inv[0] = 1; if(r+1>=2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[m % i] % m; } int ans = 1; // for 1/(r!) part for (int i = 2; i <= r; i++) { ans = ((ans % m) * (inv[i] % m)) % m; } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (int i = n; i >= (n - r + 1); i--) { ans = ((ans % m) * (i % m)) % m; } return ans;} /* Driver code*/int main(){ int n = 5, r = 2; cout << "Value of C(" << n << ", " << r << ") is " << binomialCoeff(n, r) << endl; return 0;}
// JAVA program for the above approachimport java.util.*;class GFG{ // Function to find binomial// coefficientstatic int binomialCoeff(int n, int r){ if (r > n) return 0; long m = 1000000007; long inv[] = new long[r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } int ans = 1; // for 1/(r!) part for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (int i = n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans;} /* Driver code*/public static void main(String[] args){ int n = 5, r = 2; System.out.print("Value of C(" + n+ ", " + r+ ") is " +binomialCoeff(n, r) +"\n");}} // This code contributed by Rajput-Ji
# Python3 program for the above approach # Function to find binomial# coefficientdef binomialCoeff(n, r): if (r > n): return 0 m = 1000000007 inv = [0 for i in range(r + 1)] inv[0] = 1; if(r+1>=2) inv[1] = 1; # Getting the modular inversion # for all the numbers # from 2 to r with respect to m # here m = 1000000007 for i in range(2, r + 1): inv[i] = m - (m // i) * inv[m % i] % m ans = 1 # for 1/(r!) part for i in range(2, r + 1): ans = ((ans % m) * (inv[i] % m)) % m # for (n)*(n-1)*(n-2)*...*(n-r+1) part for i in range(n, n - r, -1): ans = ((ans % m) * (i % m)) % m return ans # Driver coden = 5r = 2 print("Value of C(" ,n , ", " , r , ") is ",binomialCoeff(n, r)) # This code is contributed by rohan07
// C# program for the above approachusing System; public class GFG{ // Function to find binomial// coefficientstatic int binomialCoeff(int n, int r){ if (r > n) return 0; long m = 1000000007; long []inv = new long[r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } int ans = 1; // for 1/(r!) part for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (int i = n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans;} /* Driver code*/public static void Main(String[] args){ int n = 5, r = 2; Console.Write("Value of C(" + n+ ", " + r+ ") is " +binomialCoeff(n, r) +"\n");}} // This code is contributed by 29AjayKumar
<script> // JavaScript Program for the above approach // Function to find binomial // coefficient function binomialCoeff(n, r) { if (r > n) return 0; let m = 1000000007; let inv = new Array(r + 1).fill(0); inv[0] = 1; if (r + 1 >= 2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (let i = 2; i <= r; i++) { inv[i] = m - Math.floor(m / i) * inv[m % i] % m; } let ans = 1; // for 1/(r!) part for (let i = 2; i <= r; i++) { ans = ((ans % m) * (inv[i] % m)) % m; } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (let i = n; i >= (n - r + 1); i--) { ans = ((ans % m) * (i % m)) % m; } return ans; } /* Driver code*/ let n = 5, r = 2; document.write("Value of C(" + n + ", " + r + ") is " + binomialCoeff(n, r) + "<br>"); // This code is contributed by Potta Lokesh </script>
Value of C(5, 2) is 10
Time Complexity: O(n+k)
Auxiliary Space: O(k)
See this for Space and time-efficient Binomial Coefficient
References: http://www.csl.mtu.edu/cs4321/www/Lectures/Lecture%2015%20-%20Dynamic%20Programming%20Binomial%20Coefficients.htm
https://cp-algorithms.com/algebra/module-inverse.html
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
vt_m
Mithun Kumar
Shivi_Aggarwal
rathbhupendra
Akanksha_Rai
MohammadMudassir
PrateekGupta10
mr_hitman
Rajput-Ji
29AjayKumar
mansimar_anand
divyanshusrivastava1
1505086kmr
gautamsw5
amit143katiyar
divyesh072019
rohan07
jyoti369
surindertarika1234
lokeshpotta20
avanitrachhadiya2155
rag2127
rajsanghavi9
shivanisinghss2110
akshaysingh98088
reenadevi98412200
simmytarika5
GauravRajput1
amartyaghoshgfg
prophet1999
surinderdawra388
binomial coefficient
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Largest Sum Contiguous Subarray
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 34596,
"s": 34568,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 34664,
"s": 34596,
"text": "The following are the common definitions of Binomial Coefficients. "
},
{
"code": null,
"e": 34767,
"s": 34664,
"text": "A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n."
},
{
"code": null,
"e": 34986,
"s": 34767,
"text": "A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects more formally, the number of k-element subsets (or k-combinations) of a n-element set."
},
{
"code": null,
"e": 35213,
"s": 34986,
"text": "The Problem Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). For example, your function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2."
},
{
"code": null,
"e": 35354,
"s": 35213,
"text": "1) Optimal Substructure The value of C(n, k) can be recursively calculated using the following standard formula for Binomial Coefficients. "
},
{
"code": null,
"e": 35416,
"s": 35354,
"text": " C(n, k) = C(n-1, k-1) + C(n-1, k)\n C(n, 0) = C(n, n) = 1"
},
{
"code": null,
"e": 35526,
"s": 35416,
"text": "Following is a simple recursive implementation that simply follows the recursive structure mentioned above. "
},
{
"code": null,
"e": 35530,
"s": 35526,
"text": "C++"
},
{
"code": null,
"e": 35532,
"s": 35530,
"text": "C"
},
{
"code": null,
"e": 35537,
"s": 35532,
"text": "Java"
},
{
"code": null,
"e": 35545,
"s": 35537,
"text": "Python3"
},
{
"code": null,
"e": 35548,
"s": 35545,
"text": "C#"
},
{
"code": null,
"e": 35552,
"s": 35548,
"text": "PHP"
},
{
"code": null,
"e": 35563,
"s": 35552,
"text": "Javascript"
},
{
"code": "// A naive recursive C++ implementation#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);} /* Driver code*/int main(){ int n = 5, k = 2; cout << \"Value of C(\" << n << \", \" << k << \") is \" << binomialCoeff(n, k); return 0;} // This is code is contributed by rathbhupendra",
"e": 36104,
"s": 35563,
"text": null
},
{
"code": "// A Naive Recursive Implementation#include <stdio.h> // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);} /* Driver program to test above function*/int main(){ int n = 5, k = 2; printf(\"Value of C(%d, %d) is %d \", n, k, binomialCoeff(n, k)); return 0;}",
"e": 36584,
"s": 36104,
"text": null
},
{
"code": "// JAVA Code for Dynamic Programming |// Set 9 (Binomial Coefficient)import java.util.*; class GFG { // Returns value of Binomial // Coefficient C(n, k) static int binomialCoeff(int n, int k) { // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k); } /* Driver program to test above function */ public static void main(String[] args) { int n = 5, k = 2; System.out.printf(\"Value of C(%d, %d) is %d \", n, k, binomialCoeff(n, k)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 37286,
"s": 36584,
"text": null
},
{
"code": "# A naive recursive Python implementation def binomialCoeff(n, k): if k > n: return 0 if k == 0 or k == n: return 1 # Recursive Call return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k) # Driver Program to test ht above functionn = 5k = 2print (\"Value of C(%d,%d) is (%d)\" % (n, k, binomialCoeff(n, k))) # This code is contributed by Nikhil Kumar Singh (nickzuck_007)",
"e": 37722,
"s": 37286,
"text": null
},
{
"code": "// C# Code for Dynamic Programming |// Set 9 (Binomial Coefficient)using System; class GFG { // Returns value of Binomial // Coefficient C(n, k) static int binomialCoeff(int n, int k) { // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k); } /* Driver program to test above function */ public static void Main() { int n = 5, k = 2; Console.Write(\"Value of C(\" + n + \",\" + k + \") is \" + binomialCoeff(n, k)); }} // This code is contributed by Sam007.",
"e": 38390,
"s": 37722,
"text": null
},
{
"code": "<?php// PHP Code for Dynamic Programming |// Set 9 (Binomial Coefficient) // Returns value of// Binomial Coefficient C(n, k)function binomialCoeff($n, $k){ // Base Cases if ($k > $n) return 0; if ($k==0 || $k==$n) return 1; // Recur return binomialCoeff($n - 1, $k - 1) + binomialCoeff($n - 1, $k);} // Driver Code $n = 5; $k = 2; echo \"Value of C\",\"(\",$n ,$k,\") is \" , binomialCoeff($n, $k); // This code is contributed by aj_36?>",
"e": 38897,
"s": 38390,
"text": null
},
{
"code": "<script>// javascript Code for Dynamic Programming |// Set 9 (Binomial Coefficient) // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n , k){ // Base Cases if (k > n) return 0; if (k == 0 || k == n) return 1; // Recur return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);} /* Driver program to test above function */var n = 5, k = 2;document.write(\"Value of C(\"+n+\", \"+k+\") is \"+binomialCoeff(n, k)); // This code is contributed by Amit Katiyar</script>",
"e": 39423,
"s": 38897,
"text": null
},
{
"code": null,
"e": 39446,
"s": 39423,
"text": "Value of C(5, 2) is 10"
},
{
"code": null,
"e": 39480,
"s": 39446,
"text": "Time Complexity: O(n*max(k,n-k)) "
},
{
"code": null,
"e": 39513,
"s": 39480,
"text": "Auxiliary Space: O(n*max(k,n-k))"
},
{
"code": null,
"e": 39789,
"s": 39513,
"text": "2) Overlapping Subproblems It should be noted that the above function computes the same subproblems again and again. See the following recursion tree for n = 5 an k = 2. The function C(3, 1) is called two times. For large values of n, there will be many common subproblems. "
},
{
"code": null,
"e": 39837,
"s": 39789,
"text": "Binomial Coefficients Recursion tree for C(5,2)"
},
{
"code": null,
"e": 40277,
"s": 39837,
"text": "Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So the Binomial Coefficient problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of the same subproblems can be avoided by constructing a temporary 2D-array C[][] in a bottom-up manner. Following is Dynamic Programming-based implementation. "
},
{
"code": null,
"e": 40281,
"s": 40277,
"text": "C++"
},
{
"code": null,
"e": 40283,
"s": 40281,
"text": "C"
},
{
"code": null,
"e": 40288,
"s": 40283,
"text": "Java"
},
{
"code": null,
"e": 40296,
"s": 40288,
"text": "Python3"
},
{
"code": null,
"e": 40299,
"s": 40296,
"text": "C#"
},
{
"code": null,
"e": 40303,
"s": 40299,
"text": "PHP"
},
{
"code": null,
"e": 40314,
"s": 40303,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based solution that uses// table C[][] to calculate the Binomial Coefficient#include <bits/stdc++.h>using namespace std; // Prototype of a utility function that// returns minimum of two integersint min(int a, int b); // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // A utility function to return// minimum of two integersint min(int a, int b) { return (a < b) ? a : b; } // Driver Codeint main(){ int n = 5, k = 2; cout << \"Value of C[\" << n << \"][\" << k << \"] is \" << binomialCoeff(n, k);} // This code is contributed by Shivi_Aggarwal",
"e": 41375,
"s": 40314,
"text": null
},
{
"code": "// A Dynamic Programming based solution// that uses table C[][] to// calculate the Binomial Coefficient#include <stdio.h> // Prototype of a utility function that// returns minimum of two integersint min(int a, int b); // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int C[n + 1][k + 1]; int i, j; // Calculate value of Binomial Coefficient // in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // A utility function to return// minimum of two integersint min(int a, int b) { return (a < b) ? a : b; } /* Drier program to test above function*/int main(){ int n = 5, k = 2; printf(\"Value of C(%d, %d) is %d \", n, k, binomialCoeff(n, k)); return 0;}",
"e": 42397,
"s": 41375,
"text": null
},
{
"code": "// A Dynamic Programming based// solution that uses table C[][] to// calculate the Binomial Coefficient class BinomialCoefficient { // Returns value of Binomial // Coefficient C(n, k) static int binomialCoeff(int n, int k) { int C[][] = new int[n + 1][k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k]; } // A utility function to return // minimum of two integers static int min(int a, int b) { return (a < b) ? a : b; } /* Driver program to test above function*/ public static void main(String args[]) { int n = 5, k = 2; System.out.println(\"Value of C(\" + n + \",\" + k + \") is \" + binomialCoeff(n, k)); }}/*This code is contributed by Rajat Mishra*/",
"e": 43577,
"s": 42397,
"text": null
},
{
"code": "# A Dynamic Programming based Python# Program that uses table C[][]# to calculate the Binomial Coefficient # Returns value of Binomial Coefficient C(n, k) def binomialCoef(n, k): C = [[0 for x in range(k+1)] for x in range(n+1)] # Calculate value of Binomial # Coefficient in bottom up manner for i in range(n+1): for j in range(min(i, k)+1): # Base Cases if j == 0 or j == i: C[i][j] = 1 # Calculate value using # previously stored values else: C[i][j] = C[i-1][j-1] + C[i-1][j] return C[n][k] # Driver program to test above functionn = 5k = 2print(\"Value of C[\" + str(n) + \"][\" + str(k) + \"] is \" + str(binomialCoef(n, k))) # This code is contributed by Bhavya Jain",
"e": 44362,
"s": 43577,
"text": null
},
{
"code": "// A Dynamic Programming based solution that// uses table C[][] to calculate the Binomial// Coefficientusing System; class GFG { // Returns value of Binomial Coefficient // C(n, k) static int binomialCoeff(int n, int k) { int[, ] C = new int[n + 1, k + 1]; int i, j; // Calculate value of Binomial // Coefficient in bottom up manner for (i = 0; i <= n; i++) { for (j = 0; j <= Math.Min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } return C[n, k]; } // A utility function to return minimum // of two integers static int min(int a, int b) { return (a < b) ? a : b; } /* Driver program to test above function*/ public static void Main() { int n = 5, k = 2; Console.WriteLine(\"Value of C(\" + n + \",\" + k + \") is \" + binomialCoeff(n, k)); }} // This code is contributed by anuj_67.",
"e": 45525,
"s": 44362,
"text": null
},
{
"code": "<?php// A Dynamic Programming based// solution that uses table C[][] to// calculate the Binomial Coefficient // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff( $n, $k){ $C = array(array()); $i; $j; // Calculate value of Binomial // Coefficient in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $k); $j++) { // Base Cases if ($j == 0 || $j == $i) $C[$i][$j] = 1; // Calculate value using // previously stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } return $C[$n][$k];} // Driver Code $n = 5; $k = 2; echo \"Value of C(\" ,$n,\" \",$k, \") is\",\" \" , binomialCoeff($n, $k) ; // This code is contributed by anuj_67.?>",
"e": 46418,
"s": 45525,
"text": null
},
{
"code": "<script> // A Dynamic Programming based// solution that uses table C to// calculate the Binomial Coefficient // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n, k){ var C = Array(n + 1).fill(0).map( x => Array(k + 1).fill(0));; var i, j; // Calculate value of Binomial // Coefficient in bottom up manner for(i = 0; i <= n; i++) { for(j = 0; j <= min(i, k); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using // previously stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[n][k];} // A utility function to return// minimum of two integersfunction min(a, b){ return (a < b) ? a : b;} // Driver codevar n = 5, k = 2;document.write(\"Value of C(\" + n + \",\" + k + \") is \" + binomialCoeff(n, k)); // This code is contributed by 29AjayKumar </script>",
"e": 47437,
"s": 46418,
"text": null
},
{
"code": null,
"e": 47460,
"s": 47437,
"text": "Value of C[5][2] is 10"
},
{
"code": null,
"e": 47508,
"s": 47460,
"text": "Time Complexity: O(n*k) Auxiliary Space: O(n*k)"
},
{
"code": null,
"e": 47643,
"s": 47508,
"text": "Following is a space-optimized version of the above code. The following code only uses O(k). Thanks to AK for suggesting this method. "
},
{
"code": null,
"e": 47647,
"s": 47643,
"text": "C++"
},
{
"code": null,
"e": 47649,
"s": 47647,
"text": "C"
},
{
"code": null,
"e": 47654,
"s": 47649,
"text": "Java"
},
{
"code": null,
"e": 47662,
"s": 47654,
"text": "Python3"
},
{
"code": null,
"e": 47665,
"s": 47662,
"text": "C#"
},
{
"code": null,
"e": 47669,
"s": 47665,
"text": "PHP"
},
{
"code": null,
"e": 47680,
"s": 47669,
"text": "Javascript"
},
{
"code": "// C++ program for space optimized Dynamic Programming// Solution of Binomial Coefficient#include <bits/stdc++.h>using namespace std; int binomialCoeff(int n, int k){ int C[k + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle using // the previous row for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} /* Driver code*/int main(){ int n = 5, k = 2; cout << \"Value of C(\" << n << \",\" << k << \")\"<< \"is \" <<binomialCoeff(n, k); return 0;} // This code is contributed by shivanisinghss2110",
"e": 48335,
"s": 47680,
"text": null
},
{
"code": "// C++ program for space optimized Dynamic Programming// Solution of Binomial Coefficient#include <stdio.h> int binomialCoeff(int n, int k){ int C[k + 1]; memset(C, 0, sizeof(C)); C[0] = 1; // nC0 is 1 for (int i = 1; i <= n; i++) { // Compute next row of pascal triangle using // the previous row for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} /* Driver code*/int main(){ int n = 5, k = 2; printf(\"Value of C(%d, %d) is %d \", n, k, binomialCoeff(n, k)); return 0;}",
"e": 48901,
"s": 48335,
"text": null
},
{
"code": "// JAVA Code for Dynamic Programming |// Set 9 (Binomial Coefficient)import java.util.*; class GFG { static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } /* Driver code */ public static void main(String[] args) { int n = 5, k = 2; System.out.printf(\"Value of C(%d, %d) is %d \", n, k, binomialCoeff(n, k)); }}",
"e": 49579,
"s": 48901,
"text": null
},
{
"code": "# Python program for Optimized# Dynamic Programming solution to# Binomial Coefficient. This one# uses the concept of pascal# Triangle and less memory def binomialCoeff(n, k): # Declaring an empty array C = [0 for i in range(k+1)] C[0] = 1 # since nC0 is 1 for i in range(1, n+1): # Compute next row of pascal triangle using # the previous row j = min(i, k) while (j > 0): C[j] = C[j] + C[j-1] j -= 1 return C[k] # Driver Coden = 5k = 2print (\"Value of C(%d,%d) is %d\" % (n, k, binomialCoeff(n, k))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 50213,
"s": 49579,
"text": null
},
{
"code": "// C# Code for Dynamic Programming |// Set 9 (Binomial Coefficient)using System; class GFG { static int binomialCoeff(int n, int k) { int[] C = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous // row for (int j = Math.Min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } /* Driver Code */ public static void Main() { int n = 5, k = 2; Console.WriteLine(\"Value of C(\" + n + \" \" + k + \") is \" + binomialCoeff(n, k)); }} // This code is contributed by anuj_67.",
"e": 50928,
"s": 50213,
"text": null
},
{
"code": "<?php// PHP program for space optimized// Dynamic Programming Solution of// Binomial Coefficientfunction binomialCoeff($n, $k){ $C = array_fill(0, $k + 1, 0); $C[0] = 1; // nC0 is 1 for ($i = 1; $i <= $n; $i++) { // Compute next row of pascal // triangle using the previous row for ($j = min($i, $k); $j > 0; $j--) $C[$j] = $C[$j] + $C[$j - 1]; } return $C[$k];} // Driver Code$n = 5; $k = 2;echo \"Value of C[$n, $k] is \". binomialCoeff($n, $k); // This code is contributed by mits.?>",
"e": 51476,
"s": 50928,
"text": null
},
{
"code": "<script> // Javascript program for space optimized// Dynamic Programming// Solution of Binomial Coefficientfunction binomialCoeff(n, k){ let C = new Array(k + 1); C.fill(0); // nC0 is 1 C[0] = 1; for(let i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous // row for(let j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k];} // Driver codelet n = 5, k = 2;document.write(\"Value of C(\" + n + \" \" + k + \") is \" + binomialCoeff(n, k)); // This code is contributed by divyesh072019 </script>",
"e": 52116,
"s": 51476,
"text": null
},
{
"code": null,
"e": 52140,
"s": 52116,
"text": "Value of C(5, 2) is 10 "
},
{
"code": null,
"e": 52186,
"s": 52140,
"text": "Time Complexity: O(n*k) Auxiliary Space: O(k)"
},
{
"code": null,
"e": 52993,
"s": 52186,
"text": "Explanation: 1==========>> n = 0, C(0,0) = 1 1–1========>> n = 1, C(1,0) = 1, C(1,1) = 1 1–2–1======>> n = 2, C(2,0) = 1, C(2,1) = 2, C(2,2) = 1 1–3–3–1====>> n = 3, C(3,0) = 1, C(3,1) = 3, C(3,2) = 3, C(3,3)=1 1–4–6–4–1==>> n = 4, C(4,0) = 1, C(4,1) = 4, C(4,2) = 6, C(4,3)=4, C(4,4)=1 So here every loop on i, builds i’th row of pascal triangle, using (i-1)th rowAt any time, every element of array C will have some value (ZERO or more) and in the next iteration, the value for those elements comes from the previous iteration. In statement, C[j] = C[j] + C[j-1] The right-hand side represents the value coming from the previous iteration (A row of Pascal’s triangle depends on the previous row). The left-Hand side represents the value of the current iteration which will be obtained by this statement. "
},
{
"code": null,
"e": 53748,
"s": 52995,
"text": "Let's say we want to calculate C(4, 3), \ni.e. n=4, k=3:\n\nAll elements of array C of size 4 (k+1) are\ninitialized to ZERO.\n\ni.e. C[0] = C[1] = C[2] = C[3] = C[4] = 0;\nThen C[0] is set to 1\n\nFor i = 1:\nC[1] = C[1] + C[0] = 0 + 1 = 1 ==>> C(1,1) = 1\n\nFor i = 2:\nC[2] = C[2] + C[1] = 0 + 1 = 1 ==>> C(2,2) = 1\nC[1] = C[1] + C[0] = 1 + 1 = 2 ==>> C(2,1) = 2\n\nFor i=3:\nC[3] = C[3] + C[2] = 0 + 1 = 1 ==>> C(3,3) = 1\nC[2] = C[2] + C[1] = 1 + 2 = 3 ==>> C(3,2) = 3\nC[1] = C[1] + C[0] = 2 + 1 = 3 ==>> C(3,1) = 3\n\nFor i=4:\nC[4] = C[4] + C[3] = 0 + 1 = 1 ==>> C(4,4) = 1\nC[3] = C[3] + C[2] = 1 + 3 = 4 ==>> C(4,3) = 4\nC[2] = C[2] + C[1] = 3 + 3 = 6 ==>> C(4,2) = 6\nC[1] = C[1] + C[0] = 3 + 1 = 4 ==>> C(4,1) = 4\n\nC(4,3) = 4 is would be the answer in our example."
},
{
"code": null,
"e": 54125,
"s": 53750,
"text": "Memoization Approach: The idea is to create a lookup table and follow the recursive top-down approach. Before computing any value, we check if it is already in the lookup table. If yes, we return the value. Else we compute the value and store it in the lookup table. Following is the Top-down approach of dynamic programming to finding the value of the Binomial Coefficient."
},
{
"code": null,
"e": 54131,
"s": 54127,
"text": "C++"
},
{
"code": null,
"e": 54136,
"s": 54131,
"text": "Java"
},
{
"code": null,
"e": 54144,
"s": 54136,
"text": "Python3"
},
{
"code": null,
"e": 54147,
"s": 54144,
"text": "C#"
},
{
"code": null,
"e": 54158,
"s": 54147,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based// solution that uses// table dp[][] to calculate// the Binomial Coefficient// A naive recursive approach// with table C++ implementation#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeffUtil(int n, int k, int** dp){ // If value in lookup table then return if (dp[n][k] != -1) // return dp[n][k]; // store value in a table before return if (k == 0) { dp[n][k] = 1; return dp[n][k]; } // store value in table before return if (k == n) { dp[n][k] = 1; return dp[n][k]; } // save value in lookup table before return dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp); return dp[n][k];} int binomialCoeff(int n, int k){ int** dp; // make a temporary lookup table dp = new int*[n + 1]; // loop to create table dynamically for (int i = 0; i < (n + 1); i++) { dp[i] = new int[k + 1]; } // nested loop to initialise the table with -1 for (int i = 0; i < (n + 1); i++) { for (int j = 0; j < (k + 1); j++) { dp[i][j] = -1; } } return binomialCoeffUtil(n, k, dp);} /* Driver code*/int main(){ int n = 5, k = 2; cout << \"Value of C(\" << n << \", \" << k << \") is \" << binomialCoeff(n, k) << endl; return 0;} // This is code is contributed by MOHAMMAD MUDASSIR",
"e": 55600,
"s": 54158,
"text": null
},
{
"code": "// A Dynamic Programming based// solution that uses// table dp[][] to calculate// the Binomial Coefficient// A naive recursive approach// with table Java implementationimport java.util.*;class GFG{ // Returns value of Binomial// Coefficient C(n, k)static int binomialCoeffUtil(int n, int k, Vector<Integer> []dp){ // If value in lookup table // then return if (dp[n].get(k) != -1) return dp[n].get(k); // store value in a table // before return if (k == 0) { dp[n].add(k, 1); return dp[n].get(k); } // store value in table // before return if (k == n) { dp[n].add(k, 1); return dp[n].get(k); } // save value in lookup table // before return dp[n].add(k, binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp)); return dp[n].get(k);} static int binomialCoeff(int n, int k){ // Make a temporary lookup table Vector<Integer> []dp = new Vector[n+1]; // Loop to create table dynamically for (int i = 0; i < (n + 1); i++) { dp[i] = new Vector<Integer>(); for(int j = 0; j <= k; j++) dp[i].add(-1); } return binomialCoeffUtil(n, k, dp);} // Driver codepublic static void main(String[] args){ int n = 5, k = 2; System.out.print(\"Value of C(\" + n + \", \" + k + \") is \" + binomialCoeff(n, k) + \"\\n\");}} // This code is contributed by Rajput-Ji",
"e": 57050,
"s": 55600,
"text": null
},
{
"code": "# A Dynamic Programming based solution# that uses table dp[][] to calculate# the Binomial Coefficient. A naive# recursive approach with table# Python3 implementation # Returns value of Binomial# Coefficient C(n, k)def binomialCoeffUtil(n, k, dp): # If value in lookup table then return if dp[n][k] != -1: return dp[n][k] # Store value in a table before return if k == 0: dp[n][k] = 1 return dp[n][k] # Store value in table before return if k == n: dp[n][k] = 1 return dp[n][k] # Save value in lookup table before return dp[n][k] = (binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp)) return dp[n][k] def binomialCoeff(n, k): # Make a temporary lookup table dp = [ [ -1 for y in range(k + 1) ] for x in range(n + 1) ] return binomialCoeffUtil(n, k, dp) # Driver coden = 5k = 2 print(\"Value of C(\" + str(n) + \", \" + str(k) + \") is\", binomialCoeff(n, k)) # This is code is contributed by Prateek Gupta",
"e": 58136,
"s": 57050,
"text": null
},
{
"code": "// C# program for the// above approach // A Dynamic Programming based// solution that uses// table [,]dp to calculate// the Binomial Coefficient// A naive recursive approach// with table C# implementationusing System;using System.Collections.Generic;class GFG{ // Returns value of Binomial// Coefficient C(n, k)static int binomialCoeffUtil(int n, int k, List<int> []dp){ // If value in lookup table // then return if (dp[n][k] != -1) return dp[n][k]; // store value in a table // before return if (k == 0) { dp[n][k] = 1; return dp[n][k]; } // store value in table // before return if (k == n) { dp[n][k] = 1; return dp[n][k]; } // save value in lookup table // before return dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp); return dp[n][k];} static int binomialCoeff(int n, int k){ // Make a temporary lookup table List<int> []dp = new List<int>[n + 1]; // Loop to create table dynamically for (int i = 0; i < (n + 1); i++) { dp[i] = new List<int>(); for(int j = 0; j <= k; j++) dp[i].Add(-1); } return binomialCoeffUtil(n, k, dp);} // Driver codepublic static void Main(String[] args){ int n = 5, k = 2; Console.Write(\"Value of C(\" + n + \", \" + k + \") is \" + binomialCoeff(n, k) + \"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 59595,
"s": 58136,
"text": null
},
{
"code": "<script> // A Dynamic Programming based solution that// uses table dp[][] to calculate the// Binomial Coefficient. A naive recursive// approach with table Javascript implementation // Returns value of Binomial// Coefficient C(n, k)function binomialCoeffUtil(n, k, dp){ // If value in lookup table // then return if (dp[n][k] != -1) return dp[n][k]; // Store value in a table // before return if (k == 0) { dp[n][k] = 1; return dp[n][k]; } // Store value in table // before return if (k == n) { dp[n][k] = 1; return dp[n][k]; } // Save value in lookup table // before return dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) + binomialCoeffUtil(n - 1, k, dp); return dp[n][k];} function binomialCoeff(n, k){ // Make a temporary lookup table let dp = new Array(n + 1); // Loop to create table dynamically for(let i = 0; i < (n + 1); i++) { dp[i] = []; for(let j = 0; j <= k; j++) dp[i].push(-1); } return binomialCoeffUtil(n, k, dp);} // Driver codelet n = 5, k = 2;document.write(\"Value of C(\" + n + \", \" + k + \") is \" + binomialCoeff(n, k) + \"\\n\"); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 60974,
"s": 59595,
"text": null
},
{
"code": null,
"e": 61006,
"s": 60974,
"text": " Time Complexity: O(max(n,n-k))"
},
{
"code": null,
"e": 61031,
"s": 61006,
"text": "Auxiliary Space: O(n*k) "
},
{
"code": null,
"e": 61054,
"s": 61031,
"text": "Value of C(5, 2) is 10"
},
{
"code": null,
"e": 61115,
"s": 61056,
"text": "Cancellation of factors between numerator and denominator:"
},
{
"code": null,
"e": 61153,
"s": 61117,
"text": "nCr = (n-r+1)*(n-r+2)*....*n / (r!)"
},
{
"code": null,
"e": 61357,
"s": 61155,
"text": "Create an array arr of numbers from n-r+1 to n which will be of size r. As nCr is always an integer, all numbers in the denominator should cancel with the product of the numerator (represented by arr)."
},
{
"code": null,
"e": 61379,
"s": 61359,
"text": "for i = 1 to i = r,"
},
{
"code": null,
"e": 61490,
"s": 61381,
"text": " search arr, if arr[j] and i have gcd>1, divide both by the gcd and when i becomes 1, stop the search"
},
{
"code": null,
"e": 61644,
"s": 61492,
"text": "Now, the answer is just the product of arr, whose value mod 10^9+7 can be found using a single pass and the formula use (a*b)%mod = (a%mod * b%mod)%mod"
},
{
"code": null,
"e": 61650,
"s": 61646,
"text": "C++"
},
{
"code": null,
"e": 61655,
"s": 61650,
"text": "Java"
},
{
"code": null,
"e": 61663,
"s": 61655,
"text": "Python3"
},
{
"code": null,
"e": 61666,
"s": 61663,
"text": "C#"
},
{
"code": null,
"e": 61677,
"s": 61666,
"text": "Javascript"
},
{
"code": "// C++ program to find gcd of// two numbers in O(log(min(a,b))) #include <bits/stdc++.h>using namespace std; int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} int nCr(int n, int r){ // base case if (r > n) return 0; // C(n,r) = C(n,n-r) if (r > n - r) r = n - r; int mod = 1000000007; // array of elements from n-r+1 to n int arr[r]; for (int i = n - r + 1; i <= n; i++) { arr[i + r - n - 1] = i; } long int ans = 1; // for numbers from 1 to r find arr[j], // such that gcd(i,arr[j])>1 for (int k = 1; k < r + 1; k++) { int j = 0, i = k; while (j < r) { int x = gcd(i, arr[j]); if (x > 1) { // if gcd>1, divide both by gcd arr[j] /= x; i /= x; } // if i becomes 1, no need to search arr if (i == 1) break; j += 1; } } // single pass to multiply the numerator for (int i : arr) ans = (ans * i) % mod; return (int)ans;} int main(){ int n = 5, r = 2; cout << \"Value of C(\" << n << \", \" << r << \") is \" << nCr(n, r) << \"\\n\"; return 0;} // This code is contributed by rajsanghavi9.",
"e": 62935,
"s": 61677,
"text": null
},
{
"code": "import java.util.*;class GFG{ static int gcd(int a, int b) // function to find gcd of two numbers in O(log(min(a,b))) { if(b==0) return a; return gcd(b,a%b); } static int nCr(int n, int r) { if(r>n) // base case return 0; if(r>n-r) // C(n,r) = C(n,n-r) better time complexity for lesser r value r = n-r; int mod = 1000000007; int[] arr = new int[r]; // array of elements from n-r+1 to n for(int i=n-r+1; i<=n; i++) { arr[i+r-n-1] = i; } long ans = 1; for(int k=1;k<r+1;k++) // for numbers from 1 to r find arr[j] such that gcd(i,arr[j])>1 { int j=0, i=k; while(j<arr.length) { int x = gcd(i,arr[j]); if(x>1) { arr[j] /= x; // if gcd>1, divide both by gcd i /= x; } if(i==1) break; // if i becomes 1, no need to search arr j += 1; } } for(int i : arr) // single pass to multiply the numerator ans = (ans*i)%mod; return (int)ans; } // Driver code public static void main(String[] args) { int n = 5, r = 2; System.out.print(\"Value of C(\" + n+ \", \" + r+ \") is \" +nCr(n, r) +\"\\n\"); }}// This code is contributed by Gautam Wadhwani",
"e": 64359,
"s": 62935,
"text": null
},
{
"code": "import mathclass GFG: def nCr(self, n, r): def gcd(a,b): # function to find gcd of two numbers in O(log(min(a,b))) if b==0: # base case return a return gcd(b,a%b) if r>n: return 0 if r>n-r: # C(n,r) = C(n,n-r) better time complexity for lesser r value r = n-r mod = 10**9 + 7 arr = list(range(n-r+1,n+1)) # array of elements from n-r+1 to n ans = 1 for i in range(1,r+1): # for numbers from 1 to r find arr[j] such that gcd(i,arr[j])>1 j=0 while j<len(arr): x = gcd(i,arr[j]) if x>1: arr[j] //= x # if gcd>1, divide both by gcd i //= x if arr[j]==1: # if element becomes 1, its of no use anymore so delete from arr del arr[j] j -= 1 if i==1: break # if i becomes 1, no need to search arr j += 1 for i in arr: # single pass to multiply the numerator ans = (ans*i)%mod return ans # Driver coden = 5k = 2ob = GFG()print(\"Value of C(\" + str(n) + \", \" + str(k) + \") is\", ob.nCr(n, k)) # This is code is contributed by Gautam Wadhwani",
"e": 65649,
"s": 64359,
"text": null
},
{
"code": "using System; class GFG{ // Function to find gcd of two numbers// in O(log(min(a,b))) static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} static int nCr(int n, int r){ // Base case if (r > n) return 0; // C(n,r) = C(n,n-r) better time // complexity for lesser r value if (r > n - r) r = n - r; int mod = 1000000007; // Array of elements from n-r+1 to n int[] arr = new int[r]; for(int i = n - r + 1; i <= n; i++) { arr[i + r - n - 1] = i; } long ans = 1; // For numbers from 1 to r find arr[j] // such that gcd(i,arr[j])>1 for(int k = 1; k < r + 1; k++) { int j = 0, i = k; while (j < arr.Length) { int x = gcd(i,arr[j]); if (x > 1) { // If gcd>1, divide both by gcd arr[j] /= x; i /= x; } if (i == 1) // If i becomes 1, no need // to search arr break; j += 1; } } // Single pass to multiply the numerator foreach(int i in arr) ans = (ans * i) % mod; return (int)ans;} // Driver codestatic public void Main(){ int n = 5, r = 2; Console.WriteLine(\"Value of C(\" + n + \", \" + r + \") is \" + nCr(n, r) + \"\\n\");}} // This code is contributed by rag2127",
"e": 67171,
"s": 65649,
"text": null
},
{
"code": "<script> // Javascript program to find gcd of// two numbers in O(log(min(a,b)))function gcd(a, b){ if (b == 0) return a; return gcd(b, a % b);} function nCr(n, r){ // Base case if (r > n) return 0; // C(n,r) = C(n,n-r) better time // complexity for lesser r value if (r > n - r) r = n - r; mod = 1000000007; // Array of elements from n-r+1 to n var arr = new Array(r); for(var i = n - r + 1; i <= n; i++) { arr[i + r - n - 1] = i; } var ans = 1; // For numbers from 1 to r find arr[j] // such that gcd(i,arr[j])>1 for(var k = 1; k < r + 1 ; k++) { var j = 0, i = k; while (j < arr.length) { var x = gcd(i, arr[j]); if (x > 1) { // If gcd>1, divide both by gcd arr[j] /= x; i /= x; } // If i becomes 1, no need to search arr if (i == 1) break; j += 1; } } // Single pass to multiply the numerator arr.forEach(function (i) { ans = (ans * i) % mod; }); return ans;} // Driver codevar n = 5, r = 2;document.write(\"Value of C(\" + n + \", \" + r + \") is \" + nCr(n, r) + \"\\n\"); // This code is contributed by shivanisinghss2110 </script>",
"e": 68583,
"s": 67171,
"text": null
},
{
"code": null,
"e": 68609,
"s": 68586,
"text": "Value of C(5, 2) is 10"
},
{
"code": null,
"e": 68696,
"s": 68611,
"text": "Time Complexity: O(( min(r, n-r)^2 ) * log(n)), useful when n >> r or n >> (n-r)"
},
{
"code": null,
"e": 68728,
"s": 68696,
"text": "Auxiliary Space: O(min(r, n-r))"
},
{
"code": null,
"e": 68767,
"s": 68730,
"text": "See this for GCD in logarithmic time"
},
{
"code": null,
"e": 68847,
"s": 68769,
"text": "Prime factorization of every number from 1 to n using Sieve of Eratosthenes :"
},
{
"code": null,
"e": 68940,
"s": 68849,
"text": "1. Create an array SPF of size n+1 to the smallest prime factor of each number from 1 to n"
},
{
"code": null,
"e": 68980,
"s": 68942,
"text": "Set SPF[i] = i for all i = 1 to i = n"
},
{
"code": null,
"e": 69012,
"s": 68982,
"text": "2. Use Sieve of Eratosthenes:"
},
{
"code": null,
"e": 69138,
"s": 69014,
"text": "for i = 2 to i = n:\n if i is prime,\n for all multiples j of i, j<=n:\n if SPF[j] equals j, set SPF[j] = i"
},
{
"code": null,
"e": 69332,
"s": 69140,
"text": "3. Once, we know the SPF of each number from 1 to n, we can find the prime factorization of any number from 1 to n in O(log(n)) time using recursive division by SPF until the number becomes 1"
},
{
"code": null,
"e": 69378,
"s": 69334,
"text": "Now, nCr = (n-r+1)*(r+2)* ... *(n) / (r)!"
},
{
"code": null,
"e": 69508,
"s": 69380,
"text": "4. Create a dictionary (or hashmap) to store the frequency of each prime in the prime factorization of the actual value of nCr."
},
{
"code": null,
"e": 69625,
"s": 69510,
"text": "5. So, just calculate the frequency of each prime in nCr and multiply them raised to the power of their frequency."
},
{
"code": null,
"e": 69756,
"s": 69627,
"text": "6. For the numerator, iterate through i = n-r+1 to i = n, and for all prime factors of i, store their frequency in a dictionary."
},
{
"code": null,
"e": 69799,
"s": 69758,
"text": "( prime_pow[prime_factor] += freq_in_i )"
},
{
"code": null,
"e": 69906,
"s": 69801,
"text": "7. For the denominator, iterate through i = 1 to i = r and now subtract the frequency instead of adding."
},
{
"code": null,
"e": 70007,
"s": 69908,
"text": "8. Now, traverse the dictionary and multiply the answer to (prime ^ prime_pow[prime]) % (10^9 + 7)"
},
{
"code": null,
"e": 70064,
"s": 70009,
"text": "ans = (ans * pow(prime, prime_pow[prime], mod) ) % mod"
},
{
"code": null,
"e": 70070,
"s": 70066,
"text": "C++"
},
{
"code": null,
"e": 70075,
"s": 70070,
"text": "Java"
},
{
"code": null,
"e": 70083,
"s": 70075,
"text": "Python3"
},
{
"code": null,
"e": 70086,
"s": 70083,
"text": "C#"
},
{
"code": null,
"e": 70097,
"s": 70086,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // pow(base,exp,mod) is used to find// (base^exp)%mod fast -> O(log(exp))long int pow(long int b, long int exp, long int mod){ long int ret = 1; while (exp > 0) { if ((exp & 1) > 0) ret = (ret * b) % mod; b = (b * b) % mod; exp >>= 1; } return ret;} int nCr(int n, int r){ // base case if (r > n) return 0; // C(n,r) = C(n,n-r) Complexity for // this code is lesser for lower n-r if (n - r > r) r = n - r; // list to smallest prime factor // of each number from 1 to n int SPF[n + 1]; // set smallest prime factor of each // number as itself for (int i = 1; i <= n; i++) SPF[i] = i; // set smallest prime factor of all // even numbers as 2 for (int i = 4; i <= n; i += 2) SPF[i] = 2; for (int i = 3; i * i < n + 1; i += 2) { // Check if i is prime if (SPF[i] == i) { // All multiples of i are // composite (and divisible by // i) so add i to their prime // factorization getpow(j,i) // times for (int j = i * i; j < n + 1; j += i) if (SPF[j] == j) { SPF[j] = i; } } } // Hash Map to store power of // each prime in C(n,r) map<int, int> prime_pow; // For numerator count frequency of each prime factor for (int i = r + 1; i < n + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { if (!prime_pow[SPF[t]]) { prime_pow[SPF[t]] = 1; } else prime_pow[SPF[t]]++; // prime_pow.put(SPF[t], // prime_pow.getOrDefault(SPF[t], 0) // + 1); t /= SPF[t]; } } // For denominator subtract the power of // each prime factor for (int i = 1; i < n - r + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { prime_pow[SPF[t]]--; // prime_pow.put(SPF[t], // prime_pow.get(SPF[t]) - 1); t /= SPF[t]; } } // long because mod is large and a%mod // * b%mod can overflow int long int ans = 1, mod = 1000000007; // use (a*b)%mod = (a%mod * b%mod)%mod for (auto it : prime_pow) // pow(base,exp,mod) is used to // find (base^exp)%mod fast ans = (ans * pow(it.first, prime_pow[it.first], mod)) % mod; return (int)ans;} int main(){ int n = 5, r = 2; cout << \"Value of C(\" << n << \", \" << r << \") is \" << nCr(n, r) << \"\\n\"; return 0;} // This code is contributed by rajsanghavi9.",
"e": 72882,
"s": 70097,
"text": null
},
{
"code": "import java.util.*;class GFG { // pow(base,exp,mod) is used to find // (base^exp)%mod fast -> O(log(exp)) static long pow(long b, long exp, long mod) { long ret = 1; while (exp > 0) { if ((exp & 1) > 0) ret = (ret * b) % mod; b = (b * b) % mod; exp >>= 1; } return ret; } static int nCr(int n, int r) { if (r > n) // base case return 0; // C(n,r) = C(n,n-r) Complexity for // this code is lesser for lower n-r if (n - r > r) r = n - r; // list to smallest prime factor // of each number from 1 to n int[] SPF = new int[n + 1]; // set smallest prime factor of each // number as itself for (int i = 1; i <= n; i++) SPF[i] = i; // set smallest prime factor of all // even numbers as 2 for (int i = 4; i <= n; i += 2) SPF[i] = 2; for (int i = 3; i * i < n + 1; i += 2) { // Check if i is prime if (SPF[i] == i) { // All multiples of i are // composite (and divisible by // i) so add i to their prime // factorization getpow(j,i) // times for (int j = i * i; j < n + 1; j += i) if (SPF[j] == j) { SPF[j] = i; } } } // Hash Map to store power of // each prime in C(n,r) Map<Integer, Integer> prime_pow = new HashMap<>(); // For numerator count frequency of each prime factor for (int i = r + 1; i < n + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { prime_pow.put(SPF[t], prime_pow.getOrDefault(SPF[t], 0) + 1); t /= SPF[t]; } } // For denominator subtract the power of // each prime factor for (int i = 1; i < n - r + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { prime_pow.put(SPF[t], prime_pow.get(SPF[t]) - 1); t /= SPF[t]; } } // long because mod is large and a%mod // * b%mod can overflow int long ans = 1, mod = 1000000007; // use (a*b)%mod = (a%mod * b%mod)%mod for (int i : prime_pow.keySet()) // pow(base,exp,mod) is used to // find (base^exp)%mod fast ans = (ans * pow(i, prime_pow.get(i), mod)) % mod; return (int)ans; } // Driver code public static void main(String[] args) { int n = 5, r = 2; System.out.print(\"Value of C(\" + n + \", \" + r + \") is \" + nCr(n, r) + \"\\n\"); }}// This code is contributed by Gautam Wadhwani",
"e": 76070,
"s": 72882,
"text": null
},
{
"code": "# Python code for the above approachimport math class GFG: def nCr(self, n, r): # Base case if r > n: return 0 # C(n,r) = C(n,n-r) Complexity for this # code is lesser for lower n-r if n - r > r: r = n - r # List to store smallest prime factor # of every number from 1 to n SPF = [i for i in range(n+1)] for i in range(4, n+1, 2): # set smallest prime factor of # all even numbers as 2 SPF[i] = 2 for i in range(3, n+1, 2): if i*i > n: break # Check if i is prime if SPF[i] == i: # All multiples of i are composite # (and divisible by i) so add i to # their prime factorization getpow(j,i) times for j in range(i*i, n+1, i): if SPF[j] == j: # set smallest prime factor # of j to i only if it is # not previously set SPF[j] = i # dictionary to store power of each prime in C(n,r) prime_pow = {} # For numerator count frequency # of each prime factor for i in range(r+1, n+1): t = i # Recursive division to # find prime factorization of i while t > 1: if not SPF[t] in prime_pow: prime_pow[SPF[t]] = 1 else: prime_pow[SPF[t]] += 1 t //= SPF[t] # For denominator subtract the # power of each prime factor for i in range(1, n-r+1): t = i # Recursive division to # find prime factorization of i while t > 1: prime_pow[SPF[t]] -= 1 t //= SPF[t] ans = 1 mod = 10**9 + 7 # Use (a*b)%mod = (a%mod * b%mod)%mod for i in prime_pow: # pow(base,exp,mod) is used to # find (base^exp)%mod fast ans = (ans*pow(i, prime_pow[i], mod)) % mod return ans # Driver coden = 5k = 2ob = GFG()print(\"Value of C(\" + str(n) + \", \" + str(k) + \") is\", ob.nCr(n, k)) # This is code is contributed by Gautam Wadhwani",
"e": 78531,
"s": 76070,
"text": null
},
{
"code": "using System;using System.Collections.Generic; public class GFG { // pow(base,exp,mod) is used to find // (base^exp)%mod fast -> O(log(exp)) static long pow(long b, long exp, long mod) { long ret = 1; while (exp > 0) { if ((exp & 1) > 0) ret = (ret * b) % mod; b = (b * b) % mod; exp >>= 1; } return ret; } static int nCr(int n, int r) { if (r > n) // base case return 0; // C(n,r) = C(n,n-r) Complexity for // this code is lesser for lower n-r if (n - r > r) r = n - r; // list to smallest prime factor // of each number from 1 to n int[] SPF = new int[n + 1]; // set smallest prime factor of each // number as itself for (int i = 1; i <= n; i++) SPF[i] = i; // set smallest prime factor of all // even numbers as 2 for (int i = 4; i <= n; i += 2) SPF[i] = 2; for (int i = 3; i * i < n + 1; i += 2) { // Check if i is prime if (SPF[i] == i) { // All multiples of i are // composite (and divisible by // i) so add i to their prime // factorization getpow(j,i) // times for (int j = i * i; j < n + 1; j += i) if (SPF[j] == j) { SPF[j] = i; } } } // Hash Map to store power of // each prime in C(n,r) Dictionary<int, int> prime_pow = new Dictionary<int, int>(); // For numerator count frequency of each prime // factor for (int i = r + 1; i < n + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { if (prime_pow.ContainsKey(SPF[t])) { prime_pow[SPF[t]] = prime_pow[SPF[t]] + 1; } else { prime_pow.Add(SPF[t], 1); } t /= SPF[t]; } } // For denominator subtract the power of // each prime factor for (int i = 1; i < n - r + 1; i++) { int t = i; // Recursive division to find // prime factorization of i while (t > 1) { if (prime_pow.ContainsKey(SPF[t])) { prime_pow[SPF[t]] = prime_pow[SPF[t]] - 1; } t /= SPF[t]; } } // long because mod is large and a%mod // * b%mod can overflow int long ans = 1, mod = 1000000007; // use (a*b)%mod = (a%mod * b%mod)%mod foreach(int i in prime_pow.Keys) // pow(base,exp,mod) is used to // find (base^exp)%mod fast ans = (ans * pow(i, prime_pow[i], mod)) % mod; return (int)ans; } // Driver code public static void Main(String[] args) { int n = 5, r = 2; Console.Write(\"Value of C(\" + n + \", \" + r + \") is \" + nCr(n, r) + \"\\n\"); }} // This code contributed by gauravrajput1",
"e": 81785,
"s": 78531,
"text": null
},
{
"code": "<script> // Javascript program to find gcd of// two numbers in O(log(min(a,b))) function gcd(a, b){ if (b == 0) return a; return gcd(b, a % b);} function nCr(n, r){ // base case if (r > n) return 0; // C(n,r) = C(n,n-r) if (r > n - r) r = n - r; var mod = 1000000007; // array of elements from n-r+1 to n var arr = new Array(r); for (var i = n - r + 1; i <= n; i++) { arr[i + r - n - 1] = i; } var ans = 1; // for numbers from 1 to r find arr[j], // such that gcd(i,arr[j])>1 for (var k = 1; k < r + 1; k++) { var j = 0; var i = k; do { var x = gcd(i, arr[j]); if (x > 1) { // if gcd>1, divide both by gcd arr[j] /= x; i /= x; } // if i becomes 1, no need to search arr if (i == 1) break; j += 1; } while (j < r); } // single pass to multiply the numerator arr.forEach(function (i, index) { ans = (ans * i) % mod; }); return ans;} var n = 5;var r = 2;document.write(\"Value of C(\" + n + \", \" + r + \") is \" + nCr(n, r) + \"<br>\"); // This code is contributed by shivani. </script>",
"e": 83041,
"s": 81785,
"text": null
},
{
"code": null,
"e": 83067,
"s": 83044,
"text": "Value of C(5, 2) is 10"
},
{
"code": null,
"e": 83122,
"s": 83069,
"text": "Time Complexity: O(n*log(n)), so useful when r->n/2"
},
{
"code": null,
"e": 83144,
"s": 83122,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 83192,
"s": 83146,
"text": "See this for Prime factorization in O(log(n))"
},
{
"code": null,
"e": 83242,
"s": 83194,
"text": "Another Approach: (Modular Inversion technique)"
},
{
"code": null,
"e": 83508,
"s": 83244,
"text": "1. The general formula of nCr is ( n*(n-1)*(n-2)* ... *(n-r+1) ) / (r!). We can directly use this formula to find nCr. But that will overflow out of bound. We need to find nCr mod m so that it doesn’t overflow. We can easily do it with modular arithmetic formula."
},
{
"code": null,
"e": 83614,
"s": 83510,
"text": "for the n*(n-1)*(n-2)* ... *(n-r+1) part we can use the formula,\n(a*b) mod m = ((a % m) * (b % m)) % m"
},
{
"code": null,
"e": 83834,
"s": 83616,
"text": "2. and for the 1/r! part, we need to find the modular inverse of every number from 1 to r. Then use the same formula above with a modular inverse of 1 to r. We can find modular inverse in O(r) time using the formula,"
},
{
"code": null,
"e": 83927,
"s": 83836,
"text": "inv[1] = 1\ninv[i] = − ⌊m/i⌋ * inv[m mod i] mod m\nTo use this formula, m has to be a prime."
},
{
"code": null,
"e": 84023,
"s": 83929,
"text": "In the practice problem, we need to show the answer with modulo 1000000007 which is a prime. "
},
{
"code": null,
"e": 84055,
"s": 84025,
"text": "So, this technique will work."
},
{
"code": null,
"e": 84061,
"s": 84057,
"text": "C++"
},
{
"code": null,
"e": 84066,
"s": 84061,
"text": "Java"
},
{
"code": null,
"e": 84074,
"s": 84066,
"text": "Python3"
},
{
"code": null,
"e": 84077,
"s": 84074,
"text": "C#"
},
{
"code": null,
"e": 84088,
"s": 84077,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find binomial// coefficientint binomialCoeff(int n, int r){ if (r > n) return 0; long long int m = 1000000007; long long int inv[r + 1] = { 0 }; inv[0] = 1; if(r+1>=2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[m % i] % m; } int ans = 1; // for 1/(r!) part for (int i = 2; i <= r; i++) { ans = ((ans % m) * (inv[i] % m)) % m; } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (int i = n; i >= (n - r + 1); i--) { ans = ((ans % m) * (i % m)) % m; } return ans;} /* Driver code*/int main(){ int n = 5, r = 2; cout << \"Value of C(\" << n << \", \" << r << \") is \" << binomialCoeff(n, r) << endl; return 0;}",
"e": 85030,
"s": 84088,
"text": null
},
{
"code": "// JAVA program for the above approachimport java.util.*;class GFG{ // Function to find binomial// coefficientstatic int binomialCoeff(int n, int r){ if (r > n) return 0; long m = 1000000007; long inv[] = new long[r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } int ans = 1; // for 1/(r!) part for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (int i = n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans;} /* Driver code*/public static void main(String[] args){ int n = 5, r = 2; System.out.print(\"Value of C(\" + n+ \", \" + r+ \") is \" +binomialCoeff(n, r) +\"\\n\");}} // This code contributed by Rajput-Ji",
"e": 86031,
"s": 85030,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find binomial# coefficientdef binomialCoeff(n, r): if (r > n): return 0 m = 1000000007 inv = [0 for i in range(r + 1)] inv[0] = 1; if(r+1>=2) inv[1] = 1; # Getting the modular inversion # for all the numbers # from 2 to r with respect to m # here m = 1000000007 for i in range(2, r + 1): inv[i] = m - (m // i) * inv[m % i] % m ans = 1 # for 1/(r!) part for i in range(2, r + 1): ans = ((ans % m) * (inv[i] % m)) % m # for (n)*(n-1)*(n-2)*...*(n-r+1) part for i in range(n, n - r, -1): ans = ((ans % m) * (i % m)) % m return ans # Driver coden = 5r = 2 print(\"Value of C(\" ,n , \", \" , r , \") is \",binomialCoeff(n, r)) # This code is contributed by rohan07",
"e": 86852,
"s": 86031,
"text": null
},
{
"code": "// C# program for the above approachusing System; public class GFG{ // Function to find binomial// coefficientstatic int binomialCoeff(int n, int r){ if (r > n) return 0; long m = 1000000007; long []inv = new long[r + 1]; inv[0] = 1; if(r+1>=2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (int i = 2; i <= r; i++) { inv[i] = m - (m / i) * inv[(int) (m % i)] % m; } int ans = 1; // for 1/(r!) part for (int i = 2; i <= r; i++) { ans = (int) (((ans % m) * (inv[i] % m)) % m); } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (int i = n; i >= (n - r + 1); i--) { ans = (int) (((ans % m) * (i % m)) % m); } return ans;} /* Driver code*/public static void Main(String[] args){ int n = 5, r = 2; Console.Write(\"Value of C(\" + n+ \", \" + r+ \") is \" +binomialCoeff(n, r) +\"\\n\");}} // This code is contributed by 29AjayKumar",
"e": 87857,
"s": 86852,
"text": null
},
{
"code": "<script> // JavaScript Program for the above approach // Function to find binomial // coefficient function binomialCoeff(n, r) { if (r > n) return 0; let m = 1000000007; let inv = new Array(r + 1).fill(0); inv[0] = 1; if (r + 1 >= 2) inv[1] = 1; // Getting the modular inversion // for all the numbers // from 2 to r with respect to m // here m = 1000000007 for (let i = 2; i <= r; i++) { inv[i] = m - Math.floor(m / i) * inv[m % i] % m; } let ans = 1; // for 1/(r!) part for (let i = 2; i <= r; i++) { ans = ((ans % m) * (inv[i] % m)) % m; } // for (n)*(n-1)*(n-2)*...*(n-r+1) part for (let i = n; i >= (n - r + 1); i--) { ans = ((ans % m) * (i % m)) % m; } return ans; } /* Driver code*/ let n = 5, r = 2; document.write(\"Value of C(\" + n + \", \" + r + \") is \" + binomialCoeff(n, r) + \"<br>\"); // This code is contributed by Potta Lokesh </script>",
"e": 89071,
"s": 87857,
"text": null
},
{
"code": null,
"e": 89097,
"s": 89074,
"text": "Value of C(5, 2) is 10"
},
{
"code": null,
"e": 89121,
"s": 89097,
"text": "Time Complexity: O(n+k)"
},
{
"code": null,
"e": 89143,
"s": 89121,
"text": "Auxiliary Space: O(k)"
},
{
"code": null,
"e": 89205,
"s": 89145,
"text": "See this for Space and time-efficient Binomial Coefficient "
},
{
"code": null,
"e": 89335,
"s": 89209,
"text": "References: http://www.csl.mtu.edu/cs4321/www/Lectures/Lecture%2015%20-%20Dynamic%20Programming%20Binomial%20Coefficients.htm"
},
{
"code": null,
"e": 89391,
"s": 89337,
"text": "https://cp-algorithms.com/algebra/module-inverse.html"
},
{
"code": null,
"e": 89520,
"s": 89393,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 89528,
"s": 89522,
"text": "jit_t"
},
{
"code": null,
"e": 89533,
"s": 89528,
"text": "vt_m"
},
{
"code": null,
"e": 89546,
"s": 89533,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 89561,
"s": 89546,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 89575,
"s": 89561,
"text": "rathbhupendra"
},
{
"code": null,
"e": 89588,
"s": 89575,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 89605,
"s": 89588,
"text": "MohammadMudassir"
},
{
"code": null,
"e": 89620,
"s": 89605,
"text": "PrateekGupta10"
},
{
"code": null,
"e": 89630,
"s": 89620,
"text": "mr_hitman"
},
{
"code": null,
"e": 89640,
"s": 89630,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 89652,
"s": 89640,
"text": "29AjayKumar"
},
{
"code": null,
"e": 89667,
"s": 89652,
"text": "mansimar_anand"
},
{
"code": null,
"e": 89688,
"s": 89667,
"text": "divyanshusrivastava1"
},
{
"code": null,
"e": 89699,
"s": 89688,
"text": "1505086kmr"
},
{
"code": null,
"e": 89709,
"s": 89699,
"text": "gautamsw5"
},
{
"code": null,
"e": 89724,
"s": 89709,
"text": "amit143katiyar"
},
{
"code": null,
"e": 89738,
"s": 89724,
"text": "divyesh072019"
},
{
"code": null,
"e": 89746,
"s": 89738,
"text": "rohan07"
},
{
"code": null,
"e": 89755,
"s": 89746,
"text": "jyoti369"
},
{
"code": null,
"e": 89774,
"s": 89755,
"text": "surindertarika1234"
},
{
"code": null,
"e": 89788,
"s": 89774,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 89809,
"s": 89788,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 89817,
"s": 89809,
"text": "rag2127"
},
{
"code": null,
"e": 89830,
"s": 89817,
"text": "rajsanghavi9"
},
{
"code": null,
"e": 89849,
"s": 89830,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 89866,
"s": 89849,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 89884,
"s": 89866,
"text": "reenadevi98412200"
},
{
"code": null,
"e": 89897,
"s": 89884,
"text": "simmytarika5"
},
{
"code": null,
"e": 89911,
"s": 89897,
"text": "GauravRajput1"
},
{
"code": null,
"e": 89927,
"s": 89911,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 89939,
"s": 89927,
"text": "prophet1999"
},
{
"code": null,
"e": 89956,
"s": 89939,
"text": "surinderdawra388"
},
{
"code": null,
"e": 89977,
"s": 89956,
"text": "binomial coefficient"
},
{
"code": null,
"e": 89997,
"s": 89977,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 90010,
"s": 89997,
"text": "Mathematical"
},
{
"code": null,
"e": 90030,
"s": 90010,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 90043,
"s": 90030,
"text": "Mathematical"
},
{
"code": null,
"e": 90141,
"s": 90043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 90150,
"s": 90141,
"text": "Comments"
},
{
"code": null,
"e": 90163,
"s": 90150,
"text": "Old Comments"
},
{
"code": null,
"e": 90195,
"s": 90163,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 90226,
"s": 90195,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 90259,
"s": 90226,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 90297,
"s": 90259,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 90365,
"s": 90297,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 90380,
"s": 90365,
"text": "C++ Data Types"
},
{
"code": null,
"e": 90423,
"s": 90380,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 90465,
"s": 90423,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 90489,
"s": 90465,
"text": "Merge two sorted arrays"
}
]
|
Bootstrap - Buttons | This chapter covers the use age of Bootstrap button with examples. Anything that is given a class of .btn will inherit the default look of a gray button with rounded corners. However, Bootstrap provides some options to style buttons, which are summarized in the following table −
btn
Default/ Standard button.
btn-primary
Provides extra visual weight and identifies the primary action in a set of buttons.
btn-success
Indicates a successful or positive action.
btn-info
Contextual button for informational alert messages.
btn-warning
Indicates caution should be taken with this action.
btn-danger
Indicates a dangerous or potentially negative action.
btn-link
Deemphasize a button by making it look like a link while maintaining button behavior.
The following example demonstrates all the above button classes −
<!-- Standard button -->
<button type = "button" class = "btn btn-default">Default Button</button>
<!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
<button type = "button" class = "btn btn-primary">Primary Button</button>
<!-- Indicates a successful or positive action -->
<button type = "button" class = "btn btn-success">Success Button</button>
<!-- Contextual button for informational alert messages -->
<button type = "button" class = "btn btn-info">Info Button</button>
<!-- Indicates caution should be taken with this action -->
<button type = "button" class = "btn btn-warning">Warning Button</button>
<!-- Indicates a dangerous or potentially negative action -->
<button type = "button" class = "btn btn-danger">Danger Button</button>
<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type = "button" class = "btn btn-link">Link Button</button>
The following table summarizes the classes used to get buttons of various sizes −
.btn-lg
This makes the button size large.
.btn-sm
This makes the button size small.
.btn-xs
This makes the button size extra small.
.btn-block
This creates block level buttons—those that span the full width of a parent.
The following example demonstrates this −
<p>
<button type = "button" class = "btn btn-primary btn-lg">
Large Primary button
</button>
<button type = "button" class = "btn btn-default btn-lg">
Large button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary">
Default size Primary button
</button>
<button type = "button" class = "btn btn-default">
Default size button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary btn-sm">
Small Primary button
</button>
<button type = "button" class = "btn btn-default btn-sm">
Small button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary btn-xs">
Extra small Primary button
</button>
<button type = "button" class = "btn btn-default btn-xs">
Extra small button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary btn-lg btn-block">
Block level Primary button
</button>
<button type = "button" class = "btn btn-default btn-lg btn-block">
Block level button
</button>
</p>
Large Primary button
Large button
Default size Primary button
Default size button
Small Primary button
Small button
Extra small Primary button
Extra small button
Block level Primary button
Block level button
Bootstrap provides classes which allow you to change the state of buttons as active, disabled etc. each of which are discussed in the following sections.
Buttons will appear pressed (with a darker background, darker border, and inset shadow) when active. The following table summarizes classes used to make button elements and anchor elements active −
The following example demonstrates this −
<p>
<button type = "button" class = "btn btn-default btn-lg ">
Default Button
</button>
<button type = "button" class = "btn btn-default btn-lg active">
Active Button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary btn-lg">
Primary button
</button>
<button type = "button" class = "btn btn-primary btn-lg active">
Active Primary button
</button>
</p>
Default Button
Active Button
Primary button
Active Primary button
When you disable a button, it will fade in color by 50%, and lose the gradient.
The following table summarizes classes used to make button element and anchor element disabled −
Add the disabled class to <a> buttons.
Note − This class will only change the <a>'s appearance, not its functionality. You need to use custom JavaScript to disable links here.
The following example demonstrates this −
<p>
<button type = "button" class = "btn btn-default btn-lg">
Default Button
</button>
<button type = "button" class = "btn btn-default btn-lg" disabled = "disabled">
Disabled Button
</button>
</p>
<p>
<button type = "button" class = "btn btn-primary btn-lg">
Primary button
</button>
<button type = "button" class = "btn btn-primary btn-lg" disabled = "disabled">
Disabled Primary button
</button>
</p>
<p>
<a href = "#" class = "btn btn-default btn-lg" role = "button">
Link
</a>
<a href = "#" class = "btn btn-default btn-lg disabled" role = "button">
Disabled Link
</a>
</p>
<p>
<a href = "#" class = "btn btn-primary btn-lg" role = "button">
Primary link
</a>
<a href = "#" class = "btn btn-primary btn-lg disabled" role = "button">
Disabled Primary link
</a>
</p>
Default Button
Disabled Button
Primary button
Disabled Primary button
Link
Disabled Link
Primary link
Disabled Primary link
You may use button classes with <a>, <button>, or <input> element. But it is recommended that you use it with <button> elements mostly to avoid cross browser inconsistency issues.
The following example demonstrates this −
<a class = "btn btn-default" href = "#" role = "button">Link</a>
<button class = "btn btn-default" type = "submit">Button</button>
<input class = "btn btn-default" type = "button" value = "Input">
<input class = "btn btn-default" type = "submit" value = "Submit">
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3611,
"s": 3331,
"text": "This chapter covers the use age of Bootstrap button with examples. Anything that is given a class of .btn will inherit the default look of a gray button with rounded corners. However, Bootstrap provides some options to style buttons, which are summarized in the following table −"
},
{
"code": null,
"e": 3615,
"s": 3611,
"text": "btn"
},
{
"code": null,
"e": 3641,
"s": 3615,
"text": "Default/ Standard button."
},
{
"code": null,
"e": 3653,
"s": 3641,
"text": "btn-primary"
},
{
"code": null,
"e": 3737,
"s": 3653,
"text": "Provides extra visual weight and identifies the primary action in a set of buttons."
},
{
"code": null,
"e": 3749,
"s": 3737,
"text": "btn-success"
},
{
"code": null,
"e": 3792,
"s": 3749,
"text": "Indicates a successful or positive action."
},
{
"code": null,
"e": 3801,
"s": 3792,
"text": "btn-info"
},
{
"code": null,
"e": 3853,
"s": 3801,
"text": "Contextual button for informational alert messages."
},
{
"code": null,
"e": 3865,
"s": 3853,
"text": "btn-warning"
},
{
"code": null,
"e": 3917,
"s": 3865,
"text": "Indicates caution should be taken with this action."
},
{
"code": null,
"e": 3928,
"s": 3917,
"text": "btn-danger"
},
{
"code": null,
"e": 3982,
"s": 3928,
"text": "Indicates a dangerous or potentially negative action."
},
{
"code": null,
"e": 3991,
"s": 3982,
"text": "btn-link"
},
{
"code": null,
"e": 4077,
"s": 3991,
"text": "Deemphasize a button by making it look like a link while maintaining button behavior."
},
{
"code": null,
"e": 4143,
"s": 4077,
"text": "The following example demonstrates all the above button classes −"
},
{
"code": null,
"e": 5097,
"s": 4143,
"text": "<!-- Standard button -->\n<button type = \"button\" class = \"btn btn-default\">Default Button</button>\n\n<!-- Provides extra visual weight and identifies the primary action in a set of buttons -->\n<button type = \"button\" class = \"btn btn-primary\">Primary Button</button>\n\n<!-- Indicates a successful or positive action -->\n<button type = \"button\" class = \"btn btn-success\">Success Button</button>\n\n<!-- Contextual button for informational alert messages -->\n<button type = \"button\" class = \"btn btn-info\">Info Button</button>\n\n<!-- Indicates caution should be taken with this action -->\n<button type = \"button\" class = \"btn btn-warning\">Warning Button</button>\n\n<!-- Indicates a dangerous or potentially negative action -->\n<button type = \"button\" class = \"btn btn-danger\">Danger Button</button>\n\n<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->\n<button type = \"button\" class = \"btn btn-link\">Link Button</button>"
},
{
"code": null,
"e": 5179,
"s": 5097,
"text": "The following table summarizes the classes used to get buttons of various sizes −"
},
{
"code": null,
"e": 5187,
"s": 5179,
"text": ".btn-lg"
},
{
"code": null,
"e": 5221,
"s": 5187,
"text": "This makes the button size large."
},
{
"code": null,
"e": 5229,
"s": 5221,
"text": ".btn-sm"
},
{
"code": null,
"e": 5263,
"s": 5229,
"text": "This makes the button size small."
},
{
"code": null,
"e": 5271,
"s": 5263,
"text": ".btn-xs"
},
{
"code": null,
"e": 5311,
"s": 5271,
"text": "This makes the button size extra small."
},
{
"code": null,
"e": 5322,
"s": 5311,
"text": ".btn-block"
},
{
"code": null,
"e": 5399,
"s": 5322,
"text": "This creates block level buttons—those that span the full width of a parent."
},
{
"code": null,
"e": 5441,
"s": 5399,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 6524,
"s": 5441,
"text": "<p>\n <button type = \"button\" class = \"btn btn-primary btn-lg\">\n Large Primary button\n </button>\n \n <button type = \"button\" class = \"btn btn-default btn-lg\">\n Large button\n </button>\n</p>\n\n<p>\n <button type = \"button\" class = \"btn btn-primary\">\n Default size Primary button\n </button>\n \n <button type = \"button\" class = \"btn btn-default\">\n Default size button\n </button>\n</p>\n\n<p>\n <button type = \"button\" class = \"btn btn-primary btn-sm\">\n Small Primary button\n </button>\n \n <button type = \"button\" class = \"btn btn-default btn-sm\">\n Small button\n </button>\n</p>\n\n<p>\n <button type = \"button\" class = \"btn btn-primary btn-xs\">\n Extra small Primary button\n </button>\n \n <button type = \"button\" class = \"btn btn-default btn-xs\">\n Extra small button\n </button>\n</p>\n\n<p>\n <button type = \"button\" class = \"btn btn-primary btn-lg btn-block\">\n Block level Primary button\n </button>\n \n <button type = \"button\" class = \"btn btn-default btn-lg btn-block\">\n Block level button\n </button>\n</p>"
},
{
"code": null,
"e": 6584,
"s": 6524,
"text": "\n\n Large Primary button\n \nLarge button\n \n"
},
{
"code": null,
"e": 6668,
"s": 6584,
"text": "\n\n Default size Primary button\n \n\n Default size button\n \n"
},
{
"code": null,
"e": 6738,
"s": 6668,
"text": "\n\n Small Primary button\n \n\n Small button\n \n"
},
{
"code": null,
"e": 6820,
"s": 6738,
"text": "\n\n Extra small Primary button\n \n\n Extra small button\n \n"
},
{
"code": null,
"e": 6902,
"s": 6820,
"text": "\n\n Block level Primary button\n \n\n Block level button\n \n"
},
{
"code": null,
"e": 7056,
"s": 6902,
"text": "Bootstrap provides classes which allow you to change the state of buttons as active, disabled etc. each of which are discussed in the following sections."
},
{
"code": null,
"e": 7254,
"s": 7056,
"text": "Buttons will appear pressed (with a darker background, darker border, and inset shadow) when active. The following table summarizes classes used to make button elements and anchor elements active −"
},
{
"code": null,
"e": 7296,
"s": 7254,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 7724,
"s": 7296,
"text": "<p>\n <button type = \"button\" class = \"btn btn-default btn-lg \">\n Default Button\n </button>\n \n <button type = \"button\" class = \"btn btn-default btn-lg active\">\n Active Button\n </button>\n</p>\n\n<p>\n <button type = \"button\" class = \"btn btn-primary btn-lg\">\n Primary button\n </button>\n \n <button type = \"button\" class = \"btn btn-primary btn-lg active\">\n Active Primary button\n </button>\n</p>"
},
{
"code": null,
"e": 7801,
"s": 7724,
"text": "\n\n Default Button\n \n\n Active Button\n \n"
},
{
"code": null,
"e": 7886,
"s": 7801,
"text": "\n\n Primary button\n \n\n Active Primary button\n \n"
},
{
"code": null,
"e": 7966,
"s": 7886,
"text": "When you disable a button, it will fade in color by 50%, and lose the gradient."
},
{
"code": null,
"e": 8063,
"s": 7966,
"text": "The following table summarizes classes used to make button element and anchor element disabled −"
},
{
"code": null,
"e": 8102,
"s": 8063,
"text": "Add the disabled class to <a> buttons."
},
{
"code": null,
"e": 8239,
"s": 8102,
"text": "Note − This class will only change the <a>'s appearance, not its functionality. You need to use custom JavaScript to disable links here."
},
{
"code": null,
"e": 8281,
"s": 8239,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 9166,
"s": 8281,
"text": "<p>\n <button type = \"button\" class = \"btn btn-default btn-lg\">\n Default Button\n </button>\n \n <button type = \"button\" class = \"btn btn-default btn-lg\" disabled = \"disabled\">\n Disabled Button\n </button>\n</p>\n\n<p>\n <button type = \"button\" class = \"btn btn-primary btn-lg\">\n Primary button\n </button>\n \n <button type = \"button\" class = \"btn btn-primary btn-lg\" disabled = \"disabled\">\n Disabled Primary button\n </button>\n</p>\n\n<p>\n <a href = \"#\" class = \"btn btn-default btn-lg\" role = \"button\">\n Link\n </a>\n \n <a href = \"#\" class = \"btn btn-default btn-lg disabled\" role = \"button\">\n Disabled Link\n </a>\n</p>\n\n<p>\n <a href = \"#\" class = \"btn btn-primary btn-lg\" role = \"button\">\n Primary link\n </a>\n \n <a href = \"#\" class = \"btn btn-primary btn-lg disabled\" role = \"button\">\n Disabled Primary link\n </a>\n</p>"
},
{
"code": null,
"e": 9245,
"s": 9166,
"text": "\n\n Default Button\n \n\n Disabled Button\n \n"
},
{
"code": null,
"e": 9332,
"s": 9245,
"text": "\n\n Primary button\n \n\n Disabled Primary button\n \n"
},
{
"code": null,
"e": 9399,
"s": 9332,
"text": "\n\n Link\n \n\n Disabled Link\n \n"
},
{
"code": null,
"e": 9482,
"s": 9399,
"text": "\n\n Primary link\n \n\n Disabled Primary link\n \n"
},
{
"code": null,
"e": 9662,
"s": 9482,
"text": "You may use button classes with <a>, <button>, or <input> element. But it is recommended that you use it with <button> elements mostly to avoid cross browser inconsistency issues."
},
{
"code": null,
"e": 9704,
"s": 9662,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 9968,
"s": 9704,
"text": "<a class = \"btn btn-default\" href = \"#\" role = \"button\">Link</a>\n<button class = \"btn btn-default\" type = \"submit\">Button</button>\n<input class = \"btn btn-default\" type = \"button\" value = \"Input\">\n<input class = \"btn btn-default\" type = \"submit\" value = \"Submit\">"
},
{
"code": null,
"e": 10001,
"s": 9968,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10015,
"s": 10001,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 10050,
"s": 10015,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 10067,
"s": 10050,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 10104,
"s": 10067,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 10132,
"s": 10104,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 10165,
"s": 10132,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 10177,
"s": 10165,
"text": " Azaz Patel"
},
{
"code": null,
"e": 10212,
"s": 10177,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10229,
"s": 10212,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 10262,
"s": 10229,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10282,
"s": 10262,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 10289,
"s": 10282,
"text": " Print"
},
{
"code": null,
"e": 10300,
"s": 10289,
"text": " Add Notes"
}
]
|
iOS - Delegates | Let's assume an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action. This is achieved with the help of delegates.
The key concepts in the above example are −
A is a delegate object of B.
A is a delegate object of B.
B will have a reference of A.
B will have a reference of A.
A will implement the delegate methods of B.
A will implement the delegate methods of B.
B will notify A through the delegate methods.
B will notify A through the delegate methods.
Step 1 − First, create a single view application.
Step 2 − Then select File → New → File...
Step 3 − Then select Objective C Class and click Next.
Step 4 − Give a name to the class, say, SampleProtocol with subclass as NSObject as shown below.
Step 5 − Then select create.
Step 6 − Add a protocol to the SampleProtocol.h file and the updated code is as follows −
#import <Foundation/Foundation.h>
// Protocol definition starts here
@protocol SampleProtocolDelegate <NSObject>
@required
- (void) processCompleted;
@end
// Protocol Definition ends here
@interface SampleProtocol : NSObject {
// Delegate to respond back
id <SampleProtocolDelegate> _delegate;
}
@property (nonatomic,strong) id delegate;
-(void)startSampleProcess; // Instance method
@end
Step 7 − Implement the instance method by updating the SampleProtocol.m file as shown below.
#import "SampleProtocol.h"
@implementation SampleProtocol
-(void)startSampleProcess {
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate
selector:@selector(processCompleted) userInfo:nil repeats:NO];
}
@end
Step 8 − Add a UILabel in the ViewController.xib by dragging the label from the object library to UIView as shown below.
Step 9 − Create an IBOutlet for the label and name it as myLabel and update the code as follows to adopt SampleProtocolDelegate in ViewController.h.
#import <UIKit/UIKit.h>
#import "SampleProtocol.h"
@interface ViewController : UIViewController<SampleProtocolDelegate> {
IBOutlet UILabel *myLabel;
}
@end
Step 10 Implement the delegate method, create object for SampleProtocol and call the startSampleProcess method. The Updated ViewController.m file is as follows −
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init];
sampleProtocol.delegate = self;
[myLabel setText:@"Processing..."];
[sampleProtocol startSampleProcess];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Sample protocol delegate
-(void)processCompleted {
[myLabel setText:@"Process Completed"];
}
@end
Step 11 We will see an output as follows. Initially the label displays "processing...", which gets updated once the delegate method is called by the SampleProtocol object.
23 Lectures
1.5 hours
Ashish Sharma
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
69 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2308,
"s": 2091,
"text": "Let's assume an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action. This is achieved with the help of delegates."
},
{
"code": null,
"e": 2352,
"s": 2308,
"text": "The key concepts in the above example are −"
},
{
"code": null,
"e": 2381,
"s": 2352,
"text": "A is a delegate object of B."
},
{
"code": null,
"e": 2410,
"s": 2381,
"text": "A is a delegate object of B."
},
{
"code": null,
"e": 2440,
"s": 2410,
"text": "B will have a reference of A."
},
{
"code": null,
"e": 2470,
"s": 2440,
"text": "B will have a reference of A."
},
{
"code": null,
"e": 2514,
"s": 2470,
"text": "A will implement the delegate methods of B."
},
{
"code": null,
"e": 2558,
"s": 2514,
"text": "A will implement the delegate methods of B."
},
{
"code": null,
"e": 2604,
"s": 2558,
"text": "B will notify A through the delegate methods."
},
{
"code": null,
"e": 2650,
"s": 2604,
"text": "B will notify A through the delegate methods."
},
{
"code": null,
"e": 2700,
"s": 2650,
"text": "Step 1 − First, create a single view application."
},
{
"code": null,
"e": 2742,
"s": 2700,
"text": "Step 2 − Then select File → New → File..."
},
{
"code": null,
"e": 2797,
"s": 2742,
"text": "Step 3 − Then select Objective C Class and click Next."
},
{
"code": null,
"e": 2894,
"s": 2797,
"text": "Step 4 − Give a name to the class, say, SampleProtocol with subclass as NSObject as shown below."
},
{
"code": null,
"e": 2923,
"s": 2894,
"text": "Step 5 − Then select create."
},
{
"code": null,
"e": 3013,
"s": 2923,
"text": "Step 6 − Add a protocol to the SampleProtocol.h file and the updated code is as follows −"
},
{
"code": null,
"e": 3413,
"s": 3013,
"text": "#import <Foundation/Foundation.h>\n\n// Protocol definition starts here \n@protocol SampleProtocolDelegate <NSObject>\n@required\n- (void) processCompleted;\n@end\n\n// Protocol Definition ends here\n@interface SampleProtocol : NSObject {\n // Delegate to respond back\n id <SampleProtocolDelegate> _delegate; \n}\n@property (nonatomic,strong) id delegate;\n\n-(void)startSampleProcess; // Instance method\n@end"
},
{
"code": null,
"e": 3506,
"s": 3413,
"text": "Step 7 − Implement the instance method by updating the SampleProtocol.m file as shown below."
},
{
"code": null,
"e": 3734,
"s": 3506,
"text": "#import \"SampleProtocol.h\"\n\n@implementation SampleProtocol\n\n-(void)startSampleProcess {\n [NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate \n\tselector:@selector(processCompleted) userInfo:nil repeats:NO];\n}\n@end"
},
{
"code": null,
"e": 3855,
"s": 3734,
"text": "Step 8 − Add a UILabel in the ViewController.xib by dragging the label from the object library to UIView as shown below."
},
{
"code": null,
"e": 4004,
"s": 3855,
"text": "Step 9 − Create an IBOutlet for the label and name it as myLabel and update the code as follows to adopt SampleProtocolDelegate in ViewController.h."
},
{
"code": null,
"e": 4164,
"s": 4004,
"text": "#import <UIKit/UIKit.h>\n#import \"SampleProtocol.h\"\n\n@interface ViewController : UIViewController<SampleProtocolDelegate> {\n IBOutlet UILabel *myLabel;\n}\n@end"
},
{
"code": null,
"e": 4326,
"s": 4164,
"text": "Step 10 Implement the delegate method, create object for SampleProtocol and call the startSampleProcess method. The Updated ViewController.m file is as follows −"
},
{
"code": null,
"e": 4970,
"s": 4326,
"text": "#import \"ViewController.h\"\n\n@interface ViewController ()\n\n@end\n\n@implementation ViewController\n\n- (void)viewDidLoad {\n [super viewDidLoad];\n SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init];\n sampleProtocol.delegate = self;\n [myLabel setText:@\"Processing...\"];\n [sampleProtocol startSampleProcess];\n // Do any additional setup after loading the view, typically from a nib.\n}\n\n- (void)didReceiveMemoryWarning {\n [super didReceiveMemoryWarning];\n // Dispose of any resources that can be recreated.\n}\n\n#pragma mark - Sample protocol delegate\n-(void)processCompleted {\n [myLabel setText:@\"Process Completed\"];\n}\n@end"
},
{
"code": null,
"e": 5142,
"s": 4970,
"text": "Step 11 We will see an output as follows. Initially the label displays \"processing...\", which gets updated once the delegate method is called by the SampleProtocol object."
},
{
"code": null,
"e": 5177,
"s": 5142,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5192,
"s": 5177,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 5224,
"s": 5192,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5241,
"s": 5224,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5276,
"s": 5241,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5293,
"s": 5276,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5328,
"s": 5293,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5345,
"s": 5328,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5378,
"s": 5345,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5395,
"s": 5378,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5428,
"s": 5395,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5445,
"s": 5428,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5452,
"s": 5445,
"text": " Print"
},
{
"code": null,
"e": 5463,
"s": 5452,
"text": " Add Notes"
}
]
|
Angular 8 - Backward Compatibility | Angular framework provides maximum compatibility with previous versions. If Angular Team deprecate a feature in a release, it will wait for 3 more release to completely remove the feature. Angular Team release a major version for every six months. Every version will have active maintenance period of six months and then Long Term Support (LTS) period for another one year. Angular does not introduce breaking changes during these 18 months. If Angular version deprecate a feature in version 5, then it will probably remove it in version 8 or in next releases.
Angular maintains documentation and guides of all version. For example, Angular documentation for version 7 can be checked @ https://v7.angular.io. Angular also provides a detailed upgrade path through https://update.angular.io/ site.
To update Angular application written from previous version, use below command inside the project directory:
ng update @angular/cli@8 @angular/core@8
Let us see some of the important changes introduced in Angular 8.
HttpModule module and its associated Http service is removed. Use HttpClient service from HttpClientModule module.
HttpModule module and its associated Http service is removed. Use HttpClient service from HttpClientModule module.
/deep/, >>> and :ng-deep component selectors are removed.
/deep/, >>> and :ng-deep component selectors are removed.
Angular default version of TypeScript is 3.4.
Angular default version of TypeScript is 3.4.
Node version supported by Angular is v10 and later.
Node version supported by Angular is v10 and later.
@ViewChild() and ContentChild() decorator behaviour is changed from dynaic to static.
@ViewChild() and ContentChild() decorator behaviour is changed from dynaic to static.
Lazy loading string syntax in router module is removed and only function based is supported.
loadChildren: './lazy/lazy.module#LazyModule'
loadChildren: () => import('./lazy/lazy.module'
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2949,
"s": 2388,
"text": "Angular framework provides maximum compatibility with previous versions. If Angular Team deprecate a feature in a release, it will wait for 3 more release to completely remove the feature. Angular Team release a major version for every six months. Every version will have active maintenance period of six months and then Long Term Support (LTS) period for another one year. Angular does not introduce breaking changes during these 18 months. If Angular version deprecate a feature in version 5, then it will probably remove it in version 8 or in next releases."
},
{
"code": null,
"e": 3184,
"s": 2949,
"text": "Angular maintains documentation and guides of all version. For example, Angular documentation for version 7 can be checked @ https://v7.angular.io. Angular also provides a detailed upgrade path through https://update.angular.io/ site."
},
{
"code": null,
"e": 3293,
"s": 3184,
"text": "To update Angular application written from previous version, use below command inside the project directory:"
},
{
"code": null,
"e": 3335,
"s": 3293,
"text": "ng update @angular/cli@8 @angular/core@8\n"
},
{
"code": null,
"e": 3401,
"s": 3335,
"text": "Let us see some of the important changes introduced in Angular 8."
},
{
"code": null,
"e": 3516,
"s": 3401,
"text": "HttpModule module and its associated Http service is removed. Use HttpClient service from HttpClientModule module."
},
{
"code": null,
"e": 3631,
"s": 3516,
"text": "HttpModule module and its associated Http service is removed. Use HttpClient service from HttpClientModule module."
},
{
"code": null,
"e": 3689,
"s": 3631,
"text": "/deep/, >>> and :ng-deep component selectors are removed."
},
{
"code": null,
"e": 3747,
"s": 3689,
"text": "/deep/, >>> and :ng-deep component selectors are removed."
},
{
"code": null,
"e": 3793,
"s": 3747,
"text": "Angular default version of TypeScript is 3.4."
},
{
"code": null,
"e": 3839,
"s": 3793,
"text": "Angular default version of TypeScript is 3.4."
},
{
"code": null,
"e": 3891,
"s": 3839,
"text": "Node version supported by Angular is v10 and later."
},
{
"code": null,
"e": 3943,
"s": 3891,
"text": "Node version supported by Angular is v10 and later."
},
{
"code": null,
"e": 4029,
"s": 3943,
"text": "@ViewChild() and ContentChild() decorator behaviour is changed from dynaic to static."
},
{
"code": null,
"e": 4115,
"s": 4029,
"text": "@ViewChild() and ContentChild() decorator behaviour is changed from dynaic to static."
},
{
"code": null,
"e": 4208,
"s": 4115,
"text": "Lazy loading string syntax in router module is removed and only function based is supported."
},
{
"code": null,
"e": 4305,
"s": 4208,
"text": "loadChildren: './lazy/lazy.module#LazyModule' \nloadChildren: () => import('./lazy/lazy.module' \n"
},
{
"code": null,
"e": 4340,
"s": 4305,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4354,
"s": 4340,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4389,
"s": 4354,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4403,
"s": 4389,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4438,
"s": 4403,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4458,
"s": 4438,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 4493,
"s": 4458,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4510,
"s": 4493,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4543,
"s": 4510,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4555,
"s": 4543,
"text": " Senol Atac"
},
{
"code": null,
"e": 4590,
"s": 4555,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4602,
"s": 4590,
"text": " Senol Atac"
},
{
"code": null,
"e": 4609,
"s": 4602,
"text": " Print"
},
{
"code": null,
"e": 4620,
"s": 4609,
"text": " Add Notes"
}
]
|
Set up a standalone HBase local instance and connect to it with Python Happybase | by Andrea Guidi | Towards Data Science | Recently, in my starting adventure as a Data Science consultant, I was involved in a project where the database we are taking the data from is the famous Apache HBase.
HBase is a distributed, Hadoop non-relational database which is really powerful at handling massive amounts of data.
In the HBase data model, rows are identified by a row key which serves more or less an equivalent of the relational Primary Key and they are sorted by row key.
Columns are grouped in the so-called Column Families which are physical and logical grouping of columns, and the columns in one family are stored separately from the columns in another family so that queries can be performed only on the data you need.
You can read more about HBase here.
The reason why I decided to install an HBase local instance is that I must live with an endless curiosity and I love experimenting.
The first thing I did was to create a Linux Virtual Machine with Alpine Linux, mounted on VMWare. Once the VM was running, I logged into the installer by typing:
localhost login: rootsetup-alpine
I followed the shell instructions and finally, I rebooted the system. I needed Java support in order for HBase to work, so I installed openjdk8:
apk add openjdk8-jre
After that, I created a couple of folders inside /home, just for comfort:
cd homemkdir downloadsmkdir andreacd downloads
So now I am inside /home/downloads and I can download the HBase compressed folder, uncompress it and change directory:
wget https://www.apache.org/dyn/closer.lua/hbase/2.2.3/hbase-2.2.3-bin.tar.gztar xzvf hbase-2.2.3-bin.tar.gzcd hbase-2.2.3
Inside of this folder, there are two important folders: bin and conf.
I went inside conf:
And then modified the JAVA_HOME environment variable inside hbase_env.sh to /usr/lib/jvm/openjdk8-jre (folders might differ):
export JAVA_HOME=/usr/lib/jvm/openjdk8-jre
Also, I overwrote the content of the file hbase-site.xml with what reported here in Example 1 for Standalone HBase.
Then, I navigated up one folder back to Hbase main folder and changed to bin directory:
To check that HBase is working:
./start-hbase.sh./hbase shell
Et voilà!
To see the tables, type list:
Of course, there are no tables, but we can create one with the following convention:
create 'table_name','columnFamily1',...,'columnFamilyN'
In Shell:
And now let’s add two rows:
To retrieve the table, let’s run a Scan:
Now, the table is there and we can connect to it using Python package Happybase, built using Python Thrift.
First, stop the HBase instance and install Python 3 and Happybase package:
apk add python3pip install happybase
Then, start Thrift server:
And HBase again:
Now we open an Interactive Python session and make a connection to HBase to see that everything is working fine using Happybase APIs:
Thanks for reading, and reach me out for anything! | [
{
"code": null,
"e": 339,
"s": 171,
"text": "Recently, in my starting adventure as a Data Science consultant, I was involved in a project where the database we are taking the data from is the famous Apache HBase."
},
{
"code": null,
"e": 456,
"s": 339,
"text": "HBase is a distributed, Hadoop non-relational database which is really powerful at handling massive amounts of data."
},
{
"code": null,
"e": 616,
"s": 456,
"text": "In the HBase data model, rows are identified by a row key which serves more or less an equivalent of the relational Primary Key and they are sorted by row key."
},
{
"code": null,
"e": 868,
"s": 616,
"text": "Columns are grouped in the so-called Column Families which are physical and logical grouping of columns, and the columns in one family are stored separately from the columns in another family so that queries can be performed only on the data you need."
},
{
"code": null,
"e": 904,
"s": 868,
"text": "You can read more about HBase here."
},
{
"code": null,
"e": 1036,
"s": 904,
"text": "The reason why I decided to install an HBase local instance is that I must live with an endless curiosity and I love experimenting."
},
{
"code": null,
"e": 1198,
"s": 1036,
"text": "The first thing I did was to create a Linux Virtual Machine with Alpine Linux, mounted on VMWare. Once the VM was running, I logged into the installer by typing:"
},
{
"code": null,
"e": 1232,
"s": 1198,
"text": "localhost login: rootsetup-alpine"
},
{
"code": null,
"e": 1377,
"s": 1232,
"text": "I followed the shell instructions and finally, I rebooted the system. I needed Java support in order for HBase to work, so I installed openjdk8:"
},
{
"code": null,
"e": 1398,
"s": 1377,
"text": "apk add openjdk8-jre"
},
{
"code": null,
"e": 1472,
"s": 1398,
"text": "After that, I created a couple of folders inside /home, just for comfort:"
},
{
"code": null,
"e": 1519,
"s": 1472,
"text": "cd homemkdir downloadsmkdir andreacd downloads"
},
{
"code": null,
"e": 1638,
"s": 1519,
"text": "So now I am inside /home/downloads and I can download the HBase compressed folder, uncompress it and change directory:"
},
{
"code": null,
"e": 1761,
"s": 1638,
"text": "wget https://www.apache.org/dyn/closer.lua/hbase/2.2.3/hbase-2.2.3-bin.tar.gztar xzvf hbase-2.2.3-bin.tar.gzcd hbase-2.2.3"
},
{
"code": null,
"e": 1831,
"s": 1761,
"text": "Inside of this folder, there are two important folders: bin and conf."
},
{
"code": null,
"e": 1851,
"s": 1831,
"text": "I went inside conf:"
},
{
"code": null,
"e": 1977,
"s": 1851,
"text": "And then modified the JAVA_HOME environment variable inside hbase_env.sh to /usr/lib/jvm/openjdk8-jre (folders might differ):"
},
{
"code": null,
"e": 2020,
"s": 1977,
"text": "export JAVA_HOME=/usr/lib/jvm/openjdk8-jre"
},
{
"code": null,
"e": 2136,
"s": 2020,
"text": "Also, I overwrote the content of the file hbase-site.xml with what reported here in Example 1 for Standalone HBase."
},
{
"code": null,
"e": 2224,
"s": 2136,
"text": "Then, I navigated up one folder back to Hbase main folder and changed to bin directory:"
},
{
"code": null,
"e": 2256,
"s": 2224,
"text": "To check that HBase is working:"
},
{
"code": null,
"e": 2286,
"s": 2256,
"text": "./start-hbase.sh./hbase shell"
},
{
"code": null,
"e": 2297,
"s": 2286,
"text": "Et voilà!"
},
{
"code": null,
"e": 2327,
"s": 2297,
"text": "To see the tables, type list:"
},
{
"code": null,
"e": 2412,
"s": 2327,
"text": "Of course, there are no tables, but we can create one with the following convention:"
},
{
"code": null,
"e": 2468,
"s": 2412,
"text": "create 'table_name','columnFamily1',...,'columnFamilyN'"
},
{
"code": null,
"e": 2478,
"s": 2468,
"text": "In Shell:"
},
{
"code": null,
"e": 2506,
"s": 2478,
"text": "And now let’s add two rows:"
},
{
"code": null,
"e": 2547,
"s": 2506,
"text": "To retrieve the table, let’s run a Scan:"
},
{
"code": null,
"e": 2655,
"s": 2547,
"text": "Now, the table is there and we can connect to it using Python package Happybase, built using Python Thrift."
},
{
"code": null,
"e": 2730,
"s": 2655,
"text": "First, stop the HBase instance and install Python 3 and Happybase package:"
},
{
"code": null,
"e": 2767,
"s": 2730,
"text": "apk add python3pip install happybase"
},
{
"code": null,
"e": 2794,
"s": 2767,
"text": "Then, start Thrift server:"
},
{
"code": null,
"e": 2811,
"s": 2794,
"text": "And HBase again:"
},
{
"code": null,
"e": 2945,
"s": 2811,
"text": "Now we open an Interactive Python session and make a connection to HBase to see that everything is working fine using Happybase APIs:"
}
]
|
Java Program to Find the Cube Root of a Given Number Using Binary Search - GeeksforGeeks | 03 Mar, 2021
Given a non-negative number find the cube root of a number using the binary search approach.
Examples :
Input: x = 27
Output: 3
Explanation: The cube root of 16 is 4.
Input: x = 120
Output: 4
Explanation: The cube root of 120 lies in between
4 and 5 so floor of the cube root is 4.
Naive Approach:
Check the cube of every element till n and store the answer till the cube is smaller or equal to the n
Java
// Java Program to Find the cube root// of given number using Naive approachimport java.io.*;class GFG { static int cuberoot(int n) { int ans = 0; for (int i = 1; i <= n; ++i) { // checking every number cube if (i * i * i <= n) { ans = i; } } return ans; } public static void main(String[] args) { // Number int number = 27; // Checking number int cuberoot = cuberoot(number); System.out.println(cuberoot); }}
3
Complexity:
SpaceComplexity: O(1)
TimeComplexity: O(n)
Efficient Approach (Binary Search):
Binary Search used Divide and Conquer approach that makes the complexity is O(log n).
Algorithm:
Initialize left=0 and right =n
Calculate mid=left+(right-left)/2
If mid*mid*mid is equal to the number return the mid
If mid*mid*mid is less than the number store the mid in ans and increase left=mid+1
If mid*mid*mid is more than the number and decrease the right=mid-1
Return the answer
Implementation:
Java
// Java Program to Find the cube root// of given number using Binary Searchimport java.io.*;import java.util.*;class GFG { // Function to find cuberoot static int cuberoot(int number) { // Lower bound int left = 1; // Upper bound int right = number; int ans = 0; while (left <= right) { // Finding the mid value int mid = left + (right - left) / 2; // Checking the mid value if (mid * mid * mid == number) { return mid; } // Shift the lower bound if (mid * mid * mid < number) { left = mid + 1; ans = mid; } // Shift the upper bound else { right = mid - 1; } } // Return the ans return ans; } public static void main(String[] args) { int number = 215; System.out.println(cuberoot(number)); }}
5
Complexity:
SpaceComplexity: O(1)
TimeComplexity: O(log n)
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 25318,
"s": 25225,
"text": "Given a non-negative number find the cube root of a number using the binary search approach."
},
{
"code": null,
"e": 25329,
"s": 25318,
"text": "Examples :"
},
{
"code": null,
"e": 25510,
"s": 25329,
"text": "Input: x = 27\nOutput: 3\nExplanation: The cube root of 16 is 4.\n\nInput: x = 120\nOutput: 4\nExplanation: The cube root of 120 lies in between\n4 and 5 so floor of the cube root is 4."
},
{
"code": null,
"e": 25526,
"s": 25510,
"text": "Naive Approach:"
},
{
"code": null,
"e": 25629,
"s": 25526,
"text": "Check the cube of every element till n and store the answer till the cube is smaller or equal to the n"
},
{
"code": null,
"e": 25634,
"s": 25629,
"text": "Java"
},
{
"code": "// Java Program to Find the cube root// of given number using Naive approachimport java.io.*;class GFG { static int cuberoot(int n) { int ans = 0; for (int i = 1; i <= n; ++i) { // checking every number cube if (i * i * i <= n) { ans = i; } } return ans; } public static void main(String[] args) { // Number int number = 27; // Checking number int cuberoot = cuberoot(number); System.out.println(cuberoot); }}",
"e": 26175,
"s": 25634,
"text": null
},
{
"code": null,
"e": 26178,
"s": 26175,
"text": "3\n"
},
{
"code": null,
"e": 26190,
"s": 26178,
"text": "Complexity:"
},
{
"code": null,
"e": 26233,
"s": 26190,
"text": "SpaceComplexity: O(1)\nTimeComplexity: O(n)"
},
{
"code": null,
"e": 26270,
"s": 26233,
"text": "Efficient Approach (Binary Search): "
},
{
"code": null,
"e": 26356,
"s": 26270,
"text": "Binary Search used Divide and Conquer approach that makes the complexity is O(log n)."
},
{
"code": null,
"e": 26367,
"s": 26356,
"text": "Algorithm:"
},
{
"code": null,
"e": 26398,
"s": 26367,
"text": "Initialize left=0 and right =n"
},
{
"code": null,
"e": 26432,
"s": 26398,
"text": "Calculate mid=left+(right-left)/2"
},
{
"code": null,
"e": 26486,
"s": 26432,
"text": "If mid*mid*mid is equal to the number return the mid"
},
{
"code": null,
"e": 26570,
"s": 26486,
"text": "If mid*mid*mid is less than the number store the mid in ans and increase left=mid+1"
},
{
"code": null,
"e": 26638,
"s": 26570,
"text": "If mid*mid*mid is more than the number and decrease the right=mid-1"
},
{
"code": null,
"e": 26656,
"s": 26638,
"text": "Return the answer"
},
{
"code": null,
"e": 26672,
"s": 26656,
"text": "Implementation:"
},
{
"code": null,
"e": 26677,
"s": 26672,
"text": "Java"
},
{
"code": "// Java Program to Find the cube root// of given number using Binary Searchimport java.io.*;import java.util.*;class GFG { // Function to find cuberoot static int cuberoot(int number) { // Lower bound int left = 1; // Upper bound int right = number; int ans = 0; while (left <= right) { // Finding the mid value int mid = left + (right - left) / 2; // Checking the mid value if (mid * mid * mid == number) { return mid; } // Shift the lower bound if (mid * mid * mid < number) { left = mid + 1; ans = mid; } // Shift the upper bound else { right = mid - 1; } } // Return the ans return ans; } public static void main(String[] args) { int number = 215; System.out.println(cuberoot(number)); }}",
"e": 27655,
"s": 26677,
"text": null
},
{
"code": null,
"e": 27658,
"s": 27655,
"text": "5\n"
},
{
"code": null,
"e": 27670,
"s": 27658,
"text": "Complexity:"
},
{
"code": null,
"e": 27717,
"s": 27670,
"text": "SpaceComplexity: O(1)\nTimeComplexity: O(log n)"
},
{
"code": null,
"e": 27724,
"s": 27717,
"text": "Picked"
},
{
"code": null,
"e": 27748,
"s": 27724,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27753,
"s": 27748,
"text": "Java"
},
{
"code": null,
"e": 27767,
"s": 27753,
"text": "Java Programs"
},
{
"code": null,
"e": 27786,
"s": 27767,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27791,
"s": 27786,
"text": "Java"
},
{
"code": null,
"e": 27889,
"s": 27791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27904,
"s": 27889,
"text": "Stream In Java"
},
{
"code": null,
"e": 27925,
"s": 27904,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27944,
"s": 27925,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27974,
"s": 27944,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28020,
"s": 27974,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28046,
"s": 28020,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28080,
"s": 28046,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28127,
"s": 28080,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 28159,
"s": 28127,
"text": "How to Iterate HashMap in Java?"
}
]
|
Implode an array with jQuery/JavaScript - GeeksforGeeks | 31 May, 2019
Given an array of elements and the task is to implode (join the elements of an array) the array elements.
Method 1: Using join() method: The join() method can be used to join an array with a separator and return it as a string. The join() method takes in the optional parameter of a separator. The separator is assumed to be a comma, if not specified. If the array contains only one string, then it would be returned without the separator.
Syntax:
array.join(separator)
Example:
<!DOCTYPE html><html> <head> <title> Implode an array with jQuery/Javascript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Implode an array with jQuery/Javascript? </b> <p> Original array is ["One", "Two", "Three", "Four", "Five"] </p> <p> Imploded array is: <span class="output"></span> </p> <button onclick="implodeArray()"> Implode Array </button> <script type="text/javascript"> function implodeArray() { originalArray = ["One", "Two", "Three", "Four", "Five"]; separator = ' '; implodedArray = originalArray.join(separator); console.log(implodedArray); document.querySelector('.output').textContent = implodedArray; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Console Output:
Method 2: Iterating through the array and create a new string with all the strings and concatenated separators: The implode function can be created by looping through the array and concatenating it to one base string. The separator is added after concatenating each string unless it is the last string in the array. This prevents from adding the separator to the end of the last string in the array.This method is slower than the join() method as a large number of strings are temporarily created during the concatenation of the base string.
Example:
<!DOCTYPE html><html> <head> <title> Implode an array with jQuery/Javascript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Implode an array with jQuery/Javascript? </b> <p> Original array is ["One", "Two", "Three", "Four", "Five"] </p> <p> Imploded array is: <span class="output"></span> </p> <button onclick="implodeArray()"> Implode Array </button> <script type="text/javascript"> function implodeArray() { originalArray = ["One", "Two", "Three", "Four", "Five"]; separator = '+'; implodedArray = ''; for(let i = 0; i < originalArray.length; i++) { // add a string from original array implodedArray += originalArray[i]; // unless the iterator reaches the end of // the array add the separator string if(i != originalArray.length - 1){ implodedArray += separator; } } console.log(implodedArray); document.querySelector('.output').textContent = implodedArray; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Console Output:
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 25901,
"s": 25873,
"text": "\n31 May, 2019"
},
{
"code": null,
"e": 26007,
"s": 25901,
"text": "Given an array of elements and the task is to implode (join the elements of an array) the array elements."
},
{
"code": null,
"e": 26341,
"s": 26007,
"text": "Method 1: Using join() method: The join() method can be used to join an array with a separator and return it as a string. The join() method takes in the optional parameter of a separator. The separator is assumed to be a comma, if not specified. If the array contains only one string, then it would be returned without the separator."
},
{
"code": null,
"e": 26349,
"s": 26341,
"text": "Syntax:"
},
{
"code": null,
"e": 26371,
"s": 26349,
"text": "array.join(separator)"
},
{
"code": null,
"e": 26380,
"s": 26371,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Implode an array with jQuery/Javascript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Implode an array with jQuery/Javascript? </b> <p> Original array is [\"One\", \"Two\", \"Three\", \"Four\", \"Five\"] </p> <p> Imploded array is: <span class=\"output\"></span> </p> <button onclick=\"implodeArray()\"> Implode Array </button> <script type=\"text/javascript\"> function implodeArray() { originalArray = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\"]; separator = ' '; implodedArray = originalArray.join(separator); console.log(implodedArray); document.querySelector('.output').textContent = implodedArray; } </script></body> </html> ",
"e": 27330,
"s": 26380,
"text": null
},
{
"code": null,
"e": 27338,
"s": 27330,
"text": "Output:"
},
{
"code": null,
"e": 27366,
"s": 27338,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 27393,
"s": 27366,
"text": "After clicking the button:"
},
{
"code": null,
"e": 27409,
"s": 27393,
"text": "Console Output:"
},
{
"code": null,
"e": 27951,
"s": 27409,
"text": "Method 2: Iterating through the array and create a new string with all the strings and concatenated separators: The implode function can be created by looping through the array and concatenating it to one base string. The separator is added after concatenating each string unless it is the last string in the array. This prevents from adding the separator to the end of the last string in the array.This method is slower than the join() method as a large number of strings are temporarily created during the concatenation of the base string."
},
{
"code": null,
"e": 27960,
"s": 27951,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Implode an array with jQuery/Javascript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Implode an array with jQuery/Javascript? </b> <p> Original array is [\"One\", \"Two\", \"Three\", \"Four\", \"Five\"] </p> <p> Imploded array is: <span class=\"output\"></span> </p> <button onclick=\"implodeArray()\"> Implode Array </button> <script type=\"text/javascript\"> function implodeArray() { originalArray = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\"]; separator = '+'; implodedArray = ''; for(let i = 0; i < originalArray.length; i++) { // add a string from original array implodedArray += originalArray[i]; // unless the iterator reaches the end of // the array add the separator string if(i != originalArray.length - 1){ implodedArray += separator; } } console.log(implodedArray); document.querySelector('.output').textContent = implodedArray; } </script></body> </html> ",
"e": 29288,
"s": 27960,
"text": null
},
{
"code": null,
"e": 29296,
"s": 29288,
"text": "Output:"
},
{
"code": null,
"e": 29324,
"s": 29296,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 29351,
"s": 29324,
"text": "After clicking the button:"
},
{
"code": null,
"e": 29367,
"s": 29351,
"text": "Console Output:"
},
{
"code": null,
"e": 29374,
"s": 29367,
"text": "Picked"
},
{
"code": null,
"e": 29385,
"s": 29374,
"text": "JavaScript"
},
{
"code": null,
"e": 29402,
"s": 29385,
"text": "Web Technologies"
},
{
"code": null,
"e": 29429,
"s": 29402,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29527,
"s": 29429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29567,
"s": 29527,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29612,
"s": 29567,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29673,
"s": 29612,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29745,
"s": 29673,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29797,
"s": 29745,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29837,
"s": 29797,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29870,
"s": 29837,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29915,
"s": 29870,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29958,
"s": 29915,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Prototype in JavaScript - GeeksforGeeks | 10 Aug, 2021
JavaScript is a prototype based language, so, whenever we create a function using JavaScript, JavaScript engine adds a prototype property inside a function, Prototype property is basically an object (also known as Prototype object), where we can attach methods and properties in a prototype object, which enables all the other objects to inherit these methods and properties.
Consider the example below:-
There are different ways to create an object, one of the way is to create an object using function constructor.
<script>// function constructorfunction Person(name, job, yearOfBirth){ this.name= name; this.job= job; this.yearOfBirth= yearOfBirth;}// this will show Person's prototype property.console.log(Person.prototype);</script>
Output:-
In above image, you can see Person has a prototype property and that prototype property has a constructor object which again points to the Person constructor function.
When we create an object using the above function constructor, JavaScript Engine will add dunder proto or __proto__ in the object which will point to the prototype’s constructor object.
Now, we will add a method calculateAge() to the Prototype property in a Person function constructor which will inherit by the different objects. Below is the code for this:-
<script>// function constructorfunction Person(name, job, yearOfBirth){ this.name= name; this.job= job; this.yearOfBirth= yearOfBirth;}Person.prototype.calculateAge= function(){ console.log('The current age is: '+(2019- this.yearOfBirth));}console.log(Person.prototype);</script>
Output:-
In above image, we can see calculateAge() method gets added to the Prototype property. Now, we will create 2 different objects which will inherit calculateAge() method and remember, When a certain method(or property) is called, it first checks inside the object but when it doesn’t find, then search moves on Object’s prototype.
<script> // function constructorfunction Person(name, job, yearOfBirth){ this.name= name; this.job= job; this.yearOfBirth= yearOfBirth;}// adding calculateAge() method to the Prototype propertyPerson.prototype.calculateAge= function(){ console.log('The current age is: '+(2019- this.yearOfBirth));}console.log(Person.prototype); // creating Object Person1let Person1= new Person('Jenni', 'clerk', 1986); console.log(Person1)let Person2= new Person('Madhu', 'Developer', 1997);console.log(Person2) Person1.calculateAge();Person2.calculateAge(); </script>
Output:-
Here, we created two Objects Person1 and Person2 using constructor function Person, when we called Person1.calculateAge() and Person2.calculateAge(), First it will check whether it is present inside Person1 and Person2 object, if it is not present, it will move Person’s Prototype object and prints the current age, which shows Prototype property enables other objects to inherit all the properties and methods of function constructor.
javascript-object
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25692,
"s": 25664,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 26068,
"s": 25692,
"text": "JavaScript is a prototype based language, so, whenever we create a function using JavaScript, JavaScript engine adds a prototype property inside a function, Prototype property is basically an object (also known as Prototype object), where we can attach methods and properties in a prototype object, which enables all the other objects to inherit these methods and properties."
},
{
"code": null,
"e": 26097,
"s": 26068,
"text": "Consider the example below:-"
},
{
"code": null,
"e": 26209,
"s": 26097,
"text": "There are different ways to create an object, one of the way is to create an object using function constructor."
},
{
"code": "<script>// function constructorfunction Person(name, job, yearOfBirth){ this.name= name; this.job= job; this.yearOfBirth= yearOfBirth;}// this will show Person's prototype property.console.log(Person.prototype);</script> ",
"e": 26443,
"s": 26209,
"text": null
},
{
"code": null,
"e": 26452,
"s": 26443,
"text": "Output:-"
},
{
"code": null,
"e": 26620,
"s": 26452,
"text": "In above image, you can see Person has a prototype property and that prototype property has a constructor object which again points to the Person constructor function."
},
{
"code": null,
"e": 26806,
"s": 26620,
"text": "When we create an object using the above function constructor, JavaScript Engine will add dunder proto or __proto__ in the object which will point to the prototype’s constructor object."
},
{
"code": null,
"e": 26980,
"s": 26806,
"text": "Now, we will add a method calculateAge() to the Prototype property in a Person function constructor which will inherit by the different objects. Below is the code for this:-"
},
{
"code": "<script>// function constructorfunction Person(name, job, yearOfBirth){ this.name= name; this.job= job; this.yearOfBirth= yearOfBirth;}Person.prototype.calculateAge= function(){ console.log('The current age is: '+(2019- this.yearOfBirth));}console.log(Person.prototype);</script>",
"e": 27275,
"s": 26980,
"text": null
},
{
"code": null,
"e": 27284,
"s": 27275,
"text": "Output:-"
},
{
"code": null,
"e": 27613,
"s": 27284,
"text": "In above image, we can see calculateAge() method gets added to the Prototype property. Now, we will create 2 different objects which will inherit calculateAge() method and remember, When a certain method(or property) is called, it first checks inside the object but when it doesn’t find, then search moves on Object’s prototype."
},
{
"code": "<script> // function constructorfunction Person(name, job, yearOfBirth){ this.name= name; this.job= job; this.yearOfBirth= yearOfBirth;}// adding calculateAge() method to the Prototype propertyPerson.prototype.calculateAge= function(){ console.log('The current age is: '+(2019- this.yearOfBirth));}console.log(Person.prototype); // creating Object Person1let Person1= new Person('Jenni', 'clerk', 1986); console.log(Person1)let Person2= new Person('Madhu', 'Developer', 1997);console.log(Person2) Person1.calculateAge();Person2.calculateAge(); </script>",
"e": 28187,
"s": 27613,
"text": null
},
{
"code": null,
"e": 28196,
"s": 28187,
"text": "Output:-"
},
{
"code": null,
"e": 28632,
"s": 28196,
"text": "Here, we created two Objects Person1 and Person2 using constructor function Person, when we called Person1.calculateAge() and Person2.calculateAge(), First it will check whether it is present inside Person1 and Person2 object, if it is not present, it will move Person’s Prototype object and prints the current age, which shows Prototype property enables other objects to inherit all the properties and methods of function constructor."
},
{
"code": null,
"e": 28650,
"s": 28632,
"text": "javascript-object"
},
{
"code": null,
"e": 28661,
"s": 28650,
"text": "JavaScript"
},
{
"code": null,
"e": 28678,
"s": 28661,
"text": "Web Technologies"
},
{
"code": null,
"e": 28776,
"s": 28678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28816,
"s": 28776,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28861,
"s": 28816,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28922,
"s": 28861,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28994,
"s": 28922,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29040,
"s": 28994,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29080,
"s": 29040,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29113,
"s": 29080,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29158,
"s": 29113,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29201,
"s": 29158,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Using mkvirtualenv to create new Virtual Environment - Python - GeeksforGeeks | 08 Jun, 2020
Virtual Environment are used If you already have a python version installed and you want to use a different version for a project without bothering the older ones. it is good practice to use a new virtual environment for different projects.
There are multiple ways of creating that, today we will create one using mkvirtualenv command.
virtualenvwrapper
To use the mkvirtualenv command you need to have virtualenvwrapper installed which is nothing but a set of python extension commands.
Make sure you have pip installed.
$ sudo apt-get install python3-pip
Installing virtualenvwrapper
$ sudo pip3 install virtualenvwrapper
Open bashrc by –
$ sudo gedit ~/.bashrc
After opening it, add the following lines to it :
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
Save the bashrc file.
Using mkvirtualenv command
Now let us use it,
The syntax is :
$ mkvirtualenv venv_name
If you want to work on another version of python, try this :
$ mkvirtualenv -p python3.x venv_name
$(venv_name) // You will see something like this
Note: You can use any version in place of x.
To work on an existing virtual environment,
$ workon venv_name
To get out of the virtual environment –
$(venv_name) deactivate
To see the list of your virtual environments are, go to-
Home/.virtualenvs
python-utility
Linux-Unix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
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": 25833,
"s": 25805,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 26074,
"s": 25833,
"text": "Virtual Environment are used If you already have a python version installed and you want to use a different version for a project without bothering the older ones. it is good practice to use a new virtual environment for different projects."
},
{
"code": null,
"e": 26170,
"s": 26074,
"text": "There are multiple ways of creating that, today we will create one using mkvirtualenv command."
},
{
"code": null,
"e": 26188,
"s": 26170,
"text": "virtualenvwrapper"
},
{
"code": null,
"e": 26323,
"s": 26188,
"text": "To use the mkvirtualenv command you need to have virtualenvwrapper installed which is nothing but a set of python extension commands."
},
{
"code": null,
"e": 26357,
"s": 26323,
"text": "Make sure you have pip installed."
},
{
"code": null,
"e": 26393,
"s": 26357,
"text": "$ sudo apt-get install python3-pip\n"
},
{
"code": null,
"e": 26423,
"s": 26393,
"text": "Installing virtualenvwrapper "
},
{
"code": null,
"e": 26462,
"s": 26423,
"text": "$ sudo pip3 install virtualenvwrapper\n"
},
{
"code": null,
"e": 26479,
"s": 26462,
"text": "Open bashrc by –"
},
{
"code": null,
"e": 26503,
"s": 26479,
"text": "$ sudo gedit ~/.bashrc\n"
},
{
"code": null,
"e": 26554,
"s": 26503,
"text": "After opening it, add the following lines to it :"
},
{
"code": null,
"e": 26668,
"s": 26554,
"text": "export WORKON_HOME=$HOME/.virtualenvs\nexport PROJECT_HOME=$HOME/Devel\nsource /usr/local/bin/virtualenvwrapper.sh\n"
},
{
"code": null,
"e": 26690,
"s": 26668,
"text": "Save the bashrc file."
},
{
"code": null,
"e": 26717,
"s": 26690,
"text": "Using mkvirtualenv command"
},
{
"code": null,
"e": 26736,
"s": 26717,
"text": "Now let us use it,"
},
{
"code": null,
"e": 26752,
"s": 26736,
"text": "The syntax is :"
},
{
"code": null,
"e": 26778,
"s": 26752,
"text": "$ mkvirtualenv venv_name\n"
},
{
"code": null,
"e": 26839,
"s": 26778,
"text": "If you want to work on another version of python, try this :"
},
{
"code": null,
"e": 26927,
"s": 26839,
"text": "$ mkvirtualenv -p python3.x venv_name\n$(venv_name) // You will see something like this\n"
},
{
"code": null,
"e": 26973,
"s": 26927,
"text": "Note: You can use any version in place of x. "
},
{
"code": null,
"e": 27017,
"s": 26973,
"text": "To work on an existing virtual environment,"
},
{
"code": null,
"e": 27037,
"s": 27017,
"text": "$ workon venv_name\n"
},
{
"code": null,
"e": 27077,
"s": 27037,
"text": "To get out of the virtual environment –"
},
{
"code": null,
"e": 27102,
"s": 27077,
"text": "$(venv_name) deactivate\n"
},
{
"code": null,
"e": 27159,
"s": 27102,
"text": "To see the list of your virtual environments are, go to-"
},
{
"code": null,
"e": 27177,
"s": 27159,
"text": "Home/.virtualenvs"
},
{
"code": null,
"e": 27192,
"s": 27177,
"text": "python-utility"
},
{
"code": null,
"e": 27203,
"s": 27192,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27210,
"s": 27203,
"text": "Python"
},
{
"code": null,
"e": 27308,
"s": 27210,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27343,
"s": 27308,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 27381,
"s": 27343,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27422,
"s": 27381,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 27457,
"s": 27422,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27493,
"s": 27457,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27521,
"s": 27493,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27571,
"s": 27521,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27593,
"s": 27571,
"text": "Python map() function"
}
]
|
Right rotate given Array K times using Pointers - GeeksforGeeks | 19 Jan, 2022
Given an array arr[] of size N and an integer K, the task is to right rotate the array K times.
Examples:
Input: arr[] = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5Explanation: After 1st rotation – {9, 1, 3, 5, 7}After 2nd rotation – {7, 9, 1, 3, 5}
Input: {1, 2, 3, 4, 5, 6}, K = 2Output: 5 6 1 2 3 4
Approach: The naive approach and approach based on reversing parts of the array is discussed here.
Pointer based approach: The base of this concept is the reversal algorithm for array rotation. The array is divided into two parts where the first part is of size (N-K) and the end part is of size K. These two parts are individually reversed. Then the whole array is reversed.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to implement above approach#include <iostream>using namespace std; // Function to print the arrayvoid print(int arr[], int N){ for (int i = 0; i < N; i++) cout << *(arr + i) << " ";} // Function to reverse the array// from start to end indexvoid reverse(int arr[], int start, int end){ int temp; int size = end - start; // Reversal based on pointer approach for (int i = 0; i < (size / 2); i++) { temp = *(arr + i + start); *(arr + i + start) = *(arr + start + size - i - 1); *(arr + start + size - i - 1) = temp; }} // Function to right rotate the array K timesvoid right(int arr[], int K, int N){ reverse(arr, 0, N - K); reverse(arr, N - K, N); reverse(arr, 0, N); print(arr, N);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; right(arr, K, N); return 0;}
// Java code to implement above approachimport java.util.*; class GFG{ // Function to print the arraystatic void print(int arr[], int N){ for (int i = 0; i < N; i++) System.out.print(arr[i]+ " ");} // Function to reverse the array// from start to end indexstatic int[] reverse(int arr[], int start, int end){ int temp; int size = end - start; // Reversal based on pointer approach for (int i = 0; i < (size / 2); i++) { temp = arr[ i + start]; arr[i + start] = arr[start + size - i - 1]; arr[start + size - i - 1] = temp; } return arr;} // Function to right rotate the array K timesstatic void right(int arr[], int K, int N){ arr = reverse(arr, 0, N - K); arr = reverse(arr, N - K, N); arr = reverse(arr, 0, N); print(arr, N);} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int N = arr.length; int K = 2; right(arr, K, N);}} // This code is contributed by 29AjayKumar
# Python code to implement above approach # Function to print arraydef print1(arr, N): for i in range(N): print(arr[i], end = " "); # Function to reverse the array# from start to end indexdef reverse(arr, start, end): temp = 0; size = end - start; # Reversal based on pointer approach for i in range(size//2): temp = arr[i + start]; arr[i + start] = arr[start + size - i - 1]; arr[start + size - i - 1] = temp; return arr; # Function to right rotate the array K timesdef right(arr, K, N): arr = reverse(arr, 0, N - K); arr = reverse(arr, N - K, N); arr = reverse(arr, 0, N); print1(arr, N); # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6]; N = len(arr); K = 2; right(arr, K, N); # This code is contributed by 29AjayKumar
// C# code to implement above approachusing System;class GFG { // Function to print the array static void print(int[] arr, int N) { for (int i = 0; i < N; i++) Console.Write(arr[i] + " "); } // Function to reverse the array // from start to end index static void reverse(int[] arr, int start, int end) { int temp; int size = end - start; // Reversal based on pointer approach for (int i = 0; i < (size / 2); i++) { temp = arr[i + start]; arr[i + start] = arr[start + size - i - 1]; arr[start + size - i - 1] = temp; } } // Function to right rotate the array K times static void right(int[] arr, int K, int N) { reverse(arr, 0, N - K); reverse(arr, N - K, N); reverse(arr, 0, N); print(arr, N); } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6 }; int N = arr.Length; int K = 2; right(arr, K, N); }} // This code is contributed by ukasp.
<script> // JavaScript code to implement above approach // Function to print the array const print = (arr, N) => { for (let i = 0; i < N; i++) document.write(`${arr[i]} `); } // Function to reverse the array // from start to end index const reverse = (arr, start, end) => { let temp; let size = end - start; // Reversal based on pointer approach for (let i = 0; i < parseInt(size / 2); i++) { temp = arr[i + start]; arr[i + start] = arr[start + size - i - 1]; arr[start + size - i - 1] = temp; } } // Function to right rotate the array K times const right = (arr, K, N) => { reverse(arr, 0, N - K); reverse(arr, N - K, N); reverse(arr, 0, N); print(arr, N); } // Driver code let arr = [1, 2, 3, 4, 5, 6]; let N = arr.length; let K = 2; right(arr, K, N); // This code is contributed by rakeshsahni </script>
5 6 1 2 3 4
Time Complexity: O(N)Auxiliary Space: O(1)
rakeshsahni
ukasp
29AjayKumar
khushboogoyal499
Pointers
rotation
Arrays
Arrays
Pointers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Remove duplicates from sorted array
Move all negative numbers to beginning and positive to end with constant extra space
Merge Overlapping Intervals | [
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 26137,
"s": 26041,
"text": "Given an array arr[] of size N and an integer K, the task is to right rotate the array K times."
},
{
"code": null,
"e": 26148,
"s": 26137,
"text": "Examples: "
},
{
"code": null,
"e": 26288,
"s": 26148,
"text": "Input: arr[] = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5Explanation: After 1st rotation – {9, 1, 3, 5, 7}After 2nd rotation – {7, 9, 1, 3, 5}"
},
{
"code": null,
"e": 26340,
"s": 26288,
"text": "Input: {1, 2, 3, 4, 5, 6}, K = 2Output: 5 6 1 2 3 4"
},
{
"code": null,
"e": 26439,
"s": 26340,
"text": "Approach: The naive approach and approach based on reversing parts of the array is discussed here."
},
{
"code": null,
"e": 26716,
"s": 26439,
"text": "Pointer based approach: The base of this concept is the reversal algorithm for array rotation. The array is divided into two parts where the first part is of size (N-K) and the end part is of size K. These two parts are individually reversed. Then the whole array is reversed."
},
{
"code": null,
"e": 26767,
"s": 26716,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26771,
"s": 26767,
"text": "C++"
},
{
"code": null,
"e": 26776,
"s": 26771,
"text": "Java"
},
{
"code": null,
"e": 26784,
"s": 26776,
"text": "Python3"
},
{
"code": null,
"e": 26787,
"s": 26784,
"text": "C#"
},
{
"code": null,
"e": 26798,
"s": 26787,
"text": "Javascript"
},
{
"code": "// C++ code to implement above approach#include <iostream>using namespace std; // Function to print the arrayvoid print(int arr[], int N){ for (int i = 0; i < N; i++) cout << *(arr + i) << \" \";} // Function to reverse the array// from start to end indexvoid reverse(int arr[], int start, int end){ int temp; int size = end - start; // Reversal based on pointer approach for (int i = 0; i < (size / 2); i++) { temp = *(arr + i + start); *(arr + i + start) = *(arr + start + size - i - 1); *(arr + start + size - i - 1) = temp; }} // Function to right rotate the array K timesvoid right(int arr[], int K, int N){ reverse(arr, 0, N - K); reverse(arr, N - K, N); reverse(arr, 0, N); print(arr, N);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; right(arr, K, N); return 0;}",
"e": 27733,
"s": 26798,
"text": null
},
{
"code": "// Java code to implement above approachimport java.util.*; class GFG{ // Function to print the arraystatic void print(int arr[], int N){ for (int i = 0; i < N; i++) System.out.print(arr[i]+ \" \");} // Function to reverse the array// from start to end indexstatic int[] reverse(int arr[], int start, int end){ int temp; int size = end - start; // Reversal based on pointer approach for (int i = 0; i < (size / 2); i++) { temp = arr[ i + start]; arr[i + start] = arr[start + size - i - 1]; arr[start + size - i - 1] = temp; } return arr;} // Function to right rotate the array K timesstatic void right(int arr[], int K, int N){ arr = reverse(arr, 0, N - K); arr = reverse(arr, N - K, N); arr = reverse(arr, 0, N); print(arr, N);} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int N = arr.length; int K = 2; right(arr, K, N);}} // This code is contributed by 29AjayKumar",
"e": 28745,
"s": 27733,
"text": null
},
{
"code": "# Python code to implement above approach # Function to print arraydef print1(arr, N): for i in range(N): print(arr[i], end = \" \"); # Function to reverse the array# from start to end indexdef reverse(arr, start, end): temp = 0; size = end - start; # Reversal based on pointer approach for i in range(size//2): temp = arr[i + start]; arr[i + start] = arr[start + size - i - 1]; arr[start + size - i - 1] = temp; return arr; # Function to right rotate the array K timesdef right(arr, K, N): arr = reverse(arr, 0, N - K); arr = reverse(arr, N - K, N); arr = reverse(arr, 0, N); print1(arr, N); # Driver codeif __name__ == '__main__': arr = [1, 2, 3, 4, 5, 6]; N = len(arr); K = 2; right(arr, K, N); # This code is contributed by 29AjayKumar",
"e": 29559,
"s": 28745,
"text": null
},
{
"code": "// C# code to implement above approachusing System;class GFG { // Function to print the array static void print(int[] arr, int N) { for (int i = 0; i < N; i++) Console.Write(arr[i] + \" \"); } // Function to reverse the array // from start to end index static void reverse(int[] arr, int start, int end) { int temp; int size = end - start; // Reversal based on pointer approach for (int i = 0; i < (size / 2); i++) { temp = arr[i + start]; arr[i + start] = arr[start + size - i - 1]; arr[start + size - i - 1] = temp; } } // Function to right rotate the array K times static void right(int[] arr, int K, int N) { reverse(arr, 0, N - K); reverse(arr, N - K, N); reverse(arr, 0, N); print(arr, N); } // Driver code public static void Main() { int[] arr = { 1, 2, 3, 4, 5, 6 }; int N = arr.Length; int K = 2; right(arr, K, N); }} // This code is contributed by ukasp.",
"e": 30506,
"s": 29559,
"text": null
},
{
"code": "<script> // JavaScript code to implement above approach // Function to print the array const print = (arr, N) => { for (let i = 0; i < N; i++) document.write(`${arr[i]} `); } // Function to reverse the array // from start to end index const reverse = (arr, start, end) => { let temp; let size = end - start; // Reversal based on pointer approach for (let i = 0; i < parseInt(size / 2); i++) { temp = arr[i + start]; arr[i + start] = arr[start + size - i - 1]; arr[start + size - i - 1] = temp; } } // Function to right rotate the array K times const right = (arr, K, N) => { reverse(arr, 0, N - K); reverse(arr, N - K, N); reverse(arr, 0, N); print(arr, N); } // Driver code let arr = [1, 2, 3, 4, 5, 6]; let N = arr.length; let K = 2; right(arr, K, N); // This code is contributed by rakeshsahni </script>",
"e": 31480,
"s": 30506,
"text": null
},
{
"code": null,
"e": 31496,
"s": 31483,
"text": "5 6 1 2 3 4 "
},
{
"code": null,
"e": 31541,
"s": 31498,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31555,
"s": 31543,
"text": "rakeshsahni"
},
{
"code": null,
"e": 31561,
"s": 31555,
"text": "ukasp"
},
{
"code": null,
"e": 31573,
"s": 31561,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31590,
"s": 31573,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 31599,
"s": 31590,
"text": "Pointers"
},
{
"code": null,
"e": 31608,
"s": 31599,
"text": "rotation"
},
{
"code": null,
"e": 31615,
"s": 31608,
"text": "Arrays"
},
{
"code": null,
"e": 31622,
"s": 31615,
"text": "Arrays"
},
{
"code": null,
"e": 31631,
"s": 31622,
"text": "Pointers"
},
{
"code": null,
"e": 31729,
"s": 31631,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31756,
"s": 31729,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 31787,
"s": 31756,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 31812,
"s": 31787,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31850,
"s": 31812,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31871,
"s": 31850,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31929,
"s": 31871,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 31988,
"s": 31929,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 32024,
"s": 31988,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 32109,
"s": 32024,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
}
]
|
Python | Pandas DatetimeIndex.week - GeeksforGeeks | 24 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.week attribute outputs the ordinal value of the week for each entries of the DatetimeIndex object. It is similar to the DatetimeIndex.week attribute.
Syntax: DatetimeIndex.week
Return: Index object
Example #1: Use DatetimeIndex.week attribute to find the ordinal value of the week for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'W' represents Weekly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='W', periods = 3, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)
Output :
Now we want to find ordinal value of the week for each entries in the DatetimeIndex object.
# find the ordinal value of the week# for each entries present in the objectdidx.week
Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the weeks present in each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.week attribute to find the ordinal value of the week for each entries in the DatetimeIndex object.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='M', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)
Output :
Now we want to find ordinal value of the week for each entries in the DatetimeIndex object.
# find the ordinal value of the week # for each entries present in the objectdidx.week
Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the weeks present in each entry of the DatetimeIndex object.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26097,
"s": 26069,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 26311,
"s": 26097,
"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": 26482,
"s": 26311,
"text": "Pandas DatetimeIndex.week attribute outputs the ordinal value of the week for each entries of the DatetimeIndex object. It is similar to the DatetimeIndex.week attribute."
},
{
"code": null,
"e": 26509,
"s": 26482,
"text": "Syntax: DatetimeIndex.week"
},
{
"code": null,
"e": 26530,
"s": 26509,
"text": "Return: Index object"
},
{
"code": null,
"e": 26659,
"s": 26530,
"text": "Example #1: Use DatetimeIndex.week attribute to find the ordinal value of the week for each entries in the DatetimeIndex object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'W' represents Weekly frequencydidx = pd.DatetimeIndex(start ='2000-01-10 06:30', freq ='W', periods = 3, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)",
"e": 26929,
"s": 26659,
"text": null
},
{
"code": null,
"e": 26938,
"s": 26929,
"text": "Output :"
},
{
"code": null,
"e": 27030,
"s": 26938,
"text": "Now we want to find ordinal value of the week for each entries in the DatetimeIndex object."
},
{
"code": "# find the ordinal value of the week# for each entries present in the objectdidx.week ",
"e": 27117,
"s": 27030,
"text": null
},
{
"code": null,
"e": 27419,
"s": 27117,
"text": "Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the weeks present in each entry of the DatetimeIndex object. Example #2: Use DatetimeIndex.week attribute to find the ordinal value of the week for each entries in the DatetimeIndex object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequencydidx = pd.DatetimeIndex(start ='2014-08-01 10:05:45', freq ='M', periods = 5, tz ='Asia/Calcutta') # Print the DatetimeIndexprint(didx)",
"e": 27697,
"s": 27419,
"text": null
},
{
"code": null,
"e": 27706,
"s": 27697,
"text": "Output :"
},
{
"code": null,
"e": 27798,
"s": 27706,
"text": "Now we want to find ordinal value of the week for each entries in the DatetimeIndex object."
},
{
"code": "# find the ordinal value of the week # for each entries present in the objectdidx.week",
"e": 27885,
"s": 27798,
"text": null
},
{
"code": null,
"e": 28058,
"s": 27885,
"text": "Output :As we can see in the output, the function has returned an Index object containing the ordinal values of the weeks present in each entry of the DatetimeIndex object."
},
{
"code": null,
"e": 28086,
"s": 28058,
"text": "Python pandas-datetimeIndex"
},
{
"code": null,
"e": 28100,
"s": 28086,
"text": "Python-pandas"
},
{
"code": null,
"e": 28107,
"s": 28100,
"text": "Python"
},
{
"code": null,
"e": 28205,
"s": 28107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28223,
"s": 28205,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28258,
"s": 28223,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28290,
"s": 28258,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28312,
"s": 28290,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28354,
"s": 28312,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28384,
"s": 28354,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28410,
"s": 28384,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28439,
"s": 28410,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28483,
"s": 28439,
"text": "Reading and Writing to text files in Python"
}
]
|
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks | 28 Jun, 2021
In a room there are only two types of people, namely Type 1 and Type 2. Type 1 people always tell the truth and Type 2 people always lie. You give a fair coin to a person in that room, without knowing which type he is from and tell him to toss it and hide the result from you till you ask for it. Upon asking, the person replies the following:
“The result of the toss is head if and only if I am telling the truth.”
Which of the following options is correct?
(A) The result is head(B) The result is tail(C) If the person is of Type 2, then the result is tail(D) If the person is of Type 1, then the result is taiAnswer: (A)Explanation:
“The result of the toss is head if and only
if I am telling the truth.”
If the person is of Type 1 who always tell truth, then result must be head.
If the person is of Type 2 who always tell lie, then result must be head.
Negation of a sentence of the form "X is true if and only if Y is true" is
"Either X is true and Y is false, or X is false and Y is true."
Refer: http://math.stackexchange.com/questions/10435/negation-of-if-and-only-if
Which means "Either toss is head and I am not telling truth, or toss is tail
and I am telling truth".
Since the person always lie, it is "Either toss is head and I am not telling truth"
Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26017,
"s": 25673,
"text": "In a room there are only two types of people, namely Type 1 and Type 2. Type 1 people always tell the truth and Type 2 people always lie. You give a fair coin to a person in that room, without knowing which type he is from and tell him to toss it and hide the result from you till you ask for it. Upon asking, the person replies the following:"
},
{
"code": null,
"e": 26090,
"s": 26017,
"text": "“The result of the toss is head if and only if I am telling the truth.” "
},
{
"code": null,
"e": 26133,
"s": 26090,
"text": "Which of the following options is correct?"
},
{
"code": null,
"e": 26310,
"s": 26133,
"text": "(A) The result is head(B) The result is tail(C) If the person is of Type 2, then the result is tail(D) If the person is of Type 1, then the result is taiAnswer: (A)Explanation:"
},
{
"code": null,
"e": 26949,
"s": 26310,
"text": "“The result of the toss is head if and only \n if I am telling the truth.” \n\n\nIf the person is of Type 1 who always tell truth, then result must be head.\n\nIf the person is of Type 2 who always tell lie, then result must be head.\n\nNegation of a sentence of the form \"X is true if and only if Y is true\" is \n\"Either X is true and Y is false, or X is false and Y is true.\"\n\nRefer: http://math.stackexchange.com/questions/10435/negation-of-if-and-only-if\n\nWhich means \"Either toss is head and I am not telling truth, or toss is tail\nand I am telling truth\".\n\nSince the person always lie, it is \"Either toss is head and I am not telling truth\"\n"
},
{
"code": null,
"e": 26971,
"s": 26949,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26992,
"s": 26971,
"text": "GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 27018,
"s": 26992,
"text": "GATE-GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 27023,
"s": 27018,
"text": "GATE"
},
{
"code": null,
"e": 27121,
"s": 27023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27155,
"s": 27121,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27189,
"s": 27155,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27223,
"s": 27189,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27256,
"s": 27223,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27292,
"s": 27256,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27326,
"s": 27292,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27362,
"s": 27326,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27396,
"s": 27362,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27430,
"s": 27396,
"text": "GATE | GATE-CS-2009 | Question 38"
}
]
|
How to modify URL without reloading the page using JavaScript ? - GeeksforGeeks | 31 Oct, 2019
Method 1: Replacing the current state with replaceState() Method: The history interface of the browser manages the browser session history. It includes the page visited in the tab or frame where the current page is located. Manipulating this state can be used to change the URL of the browser without reloading the page.
The replaceState() method is used to modify the current history entry and replace the properties of the state with ones in the passed parameters.
The parameters of this method have 3 parts, the state object which is a serializable object about the state, the title which is the title of the new state and the URL which is the new URL of the state.
The URL can be changed by passing the required URL as a string to this method. This will change the URL of the page without reloading the page.
Example:
<!DOCTYPE html><html> <head> <title> How to modify URL without reloading the page using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to modify URL without reloading the page using JavaScript? </b> <p> Click on the button below to modify the current history state </p> <button onclick="modifyState()"> Modify history state </button> <script> function modifyState() { let stateObj = { id: "100" }; window.history.replaceState(stateObj, "Page 3", "/page3.html"); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page.
The parameters of this method have three parts, the state object which is a serializable object about the state, the title which is the new title of the state and the URL which is the new URL of the state.The URL can be changed by passing the required URL as a string to this method. This will change the URL of the page without reloading the page.
Example:
<!DOCTYPE html><html> <head> <title> How to modify URL without reloading the page using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to modify URL without reloading the page using JavaScript? </b> <p> Click on the button below to add a new history state </p> <button onclick="addState()"> Add history state </button> <script> function addState() { let stateObj = { id: "100" }; window.history.pushState(stateObj, "Page 2", "/page2.html"); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 26942,
"s": 26621,
"text": "Method 1: Replacing the current state with replaceState() Method: The history interface of the browser manages the browser session history. It includes the page visited in the tab or frame where the current page is located. Manipulating this state can be used to change the URL of the browser without reloading the page."
},
{
"code": null,
"e": 27088,
"s": 26942,
"text": "The replaceState() method is used to modify the current history entry and replace the properties of the state with ones in the passed parameters."
},
{
"code": null,
"e": 27290,
"s": 27088,
"text": "The parameters of this method have 3 parts, the state object which is a serializable object about the state, the title which is the title of the new state and the URL which is the new URL of the state."
},
{
"code": null,
"e": 27434,
"s": 27290,
"text": "The URL can be changed by passing the required URL as a string to this method. This will change the URL of the page without reloading the page."
},
{
"code": null,
"e": 27443,
"s": 27434,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to modify URL without reloading the page using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to modify URL without reloading the page using JavaScript? </b> <p> Click on the button below to modify the current history state </p> <button onclick=\"modifyState()\"> Modify history state </button> <script> function modifyState() { let stateObj = { id: \"100\" }; window.history.replaceState(stateObj, \"Page 3\", \"/page3.html\"); } </script></body> </html>",
"e": 28152,
"s": 27443,
"text": null
},
{
"code": null,
"e": 28160,
"s": 28152,
"text": "Output:"
},
{
"code": null,
"e": 28188,
"s": 28160,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 28215,
"s": 28188,
"text": "After clicking the button:"
},
{
"code": null,
"e": 28453,
"s": 28215,
"text": "Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page."
},
{
"code": null,
"e": 28802,
"s": 28453,
"text": "The parameters of this method have three parts, the state object which is a serializable object about the state, the title which is the new title of the state and the URL which is the new URL of the state.The URL can be changed by passing the required URL as a string to this method. This will change the URL of the page without reloading the page."
},
{
"code": null,
"e": 28811,
"s": 28802,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to modify URL without reloading the page using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to modify URL without reloading the page using JavaScript? </b> <p> Click on the button below to add a new history state </p> <button onclick=\"addState()\"> Add history state </button> <script> function addState() { let stateObj = { id: \"100\" }; window.history.pushState(stateObj, \"Page 2\", \"/page2.html\"); } </script></body> </html>",
"e": 29510,
"s": 28811,
"text": null
},
{
"code": null,
"e": 29518,
"s": 29510,
"text": "Output:"
},
{
"code": null,
"e": 29546,
"s": 29518,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 29573,
"s": 29546,
"text": "After clicking the button:"
},
{
"code": null,
"e": 29589,
"s": 29573,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29596,
"s": 29589,
"text": "Picked"
},
{
"code": null,
"e": 29607,
"s": 29596,
"text": "JavaScript"
},
{
"code": null,
"e": 29624,
"s": 29607,
"text": "Web Technologies"
},
{
"code": null,
"e": 29651,
"s": 29624,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29749,
"s": 29651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29789,
"s": 29749,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29834,
"s": 29789,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29895,
"s": 29834,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29967,
"s": 29895,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30019,
"s": 29967,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30059,
"s": 30019,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30092,
"s": 30059,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30137,
"s": 30092,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30180,
"s": 30137,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Extract all the URLs from the webpage Using Python - GeeksforGeeks | 07 Jan, 2021
Scraping is a very essential skill for everyone to get data from any website. In this article, we are going to write Python scripts to extract all the URLs from the website or you can save it as a CSV file.
Module Needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests
Approach:
Import module
Make requests instance and pass into URL
Pass the requests into a Beautifulsoup() function
Use ‘a’ tag to find them all tag (‘a href ‘)
Example 1:
Python3
import requestsfrom bs4 import BeautifulSoup url = 'https://www.geeksforgeeks.org/'reqs = requests.get(url)soup = BeautifulSoup(reqs.text, 'html.parser') urls = []for link in soup.find_all('a'): print(link.get('href'))
Output:
Example 2:
Extracting URLs and save as CSV files.
Python3
import requestsfrom bs4 import BeautifulSoup urls = 'https://www.geeksforgeeks.org/'grab = requests.get(urls)soup = BeautifulSoup(grab.text, 'html.parser') # opening a file in write modef = open("test1.txt", "w")# traverse paragraphs from soupfor link in soup.find_all("a"): data = link.get('href') f.write(data) f.write("\n") f.close()
Output:
skrg141
Python web-scraping-exercises
python-utility
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 25744,
"s": 25537,
"text": "Scraping is a very essential skill for everyone to get data from any website. In this article, we are going to write Python scripts to extract all the URLs from the website or you can save it as a CSV file."
},
{
"code": null,
"e": 25759,
"s": 25744,
"text": "Module Needed:"
},
{
"code": null,
"e": 25952,
"s": 25759,
"text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 25968,
"s": 25952,
"text": "pip install bs4"
},
{
"code": null,
"e": 26153,
"s": 25968,
"text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal."
},
{
"code": null,
"e": 26174,
"s": 26153,
"text": "pip install requests"
},
{
"code": null,
"e": 26184,
"s": 26174,
"text": "Approach:"
},
{
"code": null,
"e": 26198,
"s": 26184,
"text": "Import module"
},
{
"code": null,
"e": 26239,
"s": 26198,
"text": "Make requests instance and pass into URL"
},
{
"code": null,
"e": 26289,
"s": 26239,
"text": "Pass the requests into a Beautifulsoup() function"
},
{
"code": null,
"e": 26334,
"s": 26289,
"text": "Use ‘a’ tag to find them all tag (‘a href ‘)"
},
{
"code": null,
"e": 26345,
"s": 26334,
"text": "Example 1:"
},
{
"code": null,
"e": 26353,
"s": 26345,
"text": "Python3"
},
{
"code": "import requestsfrom bs4 import BeautifulSoup url = 'https://www.geeksforgeeks.org/'reqs = requests.get(url)soup = BeautifulSoup(reqs.text, 'html.parser') urls = []for link in soup.find_all('a'): print(link.get('href'))",
"e": 26576,
"s": 26353,
"text": null
},
{
"code": null,
"e": 26584,
"s": 26576,
"text": "Output:"
},
{
"code": null,
"e": 26595,
"s": 26584,
"text": "Example 2:"
},
{
"code": null,
"e": 26634,
"s": 26595,
"text": "Extracting URLs and save as CSV files."
},
{
"code": null,
"e": 26642,
"s": 26634,
"text": "Python3"
},
{
"code": "import requestsfrom bs4 import BeautifulSoup urls = 'https://www.geeksforgeeks.org/'grab = requests.get(urls)soup = BeautifulSoup(grab.text, 'html.parser') # opening a file in write modef = open(\"test1.txt\", \"w\")# traverse paragraphs from soupfor link in soup.find_all(\"a\"): data = link.get('href') f.write(data) f.write(\"\\n\") f.close()",
"e": 26985,
"s": 26642,
"text": null
},
{
"code": null,
"e": 26993,
"s": 26985,
"text": "Output:"
},
{
"code": null,
"e": 27003,
"s": 26995,
"text": "skrg141"
},
{
"code": null,
"e": 27033,
"s": 27003,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 27048,
"s": 27033,
"text": "python-utility"
},
{
"code": null,
"e": 27061,
"s": 27048,
"text": "Web-scraping"
},
{
"code": null,
"e": 27068,
"s": 27061,
"text": "Python"
},
{
"code": null,
"e": 27166,
"s": 27068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27198,
"s": 27166,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27240,
"s": 27198,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27282,
"s": 27240,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27309,
"s": 27282,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27365,
"s": 27309,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27387,
"s": 27365,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27426,
"s": 27387,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27457,
"s": 27426,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27486,
"s": 27457,
"text": "Create a directory in Python"
}
]
|
Python - Convert Lists of List to Dictionary - GeeksforGeeks | 22 Apr, 2020
Sometimes, while working with Python records, we can have problem in which we have data in form of Lists of list and we need to allocate certain elements as keys and certain as values to form a dictionary. This type of application can occur in data domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute way in which we perform this task. In this, we iterate through the lists forming key value pairs according to required slicing.
# Python3 code to demonstrate working of # Convert Lists of List to Dictionary# Using loop # initializing listtest_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]] # printing original listprint("The original list is : " + str(test_list)) # Convert Lists of List to Dictionary# Using loopres = dict()for sub in test_list: res[tuple(sub[:2])] = tuple(sub[2:]) # printing result print("The mapped Dictionary : " + str(res))
The original list is : [[‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4], [‘e’, ‘f’, 5, 6]]The mapped Dictionary : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}
Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. This is similar to above method, just a one liner alternative.
# Python3 code to demonstrate working of # Convert Lists of List to Dictionary# Using dictionary comprehension # initializing listtest_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]] # printing original listprint("The original list is : " + str(test_list)) # Convert Lists of List to Dictionary# Using dictionary comprehensionres = {tuple(sub[:2]): tuple(sub[2:]) for sub in test_list} # printing result print("The mapped Dictionary : " + str(res))
The original list is : [[‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4], [‘e’, ‘f’, 5, 6]]The mapped Dictionary : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
How to print without newline in Python? | [
{
"code": null,
"e": 25485,
"s": 25457,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25806,
"s": 25485,
"text": "Sometimes, while working with Python records, we can have problem in which we have data in form of Lists of list and we need to allocate certain elements as keys and certain as values to form a dictionary. This type of application can occur in data domains. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 25970,
"s": 25806,
"text": "Method #1 : Using loopThis is brute way in which we perform this task. In this, we iterate through the lists forming key value pairs according to required slicing."
},
{
"code": "# Python3 code to demonstrate working of # Convert Lists of List to Dictionary# Using loop # initializing listtest_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert Lists of List to Dictionary# Using loopres = dict()for sub in test_list: res[tuple(sub[:2])] = tuple(sub[2:]) # printing result print(\"The mapped Dictionary : \" + str(res)) ",
"e": 26416,
"s": 25970,
"text": null
},
{
"code": null,
"e": 26578,
"s": 26416,
"text": "The original list is : [[‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4], [‘e’, ‘f’, 5, 6]]The mapped Dictionary : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}"
},
{
"code": null,
"e": 26746,
"s": 26580,
"text": "Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. This is similar to above method, just a one liner alternative."
},
{
"code": "# Python3 code to demonstrate working of # Convert Lists of List to Dictionary# Using dictionary comprehension # initializing listtest_list = [['a', 'b', 1, 2], ['c', 'd', 3, 4], ['e', 'f', 5, 6]] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert Lists of List to Dictionary# Using dictionary comprehensionres = {tuple(sub[:2]): tuple(sub[2:]) for sub in test_list} # printing result print(\"The mapped Dictionary : \" + str(res)) ",
"e": 27218,
"s": 26746,
"text": null
},
{
"code": null,
"e": 27380,
"s": 27218,
"text": "The original list is : [[‘a’, ‘b’, 1, 2], [‘c’, ‘d’, 3, 4], [‘e’, ‘f’, 5, 6]]The mapped Dictionary : {(‘c’, ‘d’): (3, 4), (‘e’, ‘f’): (5, 6), (‘a’, ‘b’): (1, 2)}"
},
{
"code": null,
"e": 27407,
"s": 27380,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27428,
"s": 27407,
"text": "Python list-programs"
},
{
"code": null,
"e": 27435,
"s": 27428,
"text": "Python"
},
{
"code": null,
"e": 27451,
"s": 27435,
"text": "Python Programs"
},
{
"code": null,
"e": 27549,
"s": 27451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27581,
"s": 27549,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27603,
"s": 27581,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27645,
"s": 27603,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27675,
"s": 27645,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27701,
"s": 27675,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27744,
"s": 27701,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27766,
"s": 27744,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27805,
"s": 27766,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27851,
"s": 27805,
"text": "Python | Split string into list of characters"
}
]
|
Solve the Slide Puzzle with Hill Climbing Search Algorithm | by Rahul Aware | Towards Data Science | Hill climbing search algorithm is one of the simplest algorithms which falls under local search and optimization techniques. Here’s how it’s defined in ‘An Introduction to Machine Learning’ book by Miroslav Kubat:
Evaluation function at step 3 calculates the distance of the current state from the final state. So in case of 3x3 Slide Puzzle we have:
Final State: 1 2 34 5 6 7 8 Consider Current State: 1 2 3 4 5 6 7 8
Evaluation Function dF calculates the sum of the moves required for each tile to reach its final state. Since tiles 1 to 7 are already in its correct position, they don’t need to be moved. However, tile 8 is 1 move away from its final position.
dF(8) = m(1)+m(2)+m(3)+m(4)+m(5)+m(6)+m(7)+m(8)= 1
Hill climbing evaluates the possible next moves and picks the one which has the least distance. It also checks if the new state after the move was already observed. If true, then it skips the move and picks the next best move. As the vacant tile can only be filled by its neighbors, Hill climbing sometimes gets locked and couldn’t find any solution. It’s one of the major drawbacks of this algorithm.
Another drawback which is highly documented is local optima. The algorithm decides the next move(state) based on immediate distance(cost), assuming that the small improvement now is the best way to reach the final state. However, the path chosen may lead to higher cost(more steps) later.
Analogues to entering a valley after climbing a small hill.
In order to get around the local optima, I propose the usage of depth-first approach.
Idea is to traverse a path for a defined number of steps(depth) to confirm that it’s the best move.
Loop over all the possible next moves(states) for the current state.Call step 1 until depth d is reached. This generates a tree of height d.Pick the move(state) with minimum cost(dF)Return dF so that evaluation can be done at depth-1 level.
Loop over all the possible next moves(states) for the current state.
Call step 1 until depth d is reached. This generates a tree of height d.
Pick the move(state) with minimum cost(dF)
Return dF so that evaluation can be done at depth-1 level.
I observed that the depth-first approach improves the overall efficiency of reaching the final state. However, its memory intensive, proportional to the depth value used. This is because the system has to keep track of future states as per the depth used.
Here’s a brief comparison of the Distance by Moves charts for various depths:
A live evaluation can be performed here. Try out various depths and complexities and see the evaluation graphs. Sometimes, the puzzle remains unresolved due to lockdown(no new state).
Or, if you are just in the mood of solving the puzzle, try yourself against the bot powered by Hill Climbing Algorithm.
Hit the like button on this article every time you lose against the bot :-)
Have fun!
Edited: Live evaluation and bot currently don’t work on mobile devices. | [
{
"code": null,
"e": 386,
"s": 172,
"text": "Hill climbing search algorithm is one of the simplest algorithms which falls under local search and optimization techniques. Here’s how it’s defined in ‘An Introduction to Machine Learning’ book by Miroslav Kubat:"
},
{
"code": null,
"e": 523,
"s": 386,
"text": "Evaluation function at step 3 calculates the distance of the current state from the final state. So in case of 3x3 Slide Puzzle we have:"
},
{
"code": null,
"e": 593,
"s": 523,
"text": "Final State: 1 2 34 5 6 7 8 Consider Current State: 1 2 3 4 5 6 7 8"
},
{
"code": null,
"e": 838,
"s": 593,
"text": "Evaluation Function dF calculates the sum of the moves required for each tile to reach its final state. Since tiles 1 to 7 are already in its correct position, they don’t need to be moved. However, tile 8 is 1 move away from its final position."
},
{
"code": null,
"e": 889,
"s": 838,
"text": "dF(8) = m(1)+m(2)+m(3)+m(4)+m(5)+m(6)+m(7)+m(8)= 1"
},
{
"code": null,
"e": 1291,
"s": 889,
"text": "Hill climbing evaluates the possible next moves and picks the one which has the least distance. It also checks if the new state after the move was already observed. If true, then it skips the move and picks the next best move. As the vacant tile can only be filled by its neighbors, Hill climbing sometimes gets locked and couldn’t find any solution. It’s one of the major drawbacks of this algorithm."
},
{
"code": null,
"e": 1580,
"s": 1291,
"text": "Another drawback which is highly documented is local optima. The algorithm decides the next move(state) based on immediate distance(cost), assuming that the small improvement now is the best way to reach the final state. However, the path chosen may lead to higher cost(more steps) later."
},
{
"code": null,
"e": 1640,
"s": 1580,
"text": "Analogues to entering a valley after climbing a small hill."
},
{
"code": null,
"e": 1726,
"s": 1640,
"text": "In order to get around the local optima, I propose the usage of depth-first approach."
},
{
"code": null,
"e": 1826,
"s": 1726,
"text": "Idea is to traverse a path for a defined number of steps(depth) to confirm that it’s the best move."
},
{
"code": null,
"e": 2067,
"s": 1826,
"text": "Loop over all the possible next moves(states) for the current state.Call step 1 until depth d is reached. This generates a tree of height d.Pick the move(state) with minimum cost(dF)Return dF so that evaluation can be done at depth-1 level."
},
{
"code": null,
"e": 2136,
"s": 2067,
"text": "Loop over all the possible next moves(states) for the current state."
},
{
"code": null,
"e": 2209,
"s": 2136,
"text": "Call step 1 until depth d is reached. This generates a tree of height d."
},
{
"code": null,
"e": 2252,
"s": 2209,
"text": "Pick the move(state) with minimum cost(dF)"
},
{
"code": null,
"e": 2311,
"s": 2252,
"text": "Return dF so that evaluation can be done at depth-1 level."
},
{
"code": null,
"e": 2567,
"s": 2311,
"text": "I observed that the depth-first approach improves the overall efficiency of reaching the final state. However, its memory intensive, proportional to the depth value used. This is because the system has to keep track of future states as per the depth used."
},
{
"code": null,
"e": 2645,
"s": 2567,
"text": "Here’s a brief comparison of the Distance by Moves charts for various depths:"
},
{
"code": null,
"e": 2829,
"s": 2645,
"text": "A live evaluation can be performed here. Try out various depths and complexities and see the evaluation graphs. Sometimes, the puzzle remains unresolved due to lockdown(no new state)."
},
{
"code": null,
"e": 2949,
"s": 2829,
"text": "Or, if you are just in the mood of solving the puzzle, try yourself against the bot powered by Hill Climbing Algorithm."
},
{
"code": null,
"e": 3025,
"s": 2949,
"text": "Hit the like button on this article every time you lose against the bot :-)"
},
{
"code": null,
"e": 3035,
"s": 3025,
"text": "Have fun!"
}
]
|
Creating a table with a TIMESTAMP field in MySQL? | For this, you can use TIMESTAMP keyword in MySQL.
Let us create a table −
mysql> create table demo50
−> (
−> id int not null auto_increment primary key,
−> start_date timestamp default current_timestamp not null,
−> end_date timestamp default current_timestamp not null
−> );
Query OK, 0 rows affected (1.35 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo50 values();
Query OK, 1 row affected (0.15 sec)
mysql> insert into demo50(end_date) values('2020−12−21');
Query OK, 1 row affected (0.07 sec)
mysql> insert into demo50(start_date) values('2020−01−01');
Query OK, 1 row affected (0.14 sec)
Display records from the table using select statement −
mysql> select *from demo50;
This will produce the following output −
+----+---------------------+---------------------+
| id | start_date | end_date |
+----+---------------------+---------------------+
| 1 | 2020−11−04 20:54:31 | 2020−11−04 20:54:31 |
| 2 | 2020−11−04 20:54:53 | 2020−12−21 00:00:00 |
| 3 | 2020−01−01 00:00:00 | 2020−11−04 20:55:04 |
+----+---------------------+---------------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1112,
"s": 1062,
"text": "For this, you can use TIMESTAMP keyword in MySQL."
},
{
"code": null,
"e": 1136,
"s": 1112,
"text": "Let us create a table −"
},
{
"code": null,
"e": 1375,
"s": 1136,
"text": "mysql> create table demo50\n−> (\n−> id int not null auto_increment primary key,\n−> start_date timestamp default current_timestamp not null,\n−> end_date timestamp default current_timestamp not null\n−> );\nQuery OK, 0 rows affected (1.35 sec)"
},
{
"code": null,
"e": 1444,
"s": 1375,
"text": "Insert some records into the table with the help of insert command −"
},
{
"code": null,
"e": 1708,
"s": 1444,
"text": "mysql> insert into demo50 values();\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into demo50(end_date) values('2020−12−21');\nQuery OK, 1 row affected (0.07 sec)\n\nmysql> insert into demo50(start_date) values('2020−01−01');\nQuery OK, 1 row affected (0.14 sec)"
},
{
"code": null,
"e": 1764,
"s": 1708,
"text": "Display records from the table using select statement −"
},
{
"code": null,
"e": 1792,
"s": 1764,
"text": "mysql> select *from demo50;"
},
{
"code": null,
"e": 1833,
"s": 1792,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2215,
"s": 1833,
"text": "+----+---------------------+---------------------+\n| id | start_date | end_date |\n+----+---------------------+---------------------+\n| 1 | 2020−11−04 20:54:31 | 2020−11−04 20:54:31 |\n| 2 | 2020−11−04 20:54:53 | 2020−12−21 00:00:00 |\n| 3 | 2020−01−01 00:00:00 | 2020−11−04 20:55:04 |\n+----+---------------------+---------------------+\n3 rows in set (0.00 sec)"
}
]
|
Word Embedding Techniques: Word2Vec and TF-IDF Explained | by Adem Akdogan | Towards Data Science | The words need to be made meaningful for machine learning or deep learning algorithms. Therefore, they must be expressed numerically. Algorithms such as One Hot Encoding, TF-IDF, Word2Vec, FastText enable words to be expressed mathematically as word embedding techniques used to solve such problems.
The word embedding techniques are used to represent words mathematically. One Hot Encoding, TF-IDF, Word2Vec, FastText are frequently used Word Embedding methods. One of these techniques (in some cases several) is preferred and used according to the status, size and purpose of processing the data.
One of the most basic techniques used to represent data numerically is One Hot Encoding technique[1]. In this method, a vector is created in the size of the total number of unique words. The value of vectors is assigned such that the value of each word belonging to its index is 1 and the others are 0. As an example, Figure 1 can be examined.
The column named “X” consists of 3 different words in Figure 1. When One Hot Encoding is applied to this column, 3 different columns representing each expression are created (in other words, 3-unit vectors are created for each row). The column corresponding to the word in each row is filled with the values 1, the others 0. Thus, these expressions are digitized. It is generally used in situations where there is not much verbal data diversity and there is no need to represent the semantic and statistical relationships between the data.
TF-IDF is a statistical measure used to determine the mathematical significance of words in documents[2]. The vectorization process is similar to One Hot Encoding. Alternatively, the value corresponding to the word is assigned a TF-IDF value instead of 1. The TF-IDF value is obtained by multiplying the TF and IDF values. As an example, let’s find the TF-IDF values for 3 documents consisting of 1 sentence.
[He is Walter],
[He is William],
[He isn’t Peter or September]
In the above example, “He” is used in all 3 documents, “is” is in 2 documents, and “or” is in only one document. According to these, let’s find the TF and then the IDF values, respectively.
TF (Term Frequency)
In the simplest terms, term frequency is the ratio of the number of target terms in the document to the total number of terms in the document. If TF values are calculated according to the above example, it will be
[0.33, 0.33, 0.33],
[0.33, 0.33, 0.33],
[0.20, 0.20, 0.20, 0.20, 0.20]
IDF (Inverse Documet Frequency)
The IDF value is the logarithm of the ratio of the total number of documents to the number of documents in which the target term occurs. At this stage, it does not matter how many times the term appears in the document. It is sufficient to determine whether it has passed or not. In this example, the base value of the logarithm to be taken is determined as 10. However, there is no problem in using different values.
“He”: Log(3/3)= 0,
“is”: Log(3/2):0.1761,
“or, Peter, ..”: log(3/1) : 0.4771
Thus, both TF and IDF values were obtained. If vectorization is created with these values, firstly a vector consisting of elements equal to the number of unique words in all documents is created for each document (in this example, there are 8 terms). At this stage, there is a problem to be solved. As seen in the term “He”, since the IDF value is 0, the TF-IDF value will also be zero. However, words that are not included in the document during the vectorization process (for example, the phrase “Peter” is not included in the 1st sentence) will be assigned a value of 0. In order to avoid confusion here, TF-IDF values are smoothed for vectorization. The most common method is to add 1 to the obtained values. Depending on the purpose, normalization can be applied to these values later. If the vectorization process is created according to the above-mentioned;
[1. , 1.1761 , 1.4771 , 0. , 0. , 0. , 0. , 0.],
[1. , 1.1761 , 0. , 1.4771 , 0. , 0. , 0. , 0.],
[1. , 0. , 0. , 0. , 1.4771 , 1.4771, 1.4771 , 1.4771],
Word2vec is another of the frequently used word embedding techniques. The entire corpus is scanned, and the vector creation process is performed by determining which words the target word occurs with more often[3]. In this way, the semantic closeness of the words to each other is also revealed. For example, let each letter in the sequences ..x y A z w.. , .. x y B z k.. and ..x l C d m... represent a word. In this case, word_A will be closer to word_B than word_C. When this situation is taken into account in vector formation, the semantic closeness between words is expressed mathematically.
Figure 2 shows one of the most frequently used images in Word2Vec. The semantic closeness between these words is the mathematical closeness of the vector values to each other. One of the frequently given examples is the equation “king-man + woman = queen”. What happens here is that the vector value obtained as a result of subtracting and adding the vectors from each other is equal to the vector corresponding to the “queen” expression. It can be understood that the words “king” and “queen” are very similar to each other, but vectorial differences arise only because of their gender.
In Word2Vec method, unlike One Hot Encoding and TF-IDF methods, unsupervised learning process is performed. Unlabeled data is trained via artificial neural networks to create the Word2Vec model that generates word vectors. Unlike other methods, the vector size is not as much as the number of unique words in the corpus. The size of the vector can be selected according to the corpus size and the type of project. This is particularly beneficial for very large data. For example, if we assume that there are 300 000 unique words in a large corpus, when vector creation is performed with One Hot Encoding, a vector of 300 000 size is created for each word, with the value of only one element of 1 and the others 0. However, by choosing the vector size 300 (it can be more or less depending on the user’s choice) on the Word2Vec side, unnecessary large size vector operations are avoided.
The vectorization of the “Royal” can be seen in Figure 3. If the word of “Royal” in a five-word sentence is vectorized with One Hot Encoding, the first vector expression (input Vector) is obtained. As can be seen, the size of this vector is as much as the total number of words in the sentence. However, if the vectorization process is done with Word2Vec, this time a vector of three units [5,12,2] is created.
Hotel reviews dataset in kaggle (https://www.kaggle.com/anu0012/hotel-review) was used for applied Word2Vec model training. All of the codes given as examples can be found here.
Since it is case sensitive, all words are converted to lowercase. Then, special characters and stopwords are cleared. The nltk library was used for ineffective words. If desired, these words can also be determined completely manually. An example sentence before these operations are performed is as follows.
“My husband and I have stayed in this hotel a few times. Though not the fanciest hotel, we love the fact that we can walk the — or so miles to Fenway. It is clean and the staff is very accomodating. My only complaint is that the fan in the bathroom was noisy and went on automatically when you turned the light on and we tried to keep the light off as much as possible. We’ve stayed in pricier hotels which charged for internet and breakfast and these are both included. Will stay there again.”
The new situation that will occur after the preprocessing of the data is as follows.
“husband stayed hotel times though fanciest hotel love fact walk miles fenway clean staff accomodating complaint fan bathroom noisy went automatically turned light tried keep light much possible weve stayed pricier hotels charged internet breakfast included stay”
After these processes are completed, Word2Vec training is performed. Parameters used during training:
min_count : The minimum number of occurrences of the target word in the corpus. Especially for very large copruses, keeping this limit high increases the success even more. However, it would be more accurate to keep it small for small datasets.
window : It is the number of neighboring words that will directly affect the vector calculations of the target expression. For example, “He is a very good person.” For window =1 , the words “a” and “good” are effective in the formation of the “very” word vector. When window = 2, the words “is”,“a”,“good” and “person” are effective in creating the “very” word vector.
size : It is the size of the vector to be created for each element.
alpha : Initial learning rate
min_alpha : It is the minimum value at which the learning rate will decrease linearly during training.
sg : Specifies how the training algorithm will work. If value of sg is 1, skip-gram algorithm is used, otherwise the CBOW algorithm is used.
The difference between CBOW (Continuous Bag of Words) vs Skip-gram algorithms can be seen in Figure 4. In the trainings in which the CBOW algorithm is used, the words adjacent to the target word are given as input and the target word itself is obtained as output. In the skip-gram algorithm, while the target word itself is given as input, neighboring words are obtained as output.
workers : Traning can be performed in parallel. The number of cores to be used for this can be determined with the workers parameter.
If you want to see the vector of the word “great” by using the model obtained as a result of the training;
w2v_model["great"]>>>array([ 3.03658217e-01, -1.56424701e-01, -8.23674500e-01,...-1.36196673e-01, 8.55127215e-01, -7.31807232e-01, 1.36362463e-01], dtype=float32)print(w2v_model["great"].shape)>>>(300,)
The 10 words closest to “great”, “terrible”, “boston”, “valet” are as follows.
w2v_model.wv.most_similar(positive=["great"])>>>[('excellent', 0.8094755411148071), ('fantastic', 0.7735758423805237), ('perfect', 0.7473931312561035), ('wonderful', 0.7063912153244019), ('good', 0.7039040327072144), ('amazing', 0.6384587287902832), ('loved', 0.6266685724258423), ('nice', 0.6253951787948608), ('awesome', 0.6186609268188477), ('enjoyed', 0.5889394283294678)]---------------------------------w2v_model.wv.most_similar(positive=["terrible"])>>>[('bad', 0.5275813341140747), ('poor', 0.504431962966919), ('horrible', 0.4722219705581665), ('awful', 0.42389577627182007), ('worst', 0.40153956413269043), ('dirty', 0.3467090427875519), ('disgusting', 0.32588857412338257), ('horrendous', 0.3157917261123657), ('lousy', 0.30114778876304626), ('uncomfortable', 0.3005620837211609)]---------------------------------w2v_model.wv.most_similar(positive=["boston"])>>>[('chicago', 0.519180417060852), ('seattle', 0.5126588940620422), ('dc', 0.4830571711063385), ('bostons', 0.4459514617919922), ('copley', 0.4455355107784271), ('city', 0.44090309739112854), ('newbury', 0.4349810481071472), ('fenway', 0.4237935543060303), ('philadelphia', 0.40892332792282104), ('denver', 0.39840811491012573)]---------------------------------w2v_model.wv.most_similar(positive=["valet"])>>>[('parking', 0.7374086380004883), ('car', 0.6263512969017029), ('garage', 0.6224508285522461), ('retrieving', 0.5173929929733276), ('self', 0.5013973712921143), ('inandout', 0.4847780168056488), ('selfpark', 0.47603434324264526), ('fee', 0.47458043694496155), ('per', 0.4741314947605133), ('parked', 0.4707031846046448)]
The working logic of FastText algorithm is similar to Word2Vec, but the biggest difference is that it also uses N-grams of words during training [4]. While this increases the size and processing time of the model, it also gives the model the ability to predict different variations of words. For example, let’s say that the word “Windows” is in the training dataset and we want to get the vector of the word “Wndows” after the training is finished. If the Word2Vec model is used for these operations, it will give an error that the word “Wndows” does not exist in the dictionary and will not return any vectors. However, if the FastText model is used for this process, both the vector will return and the word of “Windows” will be among the closest words. As explained above, not only the word itself but also N-gram variations are included in training (Example 3-gram expressions for the word “Windows” -> Win, ind, ndo, dow, ows). Although the FastText model is used in many different areas today, it is frequently preferred especially when word embedding techniques are needed in OCR works. Especially compared to other techniques that do not tolerate the slightest OCR error, FastText provides a great advantage in obtaining vectors of even words that are not directly in its own vocabulary. For this reason, it is one step ahead of other alternatives in problems where word mistakes may occur.
The vectorization methods described above are the most commonly used techniques today. Each of them has different uses. In studies where word vectorization is needed, the problem should be determined first, and then the vectorization technique should be preferred according to this problem. As a matter of fact, there are different situations where each technique is strong.
In addition to these, there are also contextual representations such as ELMO and BERT[5]. These issues will be discussed in the next article.
All codes can be found at https://github.com/ademakdogan/word2vec_generator . In this project, word2vec training can be done autonomously according to the column to be determined in any csv file desired. The word2vec model that will be created as a result of the operations is saved under the “model” folder. Example usage can be seen below. This project can also run on docker. Parameters in src/training.py can be optimized according to data size.
python3 src/w2vec.py -c </Users/.../data.csv> -t <target_column_name>
Github : https://github.com/ademakdogan
Linkedin : https://www.linkedin.com/in/adem-akdo%C4%9Fan-948334177/
[1]Stevens, S. S. (1946). “On the Theory of Scales of Measurement”. Science, New Series, 103.2684,677–680.
[2]Aizawa Akiko, (2003). “An information-theoretic perspective of tf–idf measures”. Information Processing and Management. 39 (1), 45–65. doi:10.1016/S0306–4573(02)00021–3
[3]Tomas Mikolov, et al. (2013). “Efficient Estimation of Word Representations in Vector Space”. arXiv:1301.3781
[4]Armand Joulin, Edouard Grave, Piotr Bojanowski, Tomas Mikolov,(2017). “Bag of Tricks for Efficient Text Classification”, Conference: Proceedings of the 15th Conference of the European Chapter of the Association for Computational Linguistics: Volume 2.
[5]Devlin Jacob, Chang Ming-Wei, Lee Kenton, Toutanova Kristina,(2018). “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” | [
{
"code": null,
"e": 472,
"s": 172,
"text": "The words need to be made meaningful for machine learning or deep learning algorithms. Therefore, they must be expressed numerically. Algorithms such as One Hot Encoding, TF-IDF, Word2Vec, FastText enable words to be expressed mathematically as word embedding techniques used to solve such problems."
},
{
"code": null,
"e": 771,
"s": 472,
"text": "The word embedding techniques are used to represent words mathematically. One Hot Encoding, TF-IDF, Word2Vec, FastText are frequently used Word Embedding methods. One of these techniques (in some cases several) is preferred and used according to the status, size and purpose of processing the data."
},
{
"code": null,
"e": 1115,
"s": 771,
"text": "One of the most basic techniques used to represent data numerically is One Hot Encoding technique[1]. In this method, a vector is created in the size of the total number of unique words. The value of vectors is assigned such that the value of each word belonging to its index is 1 and the others are 0. As an example, Figure 1 can be examined."
},
{
"code": null,
"e": 1657,
"s": 1115,
"text": "The column named “X” consists of 3 different words in Figure 1. When One Hot Encoding is applied to this column, 3 different columns representing each expression are created (in other words, 3-unit vectors are created for each row). The column corresponding to the word in each row is filled with the values 1, the others 0. Thus, these expressions are digitized. It is generally used in situations where there is not much verbal data diversity and there is no need to represent the semantic and statistical relationships between the data."
},
{
"code": null,
"e": 2068,
"s": 1657,
"text": "TF-IDF is a statistical measure used to determine the mathematical significance of words in documents[2]. The vectorization process is similar to One Hot Encoding. Alternatively, the value corresponding to the word is assigned a TF-IDF value instead of 1. The TF-IDF value is obtained by multiplying the TF and IDF values. As an example, let’s find the TF-IDF values for 3 documents consisting of 1 sentence."
},
{
"code": null,
"e": 2084,
"s": 2068,
"text": "[He is Walter],"
},
{
"code": null,
"e": 2101,
"s": 2084,
"text": "[He is William],"
},
{
"code": null,
"e": 2131,
"s": 2101,
"text": "[He isn’t Peter or September]"
},
{
"code": null,
"e": 2321,
"s": 2131,
"text": "In the above example, “He” is used in all 3 documents, “is” is in 2 documents, and “or” is in only one document. According to these, let’s find the TF and then the IDF values, respectively."
},
{
"code": null,
"e": 2341,
"s": 2321,
"text": "TF (Term Frequency)"
},
{
"code": null,
"e": 2557,
"s": 2341,
"text": "In the simplest terms, term frequency is the ratio of the number of target terms in the document to the total number of terms in the document. If TF values are calculated according to the above example, it will be"
},
{
"code": null,
"e": 2577,
"s": 2557,
"text": "[0.33, 0.33, 0.33],"
},
{
"code": null,
"e": 2597,
"s": 2577,
"text": "[0.33, 0.33, 0.33],"
},
{
"code": null,
"e": 2628,
"s": 2597,
"text": "[0.20, 0.20, 0.20, 0.20, 0.20]"
},
{
"code": null,
"e": 2660,
"s": 2628,
"text": "IDF (Inverse Documet Frequency)"
},
{
"code": null,
"e": 3078,
"s": 2660,
"text": "The IDF value is the logarithm of the ratio of the total number of documents to the number of documents in which the target term occurs. At this stage, it does not matter how many times the term appears in the document. It is sufficient to determine whether it has passed or not. In this example, the base value of the logarithm to be taken is determined as 10. However, there is no problem in using different values."
},
{
"code": null,
"e": 3097,
"s": 3078,
"text": "“He”: Log(3/3)= 0,"
},
{
"code": null,
"e": 3120,
"s": 3097,
"text": "“is”: Log(3/2):0.1761,"
},
{
"code": null,
"e": 3155,
"s": 3120,
"text": "“or, Peter, ..”: log(3/1) : 0.4771"
},
{
"code": null,
"e": 4026,
"s": 3155,
"text": "Thus, both TF and IDF values were obtained. If vectorization is created with these values, firstly a vector consisting of elements equal to the number of unique words in all documents is created for each document (in this example, there are 8 terms). At this stage, there is a problem to be solved. As seen in the term “He”, since the IDF value is 0, the TF-IDF value will also be zero. However, words that are not included in the document during the vectorization process (for example, the phrase “Peter” is not included in the 1st sentence) will be assigned a value of 0. In order to avoid confusion here, TF-IDF values are smoothed for vectorization. The most common method is to add 1 to the obtained values. Depending on the purpose, normalization can be applied to these values later. If the vectorization process is created according to the above-mentioned;"
},
{
"code": null,
"e": 4075,
"s": 4026,
"text": "[1. , 1.1761 , 1.4771 , 0. , 0. , 0. , 0. , 0.],"
},
{
"code": null,
"e": 4124,
"s": 4075,
"text": "[1. , 1.1761 , 0. , 1.4771 , 0. , 0. , 0. , 0.],"
},
{
"code": null,
"e": 4180,
"s": 4124,
"text": "[1. , 0. , 0. , 0. , 1.4771 , 1.4771, 1.4771 , 1.4771],"
},
{
"code": null,
"e": 4778,
"s": 4180,
"text": "Word2vec is another of the frequently used word embedding techniques. The entire corpus is scanned, and the vector creation process is performed by determining which words the target word occurs with more often[3]. In this way, the semantic closeness of the words to each other is also revealed. For example, let each letter in the sequences ..x y A z w.. , .. x y B z k.. and ..x l C d m... represent a word. In this case, word_A will be closer to word_B than word_C. When this situation is taken into account in vector formation, the semantic closeness between words is expressed mathematically."
},
{
"code": null,
"e": 5368,
"s": 4778,
"text": "Figure 2 shows one of the most frequently used images in Word2Vec. The semantic closeness between these words is the mathematical closeness of the vector values to each other. One of the frequently given examples is the equation “king-man + woman = queen”. What happens here is that the vector value obtained as a result of subtracting and adding the vectors from each other is equal to the vector corresponding to the “queen” expression. It can be understood that the words “king” and “queen” are very similar to each other, but vectorial differences arise only because of their gender."
},
{
"code": null,
"e": 6255,
"s": 5368,
"text": "In Word2Vec method, unlike One Hot Encoding and TF-IDF methods, unsupervised learning process is performed. Unlabeled data is trained via artificial neural networks to create the Word2Vec model that generates word vectors. Unlike other methods, the vector size is not as much as the number of unique words in the corpus. The size of the vector can be selected according to the corpus size and the type of project. This is particularly beneficial for very large data. For example, if we assume that there are 300 000 unique words in a large corpus, when vector creation is performed with One Hot Encoding, a vector of 300 000 size is created for each word, with the value of only one element of 1 and the others 0. However, by choosing the vector size 300 (it can be more or less depending on the user’s choice) on the Word2Vec side, unnecessary large size vector operations are avoided."
},
{
"code": null,
"e": 6666,
"s": 6255,
"text": "The vectorization of the “Royal” can be seen in Figure 3. If the word of “Royal” in a five-word sentence is vectorized with One Hot Encoding, the first vector expression (input Vector) is obtained. As can be seen, the size of this vector is as much as the total number of words in the sentence. However, if the vectorization process is done with Word2Vec, this time a vector of three units [5,12,2] is created."
},
{
"code": null,
"e": 6844,
"s": 6666,
"text": "Hotel reviews dataset in kaggle (https://www.kaggle.com/anu0012/hotel-review) was used for applied Word2Vec model training. All of the codes given as examples can be found here."
},
{
"code": null,
"e": 7152,
"s": 6844,
"text": "Since it is case sensitive, all words are converted to lowercase. Then, special characters and stopwords are cleared. The nltk library was used for ineffective words. If desired, these words can also be determined completely manually. An example sentence before these operations are performed is as follows."
},
{
"code": null,
"e": 7647,
"s": 7152,
"text": "“My husband and I have stayed in this hotel a few times. Though not the fanciest hotel, we love the fact that we can walk the — or so miles to Fenway. It is clean and the staff is very accomodating. My only complaint is that the fan in the bathroom was noisy and went on automatically when you turned the light on and we tried to keep the light off as much as possible. We’ve stayed in pricier hotels which charged for internet and breakfast and these are both included. Will stay there again.”"
},
{
"code": null,
"e": 7732,
"s": 7647,
"text": "The new situation that will occur after the preprocessing of the data is as follows."
},
{
"code": null,
"e": 7996,
"s": 7732,
"text": "“husband stayed hotel times though fanciest hotel love fact walk miles fenway clean staff accomodating complaint fan bathroom noisy went automatically turned light tried keep light much possible weve stayed pricier hotels charged internet breakfast included stay”"
},
{
"code": null,
"e": 8098,
"s": 7996,
"text": "After these processes are completed, Word2Vec training is performed. Parameters used during training:"
},
{
"code": null,
"e": 8343,
"s": 8098,
"text": "min_count : The minimum number of occurrences of the target word in the corpus. Especially for very large copruses, keeping this limit high increases the success even more. However, it would be more accurate to keep it small for small datasets."
},
{
"code": null,
"e": 8712,
"s": 8343,
"text": "window : It is the number of neighboring words that will directly affect the vector calculations of the target expression. For example, “He is a very good person.” For window =1 , the words “a” and “good” are effective in the formation of the “very” word vector. When window = 2, the words “is”,“a”,“good” and “person” are effective in creating the “very” word vector."
},
{
"code": null,
"e": 8780,
"s": 8712,
"text": "size : It is the size of the vector to be created for each element."
},
{
"code": null,
"e": 8810,
"s": 8780,
"text": "alpha : Initial learning rate"
},
{
"code": null,
"e": 8913,
"s": 8810,
"text": "min_alpha : It is the minimum value at which the learning rate will decrease linearly during training."
},
{
"code": null,
"e": 9054,
"s": 8913,
"text": "sg : Specifies how the training algorithm will work. If value of sg is 1, skip-gram algorithm is used, otherwise the CBOW algorithm is used."
},
{
"code": null,
"e": 9436,
"s": 9054,
"text": "The difference between CBOW (Continuous Bag of Words) vs Skip-gram algorithms can be seen in Figure 4. In the trainings in which the CBOW algorithm is used, the words adjacent to the target word are given as input and the target word itself is obtained as output. In the skip-gram algorithm, while the target word itself is given as input, neighboring words are obtained as output."
},
{
"code": null,
"e": 9570,
"s": 9436,
"text": "workers : Traning can be performed in parallel. The number of cores to be used for this can be determined with the workers parameter."
},
{
"code": null,
"e": 9677,
"s": 9570,
"text": "If you want to see the vector of the word “great” by using the model obtained as a result of the training;"
},
{
"code": null,
"e": 9887,
"s": 9677,
"text": "w2v_model[\"great\"]>>>array([ 3.03658217e-01, -1.56424701e-01, -8.23674500e-01,...-1.36196673e-01, 8.55127215e-01, -7.31807232e-01, 1.36362463e-01], dtype=float32)print(w2v_model[\"great\"].shape)>>>(300,)"
},
{
"code": null,
"e": 9966,
"s": 9887,
"text": "The 10 words closest to “great”, “terrible”, “boston”, “valet” are as follows."
},
{
"code": null,
"e": 11567,
"s": 9966,
"text": "w2v_model.wv.most_similar(positive=[\"great\"])>>>[('excellent', 0.8094755411148071), ('fantastic', 0.7735758423805237), ('perfect', 0.7473931312561035), ('wonderful', 0.7063912153244019), ('good', 0.7039040327072144), ('amazing', 0.6384587287902832), ('loved', 0.6266685724258423), ('nice', 0.6253951787948608), ('awesome', 0.6186609268188477), ('enjoyed', 0.5889394283294678)]---------------------------------w2v_model.wv.most_similar(positive=[\"terrible\"])>>>[('bad', 0.5275813341140747), ('poor', 0.504431962966919), ('horrible', 0.4722219705581665), ('awful', 0.42389577627182007), ('worst', 0.40153956413269043), ('dirty', 0.3467090427875519), ('disgusting', 0.32588857412338257), ('horrendous', 0.3157917261123657), ('lousy', 0.30114778876304626), ('uncomfortable', 0.3005620837211609)]---------------------------------w2v_model.wv.most_similar(positive=[\"boston\"])>>>[('chicago', 0.519180417060852), ('seattle', 0.5126588940620422), ('dc', 0.4830571711063385), ('bostons', 0.4459514617919922), ('copley', 0.4455355107784271), ('city', 0.44090309739112854), ('newbury', 0.4349810481071472), ('fenway', 0.4237935543060303), ('philadelphia', 0.40892332792282104), ('denver', 0.39840811491012573)]---------------------------------w2v_model.wv.most_similar(positive=[\"valet\"])>>>[('parking', 0.7374086380004883), ('car', 0.6263512969017029), ('garage', 0.6224508285522461), ('retrieving', 0.5173929929733276), ('self', 0.5013973712921143), ('inandout', 0.4847780168056488), ('selfpark', 0.47603434324264526), ('fee', 0.47458043694496155), ('per', 0.4741314947605133), ('parked', 0.4707031846046448)]"
},
{
"code": null,
"e": 12966,
"s": 11567,
"text": "The working logic of FastText algorithm is similar to Word2Vec, but the biggest difference is that it also uses N-grams of words during training [4]. While this increases the size and processing time of the model, it also gives the model the ability to predict different variations of words. For example, let’s say that the word “Windows” is in the training dataset and we want to get the vector of the word “Wndows” after the training is finished. If the Word2Vec model is used for these operations, it will give an error that the word “Wndows” does not exist in the dictionary and will not return any vectors. However, if the FastText model is used for this process, both the vector will return and the word of “Windows” will be among the closest words. As explained above, not only the word itself but also N-gram variations are included in training (Example 3-gram expressions for the word “Windows” -> Win, ind, ndo, dow, ows). Although the FastText model is used in many different areas today, it is frequently preferred especially when word embedding techniques are needed in OCR works. Especially compared to other techniques that do not tolerate the slightest OCR error, FastText provides a great advantage in obtaining vectors of even words that are not directly in its own vocabulary. For this reason, it is one step ahead of other alternatives in problems where word mistakes may occur."
},
{
"code": null,
"e": 13341,
"s": 12966,
"text": "The vectorization methods described above are the most commonly used techniques today. Each of them has different uses. In studies where word vectorization is needed, the problem should be determined first, and then the vectorization technique should be preferred according to this problem. As a matter of fact, there are different situations where each technique is strong."
},
{
"code": null,
"e": 13483,
"s": 13341,
"text": "In addition to these, there are also contextual representations such as ELMO and BERT[5]. These issues will be discussed in the next article."
},
{
"code": null,
"e": 13933,
"s": 13483,
"text": "All codes can be found at https://github.com/ademakdogan/word2vec_generator . In this project, word2vec training can be done autonomously according to the column to be determined in any csv file desired. The word2vec model that will be created as a result of the operations is saved under the “model” folder. Example usage can be seen below. This project can also run on docker. Parameters in src/training.py can be optimized according to data size."
},
{
"code": null,
"e": 14003,
"s": 13933,
"text": "python3 src/w2vec.py -c </Users/.../data.csv> -t <target_column_name>"
},
{
"code": null,
"e": 14043,
"s": 14003,
"text": "Github : https://github.com/ademakdogan"
},
{
"code": null,
"e": 14111,
"s": 14043,
"text": "Linkedin : https://www.linkedin.com/in/adem-akdo%C4%9Fan-948334177/"
},
{
"code": null,
"e": 14218,
"s": 14111,
"text": "[1]Stevens, S. S. (1946). “On the Theory of Scales of Measurement”. Science, New Series, 103.2684,677–680."
},
{
"code": null,
"e": 14390,
"s": 14218,
"text": "[2]Aizawa Akiko, (2003). “An information-theoretic perspective of tf–idf measures”. Information Processing and Management. 39 (1), 45–65. doi:10.1016/S0306–4573(02)00021–3"
},
{
"code": null,
"e": 14503,
"s": 14390,
"text": "[3]Tomas Mikolov, et al. (2013). “Efficient Estimation of Word Representations in Vector Space”. arXiv:1301.3781"
},
{
"code": null,
"e": 14758,
"s": 14503,
"text": "[4]Armand Joulin, Edouard Grave, Piotr Bojanowski, Tomas Mikolov,(2017). “Bag of Tricks for Efficient Text Classification”, Conference: Proceedings of the 15th Conference of the European Chapter of the Association for Computational Linguistics: Volume 2."
}
]
|
What is a Webcrawler and where is it used? - GeeksforGeeks | 09 Jul, 2021
Web Crawler is a bot that downloads the content from the internet and indexes it. The main purpose of this bot is to learn about the different web pages on the internet. This kind of bots is mostly operated by search engines. By applying the search algorithms to the data collected by the web crawlers, search engines can provide the relevant links as the response for the request requested by the user. In this article, let’s discuss how the web crawler is implemented.
Webcrawler is a very important application of the Breadth-First Search Algorithm. The idea is that the whole internet can be represented by a directed graph:
with vertices -> Domains/ URLs/ Websites.
edges -> Connections.
Example:
Approach: The idea behind the working of this algorithm is to parse the raw HTML of the website and look for other URL in the obtained data. If there is a URL, then add it to the queue and visit them in breadth-first search manner.
Note: This code will not work on an online IDE due to proxy issues. Try to run on your local computer.
Java
// Java program to illustrate the WebCrawler import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.URL;import java.util.HashSet;import java.util.LinkedList;import java.util.List;import java.util.Queue;import java.util.regex.Matcher;import java.util.regex.Pattern; // Class Contains the functions// required for WebCrowlerclass WebCrowler { // To store the URLs in the / /FIFO order required for BFS private Queue<String> queue; // To store visited URls private HashSet<String> discovered_websites; // Constructor for initializing the // required variables public WebCrowler() { this.queue = new LinkedList<>(); this.discovered_websites = new HashSet<>(); } // Function to start the BFS and // discover all URLs public void discover(String root) { // Storing the root URL to // initiate BFS. this.queue.add(root); this.discovered_websites.add(root); // It will loop until queue is empty while (!queue.isEmpty()) { // To store the URL present in // the front of the queue String v = queue.remove(); // To store the raw HTML of // the website String raw = readUrl(v); // Regular expression for a URL String regex = "https://(\\w+\\.)*(\\w+)"; // To store the pattern of the // URL formed by regex Pattern pattern = Pattern.compile(regex); // To extract all the URL that // matches the pattern in raw Matcher matcher = pattern.matcher(raw); // It will loop until all the URLs // in the current website get stored // in the queue while (matcher.find()) { // To store the next URL in raw String actual = matcher.group(); // It will check whether this URL is // visited or not if (!discovered_websites .contains(actual)) { // If not visited it will add // this URL in queue, print it // and mark it as visited discovered_websites .add(actual); System.out.println( "Website found: " + actual); queue.add(actual); } } } } // Function to return the raw HTML // of the current website public String readUrl(String v) { // Initializing empty string String raw = ""; // Use try-catch block to handle // any exceptions given by this code try { // Convert the string in URL URL url = new URL(v); // Read the HTML from website BufferedReader be = new BufferedReader( new InputStreamReader( url.openStream())); // To store the input // from the website String input = ""; // Read the HTML line by line // and append it to raw while ((input = br.readLine()) != null) { raw += input; } // Close BufferedReader br.close(); } catch (Exception ex) { ex.printStackTrace(); } return raw; }} // Driver codepublic class Main { // Driver Code public static void main(String[] args) { // Creating Object of WebCrawler WebCrowler web_crowler = new WebCrowler(); // Given URL String root = "https:// www.google.com"; // Method call web_crowler.discover(root); }}
Output:
Website found: https://www.google.com
Website found: https://www.facebook.com
Website found: https://www.amazon.com
Website found: https://www.microsoft.com
Website found: https://www.apple.com
Applications: This kind of web crawler is used to acquire the important parameters of the web like:
What are the frequently visited websites?What are the websites that are important in the network as a whole?Useful Information on social networks: Facebook, Twitter... etc.Who is the most popular person in a group of people?Who is the most important software engineer in a company?
What are the frequently visited websites?
What are the websites that are important in the network as a whole?
Useful Information on social networks: Facebook, Twitter... etc.
Who is the most popular person in a group of people?
Who is the most important software engineer in a company?
abhishek0719kadiyan
BFS
Algorithms
Data Structures
Graph
Java
Pattern Searching
Queue
Searching
Strings
Web Technologies
Write From Home
Data Structures
Searching
Strings
Java
Graph
Queue
Pattern Searching
BFS
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
Quadratic Probing in Hashing
Introduction to Algorithms
Uniform-Cost Search (Dijkstra for large Graphs)
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Doubly Linked List | Set 1 (Introduction and Insertion)
Implementing a Linked List in Java using Class
Comparison between Adjacency List and Adjacency Matrix representation of Graph
Introduction to Algorithms | [
{
"code": null,
"e": 24585,
"s": 24557,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 25057,
"s": 24585,
"text": "Web Crawler is a bot that downloads the content from the internet and indexes it. The main purpose of this bot is to learn about the different web pages on the internet. This kind of bots is mostly operated by search engines. By applying the search algorithms to the data collected by the web crawlers, search engines can provide the relevant links as the response for the request requested by the user. In this article, let’s discuss how the web crawler is implemented. "
},
{
"code": null,
"e": 25216,
"s": 25057,
"text": "Webcrawler is a very important application of the Breadth-First Search Algorithm. The idea is that the whole internet can be represented by a directed graph: "
},
{
"code": null,
"e": 25258,
"s": 25216,
"text": "with vertices -> Domains/ URLs/ Websites."
},
{
"code": null,
"e": 25280,
"s": 25258,
"text": "edges -> Connections."
},
{
"code": null,
"e": 25291,
"s": 25280,
"text": "Example: "
},
{
"code": null,
"e": 25525,
"s": 25291,
"text": "Approach: The idea behind the working of this algorithm is to parse the raw HTML of the website and look for other URL in the obtained data. If there is a URL, then add it to the queue and visit them in breadth-first search manner. "
},
{
"code": null,
"e": 25628,
"s": 25525,
"text": "Note: This code will not work on an online IDE due to proxy issues. Try to run on your local computer."
},
{
"code": null,
"e": 25633,
"s": 25628,
"text": "Java"
},
{
"code": "// Java program to illustrate the WebCrawler import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.URL;import java.util.HashSet;import java.util.LinkedList;import java.util.List;import java.util.Queue;import java.util.regex.Matcher;import java.util.regex.Pattern; // Class Contains the functions// required for WebCrowlerclass WebCrowler { // To store the URLs in the / /FIFO order required for BFS private Queue<String> queue; // To store visited URls private HashSet<String> discovered_websites; // Constructor for initializing the // required variables public WebCrowler() { this.queue = new LinkedList<>(); this.discovered_websites = new HashSet<>(); } // Function to start the BFS and // discover all URLs public void discover(String root) { // Storing the root URL to // initiate BFS. this.queue.add(root); this.discovered_websites.add(root); // It will loop until queue is empty while (!queue.isEmpty()) { // To store the URL present in // the front of the queue String v = queue.remove(); // To store the raw HTML of // the website String raw = readUrl(v); // Regular expression for a URL String regex = \"https://(\\\\w+\\\\.)*(\\\\w+)\"; // To store the pattern of the // URL formed by regex Pattern pattern = Pattern.compile(regex); // To extract all the URL that // matches the pattern in raw Matcher matcher = pattern.matcher(raw); // It will loop until all the URLs // in the current website get stored // in the queue while (matcher.find()) { // To store the next URL in raw String actual = matcher.group(); // It will check whether this URL is // visited or not if (!discovered_websites .contains(actual)) { // If not visited it will add // this URL in queue, print it // and mark it as visited discovered_websites .add(actual); System.out.println( \"Website found: \" + actual); queue.add(actual); } } } } // Function to return the raw HTML // of the current website public String readUrl(String v) { // Initializing empty string String raw = \"\"; // Use try-catch block to handle // any exceptions given by this code try { // Convert the string in URL URL url = new URL(v); // Read the HTML from website BufferedReader be = new BufferedReader( new InputStreamReader( url.openStream())); // To store the input // from the website String input = \"\"; // Read the HTML line by line // and append it to raw while ((input = br.readLine()) != null) { raw += input; } // Close BufferedReader br.close(); } catch (Exception ex) { ex.printStackTrace(); } return raw; }} // Driver codepublic class Main { // Driver Code public static void main(String[] args) { // Creating Object of WebCrawler WebCrowler web_crowler = new WebCrowler(); // Given URL String root = \"https:// www.google.com\"; // Method call web_crowler.discover(root); }}",
"e": 29524,
"s": 25633,
"text": null
},
{
"code": null,
"e": 29533,
"s": 29524,
"text": "Output: "
},
{
"code": null,
"e": 29727,
"s": 29533,
"text": "Website found: https://www.google.com\nWebsite found: https://www.facebook.com\nWebsite found: https://www.amazon.com\nWebsite found: https://www.microsoft.com\nWebsite found: https://www.apple.com"
},
{
"code": null,
"e": 29828,
"s": 29727,
"text": "Applications: This kind of web crawler is used to acquire the important parameters of the web like: "
},
{
"code": null,
"e": 30110,
"s": 29828,
"text": "What are the frequently visited websites?What are the websites that are important in the network as a whole?Useful Information on social networks: Facebook, Twitter... etc.Who is the most popular person in a group of people?Who is the most important software engineer in a company?"
},
{
"code": null,
"e": 30152,
"s": 30110,
"text": "What are the frequently visited websites?"
},
{
"code": null,
"e": 30220,
"s": 30152,
"text": "What are the websites that are important in the network as a whole?"
},
{
"code": null,
"e": 30285,
"s": 30220,
"text": "Useful Information on social networks: Facebook, Twitter... etc."
},
{
"code": null,
"e": 30338,
"s": 30285,
"text": "Who is the most popular person in a group of people?"
},
{
"code": null,
"e": 30396,
"s": 30338,
"text": "Who is the most important software engineer in a company?"
},
{
"code": null,
"e": 30418,
"s": 30398,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 30422,
"s": 30418,
"text": "BFS"
},
{
"code": null,
"e": 30433,
"s": 30422,
"text": "Algorithms"
},
{
"code": null,
"e": 30449,
"s": 30433,
"text": "Data Structures"
},
{
"code": null,
"e": 30455,
"s": 30449,
"text": "Graph"
},
{
"code": null,
"e": 30460,
"s": 30455,
"text": "Java"
},
{
"code": null,
"e": 30478,
"s": 30460,
"text": "Pattern Searching"
},
{
"code": null,
"e": 30484,
"s": 30478,
"text": "Queue"
},
{
"code": null,
"e": 30494,
"s": 30484,
"text": "Searching"
},
{
"code": null,
"e": 30502,
"s": 30494,
"text": "Strings"
},
{
"code": null,
"e": 30519,
"s": 30502,
"text": "Web Technologies"
},
{
"code": null,
"e": 30535,
"s": 30519,
"text": "Write From Home"
},
{
"code": null,
"e": 30551,
"s": 30535,
"text": "Data Structures"
},
{
"code": null,
"e": 30561,
"s": 30551,
"text": "Searching"
},
{
"code": null,
"e": 30569,
"s": 30561,
"text": "Strings"
},
{
"code": null,
"e": 30574,
"s": 30569,
"text": "Java"
},
{
"code": null,
"e": 30580,
"s": 30574,
"text": "Graph"
},
{
"code": null,
"e": 30586,
"s": 30580,
"text": "Queue"
},
{
"code": null,
"e": 30604,
"s": 30586,
"text": "Pattern Searching"
},
{
"code": null,
"e": 30608,
"s": 30604,
"text": "BFS"
},
{
"code": null,
"e": 30619,
"s": 30608,
"text": "Algorithms"
},
{
"code": null,
"e": 30717,
"s": 30619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30726,
"s": 30717,
"text": "Comments"
},
{
"code": null,
"e": 30739,
"s": 30726,
"text": "Old Comments"
},
{
"code": null,
"e": 30788,
"s": 30739,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30817,
"s": 30788,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 30844,
"s": 30817,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 30892,
"s": 30844,
"text": "Uniform-Cost Search (Dijkstra for large Graphs)"
},
{
"code": null,
"e": 30917,
"s": 30892,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 30966,
"s": 30917,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 31022,
"s": 30966,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 31069,
"s": 31022,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 31148,
"s": 31069,
"text": "Comparison between Adjacency List and Adjacency Matrix representation of Graph"
}
]
|
PHP Prime Number Program | Theory of Computation
A prime number is a whole number greater than 1 whose only factors are 1 and itself, like -2, 3, 5, 7, 11 etc. For example, 17 is a prime number because it is only divisible by 1 and 17. On the other hand, 18 is not a prime number because it is divisible by 2, 3, 6, 9 and the number itself. These are different ways to print prime number between 1 to 100 in the PHP programming language.
The following code prints a list of prime numbers between 1 and 100 (that is, numbers not divisible by something other than 1 or the number itself) using a while loop.
<?php
$limit = 100;
$init = 2;
while(TRUE)
{
$div = 2;
if($init > $limit)
{
break;
}
while(TRUE)
{
if($div > sqrt($init))
{
echo $init." ";
break;
}
if($init % $div == 0)
{
break;
}
$div = $div + 1;
}
$init = $init + 1;
}
?>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
In the above code, we have two while loops. The inner while loop does the testing with each possible divisor. If the inner loop finds a divisor, the number is not prime, so it breaks out without printing anything, and if the testing gets as high as the square root of the number, we can assume that the number is prime. The outer loop works through all the numbers between 1 and 100. This loop is broken when we have reached the breaking point of numbers to test.
Here, we have created a function 'checkPrime()' to check whether the number is prime or not. We loop over the number range (1 to 100) and pass each as a parameter to the function to check whether a number is prime or not.
<?php
function checkPrime($num)
{
if ($num == 1)
return 0;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
return 0;
}
return 1;
}
echo '<h2>Prime Numbers between 1 and 100</h2> ';
for($num = 1; $num <= 100; $num++) {
$flag = checkPrime($num);
if ($flag == 1) {
echo $num." ";
}
}
?>
Prime Numbers between 1 and 100 :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 | [
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 501,
"s": 112,
"text": "A prime number is a whole number greater than 1 whose only factors are 1 and itself, like -2, 3, 5, 7, 11 etc. For example, 17 is a prime number because it is only divisible by 1 and 17. On the other hand, 18 is not a prime number because it is divisible by 2, 3, 6, 9 and the number itself. These are different ways to print prime number between 1 to 100 in the PHP programming language."
},
{
"code": null,
"e": 669,
"s": 501,
"text": "The following code prints a list of prime numbers between 1 and 100 (that is, numbers not divisible by something other than 1 or the number itself) using a while loop."
},
{
"code": null,
"e": 959,
"s": 669,
"text": "<?php \n\t$limit = 100;\n\t$init = 2;\n\t\n\twhile(TRUE)\n\t{\n\t\t$div = 2;\n\t\tif($init > $limit) \n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\twhile(TRUE)\n\t\t{\n\t\t\tif($div > sqrt($init))\n\t\t\t{\n\t\t\t\techo $init.\" \";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif($init % $div == 0) \n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t$div = $div + 1;\n\t\t}\n\t\t$init = $init + 1;\n\t}\n?>\n"
},
{
"code": null,
"e": 1054,
"s": 959,
"text": "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97"
},
{
"code": null,
"e": 1518,
"s": 1054,
"text": "In the above code, we have two while loops. The inner while loop does the testing with each possible divisor. If the inner loop finds a divisor, the number is not prime, so it breaks out without printing anything, and if the testing gets as high as the square root of the number, we can assume that the number is prime. The outer loop works through all the numbers between 1 and 100. This loop is broken when we have reached the breaking point of numbers to test."
},
{
"code": null,
"e": 1740,
"s": 1518,
"text": "Here, we have created a function 'checkPrime()' to check whether the number is prime or not. We loop over the number range (1 to 100) and pass each as a parameter to the function to check whether a number is prime or not."
},
{
"code": null,
"e": 2070,
"s": 1740,
"text": "<?php\nfunction checkPrime($num)\n{\n if ($num == 1)\n return 0;\n for ($i = 2; $i <= $num/2; $i++)\n {\n if ($num % $i == 0)\n return 0;\n }\n return 1;\n}\n\necho '<h2>Prime Numbers between 1 and 100</h2> ';\nfor($num = 1; $num <= 100; $num++) {\n\t$flag = checkPrime($num);\n\tif ($flag == 1) {\n\t\techo $num.\" \";\n\t}\t\n} \n?>"
}
]
|
Bootstrap alert-danger class | The alert-danger class in Bootstrap is used to set danger action.
You can try to run the following code to implement the alert-danger class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "alert alert-danger">This is danger action!</div>
</body>
</html> | [
{
"code": null,
"e": 1128,
"s": 1062,
"text": "The alert-danger class in Bootstrap is used to set danger action."
},
{
"code": null,
"e": 1217,
"s": 1128,
"text": "You can try to run the following code to implement the alert-danger class in Bootstrap −"
},
{
"code": null,
"e": 1227,
"s": 1217,
"text": "Live Demo"
},
{
"code": null,
"e": 1600,
"s": 1227,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"alert alert-danger\">This is danger action!</div>\n </body>\n</html>"
}
]
|
AngularJS and W3.CSS - GeeksforGeeks | 27 Oct, 2021
What is W3.CSS?
W3.CSS is a modern framework with built-in reponsiveness and easy to learn and use compared to other CSS framework.
Its aim is to speed up and simplify web development and support modern responsive devices like Mobile, Laptop, Tablet and Desktop
W3.CSS was designed to be a high quality alternative to Bootstrap and is developed by w3school.com
What is angularJS?
AngularJS is a structural framework for dynamic web apps which extends HTML with new attributes.
It provides automated testing and is perfect for single page application
It gives application a clean structure and lot of reusable code.
Most important part of W3.CSS :
w3-container: adds a 16px left and right padding to any HTML element.w3-fontSize : w3-tiny, w3-small, w3-medium(default), w3-large, w3-xlarge, w3-xlarge, w3-xxlarge, w3-xxxlarge, w3-jumbo.w3-text: It provides css features like alignment, opacity, shadow, special effect.w3-input: It provides input cards, coloured labels, border, checkbox, radio buttons, etc
w3-container: adds a 16px left and right padding to any HTML element.
w3-fontSize : w3-tiny, w3-small, w3-medium(default), w3-large, w3-xlarge, w3-xlarge, w3-xxlarge, w3-xxxlarge, w3-jumbo.
w3-text: It provides css features like alignment, opacity, shadow, special effect.
w3-input: It provides input cards, coloured labels, border, checkbox, radio buttons, etc
Example:
html
<!DOCTYPE html><html><head> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <style> .pad { margin: 0 0 0 0; } </style> </head> <body ng-app="myApp" ng-controller="myCtrl"> <div class="w3-container "> <p class="w3-jumbo w3-text-green pad" align="center">GeeksforGeeks</p> <p class="w3-large w3-text-green pad" align="center" > A computer science portal for geeks</p> <form> <h3 align="center" > Enter user details </h3> <label>First Name:</label> <input class="w3-input w3-border w3-round-xxlarge" type="text" ng-model="fname" placeholder="First Name"></br> <label>Last Name:</label> <input class="w3-input w3-border w3-round-xxlarge" type="text" ng-model="lname" placeholder="Last Name"></br> <label>Email id:</label> <input class="w3-input w3-border w3-round-xxlarge" type="email" ng-model="mail" placeholder="Email id"></br> <label>Password:</label> <input class="w3-input w3-border w3-round-xxlarge" type="password" ng-model="pass" placeholder="Password"></br> <p align="center"> <button class="w3-btn w3-green w3-ripple " > Save </button></p> </form> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.fname = "Fname"; $scope.lname = "Lname"; $scope.mail = "[email protected]"; $scope.pass = "password"; }); </script></body></html>
Output:
GeeksforGeeks login page
ruhelaa48
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Top 10 Angular Libraries For Web Developers
Angular | keyup event
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 28271,
"s": 28243,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 28287,
"s": 28271,
"text": "What is W3.CSS?"
},
{
"code": null,
"e": 28403,
"s": 28287,
"text": "W3.CSS is a modern framework with built-in reponsiveness and easy to learn and use compared to other CSS framework."
},
{
"code": null,
"e": 28533,
"s": 28403,
"text": "Its aim is to speed up and simplify web development and support modern responsive devices like Mobile, Laptop, Tablet and Desktop"
},
{
"code": null,
"e": 28632,
"s": 28533,
"text": "W3.CSS was designed to be a high quality alternative to Bootstrap and is developed by w3school.com"
},
{
"code": null,
"e": 28651,
"s": 28632,
"text": "What is angularJS?"
},
{
"code": null,
"e": 28748,
"s": 28651,
"text": "AngularJS is a structural framework for dynamic web apps which extends HTML with new attributes."
},
{
"code": null,
"e": 28821,
"s": 28748,
"text": "It provides automated testing and is perfect for single page application"
},
{
"code": null,
"e": 28886,
"s": 28821,
"text": "It gives application a clean structure and lot of reusable code."
},
{
"code": null,
"e": 28918,
"s": 28886,
"text": "Most important part of W3.CSS :"
},
{
"code": null,
"e": 29277,
"s": 28918,
"text": "w3-container: adds a 16px left and right padding to any HTML element.w3-fontSize : w3-tiny, w3-small, w3-medium(default), w3-large, w3-xlarge, w3-xlarge, w3-xxlarge, w3-xxxlarge, w3-jumbo.w3-text: It provides css features like alignment, opacity, shadow, special effect.w3-input: It provides input cards, coloured labels, border, checkbox, radio buttons, etc"
},
{
"code": null,
"e": 29347,
"s": 29277,
"text": "w3-container: adds a 16px left and right padding to any HTML element."
},
{
"code": null,
"e": 29467,
"s": 29347,
"text": "w3-fontSize : w3-tiny, w3-small, w3-medium(default), w3-large, w3-xlarge, w3-xlarge, w3-xxlarge, w3-xxxlarge, w3-jumbo."
},
{
"code": null,
"e": 29550,
"s": 29467,
"text": "w3-text: It provides css features like alignment, opacity, shadow, special effect."
},
{
"code": null,
"e": 29639,
"s": 29550,
"text": "w3-input: It provides input cards, coloured labels, border, checkbox, radio buttons, etc"
},
{
"code": null,
"e": 29648,
"s": 29639,
"text": "Example:"
},
{
"code": null,
"e": 29653,
"s": 29648,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><head> <link rel=\"stylesheet\" href=\"https://www.w3schools.com/w3css/4/w3.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <style> .pad { margin: 0 0 0 0; } </style> </head> <body ng-app=\"myApp\" ng-controller=\"myCtrl\"> <div class=\"w3-container \"> <p class=\"w3-jumbo w3-text-green pad\" align=\"center\">GeeksforGeeks</p> <p class=\"w3-large w3-text-green pad\" align=\"center\" > A computer science portal for geeks</p> <form> <h3 align=\"center\" > Enter user details </h3> <label>First Name:</label> <input class=\"w3-input w3-border w3-round-xxlarge\" type=\"text\" ng-model=\"fname\" placeholder=\"First Name\"></br> <label>Last Name:</label> <input class=\"w3-input w3-border w3-round-xxlarge\" type=\"text\" ng-model=\"lname\" placeholder=\"Last Name\"></br> <label>Email id:</label> <input class=\"w3-input w3-border w3-round-xxlarge\" type=\"email\" ng-model=\"mail\" placeholder=\"Email id\"></br> <label>Password:</label> <input class=\"w3-input w3-border w3-round-xxlarge\" type=\"password\" ng-model=\"pass\" placeholder=\"Password\"></br> <p align=\"center\"> <button class=\"w3-btn w3-green w3-ripple \" > Save </button></p> </form> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.fname = \"Fname\"; $scope.lname = \"Lname\"; $scope.mail = \"[email protected]\"; $scope.pass = \"password\"; }); </script></body></html>",
"e": 31517,
"s": 29653,
"text": null
},
{
"code": null,
"e": 31525,
"s": 31517,
"text": "Output:"
},
{
"code": null,
"e": 31550,
"s": 31525,
"text": "GeeksforGeeks login page"
},
{
"code": null,
"e": 31560,
"s": 31550,
"text": "ruhelaa48"
},
{
"code": null,
"e": 31575,
"s": 31560,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 31582,
"s": 31575,
"text": "Picked"
},
{
"code": null,
"e": 31592,
"s": 31582,
"text": "AngularJS"
},
{
"code": null,
"e": 31609,
"s": 31592,
"text": "Web Technologies"
},
{
"code": null,
"e": 31707,
"s": 31609,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31727,
"s": 31707,
"text": "Angular File Upload"
},
{
"code": null,
"e": 31771,
"s": 31727,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 31793,
"s": 31771,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 31824,
"s": 31793,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 31866,
"s": 31824,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 31908,
"s": 31866,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31941,
"s": 31908,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31984,
"s": 31941,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32046,
"s": 31984,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Time Series Analysis using Pandas in Python | by Dr. Varshita Sher | Towards Data Science | Right off the bat, time-series data is not your average dataset! You might have worked with housing data wherein each row represents features of a particular house (such as total area, number of bedrooms, year in which it was built) or student dataset wherein each row represents such information about a student (such as age, gender, prior GPA). In all these datasets, the common thing is that all samples (or rows in your dataset), in general, are independent of each other. What sets these datasets apart from time-series data is that in the latter, each row represents a point in time so naturally, there is some inherent ordering to the data. This is how a typical time-series data looks like:
In the above dataset, we have recorded some value (say the temperature) for each day of the month of January in the year 1991. You can, of course, have more values collected on a particular day in addition to the temperature, such as humidity that day or the wind speed.
We will be working with the publicly available dataset Open Power System Data. You can download the data here. It contains electricity consumption, wind power production, and solar power production for 2006–2017.
Loading the dataset into Jupyter Notebook:
url='https://raw.githubusercontent.com/jenfly/opsd/master/opsd_germany_daily.csv'data = pd.read_csv(url,sep=",")
This is how our data looks like:
If you read my previous article, you know the importance of proper date-time formatting. Likewise, when working with time series, it becomes much easier if we have the Datecolumn represented as a Timestamp. Timestamp is the main pandas data structures for working with dates and times. The pandas function to_datetime() can help us convert a string to a proper date/time format.
# to explicitly convert the date column to type DATETIMEdata['Date'] = pd.to_datetime(data['Date'])data.dtypes
We will now go ahead and set this column as the index for the dataframe using the set_index() call.
data = data.set_index('Date')data
If you compare this with the output in Fig 1 above, you would notice that the indices of the dataframe are no longer in range 0 to 4382. Instead, now the indices are the respective date on which the data was collected.
We can explicitly check the indices as well:
data.index
An interesting thing to note here is thatfreq = None. What this means is that it is not known if data is collected by the hour, by day, my minute, etc. However, just by eyeballing the indices, we can see that it looks like the data was collected by the day. It would be nice to explicitly put this info into the data frame as well and we will be seeing how to do this shortly! But first a quick detour...
You will come across datasets where the Date and Time were recorded as separate columns at the time of data collection. A simple yet neat trick to set them as data index is:
Concatenate the two columns but with a space between them.The space is important!!
Convert this concatenated column to a Timestamp using to_datetime().
Set this concatenated column as the index using set_index().
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])df = df.set_index('Datetime')
Alternatively, you could set them as the index at the time of reading the file like below:
pd.read_csv('xyz.csv', parse_dates = [['Date','Time']], index_col = 0)
As we mentioned previously, quick glance at the data suggests it was collected at an interval of 24 hours (or a day). However, the data reflects freq = None. We can correct it as follows:
data_freq = data.asfreq('D')data_freq
Note: Available frequencies in pandas include hourly (‘H’), calendar daily (‘D’), business daily (‘B’), weekly (‘W’), monthly (‘M’), quarterly (‘Q’), annual (‘A’), and many others.
What we have done above is say “hey, the data was collected at a day’s interval and hence each row is a new day”. So technically, we should have values for power consumption, solar production, wind production, etc for all days from 2006–2017.
In case, some days are missing in our data, the above code is going to insert empty rows and in each of these rows the values corresponding to the columns would be allNaNs. In order to avoid these NaN values, we can tell as.freq function how to fill these null values
data_freq = data.asfreq('D', method = 'ffill')data_freq
ffill refers to forward fill. This means when a null is encountered for a particular column, it will be replaced by the value in the previous row. As an example:
In the above table, forward filling the nulls would produce the following dataframe:
This technique of forward filling makes sense on some level — if we are not aware of the amount of power consumption on today’s date, we can always assume it is the same as it was yesterday.
Similarly, filling missing data in a time-series dataset can be achieved as follows:
data = data.ffill().head()
Remember, replacing missing data with medians or means in not such a good idea when it comes to time-series data. Better alternatives exist such as forward filling, backward filling, linear interpolation, mean of nearest neighbours, etc.
Finally, looking at our data set after fixing the frequency type and imputing missing values, we find that our dataset is the same as before (no new rows were added. I guess whosoever did the data collection did one hell of a job!)
You might be wondering why are there still some null values, especially at the beginning of the dataset. The reason is that these have been forward filled but because the value in the very first row was null, we are unable to see any difference.
Resampling simply refers to an aggregation of data over a certain time period. Its performance is similar to the group by function in SQL, i.e. data is first split into time bins and some computation is performed on each bin. For instance, given our daily data, we can resample (or bin) it by the month or year and generate some relevant statistics such as minimum, maximum, or mean values.
To compute weekly mean values for electricity consumption, wind, and solar production:
data_columns = ['Consumption', 'Wind', 'Solar', 'Wind+Solar']data_weekly_mean = data[data_columns].resample('W').mean() # W stands for weeklydata_weekly_mean
If you notice the indices in the output, you would observe that they are at a gap of one week, we have Jan1 2006 followed by Jan8 2006, and so on. The first row above, labeled 2006–01–01, contains the mean of all the data contained in the time bin 2006–01–01 through 2006–01–07.
Similarly, to compute monthly maximum values for electricity consumption, wind, and solar production:
data_columns = ['Consumption', 'Wind', 'Solar', 'Wind+Solar']data_monthly_max = data[data_columns].resample('M').max() # W stands for weeklydata_monthly_max
This is quite similar to the resampling process that we just learned. The difference is that the bins over which some aggregating functions are performed) are overlapping.
Bins in case of weekly resampling: Jan1- Jan 7; Jan8 - Jan14, Jan 15 - Jan 21, etc
Bins in case of weekly rolling: Jan1- Jan7; Jan 2- Jan 8, Jan 3- Jan 9, etc.
To compute a 7-day rolling mean:
data_columns = ['Consumption', 'Wind', 'Solar', 'Wind+Solar']data_7d_rol = data[data_columns].rolling(window = 7, center = True).mean()data_7d_rol
In the above command, center = True means for the time bin, say Jan 1 to Jan 8, the rolling mean would be calculated and placed next to the center of the bin i.e. Jan 4. To make it clearer, let's check the output of the above code:
As you can see, the mean consumption value (of 1361.471) in 2006–01–04 was calculated by averaging the values from 2006–01–01 to 2006–01–07. Similarly, the mean consumption value (of 1381.300) in 2006–01–05 was calculated by averaging the values from 2006–01–02 to 2006–01–08.
By the same logic, to calculate the mean consumption value for 2006–01–01, we would need to average the values from 2005–12–29 to 2006–01–04. However, the data for the year 2005 is missing and thus we obtain a Null for the first few rows.
Rolling means are quite handy for assessing the trend in our dataset. But first, what are trends?
Trend is the smooth long term tendency of a time series . It might change direction (increase or decrease) as time progresses.
An increasing trend looks like this:
An easy way to visualize these trends is with rolling means at different time scales.
Let’s see the trend of electricity consumption in our dataset using rolling means at an annual scale (365 days):
data_365d_rol = data[data_columns].rolling(window = 365, center = True).mean()
Let’s visualize our results to get a better sense of trend. We will be plotting the annual trend against the daily and 7-day rolling mean:
fig, ax = plt.subplots(figsize = (11,4))# plotting daily dataax.plot(data['Consumption'], marker='.', markersize=2, color='0.6',linestyle='None', label='Daily')# plotting 7-day rolling dataax.plot(data_7d_rol['Consumption'], linewidth=2, label='7-d Rolling Mean')# plotting annual rolling dataax.plot(data_365d_rol['Consumption'], color='0.2', linewidth=3, label='Trend (365-d Rolling Mean)')# Beautification of plotax.xaxis.set_major_locator(mdates.YearLocator())ax.legend()ax.set_xlabel('Year')ax.set_ylabel('Consumption (GWh)')ax.set_title('Trends in Electricity Consumption')
Looking at the 365-day rolling mean time series, we can see that the overall annual trend in electricity consumption is fairly stable with low consumption recorded around 2009 and 2013.
Sometimes it would be beneficial to remove the trend from our data, especially if it is quite pronounced (as seen in Fig 3), so we can assess the seasonal variation (more on this in a few minutes) or the noise in our time series. Removing the trend (or de-trending) can also simplify the modeling process and improve model performance.
A time series with a trend is called non-stationary. A time series that does not have a trend or has the trend removed is said to be stationary.
Detrended time series is used as input for learning algorithms such as ARIMA (Python library for analyzing and forecasting time series data) or it can also be used as an additional input for a machine learning algorithm.
We can remove the trend by using a method known as differencing. It essentially means creating a new time series wherein value at time (t)= original value at time (t) - original value at time (t-1)
Differencing is super helpful in turning your time series into a stationary time series.
To create first-order differencing of time series:
# creating the first order differencing datadata_first_order_diff = data[data_columns].diff()
On left, we have the original dataset, and on right, we have the difference detrended version. Looking at the consumption column, we can see the value in 2006–01–02 has now changed from 1380.521 to 311.337, which was obtained by subtracting consumption values in 2006–01–02 and 2006–01–01 (1380.521–1069.184 = 311.337).
In general, what the differenced time series tells us is not the actual value at that particular point in time, but how much different it is from the value in the preceding point in time. That means when we plot this differenced time series, most of these values will lie on either side of the x-axis (or y=0).
Plotting to visualize the differenced time series:
start, end = '2017-01', '2017-06'fig, ax = plt.subplots(figsize=(11, 4))ax.plot(data_first_order_diff.loc[start:end, 'Consumption'],marker='o', markersize=4, linestyle='-', label='First Order Differencing')ax.set_ylabel('Electricity Consumption (GWh)')ax.legend();
We did not have any trend, to begin with, so it might be a bit hard for you to see if the trend has been removed or not. But you don’t have to just take my word for it! When you perform 1st order differencing for your own data (that has a trend component as seen in the figure below on left), you should be able to see a transformation similar to the one in the right:
P.S: In case 1st order differencing is unable to remove the trend, you can perform 2nd order differencing using the formula:value at time (t)= original value at time (t) — 2 *original value at time (t-1) + original value at time (t-2)
P.P.S.: The time series resulting from second-order differencing have N — 2 observations. This is because no difference value can be created for the first two observations (there is nothing for it to be subtracted from).
A time series is periodic if it repeats itself at equally spaced intervals, say, every 12 months, every 1 week, every 4 months, and so on.
Let us check if our time series has some seasonality element to it.
plt.figure(figsize=(11,4), dpi= 80)data['Consumption'].plot(linewidth = 0.5)
It seems our consumption time series is repeating every 12 months. We can see a peak at the beginning and end of every year with a trough in the middle summer months.
We can look in-depth into a particular year to see if there is any weekly seasonality. Here we look at two month’s worth of data: Jan 2010 & Feb 2010:
data.loc['2010-01': '2010-02','Consumption'].plot(marker = 'o', figsize=(11, 9))
As you can see, the weekly oscillations are quite clear. The power consumption is in general low on weekends and quite high during weekdays.
Autocorrelation is a technique for analyzing seasonality. It plots the correlation of the time series with itself at a different time lag.
Confusing much?
I learned a great intuitive way to understand autocorrelation using the tutorial here. It basically says, if you take a time series and move it by 12 months (lag = 12) backwards or forwards, it would map onto itself in some way. Autocorrelation is a way of telling how good this mapping is. If it is very good, it means the time series and the shifted time series are almost similar and the correlation at that time lag would be high. The correlation of a time series with such a shifted version of itself is captured by the concept of autocorrelation (big shout out to Hugo Bowne-Anderson for this wonderful explanation, which I have re-iterated here).
plt.figure(figsize=(11,4), dpi= 80)pd.plotting.autocorrelation_plot(data.loc['2012-01': '2013-01', 'Consumption']);
Before I show what the plot looks like, it would be nice to give heads up on how to read the plot. On the x-axis, you have the lag and on the y-axis, you have how correlated the time series is with itself at that lag. If the original consumption time series repeats itself every two days, you would expect to see a spike in the autocorrelation plot at a lag of 2 days.
From the plot, we can see there is a high peak in correlation at the lag of 7th day, then again on the 14th day, and so on. Which means the time series repeats every 7 days i.e. weekly. This pattern wears off after 3 months (100 days approximately). As you move further away, there’s less and less of a correlation.
The dotted lines in the above plot actually tell you about the statistical significance of the correlation. Each spike that rises above or falls below the dashed lines is considered to be statistically significant.
Thus, we can be sure the consumption series is genuinely autocorrelated with a lag of 1 week.
Note: For brevity, we have only plotted the autocorrelation plot for a subset of our time-series data. If we are to expand to include the complete dataset, the autocorrelation plot would still look pretty much the same.
At times, it would be essential to extract the month, day of the week, date, etc for each timestamp (i.e. each row of our data). Since we already have the indices set in the DateTime format, extracting these elements become super easy:
# Extract the year, month, date separately using the index setdata['Year'] = data.index.yeardata['Month'] = data.index.monthdata['Weekday_Name'] = data.index.weekday_name
We can also use these additional features as inputs in our models. But more on that in Part 2 of Time Series Modeling in Python (hopefully next week).
These additional features can also be useful for exploratory analysis of your dataset. For instance, we can plot the median power consumption for each month.
import seaborn as snsfig, axes = plt.subplots(3, 1, figsize=(11, 10), sharex=True)for name, ax in zip(['Consumption', 'Solar', 'Wind'], axes): sns.boxplot(data=data, x='Month', y=name, ax=ax) ax.set_ylabel('GWh') ax.set_title(name) # Keep the x-axis label for only the bottom subplot if ax != axes[-1]: ax.set_xlabel('')
Hopefully, this warm introduction to time-series data was enough to get you started. In Part 2 of this article, we will be learning how to develop prediction models that can forecast electricity consumption on a particular day. In Part 3, we will be working on a case study analyzing the time series data generated by call centers, essentially working towards analyzing the (dreaded) increment in abandonment rates.
Until next time :) | [
{
"code": null,
"e": 746,
"s": 47,
"text": "Right off the bat, time-series data is not your average dataset! You might have worked with housing data wherein each row represents features of a particular house (such as total area, number of bedrooms, year in which it was built) or student dataset wherein each row represents such information about a student (such as age, gender, prior GPA). In all these datasets, the common thing is that all samples (or rows in your dataset), in general, are independent of each other. What sets these datasets apart from time-series data is that in the latter, each row represents a point in time so naturally, there is some inherent ordering to the data. This is how a typical time-series data looks like:"
},
{
"code": null,
"e": 1017,
"s": 746,
"text": "In the above dataset, we have recorded some value (say the temperature) for each day of the month of January in the year 1991. You can, of course, have more values collected on a particular day in addition to the temperature, such as humidity that day or the wind speed."
},
{
"code": null,
"e": 1230,
"s": 1017,
"text": "We will be working with the publicly available dataset Open Power System Data. You can download the data here. It contains electricity consumption, wind power production, and solar power production for 2006–2017."
},
{
"code": null,
"e": 1273,
"s": 1230,
"text": "Loading the dataset into Jupyter Notebook:"
},
{
"code": null,
"e": 1386,
"s": 1273,
"text": "url='https://raw.githubusercontent.com/jenfly/opsd/master/opsd_germany_daily.csv'data = pd.read_csv(url,sep=\",\")"
},
{
"code": null,
"e": 1419,
"s": 1386,
"text": "This is how our data looks like:"
},
{
"code": null,
"e": 1798,
"s": 1419,
"text": "If you read my previous article, you know the importance of proper date-time formatting. Likewise, when working with time series, it becomes much easier if we have the Datecolumn represented as a Timestamp. Timestamp is the main pandas data structures for working with dates and times. The pandas function to_datetime() can help us convert a string to a proper date/time format."
},
{
"code": null,
"e": 1909,
"s": 1798,
"text": "# to explicitly convert the date column to type DATETIMEdata['Date'] = pd.to_datetime(data['Date'])data.dtypes"
},
{
"code": null,
"e": 2009,
"s": 1909,
"text": "We will now go ahead and set this column as the index for the dataframe using the set_index() call."
},
{
"code": null,
"e": 2043,
"s": 2009,
"text": "data = data.set_index('Date')data"
},
{
"code": null,
"e": 2262,
"s": 2043,
"text": "If you compare this with the output in Fig 1 above, you would notice that the indices of the dataframe are no longer in range 0 to 4382. Instead, now the indices are the respective date on which the data was collected."
},
{
"code": null,
"e": 2307,
"s": 2262,
"text": "We can explicitly check the indices as well:"
},
{
"code": null,
"e": 2318,
"s": 2307,
"text": "data.index"
},
{
"code": null,
"e": 2723,
"s": 2318,
"text": "An interesting thing to note here is thatfreq = None. What this means is that it is not known if data is collected by the hour, by day, my minute, etc. However, just by eyeballing the indices, we can see that it looks like the data was collected by the day. It would be nice to explicitly put this info into the data frame as well and we will be seeing how to do this shortly! But first a quick detour..."
},
{
"code": null,
"e": 2897,
"s": 2723,
"text": "You will come across datasets where the Date and Time were recorded as separate columns at the time of data collection. A simple yet neat trick to set them as data index is:"
},
{
"code": null,
"e": 2980,
"s": 2897,
"text": "Concatenate the two columns but with a space between them.The space is important!!"
},
{
"code": null,
"e": 3049,
"s": 2980,
"text": "Convert this concatenated column to a Timestamp using to_datetime()."
},
{
"code": null,
"e": 3110,
"s": 3049,
"text": "Set this concatenated column as the index using set_index()."
},
{
"code": null,
"e": 3202,
"s": 3110,
"text": "df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])df = df.set_index('Datetime')"
},
{
"code": null,
"e": 3293,
"s": 3202,
"text": "Alternatively, you could set them as the index at the time of reading the file like below:"
},
{
"code": null,
"e": 3364,
"s": 3293,
"text": "pd.read_csv('xyz.csv', parse_dates = [['Date','Time']], index_col = 0)"
},
{
"code": null,
"e": 3552,
"s": 3364,
"text": "As we mentioned previously, quick glance at the data suggests it was collected at an interval of 24 hours (or a day). However, the data reflects freq = None. We can correct it as follows:"
},
{
"code": null,
"e": 3590,
"s": 3552,
"text": "data_freq = data.asfreq('D')data_freq"
},
{
"code": null,
"e": 3771,
"s": 3590,
"text": "Note: Available frequencies in pandas include hourly (‘H’), calendar daily (‘D’), business daily (‘B’), weekly (‘W’), monthly (‘M’), quarterly (‘Q’), annual (‘A’), and many others."
},
{
"code": null,
"e": 4014,
"s": 3771,
"text": "What we have done above is say “hey, the data was collected at a day’s interval and hence each row is a new day”. So technically, we should have values for power consumption, solar production, wind production, etc for all days from 2006–2017."
},
{
"code": null,
"e": 4282,
"s": 4014,
"text": "In case, some days are missing in our data, the above code is going to insert empty rows and in each of these rows the values corresponding to the columns would be allNaNs. In order to avoid these NaN values, we can tell as.freq function how to fill these null values"
},
{
"code": null,
"e": 4338,
"s": 4282,
"text": "data_freq = data.asfreq('D', method = 'ffill')data_freq"
},
{
"code": null,
"e": 4500,
"s": 4338,
"text": "ffill refers to forward fill. This means when a null is encountered for a particular column, it will be replaced by the value in the previous row. As an example:"
},
{
"code": null,
"e": 4585,
"s": 4500,
"text": "In the above table, forward filling the nulls would produce the following dataframe:"
},
{
"code": null,
"e": 4776,
"s": 4585,
"text": "This technique of forward filling makes sense on some level — if we are not aware of the amount of power consumption on today’s date, we can always assume it is the same as it was yesterday."
},
{
"code": null,
"e": 4861,
"s": 4776,
"text": "Similarly, filling missing data in a time-series dataset can be achieved as follows:"
},
{
"code": null,
"e": 4888,
"s": 4861,
"text": "data = data.ffill().head()"
},
{
"code": null,
"e": 5126,
"s": 4888,
"text": "Remember, replacing missing data with medians or means in not such a good idea when it comes to time-series data. Better alternatives exist such as forward filling, backward filling, linear interpolation, mean of nearest neighbours, etc."
},
{
"code": null,
"e": 5358,
"s": 5126,
"text": "Finally, looking at our data set after fixing the frequency type and imputing missing values, we find that our dataset is the same as before (no new rows were added. I guess whosoever did the data collection did one hell of a job!)"
},
{
"code": null,
"e": 5604,
"s": 5358,
"text": "You might be wondering why are there still some null values, especially at the beginning of the dataset. The reason is that these have been forward filled but because the value in the very first row was null, we are unable to see any difference."
},
{
"code": null,
"e": 5995,
"s": 5604,
"text": "Resampling simply refers to an aggregation of data over a certain time period. Its performance is similar to the group by function in SQL, i.e. data is first split into time bins and some computation is performed on each bin. For instance, given our daily data, we can resample (or bin) it by the month or year and generate some relevant statistics such as minimum, maximum, or mean values."
},
{
"code": null,
"e": 6082,
"s": 5995,
"text": "To compute weekly mean values for electricity consumption, wind, and solar production:"
},
{
"code": null,
"e": 6240,
"s": 6082,
"text": "data_columns = ['Consumption', 'Wind', 'Solar', 'Wind+Solar']data_weekly_mean = data[data_columns].resample('W').mean() # W stands for weeklydata_weekly_mean"
},
{
"code": null,
"e": 6519,
"s": 6240,
"text": "If you notice the indices in the output, you would observe that they are at a gap of one week, we have Jan1 2006 followed by Jan8 2006, and so on. The first row above, labeled 2006–01–01, contains the mean of all the data contained in the time bin 2006–01–01 through 2006–01–07."
},
{
"code": null,
"e": 6621,
"s": 6519,
"text": "Similarly, to compute monthly maximum values for electricity consumption, wind, and solar production:"
},
{
"code": null,
"e": 6778,
"s": 6621,
"text": "data_columns = ['Consumption', 'Wind', 'Solar', 'Wind+Solar']data_monthly_max = data[data_columns].resample('M').max() # W stands for weeklydata_monthly_max"
},
{
"code": null,
"e": 6950,
"s": 6778,
"text": "This is quite similar to the resampling process that we just learned. The difference is that the bins over which some aggregating functions are performed) are overlapping."
},
{
"code": null,
"e": 7033,
"s": 6950,
"text": "Bins in case of weekly resampling: Jan1- Jan 7; Jan8 - Jan14, Jan 15 - Jan 21, etc"
},
{
"code": null,
"e": 7110,
"s": 7033,
"text": "Bins in case of weekly rolling: Jan1- Jan7; Jan 2- Jan 8, Jan 3- Jan 9, etc."
},
{
"code": null,
"e": 7143,
"s": 7110,
"text": "To compute a 7-day rolling mean:"
},
{
"code": null,
"e": 7290,
"s": 7143,
"text": "data_columns = ['Consumption', 'Wind', 'Solar', 'Wind+Solar']data_7d_rol = data[data_columns].rolling(window = 7, center = True).mean()data_7d_rol"
},
{
"code": null,
"e": 7522,
"s": 7290,
"text": "In the above command, center = True means for the time bin, say Jan 1 to Jan 8, the rolling mean would be calculated and placed next to the center of the bin i.e. Jan 4. To make it clearer, let's check the output of the above code:"
},
{
"code": null,
"e": 7799,
"s": 7522,
"text": "As you can see, the mean consumption value (of 1361.471) in 2006–01–04 was calculated by averaging the values from 2006–01–01 to 2006–01–07. Similarly, the mean consumption value (of 1381.300) in 2006–01–05 was calculated by averaging the values from 2006–01–02 to 2006–01–08."
},
{
"code": null,
"e": 8038,
"s": 7799,
"text": "By the same logic, to calculate the mean consumption value for 2006–01–01, we would need to average the values from 2005–12–29 to 2006–01–04. However, the data for the year 2005 is missing and thus we obtain a Null for the first few rows."
},
{
"code": null,
"e": 8136,
"s": 8038,
"text": "Rolling means are quite handy for assessing the trend in our dataset. But first, what are trends?"
},
{
"code": null,
"e": 8263,
"s": 8136,
"text": "Trend is the smooth long term tendency of a time series . It might change direction (increase or decrease) as time progresses."
},
{
"code": null,
"e": 8300,
"s": 8263,
"text": "An increasing trend looks like this:"
},
{
"code": null,
"e": 8386,
"s": 8300,
"text": "An easy way to visualize these trends is with rolling means at different time scales."
},
{
"code": null,
"e": 8499,
"s": 8386,
"text": "Let’s see the trend of electricity consumption in our dataset using rolling means at an annual scale (365 days):"
},
{
"code": null,
"e": 8578,
"s": 8499,
"text": "data_365d_rol = data[data_columns].rolling(window = 365, center = True).mean()"
},
{
"code": null,
"e": 8717,
"s": 8578,
"text": "Let’s visualize our results to get a better sense of trend. We will be plotting the annual trend against the daily and 7-day rolling mean:"
},
{
"code": null,
"e": 9297,
"s": 8717,
"text": "fig, ax = plt.subplots(figsize = (11,4))# plotting daily dataax.plot(data['Consumption'], marker='.', markersize=2, color='0.6',linestyle='None', label='Daily')# plotting 7-day rolling dataax.plot(data_7d_rol['Consumption'], linewidth=2, label='7-d Rolling Mean')# plotting annual rolling dataax.plot(data_365d_rol['Consumption'], color='0.2', linewidth=3, label='Trend (365-d Rolling Mean)')# Beautification of plotax.xaxis.set_major_locator(mdates.YearLocator())ax.legend()ax.set_xlabel('Year')ax.set_ylabel('Consumption (GWh)')ax.set_title('Trends in Electricity Consumption')"
},
{
"code": null,
"e": 9483,
"s": 9297,
"text": "Looking at the 365-day rolling mean time series, we can see that the overall annual trend in electricity consumption is fairly stable with low consumption recorded around 2009 and 2013."
},
{
"code": null,
"e": 9819,
"s": 9483,
"text": "Sometimes it would be beneficial to remove the trend from our data, especially if it is quite pronounced (as seen in Fig 3), so we can assess the seasonal variation (more on this in a few minutes) or the noise in our time series. Removing the trend (or de-trending) can also simplify the modeling process and improve model performance."
},
{
"code": null,
"e": 9964,
"s": 9819,
"text": "A time series with a trend is called non-stationary. A time series that does not have a trend or has the trend removed is said to be stationary."
},
{
"code": null,
"e": 10185,
"s": 9964,
"text": "Detrended time series is used as input for learning algorithms such as ARIMA (Python library for analyzing and forecasting time series data) or it can also be used as an additional input for a machine learning algorithm."
},
{
"code": null,
"e": 10383,
"s": 10185,
"text": "We can remove the trend by using a method known as differencing. It essentially means creating a new time series wherein value at time (t)= original value at time (t) - original value at time (t-1)"
},
{
"code": null,
"e": 10472,
"s": 10383,
"text": "Differencing is super helpful in turning your time series into a stationary time series."
},
{
"code": null,
"e": 10523,
"s": 10472,
"text": "To create first-order differencing of time series:"
},
{
"code": null,
"e": 10617,
"s": 10523,
"text": "# creating the first order differencing datadata_first_order_diff = data[data_columns].diff()"
},
{
"code": null,
"e": 10937,
"s": 10617,
"text": "On left, we have the original dataset, and on right, we have the difference detrended version. Looking at the consumption column, we can see the value in 2006–01–02 has now changed from 1380.521 to 311.337, which was obtained by subtracting consumption values in 2006–01–02 and 2006–01–01 (1380.521–1069.184 = 311.337)."
},
{
"code": null,
"e": 11248,
"s": 10937,
"text": "In general, what the differenced time series tells us is not the actual value at that particular point in time, but how much different it is from the value in the preceding point in time. That means when we plot this differenced time series, most of these values will lie on either side of the x-axis (or y=0)."
},
{
"code": null,
"e": 11299,
"s": 11248,
"text": "Plotting to visualize the differenced time series:"
},
{
"code": null,
"e": 11564,
"s": 11299,
"text": "start, end = '2017-01', '2017-06'fig, ax = plt.subplots(figsize=(11, 4))ax.plot(data_first_order_diff.loc[start:end, 'Consumption'],marker='o', markersize=4, linestyle='-', label='First Order Differencing')ax.set_ylabel('Electricity Consumption (GWh)')ax.legend();"
},
{
"code": null,
"e": 11933,
"s": 11564,
"text": "We did not have any trend, to begin with, so it might be a bit hard for you to see if the trend has been removed or not. But you don’t have to just take my word for it! When you perform 1st order differencing for your own data (that has a trend component as seen in the figure below on left), you should be able to see a transformation similar to the one in the right:"
},
{
"code": null,
"e": 12168,
"s": 11933,
"text": "P.S: In case 1st order differencing is unable to remove the trend, you can perform 2nd order differencing using the formula:value at time (t)= original value at time (t) — 2 *original value at time (t-1) + original value at time (t-2)"
},
{
"code": null,
"e": 12389,
"s": 12168,
"text": "P.P.S.: The time series resulting from second-order differencing have N — 2 observations. This is because no difference value can be created for the first two observations (there is nothing for it to be subtracted from)."
},
{
"code": null,
"e": 12528,
"s": 12389,
"text": "A time series is periodic if it repeats itself at equally spaced intervals, say, every 12 months, every 1 week, every 4 months, and so on."
},
{
"code": null,
"e": 12596,
"s": 12528,
"text": "Let us check if our time series has some seasonality element to it."
},
{
"code": null,
"e": 12673,
"s": 12596,
"text": "plt.figure(figsize=(11,4), dpi= 80)data['Consumption'].plot(linewidth = 0.5)"
},
{
"code": null,
"e": 12840,
"s": 12673,
"text": "It seems our consumption time series is repeating every 12 months. We can see a peak at the beginning and end of every year with a trough in the middle summer months."
},
{
"code": null,
"e": 12991,
"s": 12840,
"text": "We can look in-depth into a particular year to see if there is any weekly seasonality. Here we look at two month’s worth of data: Jan 2010 & Feb 2010:"
},
{
"code": null,
"e": 13072,
"s": 12991,
"text": "data.loc['2010-01': '2010-02','Consumption'].plot(marker = 'o', figsize=(11, 9))"
},
{
"code": null,
"e": 13213,
"s": 13072,
"text": "As you can see, the weekly oscillations are quite clear. The power consumption is in general low on weekends and quite high during weekdays."
},
{
"code": null,
"e": 13352,
"s": 13213,
"text": "Autocorrelation is a technique for analyzing seasonality. It plots the correlation of the time series with itself at a different time lag."
},
{
"code": null,
"e": 13368,
"s": 13352,
"text": "Confusing much?"
},
{
"code": null,
"e": 14022,
"s": 13368,
"text": "I learned a great intuitive way to understand autocorrelation using the tutorial here. It basically says, if you take a time series and move it by 12 months (lag = 12) backwards or forwards, it would map onto itself in some way. Autocorrelation is a way of telling how good this mapping is. If it is very good, it means the time series and the shifted time series are almost similar and the correlation at that time lag would be high. The correlation of a time series with such a shifted version of itself is captured by the concept of autocorrelation (big shout out to Hugo Bowne-Anderson for this wonderful explanation, which I have re-iterated here)."
},
{
"code": null,
"e": 14138,
"s": 14022,
"text": "plt.figure(figsize=(11,4), dpi= 80)pd.plotting.autocorrelation_plot(data.loc['2012-01': '2013-01', 'Consumption']);"
},
{
"code": null,
"e": 14507,
"s": 14138,
"text": "Before I show what the plot looks like, it would be nice to give heads up on how to read the plot. On the x-axis, you have the lag and on the y-axis, you have how correlated the time series is with itself at that lag. If the original consumption time series repeats itself every two days, you would expect to see a spike in the autocorrelation plot at a lag of 2 days."
},
{
"code": null,
"e": 14823,
"s": 14507,
"text": "From the plot, we can see there is a high peak in correlation at the lag of 7th day, then again on the 14th day, and so on. Which means the time series repeats every 7 days i.e. weekly. This pattern wears off after 3 months (100 days approximately). As you move further away, there’s less and less of a correlation."
},
{
"code": null,
"e": 15038,
"s": 14823,
"text": "The dotted lines in the above plot actually tell you about the statistical significance of the correlation. Each spike that rises above or falls below the dashed lines is considered to be statistically significant."
},
{
"code": null,
"e": 15132,
"s": 15038,
"text": "Thus, we can be sure the consumption series is genuinely autocorrelated with a lag of 1 week."
},
{
"code": null,
"e": 15352,
"s": 15132,
"text": "Note: For brevity, we have only plotted the autocorrelation plot for a subset of our time-series data. If we are to expand to include the complete dataset, the autocorrelation plot would still look pretty much the same."
},
{
"code": null,
"e": 15588,
"s": 15352,
"text": "At times, it would be essential to extract the month, day of the week, date, etc for each timestamp (i.e. each row of our data). Since we already have the indices set in the DateTime format, extracting these elements become super easy:"
},
{
"code": null,
"e": 15759,
"s": 15588,
"text": "# Extract the year, month, date separately using the index setdata['Year'] = data.index.yeardata['Month'] = data.index.monthdata['Weekday_Name'] = data.index.weekday_name"
},
{
"code": null,
"e": 15910,
"s": 15759,
"text": "We can also use these additional features as inputs in our models. But more on that in Part 2 of Time Series Modeling in Python (hopefully next week)."
},
{
"code": null,
"e": 16068,
"s": 15910,
"text": "These additional features can also be useful for exploratory analysis of your dataset. For instance, we can plot the median power consumption for each month."
},
{
"code": null,
"e": 16411,
"s": 16068,
"text": "import seaborn as snsfig, axes = plt.subplots(3, 1, figsize=(11, 10), sharex=True)for name, ax in zip(['Consumption', 'Solar', 'Wind'], axes): sns.boxplot(data=data, x='Month', y=name, ax=ax) ax.set_ylabel('GWh') ax.set_title(name) # Keep the x-axis label for only the bottom subplot if ax != axes[-1]: ax.set_xlabel('')"
},
{
"code": null,
"e": 16827,
"s": 16411,
"text": "Hopefully, this warm introduction to time-series data was enough to get you started. In Part 2 of this article, we will be learning how to develop prediction models that can forecast electricity consumption on a particular day. In Part 3, we will be working on a case study analyzing the time series data generated by call centers, essentially working towards analyzing the (dreaded) increment in abandonment rates."
}
]
|
Sorting 2D Vector in C++ | Set 2 (In descending order by row and column) - GeeksforGeeks | 29 May, 2017
We have discussed some of the cases of sorting 2D vector in below set 1.
Sorting 2D Vector in C++ | Set 1 (By row and column)
More cases are discussed in this article
Case 3 : To sort a particular row of 2D vector in descending orderThis type of sorting arranges a selected row of 2D vector in descending order . This is achieved by using “sort()” and passing iterators of 1D vector as its arguments.
// C++ code to demonstrate sorting of a// row of 2D vector in descending order#include<iostream>#include<vector> // for 2D vector#include<algorithm> // for sort()using namespace std; int main(){ // Initializing 2D vector "vect" with // values vector< vector<int> > vect{{3, 5, 1}, {4, 8, 6}, {7, 2, 9}}; // Number of rows; int m = vect.size(); // Number of columns (Assuming all rows // are of same size). We can have different // sizes though (like Java). int n = vect[0].size(); // Displaying the 2D vector before sorting cout << "The Matrix before sorting 1st row is:\n"; for (int i=0; i<m; i++) { for (int j=0; j<n ;j++) cout << vect[i][j] << " "; cout << endl; } // Use of "sort()" for sorting first row sort(vect[0].rbegin(), vect[0].rend()); // Displaying the 2D vector after sorting cout << "The Matrix after sorting 1st row is:\n"; for (int i=0; i<m; i++) { for (int j=0; j<n ;j++) cout << vect[i][j] << " "; cout << endl; } return 0;}
Output:
The Matrix before sorting 1st row is:
3 5 1
4 8 6
7 2 9
The Matrix after sorting 1st row is:
5 3 1
4 8 6
7 2 9
Case 4 : To sort the entire 2D vector on basis of a particular column in descending order.In this type of sorting 2D vector is entirely sorted on basis of a chosen column in descending order. For example if the chosen column is second, the row with greatest value in second column becomes first row, second greatest value in second column becomes second row, and so on.
{3, 5, 1},{4, 8, 6},{7, 2, 9};
After sorting this matrix by second column, we get
{4, 8, 6} // Row with greatest value in second column{3, 5, 1} // Row with second greatest value in second column{7, 2, 9}
This is achieved by passing a third argument in “sort()” as a call to user defined explicit function.
// C++ code to demonstrate sorting of a// 2D vector on basis of a column in// descending order#include<iostream>#include<vector> // for 2D vector#include<algorithm> // for sort()using namespace std; // Driver function to sort the 2D vector// on basis of a particular column in // descending orderbool sortcol( const vector<int>& v1, const vector<int>& v2 ) { return v1[1] > v2[1];} int main(){ // Initializing 2D vector "vect" with // values vector< vector<int> > vect{{3, 5, 1}, {4, 8, 6}, {7, 2, 9}}; // Number of rows; int m = vect.size(); // Number of columns (Assuming all rows // are of same size). We can have different // sizes though (like Java). int n = vect[0].size(); // Displaying the 2D vector before sorting cout << "The Matrix before sorting is:\n"; for (int i=0; i<m; i++) { for (int j=0; j<n ;j++) cout << vect[i][j] << " "; cout << endl; } // Use of "sort()" for sorting on basis // of 2nd column in descending order sort(vect.begin(), vect.end(),sortcol); // Displaying the 2D vector after sorting cout << "The Matrix after sorting is:\n"; for (int i=0; i<m; i++) { for (int j=0; j<n ;j++) cout << vect[i][j] << " "; cout << endl; } return 0;}
Output:
The Matrix before sorting is:
3 5 1
4 8 6
7 2 9
The Matrix after sorting is:
4 8 6
3 5 1
7 2 9
This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
CPP-Library
cpp-vector
STL
C Language
C++
Sorting
Sorting
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
Command line arguments in C/C++
INT_MAX and INT_MIN in C/C++ and Applications
fork() in C
Function Pointer in C
Inheritance in C++
Initialize a vector in C++ (6 different ways)
getline (string) in C++
C++ Classes and Objects
rand() and srand() in C/C++ | [
{
"code": null,
"e": 24533,
"s": 24505,
"text": "\n29 May, 2017"
},
{
"code": null,
"e": 24606,
"s": 24533,
"text": "We have discussed some of the cases of sorting 2D vector in below set 1."
},
{
"code": null,
"e": 24659,
"s": 24606,
"text": "Sorting 2D Vector in C++ | Set 1 (By row and column)"
},
{
"code": null,
"e": 24700,
"s": 24659,
"text": "More cases are discussed in this article"
},
{
"code": null,
"e": 24934,
"s": 24700,
"text": "Case 3 : To sort a particular row of 2D vector in descending orderThis type of sorting arranges a selected row of 2D vector in descending order . This is achieved by using “sort()” and passing iterators of 1D vector as its arguments."
},
{
"code": "// C++ code to demonstrate sorting of a// row of 2D vector in descending order#include<iostream>#include<vector> // for 2D vector#include<algorithm> // for sort()using namespace std; int main(){ // Initializing 2D vector \"vect\" with // values vector< vector<int> > vect{{3, 5, 1}, {4, 8, 6}, {7, 2, 9}}; // Number of rows; int m = vect.size(); // Number of columns (Assuming all rows // are of same size). We can have different // sizes though (like Java). int n = vect[0].size(); // Displaying the 2D vector before sorting cout << \"The Matrix before sorting 1st row is:\\n\"; for (int i=0; i<m; i++) { for (int j=0; j<n ;j++) cout << vect[i][j] << \" \"; cout << endl; } // Use of \"sort()\" for sorting first row sort(vect[0].rbegin(), vect[0].rend()); // Displaying the 2D vector after sorting cout << \"The Matrix after sorting 1st row is:\\n\"; for (int i=0; i<m; i++) { for (int j=0; j<n ;j++) cout << vect[i][j] << \" \"; cout << endl; } return 0;}",
"e": 26072,
"s": 24934,
"text": null
},
{
"code": null,
"e": 26080,
"s": 26072,
"text": "Output:"
},
{
"code": null,
"e": 26198,
"s": 26080,
"text": "The Matrix before sorting 1st row is:\n3 5 1 \n4 8 6 \n7 2 9 \nThe Matrix after sorting 1st row is:\n5 3 1 \n4 8 6 \n7 2 9 \n"
},
{
"code": null,
"e": 26568,
"s": 26198,
"text": "Case 4 : To sort the entire 2D vector on basis of a particular column in descending order.In this type of sorting 2D vector is entirely sorted on basis of a chosen column in descending order. For example if the chosen column is second, the row with greatest value in second column becomes first row, second greatest value in second column becomes second row, and so on."
},
{
"code": null,
"e": 26599,
"s": 26568,
"text": "{3, 5, 1},{4, 8, 6},{7, 2, 9};"
},
{
"code": null,
"e": 26650,
"s": 26599,
"text": "After sorting this matrix by second column, we get"
},
{
"code": null,
"e": 26773,
"s": 26650,
"text": "{4, 8, 6} // Row with greatest value in second column{3, 5, 1} // Row with second greatest value in second column{7, 2, 9}"
},
{
"code": null,
"e": 26875,
"s": 26773,
"text": "This is achieved by passing a third argument in “sort()” as a call to user defined explicit function."
},
{
"code": "// C++ code to demonstrate sorting of a// 2D vector on basis of a column in// descending order#include<iostream>#include<vector> // for 2D vector#include<algorithm> // for sort()using namespace std; // Driver function to sort the 2D vector// on basis of a particular column in // descending orderbool sortcol( const vector<int>& v1, const vector<int>& v2 ) { return v1[1] > v2[1];} int main(){ // Initializing 2D vector \"vect\" with // values vector< vector<int> > vect{{3, 5, 1}, {4, 8, 6}, {7, 2, 9}}; // Number of rows; int m = vect.size(); // Number of columns (Assuming all rows // are of same size). We can have different // sizes though (like Java). int n = vect[0].size(); // Displaying the 2D vector before sorting cout << \"The Matrix before sorting is:\\n\"; for (int i=0; i<m; i++) { for (int j=0; j<n ;j++) cout << vect[i][j] << \" \"; cout << endl; } // Use of \"sort()\" for sorting on basis // of 2nd column in descending order sort(vect.begin(), vect.end(),sortcol); // Displaying the 2D vector after sorting cout << \"The Matrix after sorting is:\\n\"; for (int i=0; i<m; i++) { for (int j=0; j<n ;j++) cout << vect[i][j] << \" \"; cout << endl; } return 0;}",
"e": 28292,
"s": 26875,
"text": null
},
{
"code": null,
"e": 28300,
"s": 28292,
"text": "Output:"
},
{
"code": null,
"e": 28403,
"s": 28300,
"text": "The Matrix before sorting is:\n3 5 1 \n4 8 6 \n7 2 9 \nThe Matrix after sorting is:\n4 8 6 \n3 5 1 \n7 2 9 \n\n"
},
{
"code": null,
"e": 28704,
"s": 28403,
"text": "This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 28829,
"s": 28704,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28841,
"s": 28829,
"text": "CPP-Library"
},
{
"code": null,
"e": 28852,
"s": 28841,
"text": "cpp-vector"
},
{
"code": null,
"e": 28856,
"s": 28852,
"text": "STL"
},
{
"code": null,
"e": 28867,
"s": 28856,
"text": "C Language"
},
{
"code": null,
"e": 28871,
"s": 28867,
"text": "C++"
},
{
"code": null,
"e": 28879,
"s": 28871,
"text": "Sorting"
},
{
"code": null,
"e": 28887,
"s": 28879,
"text": "Sorting"
},
{
"code": null,
"e": 28891,
"s": 28887,
"text": "STL"
},
{
"code": null,
"e": 28895,
"s": 28891,
"text": "CPP"
},
{
"code": null,
"e": 28993,
"s": 28895,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29002,
"s": 28993,
"text": "Comments"
},
{
"code": null,
"e": 29015,
"s": 29002,
"text": "Old Comments"
},
{
"code": null,
"e": 29043,
"s": 29015,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29075,
"s": 29043,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 29121,
"s": 29075,
"text": "INT_MAX and INT_MIN in C/C++ and Applications"
},
{
"code": null,
"e": 29133,
"s": 29121,
"text": "fork() in C"
},
{
"code": null,
"e": 29155,
"s": 29133,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 29174,
"s": 29155,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29220,
"s": 29174,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29244,
"s": 29220,
"text": "getline (string) in C++"
},
{
"code": null,
"e": 29268,
"s": 29244,
"text": "C++ Classes and Objects"
}
]
|
Style the active link with CSS | To style the active links, use the CSS :active selector. You can try to run the following code to style the active links
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
a:active {
background-color: green;
}
</style>
</head>
<body>
<a href = "https://qries.com">Welcome to Qries</a>
<p>Click on the above link to see the effect.</p>
</body>
</html> | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "To style the active links, use the CSS :active selector. You can try to run the following code to style the active links"
},
{
"code": null,
"e": 1193,
"s": 1183,
"text": "Live Demo"
},
{
"code": null,
"e": 1476,
"s": 1193,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n a:active {\n background-color: green;\n }\n </style>\n </head>\n <body>\n <a href = \"https://qries.com\">Welcome to Qries</a>\n <p>Click on the above link to see the effect.</p>\n </body>\n</html>"
}
]
|
C# Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack - GeeksforGeeks | 15 Dec, 2021
Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.
Example:
Input: exp = “[()]{}{[()()]()}” Output: Balanced
Input: exp = “[(])” Output: Not Balanced
Algorithm:
Declare a character stack S.
Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced.
If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced.
If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced.
After complete traversal, if there is some starting bracket left in stack then “not balanced”
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C#
// C# program for checking// balanced Bracketsusing System;using System.Collections.Generic; public class BalancedBrackets { public class stack { public int top = -1; public char[] items = new char[100]; public void push(char x) { if (top == 99) { Console.WriteLine("Stack full"); } else { items[++top] = x; } } char pop() { if (top == -1) { Console.WriteLine("Underflow error"); return '�'; } else { char element = items[top]; top--; return element; } } Boolean isEmpty() { return (top == -1) ? true : false; } } // Returns true if character1 and character2 // are matching left and right brackets */ static Boolean isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return true; else if (character1 == '{' && character2 == '}') return true; else if (character1 == '[' && character2 == ']') return true; else return false; } // Return true if expression has balanced // Brackets static Boolean areBracketsBalanced(char[] exp) { // Declare an empty character stack */ Stack<char> st = new Stack<char>(); // Traverse the given expression to // check matching brackets for (int i = 0; i < exp.Length; i++) { // If the exp[i] is a starting // bracket then push it if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') st.Push(exp[i]); // If exp[i] is an ending bracket // then pop from stack and check if the // popped bracket is a matching pair if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { // If we see an ending bracket without // a pair then return false if (st.Count == 0) { return false; } // Pop the top element from stack, if // it is not a pair brackets of // character then there is a mismatch. This // happens for expressions like {(}) else if (!isMatchingPair(st.Pop(), exp[i])) { return false; } } } // If there is something left in expression // then there is a starting bracket without // a closing bracket if (st.Count == 0) return true; // balanced else { // not balanced return false; } } // Driver code public static void Main(String[] args) { char[] exp = { '{', '(', ')', '}', '[', ']' }; // Function call if (areBracketsBalanced(exp)) Console.WriteLine("Balanced "); else Console.WriteLine("Not Balanced "); }} // This code is contributed by 29AjayKumar
Balanced
Time Complexity: O(n) Auxiliary Space: O(n) for stack.
Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details!
Amazon
Hike
Oracle
Parentheses-Problems
Snapdeal
Walmart
Wipro
Yatra.com
Zoho
C Programs
Stack
Strings
Zoho
Amazon
Snapdeal
Hike
Oracle
Walmart
Wipro
Yatra.com
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Check for Balanced Brackets in an expression (well-formedness) using Stack
Program for Tower of Hanoi | [
{
"code": null,
"e": 25008,
"s": 24980,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 25152,
"s": 25008,
"text": "Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp."
},
{
"code": null,
"e": 25162,
"s": 25152,
"text": "Example: "
},
{
"code": null,
"e": 25211,
"s": 25162,
"text": "Input: exp = “[()]{}{[()()]()}” Output: Balanced"
},
{
"code": null,
"e": 25253,
"s": 25211,
"text": "Input: exp = “[(])” Output: Not Balanced "
},
{
"code": null,
"e": 25265,
"s": 25253,
"text": "Algorithm: "
},
{
"code": null,
"e": 25294,
"s": 25265,
"text": "Declare a character stack S."
},
{
"code": null,
"e": 25612,
"s": 25294,
"text": "Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced."
},
{
"code": null,
"e": 25890,
"s": 25612,
"text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced."
},
{
"code": null,
"e": 25980,
"s": 25890,
"text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack."
},
{
"code": null,
"e": 26169,
"s": 25980,
"text": "If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced."
},
{
"code": null,
"e": 26263,
"s": 26169,
"text": "After complete traversal, if there is some starting bracket left in stack then “not balanced”"
},
{
"code": null,
"e": 26311,
"s": 26263,
"text": "Below image is a dry run of the above approach:"
},
{
"code": null,
"e": 26362,
"s": 26311,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26365,
"s": 26362,
"text": "C#"
},
{
"code": "// C# program for checking// balanced Bracketsusing System;using System.Collections.Generic; public class BalancedBrackets { public class stack { public int top = -1; public char[] items = new char[100]; public void push(char x) { if (top == 99) { Console.WriteLine(\"Stack full\"); } else { items[++top] = x; } } char pop() { if (top == -1) { Console.WriteLine(\"Underflow error\"); return '�'; } else { char element = items[top]; top--; return element; } } Boolean isEmpty() { return (top == -1) ? true : false; } } // Returns true if character1 and character2 // are matching left and right brackets */ static Boolean isMatchingPair(char character1, char character2) { if (character1 == '(' && character2 == ')') return true; else if (character1 == '{' && character2 == '}') return true; else if (character1 == '[' && character2 == ']') return true; else return false; } // Return true if expression has balanced // Brackets static Boolean areBracketsBalanced(char[] exp) { // Declare an empty character stack */ Stack<char> st = new Stack<char>(); // Traverse the given expression to // check matching brackets for (int i = 0; i < exp.Length; i++) { // If the exp[i] is a starting // bracket then push it if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') st.Push(exp[i]); // If exp[i] is an ending bracket // then pop from stack and check if the // popped bracket is a matching pair if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { // If we see an ending bracket without // a pair then return false if (st.Count == 0) { return false; } // Pop the top element from stack, if // it is not a pair brackets of // character then there is a mismatch. This // happens for expressions like {(}) else if (!isMatchingPair(st.Pop(), exp[i])) { return false; } } } // If there is something left in expression // then there is a starting bracket without // a closing bracket if (st.Count == 0) return true; // balanced else { // not balanced return false; } } // Driver code public static void Main(String[] args) { char[] exp = { '{', '(', ')', '}', '[', ']' }; // Function call if (areBracketsBalanced(exp)) Console.WriteLine(\"Balanced \"); else Console.WriteLine(\"Not Balanced \"); }} // This code is contributed by 29AjayKumar",
"e": 29657,
"s": 26365,
"text": null
},
{
"code": null,
"e": 29666,
"s": 29657,
"text": "Balanced"
},
{
"code": null,
"e": 29722,
"s": 29666,
"text": "Time Complexity: O(n) Auxiliary Space: O(n) for stack. "
},
{
"code": null,
"e": 29848,
"s": 29722,
"text": "Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details!"
},
{
"code": null,
"e": 29855,
"s": 29848,
"text": "Amazon"
},
{
"code": null,
"e": 29860,
"s": 29855,
"text": "Hike"
},
{
"code": null,
"e": 29867,
"s": 29860,
"text": "Oracle"
},
{
"code": null,
"e": 29888,
"s": 29867,
"text": "Parentheses-Problems"
},
{
"code": null,
"e": 29897,
"s": 29888,
"text": "Snapdeal"
},
{
"code": null,
"e": 29905,
"s": 29897,
"text": "Walmart"
},
{
"code": null,
"e": 29911,
"s": 29905,
"text": "Wipro"
},
{
"code": null,
"e": 29921,
"s": 29911,
"text": "Yatra.com"
},
{
"code": null,
"e": 29926,
"s": 29921,
"text": "Zoho"
},
{
"code": null,
"e": 29937,
"s": 29926,
"text": "C Programs"
},
{
"code": null,
"e": 29943,
"s": 29937,
"text": "Stack"
},
{
"code": null,
"e": 29951,
"s": 29943,
"text": "Strings"
},
{
"code": null,
"e": 29956,
"s": 29951,
"text": "Zoho"
},
{
"code": null,
"e": 29963,
"s": 29956,
"text": "Amazon"
},
{
"code": null,
"e": 29972,
"s": 29963,
"text": "Snapdeal"
},
{
"code": null,
"e": 29977,
"s": 29972,
"text": "Hike"
},
{
"code": null,
"e": 29984,
"s": 29977,
"text": "Oracle"
},
{
"code": null,
"e": 29992,
"s": 29984,
"text": "Walmart"
},
{
"code": null,
"e": 29998,
"s": 29992,
"text": "Wipro"
},
{
"code": null,
"e": 30008,
"s": 29998,
"text": "Yatra.com"
},
{
"code": null,
"e": 30016,
"s": 30008,
"text": "Strings"
},
{
"code": null,
"e": 30022,
"s": 30016,
"text": "Stack"
},
{
"code": null,
"e": 30120,
"s": 30022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30161,
"s": 30120,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30192,
"s": 30161,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 30233,
"s": 30192,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 30267,
"s": 30233,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 30292,
"s": 30267,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 30340,
"s": 30292,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 30360,
"s": 30340,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30376,
"s": 30360,
"text": "Stack in Python"
},
{
"code": null,
"e": 30451,
"s": 30376,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
]
|
C library function - cosh() | The C library function double cosh(double x) returns the hypebolic cosine of x.
Following is the declaration for cosh() function.
double cosh(double x)
x − This is the floating point value.
x − This is the floating point value.
This function returns hyperbolic cosine of x.
The following example shows the usage of cosh() function.
#include <stdio.h>
#include <math.h>
int main () {
double x;
x = 0.5;
printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));
x = 1.0;
printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));
x = 1.5;
printf("The hyperbolic cosine of %lf is %lf\n", x, cosh(x));
return(0);
}
Let us compile and run the above program to produce the following result −
The hyperbolic cosine of 0.500000 is 1.127626
The hyperbolic cosine of 1.000000 is 1.543081
The hyperbolic cosine of 1.500000 is 2.352410
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2087,
"s": 2007,
"text": "The C library function double cosh(double x) returns the hypebolic cosine of x."
},
{
"code": null,
"e": 2137,
"s": 2087,
"text": "Following is the declaration for cosh() function."
},
{
"code": null,
"e": 2159,
"s": 2137,
"text": "double cosh(double x)"
},
{
"code": null,
"e": 2197,
"s": 2159,
"text": "x − This is the floating point value."
},
{
"code": null,
"e": 2235,
"s": 2197,
"text": "x − This is the floating point value."
},
{
"code": null,
"e": 2281,
"s": 2235,
"text": "This function returns hyperbolic cosine of x."
},
{
"code": null,
"e": 2339,
"s": 2281,
"text": "The following example shows the usage of cosh() function."
},
{
"code": null,
"e": 2652,
"s": 2339,
"text": "#include <stdio.h>\n#include <math.h>\n\nint main () {\n double x;\n\n x = 0.5;\n printf(\"The hyperbolic cosine of %lf is %lf\\n\", x, cosh(x));\n\n x = 1.0;\n printf(\"The hyperbolic cosine of %lf is %lf\\n\", x, cosh(x));\n\n x = 1.5;\n printf(\"The hyperbolic cosine of %lf is %lf\\n\", x, cosh(x));\n\n return(0);\n}"
},
{
"code": null,
"e": 2727,
"s": 2652,
"text": "Let us compile and run the above program to produce the following result −"
},
{
"code": null,
"e": 2866,
"s": 2727,
"text": "The hyperbolic cosine of 0.500000 is 1.127626\nThe hyperbolic cosine of 1.000000 is 1.543081\nThe hyperbolic cosine of 1.500000 is 2.352410\n"
},
{
"code": null,
"e": 2899,
"s": 2866,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2914,
"s": 2899,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2949,
"s": 2914,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2964,
"s": 2949,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2999,
"s": 2964,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3013,
"s": 2999,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3046,
"s": 3013,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3064,
"s": 3046,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3099,
"s": 3064,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3118,
"s": 3099,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3151,
"s": 3118,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3163,
"s": 3151,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3170,
"s": 3163,
"text": " Print"
},
{
"code": null,
"e": 3181,
"s": 3170,
"text": " Add Notes"
}
]
|
Python String swapcase() Method | Python string method swapcase() returns a copy of the string in which all the case-based characters have had their case swapped.
Following is the syntax for swapcase() method −
str.swapcase();
NA
NA
This method returns a copy of the string in which all the case-based characters have had their case swapped.
The following example shows the usage of swapcase() method.
#!/usr/bin/python
str = "this is string example....wow!!!";
print str.swapcase()
str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.swapcase()
When we run above program, it produces following result −
THIS IS STRING EXAMPLE....WOW!!!
this is string example....wow!!!
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2374,
"s": 2244,
"text": "Python string method swapcase() returns a copy of the string in which all the case-based characters have had their case swapped."
},
{
"code": null,
"e": 2422,
"s": 2374,
"text": "Following is the syntax for swapcase() method −"
},
{
"code": null,
"e": 2439,
"s": 2422,
"text": "str.swapcase();\n"
},
{
"code": null,
"e": 2442,
"s": 2439,
"text": "NA"
},
{
"code": null,
"e": 2445,
"s": 2442,
"text": "NA"
},
{
"code": null,
"e": 2554,
"s": 2445,
"text": "This method returns a copy of the string in which all the case-based characters have had their case swapped."
},
{
"code": null,
"e": 2614,
"s": 2554,
"text": "The following example shows the usage of swapcase() method."
},
{
"code": null,
"e": 2760,
"s": 2614,
"text": "#!/usr/bin/python\n\nstr = \"this is string example....wow!!!\";\nprint str.swapcase()\n\nstr = \"THIS IS STRING EXAMPLE....WOW!!!\";\nprint str.swapcase()"
},
{
"code": null,
"e": 2818,
"s": 2760,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2885,
"s": 2818,
"text": "THIS IS STRING EXAMPLE....WOW!!!\nthis is string example....wow!!!\n"
},
{
"code": null,
"e": 2922,
"s": 2885,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2938,
"s": 2922,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2971,
"s": 2938,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2990,
"s": 2971,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3025,
"s": 2990,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3047,
"s": 3025,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3081,
"s": 3047,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3109,
"s": 3081,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3144,
"s": 3109,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3158,
"s": 3144,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3191,
"s": 3158,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3208,
"s": 3191,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3215,
"s": 3208,
"text": " Print"
},
{
"code": null,
"e": 3226,
"s": 3215,
"text": " Add Notes"
}
]
|
Logo - Repetition | We often repeat a sequence of commands. Computer programs often perform repetitive tasks. Just about every programming system has a way of carrying out this repetition, or iteration, as computer scientists call it. Let us consider the following example −
Let us assume we want to draw a square with sides of length 100, we can do this with the following program −
fd 100
rt 90
fd 100
rt 90
fd 100
rt 90
fd 100
rt 90
We note that the two commands – fd 100 and rt 90 are repeated four times. Will it not be simpler to tell the computer that it should just repeat these two commands four times instead of writing them four times in a row? We can do exactly this, using the following command −
It saves our time of typing-in to make a square. The general form is: repeat number [commands]. We must use the keyword – repeat followed by a number and then a sequence of commands in [square brackets].
Often, we might have to repeat within repeat. This is called nesting. Let us look at some examples on this.
Following is an exercise to check your aptitude on what you have learnt so far in this chapter.
48 Lectures
6 hours
Arnab Chakraborty
38 Lectures
2.5 hours
Rob Cubbon
81 Lectures
7.5 hours
YouAccel
8 Lectures
34 mins
Yash Rajoliya
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2089,
"s": 1834,
"text": "We often repeat a sequence of commands. Computer programs often perform repetitive tasks. Just about every programming system has a way of carrying out this repetition, or iteration, as computer scientists call it. Let us consider the following example −"
},
{
"code": null,
"e": 2198,
"s": 2089,
"text": "Let us assume we want to draw a square with sides of length 100, we can do this with the following program −"
},
{
"code": null,
"e": 2251,
"s": 2198,
"text": "fd 100\nrt 90\nfd 100\nrt 90\nfd 100\nrt 90\nfd 100\nrt 90\n"
},
{
"code": null,
"e": 2525,
"s": 2251,
"text": "We note that the two commands – fd 100 and rt 90 are repeated four times. Will it not be simpler to tell the computer that it should just repeat these two commands four times instead of writing them four times in a row? We can do exactly this, using the following command −"
},
{
"code": null,
"e": 2729,
"s": 2525,
"text": "It saves our time of typing-in to make a square. The general form is: repeat number [commands]. We must use the keyword – repeat followed by a number and then a sequence of commands in [square brackets]."
},
{
"code": null,
"e": 2837,
"s": 2729,
"text": "Often, we might have to repeat within repeat. This is called nesting. Let us look at some examples on this."
},
{
"code": null,
"e": 2933,
"s": 2837,
"text": "Following is an exercise to check your aptitude on what you have learnt so far in this chapter."
},
{
"code": null,
"e": 2966,
"s": 2933,
"text": "\n 48 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2985,
"s": 2966,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3020,
"s": 2985,
"text": "\n 38 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3032,
"s": 3020,
"text": " Rob Cubbon"
},
{
"code": null,
"e": 3067,
"s": 3032,
"text": "\n 81 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3077,
"s": 3067,
"text": " YouAccel"
},
{
"code": null,
"e": 3108,
"s": 3077,
"text": "\n 8 Lectures \n 34 mins\n"
},
{
"code": null,
"e": 3123,
"s": 3108,
"text": " Yash Rajoliya"
},
{
"code": null,
"e": 3130,
"s": 3123,
"text": " Print"
},
{
"code": null,
"e": 3141,
"s": 3130,
"text": " Add Notes"
}
]
|
Explain the PowerShell Advanced Function. | Before starting the Advance PowerShell function, assuming we know about the PowerShell function. You can check the explanation on the PowerShell function below.
https://www.tutorialspoint.com/explain-the-powershell-function
Here, we will take the math function example that calculates the different types of operations. We already have a code with the simple function as shown below.
function math_Operation{
param([int]$val1,[int]$val2)
Write-Host "Multiply : $($val1*$val2)"
Write-Host "Addition : $($val1+$val2)"
Write-Host "Subtraction : $($val1-$val2)"
Write-Host "Divide : $($val1+$val2)"
}
The above example is of the simple function. When you run the above code and run the function from the terminal and you can notice you will see only the $val1 and $val2 parameters while the PowerShell advanced function contains the additional common parameters like ErrorAction, WarningAction, Verbose, Passthru, etc.
Check the syntax below for the function when it is used as a simple function. No common
parameters are added.
PS C:\WINDOWS\system32> Get-Help math_Operation
NAME
math_Operation
SYNTAX
math_Operation [[-val1] <int>] [[-val2] <int>]
ALIASES
None
REMARKS
None
To convert the simple function into the advanced function we just need to use the [cmdletbinding] into the function.
function math_Operation{
[cmdletbinding()]
param([int]$val1,[int]$val2)
Write-Host "Multiply : $($val1*$val2)"
Write-Host "Addition : $($val1+$val2)"
Write-Host "Subtraction : $($val1-$val2)"
Write-Host "Divide : $($val1+$val2)"
}
Now execute the above code and check the parameters, you can see the other parameters referred to as common parameters. Check the Syntax of this function after the execution of the code.
PS C:\WINDOWS\system32> Get-Help math_Operation
NAME
math_Operation
SYNTAX
math_Operation [[-val1] <int>] [[-val2] <int>] [<CommonParameters>]
ALIASES
None
REMARKS
None
This does not end here. PowerShell advanced function is more. So far we have converted the simple function into an advanced function. Let’s check the structure of the advanced function.
function Verb-Noun {
[CmdletBinding()]
param (
// Parameters to declare with their datatypes
)
begin {
// Initialization of variables, create a log file
}
process {
// Program code to make this function work
}
end {
// Clearing values, log files, etc.
}
}
In the above function, you can see the PowerShell Advanced Function is mainly comprised of 3 blocks (Begin, Process, and End).
In the Begin block, you need to initialize the value of the variable or need to declare the log files, etc. This block executes first before the other two blocks and executes once only.
In the Begin block, you need to initialize the value of the variable or need to declare the log files, etc. This block executes first before the other two blocks and executes once only.
The Process block, where the actual code is executed and which uses the parameters declared in Param block and the values and log file path initialized in Begin block. This block runs for each item in the block.
The Process block, where the actual code is executed and which uses the parameters declared in Param block and the values and log file path initialized in Begin block. This block runs for each item in the block.
The End block contains the values to be released/cleared from the variables and other cleanup tasks. This block also executes one time only after the process block executed.
The End block contains the values to be released/cleared from the variables and other cleanup tasks. This block also executes one time only after the process block executed.
Apart from the above functionalities, many other parameter attributes and arguments are
supported which are explained in the next subsequent articles. Just have a glance at those
parameter attributes and arguments.
Mandatory
Mandatory
Parameter=0
Parameter=0
ValueFromPipeline
ValueFromPipeline
ValueFromPipelineByPropertyName
ValueFromPipelineByPropertyName
ValueFromRemainingArguments
ValueFromRemainingArguments
HelpMessage
HelpMessage
Param
Param
Parameter
Parameter
[AllowNull()]
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyString()]
[AllowEmptyCollection()]
[AllowEmptyCollection()]
[ValidateCount()]
[ValidateCount()]
[ValidateLength()]
[ValidateLength()]
[ValidatePattern()]
[ValidatePattern()]
[ValidateRange()]
[ValidateRange()]
[ValidateScript()]
[ValidateScript()]
[ValidateSet()]
[ValidateSet()]
[ValidateNotNull()]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[ValidateNotNullOrEmpty()]
[DynamicParam]
[DynamicParam]
[Switch]
[Switch] | [
{
"code": null,
"e": 1223,
"s": 1062,
"text": "Before starting the Advance PowerShell function, assuming we know about the PowerShell function. You can check the explanation on the PowerShell function below."
},
{
"code": null,
"e": 1286,
"s": 1223,
"text": "https://www.tutorialspoint.com/explain-the-powershell-function"
},
{
"code": null,
"e": 1446,
"s": 1286,
"text": "Here, we will take the math function example that calculates the different types of operations. We already have a code with the simple function as shown below."
},
{
"code": null,
"e": 1674,
"s": 1446,
"text": "function math_Operation{\n param([int]$val1,[int]$val2)\n Write-Host \"Multiply : $($val1*$val2)\"\n Write-Host \"Addition : $($val1+$val2)\"\n Write-Host \"Subtraction : $($val1-$val2)\"\n Write-Host \"Divide : $($val1+$val2)\"\n}"
},
{
"code": null,
"e": 1992,
"s": 1674,
"text": "The above example is of the simple function. When you run the above code and run the function from the terminal and you can notice you will see only the $val1 and $val2 parameters while the PowerShell advanced function contains the additional common parameters like ErrorAction, WarningAction, Verbose, Passthru, etc."
},
{
"code": null,
"e": 2102,
"s": 1992,
"text": "Check the syntax below for the function when it is used as a simple function. No common\nparameters are added."
},
{
"code": null,
"e": 2262,
"s": 2102,
"text": "PS C:\\WINDOWS\\system32> Get-Help math_Operation\nNAME\n math_Operation\nSYNTAX\n math_Operation [[-val1] <int>] [[-val2] <int>]\nALIASES\n None\nREMARKS\n None"
},
{
"code": null,
"e": 2379,
"s": 2262,
"text": "To convert the simple function into the advanced function we just need to use the [cmdletbinding] into the function."
},
{
"code": null,
"e": 2628,
"s": 2379,
"text": "function math_Operation{\n [cmdletbinding()]\n param([int]$val1,[int]$val2)\n Write-Host \"Multiply : $($val1*$val2)\"\n Write-Host \"Addition : $($val1+$val2)\"\n Write-Host \"Subtraction : $($val1-$val2)\"\n Write-Host \"Divide : $($val1+$val2)\"\n}"
},
{
"code": null,
"e": 2815,
"s": 2628,
"text": "Now execute the above code and check the parameters, you can see the other parameters referred to as common parameters. Check the Syntax of this function after the execution of the code."
},
{
"code": null,
"e": 2996,
"s": 2815,
"text": "PS C:\\WINDOWS\\system32> Get-Help math_Operation\nNAME\n math_Operation\nSYNTAX\n math_Operation [[-val1] <int>] [[-val2] <int>] [<CommonParameters>]\nALIASES\n None\nREMARKS\n None"
},
{
"code": null,
"e": 3182,
"s": 2996,
"text": "This does not end here. PowerShell advanced function is more. So far we have converted the simple function into an advanced function. Let’s check the structure of the advanced function."
},
{
"code": null,
"e": 3489,
"s": 3182,
"text": "function Verb-Noun {\n [CmdletBinding()]\n param (\n // Parameters to declare with their datatypes\n )\n begin {\n // Initialization of variables, create a log file\n }\n process {\n // Program code to make this function work\n }\n end {\n // Clearing values, log files, etc.\n }\n}"
},
{
"code": null,
"e": 3616,
"s": 3489,
"text": "In the above function, you can see the PowerShell Advanced Function is mainly comprised of 3 blocks (Begin, Process, and End)."
},
{
"code": null,
"e": 3802,
"s": 3616,
"text": "In the Begin block, you need to initialize the value of the variable or need to declare the log files, etc. This block executes first before the other two blocks and executes once only."
},
{
"code": null,
"e": 3988,
"s": 3802,
"text": "In the Begin block, you need to initialize the value of the variable or need to declare the log files, etc. This block executes first before the other two blocks and executes once only."
},
{
"code": null,
"e": 4200,
"s": 3988,
"text": "The Process block, where the actual code is executed and which uses the parameters declared in Param block and the values and log file path initialized in Begin block. This block runs for each item in the block."
},
{
"code": null,
"e": 4412,
"s": 4200,
"text": "The Process block, where the actual code is executed and which uses the parameters declared in Param block and the values and log file path initialized in Begin block. This block runs for each item in the block."
},
{
"code": null,
"e": 4586,
"s": 4412,
"text": "The End block contains the values to be released/cleared from the variables and other cleanup tasks. This block also executes one time only after the process block executed."
},
{
"code": null,
"e": 4760,
"s": 4586,
"text": "The End block contains the values to be released/cleared from the variables and other cleanup tasks. This block also executes one time only after the process block executed."
},
{
"code": null,
"e": 4975,
"s": 4760,
"text": "Apart from the above functionalities, many other parameter attributes and arguments are\nsupported which are explained in the next subsequent articles. Just have a glance at those\nparameter attributes and arguments."
},
{
"code": null,
"e": 4985,
"s": 4975,
"text": "Mandatory"
},
{
"code": null,
"e": 4995,
"s": 4985,
"text": "Mandatory"
},
{
"code": null,
"e": 5007,
"s": 4995,
"text": "Parameter=0"
},
{
"code": null,
"e": 5019,
"s": 5007,
"text": "Parameter=0"
},
{
"code": null,
"e": 5037,
"s": 5019,
"text": "ValueFromPipeline"
},
{
"code": null,
"e": 5055,
"s": 5037,
"text": "ValueFromPipeline"
},
{
"code": null,
"e": 5087,
"s": 5055,
"text": "ValueFromPipelineByPropertyName"
},
{
"code": null,
"e": 5119,
"s": 5087,
"text": "ValueFromPipelineByPropertyName"
},
{
"code": null,
"e": 5147,
"s": 5119,
"text": "ValueFromRemainingArguments"
},
{
"code": null,
"e": 5175,
"s": 5147,
"text": "ValueFromRemainingArguments"
},
{
"code": null,
"e": 5187,
"s": 5175,
"text": "HelpMessage"
},
{
"code": null,
"e": 5199,
"s": 5187,
"text": "HelpMessage"
},
{
"code": null,
"e": 5205,
"s": 5199,
"text": "Param"
},
{
"code": null,
"e": 5211,
"s": 5205,
"text": "Param"
},
{
"code": null,
"e": 5221,
"s": 5211,
"text": "Parameter"
},
{
"code": null,
"e": 5231,
"s": 5221,
"text": "Parameter"
},
{
"code": null,
"e": 5245,
"s": 5231,
"text": "[AllowNull()]"
},
{
"code": null,
"e": 5259,
"s": 5245,
"text": "[AllowNull()]"
},
{
"code": null,
"e": 5280,
"s": 5259,
"text": "[AllowEmptyString()]"
},
{
"code": null,
"e": 5301,
"s": 5280,
"text": "[AllowEmptyString()]"
},
{
"code": null,
"e": 5326,
"s": 5301,
"text": "[AllowEmptyCollection()]"
},
{
"code": null,
"e": 5351,
"s": 5326,
"text": "[AllowEmptyCollection()]"
},
{
"code": null,
"e": 5369,
"s": 5351,
"text": "[ValidateCount()]"
},
{
"code": null,
"e": 5387,
"s": 5369,
"text": "[ValidateCount()]"
},
{
"code": null,
"e": 5406,
"s": 5387,
"text": "[ValidateLength()]"
},
{
"code": null,
"e": 5425,
"s": 5406,
"text": "[ValidateLength()]"
},
{
"code": null,
"e": 5445,
"s": 5425,
"text": "[ValidatePattern()]"
},
{
"code": null,
"e": 5465,
"s": 5445,
"text": "[ValidatePattern()]"
},
{
"code": null,
"e": 5483,
"s": 5465,
"text": "[ValidateRange()]"
},
{
"code": null,
"e": 5501,
"s": 5483,
"text": "[ValidateRange()]"
},
{
"code": null,
"e": 5520,
"s": 5501,
"text": "[ValidateScript()]"
},
{
"code": null,
"e": 5539,
"s": 5520,
"text": "[ValidateScript()]"
},
{
"code": null,
"e": 5555,
"s": 5539,
"text": "[ValidateSet()]"
},
{
"code": null,
"e": 5571,
"s": 5555,
"text": "[ValidateSet()]"
},
{
"code": null,
"e": 5591,
"s": 5571,
"text": "[ValidateNotNull()]"
},
{
"code": null,
"e": 5611,
"s": 5591,
"text": "[ValidateNotNull()]"
},
{
"code": null,
"e": 5638,
"s": 5611,
"text": "[ValidateNotNullOrEmpty()]"
},
{
"code": null,
"e": 5665,
"s": 5638,
"text": "[ValidateNotNullOrEmpty()]"
},
{
"code": null,
"e": 5680,
"s": 5665,
"text": "[DynamicParam]"
},
{
"code": null,
"e": 5695,
"s": 5680,
"text": "[DynamicParam]"
},
{
"code": null,
"e": 5704,
"s": 5695,
"text": "[Switch]"
},
{
"code": null,
"e": 5713,
"s": 5704,
"text": "[Switch]"
}
]
|
Graph Theory Basics. What you need to know as graph theory... | by Miguel Saldana | Towards Data Science | In programming and mathematical terms, graph theory is really nothing new, but the implementation and usage of it in code has grown in advances in Machine Learning and AI. One big reason for this is that advances in computing power to power large-scale models allow for complex models to be developed that can represent relationships between anything. One of the most famous and early implementations in tech of Graph Theory is Google’s Page Rank algorithm. The Page Rank algorithm was the initial version of Google’s searching algorithm and is rooted in graph theory and is based on an efficient way to measure how the internet web pages are connected via links and user clicks/traffic and from that which ones are the most popular. Additionally, in more recent times graph theory has been applied to knowledge graphs to help understand the interconnected relationship of variables within a system (for example, a factory and all the pieces of machinery and factors that are within it and how they affect each other). Also, graph theory has been applied to economic models to understand how the stock market behaves as well as the inner workings of blockchains are supported by graph theory. So the widespread ability to compute and create extremely complex models through graphical means is only going to continue to grow and the need to learn and understand the basics is vital to apply it to additional use cases.
In mathematics, graph theory is the study of graphs, which are mathematical structures used to model pairwise relations between objects. A graph in this contec is made up vertices (also called nodes or points) which are connected by edges (also called links or lines). — Wikipedia
A quick Wikipedia search will give you this definition of graph theory and below we will start to breakdown what it is and how it works
Vertices/Nodes — These are the objects that will usually have properties about themselves and then connections to other objects in a graph. A simple example of a property that an object could have is weight or a value, in more complex objects this could also include things like cost, descriptive properties (color, size, weight), power, probabilities, etc... it will all depend on how the graph network is built and what it is trying to accomplish
Edges/Links — The edges are essentially the relationship between objects or the road that connects them together. Objects that have edges between themselves have a relation, while those that are not connected don’t.
Directed/Undirected Graphs — The easiest way to understand the difference between a directed graph and an undirected graph is to think of the edge between an object as either a two-way road or a one-way road. A directed graph shows a relation from one object that passes whatever is in the relation to another object and that is not reciprocated back. An undirected graph is a connection between two objects but information about its relationship can flow both ways between them. It is a key point to point out that in directed graphs you can have two edges between a pair of nodes that simulate “an undirected” nature between the pairs.
Cyclical/Acyclical Graph — A cyclical graph is one that has a set of nodes that are connected in a closed-loop, acyclical do not have the closed-loop property.
The two most common themes in graphical representations for computers are adjacency matrix (sometimes referred to as incidence matrix) or adjacency lists.
Adjacency Matrix — In this method, a graph is converted into a matrix representation of a graph. The matrix will be an n x n shaped matrix where n represents the number of nodes and the values in the matrix represents the edges between the nodes as shown below. It is important to note that the matrix representation of an undirected graph will be a mirror of itself along the diagonal.
Adjacency List — This version of a graph is represented as the name implies a list. It is an unordered list that describes the neighbors of a vertex (or edge) in a graph.
Putting the graphs into these two kinds of forms allows us to computational program the graphs in a way that we can then set rules, relationships, properties, and changes to the graphs.
With these basic terms and concepts, we can explore a few examples of the basic problems that graph theory is used to solve and hopefully use them as examples of the building blocks for more complex systems.
One of the most basic things you may want to know about a graph network is the distance between paths and what is the optimal or shortest path between them. Some examples of where this might be useful are looking at an electricity grid or finding degrees of separation in a social network (a la Kevin Bacon).
In almost all learning platforms the first two algorithms introduced with graph theory will be DFS and BFS. They are both algorithms that look to traverse a graph. In essence, both DFS and BFS are trying to accomplish the same goal but go about in slightly different manners.
Starting off with BFS, the principle behind this algorithm is to investigate all neighboring nodes from a starting place before moving to the following node. A queue is used to help denote which nodes have been visited and once that path has been completed, it will go to the next unvisited node and begin traversing the graph just as it did before, marking all visited nodes. This cycle will repeat for the entire graph until all nodes have been visited. In the queue, it is then possible to determine the shortest path from the starting point to the targeted endpoint. Below is an example of the pseudocode for the BFS search algorithm.
1 procedure BFS(G, root) is 2 let Q be a queue 3 label root as discovered 4 Q.enqueue(root) 5 while Q is not empty do 6 v := Q.dequeue() 7 if v is the goal then 8 return v 9 for all edges from v to w in G.adjacentEdges(v) do10 if w is not labeled as discovered then11 label w as discovered12 Q.enqueue(w)
DFS or Depth-First Search is a very similar algorithm to BFS, but it behaves slightly differently. When traversing through the graph, once a dead-end is reached in DFS, the algorithm will backtrack to a previous node that is connected to an unvisited node and continue in that path. It will then only go to a random node if it is unconnected from the original network of the graph. Both of these methods are some of the first methods taught to traverse along a graph and find the shortest path. Potential applications would be to apply it to a graph of a social network to determine potential suggestions of people with similar backgrounds, friends, or hobbies. Below is an example of a DFS Pseudocode.
1 procedure DFS_iterative(G, v) is2 let S be a stack3 S.push(v)4 while S is not empty do5 v = S.pop()6 if v is not labeled as discovered then7 label v as discovered8 for all edges from v to w in G.adjacentEdges(v) do9 S.push(w)
There are more advanced graph-traversing methods such as the Bellman-Ford, Djikstra, and Kruskal for example. Each tries and tackles additional problems that could be encountered that the methods employed in BFS or DFS wouldn’t be able to tackle, for example, edges with negative weights/lengths, cyclical graphs, etc...
Enumeration — In other words is evaluating and counting graphs that meet specific conditions or in other words solving combinatorics problems.
Subgraphs — Looking at graphs to determine if components of a graph are subcomponents of another graph or looking at “hereditary” traits between graphs
Graph Coloring — Similar to enumeration, but applying coloring to the problem of a graph so that you will never have similar colors touching each other along coloring vertices in a graph
Unification — Evaluating graphs that are more constrained (or have more information) and how they roll up into graphs or models that less constrained (or more generalized)
Network Flow — An example of this type of problem would be like evaluating an energy grid to determine the flow of energy across a system
Visibility Problems — Trying to solve a problem similar to the museum guard problem such that you figure out the minimum number of security guards to see an entire museum gallery.
Decomposition — Looking at breaking down graphs with certain conditions.
Route Problems — The shortest path example is one such problem, another would be the traveling salesman problem or the Seven Bridges of Konigsberg problem.
As mentioned before, graph theory is slowly becoming a more efficient way to represent real-world problems. The computing power to solve extremely complex relationships and details about any system can be now be done through programmatic methods. This article is intended to really serve as a primer of graph theory and to encourage you to continue learning about different methods of evaluating and implementing graphs to solve real-world problems.
One of my personal favorite subjects that I’m currently researching heavily is blockchains and you think of a blockchain in terms of graph theory to some extent.
If you have any questions or comments about this article, please leave a comment. | [
{
"code": null,
"e": 1590,
"s": 172,
"text": "In programming and mathematical terms, graph theory is really nothing new, but the implementation and usage of it in code has grown in advances in Machine Learning and AI. One big reason for this is that advances in computing power to power large-scale models allow for complex models to be developed that can represent relationships between anything. One of the most famous and early implementations in tech of Graph Theory is Google’s Page Rank algorithm. The Page Rank algorithm was the initial version of Google’s searching algorithm and is rooted in graph theory and is based on an efficient way to measure how the internet web pages are connected via links and user clicks/traffic and from that which ones are the most popular. Additionally, in more recent times graph theory has been applied to knowledge graphs to help understand the interconnected relationship of variables within a system (for example, a factory and all the pieces of machinery and factors that are within it and how they affect each other). Also, graph theory has been applied to economic models to understand how the stock market behaves as well as the inner workings of blockchains are supported by graph theory. So the widespread ability to compute and create extremely complex models through graphical means is only going to continue to grow and the need to learn and understand the basics is vital to apply it to additional use cases."
},
{
"code": null,
"e": 1871,
"s": 1590,
"text": "In mathematics, graph theory is the study of graphs, which are mathematical structures used to model pairwise relations between objects. A graph in this contec is made up vertices (also called nodes or points) which are connected by edges (also called links or lines). — Wikipedia"
},
{
"code": null,
"e": 2007,
"s": 1871,
"text": "A quick Wikipedia search will give you this definition of graph theory and below we will start to breakdown what it is and how it works"
},
{
"code": null,
"e": 2456,
"s": 2007,
"text": "Vertices/Nodes — These are the objects that will usually have properties about themselves and then connections to other objects in a graph. A simple example of a property that an object could have is weight or a value, in more complex objects this could also include things like cost, descriptive properties (color, size, weight), power, probabilities, etc... it will all depend on how the graph network is built and what it is trying to accomplish"
},
{
"code": null,
"e": 2672,
"s": 2456,
"text": "Edges/Links — The edges are essentially the relationship between objects or the road that connects them together. Objects that have edges between themselves have a relation, while those that are not connected don’t."
},
{
"code": null,
"e": 3310,
"s": 2672,
"text": "Directed/Undirected Graphs — The easiest way to understand the difference between a directed graph and an undirected graph is to think of the edge between an object as either a two-way road or a one-way road. A directed graph shows a relation from one object that passes whatever is in the relation to another object and that is not reciprocated back. An undirected graph is a connection between two objects but information about its relationship can flow both ways between them. It is a key point to point out that in directed graphs you can have two edges between a pair of nodes that simulate “an undirected” nature between the pairs."
},
{
"code": null,
"e": 3470,
"s": 3310,
"text": "Cyclical/Acyclical Graph — A cyclical graph is one that has a set of nodes that are connected in a closed-loop, acyclical do not have the closed-loop property."
},
{
"code": null,
"e": 3625,
"s": 3470,
"text": "The two most common themes in graphical representations for computers are adjacency matrix (sometimes referred to as incidence matrix) or adjacency lists."
},
{
"code": null,
"e": 4012,
"s": 3625,
"text": "Adjacency Matrix — In this method, a graph is converted into a matrix representation of a graph. The matrix will be an n x n shaped matrix where n represents the number of nodes and the values in the matrix represents the edges between the nodes as shown below. It is important to note that the matrix representation of an undirected graph will be a mirror of itself along the diagonal."
},
{
"code": null,
"e": 4183,
"s": 4012,
"text": "Adjacency List — This version of a graph is represented as the name implies a list. It is an unordered list that describes the neighbors of a vertex (or edge) in a graph."
},
{
"code": null,
"e": 4369,
"s": 4183,
"text": "Putting the graphs into these two kinds of forms allows us to computational program the graphs in a way that we can then set rules, relationships, properties, and changes to the graphs."
},
{
"code": null,
"e": 4577,
"s": 4369,
"text": "With these basic terms and concepts, we can explore a few examples of the basic problems that graph theory is used to solve and hopefully use them as examples of the building blocks for more complex systems."
},
{
"code": null,
"e": 4886,
"s": 4577,
"text": "One of the most basic things you may want to know about a graph network is the distance between paths and what is the optimal or shortest path between them. Some examples of where this might be useful are looking at an electricity grid or finding degrees of separation in a social network (a la Kevin Bacon)."
},
{
"code": null,
"e": 5162,
"s": 4886,
"text": "In almost all learning platforms the first two algorithms introduced with graph theory will be DFS and BFS. They are both algorithms that look to traverse a graph. In essence, both DFS and BFS are trying to accomplish the same goal but go about in slightly different manners."
},
{
"code": null,
"e": 5801,
"s": 5162,
"text": "Starting off with BFS, the principle behind this algorithm is to investigate all neighboring nodes from a starting place before moving to the following node. A queue is used to help denote which nodes have been visited and once that path has been completed, it will go to the next unvisited node and begin traversing the graph just as it did before, marking all visited nodes. This cycle will repeat for the entire graph until all nodes have been visited. In the queue, it is then possible to determine the shortest path from the starting point to the targeted endpoint. Below is an example of the pseudocode for the BFS search algorithm."
},
{
"code": null,
"e": 6215,
"s": 5801,
"text": " 1 procedure BFS(G, root) is 2 let Q be a queue 3 label root as discovered 4 Q.enqueue(root) 5 while Q is not empty do 6 v := Q.dequeue() 7 if v is the goal then 8 return v 9 for all edges from v to w in G.adjacentEdges(v) do10 if w is not labeled as discovered then11 label w as discovered12 Q.enqueue(w)"
},
{
"code": null,
"e": 6918,
"s": 6215,
"text": "DFS or Depth-First Search is a very similar algorithm to BFS, but it behaves slightly differently. When traversing through the graph, once a dead-end is reached in DFS, the algorithm will backtrack to a previous node that is connected to an unvisited node and continue in that path. It will then only go to a random node if it is unconnected from the original network of the graph. Both of these methods are some of the first methods taught to traverse along a graph and find the shortest path. Potential applications would be to apply it to a graph of a social network to determine potential suggestions of people with similar backgrounds, friends, or hobbies. Below is an example of a DFS Pseudocode."
},
{
"code": null,
"e": 7211,
"s": 6918,
"text": "1 procedure DFS_iterative(G, v) is2 let S be a stack3 S.push(v)4 while S is not empty do5 v = S.pop()6 if v is not labeled as discovered then7 label v as discovered8 for all edges from v to w in G.adjacentEdges(v) do9 S.push(w)"
},
{
"code": null,
"e": 7532,
"s": 7211,
"text": "There are more advanced graph-traversing methods such as the Bellman-Ford, Djikstra, and Kruskal for example. Each tries and tackles additional problems that could be encountered that the methods employed in BFS or DFS wouldn’t be able to tackle, for example, edges with negative weights/lengths, cyclical graphs, etc..."
},
{
"code": null,
"e": 7675,
"s": 7532,
"text": "Enumeration — In other words is evaluating and counting graphs that meet specific conditions or in other words solving combinatorics problems."
},
{
"code": null,
"e": 7827,
"s": 7675,
"text": "Subgraphs — Looking at graphs to determine if components of a graph are subcomponents of another graph or looking at “hereditary” traits between graphs"
},
{
"code": null,
"e": 8014,
"s": 7827,
"text": "Graph Coloring — Similar to enumeration, but applying coloring to the problem of a graph so that you will never have similar colors touching each other along coloring vertices in a graph"
},
{
"code": null,
"e": 8186,
"s": 8014,
"text": "Unification — Evaluating graphs that are more constrained (or have more information) and how they roll up into graphs or models that less constrained (or more generalized)"
},
{
"code": null,
"e": 8324,
"s": 8186,
"text": "Network Flow — An example of this type of problem would be like evaluating an energy grid to determine the flow of energy across a system"
},
{
"code": null,
"e": 8504,
"s": 8324,
"text": "Visibility Problems — Trying to solve a problem similar to the museum guard problem such that you figure out the minimum number of security guards to see an entire museum gallery."
},
{
"code": null,
"e": 8577,
"s": 8504,
"text": "Decomposition — Looking at breaking down graphs with certain conditions."
},
{
"code": null,
"e": 8733,
"s": 8577,
"text": "Route Problems — The shortest path example is one such problem, another would be the traveling salesman problem or the Seven Bridges of Konigsberg problem."
},
{
"code": null,
"e": 9183,
"s": 8733,
"text": "As mentioned before, graph theory is slowly becoming a more efficient way to represent real-world problems. The computing power to solve extremely complex relationships and details about any system can be now be done through programmatic methods. This article is intended to really serve as a primer of graph theory and to encourage you to continue learning about different methods of evaluating and implementing graphs to solve real-world problems."
},
{
"code": null,
"e": 9345,
"s": 9183,
"text": "One of my personal favorite subjects that I’m currently researching heavily is blockchains and you think of a blockchain in terms of graph theory to some extent."
}
]
|
Python program to find the second largest number in a list | In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a list, we need to display the second largest number in a list.
There are three approaches to solve the problem−
Live Demo
list1 = [11,22,1,2,5,67,21,32]
# to get unique elements
new_list = set(list1)
# removing the largest element from list1
new_list.remove(max(new_list))
# now computing the max element by built-in method?
print(max(new_list))
32
Live Demo
list1 = [11,22,1,2,5,67,21,32]
# using built-in sort method
list1.sort()
# second last element
print("Second largest element in the list is:", list1[-2])
Second largest element in the list is: 32
Live Demo
list1 = [11,22,1,2,5,67,21,32]
#assuming max_ is equal to maximum of element at 0th and 1st index
and secondmax is the minimum among them
max_=max(list1[0],list1[1])
secondmax=min(list1[0],list1[1])
for i in range(2,len(list1)):
# if found element is greater than max_
if list1[i]>max_:
secondmax=max_
max_=list1[i]
#if found element is greator than secondmax
else:
if list1[i]>secondmax:
secondmax=list1[i]
print("Second highest number is the list is : ",str(secondmax))
Second highest number is the list is : 32
In this article, we have learned about how we can find the second largest element in a list. | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1247,
"s": 1150,
"text": "Problem statement − We are given a list, we need to display the second largest number in a list."
},
{
"code": null,
"e": 1296,
"s": 1247,
"text": "There are three approaches to solve the problem−"
},
{
"code": null,
"e": 1307,
"s": 1296,
"text": " Live Demo"
},
{
"code": null,
"e": 1531,
"s": 1307,
"text": "list1 = [11,22,1,2,5,67,21,32]\n# to get unique elements\nnew_list = set(list1)\n# removing the largest element from list1\nnew_list.remove(max(new_list))\n# now computing the max element by built-in method?\nprint(max(new_list))"
},
{
"code": null,
"e": 1534,
"s": 1531,
"text": "32"
},
{
"code": null,
"e": 1545,
"s": 1534,
"text": " Live Demo"
},
{
"code": null,
"e": 1699,
"s": 1545,
"text": "list1 = [11,22,1,2,5,67,21,32]\n# using built-in sort method\nlist1.sort()\n# second last element\nprint(\"Second largest element in the list is:\", list1[-2])"
},
{
"code": null,
"e": 1741,
"s": 1699,
"text": "Second largest element in the list is: 32"
},
{
"code": null,
"e": 1752,
"s": 1741,
"text": " Live Demo"
},
{
"code": null,
"e": 2263,
"s": 1752,
"text": "list1 = [11,22,1,2,5,67,21,32]\n#assuming max_ is equal to maximum of element at 0th and 1st index\nand secondmax is the minimum among them\nmax_=max(list1[0],list1[1])\nsecondmax=min(list1[0],list1[1])\nfor i in range(2,len(list1)):\n # if found element is greater than max_\n if list1[i]>max_:\n secondmax=max_\n max_=list1[i]\n #if found element is greator than secondmax\n else:\n if list1[i]>secondmax:\n secondmax=list1[i]\nprint(\"Second highest number is the list is : \",str(secondmax))"
},
{
"code": null,
"e": 2305,
"s": 2263,
"text": "Second highest number is the list is : 32"
},
{
"code": null,
"e": 2398,
"s": 2305,
"text": "In this article, we have learned about how we can find the second largest element in a list."
}
]
|
Matplotlib vs. ggplot2: Which to Choose for 2020 and Beyond? | by Dario Radečić | Towards Data Science | 2020 is coming to an end (finally), and data visualization was never more important. Presenting something that looks like a 5-year-old made it is no longer an option, so data scientists need an attractive and simple-to-use data visualization library. We’ll compare two of these today — Matplotlib and ggplot2.
So, why these two? I’ll take my chances and say those are the first visualization libraries you’ll learn, depending on the programming language choice. I’ve grown to like ggplot2 a bit more, but today we’ll recreate five identical plots in both libraries and see how things go, both code-wise and aesthetics-wise.
What about the data? We’ll use two well-known datasets: mtcars and airline passengers. You can obtain the first through RStudio via the export CSV functionality, and the second is available here.
Here are the library imports for both R and Python:
R: library(ggplot2) Python: import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates mtcars = pd.read_csv('mtcars.csv')
We use histograms to visualize the distribution of a given variable. That’s just what we’ll do with the mtcars dataset — visualize the distribution of the MPG attribute.
Here is the code and results for R:
ggplot(mtcars, aes(x=mpg)) + geom_histogram(bins=15, fill='#087E8B', color='#02454d') + ggtitle('Histogram of MPG') + xlab('MPG') + ylab('Count')
And here’s the same for Python:
plt.figure(figsize=(12, 7)) plt.hist(mtcars['mpg'], bins=15, color='#087E8B', ec='#02454d')plt.title('Histogram of MPG') plt.xlabel('MPG') plt.ylabel('Count');
Both are very similar by default. Even the amount of code we need to write is more or less the same, so it’s hard to pick a favorite here. I like how Python’s x-axis starts from 0, but that can be easily altered in R. On the other hand, I like the lack of borders in R, but again, that’s something easy to implement in Python.
Winner: draw
Bar charts are made of different height rectangles, where the height represents the value for a given attribute segment. We’ll use them to compare counts for a different number of cylinders (attribute cyl).
Here is the code and results for R:
ggplot(mtcars, aes(x=cyl)) + geom_bar(fill='#087E8B', color='#02454d') + scale_x_continuous(breaks=seq(min(mtcars$cyl), max(mtcars$cyl), by=2)) + ggtitle('Bar chart of CYL') + xlab('Number of cylinders') + ylab('Count')
And here’s the same for Python:
bar_x = mtcars['cyl'].value_counts().index bar_height = mtcars['cyl'].value_counts().values plt.figure(figsize=(12, 7)) plt.bar(x=bar_x, height=bar_height, color='#087E8B', ec='#02454d') plt.xticks([4, 6, 8]) plt.title('Bar chart of CYL') plt.xlabel('Number of cylinders') plt.ylabel('Count');
There’s no arguing that R’s code is much tidier and simpler, as Python requires manual height calculation. Aesthetic-wise they are very similar, but I prefer the R version a bit more.
Winner: ggplot2
Scatter plots are used to visualize relationships between two variables. The idea is to see what happens to the second variable as the first one changes (goes up or down). We can also add another ‘dimension’ to the 2-dimensional plot by coloring the points from other attribute values.
We’ll use the scatter plot to visualize the relationship between HP and MPG attributes.
Here is the code and results for R:
ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point(aes(size=cyl, color=cyl)) + ggtitle('Scatter plot of HP vs MPG') + xlab('Horse power') + ylab('Miles per gallon')
And here’s the same for Python:
colors = [] for val in mtcars['cyl']: if val == 4: colors.append('#17314c') elif val == 6: colors.append('#326b99') else: colors.append('#54aef3') plt.figure(figsize=(12, 7)) plt.scatter(x=mtcars['hp'], y=mtcars['mpg'], s=mtcars['cyl'] * 20, c=colors) plt.title('Scatter plot of HP vs MPG') plt.xlabel('Horse power') plt.ylabel('Miles per gallon');
Code-wise it’s a clear win for R and ggplot2. Matplotlib doesn’t offer an easy way to color data points by some third attribute, so we have to do that step manually. The sizing is also a bit weird.
Winner: ggplot2
Boxplots are used to visualize the data through their quartiles. It’s common for them to have lines (whiskers) extending from the boxes, and those display variability outside the upper and lower quartiles. The line in the middle is the median value. Dots shown on top or bottom (after the whiskers) are considered to be outliers.
We’ll use a boxplot to visualize MPG by different CYL values.
Here is the code and results for R:
ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + geom_boxplot(fill='#087E8B', alpha=0.6) + ggtitle('Boxplot of CYL vs MPG') + xlab('Number of cylinders') + ylab('Miles per gallon')
And here’s the same for Python:
boxplot_data = [ mtcars[mtcars['cyl'] == 4]['mpg'].tolist(), mtcars[mtcars['cyl'] == 6]['mpg'].tolist(), mtcars[mtcars['cyl'] == 8]['mpg'].tolist() ] fig = plt.figure(1, figsize=(12, 7)) ax = fig.add_subplot(111) bp = ax.boxplot(boxplot_data, patch_artist=True) for box in bp['boxes']: box.set(facecolor='#087E8B', alpha=0.6, linewidth=2) for whisker in bp['whiskers']: whisker.set(linewidth=2) for median in bp['medians']: median.set(color='black', linewidth=3) ax.set_title('Boxplot of CYL vs MPG') ax.set_xlabel('Number of cylinders') ax.set_ylabel('Miles per galon') ax.set_xticklabels([4, 6, 8]);
One thing is immediately visible — Matplotlib requires so much code to produce a decent-looking boxplot. That’s not the case with ggplot2. R is the obvious winner here, by far.
Winner: ggplot2
We’ll now move away from the mtcars dataset to the airline passengers dataset. We’ll use it to create a simple line chart with a date-formatted x-axis. It’s not as easy as it sounds.
Here is the code and results for R:
ap <- read.csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv') ap$Month <- as.Date(paste(ap$Month, '-01', sep='')) ggplot(ap, aes(x=Month, y=Passengers)) + geom_line(size=1.5, color='#087E8B') + scale_x_date(date_breaks='1 year', date_labels='%Y') + ggtitle('Line chart of Airline passengers') + xlab('Year') + ylab('Count')
And here’s the same for Python:
ap = pd.read_csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv') ap['Month'] = ap['Month'].apply(lambda x: pd.to_datetime(f'{x}-01')) fig = plt.figure(1, figsize=(12, 7)) ax = fig.add_subplot(111) line = ax.plot(ap['Month'], ap['Passengers'], lw=2.5, color='#087E8B') formatter = mdates.DateFormatter('%Y')ax.xaxis.set_major_formatter(formatter) locator = mdates.YearLocator() ax.xaxis.set_major_locator(locator) ax.set_title('Line chart of Airline passengers') ax.set_xlabel('Year') ax.set_ylabel('Count');
The plots are pretty much identical, aesthetics-wise, but ggplot2 beats Matplotlib once again when it comes to code amount. It’s also much easier to format the x-axis to display dates in R than it is in Python.
Winner: ggplot2
In my opinion, ggplot2 is a clear winner when it comes to simple and good-looking data visualization. Almost always it boils down to very similar 3–5 lines of code, which is not the case with Python.
We haven’t touched a bit on plot customization, as the idea was to compare the ‘default’ stylings of the ‘default’ visualization libraries. Feel free to explore further on your own.
Thanks for reading.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Originally published at https://betterdatascience.com on September 29, 2020. | [
{
"code": null,
"e": 482,
"s": 172,
"text": "2020 is coming to an end (finally), and data visualization was never more important. Presenting something that looks like a 5-year-old made it is no longer an option, so data scientists need an attractive and simple-to-use data visualization library. We’ll compare two of these today — Matplotlib and ggplot2."
},
{
"code": null,
"e": 796,
"s": 482,
"text": "So, why these two? I’ll take my chances and say those are the first visualization libraries you’ll learn, depending on the programming language choice. I’ve grown to like ggplot2 a bit more, but today we’ll recreate five identical plots in both libraries and see how things go, both code-wise and aesthetics-wise."
},
{
"code": null,
"e": 992,
"s": 796,
"text": "What about the data? We’ll use two well-known datasets: mtcars and airline passengers. You can obtain the first through RStudio via the export CSV functionality, and the second is available here."
},
{
"code": null,
"e": 1044,
"s": 992,
"text": "Here are the library imports for both R and Python:"
},
{
"code": null,
"e": 1193,
"s": 1044,
"text": "R: library(ggplot2) Python: import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates mtcars = pd.read_csv('mtcars.csv')"
},
{
"code": null,
"e": 1363,
"s": 1193,
"text": "We use histograms to visualize the distribution of a given variable. That’s just what we’ll do with the mtcars dataset — visualize the distribution of the MPG attribute."
},
{
"code": null,
"e": 1399,
"s": 1363,
"text": "Here is the code and results for R:"
},
{
"code": null,
"e": 1548,
"s": 1399,
"text": "ggplot(mtcars, aes(x=mpg)) + geom_histogram(bins=15, fill='#087E8B', color='#02454d') + ggtitle('Histogram of MPG') + xlab('MPG') + ylab('Count')"
},
{
"code": null,
"e": 1580,
"s": 1548,
"text": "And here’s the same for Python:"
},
{
"code": null,
"e": 1740,
"s": 1580,
"text": "plt.figure(figsize=(12, 7)) plt.hist(mtcars['mpg'], bins=15, color='#087E8B', ec='#02454d')plt.title('Histogram of MPG') plt.xlabel('MPG') plt.ylabel('Count');"
},
{
"code": null,
"e": 2067,
"s": 1740,
"text": "Both are very similar by default. Even the amount of code we need to write is more or less the same, so it’s hard to pick a favorite here. I like how Python’s x-axis starts from 0, but that can be easily altered in R. On the other hand, I like the lack of borders in R, but again, that’s something easy to implement in Python."
},
{
"code": null,
"e": 2080,
"s": 2067,
"text": "Winner: draw"
},
{
"code": null,
"e": 2287,
"s": 2080,
"text": "Bar charts are made of different height rectangles, where the height represents the value for a given attribute segment. We’ll use them to compare counts for a different number of cylinders (attribute cyl)."
},
{
"code": null,
"e": 2323,
"s": 2287,
"text": "Here is the code and results for R:"
},
{
"code": null,
"e": 2551,
"s": 2323,
"text": "ggplot(mtcars, aes(x=cyl)) + geom_bar(fill='#087E8B', color='#02454d') + scale_x_continuous(breaks=seq(min(mtcars$cyl), max(mtcars$cyl), by=2)) + ggtitle('Bar chart of CYL') + xlab('Number of cylinders') + ylab('Count')"
},
{
"code": null,
"e": 2583,
"s": 2551,
"text": "And here’s the same for Python:"
},
{
"code": null,
"e": 2877,
"s": 2583,
"text": "bar_x = mtcars['cyl'].value_counts().index bar_height = mtcars['cyl'].value_counts().values plt.figure(figsize=(12, 7)) plt.bar(x=bar_x, height=bar_height, color='#087E8B', ec='#02454d') plt.xticks([4, 6, 8]) plt.title('Bar chart of CYL') plt.xlabel('Number of cylinders') plt.ylabel('Count');"
},
{
"code": null,
"e": 3061,
"s": 2877,
"text": "There’s no arguing that R’s code is much tidier and simpler, as Python requires manual height calculation. Aesthetic-wise they are very similar, but I prefer the R version a bit more."
},
{
"code": null,
"e": 3077,
"s": 3061,
"text": "Winner: ggplot2"
},
{
"code": null,
"e": 3363,
"s": 3077,
"text": "Scatter plots are used to visualize relationships between two variables. The idea is to see what happens to the second variable as the first one changes (goes up or down). We can also add another ‘dimension’ to the 2-dimensional plot by coloring the points from other attribute values."
},
{
"code": null,
"e": 3451,
"s": 3363,
"text": "We’ll use the scatter plot to visualize the relationship between HP and MPG attributes."
},
{
"code": null,
"e": 3487,
"s": 3451,
"text": "Here is the code and results for R:"
},
{
"code": null,
"e": 3653,
"s": 3487,
"text": "ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point(aes(size=cyl, color=cyl)) + ggtitle('Scatter plot of HP vs MPG') + xlab('Horse power') + ylab('Miles per gallon')"
},
{
"code": null,
"e": 3685,
"s": 3653,
"text": "And here’s the same for Python:"
},
{
"code": null,
"e": 4046,
"s": 3685,
"text": "colors = [] for val in mtcars['cyl']: if val == 4: colors.append('#17314c') elif val == 6: colors.append('#326b99') else: colors.append('#54aef3') plt.figure(figsize=(12, 7)) plt.scatter(x=mtcars['hp'], y=mtcars['mpg'], s=mtcars['cyl'] * 20, c=colors) plt.title('Scatter plot of HP vs MPG') plt.xlabel('Horse power') plt.ylabel('Miles per gallon');"
},
{
"code": null,
"e": 4244,
"s": 4046,
"text": "Code-wise it’s a clear win for R and ggplot2. Matplotlib doesn’t offer an easy way to color data points by some third attribute, so we have to do that step manually. The sizing is also a bit weird."
},
{
"code": null,
"e": 4260,
"s": 4244,
"text": "Winner: ggplot2"
},
{
"code": null,
"e": 4590,
"s": 4260,
"text": "Boxplots are used to visualize the data through their quartiles. It’s common for them to have lines (whiskers) extending from the boxes, and those display variability outside the upper and lower quartiles. The line in the middle is the median value. Dots shown on top or bottom (after the whiskers) are considered to be outliers."
},
{
"code": null,
"e": 4652,
"s": 4590,
"text": "We’ll use a boxplot to visualize MPG by different CYL values."
},
{
"code": null,
"e": 4688,
"s": 4652,
"text": "Here is the code and results for R:"
},
{
"code": null,
"e": 4873,
"s": 4688,
"text": "ggplot(mtcars, aes(x=as.factor(cyl), y=mpg)) + geom_boxplot(fill='#087E8B', alpha=0.6) + ggtitle('Boxplot of CYL vs MPG') + xlab('Number of cylinders') + ylab('Miles per gallon')"
},
{
"code": null,
"e": 4905,
"s": 4873,
"text": "And here’s the same for Python:"
},
{
"code": null,
"e": 5531,
"s": 4905,
"text": "boxplot_data = [ mtcars[mtcars['cyl'] == 4]['mpg'].tolist(), mtcars[mtcars['cyl'] == 6]['mpg'].tolist(), mtcars[mtcars['cyl'] == 8]['mpg'].tolist() ] fig = plt.figure(1, figsize=(12, 7)) ax = fig.add_subplot(111) bp = ax.boxplot(boxplot_data, patch_artist=True) for box in bp['boxes']: box.set(facecolor='#087E8B', alpha=0.6, linewidth=2) for whisker in bp['whiskers']: whisker.set(linewidth=2) for median in bp['medians']: median.set(color='black', linewidth=3) ax.set_title('Boxplot of CYL vs MPG') ax.set_xlabel('Number of cylinders') ax.set_ylabel('Miles per galon') ax.set_xticklabels([4, 6, 8]);"
},
{
"code": null,
"e": 5708,
"s": 5531,
"text": "One thing is immediately visible — Matplotlib requires so much code to produce a decent-looking boxplot. That’s not the case with ggplot2. R is the obvious winner here, by far."
},
{
"code": null,
"e": 5724,
"s": 5708,
"text": "Winner: ggplot2"
},
{
"code": null,
"e": 5907,
"s": 5724,
"text": "We’ll now move away from the mtcars dataset to the airline passengers dataset. We’ll use it to create a simple line chart with a date-formatted x-axis. It’s not as easy as it sounds."
},
{
"code": null,
"e": 5943,
"s": 5907,
"text": "Here is the code and results for R:"
},
{
"code": null,
"e": 6314,
"s": 5943,
"text": "ap <- read.csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv') ap$Month <- as.Date(paste(ap$Month, '-01', sep='')) ggplot(ap, aes(x=Month, y=Passengers)) + geom_line(size=1.5, color='#087E8B') + scale_x_date(date_breaks='1 year', date_labels='%Y') + ggtitle('Line chart of Airline passengers') + xlab('Year') + ylab('Count')"
},
{
"code": null,
"e": 6346,
"s": 6314,
"text": "And here’s the same for Python:"
},
{
"code": null,
"e": 6892,
"s": 6346,
"text": "ap = pd.read_csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv') ap['Month'] = ap['Month'].apply(lambda x: pd.to_datetime(f'{x}-01')) fig = plt.figure(1, figsize=(12, 7)) ax = fig.add_subplot(111) line = ax.plot(ap['Month'], ap['Passengers'], lw=2.5, color='#087E8B') formatter = mdates.DateFormatter('%Y')ax.xaxis.set_major_formatter(formatter) locator = mdates.YearLocator() ax.xaxis.set_major_locator(locator) ax.set_title('Line chart of Airline passengers') ax.set_xlabel('Year') ax.set_ylabel('Count');"
},
{
"code": null,
"e": 7103,
"s": 6892,
"text": "The plots are pretty much identical, aesthetics-wise, but ggplot2 beats Matplotlib once again when it comes to code amount. It’s also much easier to format the x-axis to display dates in R than it is in Python."
},
{
"code": null,
"e": 7119,
"s": 7103,
"text": "Winner: ggplot2"
},
{
"code": null,
"e": 7319,
"s": 7119,
"text": "In my opinion, ggplot2 is a clear winner when it comes to simple and good-looking data visualization. Almost always it boils down to very similar 3–5 lines of code, which is not the case with Python."
},
{
"code": null,
"e": 7501,
"s": 7319,
"text": "We haven’t touched a bit on plot customization, as the idea was to compare the ‘default’ stylings of the ‘default’ visualization libraries. Feel free to explore further on your own."
},
{
"code": null,
"e": 7521,
"s": 7501,
"text": "Thanks for reading."
},
{
"code": null,
"e": 7704,
"s": 7521,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 7715,
"s": 7704,
"text": "medium.com"
}
]
|
MySQL Tryit Editor v1.0 | SELECT * FROM Customers
WHERE Country='Mexico';
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 24,
"s": 0,
"text": "SELECT * FROM Customers"
},
{
"code": null,
"e": 48,
"s": 24,
"text": "WHERE Country='Mexico';"
},
{
"code": null,
"e": 50,
"s": 48,
"text": ""
},
{
"code": null,
"e": 122,
"s": 59,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 182,
"s": 122,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 250,
"s": 182,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 288,
"s": 250,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 373,
"s": 288,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 547,
"s": 373,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 598,
"s": 547,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 666,
"s": 598,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 837,
"s": 666,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 937,
"s": 837,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 987,
"s": 937,
"text": "WebSQL is supported in Chrome, Safari, and Opera."
}
]
|
IntStream summaryStatistics() in Java - GeeksforGeeks | 21 Mar, 2018
IntStream summaryStatistics() returns an IntSummaryStatistics describing various summary data about the elements of this stream like count of number of elements in the IntStream, average of all elements present in IntStream, minimum and maximum element in the IntStream and so on. This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Syntax :
IntSummaryStatistics summaryStatistics()
Parameters :
IntSummaryStatistics : A state object for collecting statistics such as count, min, max, sum, and average.
IntSummaryStatistics : A state object for collecting statistics such as count, min, max, sum, and average.
Return Value : IntSummaryStatistics summaryStatistics() returns an IntSummaryStatistics describing various summary data about the elements of this stream.
Note : IntStream summaryStatistics() is a special case of a reduction. A reduction operation, also known as fold takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation. The combining operation can be finding the sum or maximum of a set of numbers.
Example 1 : Using IntStream summaryStatistics() to get the IntSummaryStatistics of elements present in given IntStream.
// Java code for IntStream summaryStatistics()// to get various summary data about the// elements of the stream.import java.util.stream.IntStream;import java.util.IntSummaryStatistics; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(4, 5, 6, 7); // Using IntStream summaryStatistics() IntSummaryStatistics summary_data = stream.summaryStatistics(); // Displaying the various summary data // about the elements of the stream System.out.println(summary_data); }}
Output :
IntSummaryStatistics{count=4, sum=22, min=4, average=5.500000, max=7}
Example 2 :Using IntStream summaryStatistics() to get the IntSummaryStatistics of elements present in given range.
// Java code for IntStream summaryStatistics()// to get various summary data about the// elements of the stream.import java.util.stream.IntStream;import java.util.IntSummaryStatistics; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream of elements // in range [5, 9) IntStream stream = IntStream.range(5, 9); // Using IntStream summaryStatistics() IntSummaryStatistics summary_data = stream.summaryStatistics(); // Displaying the various summary data // about the elements of the stream System.out.println(summary_data); }}
Output :
IntSummaryStatistics{count=4, sum=26, min=5, average=6.500000, max=8}
Java - util package
java-intstream
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java | [
{
"code": null,
"e": 23687,
"s": 23659,
"text": "\n21 Mar, 2018"
},
{
"code": null,
"e": 24067,
"s": 23687,
"text": "IntStream summaryStatistics() returns an IntSummaryStatistics describing various summary data about the elements of this stream like count of number of elements in the IntStream, average of all elements present in IntStream, minimum and maximum element in the IntStream and so on. This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect."
},
{
"code": null,
"e": 24076,
"s": 24067,
"text": "Syntax :"
},
{
"code": null,
"e": 24118,
"s": 24076,
"text": "IntSummaryStatistics summaryStatistics()\n"
},
{
"code": null,
"e": 24131,
"s": 24118,
"text": "Parameters :"
},
{
"code": null,
"e": 24238,
"s": 24131,
"text": "IntSummaryStatistics : A state object for collecting statistics such as count, min, max, sum, and average."
},
{
"code": null,
"e": 24345,
"s": 24238,
"text": "IntSummaryStatistics : A state object for collecting statistics such as count, min, max, sum, and average."
},
{
"code": null,
"e": 24500,
"s": 24345,
"text": "Return Value : IntSummaryStatistics summaryStatistics() returns an IntSummaryStatistics describing various summary data about the elements of this stream."
},
{
"code": null,
"e": 24824,
"s": 24500,
"text": "Note : IntStream summaryStatistics() is a special case of a reduction. A reduction operation, also known as fold takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation. The combining operation can be finding the sum or maximum of a set of numbers."
},
{
"code": null,
"e": 24944,
"s": 24824,
"text": "Example 1 : Using IntStream summaryStatistics() to get the IntSummaryStatistics of elements present in given IntStream."
},
{
"code": "// Java code for IntStream summaryStatistics()// to get various summary data about the// elements of the stream.import java.util.stream.IntStream;import java.util.IntSummaryStatistics; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(4, 5, 6, 7); // Using IntStream summaryStatistics() IntSummaryStatistics summary_data = stream.summaryStatistics(); // Displaying the various summary data // about the elements of the stream System.out.println(summary_data); }}",
"e": 25574,
"s": 24944,
"text": null
},
{
"code": null,
"e": 25583,
"s": 25574,
"text": "Output :"
},
{
"code": null,
"e": 25654,
"s": 25583,
"text": "IntSummaryStatistics{count=4, sum=22, min=4, average=5.500000, max=7}\n"
},
{
"code": null,
"e": 25769,
"s": 25654,
"text": "Example 2 :Using IntStream summaryStatistics() to get the IntSummaryStatistics of elements present in given range."
},
{
"code": "// Java code for IntStream summaryStatistics()// to get various summary data about the// elements of the stream.import java.util.stream.IntStream;import java.util.IntSummaryStatistics; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream of elements // in range [5, 9) IntStream stream = IntStream.range(5, 9); // Using IntStream summaryStatistics() IntSummaryStatistics summary_data = stream.summaryStatistics(); // Displaying the various summary data // about the elements of the stream System.out.println(summary_data); }}",
"e": 26432,
"s": 25769,
"text": null
},
{
"code": null,
"e": 26441,
"s": 26432,
"text": "Output :"
},
{
"code": null,
"e": 26512,
"s": 26441,
"text": "IntSummaryStatistics{count=4, sum=26, min=5, average=6.500000, max=8}\n"
},
{
"code": null,
"e": 26532,
"s": 26512,
"text": "Java - util package"
},
{
"code": null,
"e": 26547,
"s": 26532,
"text": "java-intstream"
},
{
"code": null,
"e": 26559,
"s": 26547,
"text": "java-stream"
},
{
"code": null,
"e": 26564,
"s": 26559,
"text": "Java"
},
{
"code": null,
"e": 26569,
"s": 26564,
"text": "Java"
},
{
"code": null,
"e": 26667,
"s": 26569,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26676,
"s": 26667,
"text": "Comments"
},
{
"code": null,
"e": 26689,
"s": 26676,
"text": "Old Comments"
},
{
"code": null,
"e": 26740,
"s": 26689,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26770,
"s": 26740,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26801,
"s": 26770,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26833,
"s": 26801,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26852,
"s": 26833,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26870,
"s": 26852,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26902,
"s": 26870,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26922,
"s": 26902,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26946,
"s": 26922,
"text": "Singleton Class in Java"
}
]
|
How can we fetch all the records from a particular MySQL table? | We can fetch all the record from a MySQL table by using SELECT * from table_name; query. An example is as follows, fetched all the records from ‘Employee’ table −
mysql> Select * from Employee;
+------+--------+
| Id | Name |
+------+--------+
| 100 | Ram |
| 200 | Gaurav |
| 300 | Mohan |
+------+--------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1225,
"s": 1062,
"text": "We can fetch all the record from a MySQL table by using SELECT * from table_name; query. An example is as follows, fetched all the records from ‘Employee’ table −"
},
{
"code": null,
"e": 1407,
"s": 1225,
"text": "mysql> Select * from Employee;\n+------+--------+\n| Id | Name |\n+------+--------+\n| 100 | Ram |\n| 200 | Gaurav |\n| 300 | Mohan |\n+------+--------+\n3 rows in set (0.00 sec)"
}
]
|
Callable and Future in Java
| java.util.concurrent.The callable object can return the computed result done by a thread in contrast to a runnable interface which can only run the thread. The Callable object returns a Future object which provides methods to monitor the progress of a task being executed by a thread. The future object can be used to check the status of a Callable and then retrieve the result from the Callable once the thread is done. It also provides timeout functionality.
//submit the callable using ThreadExecutor
//and get the result as a Future object
Future<Long> result10 = executor.submit(new FactorialService(10));
//get the result using get method of the Future object
//get method waits till the thread execution and then return the result of the execution.
Long factorial10 = result10.get();
The following TestThread program shows usage of Futures and Callables in the thread based environment.
Live Demo
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newSingleThreadExecutor();
System.out.println("Factorial Service called for 10!");
Future<Long> result10 = executor.submit(new FactorialService(10));
System.out.println("Factorial Service called for 20!");
Future<Long> result20 = executor.submit(new FactorialService(20));
Long factorial10 = result10.get();
System.out.println("10! = " + factorial10);
Long factorial20 = result20.get();
System.out.println("20! = " + factorial20);
executor.shutdown();
}
static class FactorialService implements Callable<Long> {
private int number;
public FactorialService(int number) {
this.number = number;
}
@Override
public Long call() throws Exception {
return factorial();
}
private Long factorial() throws InterruptedException {
long result = 1;
while (number != 0) {
result = number * result;
number--;
Thread.sleep(100);
}
return result;
}
}
}
This will produce the following result.
Factorial Service called for 10!
Factorial Service called for 20!
10! = 3628800
20! = 2432902008176640000 | [
{
"code": null,
"e": 1523,
"s": 1062,
"text": "java.util.concurrent.The callable object can return the computed result done by a thread in contrast to a runnable interface which can only run the thread. The Callable object returns a Future object which provides methods to monitor the progress of a task being executed by a thread. The future object can be used to check the status of a Callable and then retrieve the result from the Callable once the thread is done. It also provides timeout functionality."
},
{
"code": null,
"e": 1856,
"s": 1523,
"text": "//submit the callable using ThreadExecutor\n//and get the result as a Future object\nFuture<Long> result10 = executor.submit(new FactorialService(10)); \n\n//get the result using get method of the Future object\n//get method waits till the thread execution and then return the result of the execution.\nLong factorial10 = result10.get();"
},
{
"code": null,
"e": 1959,
"s": 1856,
"text": "The following TestThread program shows usage of Futures and Callables in the thread based environment."
},
{
"code": null,
"e": 1969,
"s": 1959,
"text": "Live Demo"
},
{
"code": null,
"e": 3448,
"s": 1969,
"text": "import java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n\npublic class TestThread {\n\n public static void main(final String[] arguments) throws InterruptedException, ExecutionException {\n\n ExecutorService executor = Executors.newSingleThreadExecutor();\n\n System.out.println(\"Factorial Service called for 10!\");\n Future<Long> result10 = executor.submit(new FactorialService(10));\n\n System.out.println(\"Factorial Service called for 20!\");\n Future<Long> result20 = executor.submit(new FactorialService(20));\n\n Long factorial10 = result10.get();\n System.out.println(\"10! = \" + factorial10);\n\n Long factorial20 = result20.get();\n System.out.println(\"20! = \" + factorial20);\n\n executor.shutdown();\n } \n\n static class FactorialService implements Callable<Long> {\n private int number;\n\n public FactorialService(int number) {\n this.number = number;\n }\n\n @Override\n public Long call() throws Exception {\n return factorial();\n }\n\n private Long factorial() throws InterruptedException {\n long result = 1;\n \n while (number != 0) { \n result = number * result;\n number--;\n Thread.sleep(100); \n }\n return result; \n }\n }\n}"
},
{
"code": null,
"e": 3488,
"s": 3448,
"text": "This will produce the following result."
},
{
"code": null,
"e": 3594,
"s": 3488,
"text": "Factorial Service called for 10!\nFactorial Service called for 20!\n10! = 3628800\n20! = 2432902008176640000"
}
]
|
Change tinyint default value to 1 in MySQL? | You can use DEFAULT command for this. Following is the syntax −
alter table yourTableName change yourColumnName yourColumnName TINYINT(1) DEFAULT 1 NOT NULL;
Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
UserName varchar(20),
UserAge int,
isMarried tinyint(1)
);
Query OK, 0 rows affected (0.80 sec)
Let us check the description of table −
mysql> desc DemoTable;
This will produce the following output −
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| UserName | varchar(20) | YES | | NULL | |
| UserAge | int(11) | YES | | NULL | |
| isMarried | tinyint(1) | YES | | NULL | |
+-----------+-------------+------+-----+---------+----------------+
4 rows in set (0.21 sec)
Following is the query to change tinyint default value to 1 −
mysql> alter table DemoTable change isMarried isMarried TINYINT(1) DEFAULT 1 NOT NULL;
Query OK, 0 rows affected (1.29 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again. The default value of tinyint has been changed to 1 −
mysql> desc DemoTable;
This will produce the following output −
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| UserName | varchar(20) | YES | | NULL | |
| UserAge | int(11) | YES | | NULL | |
| isMarried | tinyint(1) | NO | | 1 | |
+-----------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1126,
"s": 1062,
"text": "You can use DEFAULT command for this. Following is the syntax −"
},
{
"code": null,
"e": 1220,
"s": 1126,
"text": "alter table yourTableName change yourColumnName yourColumnName TINYINT(1) DEFAULT 1 NOT NULL;"
},
{
"code": null,
"e": 1250,
"s": 1220,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1434,
"s": 1250,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n UserName varchar(20),\n UserAge int,\n isMarried tinyint(1)\n);\nQuery OK, 0 rows affected (0.80 sec)"
},
{
"code": null,
"e": 1474,
"s": 1434,
"text": "Let us check the description of table −"
},
{
"code": null,
"e": 1497,
"s": 1474,
"text": "mysql> desc DemoTable;"
},
{
"code": null,
"e": 1538,
"s": 1497,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2107,
"s": 1538,
"text": "+-----------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-----------+-------------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| UserName | varchar(20) | YES | | NULL | |\n| UserAge | int(11) | YES | | NULL | |\n| isMarried | tinyint(1) | YES | | NULL | |\n+-----------+-------------+------+-----+---------+----------------+\n4 rows in set (0.21 sec)"
},
{
"code": null,
"e": 2169,
"s": 2107,
"text": "Following is the query to change tinyint default value to 1 −"
},
{
"code": null,
"e": 2330,
"s": 2169,
"text": "mysql> alter table DemoTable change isMarried isMarried TINYINT(1) DEFAULT 1 NOT NULL;\nQuery OK, 0 rows affected (1.29 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2433,
"s": 2330,
"text": "Let us check the description of table once again. The default value of tinyint has been changed to 1 −"
},
{
"code": null,
"e": 2456,
"s": 2433,
"text": "mysql> desc DemoTable;"
},
{
"code": null,
"e": 2497,
"s": 2456,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3066,
"s": 2497,
"text": "+-----------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-----------+-------------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| UserName | varchar(20) | YES | | NULL | |\n| UserAge | int(11) | YES | | NULL | |\n| isMarried | tinyint(1) | NO | | 1 | |\n+-----------+-------------+------+-----+---------+----------------+\n4 rows in set (0.00 sec)"
}
]
|
How to convert a JSON array to CSV in Java? | The JSON can be used as a data-interchange format and is lightweight and language independent. A JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. We can convert a JSON Array to CSV format using org.json.CDL class, it can provide a static method toString(), to convert a JSONArray into comma-delimited text. We need to import org.apache.commons.io.FileUtils package to store the data in a CSV file using the writeStringToFile() method.
public static java.lang.String toString(JSONArray ja) throws JSONException
In the below example, we can convert a JSON Array to CSV format.
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.*;
public class ConvertJsonToCSVTest {
public static void main(String[] args) throws JSONException {
String jsonArrayString = "{\"fileName\": [{\"first name\": \"Ravi\",\"last name\": \"Chandra\",\"location\": \"Bangalore\"}]}";
JSONObject output;
try {
output = new JSONObject(jsonArrayString);
JSONArray docs = output.getJSONArray("fileName");
File file = new File("EmpDetails.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
System.out.println("Data has been Sucessfully Writeen to "+ file);
System.out.println(csv);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Data has been Sucessfully Writeen to EmpDetails.csv
last name,first name,location
Chandra,Ravi,Bangalore | [
{
"code": null,
"e": 1558,
"s": 1062,
"text": "The JSON can be used as a data-interchange format and is lightweight and language independent. A JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. We can convert a JSON Array to CSV format using org.json.CDL class, it can provide a static method toString(), to convert a JSONArray into comma-delimited text. We need to import org.apache.commons.io.FileUtils package to store the data in a CSV file using the writeStringToFile() method."
},
{
"code": null,
"e": 1633,
"s": 1558,
"text": "public static java.lang.String toString(JSONArray ja) throws JSONException"
},
{
"code": null,
"e": 1698,
"s": 1633,
"text": "In the below example, we can convert a JSON Array to CSV format."
},
{
"code": null,
"e": 2490,
"s": 1698,
"text": "import java.io.File;\nimport org.apache.commons.io.FileUtils;\nimport org.json.*;\npublic class ConvertJsonToCSVTest {\n public static void main(String[] args) throws JSONException {\n String jsonArrayString = \"{\\\"fileName\\\": [{\\\"first name\\\": \\\"Ravi\\\",\\\"last name\\\": \\\"Chandra\\\",\\\"location\\\": \\\"Bangalore\\\"}]}\";\n JSONObject output;\n try {\n output = new JSONObject(jsonArrayString);\n JSONArray docs = output.getJSONArray(\"fileName\");\n File file = new File(\"EmpDetails.csv\");\n String csv = CDL.toString(docs);\n FileUtils.writeStringToFile(file, csv);\n System.out.println(\"Data has been Sucessfully Writeen to \"+ file);\n System.out.println(csv);\n }\n catch(Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2595,
"s": 2490,
"text": "Data has been Sucessfully Writeen to EmpDetails.csv\nlast name,first name,location\nChandra,Ravi,Bangalore"
}
]
|
Simulated Annealing - GeeksforGeeks | 01 Nov, 2021
Problem : Given a cost function f: R^n –> R, find an n-tuple that minimizes the value of f. Note that minimizing the value of a function is algorithmically equivalent to maximization (since we can redefine the cost function as 1-f).Many of you with a background in calculus/analysis are likely familiar with simple optimization for single variable functions. For instance, the function f(x) = x^2 + 2x can be optimized setting the first derivative equal to zero, obtaining the solution x = -1 yielding the minimum value f(-1) = -1. This technique suffices for simple functions with few variables. However, it is often the case that researchers are interested in optimizing functions of several variables, in which case the solution can only be obtained computationally.
One excellent example of a difficult optimization task is the chip floor planning problem. Imagine you’re working at Intel and you’re tasked with designing the layout for an integrated circuit. You have a set of modules of different shapes/sizes and a fixed area on which the modules can be placed. There are a number of objectives you want to achieve: maximizing ability for wires to connect components, minimize net area, minimize chip cost, etc. With these in mind, you create a cost function, taking all, say, 1000 variable configurations and returning a single real value representing the ‘cost’ of the input configuration. We call this the objective function, since the goal is to minimize its value. A naive algorithm would be a complete space search — we search all possible configurations until we find the minimum. This may suffice for functions of few variables, but the problem we have in mind would entail such a brute force algorithm to fun in O(n!).
Due to the computational intractability of problems like these, and other NP-hard problems, many optimization heuristics have been developed in an attempt to yield a good, albeit potentially suboptimal, value. In our case, we don’t necessarily need to find a strictly optimal value — finding a near-optimal value would satisfy our goal. One widely used technique is simulated annealing, by which we introduce a degree of stochasticity, potentially shifting from a better solution to a worse one, in an attempt to escape local minima and converge to a value closer to the global optimum.
Simulated annealing is based on metallurgical practices by which a material is heated to a high temperature and cooled. At high temperatures, atoms may shift unpredictably, often eliminating impurities as the material cools into a pure crystal. This is replicated via the simulated annealing optimization algorithm, with energy state corresponding to current solution.In this algorithm, we define an initial temperature, often set as 1, and a minimum temperature, on the order of 10^-4. The current temperature is multiplied by some fraction alpha and thus decreased until it reaches the minimum temperature. For each distinct temperature value, we run the core optimization routine a fixed number of times. The optimization routine consists of finding a neighboring solution and accepting it with probability e^(f(c) – f(n)) where c is the current solution and n is the neighboring solution. A neighboring solution is found by applying a slight perturbation to the current solution. This randomness is useful to escape the common pitfall of optimization heuristics — getting trapped in local minima. By potentially accepting a less optimal solution than we currently have, and accepting it with probability inverse to the increase in cost, the algorithm is more likely to converge near the global optimum. Designing a neighbor function is quite tricky and must be done on a case by case basis, but below are some ideas for finding neighbors in locational optimization problems.
Move all points 0 or 1 units in a random direction
Shift input elements randomly
Swap random elements in input sequence
Permute input sequence
Partition input sequence into a random number of segments and permute segments
One caveat is that we need to provide an initial solution so the algorithm knows where to start. This can be done in two ways: (1) using prior knowledge about the problem to input a good starting point and (2) generating a random solution. Although generating a random solution is worse and can occasionally inhibit the success of the algorithm, it is the only option for problems where we know nothing about the landscape.
There are many other optimization techniques, although simulated annealing is a useful, stochastic optimization heuristic for large, discrete search spaces in which optimality is prioritized over time. Below, I’ve included a basic framework for locational-based simulated annealing (perhaps the most applicable flavor of optimization for simulated annealing). Of course, the cost function, candidate generation function, and neighbor function must be defined based on the specific problem at hand, although the core optimization routine has already been implemented.
Java
// Java program to implement Simulated Annealingimport java.util.*; public class SimulatedAnnealing { // Initial and final temperature public static double T = 1; // Simulated Annealing parameters // Temperature at which iteration terminates static final double Tmin = .0001; // Decrease in temperature static final double alpha = 0.9; // Number of iterations of annealing // before decreasing temperature static final int numIterations = 100; // Locational parameters // Target array is discretized as M*N grid static final int M = 5, N = 5; // Number of objects desired static final int k = 5; public static void main(String[] args) { // Problem: place k objects in an MxN target // plane yielding minimal cost according to // defined objective function // Set of all possible candidate locations String[][] sourceArray = new String[M][N]; // Global minimum Solution min = new Solution(Double.MAX_VALUE, null); // Generates random initial candidate solution // before annealing process Solution currentSol = genRandSol(); // Continues annealing until reaching minimum // temperature while (T > Tmin) { for (int i=0;i<numIterations;i++){ // Reassigns global minimum accordingly if (currentSol.CVRMSE < min.CVRMSE){ min = currentSol; } Solution newSol = neighbor(currentSol); double ap = Math.pow(Math.E, (currentSol.CVRMSE - newSol.CVRMSE)/T); if (ap > Math.random()) currentSol = newSol; } T *= alpha; // Decreases T, cooling phase } //Returns minimum value based on optimization System.out.println(min.CVRMSE+"\n\n"); for(String[] row:sourceArray) Arrays.fill(row, "X"); // Displays for (int object:min.config) { int[] coord = indexToPoints(object); sourceArray[coord[0]][coord[1]] = "-"; } // Displays optimal location for (String[] row:sourceArray) System.out.println(Arrays.toString(row)); } // Given current configuration, returns "neighboring" // configuration (i.e. very similar) // integer of k points each in range [0, n) /* Different neighbor selection strategies: * Move all points 0 or 1 units in a random direction * Shift input elements randomly * Swap random elements in input sequence * Permute input sequence * Partition input sequence into a random number of segments and permute segments */ public static Solution neighbor(Solution currentSol){ // Slight perturbation to the current solution // to avoid getting stuck in local minimas // Returning for the sake of compilation return currentSol; } // Generates random solution via modified Fisher-Yates // shuffle for first k elements // Pseudorandomly selects k integers from the interval // [0, n-1] public static Solution genRandSol(){ // Instantiating for the sake of compilation int[] a = {1, 2, 3, 4, 5}; // Returning for the sake of compilation return new Solution(-1, a); } // Complexity is O(M*N*k), asymptotically tight public static double cost(int[] inputConfiguration){ // Given specific configuration, return object // solution with assigned cost return -1; //Returning for the sake of compilation } // Mapping from [0, M*N] --> [0,M]x[0,N] public static int[] indexToPoints(int index){ int[] points = {index%M, index/M}; return points; } // Class solution, bundling configuration with error static class Solution { // function value of instance of solution; // using coefficient of variance root mean // squared error public double CVRMSE; public int[] config; // Configuration array public Solution(double CVRMSE, int[] configuration) { this.CVRMSE = CVRMSE; config = configuration; } }}
Output :
-1.0
[X, -, X, X, X]
[-, X, X, X, X]
[-, X, X, X, X]
[-, X, X, X, X]
[-, X, X, X, X]
This article is contributed by Joel Abraham . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Piyushgupta12
surinderdawra388
kashishsoda
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Fizz Buzz Implementation
Count all possible paths from top left to bottom right of a mXn matrix
Check if a number is Palindrome
Program to multiply two matrices
Generate all permutation of a set in Python
Merge two sorted arrays with O(1) extra space
Count ways to reach the n'th stair | [
{
"code": null,
"e": 25963,
"s": 25935,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 26734,
"s": 25963,
"text": "Problem : Given a cost function f: R^n –> R, find an n-tuple that minimizes the value of f. Note that minimizing the value of a function is algorithmically equivalent to maximization (since we can redefine the cost function as 1-f).Many of you with a background in calculus/analysis are likely familiar with simple optimization for single variable functions. For instance, the function f(x) = x^2 + 2x can be optimized setting the first derivative equal to zero, obtaining the solution x = -1 yielding the minimum value f(-1) = -1. This technique suffices for simple functions with few variables. However, it is often the case that researchers are interested in optimizing functions of several variables, in which case the solution can only be obtained computationally. "
},
{
"code": null,
"e": 27699,
"s": 26734,
"text": "One excellent example of a difficult optimization task is the chip floor planning problem. Imagine you’re working at Intel and you’re tasked with designing the layout for an integrated circuit. You have a set of modules of different shapes/sizes and a fixed area on which the modules can be placed. There are a number of objectives you want to achieve: maximizing ability for wires to connect components, minimize net area, minimize chip cost, etc. With these in mind, you create a cost function, taking all, say, 1000 variable configurations and returning a single real value representing the ‘cost’ of the input configuration. We call this the objective function, since the goal is to minimize its value. A naive algorithm would be a complete space search — we search all possible configurations until we find the minimum. This may suffice for functions of few variables, but the problem we have in mind would entail such a brute force algorithm to fun in O(n!)."
},
{
"code": null,
"e": 28287,
"s": 27699,
"text": "Due to the computational intractability of problems like these, and other NP-hard problems, many optimization heuristics have been developed in an attempt to yield a good, albeit potentially suboptimal, value. In our case, we don’t necessarily need to find a strictly optimal value — finding a near-optimal value would satisfy our goal. One widely used technique is simulated annealing, by which we introduce a degree of stochasticity, potentially shifting from a better solution to a worse one, in an attempt to escape local minima and converge to a value closer to the global optimum. "
},
{
"code": null,
"e": 29767,
"s": 28287,
"text": "Simulated annealing is based on metallurgical practices by which a material is heated to a high temperature and cooled. At high temperatures, atoms may shift unpredictably, often eliminating impurities as the material cools into a pure crystal. This is replicated via the simulated annealing optimization algorithm, with energy state corresponding to current solution.In this algorithm, we define an initial temperature, often set as 1, and a minimum temperature, on the order of 10^-4. The current temperature is multiplied by some fraction alpha and thus decreased until it reaches the minimum temperature. For each distinct temperature value, we run the core optimization routine a fixed number of times. The optimization routine consists of finding a neighboring solution and accepting it with probability e^(f(c) – f(n)) where c is the current solution and n is the neighboring solution. A neighboring solution is found by applying a slight perturbation to the current solution. This randomness is useful to escape the common pitfall of optimization heuristics — getting trapped in local minima. By potentially accepting a less optimal solution than we currently have, and accepting it with probability inverse to the increase in cost, the algorithm is more likely to converge near the global optimum. Designing a neighbor function is quite tricky and must be done on a case by case basis, but below are some ideas for finding neighbors in locational optimization problems. "
},
{
"code": null,
"e": 29818,
"s": 29767,
"text": "Move all points 0 or 1 units in a random direction"
},
{
"code": null,
"e": 29848,
"s": 29818,
"text": "Shift input elements randomly"
},
{
"code": null,
"e": 29887,
"s": 29848,
"text": "Swap random elements in input sequence"
},
{
"code": null,
"e": 29910,
"s": 29887,
"text": "Permute input sequence"
},
{
"code": null,
"e": 29989,
"s": 29910,
"text": "Partition input sequence into a random number of segments and permute segments"
},
{
"code": null,
"e": 30414,
"s": 29989,
"text": "One caveat is that we need to provide an initial solution so the algorithm knows where to start. This can be done in two ways: (1) using prior knowledge about the problem to input a good starting point and (2) generating a random solution. Although generating a random solution is worse and can occasionally inhibit the success of the algorithm, it is the only option for problems where we know nothing about the landscape. "
},
{
"code": null,
"e": 30981,
"s": 30414,
"text": "There are many other optimization techniques, although simulated annealing is a useful, stochastic optimization heuristic for large, discrete search spaces in which optimality is prioritized over time. Below, I’ve included a basic framework for locational-based simulated annealing (perhaps the most applicable flavor of optimization for simulated annealing). Of course, the cost function, candidate generation function, and neighbor function must be defined based on the specific problem at hand, although the core optimization routine has already been implemented."
},
{
"code": null,
"e": 30986,
"s": 30981,
"text": "Java"
},
{
"code": "// Java program to implement Simulated Annealingimport java.util.*; public class SimulatedAnnealing { // Initial and final temperature public static double T = 1; // Simulated Annealing parameters // Temperature at which iteration terminates static final double Tmin = .0001; // Decrease in temperature static final double alpha = 0.9; // Number of iterations of annealing // before decreasing temperature static final int numIterations = 100; // Locational parameters // Target array is discretized as M*N grid static final int M = 5, N = 5; // Number of objects desired static final int k = 5; public static void main(String[] args) { // Problem: place k objects in an MxN target // plane yielding minimal cost according to // defined objective function // Set of all possible candidate locations String[][] sourceArray = new String[M][N]; // Global minimum Solution min = new Solution(Double.MAX_VALUE, null); // Generates random initial candidate solution // before annealing process Solution currentSol = genRandSol(); // Continues annealing until reaching minimum // temperature while (T > Tmin) { for (int i=0;i<numIterations;i++){ // Reassigns global minimum accordingly if (currentSol.CVRMSE < min.CVRMSE){ min = currentSol; } Solution newSol = neighbor(currentSol); double ap = Math.pow(Math.E, (currentSol.CVRMSE - newSol.CVRMSE)/T); if (ap > Math.random()) currentSol = newSol; } T *= alpha; // Decreases T, cooling phase } //Returns minimum value based on optimization System.out.println(min.CVRMSE+\"\\n\\n\"); for(String[] row:sourceArray) Arrays.fill(row, \"X\"); // Displays for (int object:min.config) { int[] coord = indexToPoints(object); sourceArray[coord[0]][coord[1]] = \"-\"; } // Displays optimal location for (String[] row:sourceArray) System.out.println(Arrays.toString(row)); } // Given current configuration, returns \"neighboring\" // configuration (i.e. very similar) // integer of k points each in range [0, n) /* Different neighbor selection strategies: * Move all points 0 or 1 units in a random direction * Shift input elements randomly * Swap random elements in input sequence * Permute input sequence * Partition input sequence into a random number of segments and permute segments */ public static Solution neighbor(Solution currentSol){ // Slight perturbation to the current solution // to avoid getting stuck in local minimas // Returning for the sake of compilation return currentSol; } // Generates random solution via modified Fisher-Yates // shuffle for first k elements // Pseudorandomly selects k integers from the interval // [0, n-1] public static Solution genRandSol(){ // Instantiating for the sake of compilation int[] a = {1, 2, 3, 4, 5}; // Returning for the sake of compilation return new Solution(-1, a); } // Complexity is O(M*N*k), asymptotically tight public static double cost(int[] inputConfiguration){ // Given specific configuration, return object // solution with assigned cost return -1; //Returning for the sake of compilation } // Mapping from [0, M*N] --> [0,M]x[0,N] public static int[] indexToPoints(int index){ int[] points = {index%M, index/M}; return points; } // Class solution, bundling configuration with error static class Solution { // function value of instance of solution; // using coefficient of variance root mean // squared error public double CVRMSE; public int[] config; // Configuration array public Solution(double CVRMSE, int[] configuration) { this.CVRMSE = CVRMSE; config = configuration; } }}",
"e": 35187,
"s": 30986,
"text": null
},
{
"code": null,
"e": 35197,
"s": 35187,
"text": "Output : "
},
{
"code": null,
"e": 35284,
"s": 35197,
"text": "-1.0\n\n\n[X, -, X, X, X]\n[-, X, X, X, X]\n[-, X, X, X, X]\n[-, X, X, X, X]\n[-, X, X, X, X]"
},
{
"code": null,
"e": 35706,
"s": 35284,
"text": "This article is contributed by Joel Abraham . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 35720,
"s": 35706,
"text": "Piyushgupta12"
},
{
"code": null,
"e": 35737,
"s": 35720,
"text": "surinderdawra388"
},
{
"code": null,
"e": 35749,
"s": 35737,
"text": "kashishsoda"
},
{
"code": null,
"e": 35762,
"s": 35749,
"text": "Mathematical"
},
{
"code": null,
"e": 35775,
"s": 35762,
"text": "Mathematical"
},
{
"code": null,
"e": 35873,
"s": 35775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35917,
"s": 35873,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 35959,
"s": 35917,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 35990,
"s": 35959,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 36015,
"s": 35990,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 36086,
"s": 36015,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 36118,
"s": 36086,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 36151,
"s": 36118,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 36195,
"s": 36151,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 36241,
"s": 36195,
"text": "Merge two sorted arrays with O(1) extra space"
}
]
|
SQL Query to Get Only Numbers From a String - GeeksforGeeks | 25 Oct, 2021
As we know in an SQL database we can insert any type of data. Sometimes in the productions server, the data gets corrupted by two or more rows being merged and being saved in a column. In that case, we can extract the numeric part from that string and save it again. So in this article, we will learn how to extract numeric parts of a string in SQL. We will make use of Microsoft SQL as our server.
So let’s start by creating a database First.
Step 1: Create DB
Query:
CREATE DATABASE GFG
Step 2: Use this DB
Query:
USE GFG
Step 3: Create a table
Create a table (GetNum) to store the data
Query:
CREATE TABLE GetNum(
StudentName varchar (255)
)
Step 4: Insert some data into the database
Query:
INSERT INTO GetNum (StudentName) VALUES ('Devesh123')
INSERT INTO GetNum (StudentName) VALUES ('Geeks2')
INSERT INTO GetNum (StudentName) VALUES ('For5')
INSERT INTO GetNum (StudentName) VALUES ('Aman98')
Output:
Step 4: SQL query to extract the numbers
We will write a SQL function in order to not run the same query again and again for extracting the numbers, we can use that function multiple times also it will be stored in the database.
Query:
CREATE FUNCTION dbo.getNumericValue
(
@inputString VARCHAR(256)
)
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @integerPart INT
SET @integerPart = PATINDEX('%[^0-9]%', @inputString)
BEGIN
WHILE @integerPart > 0
BEGIN
SET @inputString = STUFF(@inputString, @integerPart, 1, '' )
SET @integerPart = PATINDEX('%[^0-9]%', @inputString )
END
END
RETURN ISNULL(@inputString,0)
END
GO
You can refer for more details for PATINDEX().
Step 5: Now run the created function to get the desired output.
Query:
SELECT dbo.getNumericValue(StudentName) from GetNum
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 25912,
"s": 25513,
"text": "As we know in an SQL database we can insert any type of data. Sometimes in the productions server, the data gets corrupted by two or more rows being merged and being saved in a column. In that case, we can extract the numeric part from that string and save it again. So in this article, we will learn how to extract numeric parts of a string in SQL. We will make use of Microsoft SQL as our server."
},
{
"code": null,
"e": 25957,
"s": 25912,
"text": "So let’s start by creating a database First."
},
{
"code": null,
"e": 25975,
"s": 25957,
"text": "Step 1: Create DB"
},
{
"code": null,
"e": 25982,
"s": 25975,
"text": "Query:"
},
{
"code": null,
"e": 26002,
"s": 25982,
"text": "CREATE DATABASE GFG"
},
{
"code": null,
"e": 26022,
"s": 26002,
"text": "Step 2: Use this DB"
},
{
"code": null,
"e": 26029,
"s": 26022,
"text": "Query:"
},
{
"code": null,
"e": 26037,
"s": 26029,
"text": "USE GFG"
},
{
"code": null,
"e": 26061,
"s": 26037,
"text": "Step 3: Create a table "
},
{
"code": null,
"e": 26103,
"s": 26061,
"text": "Create a table (GetNum) to store the data"
},
{
"code": null,
"e": 26110,
"s": 26103,
"text": "Query:"
},
{
"code": null,
"e": 26162,
"s": 26110,
"text": "CREATE TABLE GetNum(\n StudentName varchar (255)\n)\n "
},
{
"code": null,
"e": 26205,
"s": 26162,
"text": "Step 4: Insert some data into the database"
},
{
"code": null,
"e": 26212,
"s": 26205,
"text": "Query:"
},
{
"code": null,
"e": 26427,
"s": 26212,
"text": " INSERT INTO GetNum (StudentName) VALUES ('Devesh123')\n \n INSERT INTO GetNum (StudentName) VALUES ('Geeks2')\n \n INSERT INTO GetNum (StudentName) VALUES ('For5')\n \n INSERT INTO GetNum (StudentName) VALUES ('Aman98')"
},
{
"code": null,
"e": 26435,
"s": 26427,
"text": "Output:"
},
{
"code": null,
"e": 26476,
"s": 26435,
"text": "Step 4: SQL query to extract the numbers"
},
{
"code": null,
"e": 26664,
"s": 26476,
"text": "We will write a SQL function in order to not run the same query again and again for extracting the numbers, we can use that function multiple times also it will be stored in the database."
},
{
"code": null,
"e": 26671,
"s": 26664,
"text": "Query:"
},
{
"code": null,
"e": 27077,
"s": 26671,
"text": "CREATE FUNCTION dbo.getNumericValue\n (\n@inputString VARCHAR(256)\n)\nRETURNS VARCHAR(256)\nAS\nBEGIN\n DECLARE @integerPart INT\n SET @integerPart = PATINDEX('%[^0-9]%', @inputString)\n BEGIN\n WHILE @integerPart > 0\n BEGIN\n SET @inputString = STUFF(@inputString, @integerPart, 1, '' )\n SET @integerPart = PATINDEX('%[^0-9]%', @inputString )\n END\n END\n RETURN ISNULL(@inputString,0)\nEND\nGO"
},
{
"code": null,
"e": 27124,
"s": 27077,
"text": "You can refer for more details for PATINDEX()."
},
{
"code": null,
"e": 27188,
"s": 27124,
"text": "Step 5: Now run the created function to get the desired output."
},
{
"code": null,
"e": 27195,
"s": 27188,
"text": "Query:"
},
{
"code": null,
"e": 27247,
"s": 27195,
"text": "SELECT dbo.getNumericValue(StudentName) from GetNum"
},
{
"code": null,
"e": 27255,
"s": 27247,
"text": "Output:"
},
{
"code": null,
"e": 27262,
"s": 27255,
"text": "Picked"
},
{
"code": null,
"e": 27273,
"s": 27262,
"text": "SQL-Server"
},
{
"code": null,
"e": 27277,
"s": 27273,
"text": "SQL"
},
{
"code": null,
"e": 27281,
"s": 27277,
"text": "SQL"
},
{
"code": null,
"e": 27379,
"s": 27281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27445,
"s": 27379,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27460,
"s": 27445,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27517,
"s": 27460,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27549,
"s": 27517,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27627,
"s": 27549,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27663,
"s": 27627,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27680,
"s": 27663,
"text": "SQL using Python"
},
{
"code": null,
"e": 27746,
"s": 27680,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 27808,
"s": 27746,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
]
|
Number Guessing Game using JavaScript - GeeksforGeeks | 15 Feb, 2019
Prerequisites:
Basic Knowledge of HTML
Basic Knowledge of Javascript
The game is to guess a random number generated by computer in range 1 – 10 in minimum number of Guesses.
Functions to be used:
1. document.getElementById(“id given”): document.getElementById() is used to fetch an element from the HTML page having the id as provided (specified) by the user.“.value” is used to access the value of the HTML element accessed.
2. Math.random() : The random() function is used to generate a random number between 0 (inclusive) and 1 (exclusive). This generated number is then multiplied with 10 and added 1 to generate numbers from 1 – 10.
3. Math.floor() : The floor() function is used to return the number to the nearest integer (downwards). The value will not be rounded, if the passed argument is an integer.
Implementation of the Game.
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>Number Guessing Game</title> <style> html { font-family: sans-serif; } body { width: 50%; max-width: 800px; min-width: 480px; margin: 0 auto; } </style></head> <body><h1>Guess The Number</h1> <p>We have selected a random number between 1 - 10. See if you can guess it.</p> <div class="form"> <label for="guessField">Enter a guess: </label> <input type = "text" id = "guessField" class = "guessField"> <input type = "submit" value = "Submit guess" class = "guessSubmit" id = "submitguess"></div> <script type = "text/javascript"> // random value generated var y = Math.floor(Math.random() * 10 + 1); // counting the number of guesses // made for correct Guess var guess = 1; document.getElementById("submitguess").onclick = function(){ // number guessed by user var x = document.getElementById("guessField").value; if(x == y) { alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT IN " + guess + " GUESS "); } else if(x > y) /* if guessed number is greater than actual number*/ { guess++; alert("OOPS SORRY!! TRY A SMALLER NUMBER"); } else { guess++; alert("OOPS SORRY!! TRY A GREATER NUMBER") }}</script></body></html>
Output:
JavaScript-Numbers
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
HTML | <img> align Attribute
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 26325,
"s": 26297,
"text": "\n15 Feb, 2019"
},
{
"code": null,
"e": 26340,
"s": 26325,
"text": "Prerequisites:"
},
{
"code": null,
"e": 26364,
"s": 26340,
"text": "Basic Knowledge of HTML"
},
{
"code": null,
"e": 26394,
"s": 26364,
"text": "Basic Knowledge of Javascript"
},
{
"code": null,
"e": 26499,
"s": 26394,
"text": "The game is to guess a random number generated by computer in range 1 – 10 in minimum number of Guesses."
},
{
"code": null,
"e": 26521,
"s": 26499,
"text": "Functions to be used:"
},
{
"code": null,
"e": 26751,
"s": 26521,
"text": "1. document.getElementById(“id given”): document.getElementById() is used to fetch an element from the HTML page having the id as provided (specified) by the user.“.value” is used to access the value of the HTML element accessed."
},
{
"code": null,
"e": 26963,
"s": 26751,
"text": "2. Math.random() : The random() function is used to generate a random number between 0 (inclusive) and 1 (exclusive). This generated number is then multiplied with 10 and added 1 to generate numbers from 1 – 10."
},
{
"code": null,
"e": 27136,
"s": 26963,
"text": "3. Math.floor() : The floor() function is used to return the number to the nearest integer (downwards). The value will not be rounded, if the passed argument is an integer."
},
{
"code": null,
"e": 27164,
"s": 27136,
"text": "Implementation of the Game."
},
{
"code": " <!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <title>Number Guessing Game</title> <style> html { font-family: sans-serif; } body { width: 50%; max-width: 800px; min-width: 480px; margin: 0 auto; } </style></head> <body><h1>Guess The Number</h1> <p>We have selected a random number between 1 - 10. See if you can guess it.</p> <div class=\"form\"> <label for=\"guessField\">Enter a guess: </label> <input type = \"text\" id = \"guessField\" class = \"guessField\"> <input type = \"submit\" value = \"Submit guess\" class = \"guessSubmit\" id = \"submitguess\"></div> <script type = \"text/javascript\"> // random value generated var y = Math.floor(Math.random() * 10 + 1); // counting the number of guesses // made for correct Guess var guess = 1; document.getElementById(\"submitguess\").onclick = function(){ // number guessed by user var x = document.getElementById(\"guessField\").value; if(x == y) { alert(\"CONGRATULATIONS!!! YOU GUESSED IT RIGHT IN \" + guess + \" GUESS \"); } else if(x > y) /* if guessed number is greater than actual number*/ { guess++; alert(\"OOPS SORRY!! TRY A SMALLER NUMBER\"); } else { guess++; alert(\"OOPS SORRY!! TRY A GREATER NUMBER\") }}</script></body></html> ",
"e": 28596,
"s": 27164,
"text": null
},
{
"code": null,
"e": 28604,
"s": 28596,
"text": "Output:"
},
{
"code": null,
"e": 28623,
"s": 28604,
"text": "JavaScript-Numbers"
},
{
"code": null,
"e": 28628,
"s": 28623,
"text": "HTML"
},
{
"code": null,
"e": 28639,
"s": 28628,
"text": "JavaScript"
},
{
"code": null,
"e": 28656,
"s": 28639,
"text": "Web Technologies"
},
{
"code": null,
"e": 28661,
"s": 28656,
"text": "HTML"
},
{
"code": null,
"e": 28759,
"s": 28661,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28783,
"s": 28759,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 28833,
"s": 28783,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28870,
"s": 28833,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28934,
"s": 28870,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 28963,
"s": 28934,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 29003,
"s": 28963,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29048,
"s": 29003,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29109,
"s": 29048,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29181,
"s": 29109,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
Python: Map VS For Loop - GeeksforGeeks | 05 Aug, 2021
Map in Python :
Map is used to compute a function for different values ‘in a single line of code ‘ .
It takes two arguments, first is function name, that is defined already and the other is list, tuple or any other iterables .
It is a way of applying same function for multiple numbers .
It generates a map object at a particular location .
It works fast when we call an already defined function on the elements
map(functionname, iterable)
map(functionname, iterable)
Note: For more information refer to Python map() function.
for loop in Python :
We use for loop to repeat a block of code for fixed number of times .
Used when no results are required .
To perform sequential traversal .
Loop from 0 to n runs n+1 times .
for var in iterable :
statements Note: Here, var is the name given to iterating variable, iterable can be replaced by range() function and they can be of any data type . Statements are the step of actions to be performed .
for var in iterable :
statements
Note: Here, var is the name given to iterating variable, iterable can be replaced by range() function and they can be of any data type . Statements are the step of actions to be performed .
Note: For more information, refer to Python For Loops.
Example:
Python
# function to square a given numberdef squareNum (a) : return a * a listt = [0, -1, 3, 4.5, 99, .08] # using 'map' to call the function# 'squareNum' for all the elements# of 'listt'x = map(squareNum, listt) # map function returns a map# object at this particular # locationprint(x) # convert map to listprint(list(x)) # alternate way to square all# elements of 'listt' using# 'for loop' for i in listt : square = i * i print(square)
Output:
<map object at 0x7fe413cf9b00>
[0, 1, 9, 20.25, 9801, 0.0064]
0
1
9
20.25
9801
0.0064
Comparing performance , map() wins! map() works way faster than for loop. Considering the same code above when run in this ide.Using map():using for loop:for loop can be with no content, no such concept exist in map() function.Example:PythonPython# we use the keyword 'pass'# to simply get a for loop # with no contentfor i in range (10) : passThere can be an else condition in for loop which only runs when no break statement is used. There is nothing like this in map.Example :PythonPython# for loop with else condition for i in range(10) : print(i)else : print("Finished !")Output :0
1
2
3
4
5
6
7
8
9
Finished !
for loop can exit before too. We can do that using break statement. Exiting before expected is not possible in map.map generates a map object, for loop does not return anything.syntax of map and for loop are completely different.for loop is for executing the same block of code for a fixed number of times, the map also does that but in a single line of code.
Comparing performance , map() wins! map() works way faster than for loop. Considering the same code above when run in this ide.Using map():using for loop:
Using map():
using for loop:
for loop can be with no content, no such concept exist in map() function.Example:PythonPython# we use the keyword 'pass'# to simply get a for loop # with no contentfor i in range (10) : pass
Example:
Python
# we use the keyword 'pass'# to simply get a for loop # with no contentfor i in range (10) : pass
There can be an else condition in for loop which only runs when no break statement is used. There is nothing like this in map.Example :PythonPython# for loop with else condition for i in range(10) : print(i)else : print("Finished !")Output :0
1
2
3
4
5
6
7
8
9
Finished !
Example :
Python
# for loop with else condition for i in range(10) : print(i)else : print("Finished !")
Output :
0
1
2
3
4
5
6
7
8
9
Finished !
for loop can exit before too. We can do that using break statement. Exiting before expected is not possible in map.
map generates a map object, for loop does not return anything.
syntax of map and for loop are completely different.
for loop is for executing the same block of code for a fixed number of times, the map also does that but in a single line of code.
akshaysingh98088
python-utility
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 25579,
"s": 25563,
"text": "Map in Python :"
},
{
"code": null,
"e": 25664,
"s": 25579,
"text": "Map is used to compute a function for different values ‘in a single line of code ‘ ."
},
{
"code": null,
"e": 25790,
"s": 25664,
"text": "It takes two arguments, first is function name, that is defined already and the other is list, tuple or any other iterables ."
},
{
"code": null,
"e": 25851,
"s": 25790,
"text": "It is a way of applying same function for multiple numbers ."
},
{
"code": null,
"e": 25904,
"s": 25851,
"text": "It generates a map object at a particular location ."
},
{
"code": null,
"e": 25975,
"s": 25904,
"text": "It works fast when we call an already defined function on the elements"
},
{
"code": null,
"e": 26004,
"s": 25975,
"text": " map(functionname, iterable)"
},
{
"code": null,
"e": 26033,
"s": 26004,
"text": " map(functionname, iterable)"
},
{
"code": null,
"e": 26092,
"s": 26033,
"text": "Note: For more information refer to Python map() function."
},
{
"code": null,
"e": 26113,
"s": 26092,
"text": "for loop in Python :"
},
{
"code": null,
"e": 26183,
"s": 26113,
"text": "We use for loop to repeat a block of code for fixed number of times ."
},
{
"code": null,
"e": 26219,
"s": 26183,
"text": "Used when no results are required ."
},
{
"code": null,
"e": 26253,
"s": 26219,
"text": "To perform sequential traversal ."
},
{
"code": null,
"e": 26287,
"s": 26253,
"text": "Loop from 0 to n runs n+1 times ."
},
{
"code": null,
"e": 26526,
"s": 26287,
"text": " for var in iterable :\n statements Note: Here, var is the name given to iterating variable, iterable can be replaced by range() function and they can be of any data type . Statements are the step of actions to be performed ."
},
{
"code": null,
"e": 26576,
"s": 26526,
"text": " for var in iterable :\n statements "
},
{
"code": null,
"e": 26766,
"s": 26576,
"text": "Note: Here, var is the name given to iterating variable, iterable can be replaced by range() function and they can be of any data type . Statements are the step of actions to be performed ."
},
{
"code": null,
"e": 26821,
"s": 26766,
"text": "Note: For more information, refer to Python For Loops."
},
{
"code": null,
"e": 26830,
"s": 26821,
"text": "Example:"
},
{
"code": null,
"e": 26837,
"s": 26830,
"text": "Python"
},
{
"code": "# function to square a given numberdef squareNum (a) : return a * a listt = [0, -1, 3, 4.5, 99, .08] # using 'map' to call the function# 'squareNum' for all the elements# of 'listt'x = map(squareNum, listt) # map function returns a map# object at this particular # locationprint(x) # convert map to listprint(list(x)) # alternate way to square all# elements of 'listt' using# 'for loop' for i in listt : square = i * i print(square)",
"e": 27291,
"s": 26837,
"text": null
},
{
"code": null,
"e": 27299,
"s": 27291,
"text": "Output:"
},
{
"code": null,
"e": 27386,
"s": 27299,
"text": "<map object at 0x7fe413cf9b00>\n[0, 1, 9, 20.25, 9801, 0.0064]\n0\n1\n9\n20.25\n9801\n0.0064\n"
},
{
"code": null,
"e": 28373,
"s": 27386,
"text": "Comparing performance , map() wins! map() works way faster than for loop. Considering the same code above when run in this ide.Using map():using for loop:for loop can be with no content, no such concept exist in map() function.Example:PythonPython# we use the keyword 'pass'# to simply get a for loop # with no contentfor i in range (10) : passThere can be an else condition in for loop which only runs when no break statement is used. There is nothing like this in map.Example :PythonPython# for loop with else condition for i in range(10) : print(i)else : print(\"Finished !\")Output :0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nFinished !\nfor loop can exit before too. We can do that using break statement. Exiting before expected is not possible in map.map generates a map object, for loop does not return anything.syntax of map and for loop are completely different.for loop is for executing the same block of code for a fixed number of times, the map also does that but in a single line of code."
},
{
"code": null,
"e": 28528,
"s": 28373,
"text": "Comparing performance , map() wins! map() works way faster than for loop. Considering the same code above when run in this ide.Using map():using for loop:"
},
{
"code": null,
"e": 28541,
"s": 28528,
"text": "Using map():"
},
{
"code": null,
"e": 28557,
"s": 28541,
"text": "using for loop:"
},
{
"code": null,
"e": 28751,
"s": 28557,
"text": "for loop can be with no content, no such concept exist in map() function.Example:PythonPython# we use the keyword 'pass'# to simply get a for loop # with no contentfor i in range (10) : pass"
},
{
"code": null,
"e": 28760,
"s": 28751,
"text": "Example:"
},
{
"code": null,
"e": 28767,
"s": 28760,
"text": "Python"
},
{
"code": "# we use the keyword 'pass'# to simply get a for loop # with no contentfor i in range (10) : pass",
"e": 28868,
"s": 28767,
"text": null
},
{
"code": null,
"e": 29149,
"s": 28868,
"text": "There can be an else condition in for loop which only runs when no break statement is used. There is nothing like this in map.Example :PythonPython# for loop with else condition for i in range(10) : print(i)else : print(\"Finished !\")Output :0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nFinished !\n"
},
{
"code": null,
"e": 29159,
"s": 29149,
"text": "Example :"
},
{
"code": null,
"e": 29166,
"s": 29159,
"text": "Python"
},
{
"code": "# for loop with else condition for i in range(10) : print(i)else : print(\"Finished !\")",
"e": 29261,
"s": 29166,
"text": null
},
{
"code": null,
"e": 29270,
"s": 29261,
"text": "Output :"
},
{
"code": null,
"e": 29302,
"s": 29270,
"text": "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\nFinished !\n"
},
{
"code": null,
"e": 29418,
"s": 29302,
"text": "for loop can exit before too. We can do that using break statement. Exiting before expected is not possible in map."
},
{
"code": null,
"e": 29481,
"s": 29418,
"text": "map generates a map object, for loop does not return anything."
},
{
"code": null,
"e": 29534,
"s": 29481,
"text": "syntax of map and for loop are completely different."
},
{
"code": null,
"e": 29665,
"s": 29534,
"text": "for loop is for executing the same block of code for a fixed number of times, the map also does that but in a single line of code."
},
{
"code": null,
"e": 29682,
"s": 29665,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 29697,
"s": 29682,
"text": "python-utility"
},
{
"code": null,
"e": 29721,
"s": 29697,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 29728,
"s": 29721,
"text": "Python"
},
{
"code": null,
"e": 29747,
"s": 29728,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29845,
"s": 29747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29877,
"s": 29845,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29919,
"s": 29877,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29961,
"s": 29919,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30017,
"s": 29961,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30044,
"s": 30017,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30083,
"s": 30044,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30114,
"s": 30083,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30136,
"s": 30114,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30165,
"s": 30136,
"text": "Create a directory in Python"
}
]
|
reflect.Swapper() Function in Golang with Examples - GeeksforGeeks | 28 Apr, 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.Swapper() Function in Golang is used to swaps the elements in the provided slice. To access this function, one needs to imports the reflect package in the program.
Syntax:
func Swapper(slice interface{}) func(i, j int)
Parameters: This function takes one parameters of Slice type.
Return Value: This function returns the swapped slice.
Below examples illustrate the use of above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Swapper() Function package main import ( "fmt" "reflect") // Main function func main() { // Slice src := []int{1, 2, 3, 4, 5} fmt.Printf("Before swap: %v\n", src) // Swapper() function is used // to swaps the elements in // the provided slice swapF := reflect.Swapper(src) swapF(2, 4) // printing the values fmt.Printf("After swap: %v\n", src)}
Output:
Before swap: [1 2 3 4 5]
After swap: [1 2 5 4 3]
Example 2: Reversing a slice using Swapper() function
// Golang program to illustrate// reflect.Swapper() Function package main import ( "fmt" "reflect") // Main function func main() { // Slice src := []int{1, 2, 3, 4, 5, 6, 7} fmt.Printf("Original Slice: %v\n", src) // Swapper() function is used // to swaps the elements in // the provided slice swapF := reflect.Swapper(src) for i := 0; i < len(src)/2; i++ { swapF(i, len(src)-1-i) } // printing the values fmt.Printf("Reversed Slice: %v\n", src)}
Output:
Original Slice: [1 2 3 4 5 6 7]
Reversed Slice: [7 6 5 4 3 2 1]
Example 3: Sorting of a slice using Swapper() function
// Golang program to illustrate// reflect.Swapper() Function package main import ( "fmt" "reflect") // Main function func main() { // Slice src := []int{1, 2, 6, 3, 8, 0, 7, 9, 5, 4, 42, 1, 3, 4, 3} fmt.Printf("Original Slice: %v\n", src) // Swapper() function is used // to swaps the elements in //the provided slice swapF := reflect.Swapper(src) for i := 0; i < len(src)-1; i++ { for j := i + 1; j < len(src); j++ { if src[i] > src[j] { swapF(i, j) } } } //printing the values fmt.Printf("Sorted Slice: %v\n", src)}
Output:
Original Slice: [1 2 6 3 8 0 7 9 5 4 42 1 3 4 3]
Sorted Slice: [0 1 1 2 3 3 3 4 4 5 6 7 8 9 42]
Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Strings in Golang
Time Durations in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Defer Keyword in Golang
Loops in Go Language
Class and Object in Golang | [
{
"code": null,
"e": 25703,
"s": 25675,
"text": "\n28 Apr, 2020"
},
{
"code": null,
"e": 26054,
"s": 25703,
"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.Swapper() Function in Golang is used to swaps the elements in the provided slice. To access this function, one needs to imports the reflect package in the program."
},
{
"code": null,
"e": 26062,
"s": 26054,
"text": "Syntax:"
},
{
"code": null,
"e": 26110,
"s": 26062,
"text": "func Swapper(slice interface{}) func(i, j int)\n"
},
{
"code": null,
"e": 26172,
"s": 26110,
"text": "Parameters: This function takes one parameters of Slice type."
},
{
"code": null,
"e": 26227,
"s": 26172,
"text": "Return Value: This function returns the swapped slice."
},
{
"code": null,
"e": 26288,
"s": 26227,
"text": "Below examples illustrate the use of above method in Golang:"
},
{
"code": null,
"e": 26299,
"s": 26288,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate// reflect.Swapper() Function package main import ( \"fmt\" \"reflect\") // Main function func main() { // Slice src := []int{1, 2, 3, 4, 5} fmt.Printf(\"Before swap: %v\\n\", src) // Swapper() function is used // to swaps the elements in // the provided slice swapF := reflect.Swapper(src) swapF(2, 4) // printing the values fmt.Printf(\"After swap: %v\\n\", src)}",
"e": 26753,
"s": 26299,
"text": null
},
{
"code": null,
"e": 26761,
"s": 26753,
"text": "Output:"
},
{
"code": null,
"e": 26811,
"s": 26761,
"text": "Before swap: [1 2 3 4 5]\nAfter swap: [1 2 5 4 3]\n"
},
{
"code": null,
"e": 26865,
"s": 26811,
"text": "Example 2: Reversing a slice using Swapper() function"
},
{
"code": "// Golang program to illustrate// reflect.Swapper() Function package main import ( \"fmt\" \"reflect\") // Main function func main() { // Slice src := []int{1, 2, 3, 4, 5, 6, 7} fmt.Printf(\"Original Slice: %v\\n\", src) // Swapper() function is used // to swaps the elements in // the provided slice swapF := reflect.Swapper(src) for i := 0; i < len(src)/2; i++ { swapF(i, len(src)-1-i) } // printing the values fmt.Printf(\"Reversed Slice: %v\\n\", src)}",
"e": 27388,
"s": 26865,
"text": null
},
{
"code": null,
"e": 27396,
"s": 27388,
"text": "Output:"
},
{
"code": null,
"e": 27461,
"s": 27396,
"text": "Original Slice: [1 2 3 4 5 6 7]\nReversed Slice: [7 6 5 4 3 2 1]\n"
},
{
"code": null,
"e": 27516,
"s": 27461,
"text": "Example 3: Sorting of a slice using Swapper() function"
},
{
"code": "// Golang program to illustrate// reflect.Swapper() Function package main import ( \"fmt\" \"reflect\") // Main function func main() { // Slice src := []int{1, 2, 6, 3, 8, 0, 7, 9, 5, 4, 42, 1, 3, 4, 3} fmt.Printf(\"Original Slice: %v\\n\", src) // Swapper() function is used // to swaps the elements in //the provided slice swapF := reflect.Swapper(src) for i := 0; i < len(src)-1; i++ { for j := i + 1; j < len(src); j++ { if src[i] > src[j] { swapF(i, j) } } } //printing the values fmt.Printf(\"Sorted Slice: %v\\n\", src)}",
"e": 28154,
"s": 27516,
"text": null
},
{
"code": null,
"e": 28162,
"s": 28154,
"text": "Output:"
},
{
"code": null,
"e": 28259,
"s": 28162,
"text": "Original Slice: [1 2 6 3 8 0 7 9 5 4 42 1 3 4 3]\nSorted Slice: [0 1 1 2 3 3 3 4 4 5 6 7 8 9 42]\n"
},
{
"code": null,
"e": 28274,
"s": 28259,
"text": "Golang-reflect"
},
{
"code": null,
"e": 28286,
"s": 28274,
"text": "Go Language"
},
{
"code": null,
"e": 28384,
"s": 28286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28430,
"s": 28384,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 28459,
"s": 28430,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 28477,
"s": 28459,
"text": "Strings in Golang"
},
{
"code": null,
"e": 28502,
"s": 28477,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 28523,
"s": 28502,
"text": "Structures in Golang"
},
{
"code": null,
"e": 28578,
"s": 28523,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 28593,
"s": 28578,
"text": "Rune in Golang"
},
{
"code": null,
"e": 28617,
"s": 28593,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 28638,
"s": 28617,
"text": "Loops in Go Language"
}
]
|
C Program to Count Inversions in an array | Set 1 (Using Merge Sort) - GeeksforGeeks | 20 Apr, 2022
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j Example:
Input: arr[] = {8, 4, 2, 1}
Output: 6
Explanation: Given array has six inversions:
(8, 4), (4, 2), (8, 2), (8, 1), (4, 1), (2, 1).
Input: arr[] = {3, 1, 2}
Output: 2
Explanation: Given array has two inversions:
(3, 1), (3, 2)
METHOD 1 (Simple):
Approach: Traverse through the array, and for every index, find the number of smaller elements on its right side of the array. This can be done using a nested loop. Sum up the counts for all index in the array and print the sum.
Algorithm:
Traverse through the array from start to endFor every element, find the count of elements smaller than the current number up to that index using another loop.Sum up the count of inversion for every index.Print the count of inversions.
Traverse through the array from start to end
For every element, find the count of elements smaller than the current number up to that index using another loop.
Sum up the count of inversion for every index.
Print the count of inversions.
Implementation:
C
// C program to Count Inversions// in an array#include <stdio.h>#include <stdlib.h>int getInvCount(int arr[], int n){ int inv_count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] > arr[j]) inv_count++; return inv_count;} // Driver codeint main(){ int arr[] = {1, 20, 6, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf(" Number of inversions are %d \n", getInvCount(arr, n)); return 0;}
Output:
Number of inversions are 5
Complexity Analysis:
Time Complexity: O(n^2), Two nested loops are needed to traverse the array from start to end, so the Time complexity is O(n^2)
Space Complexity:O(1), No extra space is required.
METHOD 2(Enhance Merge Sort):
Approach: Suppose the number of inversions in the left half and right half of the array (let be inv1 and inv2); what kinds of inversions are not accounted for in Inv1 + Inv2? The answer is – the inversions that need to be counted during the merge step. Therefore, to get the total number of inversions that needs to be added are the number of inversions in the left subarray, right subarray, and merge().
How to get the number of inversions in merge()? In merge process, let i is used for indexing left sub-array and j for right sub-array. At any step in merge(), if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j]
The complete picture:
Algorithm:
The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached.Create a function merge that counts the number of inversions when two halves of the array are merged, create two indices i and j, i is the index for the first half, and j is an index of the second half. if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j].Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, the number of inversion in the second half and the number of inversions by merging the two.The base case of recursion is when there is only one element in the given half.Print the answer
The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached.
Create a function merge that counts the number of inversions when two halves of the array are merged, create two indices i and j, i is the index for the first half, and j is an index of the second half. if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j].
Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, the number of inversion in the second half and the number of inversions by merging the two.
The base case of recursion is when there is only one element in the given half.
Print the answer
Implementation:
C
// C program to Count Inversions in// an array using Merge Sort#include <stdio.h>#include <stdlib.h> int _mergeSort(int arr[], int temp[], int left, int right);int merge(int arr[], int temp[], int left, int mid, int right); /* This function sorts the input array and returns the number of inversions in the array */int mergeSort(int arr[], int array_size){ int* temp = (int*)malloc(sizeof(int) * array_size); return _mergeSort(arr, temp, 0, array_size - 1);} /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array.*/int _mergeSort(int arr[], int temp[], int left, int right){ int mid, inv_count = 0; if (right > left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left) / 2; /* Inversion count will be the sum of inversions in left-part, right-part and number of inversions in merging */ inv_count += _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); // Merge the two parts inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count;} /* This function merges two sorted arrays and returns inversion count in the arrays.*/int merge(int arr[], int temp[], int left, int mid, int right){ int i, j, k; int inv_count = 0; // i is index for left subarray i = left; // j is index for right subarray j = mid; /* k is index for resultant merged subarray*/ k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; /* This is tricky -- see above explanation/diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /* Copy back the merged elements to original array*/ for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count;} // Driver codeint main(int argv, char** args){ int arr[] = {1, 20, 6, 4, 5}; printf("Number of inversions are %d \n", mergeSort(arr, 5)); getchar(); return 0;}
Output:
Number of inversions are 5
Complexity Analysis:
Time Complexity: O(n log n), The algorithm used is divide and conquer, So in each level, one full array traversal is needed, and there are log n levels, so the time complexity is O(n log n).
Space Complexity: O(n), Temporary array.
Note that the above code modifies (or sorts) the input array. If we want to count only inversions, we need to create a copy of the original array and call mergeSort() on the copy to preserve the original array’s order.
shivamraj74
surinderdawra388
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Exit codes in C/C++ with Examples
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Regular expressions in C
Create n-child process from same parent process using fork() in C
Conditional wait and signal in multi-threading
Difference between break and continue statement in C | [
{
"code": null,
"e": 26199,
"s": 26171,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 26538,
"s": 26199,
"text": "Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j Example: "
},
{
"code": null,
"e": 26766,
"s": 26538,
"text": "Input: arr[] = {8, 4, 2, 1}\nOutput: 6\nExplanation: Given array has six inversions:\n(8, 4), (4, 2), (8, 2), (8, 1), (4, 1), (2, 1).\n\nInput: arr[] = {3, 1, 2}\nOutput: 2\nExplanation: Given array has two inversions:\n(3, 1), (3, 2) "
},
{
"code": null,
"e": 26787,
"s": 26766,
"text": "METHOD 1 (Simple): "
},
{
"code": null,
"e": 27016,
"s": 26787,
"text": "Approach: Traverse through the array, and for every index, find the number of smaller elements on its right side of the array. This can be done using a nested loop. Sum up the counts for all index in the array and print the sum."
},
{
"code": null,
"e": 27027,
"s": 27016,
"text": "Algorithm:"
},
{
"code": null,
"e": 27262,
"s": 27027,
"text": "Traverse through the array from start to endFor every element, find the count of elements smaller than the current number up to that index using another loop.Sum up the count of inversion for every index.Print the count of inversions."
},
{
"code": null,
"e": 27307,
"s": 27262,
"text": "Traverse through the array from start to end"
},
{
"code": null,
"e": 27422,
"s": 27307,
"text": "For every element, find the count of elements smaller than the current number up to that index using another loop."
},
{
"code": null,
"e": 27469,
"s": 27422,
"text": "Sum up the count of inversion for every index."
},
{
"code": null,
"e": 27500,
"s": 27469,
"text": "Print the count of inversions."
},
{
"code": null,
"e": 27516,
"s": 27500,
"text": "Implementation:"
},
{
"code": null,
"e": 27518,
"s": 27516,
"text": "C"
},
{
"code": "// C program to Count Inversions// in an array#include <stdio.h>#include <stdlib.h>int getInvCount(int arr[], int n){ int inv_count = 0; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] > arr[j]) inv_count++; return inv_count;} // Driver codeint main(){ int arr[] = {1, 20, 6, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf(\" Number of inversions are %d \\n\", getInvCount(arr, n)); return 0;}",
"e": 28006,
"s": 27518,
"text": null
},
{
"code": null,
"e": 28014,
"s": 28006,
"text": "Output:"
},
{
"code": null,
"e": 28042,
"s": 28014,
"text": " Number of inversions are 5"
},
{
"code": null,
"e": 28065,
"s": 28042,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 28192,
"s": 28065,
"text": "Time Complexity: O(n^2), Two nested loops are needed to traverse the array from start to end, so the Time complexity is O(n^2)"
},
{
"code": null,
"e": 28243,
"s": 28192,
"text": "Space Complexity:O(1), No extra space is required."
},
{
"code": null,
"e": 28274,
"s": 28243,
"text": "METHOD 2(Enhance Merge Sort): "
},
{
"code": null,
"e": 28679,
"s": 28274,
"text": "Approach: Suppose the number of inversions in the left half and right half of the array (let be inv1 and inv2); what kinds of inversions are not accounted for in Inv1 + Inv2? The answer is – the inversions that need to be counted during the merge step. Therefore, to get the total number of inversions that needs to be added are the number of inversions in the left subarray, right subarray, and merge()."
},
{
"code": null,
"e": 29051,
"s": 28679,
"text": "How to get the number of inversions in merge()? In merge process, let i is used for indexing left sub-array and j for right sub-array. At any step in merge(), if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j]"
},
{
"code": null,
"e": 29073,
"s": 29051,
"text": "The complete picture:"
},
{
"code": null,
"e": 29086,
"s": 29073,
"text": "Algorithm: "
},
{
"code": null,
"e": 29958,
"s": 29086,
"text": "The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached.Create a function merge that counts the number of inversions when two halves of the array are merged, create two indices i and j, i is the index for the first half, and j is an index of the second half. if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j].Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, the number of inversion in the second half and the number of inversions by merging the two.The base case of recursion is when there is only one element in the given half.Print the answer"
},
{
"code": null,
"e": 30093,
"s": 29958,
"text": "The idea is similar to merge sort, divide the array into two equal or almost equal halves in each step until the base case is reached."
},
{
"code": null,
"e": 30510,
"s": 30093,
"text": "Create a function merge that counts the number of inversions when two halves of the array are merged, create two indices i and j, i is the index for the first half, and j is an index of the second half. if a[i] is greater than a[j], then there are (mid – i) inversions. because left and right subarrays are sorted, so all the remaining elements in left-subarray (a[i+1], a[i+2] ... a[mid]) will be greater than a[j]."
},
{
"code": null,
"e": 30737,
"s": 30510,
"text": "Create a recursive function to divide the array into halves and find the answer by summing the number of inversions is the first half, the number of inversion in the second half and the number of inversions by merging the two."
},
{
"code": null,
"e": 30817,
"s": 30737,
"text": "The base case of recursion is when there is only one element in the given half."
},
{
"code": null,
"e": 30834,
"s": 30817,
"text": "Print the answer"
},
{
"code": null,
"e": 30850,
"s": 30834,
"text": "Implementation:"
},
{
"code": null,
"e": 30852,
"s": 30850,
"text": "C"
},
{
"code": "// C program to Count Inversions in// an array using Merge Sort#include <stdio.h>#include <stdlib.h> int _mergeSort(int arr[], int temp[], int left, int right);int merge(int arr[], int temp[], int left, int mid, int right); /* This function sorts the input array and returns the number of inversions in the array */int mergeSort(int arr[], int array_size){ int* temp = (int*)malloc(sizeof(int) * array_size); return _mergeSort(arr, temp, 0, array_size - 1);} /* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array.*/int _mergeSort(int arr[], int temp[], int left, int right){ int mid, inv_count = 0; if (right > left) { /* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */ mid = (right + left) / 2; /* Inversion count will be the sum of inversions in left-part, right-part and number of inversions in merging */ inv_count += _mergeSort(arr, temp, left, mid); inv_count += _mergeSort(arr, temp, mid + 1, right); // Merge the two parts inv_count += merge(arr, temp, left, mid + 1, right); } return inv_count;} /* This function merges two sorted arrays and returns inversion count in the arrays.*/int merge(int arr[], int temp[], int left, int mid, int right){ int i, j, k; int inv_count = 0; // i is index for left subarray i = left; // j is index for right subarray j = mid; /* k is index for resultant merged subarray*/ k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; /* This is tricky -- see above explanation/diagram for merge()*/ inv_count = inv_count + (mid - i); } } /* Copy the remaining elements of left subarray (if there are any) to temp*/ while (i <= mid - 1) temp[k++] = arr[i++]; /* Copy the remaining elements of right subarray (if there are any) to temp*/ while (j <= right) temp[k++] = arr[j++]; /* Copy back the merged elements to original array*/ for (i = left; i <= right; i++) arr[i] = temp[i]; return inv_count;} // Driver codeint main(int argv, char** args){ int arr[] = {1, 20, 6, 4, 5}; printf(\"Number of inversions are %d \\n\", mergeSort(arr, 5)); getchar(); return 0;}",
"e": 33589,
"s": 30852,
"text": null
},
{
"code": null,
"e": 33597,
"s": 33589,
"text": "Output:"
},
{
"code": null,
"e": 33624,
"s": 33597,
"text": "Number of inversions are 5"
},
{
"code": null,
"e": 33645,
"s": 33624,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 33836,
"s": 33645,
"text": "Time Complexity: O(n log n), The algorithm used is divide and conquer, So in each level, one full array traversal is needed, and there are log n levels, so the time complexity is O(n log n)."
},
{
"code": null,
"e": 33877,
"s": 33836,
"text": "Space Complexity: O(n), Temporary array."
},
{
"code": null,
"e": 34097,
"s": 33877,
"text": "Note that the above code modifies (or sorts) the input array. If we want to count only inversions, we need to create a copy of the original array and call mergeSort() on the copy to preserve the original array’s order. "
},
{
"code": null,
"e": 34109,
"s": 34097,
"text": "shivamraj74"
},
{
"code": null,
"e": 34126,
"s": 34109,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34137,
"s": 34126,
"text": "C Programs"
},
{
"code": null,
"e": 34235,
"s": 34137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34276,
"s": 34235,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 34307,
"s": 34276,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 34341,
"s": 34307,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 34382,
"s": 34341,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 34453,
"s": 34382,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 34543,
"s": 34453,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 34568,
"s": 34543,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 34634,
"s": 34568,
"text": "Create n-child process from same parent process using fork() in C"
},
{
"code": null,
"e": 34681,
"s": 34634,
"text": "Conditional wait and signal in multi-threading"
}
]
|
How to write a:hover in inline CSS? - GeeksforGeeks | 30 Jul, 2021
It is called pseudo-selector and used to select all the elements when the user move mouse over the elements. It can be used on all the element. A <!DOCTYPE html> element must be declared in the document to see the working of this selector in all the elements.
Example 1:
<!DOCTYPE html><html> <head> <title>a:hover in inline CSS</title> <style> h1 { color:green; } body { text-align:center; } a { text-decoration:none; color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>a:hover in inline CSS</h2> <a href="#" onMouseOver="this.style.color='red'" onMouseOut="this.style.color='green'" >GeeksforGeeks</a> </body></html>
Output:
Example 2: This example uses JavaScript to display a:hover content in CSS. The onmouseover and onmouseout event attribute is called to display the a:hover content.
<!DOCTYPE html><html> <head> <title>a:hover in inline CSS</title> <style> h1 { color:green; } body { text-align:center; } a { text-decoration:none; color:green; } </style> <script> function mouseover() { document.getElementById("gfg").style.color = "red"; } function mouseout() { document.getElementById("gfg").style.color = "green"; } </script> </head> <body> <h1>GeeksforGeeks</h1> <h2>a:hover in inline CSS</h2> <a href = "#" id="gfg" onmouseover="mouseover()" onmouseout="mouseout()">GeeksforGeeks</a> </body></html>
Output:
Supported Browsers: The browser supported by a:hover selector are listed below:
Apple Safari 3.1
Google Chrome 4.0
Firefox 2.0
Opera 9.6
Internet Explorer 7.0
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 25923,
"s": 25895,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 26183,
"s": 25923,
"text": "It is called pseudo-selector and used to select all the elements when the user move mouse over the elements. It can be used on all the element. A <!DOCTYPE html> element must be declared in the document to see the working of this selector in all the elements."
},
{
"code": null,
"e": 26194,
"s": 26183,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>a:hover in inline CSS</title> <style> h1 { color:green; } body { text-align:center; } a { text-decoration:none; color:green; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>a:hover in inline CSS</h2> <a href=\"#\" onMouseOver=\"this.style.color='red'\" onMouseOut=\"this.style.color='green'\" >GeeksforGeeks</a> </body></html> ",
"e": 26763,
"s": 26194,
"text": null
},
{
"code": null,
"e": 26771,
"s": 26763,
"text": "Output:"
},
{
"code": null,
"e": 26935,
"s": 26771,
"text": "Example 2: This example uses JavaScript to display a:hover content in CSS. The onmouseover and onmouseout event attribute is called to display the a:hover content."
},
{
"code": "<!DOCTYPE html><html> <head> <title>a:hover in inline CSS</title> <style> h1 { color:green; } body { text-align:center; } a { text-decoration:none; color:green; } </style> <script> function mouseover() { document.getElementById(\"gfg\").style.color = \"red\"; } function mouseout() { document.getElementById(\"gfg\").style.color = \"green\"; } </script> </head> <body> <h1>GeeksforGeeks</h1> <h2>a:hover in inline CSS</h2> <a href = \"#\" id=\"gfg\" onmouseover=\"mouseover()\" onmouseout=\"mouseout()\">GeeksforGeeks</a> </body></html> ",
"e": 27766,
"s": 26935,
"text": null
},
{
"code": null,
"e": 27774,
"s": 27766,
"text": "Output:"
},
{
"code": null,
"e": 27854,
"s": 27774,
"text": "Supported Browsers: The browser supported by a:hover selector are listed below:"
},
{
"code": null,
"e": 27871,
"s": 27854,
"text": "Apple Safari 3.1"
},
{
"code": null,
"e": 27889,
"s": 27871,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 27901,
"s": 27889,
"text": "Firefox 2.0"
},
{
"code": null,
"e": 27911,
"s": 27901,
"text": "Opera 9.6"
},
{
"code": null,
"e": 27933,
"s": 27911,
"text": "Internet Explorer 7.0"
},
{
"code": null,
"e": 28127,
"s": 27933,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 28313,
"s": 28127,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 28450,
"s": 28313,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28459,
"s": 28450,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28466,
"s": 28459,
"text": "Picked"
},
{
"code": null,
"e": 28470,
"s": 28466,
"text": "CSS"
},
{
"code": null,
"e": 28475,
"s": 28470,
"text": "HTML"
},
{
"code": null,
"e": 28492,
"s": 28475,
"text": "Web Technologies"
},
{
"code": null,
"e": 28497,
"s": 28492,
"text": "HTML"
},
{
"code": null,
"e": 28595,
"s": 28497,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28645,
"s": 28595,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28707,
"s": 28645,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28755,
"s": 28707,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28813,
"s": 28755,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28868,
"s": 28813,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 28918,
"s": 28868,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28980,
"s": 28918,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29028,
"s": 28980,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29088,
"s": 29028,
"text": "How to set the default value for an HTML <select> element ?"
}
]
|
What are Chrome Flags or Experiments? - GeeksforGeeks | 31 Mar, 2021
Chrome Flags also called Experiments are the experimental features that are provided by the Chrome browser but are not a part of the default chrome experience. Anyone can use them by following some simple steps and transform their chrome browsing experience. Some flags eventually become a part of the default public release once they are tried and tested completely. For example, the Tab Groups feature was first introduced as a Chrome flag before it was rolled out as a default feature.
Chrome flags Warning
Flags are experimental features and are not always stable. Using them might make the browser act weird or crash as they haven’t been tested extensively.
Flags are not tested thoroughly for security as well. So you might want to use a different browser or turn them off when doing online banking or other sensitive activities.
To enable a flag, the browser needs to be relaunched. Once the browser is relaunched, all the windows and tabs will reopen while the incognito windows will be lost.
Proceed with Caution
WARNING: EXPERIMENTAL FEATURES AHEAD!
By enabling these features, you could lose browser data or compromise your security or privacy.
Enabled features apply to all users of this browser.
Chrome flags can be accessed on this URL on any chrome browser be it Windows, Chromebook, MacOS, iPhones, or Android.
chrome://flags/
This will take you to the home page of Chrome Experiments where all the chrome flags are available along with their status (Default/Enabled/Disabled).
Let us consider the chrome flag Enable Tab Search.
There are two ways to access it:
Search with the name in the search box, or
Search for a flag
Go to the flag tag. For e.g. chrome://flags/#enable-tab-search
URL for a flag
Then just enable it and relaunch the browser.
Enable a flag
You can now see the Search Tabs icon on the right side of the title bar. With just a few clicks you can enable a very useful feature.
Individual flags can be reset similarly by changing their state to Default or Disabled. The Reset all button will bring everything back to the default state. In either case, chrome needs to be relaunched to apply the changes.
Here is a link to a list of some chrome flags mentioned on the Google Chrome Github page.
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
Top Programming Languages for Android App Development
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU. | [
{
"code": null,
"e": 26599,
"s": 26571,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 27088,
"s": 26599,
"text": "Chrome Flags also called Experiments are the experimental features that are provided by the Chrome browser but are not a part of the default chrome experience. Anyone can use them by following some simple steps and transform their chrome browsing experience. Some flags eventually become a part of the default public release once they are tried and tested completely. For example, the Tab Groups feature was first introduced as a Chrome flag before it was rolled out as a default feature."
},
{
"code": null,
"e": 27109,
"s": 27088,
"text": "Chrome flags Warning"
},
{
"code": null,
"e": 27262,
"s": 27109,
"text": "Flags are experimental features and are not always stable. Using them might make the browser act weird or crash as they haven’t been tested extensively."
},
{
"code": null,
"e": 27435,
"s": 27262,
"text": "Flags are not tested thoroughly for security as well. So you might want to use a different browser or turn them off when doing online banking or other sensitive activities."
},
{
"code": null,
"e": 27600,
"s": 27435,
"text": "To enable a flag, the browser needs to be relaunched. Once the browser is relaunched, all the windows and tabs will reopen while the incognito windows will be lost."
},
{
"code": null,
"e": 27622,
"s": 27600,
"text": "Proceed with Caution "
},
{
"code": null,
"e": 27811,
"s": 27622,
"text": "WARNING: EXPERIMENTAL FEATURES AHEAD! \nBy enabling these features, you could lose browser data or compromise your security or privacy. \nEnabled features apply to all users of this browser."
},
{
"code": null,
"e": 27929,
"s": 27811,
"text": "Chrome flags can be accessed on this URL on any chrome browser be it Windows, Chromebook, MacOS, iPhones, or Android."
},
{
"code": null,
"e": 27945,
"s": 27929,
"text": "chrome://flags/"
},
{
"code": null,
"e": 28096,
"s": 27945,
"text": "This will take you to the home page of Chrome Experiments where all the chrome flags are available along with their status (Default/Enabled/Disabled)."
},
{
"code": null,
"e": 28148,
"s": 28096,
"text": "Let us consider the chrome flag Enable Tab Search. "
},
{
"code": null,
"e": 28181,
"s": 28148,
"text": "There are two ways to access it:"
},
{
"code": null,
"e": 28225,
"s": 28181,
"text": "Search with the name in the search box, or "
},
{
"code": null,
"e": 28243,
"s": 28225,
"text": "Search for a flag"
},
{
"code": null,
"e": 28307,
"s": 28243,
"text": "Go to the flag tag. For e.g. chrome://flags/#enable-tab-search "
},
{
"code": null,
"e": 28322,
"s": 28307,
"text": "URL for a flag"
},
{
"code": null,
"e": 28369,
"s": 28322,
"text": "Then just enable it and relaunch the browser. "
},
{
"code": null,
"e": 28383,
"s": 28369,
"text": "Enable a flag"
},
{
"code": null,
"e": 28517,
"s": 28383,
"text": "You can now see the Search Tabs icon on the right side of the title bar. With just a few clicks you can enable a very useful feature."
},
{
"code": null,
"e": 28743,
"s": 28517,
"text": "Individual flags can be reset similarly by changing their state to Default or Disabled. The Reset all button will bring everything back to the default state. In either case, chrome needs to be relaunched to apply the changes."
},
{
"code": null,
"e": 28833,
"s": 28743,
"text": "Here is a link to a list of some chrome flags mentioned on the Google Chrome Github page."
},
{
"code": null,
"e": 28840,
"s": 28833,
"text": "How To"
},
{
"code": null,
"e": 28849,
"s": 28840,
"text": "TechTips"
},
{
"code": null,
"e": 28947,
"s": 28849,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28974,
"s": 28947,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 29019,
"s": 28974,
"text": "How to Install OpenCV for Python on Windows?"
},
{
"code": null,
"e": 29067,
"s": 29019,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 29081,
"s": 29067,
"text": "Java Tutorial"
},
{
"code": null,
"e": 29115,
"s": 29081,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 29169,
"s": 29115,
"text": "Top Programming Languages for Android App Development"
},
{
"code": null,
"e": 29195,
"s": 29169,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 29230,
"s": 29195,
"text": "Setting up the environment in Java"
},
{
"code": null,
"e": 29271,
"s": 29230,
"text": "How to Run a Python Script using Docker?"
}
]
|
Convert Array to HashSet in Java - GeeksforGeeks | 28 Dec, 2020
The Single Data structure cannot be able to fulfill the requirements of the programmers that’s why there are a lot of inbuilt Data-Structures in Programming languages.
Arrays are the most commonly used Data-Structure in most programming languages. The advantage of this Data-Structure is O(1) accessing the elements of the Arrays with the help of indexing but the most common disadvantages are we cannot change the size of the array after creating and the deletion of the elements is a complicated process in Arrays.
Sets: In Java, Any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface. Sets are classified into two parts sorted set and unsorted set bot have advantage and disadvantage. Sorted Set i.e TreeSet sort its unique elements but the time-complexity of TreeSet is O(N log N) but unsorted Sets such as HashSet and LinkedSet do change the order of the elements but the difference between the HashSet and LinkedSet is Random Order of its elements.
Examples:
Input : Array: [1, 2, 3, 4, 5, 6]
Output: Set: [1, 2, 3, 4, 5, 6]
Input : Array: [a, b, c, d]
Output: Set: [a, b, c, d]
Approach: Brute Force or Naive Method
Create an empty set (HashSet if unsorted elements require) Iterate the elements of the array and add one by one to the set.
Example:
// Convert array to HashSet in Javaimport java.io.*;import java.util.Iterator;// Importing Set librariesimport java.util.Set;import java.util.HashSet; class GFG { // Function to convert array to set static Set<Integer> convert(int[] array) { // Hash Set Initialisation Set<Integer> Set = new HashSet<>(); // Iteration using enhanced for loop for (int element : array) { Set.add(element); } // returning the set return Set; } // Function to print the set static void print(Set<Integer> Set) { // Implement to iterator the Set Iterator<Integer> _iterator = Set.iterator(); // Iterate the elements of Set while (_iterator.hasNext()) { // print the element of the Set System.out.print(_iterator.next() + " "); } } public static void main(String[] args) { // Array taken for consideration int array[] = { 1, 2, 3, 4, 5, 6 }; // Calling function to convert the array Set<Integer> Set = convert(array); // print the set print(Set); }}
1 2 3 4 5 6
Approach 2:
Using Java 8 Stream API: HashSet constructor can take another collection object to construct a new set containing the elements of the specified array.
Get the Array to be converted.Convert the array to StreamConvert the Stream to Set using Collectors.toSet()Collect the formed set using the collect() methodReturn the formed Set.
Get the Array to be converted.
Convert the array to Stream
Convert the Stream to Set using Collectors.toSet()
Collect the formed set using the collect() method
Return the formed Set.
Example:
// Convert Array to HashSet in Java import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert array to set public static <T> Set<T> convertArrayToSet(T array[]) { // create a set from the Array return Arrays.stream(array).collect( Collectors.toSet()); } public static void main(String args[]) { // Create an Array String array[] = { "Geeks", "forGeeks", "A computer Portal" }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to Set Set<String> set = convertArrayToSet(array); // Print the Set System.out.println("Set: " + set); }}
Array: [Geeks, forGeeks, A computer Portal]
Set: [A computer Portal, Geeks, forGeeks]
Java-Arrays
java-hashset
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 25447,
"s": 25419,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 25616,
"s": 25447,
"text": "The Single Data structure cannot be able to fulfill the requirements of the programmers that’s why there are a lot of inbuilt Data-Structures in Programming languages. "
},
{
"code": null,
"e": 25965,
"s": 25616,
"text": "Arrays are the most commonly used Data-Structure in most programming languages. The advantage of this Data-Structure is O(1) accessing the elements of the Arrays with the help of indexing but the most common disadvantages are we cannot change the size of the array after creating and the deletion of the elements is a complicated process in Arrays."
},
{
"code": null,
"e": 26607,
"s": 25965,
"text": "Sets: In Java, Any group of individual objects which are represented as a single unit is known as the collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface. Sets are classified into two parts sorted set and unsorted set bot have advantage and disadvantage. Sorted Set i.e TreeSet sort its unique elements but the time-complexity of TreeSet is O(N log N) but unsorted Sets such as HashSet and LinkedSet do change the order of the elements but the difference between the HashSet and LinkedSet is Random Order of its elements."
},
{
"code": null,
"e": 26617,
"s": 26607,
"text": "Examples:"
},
{
"code": null,
"e": 26739,
"s": 26617,
"text": "Input : Array: [1, 2, 3, 4, 5, 6]\nOutput: Set: [1, 2, 3, 4, 5, 6]\n \nInput : Array: [a, b, c, d]\nOutput: Set: [a, b, c, d]"
},
{
"code": null,
"e": 26777,
"s": 26739,
"text": "Approach: Brute Force or Naive Method"
},
{
"code": null,
"e": 26902,
"s": 26777,
"text": "Create an empty set (HashSet if unsorted elements require) Iterate the elements of the array and add one by one to the set."
},
{
"code": null,
"e": 26911,
"s": 26902,
"text": "Example:"
},
{
"code": "// Convert array to HashSet in Javaimport java.io.*;import java.util.Iterator;// Importing Set librariesimport java.util.Set;import java.util.HashSet; class GFG { // Function to convert array to set static Set<Integer> convert(int[] array) { // Hash Set Initialisation Set<Integer> Set = new HashSet<>(); // Iteration using enhanced for loop for (int element : array) { Set.add(element); } // returning the set return Set; } // Function to print the set static void print(Set<Integer> Set) { // Implement to iterator the Set Iterator<Integer> _iterator = Set.iterator(); // Iterate the elements of Set while (_iterator.hasNext()) { // print the element of the Set System.out.print(_iterator.next() + \" \"); } } public static void main(String[] args) { // Array taken for consideration int array[] = { 1, 2, 3, 4, 5, 6 }; // Calling function to convert the array Set<Integer> Set = convert(array); // print the set print(Set); }}",
"e": 28046,
"s": 26911,
"text": null
},
{
"code": null,
"e": 28058,
"s": 28046,
"text": "1 2 3 4 5 6"
},
{
"code": null,
"e": 28071,
"s": 28058,
"text": "Approach 2: "
},
{
"code": null,
"e": 28222,
"s": 28071,
"text": "Using Java 8 Stream API: HashSet constructor can take another collection object to construct a new set containing the elements of the specified array."
},
{
"code": null,
"e": 28401,
"s": 28222,
"text": "Get the Array to be converted.Convert the array to StreamConvert the Stream to Set using Collectors.toSet()Collect the formed set using the collect() methodReturn the formed Set."
},
{
"code": null,
"e": 28432,
"s": 28401,
"text": "Get the Array to be converted."
},
{
"code": null,
"e": 28460,
"s": 28432,
"text": "Convert the array to Stream"
},
{
"code": null,
"e": 28511,
"s": 28460,
"text": "Convert the Stream to Set using Collectors.toSet()"
},
{
"code": null,
"e": 28561,
"s": 28511,
"text": "Collect the formed set using the collect() method"
},
{
"code": null,
"e": 28584,
"s": 28561,
"text": "Return the formed Set."
},
{
"code": null,
"e": 28593,
"s": 28584,
"text": "Example:"
},
{
"code": "// Convert Array to HashSet in Java import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert array to set public static <T> Set<T> convertArrayToSet(T array[]) { // create a set from the Array return Arrays.stream(array).collect( Collectors.toSet()); } public static void main(String args[]) { // Create an Array String array[] = { \"Geeks\", \"forGeeks\", \"A computer Portal\" }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to Set Set<String> set = convertArrayToSet(array); // Print the Set System.out.println(\"Set: \" + set); }}",
"e": 29354,
"s": 28593,
"text": null
},
{
"code": null,
"e": 29440,
"s": 29354,
"text": "Array: [Geeks, forGeeks, A computer Portal]\nSet: [A computer Portal, Geeks, forGeeks]"
},
{
"code": null,
"e": 29452,
"s": 29440,
"text": "Java-Arrays"
},
{
"code": null,
"e": 29465,
"s": 29452,
"text": "java-hashset"
},
{
"code": null,
"e": 29472,
"s": 29465,
"text": "Picked"
},
{
"code": null,
"e": 29496,
"s": 29472,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 29501,
"s": 29496,
"text": "Java"
},
{
"code": null,
"e": 29515,
"s": 29501,
"text": "Java Programs"
},
{
"code": null,
"e": 29534,
"s": 29515,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29539,
"s": 29534,
"text": "Java"
},
{
"code": null,
"e": 29637,
"s": 29539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29652,
"s": 29637,
"text": "Stream In Java"
},
{
"code": null,
"e": 29671,
"s": 29652,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29689,
"s": 29671,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29721,
"s": 29689,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29741,
"s": 29721,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29769,
"s": 29741,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 29813,
"s": 29769,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 29839,
"s": 29813,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29873,
"s": 29839,
"text": "Convert Double to Integer in Java"
}
]
|
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks | 28 Jun, 2021
The height of a tree is the length of the longest root-to-leaf path in it. The maximum and minimum number of nodes in a binary tree of height 5 are(A) 63 and 6, respectively(B) 64 and 5, respectively(C) 32 and 6, respectively(D) 31 and 5, respectivelyAnswer: (A)Explanation:
Number of nodes is maximum for a perfect binary tree.
A perfect binary tree of height h has 2h+1 - 1 nodes
Number of nodes is minimum for a skewed binary tree.
A perfect binary tree of height h has h+1 nodes.
Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25719,
"s": 25691,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25994,
"s": 25719,
"text": "The height of a tree is the length of the longest root-to-leaf path in it. The maximum and minimum number of nodes in a binary tree of height 5 are(A) 63 and 6, respectively(B) 64 and 5, respectively(C) 32 and 6, respectively(D) 31 and 5, respectivelyAnswer: (A)Explanation:"
},
{
"code": null,
"e": 26205,
"s": 25994,
"text": "Number of nodes is maximum for a perfect binary tree.\nA perfect binary tree of height h has 2h+1 - 1 nodes\n\nNumber of nodes is minimum for a skewed binary tree.\nA perfect binary tree of height h has h+1 nodes.\n"
},
{
"code": null,
"e": 26227,
"s": 26205,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26248,
"s": 26227,
"text": "GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 26274,
"s": 26248,
"text": "GATE-GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 26279,
"s": 26274,
"text": "GATE"
},
{
"code": null,
"e": 26377,
"s": 26279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26411,
"s": 26377,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26445,
"s": 26411,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26479,
"s": 26445,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26512,
"s": 26479,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26548,
"s": 26512,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26584,
"s": 26548,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26618,
"s": 26584,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26652,
"s": 26618,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26686,
"s": 26652,
"text": "GATE | GATE-CS-2009 | Question 38"
}
]
|
C# Program to Sort a List of Employees Based on Salary in Descending Order and Whose Department is XYZ using LINQ - GeeksforGeeks | 28 Feb, 2022
Given a list of employees, now we sort the list according to the salary in descending order and whose department is XYZ. So we use the OrderByDescending() method of LINQ along with the Where() method. The OrderByDescending() is used to sort the specified list in descending order. To solve the given problem we use the following LINQ query:
var result_set = Geeks.Where(emp=>emp.Emp_Department==”XYZ”).OrderByDescending(sal => sal.Emp_Salary);
Here, the Where() method finds those employees whose department is “XYZ” and OrderByDescending() method sort them in descending order based on their salary.
Example:
Input: {id = 202, Name = Mohit, Salary = 10000, Department = XYZ}
{id = 204, Name = Sumit, Salary = 20000, Department = ABC}
{id = 205, Name = Pritam, Salary = 80000, Department = ABC}
{id = 206, Name = Poonam, Salary = 30000, Department = XYZ}
Output: {id = 206, Name = Poonam, Salary = 30000, Department = XYZ}
{id = 202, Name = Mohit, Salary = 10000, Department = XYZ}
C#
// C# program to sort a list of employees based on// salary in descending order and whose department is XYZusing System;using System.Linq;using System.Collections.Generic; class Geek{ int emp_id;string Emp_Name;int Emp_Salary;string Emp_Department; static void Main(string[] args){ // List to store the details of employees List<Geek> Geeks = new List<Geek>() { new Geek{emp_id = 101, Emp_Name = "Amit", Emp_Salary = 50000,Emp_Department = "XYZ"}, new Geek{emp_id = 102, Emp_Name = "Poonam", Emp_Salary = 65000,Emp_Department = "ABC"}, new Geek{emp_id = 103, Emp_Name = "Priya", Emp_Salary = 45000,Emp_Department = "ABC"}, new Geek{emp_id = 104, Emp_Name = "Sita", Emp_Salary = 20000,Emp_Department = "XYZ"}, new Geek{emp_id = 105, Emp_Name = "kiran", Emp_Salary = 70000,Emp_Department = "ABC"}, new Geek{emp_id = 106, Emp_Name = "Sohan", Emp_Salary = 40000,Emp_Department = "XYZ"}, }; // Using the where command we have selected the // geeks having XYZ department and then we have // sorted the data in descending order using // OrderByDescending() command var result_set = Geeks.Where(emp => emp.Emp_Department == "XYZ").OrderByDescending( sal => sal.Emp_Salary); // Display the results foreach (Geek emp in result_set) { Console.WriteLine(emp.emp_id + " " + emp.Emp_Name + " " + emp.Emp_Salary + " " + emp.Emp_Department); }}}
Output:
101 Amit 50000 XYZ
106 Sohan 40000 XYZ
104 Sita 20000 XYZ
nikhatkhan11
CSharp LINQ
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7 | [
{
"code": null,
"e": 25571,
"s": 25543,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 25912,
"s": 25571,
"text": "Given a list of employees, now we sort the list according to the salary in descending order and whose department is XYZ. So we use the OrderByDescending() method of LINQ along with the Where() method. The OrderByDescending() is used to sort the specified list in descending order. To solve the given problem we use the following LINQ query:"
},
{
"code": null,
"e": 26015,
"s": 25912,
"text": "var result_set = Geeks.Where(emp=>emp.Emp_Department==”XYZ”).OrderByDescending(sal => sal.Emp_Salary);"
},
{
"code": null,
"e": 26172,
"s": 26015,
"text": "Here, the Where() method finds those employees whose department is “XYZ” and OrderByDescending() method sort them in descending order based on their salary."
},
{
"code": null,
"e": 26182,
"s": 26172,
"text": "Example: "
},
{
"code": null,
"e": 26583,
"s": 26182,
"text": "Input: {id = 202, Name = Mohit, Salary = 10000, Department = XYZ}\n {id = 204, Name = Sumit, Salary = 20000, Department = ABC}\n {id = 205, Name = Pritam, Salary = 80000, Department = ABC}\n {id = 206, Name = Poonam, Salary = 30000, Department = XYZ}\nOutput: {id = 206, Name = Poonam, Salary = 30000, Department = XYZ}\n {id = 202, Name = Mohit, Salary = 10000, Department = XYZ}"
},
{
"code": null,
"e": 26586,
"s": 26583,
"text": "C#"
},
{
"code": "// C# program to sort a list of employees based on// salary in descending order and whose department is XYZusing System;using System.Linq;using System.Collections.Generic; class Geek{ int emp_id;string Emp_Name;int Emp_Salary;string Emp_Department; static void Main(string[] args){ // List to store the details of employees List<Geek> Geeks = new List<Geek>() { new Geek{emp_id = 101, Emp_Name = \"Amit\", Emp_Salary = 50000,Emp_Department = \"XYZ\"}, new Geek{emp_id = 102, Emp_Name = \"Poonam\", Emp_Salary = 65000,Emp_Department = \"ABC\"}, new Geek{emp_id = 103, Emp_Name = \"Priya\", Emp_Salary = 45000,Emp_Department = \"ABC\"}, new Geek{emp_id = 104, Emp_Name = \"Sita\", Emp_Salary = 20000,Emp_Department = \"XYZ\"}, new Geek{emp_id = 105, Emp_Name = \"kiran\", Emp_Salary = 70000,Emp_Department = \"ABC\"}, new Geek{emp_id = 106, Emp_Name = \"Sohan\", Emp_Salary = 40000,Emp_Department = \"XYZ\"}, }; // Using the where command we have selected the // geeks having XYZ department and then we have // sorted the data in descending order using // OrderByDescending() command var result_set = Geeks.Where(emp => emp.Emp_Department == \"XYZ\").OrderByDescending( sal => sal.Emp_Salary); // Display the results foreach (Geek emp in result_set) { Console.WriteLine(emp.emp_id + \" \" + emp.Emp_Name + \" \" + emp.Emp_Salary + \" \" + emp.Emp_Department); }}}",
"e": 28251,
"s": 26586,
"text": null
},
{
"code": null,
"e": 28259,
"s": 28251,
"text": "Output:"
},
{
"code": null,
"e": 28317,
"s": 28259,
"text": "101 Amit 50000 XYZ\n106 Sohan 40000 XYZ\n104 Sita 20000 XYZ"
},
{
"code": null,
"e": 28332,
"s": 28319,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 28344,
"s": 28332,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 28351,
"s": 28344,
"text": "Picked"
},
{
"code": null,
"e": 28354,
"s": 28351,
"text": "C#"
},
{
"code": null,
"e": 28366,
"s": 28354,
"text": "C# Programs"
},
{
"code": null,
"e": 28464,
"s": 28366,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28487,
"s": 28464,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28515,
"s": 28487,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28532,
"s": 28515,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28554,
"s": 28532,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28583,
"s": 28554,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 28623,
"s": 28583,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28657,
"s": 28623,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 28703,
"s": 28657,
"text": "Getting a Month Name Using Month Number in C#"
},
{
"code": null,
"e": 28728,
"s": 28703,
"text": "Socket Programming in C#"
}
]
|
Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n - GeeksforGeeks | 12 Apr, 2021
This is a mathematical series program where a user must enter the number of terms up to which the sum of the series is to be found. Following this, we also need the value of x, which forms the base of the series.Examples :
Input : base = 2, range = 5
Output : 18.07
Input : base = 1, range = 10
Output : 3.93
Method 1 (Simple) We just need to follow the series and put the values of the base at x and value range at n and get the sum.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of series// 1 + x/1 + x^2/2 + x^3/3 + ....+ x^n/n#include <math.h>#include <iostream>#include <boost/format.hpp>class gfg{public :double sum(int x, int n){ double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (pow(x, i) / i); return total;}};// Driver codeint main(){ gfg g; int x = 2; int n = 5; //std::cout<<g.sum(x,n); std::cout << boost::format("%.2f") % g.sum(x,n); return 0;}
// C program to find sum of series// 1 + x/1 + x^2/2 + x^3/3 + ....+ x^n/n#include <math.h>#include <stdio.h> double sum(int x, int n){ double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (pow(x, i) / i); return total;} // Driver codeint main(){ int x = 2; int n = 5; printf("%.2f", sum(x, n)); return 0;}
// Java program to find sum of series// 1 + 1/x + x^2/2 + x^3/3 + ....+ x^n/nimport static java.lang.Math.pow; class GFG{ // Java code to print the// sum of the seriesstatic double sum(int x, int n){ double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (Math.pow(x, i) / i); return total;} // Driver codepublic static void main(String[] args){ int x = 2; int n = 5; System.out.printf("%.2f", sum(x, n));}} // This code is contributed by// Smitha Dinesh Semwal
# Python3 code to find sum of series# 1 + x/1 + x^2/2 + x^3/3 + .. .+ x^n/n def SUM(x, n): total = 1 for i in range(1, n + 1): total = total + ((x**i)/i) return total # Driver Codex = 2n = 5s = SUM(x, n)print(round(s, 2))
// C# program to find sum of series// 1 + 1/x + x^2/2 + x^3/3 + ....+ x^n/nusing System; class GFG{ // Java code to print the // sum of the series static float sum(int x, int n) { double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (Math.Pow(x, i) / i); return (float)total; } // Driver code public static void Main() { int x = 2; int n = 5; Console.WriteLine(sum(x, n)); }} // This code is contributed by vt_m.
<?php// PHP program to find sum of series// 1 + x/1 + x^2/2 + x^3/3 + ....+ x^n/n // Code to print the sum// of the seriesfunction sum($x, $n){ $i; $total = 1.0; for ($i = 1; $i <= $n; $i++) $total = $total + (pow($x, $i) / $i); return $total;} // Driver code$x = 2;$n = 5;echo(sum($x, $n)); // This code is contributed by Ajit.?>
<script>// JavaScript program to find sum of series// 1 + x/1 + x^2/2 + x^3/3 + ....+ x^n/nfunction sum(x, n){ let i, total = 1.0; for (i = 1; i <= n; i++) total = total + (Math.pow(x, i) / i); return total;} // Driver code let g; let x = 2; let n = 5; document.write(sum(x, n).toFixed(2)); // This code is contributed by Surbhi Tyagi.</script>
Output :
18.07
Method 2 (Optimized) We can avoid use of pow() function and reuse the previously computed power.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n#include <bits/stdc++.h>using namespace std; // C++ code to print the sum// of the seriesdouble sum(int x, int n){ double i, total = 1.0, multi = x; for (i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return total;} // Driver codeint main(){ int x = 2; int n = 5; cout << fixed << setprecision(2) << sum(x, n); return 0;} // This code is contributed by shubhamsingh10
// C program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n#include <math.h>#include <stdio.h> // C code to print the sum// of the seriesdouble sum(int x, int n){ double i, total = 1.0, multi = x; for (i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return total;} // Driver codeint main(){ int x = 2; int n = 5; printf("%.2f", sum(x, n)); return 0;}
// Java program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n class GFG{ // Java code to print the sum// of the given seriesstatic double sum(int x, int n){ double i, total = 1.0, multi = x; for (i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return total;} // Driver codepublic static void main(String[] args){ int x = 2; int n = 5; System.out.printf("%.2f", sum(x, n));}} // This code is contributed by// Smitha Dinesh Semwal
# Python 3 program to find sum of series# 1 + x^2/2 + x^3/3 + ....+ x^n/n # Python 3 code to print the# sum of the seriesdef sum(x, n): total = 1.0 multi = x for i in range(1, n+1): total = total + multi / i multi = multi * x return total # Driver codex = 2n = 5print(round(sum(x, n), 2)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/nusing System; class GFG{ // Java code to print the sum // of the given series static float sum(int x, int n) { double i, total = 1.0, multi = x; for (i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return (float)total; } // Driver code public static void Main() { int x = 2; int n = 5; Console.WriteLine(sum(x, n)); }} // This code is contributed by vt_m.
<?php// PHP program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n // code to print the sum// of the seriesfunction sum($x, $n){ $i; $total = 1.0; $multi = $x; for ($i = 1; $i <= $n; $i++) { $total = $total + $multi / $i; $multi = $multi * $x; } return $total;} // Driver code$x = 2;$n = 5;echo(sum($x, $n)); // This code is contributed by Ajit.?>
<script> // Javascript program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n // JavaScript code to print the sum// of the seriesfunction sum(x, n){ let total = 1.0; let multi = x; for (let i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return total;} // Driver codelet x = 2;let n = 5;document.write(sum(x, n).toFixed(2)); // This code is contributed by sravan kumar </script>
Output :
18.07
jit_t
SoumikMondal
SHUBHAMSINGH10
surbhityagi15
sravankumar8128
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number
Print all possible combinations of r elements in a given array of size n
The Knight's tour problem | Backtracking-1
Operators in C / C++
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Minimum number of jumps to reach end
Program to print prime numbers from 1 to N.
Euclidean algorithms (Basic and Extended) | [
{
"code": null,
"e": 26583,
"s": 26555,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 26808,
"s": 26583,
"text": "This is a mathematical series program where a user must enter the number of terms up to which the sum of the series is to be found. Following this, we also need the value of x, which forms the base of the series.Examples : "
},
{
"code": null,
"e": 26895,
"s": 26808,
"text": "Input : base = 2, range = 5\nOutput : 18.07\n\nInput : base = 1, range = 10\nOutput : 3.93"
},
{
"code": null,
"e": 27024,
"s": 26897,
"text": "Method 1 (Simple) We just need to follow the series and put the values of the base at x and value range at n and get the sum. "
},
{
"code": null,
"e": 27028,
"s": 27024,
"text": "C++"
},
{
"code": null,
"e": 27030,
"s": 27028,
"text": "C"
},
{
"code": null,
"e": 27035,
"s": 27030,
"text": "Java"
},
{
"code": null,
"e": 27043,
"s": 27035,
"text": "Python3"
},
{
"code": null,
"e": 27046,
"s": 27043,
"text": "C#"
},
{
"code": null,
"e": 27050,
"s": 27046,
"text": "PHP"
},
{
"code": null,
"e": 27061,
"s": 27050,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of series// 1 + x/1 + x^2/2 + x^3/3 + ....+ x^n/n#include <math.h>#include <iostream>#include <boost/format.hpp>class gfg{public :double sum(int x, int n){ double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (pow(x, i) / i); return total;}};// Driver codeint main(){ gfg g; int x = 2; int n = 5; //std::cout<<g.sum(x,n); std::cout << boost::format(\"%.2f\") % g.sum(x,n); return 0;}",
"e": 27530,
"s": 27061,
"text": null
},
{
"code": "// C program to find sum of series// 1 + x/1 + x^2/2 + x^3/3 + ....+ x^n/n#include <math.h>#include <stdio.h> double sum(int x, int n){ double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (pow(x, i) / i); return total;} // Driver codeint main(){ int x = 2; int n = 5; printf(\"%.2f\", sum(x, n)); return 0;}",
"e": 27891,
"s": 27530,
"text": null
},
{
"code": "// Java program to find sum of series// 1 + 1/x + x^2/2 + x^3/3 + ....+ x^n/nimport static java.lang.Math.pow; class GFG{ // Java code to print the// sum of the seriesstatic double sum(int x, int n){ double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (Math.pow(x, i) / i); return total;} // Driver codepublic static void main(String[] args){ int x = 2; int n = 5; System.out.printf(\"%.2f\", sum(x, n));}} // This code is contributed by// Smitha Dinesh Semwal",
"e": 28407,
"s": 27891,
"text": null
},
{
"code": "# Python3 code to find sum of series# 1 + x/1 + x^2/2 + x^3/3 + .. .+ x^n/n def SUM(x, n): total = 1 for i in range(1, n + 1): total = total + ((x**i)/i) return total # Driver Codex = 2n = 5s = SUM(x, n)print(round(s, 2))",
"e": 28645,
"s": 28407,
"text": null
},
{
"code": "// C# program to find sum of series// 1 + 1/x + x^2/2 + x^3/3 + ....+ x^n/nusing System; class GFG{ // Java code to print the // sum of the series static float sum(int x, int n) { double i, total = 1.0; for (i = 1; i <= n; i++) total = total + (Math.Pow(x, i) / i); return (float)total; } // Driver code public static void Main() { int x = 2; int n = 5; Console.WriteLine(sum(x, n)); }} // This code is contributed by vt_m.",
"e": 29171,
"s": 28645,
"text": null
},
{
"code": "<?php// PHP program to find sum of series// 1 + x/1 + x^2/2 + x^3/3 + ....+ x^n/n // Code to print the sum// of the seriesfunction sum($x, $n){ $i; $total = 1.0; for ($i = 1; $i <= $n; $i++) $total = $total + (pow($x, $i) / $i); return $total;} // Driver code$x = 2;$n = 5;echo(sum($x, $n)); // This code is contributed by Ajit.?>",
"e": 29534,
"s": 29171,
"text": null
},
{
"code": "<script>// JavaScript program to find sum of series// 1 + x/1 + x^2/2 + x^3/3 + ....+ x^n/nfunction sum(x, n){ let i, total = 1.0; for (i = 1; i <= n; i++) total = total + (Math.pow(x, i) / i); return total;} // Driver code let g; let x = 2; let n = 5; document.write(sum(x, n).toFixed(2)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 29922,
"s": 29534,
"text": null
},
{
"code": null,
"e": 29933,
"s": 29922,
"text": "Output : "
},
{
"code": null,
"e": 29939,
"s": 29933,
"text": "18.07"
},
{
"code": null,
"e": 30038,
"s": 29939,
"text": "Method 2 (Optimized) We can avoid use of pow() function and reuse the previously computed power. "
},
{
"code": null,
"e": 30042,
"s": 30038,
"text": "C++"
},
{
"code": null,
"e": 30044,
"s": 30042,
"text": "C"
},
{
"code": null,
"e": 30049,
"s": 30044,
"text": "Java"
},
{
"code": null,
"e": 30057,
"s": 30049,
"text": "Python3"
},
{
"code": null,
"e": 30060,
"s": 30057,
"text": "C#"
},
{
"code": null,
"e": 30064,
"s": 30060,
"text": "PHP"
},
{
"code": null,
"e": 30075,
"s": 30064,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n#include <bits/stdc++.h>using namespace std; // C++ code to print the sum// of the seriesdouble sum(int x, int n){ double i, total = 1.0, multi = x; for (i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return total;} // Driver codeint main(){ int x = 2; int n = 5; cout << fixed << setprecision(2) << sum(x, n); return 0;} // This code is contributed by shubhamsingh10",
"e": 30577,
"s": 30075,
"text": null
},
{
"code": "// C program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n#include <math.h>#include <stdio.h> // C code to print the sum// of the seriesdouble sum(int x, int n){ double i, total = 1.0, multi = x; for (i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return total;} // Driver codeint main(){ int x = 2; int n = 5; printf(\"%.2f\", sum(x, n)); return 0;}",
"e": 30997,
"s": 30577,
"text": null
},
{
"code": "// Java program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n class GFG{ // Java code to print the sum// of the given seriesstatic double sum(int x, int n){ double i, total = 1.0, multi = x; for (i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return total;} // Driver codepublic static void main(String[] args){ int x = 2; int n = 5; System.out.printf(\"%.2f\", sum(x, n));}} // This code is contributed by// Smitha Dinesh Semwal",
"e": 31496,
"s": 30997,
"text": null
},
{
"code": "# Python 3 program to find sum of series# 1 + x^2/2 + x^3/3 + ....+ x^n/n # Python 3 code to print the# sum of the seriesdef sum(x, n): total = 1.0 multi = x for i in range(1, n+1): total = total + multi / i multi = multi * x return total # Driver codex = 2n = 5print(round(sum(x, n), 2)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 31870,
"s": 31496,
"text": null
},
{
"code": "// C# program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/nusing System; class GFG{ // Java code to print the sum // of the given series static float sum(int x, int n) { double i, total = 1.0, multi = x; for (i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return (float)total; } // Driver code public static void Main() { int x = 2; int n = 5; Console.WriteLine(sum(x, n)); }} // This code is contributed by vt_m.",
"e": 32424,
"s": 31870,
"text": null
},
{
"code": "<?php// PHP program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n // code to print the sum// of the seriesfunction sum($x, $n){ $i; $total = 1.0; $multi = $x; for ($i = 1; $i <= $n; $i++) { $total = $total + $multi / $i; $multi = $multi * $x; } return $total;} // Driver code$x = 2;$n = 5;echo(sum($x, $n)); // This code is contributed by Ajit.?>",
"e": 32810,
"s": 32424,
"text": null
},
{
"code": "<script> // Javascript program to find sum of series// 1 + x^2/2 + x^3/3 + ....+ x^n/n // JavaScript code to print the sum// of the seriesfunction sum(x, n){ let total = 1.0; let multi = x; for (let i = 1; i <= n; i++) { total = total + multi / i; multi = multi * x; } return total;} // Driver codelet x = 2;let n = 5;document.write(sum(x, n).toFixed(2)); // This code is contributed by sravan kumar </script>",
"e": 33258,
"s": 32810,
"text": null
},
{
"code": null,
"e": 33269,
"s": 33258,
"text": "Output : "
},
{
"code": null,
"e": 33275,
"s": 33269,
"text": "18.07"
},
{
"code": null,
"e": 33283,
"s": 33277,
"text": "jit_t"
},
{
"code": null,
"e": 33296,
"s": 33283,
"text": "SoumikMondal"
},
{
"code": null,
"e": 33311,
"s": 33296,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 33325,
"s": 33311,
"text": "surbhityagi15"
},
{
"code": null,
"e": 33341,
"s": 33325,
"text": "sravankumar8128"
},
{
"code": null,
"e": 33348,
"s": 33341,
"text": "series"
},
{
"code": null,
"e": 33361,
"s": 33348,
"text": "Mathematical"
},
{
"code": null,
"e": 33374,
"s": 33361,
"text": "Mathematical"
},
{
"code": null,
"e": 33381,
"s": 33374,
"text": "series"
},
{
"code": null,
"e": 33479,
"s": 33381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33522,
"s": 33479,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33556,
"s": 33522,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 33629,
"s": 33556,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 33672,
"s": 33629,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 33693,
"s": 33672,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 33746,
"s": 33693,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 33795,
"s": 33746,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33832,
"s": 33795,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 33876,
"s": 33832,
"text": "Program to print prime numbers from 1 to N."
}
]
|
numpy.arccosh() in Python - GeeksforGeeks | 29 Nov, 2018
numpy.arccosh() : This mathematical function helps user to calculate inverse hyperbolic cosine, element-wise for all arr.
Syntax :
numpy.arccosh(arr, /, out=None, *, where=True,casting=’same_kind’, order=’K’, dtype=None, ufunc ‘arccosh’)
Parameters :
arr : array_likeInput array.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : array_like, optionalValues of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs :Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
Return : An array with inverse hyperbolic cosine of arrfor all arr i.e. array elements.
Note :
2pi Radians = 360 degreesThe convention is to return the angle of arr whose imaginary part lies in [-pi, pi] and the real part in [0, inf].
Code #1 : Working
# Python program explaining# arccosh() function import numpy as np in_array = [2, 1, 10, 100]print ("Input array : \n", in_array) arccosh_Values = np.arccosh(in_array)print ("\nInverse hyperbolic Cosine values : \n", arccosh_Values)
Output :
Input array :
[2, 1, 10, 100]
Inverse hyperbolic Cosine values :
[ 1.3169579 0. 2.99322285 5.29829237]
Code #2 : Graphical representation
# Python program showing# Graphical representation # of arccosh() function%matplotlib inline import numpy as npimport matplotlib.pyplot as pltin_array = np.linspace(1, np.pi, 18)out_array1 = np.cos(in_array)out_array2 = np.arccosh(in_array) print("in_array : ", in_array)print("\nout_array with cos : ", out_array1)print("\nout_array with arccosh : ", out_array2)#blue for numpy.cosh() # red for numpy.arccosh()plt.plot(in_array, out_array1, color = 'blue', marker = ".") plt.plot(in_array, out_array2, color = 'red', marker = "+") plt.title("blue : numpy.cos() \nred : numpy.arccosh()")plt.xlabel("X")plt.ylabel("Y")
Output :
in_array : [ 1. 1.12597604 1.25195208 1.37792812 1.50390415 1.62988019
1.75585623 1.88183227 2.00780831 2.13378435 2.25976038 2.38573642
2.51171246 2.6376885 2.76366454 2.88964058 3.01561662 3.14159265]
out_array with cos : [ 0.54030231 0.43029566 0.31346927 0.19167471 0.0668423 -0.0590495
-0.18400541 -0.30604504 -0.42323415 -0.53371544 -0.63573787 -0.72768451
-0.80809809 -0.87570413 -0.92943115 -0.96842762 -0.99207551 -1. ]
out_array with arccosh : [ 0. 0.49682282 0.69574433 0.84411504 0.96590748 1.07053332
1.16287802 1.24587516 1.32145434 1.39096696 1.45540398 1.51551804
1.57189678 1.62500948 1.67523791 1.7228975 1.76825238 1.81152627]
)
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 25787,
"s": 25665,
"text": "numpy.arccosh() : This mathematical function helps user to calculate inverse hyperbolic cosine, element-wise for all arr."
},
{
"code": null,
"e": 25796,
"s": 25787,
"text": "Syntax :"
},
{
"code": null,
"e": 25903,
"s": 25796,
"text": "numpy.arccosh(arr, /, out=None, *, where=True,casting=’same_kind’, order=’K’, dtype=None, ufunc ‘arccosh’)"
},
{
"code": null,
"e": 25916,
"s": 25903,
"text": "Parameters :"
},
{
"code": null,
"e": 26440,
"s": 25916,
"text": "arr : array_likeInput array.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : array_like, optionalValues of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs :Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function."
},
{
"code": null,
"e": 26528,
"s": 26440,
"text": "Return : An array with inverse hyperbolic cosine of arrfor all arr i.e. array elements."
},
{
"code": null,
"e": 26535,
"s": 26528,
"text": "Note :"
},
{
"code": null,
"e": 26675,
"s": 26535,
"text": "2pi Radians = 360 degreesThe convention is to return the angle of arr whose imaginary part lies in [-pi, pi] and the real part in [0, inf]."
},
{
"code": null,
"e": 26694,
"s": 26675,
"text": " Code #1 : Working"
},
{
"code": "# Python program explaining# arccosh() function import numpy as np in_array = [2, 1, 10, 100]print (\"Input array : \\n\", in_array) arccosh_Values = np.arccosh(in_array)print (\"\\nInverse hyperbolic Cosine values : \\n\", arccosh_Values)",
"e": 26930,
"s": 26694,
"text": null
},
{
"code": null,
"e": 26939,
"s": 26930,
"text": "Output :"
},
{
"code": null,
"e": 27059,
"s": 26939,
"text": "Input array : \n [2, 1, 10, 100]\n\nInverse hyperbolic Cosine values : \n [ 1.3169579 0. 2.99322285 5.29829237]"
},
{
"code": null,
"e": 27095,
"s": 27059,
"text": " Code #2 : Graphical representation"
},
{
"code": "# Python program showing# Graphical representation # of arccosh() function%matplotlib inline import numpy as npimport matplotlib.pyplot as pltin_array = np.linspace(1, np.pi, 18)out_array1 = np.cos(in_array)out_array2 = np.arccosh(in_array) print(\"in_array : \", in_array)print(\"\\nout_array with cos : \", out_array1)print(\"\\nout_array with arccosh : \", out_array2)#blue for numpy.cosh() # red for numpy.arccosh()plt.plot(in_array, out_array1, color = 'blue', marker = \".\") plt.plot(in_array, out_array2, color = 'red', marker = \"+\") plt.title(\"blue : numpy.cos() \\nred : numpy.arccosh()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")",
"e": 27766,
"s": 27095,
"text": null
},
{
"code": null,
"e": 27775,
"s": 27766,
"text": "Output :"
},
{
"code": null,
"e": 28497,
"s": 27775,
"text": "\nin_array : [ 1. 1.12597604 1.25195208 1.37792812 1.50390415 1.62988019\n 1.75585623 1.88183227 2.00780831 2.13378435 2.25976038 2.38573642\n 2.51171246 2.6376885 2.76366454 2.88964058 3.01561662 3.14159265]\n\nout_array with cos : [ 0.54030231 0.43029566 0.31346927 0.19167471 0.0668423 -0.0590495\n -0.18400541 -0.30604504 -0.42323415 -0.53371544 -0.63573787 -0.72768451\n -0.80809809 -0.87570413 -0.92943115 -0.96842762 -0.99207551 -1. ]\n\nout_array with arccosh : [ 0. 0.49682282 0.69574433 0.84411504 0.96590748 1.07053332\n 1.16287802 1.24587516 1.32145434 1.39096696 1.45540398 1.51551804\n 1.57189678 1.62500948 1.67523791 1.7228975 1.76825238 1.81152627]"
},
{
"code": null,
"e": 28499,
"s": 28497,
"text": ")"
},
{
"code": null,
"e": 28534,
"s": 28499,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 28547,
"s": 28534,
"text": "Python-numpy"
},
{
"code": null,
"e": 28554,
"s": 28547,
"text": "Python"
},
{
"code": null,
"e": 28652,
"s": 28554,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28684,
"s": 28652,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28726,
"s": 28684,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28768,
"s": 28726,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28824,
"s": 28768,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28851,
"s": 28824,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28882,
"s": 28851,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28911,
"s": 28882,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28933,
"s": 28911,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28972,
"s": 28933,
"text": "Python | Get unique values from a list"
}
]
|
Program to find the diameter, cycles and edges of a Wheel Graph in C++ | In this problem, we are given a number that denotes the number of vertices of a Wheel Graph. Our task is to create a Program to find the diameter,
cycles and edges of a Wheel Graph in C++.
Problem description − Here, we need to find the number of cycles, number of edges, and the diameter of Wheel Graph with n vertices.
First, let’s understand some basics about Wheel Graph −
A wheel graph is obtained from a cycle graph Cn-1 by adding a new vertex. That new vertex is called a Hub which is connected to all the vertices of Cn.
Example of a wheel graph with 7 vertices.
Diameter of wheel Graph is the number of edges that we need to cover to go from anyone vertices to others. For the above Wheel Graph, the diameter
is 2
No. of Cycle of Wheel Graph is the total number of closed cycles that can be the given graph. For the above Wheel Graph, the no. of cycles is 31.
No. of Edge of Wheel Graph is the count of edges that connect all the vertices. For the above Wheel Graph, no of edges is 12.
To solve the problem, we will be using the direct formula that is given in the
graph theory to find the required values for a wheel graph.
The Formulas are,
Diameter of a Wheel Graph =
1, if vertices = 4, else 2.
No. of cycles of a Wheel Graph =
(No. of vertices )^2 - (3 * (No. of vertices -1) )
No. of edges of a wheel Graph =
2 * (No. of vertices - 1)
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
#include <math.h>
using namespace std;
void calcValuesWheelGraph(int V){
// Calculating the Diameter
if(V == 4){
cout<<"The Diameter of the Wheel Graph is 1 "<<endl;
}
else {
cout<<"The Diameter of the Wheel Graph is 2 "<<endl;
}
// Calculating the no. of cycles
cout<<"The number of cycles of the Wheel Graph is "<<(pow(V, 2) - (3 * (V-1)))<<endl;
// Calculating the no. of Edges
cout<<"The number of Edges of the Wheel Graph is "<<(2 * (V-1))<<endl;
}
int main(){
int V = 9;
calcValuesWheelGraph(V);
return 0;
}
The Diameter of the Wheel Graph is 2
The number of cycles of the Wheel Graph is 57
The number of Edges of the Wheel Graph is 16 | [
{
"code": null,
"e": 1251,
"s": 1062,
"text": "In this problem, we are given a number that denotes the number of vertices of a Wheel Graph. Our task is to create a Program to find the diameter,\ncycles and edges of a Wheel Graph in C++."
},
{
"code": null,
"e": 1383,
"s": 1251,
"text": "Problem description − Here, we need to find the number of cycles, number of edges, and the diameter of Wheel Graph with n vertices."
},
{
"code": null,
"e": 1439,
"s": 1383,
"text": "First, let’s understand some basics about Wheel Graph −"
},
{
"code": null,
"e": 1591,
"s": 1439,
"text": "A wheel graph is obtained from a cycle graph Cn-1 by adding a new vertex. That new vertex is called a Hub which is connected to all the vertices of Cn."
},
{
"code": null,
"e": 1633,
"s": 1591,
"text": "Example of a wheel graph with 7 vertices."
},
{
"code": null,
"e": 1785,
"s": 1633,
"text": "Diameter of wheel Graph is the number of edges that we need to cover to go from anyone vertices to others. For the above Wheel Graph, the diameter\nis 2"
},
{
"code": null,
"e": 1931,
"s": 1785,
"text": "No. of Cycle of Wheel Graph is the total number of closed cycles that can be the given graph. For the above Wheel Graph, the no. of cycles is 31."
},
{
"code": null,
"e": 2057,
"s": 1931,
"text": "No. of Edge of Wheel Graph is the count of edges that connect all the vertices. For the above Wheel Graph, no of edges is 12."
},
{
"code": null,
"e": 2196,
"s": 2057,
"text": "To solve the problem, we will be using the direct formula that is given in the\ngraph theory to find the required values for a wheel graph."
},
{
"code": null,
"e": 2214,
"s": 2196,
"text": "The Formulas are,"
},
{
"code": null,
"e": 2242,
"s": 2214,
"text": "Diameter of a Wheel Graph ="
},
{
"code": null,
"e": 2270,
"s": 2242,
"text": "1, if vertices = 4, else 2."
},
{
"code": null,
"e": 2303,
"s": 2270,
"text": "No. of cycles of a Wheel Graph ="
},
{
"code": null,
"e": 2354,
"s": 2303,
"text": "(No. of vertices )^2 - (3 * (No. of vertices -1) )"
},
{
"code": null,
"e": 2386,
"s": 2354,
"text": "No. of edges of a wheel Graph ="
},
{
"code": null,
"e": 2412,
"s": 2386,
"text": "2 * (No. of vertices - 1)"
},
{
"code": null,
"e": 2463,
"s": 2412,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 2474,
"s": 2463,
"text": " Live Demo"
},
{
"code": null,
"e": 3056,
"s": 2474,
"text": "#include <iostream>\n#include <math.h>\nusing namespace std;\nvoid calcValuesWheelGraph(int V){\n // Calculating the Diameter\n if(V == 4){\n cout<<\"The Diameter of the Wheel Graph is 1 \"<<endl;\n }\n else {\n cout<<\"The Diameter of the Wheel Graph is 2 \"<<endl;\n }\n // Calculating the no. of cycles\n cout<<\"The number of cycles of the Wheel Graph is \"<<(pow(V, 2) - (3 * (V-1)))<<endl;\n // Calculating the no. of Edges\n cout<<\"The number of Edges of the Wheel Graph is \"<<(2 * (V-1))<<endl;\n}\nint main(){\n int V = 9;\n calcValuesWheelGraph(V);\n return 0;\n}"
},
{
"code": null,
"e": 3184,
"s": 3056,
"text": "The Diameter of the Wheel Graph is 2\nThe number of cycles of the Wheel Graph is 57\nThe number of Edges of the Wheel Graph is 16"
}
]
|
Pytorch vs Tensorflow in 2020. How the two popular frameworks have... | by Moiz Saifee | Towards Data Science | Pytorch and Tensorflow are by far two of the most popular frameworks for Deep Learning. It’s always a lot of work to learn and be comfortable with a new framework, so a lot of people face the dilemma of which one to choose out of the two
The two frameworks had a lot of major differences in terms of design, paradigm, syntax etc till some time back, but they have since evolved a lot, both have picked up good features from each other and are no longer that different.
A lot of online articles comparing the two are a little old, and do not appropriately capture the present scenario. In fact Soumith Chintala, one of the original authors of PyTorch, also recently tweeted about how the two frameworks are pretty similar now.
Tensorflow is from Google and was released in 2015, and PyTorch was released by Facebook in 2017.
Tensorflow arrived earlier at the scene, so it had a head start in terms of number of users, adoption etc but Pytorch has bridged the gap significantly over the years
Both work on fundamental data type called Tensors which are nothing but multi-dimensional arrays, amenable to high performance computation. Both represent computation as a directed acyclic graph often called Computation Graph.
Let’s look into some of the important aspect about these frameworks, the major differences in the beginning and where things stand as of today.
Programming API
The Tensorflow API was very cryptic to start with, it almost felt like learning a new programming language, on top of it, it was also very hard to debug due to its static computation graph approach (more on that below). Pytorch (python) API on the other hand is very Pythonic from the start and felt just like writing native Python code and very easy to debug.
Tensorflow did a major cleanup of its API with Tensorflow 2.0, and integrated the high level programming API Keras in the main API itself. A combination of these two significantly reduced the cognitive load which one had to undergo while writing Tensorflow code in the past :-)
The programming APIs (of TensorFlow and PyTorch) in fact look very similar now, so much that the two are indistinguishable a number of times (see example towards the end)
Computation graph was a major design difference between the two frameworks to start with.
Tensorflow adopted a static Computation Graph approach where one defines the sequence of computation that one wants to do, with placeholder for the data. After that for training / running the model you feed in the data. Static computation graph is great for performance and ability to run on different devices (cpu / gpu / tpu), but is a major pain to debug.
Pytorch on the other hand adopted a dynamic computation graph approach, where computations are done line by line as the code is interpreted. This makes it a lot easier to debug the code, and also offers other benefits — example supporting variable length inputs in models like RNN.
Fast forward to today, Tensorflow introduced the facility to build dynamic computation graph through its “Eager” mode, and PyTorch allows building of static computational graph, so you kind of have both static/dynamic modes in both the frameworks now.
Both the frameworks provided the facility to run on single / multiple / distributed CPUs or GPUs. In earlier days it used to be a pain to get Tensorflow to work on multiple GPUs as one had to manually code and fine tune performance across multiple devices, things have changed since then and now its almost effortless to do distributed computing with both the frameworks.
Google made its custom hardware accelerator Tensor Processing Unit (TPU) which can run computation at blazing speed, even a lot faster than GPU, available for 3rd party use in 2018. Since Tensorflow and TPU are both from Google, its far easier to run code on TPUs using Tensorflow as opposed to PyTorch, as PyTorch has a bit of patchy way of working on TPUs using third party libraries like XLA
Deployment is something where Tensorflow had a lot of advantage over PyTorch, in part due to better performance due to its Static Computation graph approach, but also due to packages / tools that facilitated quick deployment over cloud, browser or mobile. That’s the reason a lot of companies preferred Tensorflow when it came to production.
PyTorch has tried to bridge this gap in version 1.5+ with TorchServe, but its yet to mature
Its amusing that for a lot of things the APIs are so similar that the codes are almost indistinguishable. Given below are code snippets for the core components on MNIST Digit Recognition (proverbial “Hello World” problem in Computer Vision) for both Tensorflow and Pytorch, try to guess which one is which
The complete Tensorflow and Pytorch code is available at my Github Repo
Data Loader
# Download the MNIST Data(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0# Add a channels dimensionx_train = x_train[..., tf.newaxis]x_test = x_test[..., tf.newaxis]train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32)test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
Which one is PyTorch code - above or below?
# Download the MNIST Data and create dataloadertransform = transforms.Compose([transforms.ToTensor()])xy_train = datasets.MNIST('./', download=True, train=True, transform=transform)xy_test = datasets.MNIST('./', download=True, train=False, transform=transform)train_ds = DataLoader(xy_train, batch_size=32, shuffle=True)test_ds = DataLoader(xy_test, batch_size=32, shuffle=True)
Okay the method to load the data looks a bit different, but I promise it gets similar from here on :-)
Model Definition
# Model Definitionclass MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.conv1 = Conv2d(in_channels=1, out_channels=32, kernel_size=3) self.flatten = Flatten() self.d1 = Linear(21632, 128) self.d2 = Linear(128, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = self.flatten(x) x = F.relu(self.d1(x)) x = self.d2(x) output = F.log_softmax(x, dim=1) return output
Which one is PyTorch code - above or below?
# Model Definitionclass MyModel(Model): def __init__(self): super(MyModel, self).__init__() self.conv1 = Conv2D(filters=32, kernel_size=3, activation='relu') self.flatten = Flatten() self.d1 = Dense(128, activation='relu') self.d2 = Dense(10) def call(self, x): x = self.conv1(x) x = self.flatten(x) x = self.d1(x) output = self.d2(x) return output
Instantiate Model, Loss, Optimizer
# Instantiate Model, Optimizer, Lossmodel = MyModel()optimizer = Adam()loss_object = SparseCategoricalCrossentropy(from_logits=True, reduction='sum')
Which one is PyTorch code - above or below?
# Instantiate Model, Optimizer, Lossmodel = MyModel()optimizer = Adam(model.parameters())loss_object = CrossEntropyLoss(reduction='sum')
Training Loop
for epoch in range(2): # Reset the metrics at the start of the next epoch train_loss = 0 train_n = 0 for images, labels in train_ds: with GradientTape() as tape: # training=True is only needed if there are layers with different # behavior during training versus inference (e.g. Dropout). predictions = model(images, training=True) loss = loss_object(labels, predictions) train_loss += loss.numpy() train_n += labels.shape[0] gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) train_loss /= train_n
Which one is PyTorch code - above or below?
for epoch in range(2): # Train model.train() train_loss = 0 train_n = 0 for image, labels in train_ds: predictions = model(image).squeeze() loss = loss_object(predictions, labels) train_loss += loss.item() train_n += labels.shape[0] loss.backward() optimizer.step() optimizer.zero_grad() train_loss /= train_n
It’s really interesting (and convenient!) how similar the APIs seem to be now.
Tensorflow and PyTorch are two excellent frameworks for research and development of deep learning applications. They do the heavy lifting in terms of computation, managing the underlying hardware and have huge communities which makes it a lot easier to develop custom application by standing on the shoulder of giants.
There were some major differences in the two frameworks till a while back, both have since adopted good features from each other and have both become better in the process. There are still things which are slightly easier in one compared to another, but its now also easier than ever to switch back and forth between the two due to increased similarity. | [
{
"code": null,
"e": 410,
"s": 172,
"text": "Pytorch and Tensorflow are by far two of the most popular frameworks for Deep Learning. It’s always a lot of work to learn and be comfortable with a new framework, so a lot of people face the dilemma of which one to choose out of the two"
},
{
"code": null,
"e": 641,
"s": 410,
"text": "The two frameworks had a lot of major differences in terms of design, paradigm, syntax etc till some time back, but they have since evolved a lot, both have picked up good features from each other and are no longer that different."
},
{
"code": null,
"e": 898,
"s": 641,
"text": "A lot of online articles comparing the two are a little old, and do not appropriately capture the present scenario. In fact Soumith Chintala, one of the original authors of PyTorch, also recently tweeted about how the two frameworks are pretty similar now."
},
{
"code": null,
"e": 996,
"s": 898,
"text": "Tensorflow is from Google and was released in 2015, and PyTorch was released by Facebook in 2017."
},
{
"code": null,
"e": 1163,
"s": 996,
"text": "Tensorflow arrived earlier at the scene, so it had a head start in terms of number of users, adoption etc but Pytorch has bridged the gap significantly over the years"
},
{
"code": null,
"e": 1390,
"s": 1163,
"text": "Both work on fundamental data type called Tensors which are nothing but multi-dimensional arrays, amenable to high performance computation. Both represent computation as a directed acyclic graph often called Computation Graph."
},
{
"code": null,
"e": 1534,
"s": 1390,
"text": "Let’s look into some of the important aspect about these frameworks, the major differences in the beginning and where things stand as of today."
},
{
"code": null,
"e": 1550,
"s": 1534,
"text": "Programming API"
},
{
"code": null,
"e": 1911,
"s": 1550,
"text": "The Tensorflow API was very cryptic to start with, it almost felt like learning a new programming language, on top of it, it was also very hard to debug due to its static computation graph approach (more on that below). Pytorch (python) API on the other hand is very Pythonic from the start and felt just like writing native Python code and very easy to debug."
},
{
"code": null,
"e": 2189,
"s": 1911,
"text": "Tensorflow did a major cleanup of its API with Tensorflow 2.0, and integrated the high level programming API Keras in the main API itself. A combination of these two significantly reduced the cognitive load which one had to undergo while writing Tensorflow code in the past :-)"
},
{
"code": null,
"e": 2360,
"s": 2189,
"text": "The programming APIs (of TensorFlow and PyTorch) in fact look very similar now, so much that the two are indistinguishable a number of times (see example towards the end)"
},
{
"code": null,
"e": 2450,
"s": 2360,
"text": "Computation graph was a major design difference between the two frameworks to start with."
},
{
"code": null,
"e": 2809,
"s": 2450,
"text": "Tensorflow adopted a static Computation Graph approach where one defines the sequence of computation that one wants to do, with placeholder for the data. After that for training / running the model you feed in the data. Static computation graph is great for performance and ability to run on different devices (cpu / gpu / tpu), but is a major pain to debug."
},
{
"code": null,
"e": 3091,
"s": 2809,
"text": "Pytorch on the other hand adopted a dynamic computation graph approach, where computations are done line by line as the code is interpreted. This makes it a lot easier to debug the code, and also offers other benefits — example supporting variable length inputs in models like RNN."
},
{
"code": null,
"e": 3343,
"s": 3091,
"text": "Fast forward to today, Tensorflow introduced the facility to build dynamic computation graph through its “Eager” mode, and PyTorch allows building of static computational graph, so you kind of have both static/dynamic modes in both the frameworks now."
},
{
"code": null,
"e": 3715,
"s": 3343,
"text": "Both the frameworks provided the facility to run on single / multiple / distributed CPUs or GPUs. In earlier days it used to be a pain to get Tensorflow to work on multiple GPUs as one had to manually code and fine tune performance across multiple devices, things have changed since then and now its almost effortless to do distributed computing with both the frameworks."
},
{
"code": null,
"e": 4110,
"s": 3715,
"text": "Google made its custom hardware accelerator Tensor Processing Unit (TPU) which can run computation at blazing speed, even a lot faster than GPU, available for 3rd party use in 2018. Since Tensorflow and TPU are both from Google, its far easier to run code on TPUs using Tensorflow as opposed to PyTorch, as PyTorch has a bit of patchy way of working on TPUs using third party libraries like XLA"
},
{
"code": null,
"e": 4452,
"s": 4110,
"text": "Deployment is something where Tensorflow had a lot of advantage over PyTorch, in part due to better performance due to its Static Computation graph approach, but also due to packages / tools that facilitated quick deployment over cloud, browser or mobile. That’s the reason a lot of companies preferred Tensorflow when it came to production."
},
{
"code": null,
"e": 4544,
"s": 4452,
"text": "PyTorch has tried to bridge this gap in version 1.5+ with TorchServe, but its yet to mature"
},
{
"code": null,
"e": 4850,
"s": 4544,
"text": "Its amusing that for a lot of things the APIs are so similar that the codes are almost indistinguishable. Given below are code snippets for the core components on MNIST Digit Recognition (proverbial “Hello World” problem in Computer Vision) for both Tensorflow and Pytorch, try to guess which one is which"
},
{
"code": null,
"e": 4922,
"s": 4850,
"text": "The complete Tensorflow and Pytorch code is available at my Github Repo"
},
{
"code": null,
"e": 4934,
"s": 4922,
"text": "Data Loader"
},
{
"code": null,
"e": 5319,
"s": 4934,
"text": "# Download the MNIST Data(x_train, y_train), (x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0# Add a channels dimensionx_train = x_train[..., tf.newaxis]x_test = x_test[..., tf.newaxis]train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32)test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)"
},
{
"code": null,
"e": 5363,
"s": 5319,
"text": "Which one is PyTorch code - above or below?"
},
{
"code": null,
"e": 5742,
"s": 5363,
"text": "# Download the MNIST Data and create dataloadertransform = transforms.Compose([transforms.ToTensor()])xy_train = datasets.MNIST('./', download=True, train=True, transform=transform)xy_test = datasets.MNIST('./', download=True, train=False, transform=transform)train_ds = DataLoader(xy_train, batch_size=32, shuffle=True)test_ds = DataLoader(xy_test, batch_size=32, shuffle=True)"
},
{
"code": null,
"e": 5845,
"s": 5742,
"text": "Okay the method to load the data looks a bit different, but I promise it gets similar from here on :-)"
},
{
"code": null,
"e": 5862,
"s": 5845,
"text": "Model Definition"
},
{
"code": null,
"e": 6341,
"s": 5862,
"text": "# Model Definitionclass MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.conv1 = Conv2d(in_channels=1, out_channels=32, kernel_size=3) self.flatten = Flatten() self.d1 = Linear(21632, 128) self.d2 = Linear(128, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = self.flatten(x) x = F.relu(self.d1(x)) x = self.d2(x) output = F.log_softmax(x, dim=1) return output"
},
{
"code": null,
"e": 6385,
"s": 6341,
"text": "Which one is PyTorch code - above or below?"
},
{
"code": null,
"e": 6810,
"s": 6385,
"text": "# Model Definitionclass MyModel(Model): def __init__(self): super(MyModel, self).__init__() self.conv1 = Conv2D(filters=32, kernel_size=3, activation='relu') self.flatten = Flatten() self.d1 = Dense(128, activation='relu') self.d2 = Dense(10) def call(self, x): x = self.conv1(x) x = self.flatten(x) x = self.d1(x) output = self.d2(x) return output"
},
{
"code": null,
"e": 6845,
"s": 6810,
"text": "Instantiate Model, Loss, Optimizer"
},
{
"code": null,
"e": 6995,
"s": 6845,
"text": "# Instantiate Model, Optimizer, Lossmodel = MyModel()optimizer = Adam()loss_object = SparseCategoricalCrossentropy(from_logits=True, reduction='sum')"
},
{
"code": null,
"e": 7039,
"s": 6995,
"text": "Which one is PyTorch code - above or below?"
},
{
"code": null,
"e": 7176,
"s": 7039,
"text": "# Instantiate Model, Optimizer, Lossmodel = MyModel()optimizer = Adam(model.parameters())loss_object = CrossEntropyLoss(reduction='sum')"
},
{
"code": null,
"e": 7190,
"s": 7176,
"text": "Training Loop"
},
{
"code": null,
"e": 7867,
"s": 7190,
"text": "for epoch in range(2): # Reset the metrics at the start of the next epoch train_loss = 0 train_n = 0 for images, labels in train_ds: with GradientTape() as tape: # training=True is only needed if there are layers with different # behavior during training versus inference (e.g. Dropout). predictions = model(images, training=True) loss = loss_object(labels, predictions) train_loss += loss.numpy() train_n += labels.shape[0] gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) train_loss /= train_n"
},
{
"code": null,
"e": 7911,
"s": 7867,
"text": "Which one is PyTorch code - above or below?"
},
{
"code": null,
"e": 8288,
"s": 7911,
"text": "for epoch in range(2): # Train model.train() train_loss = 0 train_n = 0 for image, labels in train_ds: predictions = model(image).squeeze() loss = loss_object(predictions, labels) train_loss += loss.item() train_n += labels.shape[0] loss.backward() optimizer.step() optimizer.zero_grad() train_loss /= train_n"
},
{
"code": null,
"e": 8367,
"s": 8288,
"text": "It’s really interesting (and convenient!) how similar the APIs seem to be now."
},
{
"code": null,
"e": 8686,
"s": 8367,
"text": "Tensorflow and PyTorch are two excellent frameworks for research and development of deep learning applications. They do the heavy lifting in terms of computation, managing the underlying hardware and have huge communities which makes it a lot easier to develop custom application by standing on the shoulder of giants."
}
]
|
Ruby | String Basics - GeeksforGeeks | 30 Jul, 2018
In Ruby, string is a sequence of one or more characters. It may consist of numbers, letters, or symbols. Here strings are the objects, and apart from other languages, strings are mutable, i.e. strings can be changed in place instead of creating new strings. String’s object holds and manipulates an arbitrary sequence of the bytes that commonly represents a sequence of characters.
Creating Strings: To create the string, just put the sequence of characters either in double quotes or single quotes. Also, the user can store the string into some variable. In Ruby, there is no need to specify the data type of the variable.
Example:
# Ruby program to demonstrate # the creation of strings # using single quotesputs 'Ruby String using single quotes' # using double quotesputs "Ruby String using double quotes" # storing string into variablesstr1 = "GFG"str2 = 'Geeks' # displaying stringputs str1puts str2
Output:
Ruby String using single quotes
Ruby String using double quotes
GFG
Geeks
Note: The only difference between using single and double quotes is that the double quotes will interpolates the variables but single quotes can’t interpolate.
Example:
# Ruby program to demonstrate the difference# while using single and double quotes to # create strings # storing string into variablesstr1 = "GFG"str2 = 'Geeks' # using single quotesputs 'Cannot Interpolate str1: #{str1}' # using double quotesputs "Interpolating str2: #{str2}"
Output:
Cannot Interpolate str1: #{str1}
Interpolating str2: Geeks
Strings are objects: As you know that Ruby is an object-oriented language so string in Ruby are objects. Basically, an object is a combination of the data and methods which enhance the communication property.
Example:
# Ruby program to illustrate that # string are objects in Ruby #!/usr/bin/ruby # using double quotesstr = "GeeksforGeeks" puts str # using new method to create string# object and assigning value to itstr2 = String.new "GeeksforGeeks" puts str2
Output:
GeeksforGeeks
GeeksforGeeks
Access String Elements: User can access the string elements by using the square brackets []. In square brackets [], the user can pass the strings, ranges or indexes.
Syntax:
name_of_string_variable[arguments]
Example:
# Ruby program to illustrate the# accessing of string #!/usr/bin/ruby # storing string in variablestr = "GeeksforGeeks Sudo Placements" # accessing the specified substringputs str["Geeks"]puts str['for'] # passing index as an argument which returns # the specified character puts str[3] # passing the negative index as an argument which # returns the specified character from the# last of the string puts str[-3] # passing Two arguments which are separated # by a comma that returns characters starting# from the 1st index and the 2nd index is the# number of charactersputs str[14, 10] # using range operators in passed argumentsputs str[14 .. 17]
Output:
Geeks
for
k
n
Sudo Place
Sudo
Creating Multiline Strings: In Ruby, a user can create the multiline strings easily whereas in other programming languages creating multiline strings requires a lot of efforts. There are three ways to create multiline strings in Ruby as follows:
Using Double Quotes(“”) It is the simplest way to create the multiline strings by just putting the string between the quotes. Between double quotes, the user can add the newline character and so on.Using (%/ /) To create the multiline string just put the string between the %/ and /.Using (<< STRING STRING) To create the multiline string just put the string between the << STRING and STRING. Here STRING should be in capital letters.
Using Double Quotes(“”) It is the simplest way to create the multiline strings by just putting the string between the quotes. Between double quotes, the user can add the newline character and so on.
Using (%/ /) To create the multiline string just put the string between the %/ and /.
Using (<< STRING STRING) To create the multiline string just put the string between the << STRING and STRING. Here STRING should be in capital letters.
Example:
# Ruby program to illustrate the# multiline strings #!/usr/bin/ruby # Using Double Quotesputs "In Ruby, a user can create the multiline strings easily where in other programming languages creating multiline strings requires a lot of efforts" puts "" # Using %/ /puts %/ In Ruby, a user can create the multiline strings easily where into other programming languages creating multiline strings requires a lot of efforts/ puts "" # Using <<STRING STRINGputs <<STRING In Ruby, a user can create the multilinestrings easily where into other programming languages creating multiline strings requires a lot of efforts STRING
Output:
In Ruby, a user can create the multiline
strings easily where in other programming
languages creating multiline strings
requires a lot of efforts
In Ruby, a user can create the multiline
strings easily where into other programming
languages creating multiline strings
requires a lot of efforts
In Ruby, a user can create the multiline
strings easily where into other programming
languages creating multiline strings
requires a lot of efforts
String Replication: Sometimes a user may require to repeat some sort of string multiple times. So to make the replication of string in Ruby, make the use of (*) operator. This operator is preceded by the string to be replicated and followed by the number of times to make replicas.
Syntax:
string_variable_or_string * number_of_times
Example:
# Ruby program to illustrate the# replication of strings #!/usr/bin/ruby # string to be replicatestr = "GeeksForGeeks\n" # using * operatorputs str * 7
Output:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
Ruby-Basics
Ruby-String
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Enumerator each_with_index function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby For Beginners
Ruby | Types of Iterators
Ruby on Rails Introduction
Ruby | Array shift() function
Ruby | Class Method and Variables
Ruby | Enumerable find() function
Ruby | pop() function
Ruby | String concat Method | [
{
"code": null,
"e": 24011,
"s": 23983,
"text": "\n30 Jul, 2018"
},
{
"code": null,
"e": 24393,
"s": 24011,
"text": "In Ruby, string is a sequence of one or more characters. It may consist of numbers, letters, or symbols. Here strings are the objects, and apart from other languages, strings are mutable, i.e. strings can be changed in place instead of creating new strings. String’s object holds and manipulates an arbitrary sequence of the bytes that commonly represents a sequence of characters."
},
{
"code": null,
"e": 24635,
"s": 24393,
"text": "Creating Strings: To create the string, just put the sequence of characters either in double quotes or single quotes. Also, the user can store the string into some variable. In Ruby, there is no need to specify the data type of the variable."
},
{
"code": null,
"e": 24644,
"s": 24635,
"text": "Example:"
},
{
"code": "# Ruby program to demonstrate # the creation of strings # using single quotesputs 'Ruby String using single quotes' # using double quotesputs \"Ruby String using double quotes\" # storing string into variablesstr1 = \"GFG\"str2 = 'Geeks' # displaying stringputs str1puts str2",
"e": 24920,
"s": 24644,
"text": null
},
{
"code": null,
"e": 24928,
"s": 24920,
"text": "Output:"
},
{
"code": null,
"e": 25003,
"s": 24928,
"text": "Ruby String using single quotes\nRuby String using double quotes\nGFG\nGeeks\n"
},
{
"code": null,
"e": 25163,
"s": 25003,
"text": "Note: The only difference between using single and double quotes is that the double quotes will interpolates the variables but single quotes can’t interpolate."
},
{
"code": null,
"e": 25172,
"s": 25163,
"text": "Example:"
},
{
"code": "# Ruby program to demonstrate the difference# while using single and double quotes to # create strings # storing string into variablesstr1 = \"GFG\"str2 = 'Geeks' # using single quotesputs 'Cannot Interpolate str1: #{str1}' # using double quotesputs \"Interpolating str2: #{str2}\"",
"e": 25453,
"s": 25172,
"text": null
},
{
"code": null,
"e": 25461,
"s": 25453,
"text": "Output:"
},
{
"code": null,
"e": 25521,
"s": 25461,
"text": "Cannot Interpolate str1: #{str1}\nInterpolating str2: Geeks\n"
},
{
"code": null,
"e": 25730,
"s": 25521,
"text": "Strings are objects: As you know that Ruby is an object-oriented language so string in Ruby are objects. Basically, an object is a combination of the data and methods which enhance the communication property."
},
{
"code": null,
"e": 25739,
"s": 25730,
"text": "Example:"
},
{
"code": "# Ruby program to illustrate that # string are objects in Ruby #!/usr/bin/ruby # using double quotesstr = \"GeeksforGeeks\" puts str # using new method to create string# object and assigning value to itstr2 = String.new \"GeeksforGeeks\" puts str2",
"e": 25988,
"s": 25739,
"text": null
},
{
"code": null,
"e": 25996,
"s": 25988,
"text": "Output:"
},
{
"code": null,
"e": 26025,
"s": 25996,
"text": "GeeksforGeeks\nGeeksforGeeks\n"
},
{
"code": null,
"e": 26191,
"s": 26025,
"text": "Access String Elements: User can access the string elements by using the square brackets []. In square brackets [], the user can pass the strings, ranges or indexes."
},
{
"code": null,
"e": 26199,
"s": 26191,
"text": "Syntax:"
},
{
"code": null,
"e": 26234,
"s": 26199,
"text": "name_of_string_variable[arguments]"
},
{
"code": null,
"e": 26243,
"s": 26234,
"text": "Example:"
},
{
"code": "# Ruby program to illustrate the# accessing of string #!/usr/bin/ruby # storing string in variablestr = \"GeeksforGeeks Sudo Placements\" # accessing the specified substringputs str[\"Geeks\"]puts str['for'] # passing index as an argument which returns # the specified character puts str[3] # passing the negative index as an argument which # returns the specified character from the# last of the string puts str[-3] # passing Two arguments which are separated # by a comma that returns characters starting# from the 1st index and the 2nd index is the# number of charactersputs str[14, 10] # using range operators in passed argumentsputs str[14 .. 17]",
"e": 26899,
"s": 26243,
"text": null
},
{
"code": null,
"e": 26907,
"s": 26899,
"text": "Output:"
},
{
"code": null,
"e": 26938,
"s": 26907,
"text": "Geeks\nfor\nk\nn\nSudo Place\nSudo\n"
},
{
"code": null,
"e": 27184,
"s": 26938,
"text": "Creating Multiline Strings: In Ruby, a user can create the multiline strings easily whereas in other programming languages creating multiline strings requires a lot of efforts. There are three ways to create multiline strings in Ruby as follows:"
},
{
"code": null,
"e": 27619,
"s": 27184,
"text": "Using Double Quotes(“”) It is the simplest way to create the multiline strings by just putting the string between the quotes. Between double quotes, the user can add the newline character and so on.Using (%/ /) To create the multiline string just put the string between the %/ and /.Using (<< STRING STRING) To create the multiline string just put the string between the << STRING and STRING. Here STRING should be in capital letters."
},
{
"code": null,
"e": 27818,
"s": 27619,
"text": "Using Double Quotes(“”) It is the simplest way to create the multiline strings by just putting the string between the quotes. Between double quotes, the user can add the newline character and so on."
},
{
"code": null,
"e": 27904,
"s": 27818,
"text": "Using (%/ /) To create the multiline string just put the string between the %/ and /."
},
{
"code": null,
"e": 28056,
"s": 27904,
"text": "Using (<< STRING STRING) To create the multiline string just put the string between the << STRING and STRING. Here STRING should be in capital letters."
},
{
"code": null,
"e": 28065,
"s": 28056,
"text": "Example:"
},
{
"code": "# Ruby program to illustrate the# multiline strings #!/usr/bin/ruby # Using Double Quotesputs \"In Ruby, a user can create the multiline strings easily where in other programming languages creating multiline strings requires a lot of efforts\" puts \"\" # Using %/ /puts %/ In Ruby, a user can create the multiline strings easily where into other programming languages creating multiline strings requires a lot of efforts/ puts \"\" # Using <<STRING STRINGputs <<STRING In Ruby, a user can create the multilinestrings easily where into other programming languages creating multiline strings requires a lot of efforts STRING",
"e": 28748,
"s": 28065,
"text": null
},
{
"code": null,
"e": 28756,
"s": 28748,
"text": "Output:"
},
{
"code": null,
"e": 29246,
"s": 28756,
"text": "In Ruby, a user can create the multiline\n strings easily where in other programming \n languages creating multiline strings \n requires a lot of efforts\n\n In Ruby, a user can create the multiline\n strings easily where into other programming \n languages creating multiline strings \n requires a lot of efforts\n\n\nIn Ruby, a user can create the multiline\nstrings easily where into other programming \nlanguages creating multiline strings \nrequires a lot of efforts \n"
},
{
"code": null,
"e": 29528,
"s": 29246,
"text": "String Replication: Sometimes a user may require to repeat some sort of string multiple times. So to make the replication of string in Ruby, make the use of (*) operator. This operator is preceded by the string to be replicated and followed by the number of times to make replicas."
},
{
"code": null,
"e": 29536,
"s": 29528,
"text": "Syntax:"
},
{
"code": null,
"e": 29580,
"s": 29536,
"text": "string_variable_or_string * number_of_times"
},
{
"code": null,
"e": 29589,
"s": 29580,
"text": "Example:"
},
{
"code": "# Ruby program to illustrate the# replication of strings #!/usr/bin/ruby # string to be replicatestr = \"GeeksForGeeks\\n\" # using * operatorputs str * 7",
"e": 29744,
"s": 29589,
"text": null
},
{
"code": null,
"e": 29752,
"s": 29744,
"text": "Output:"
},
{
"code": null,
"e": 29851,
"s": 29752,
"text": "GeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\n"
},
{
"code": null,
"e": 29863,
"s": 29851,
"text": "Ruby-Basics"
},
{
"code": null,
"e": 29875,
"s": 29863,
"text": "Ruby-String"
},
{
"code": null,
"e": 29880,
"s": 29875,
"text": "Ruby"
},
{
"code": null,
"e": 29978,
"s": 29880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30021,
"s": 29978,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 30089,
"s": 30021,
"text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1"
},
{
"code": null,
"e": 30108,
"s": 30089,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 30134,
"s": 30108,
"text": "Ruby | Types of Iterators"
},
{
"code": null,
"e": 30161,
"s": 30134,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 30191,
"s": 30161,
"text": "Ruby | Array shift() function"
},
{
"code": null,
"e": 30225,
"s": 30191,
"text": "Ruby | Class Method and Variables"
},
{
"code": null,
"e": 30259,
"s": 30225,
"text": "Ruby | Enumerable find() function"
},
{
"code": null,
"e": 30281,
"s": 30259,
"text": "Ruby | pop() function"
}
]
|
jQuery | delegate() Method - GeeksforGeeks | 19 Feb, 2019
The delegate() Method in jQuery is used to add one or more event handlers to the specified element that are children of selected elements and are also used to specify a function to run whenever the event occurs.
Syntax
$(selector).delegate( childSelector, event, data, function )
Parameter: This method accepts four parameters as mentioned above and described below:
childSelector: It is required parameter and used to specify one or more child elements attached to the event handler.
event: It is required parameter and used to specify one or more events attached to the elements. Multiple event values are separated by space and it must be a valid event.
data: It is an optional parameter and used to specify the additional data to pass along the function.
function: It is required parameter and used to specify the function to run when the event occurs.
Example 1:
<!DOCTYPE html> <html> <head> <title> delegate() Method in jQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery script to add events --> <script> $(document).ready(function() { $("div").delegate("h3", "click", function() { $("h3").css("background-color", "green"); }); }); </script> </head> <body> <center> <h1>Welcome to GeeksforGeeks!</h1> <p> Click on the below element (lightgreen background) to change background-color </p> <div style="background-color:lightgreen;"> <h3>GeeksForGeeks</h3> </div> <h3>GeeksForGeeks.</h3> </center> </body> </html>
Output:Before Click on the element:After Click on the element:
Example 2:
<!DOCTYPE html> <html> <head> <title> delegate() Method in jQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery script for delegate() method --> <script> $(document).ready(function(){ $("div").delegate("h3", "click", function(){ $(this).slideToggle(); }); $("button").click(function(){ $("<h3>This show how the delegate Method" + " works .</h3>").insertAfter("button"); }); }); </script> </head> <body> <center> <h1>Welcome to GeeksforGeeks!.</h1> <div style="background-color:green"> <h3>GeeksforGeeks.</h3> <h3>The delegate Method.</h3> <button>Click</button> </div> </center> </body> </html>
Output:Before Click on the button:After Click on the button:
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 40723,
"s": 40695,
"text": "\n19 Feb, 2019"
},
{
"code": null,
"e": 40935,
"s": 40723,
"text": "The delegate() Method in jQuery is used to add one or more event handlers to the specified element that are children of selected elements and are also used to specify a function to run whenever the event occurs."
},
{
"code": null,
"e": 40942,
"s": 40935,
"text": "Syntax"
},
{
"code": null,
"e": 41003,
"s": 40942,
"text": "$(selector).delegate( childSelector, event, data, function )"
},
{
"code": null,
"e": 41090,
"s": 41003,
"text": "Parameter: This method accepts four parameters as mentioned above and described below:"
},
{
"code": null,
"e": 41208,
"s": 41090,
"text": "childSelector: It is required parameter and used to specify one or more child elements attached to the event handler."
},
{
"code": null,
"e": 41380,
"s": 41208,
"text": "event: It is required parameter and used to specify one or more events attached to the elements. Multiple event values are separated by space and it must be a valid event."
},
{
"code": null,
"e": 41482,
"s": 41380,
"text": "data: It is an optional parameter and used to specify the additional data to pass along the function."
},
{
"code": null,
"e": 41580,
"s": 41482,
"text": "function: It is required parameter and used to specify the function to run when the event occurs."
},
{
"code": null,
"e": 41591,
"s": 41580,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> delegate() Method in jQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery script to add events --> <script> $(document).ready(function() { $(\"div\").delegate(\"h3\", \"click\", function() { $(\"h3\").css(\"background-color\", \"green\"); }); }); </script> </head> <body> <center> <h1>Welcome to GeeksforGeeks!</h1> <p> Click on the below element (lightgreen background) to change background-color </p> <div style=\"background-color:lightgreen;\"> <h3>GeeksForGeeks</h3> </div> <h3>GeeksForGeeks.</h3> </center> </body> </html> ",
"e": 42539,
"s": 41591,
"text": null
},
{
"code": null,
"e": 42602,
"s": 42539,
"text": "Output:Before Click on the element:After Click on the element:"
},
{
"code": null,
"e": 42613,
"s": 42602,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> delegate() Method in jQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery script for delegate() method --> <script> $(document).ready(function(){ $(\"div\").delegate(\"h3\", \"click\", function(){ $(this).slideToggle(); }); $(\"button\").click(function(){ $(\"<h3>This show how the delegate Method\" + \" works .</h3>\").insertAfter(\"button\"); }); }); </script> </head> <body> <center> <h1>Welcome to GeeksforGeeks!.</h1> <div style=\"background-color:green\"> <h3>GeeksforGeeks.</h3> <h3>The delegate Method.</h3> <button>Click</button> </div> </center> </body> </html> ",
"e": 43662,
"s": 42613,
"text": null
},
{
"code": null,
"e": 43723,
"s": 43662,
"text": "Output:Before Click on the button:After Click on the button:"
},
{
"code": null,
"e": 43730,
"s": 43723,
"text": "Picked"
},
{
"code": null,
"e": 43737,
"s": 43730,
"text": "JQuery"
},
{
"code": null,
"e": 43754,
"s": 43737,
"text": "Web Technologies"
},
{
"code": null,
"e": 43852,
"s": 43754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43898,
"s": 43852,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 43961,
"s": 43898,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 43990,
"s": 43961,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 44067,
"s": 43990,
"text": "How to change the background color after clicking the button in JavaScript ?"
},
{
"code": null,
"e": 44123,
"s": 44067,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 44165,
"s": 44123,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 44198,
"s": 44165,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 44241,
"s": 44198,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 44303,
"s": 44241,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.