title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Java and multiple inheritance | Java does not support multiple inheritance. This means that a class cannot extend more than one class. Therefore, following is illegal
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritance. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. For example, if the Hockey interface extended both Sports and Event, it would be declared as −
public interface Hockey extends Sports, Event
Following example demonstrates the running example.
Live Demo
interface Event {
public void start();
}
interface Sports {
public void play();
}
interface Hockey extends Sports, Event{
public void show();
}
public class Tester{
public static void main(String[] args){
Hockey hockey = new Hockey() {
public void start() {
System.out.println("Start Event");
}
public void play() {
System.out.println("Play Sports.");
}
public void show() {
System.out.println("Show Hockey.");
}
};
hockey.start();
hockey.play();
hockey.show();
}
}
Start Event
Play Sports.
Show Hockey. | [
{
"code": null,
"e": 1197,
"s": 1062,
"text": "Java does not support multiple inheritance. This means that a class cannot extend more than one class. Therefore, following is illegal"
},
{
"code": null,
"e": 1235,
"s": 1197,
"text": "public class extends Animal, Mammal{}"
},
{
"code": null,
"e": 1561,
"s": 1235,
"text": "However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritance. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. For example, if the Hockey interface extended both Sports and Event, it would be declared as −"
},
{
"code": null,
"e": 1607,
"s": 1561,
"text": "public interface Hockey extends Sports, Event"
},
{
"code": null,
"e": 1659,
"s": 1607,
"text": "Following example demonstrates the running example."
},
{
"code": null,
"e": 1670,
"s": 1659,
"text": " Live Demo"
},
{
"code": null,
"e": 2272,
"s": 1670,
"text": "interface Event {\n public void start();\n}\ninterface Sports {\n public void play();\n}\ninterface Hockey extends Sports, Event{\n public void show();\n}\npublic class Tester{\n public static void main(String[] args){\n Hockey hockey = new Hockey() {\n public void start() {\n System.out.println(\"Start Event\");\n }\n public void play() {\n System.out.println(\"Play Sports.\");\n }\n public void show() {\n System.out.println(\"Show Hockey.\");\n }\n };\n\n hockey.start();\n hockey.play();\n hockey.show();\n }\n}"
},
{
"code": null,
"e": 2310,
"s": 2272,
"text": "Start Event\nPlay Sports.\nShow Hockey."
}
] |
How to Set-Up Shiny Server on Ubuntu | Shiny is an R package that allows Linux users to convert R code into an interactive webpage and documents online. You can take your shiny apps and share them in your organisation or the world. This article explains about how to set up shiny server on Ubuntu.
Before installing Shiny server, we need to install the shiny R package. To install R packages, use the following command –
$ sudo apt-get install r-base
The sample output should be like this -
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
apport-hooks-elementary contractor javascript-common libgda-5.0-4 libgda-5.0-common libgranite-common libgranite3 libgsignon-glib1
libindicate5 libjs-jquery libnoise-core0 libtagc0 mysql-server-5.7 mysql-server-core-5.7
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
bzip2-doc cdbs debhelper dh-strip-nondeterminism dh-translations gfortran gfortran-5 intltool libblas-common libblas-dev libblas3 libbz2-dev
libfile-stripnondeterminism-perl libgfortran-5-dev libgfortran3 liblapack-dev liblapack3 liblzma-dev liblzma5 libmail-sendmail-perl
libncurses5-dev libpcre3-dev libpcre32-3 libpcrecpp0v5 libpng12-dev libreadline-dev libreadline6-dev libsys-hostname-long-perl libtinfo-dev
po-debconf python-scour python-six r-base-core r-base-dev r-base-html r-cran-boot r-cran-class r-cran-cluster r-cran-codetools
r-cran-foreign r-cran-kernsmooth r-cran-lattice r-cran-mass r-cran-matrix r-cran-mgcv r-cran-nlme r-cran-nnet r-cran-rpart r-cran-spatial
r-cran-survival r-doc-html r-recommended
.......................................................................
We’re going to install Shiny server with the GDebi tool. To install GDebi, use the following command –
$ sudo apt-get install gdebi-core
The sample output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
apport-hooks-elementary contractor javascript-common libgda-5.0-4 libgda-5.0-common libgranite-common libgranite3 libgsignon-glib1
libindicate5 libjs-jquery libnoise-core0 libtagc0 mysql-server-5.7 mysql-server-core-5.7
Use 'sudo apt autoremove' to remove them.
The following NEW packages will be installed:
gdebi-core
0 upgraded, 1 newly installed, 0 to remove and 180 not upgraded.
Need to get 9,716 B of archives.
After this operation, 135 kB of additional disk space will be used.
Get:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 gdebi-core all 0.9.5.7ubuntu1 [9,716 B]
Fetched 9,716 B in 0s (31.5 kB/s)
Selecting previously unselected package gdebi-core.
(Reading database ... 189573 files and directories currently installed.)
Preparing to unpack .../gdebi-core_0.9.5.7ubuntu1_all.deb ...
Unpacking gdebi-core (0.9.5.7ubuntu1) ...
Processing triggers for man-db (2.7.5-1) ...
Setting up gdebi-core (0.9.5.7ubuntu1) ...
...........................................................................................
To download Shiny server, use the following command –
$ wget https://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-1.4.2.786-amd64.deb
The sample output should be like this –
--2016-05-16 11:38:20-- https://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-1.4.2.786-amd64.deb
Resolving download3.rstudio.org (download3.rstudio.org)... 54.230.190.35, 54.230.190.248, 54.230.190.84, ...
Connecting to download3.rstudio.org (download3.rstudio.org)|54.230.190.35|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 53653388 (51M) [application/octet-stream]
Saving to: ‘shiny-server-1.4.2.786-amd64.deb’
shiny-server-1.4.2.786-amd64.deb 100%[===================================================================>] 51.17M 408KB/s in 2m 26s
2016-05-16 11:40:48 (358 KB/s) - ‘shiny-server-1.4.2.786-amd64.deb’ saved [53653388/53653388]
Now use GDebi to install the file that was downloaded using the following command –
$ sudo gdebi shiny-server-1.4.2.786-amd64.deb
The sample output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading state information... Done
Shiny Server
Shiny Server is a server program from RStudio, Inc. that makes Shiny applications available over the web. Shiny is a web application framework for the R statistical computation language.
Do you want to install the software package? [y/N]:y
Selecting previously unselected package shiny-server.
(Reading database ... 189587 files and directories currently installed.)
Preparing to unpack shiny-server-1.4.2.786-amd64.deb ...
Unpacking shiny-server (1.4.2.786) ...
Setting up shiny-server (1.4.2.786) ...
Creating user shiny
Adding LANG to /etc/systemd/system/shiny-server.service, setting to en_IN
Created symlink from /etc/systemd/system/multi-user.target.wants/shiny-server.service to /etc/systemd/system/shiny-server.service.
shiny-server.service - ShinyServer
Loaded: loaded (/etc/systemd/system/shiny-server.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2016-05-16 11:42:45 IST; 36ms ago
Process: 1583 ExecStartPost=/bin/sleep 3 (code=exited, status=0/SUCCESS)
Main PID: 1584 (shiny-server)
Tasks: 8 (limit: 512)
CGroup: /system.slice/shiny-server.service
├─1582 /bin/bash -c /opt/shiny-server/bin/shiny-server --pidfile=/var/run/shiny-server.pid >> /var/log/shiny-server.log 2>&1
└─1584 /opt/shiny-server/ext/node/bin/shiny-server /opt/shiny-server/lib/main.js --pidfile=/var/run/shiny-server.pid
May 16 11:42:42 linux systemd[1]: Starting ShinyServer...
May 16 11:42:45 linux systemd[1]: shiny-server.service: Supervising process 1584 which is not our child. We'll most likely not notice...t exits.
May 16 11:42:45 linux systemd[1]: Started ShinyServer.
Hint: Some lines were ellipsized, use -l to show in full.
Shiny Server should now be installed and running on port 3838. You should be able to see a default welcome screen at http://your_server_ip:3838/. The sample output should be like this –
At this point you should have a working Shiny Server that can host Shiny applications, but it cannot yet host interactive R markdown documents because the rmarkdown R package isn’t installed. Shiny Server comes with a sample interactive document that is available at
Shiny Server comes with a sample interactive document that is available at http://your_server_ip:3838/sample-apps/rmd/. If you go to that URL right now, you will see an error.
To fix the above problem, use the following command-
$ sudo su - -c "R -e \"install.packages('rmarkdown', repos='http://cran.rstudio.com/')\""
The sample output should be like this –
R version 3.2.3 (2015-12-10) -- "Wooden Christmas-Tree"
Copyright (C) 2015 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
...........................................................................................
Now, Shiny server is set up to run interactive R markdown documents as well as Shiny applications. To verify how interactive documents work, go to http://your_server_ip:3838/sample-apps/rmd/.
You now have a functioning Shiny Server that can host Shiny applications or interactive documents. The configuration file for Shiny Server is at /etc/shiny-server/shiny-server.conf. By default it is configured to serve applications in the /srv/shiny-server/ directory. This means that any Shiny application that is placed at /srv/shiny-server/app_name will be available to the public at http://your_server_ip:3838/app_name/.
After this article, you will be able to understand – How To Set Up Shiny Server on Ubuntu. In our next articles, we will come up with more Linux based tricks and tips. Keep reading! | [
{
"code": null,
"e": 1321,
"s": 1062,
"text": "Shiny is an R package that allows Linux users to convert R code into an interactive webpage and documents online. You can take your shiny apps and share them in your organisation or the world. This article explains about how to set up shiny server on Ubuntu."
},
{
"code": null,
"e": 1444,
"s": 1321,
"text": "Before installing Shiny server, we need to install the shiny R package. To install R packages, use the following command –"
},
{
"code": null,
"e": 1474,
"s": 1444,
"text": "$ sudo apt-get install r-base"
},
{
"code": null,
"e": 1514,
"s": 1474,
"text": "The sample output should be like this -"
},
{
"code": null,
"e": 2789,
"s": 1514,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\napport-hooks-elementary contractor javascript-common libgda-5.0-4 libgda-5.0-common libgranite-common libgranite3 libgsignon-glib1\nlibindicate5 libjs-jquery libnoise-core0 libtagc0 mysql-server-5.7 mysql-server-core-5.7\nUse 'sudo apt autoremove' to remove them.\nThe following additional packages will be installed:\nbzip2-doc cdbs debhelper dh-strip-nondeterminism dh-translations gfortran gfortran-5 intltool libblas-common libblas-dev libblas3 libbz2-dev\nlibfile-stripnondeterminism-perl libgfortran-5-dev libgfortran3 liblapack-dev liblapack3 liblzma-dev liblzma5 libmail-sendmail-perl\nlibncurses5-dev libpcre3-dev libpcre32-3 libpcrecpp0v5 libpng12-dev libreadline-dev libreadline6-dev libsys-hostname-long-perl libtinfo-dev\npo-debconf python-scour python-six r-base-core r-base-dev r-base-html r-cran-boot r-cran-class r-cran-cluster r-cran-codetools\nr-cran-foreign r-cran-kernsmooth r-cran-lattice r-cran-mass r-cran-matrix r-cran-mgcv r-cran-nlme r-cran-nnet r-cran-rpart r-cran-spatial\nr-cran-survival r-doc-html r-recommended\n......................................................................."
},
{
"code": null,
"e": 2892,
"s": 2789,
"text": "We’re going to install Shiny server with the GDebi tool. To install GDebi, use the following command –"
},
{
"code": null,
"e": 2926,
"s": 2892,
"text": "$ sudo apt-get install gdebi-core"
},
{
"code": null,
"e": 2966,
"s": 2926,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 4163,
"s": 2966,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\napport-hooks-elementary contractor javascript-common libgda-5.0-4 libgda-5.0-common libgranite-common libgranite3 libgsignon-glib1\nlibindicate5 libjs-jquery libnoise-core0 libtagc0 mysql-server-5.7 mysql-server-core-5.7\nUse 'sudo apt autoremove' to remove them.\nThe following NEW packages will be installed:\ngdebi-core\n0 upgraded, 1 newly installed, 0 to remove and 180 not upgraded.\nNeed to get 9,716 B of archives.\nAfter this operation, 135 kB of additional disk space will be used.\nGet:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 gdebi-core all 0.9.5.7ubuntu1 [9,716 B]\nFetched 9,716 B in 0s (31.5 kB/s)\nSelecting previously unselected package gdebi-core.\n(Reading database ... 189573 files and directories currently installed.)\nPreparing to unpack .../gdebi-core_0.9.5.7ubuntu1_all.deb ...\nUnpacking gdebi-core (0.9.5.7ubuntu1) ...\nProcessing triggers for man-db (2.7.5-1) ...\nSetting up gdebi-core (0.9.5.7ubuntu1) ...\n..........................................................................................."
},
{
"code": null,
"e": 4217,
"s": 4163,
"text": "To download Shiny server, use the following command –"
},
{
"code": null,
"e": 4307,
"s": 4217,
"text": "$ wget https://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-1.4.2.786-amd64.deb"
},
{
"code": null,
"e": 4347,
"s": 4307,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 5030,
"s": 4347,
"text": "--2016-05-16 11:38:20-- https://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-1.4.2.786-amd64.deb\nResolving download3.rstudio.org (download3.rstudio.org)... 54.230.190.35, 54.230.190.248, 54.230.190.84, ...\nConnecting to download3.rstudio.org (download3.rstudio.org)|54.230.190.35|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 53653388 (51M) [application/octet-stream]\nSaving to: ‘shiny-server-1.4.2.786-amd64.deb’\n\nshiny-server-1.4.2.786-amd64.deb 100%[===================================================================>] 51.17M 408KB/s in 2m 26s\n\n2016-05-16 11:40:48 (358 KB/s) - ‘shiny-server-1.4.2.786-amd64.deb’ saved [53653388/53653388]\n\n"
},
{
"code": null,
"e": 5114,
"s": 5030,
"text": "Now use GDebi to install the file that was downloaded using the following command –"
},
{
"code": null,
"e": 5160,
"s": 5114,
"text": "$ sudo gdebi shiny-server-1.4.2.786-amd64.deb"
},
{
"code": null,
"e": 5200,
"s": 5160,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 7017,
"s": 5200,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nReading state information... Done\n\nShiny Server\nShiny Server is a server program from RStudio, Inc. that makes Shiny applications available over the web. Shiny is a web application framework for the R statistical computation language.\nDo you want to install the software package? [y/N]:y\nSelecting previously unselected package shiny-server.\n(Reading database ... 189587 files and directories currently installed.)\nPreparing to unpack shiny-server-1.4.2.786-amd64.deb ...\nUnpacking shiny-server (1.4.2.786) ...\nSetting up shiny-server (1.4.2.786) ...\nCreating user shiny\nAdding LANG to /etc/systemd/system/shiny-server.service, setting to en_IN\nCreated symlink from /etc/systemd/system/multi-user.target.wants/shiny-server.service to /etc/systemd/system/shiny-server.service.\nshiny-server.service - ShinyServer\nLoaded: loaded (/etc/systemd/system/shiny-server.service; enabled; vendor preset: enabled)\nActive: active (running) since Mon 2016-05-16 11:42:45 IST; 36ms ago\nProcess: 1583 ExecStartPost=/bin/sleep 3 (code=exited, status=0/SUCCESS)\nMain PID: 1584 (shiny-server)\nTasks: 8 (limit: 512)\nCGroup: /system.slice/shiny-server.service\n ├─1582 /bin/bash -c /opt/shiny-server/bin/shiny-server --pidfile=/var/run/shiny-server.pid >> /var/log/shiny-server.log 2>&1\n └─1584 /opt/shiny-server/ext/node/bin/shiny-server /opt/shiny-server/lib/main.js --pidfile=/var/run/shiny-server.pid\n\nMay 16 11:42:42 linux systemd[1]: Starting ShinyServer...\nMay 16 11:42:45 linux systemd[1]: shiny-server.service: Supervising process 1584 which is not our child. We'll most likely not notice...t exits.\nMay 16 11:42:45 linux systemd[1]: Started ShinyServer.\nHint: Some lines were ellipsized, use -l to show in full."
},
{
"code": null,
"e": 7203,
"s": 7017,
"text": "Shiny Server should now be installed and running on port 3838. You should be able to see a default welcome screen at http://your_server_ip:3838/. The sample output should be like this –"
},
{
"code": null,
"e": 7470,
"s": 7203,
"text": "At this point you should have a working Shiny Server that can host Shiny applications, but it cannot yet host interactive R markdown documents because the rmarkdown R package isn’t installed. Shiny Server comes with a sample interactive document that is available at"
},
{
"code": null,
"e": 7646,
"s": 7470,
"text": "Shiny Server comes with a sample interactive document that is available at http://your_server_ip:3838/sample-apps/rmd/. If you go to that URL right now, you will see an error."
},
{
"code": null,
"e": 7699,
"s": 7646,
"text": "To fix the above problem, use the following command-"
},
{
"code": null,
"e": 7789,
"s": 7699,
"text": "$ sudo su - -c \"R -e \\\"install.packages('rmarkdown', repos='http://cran.rstudio.com/')\\\"\""
},
{
"code": null,
"e": 7829,
"s": 7789,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 8369,
"s": 7829,
"text": "R version 3.2.3 (2015-12-10) -- \"Wooden Christmas-Tree\"\nCopyright (C) 2015 The R Foundation for Statistical Computing\nPlatform: x86_64-pc-linux-gnu (64-bit)\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\nNatural language support but running in an English locale\n\nR is a collaborative project with many contributors.\n..........................................................................................."
},
{
"code": null,
"e": 8561,
"s": 8369,
"text": "Now, Shiny server is set up to run interactive R markdown documents as well as Shiny applications. To verify how interactive documents work, go to http://your_server_ip:3838/sample-apps/rmd/."
},
{
"code": null,
"e": 8986,
"s": 8561,
"text": "You now have a functioning Shiny Server that can host Shiny applications or interactive documents. The configuration file for Shiny Server is at /etc/shiny-server/shiny-server.conf. By default it is configured to serve applications in the /srv/shiny-server/ directory. This means that any Shiny application that is placed at /srv/shiny-server/app_name will be available to the public at http://your_server_ip:3838/app_name/."
},
{
"code": null,
"e": 9168,
"s": 8986,
"text": "After this article, you will be able to understand – How To Set Up Shiny Server on Ubuntu. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!"
}
] |
Datagrams in Java - GeeksforGeeks | 24 May, 2018
TCP/IP-style networking provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. TCP includes algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to inefficient way to transport data.Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicated point-to-point channel between themselves. To communicate, they establish a connection, transmit the data, and then close the connection. All data sent over the channel is received in the same order in which it was sent. This is guaranteed by the channel.In contrast, applications that communicate via datagrams send and receive completely independent packets of information. These clients and servers do not have and do not need a dedicated point-to-point channel. The delivery of datagrams to their destinations is not guaranteed. Nor is the order of their arrival.
Datagram
A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.
Datagrams plays a vital role as an alternative.
Datagrams are bundles of information passed between machines. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it.
Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response and it is crucial point to note.
Java implements datagrams on top of the UDP (User Datagram Protocol) protocol by using two classes:
DatagramPacket object is the data container.DatagramSocket is the mechanism used to send or receive the DatagramPackets.
DatagramPacket object is the data container.
DatagramSocket is the mechanism used to send or receive the DatagramPackets.
DatagramSocket Class
DatagramSocket defines four public constructors. They are shown here:
DatagramSocket( ) throws SocketException : It creates a DatagramSocket bound to any unused port on the local computer.
DatagramSocket(int port) throws SocketException : It creates a DatagramSocket bound to the port specified by port.
DatagramSocket(int port, InetAddress ipAddress) throws SocketException : It constructs a DatagramSocket bound to the specified port and InetAddress.
DatagramSocket(SocketAddress address) throws SocketException : It constructs a DatagramSocket bound to the specified SocketAddress.
SocketAddress is an abstract class that is implemented by the concrete class InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number. All can throw a SocketException if an error occurs while creating the socket. DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are shown here:
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
The send( ) method sends packet to the port specified by packet. The receive method waits for a packet to be received from the port specified by packet and returns the result.Other methods give you access to various attributes associated with a DatagramSocket. Here is a sampling:
DatagramPacket Class
DatagramPacket defines several constructors. Four are shown here:
DatagramPacket(byte data[ ], int size) : It specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket
DatagramPacket(byte data[ ], int offset, int size) : It allows you to specify an offset into the buffer at which data will be stored.
DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) : It specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent.
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port) : It transmits packets beginning at the specified offset into the data.
Think of the first two forms as building an “in box, ” and the second two forms as stuffing and addressing an envelope.
DatagramPacket defines several methods, including those shown here, that give access to the address and port number of a packet, as well as the raw data and its length. In general, the get methods are used on packets that are received and the set methods are used on packets that will be sent.
A Datagram Example
The following example implements a very simple networked communications client and server. Messages are typed into the window at the server and written across the network to the client side, where they are displayed.
// Java program to illustrate datagramsimport java.net.*;class WriteServer { // Specified server port public static int serverPort = 998; // Specified client port public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds; // an array of buffer_size public static byte buffer[] = new byte[buffer_size]; // Function for server public static void TheServer() throws Exception { int pos = 0; while (true) { int c = System.in.read(); switch (c) { case -1: // -1 is given then server quits and returns System.out.println("Server Quits."); return; case '\r': break; // loop broken case '\n': // send the data to client ds.send(new DatagramPacket(buffer, pos, InetAddress.getLocalHost(), clientPort)); pos = 0; break; default: // otherwise put the input in buffer array buffer[pos++] = (byte)c; } } } // Function for client public static void TheClient() throws Exception { while (true) { // first one is array and later is its size DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p); // printing the data which has been sent by the server System.out.println(new String(p.getData(), 0, p.getLength())); } } // main driver function public static void main(String args[]) throws Exception { // if WriteServer 1 passed then this will run the server function // otherwise client function will run if (args.length == 1) { ds = new DatagramSocket(serverPort); TheServer(); } else { ds = new DatagramSocket(clientPort); TheClient(); } }}
This sample program is restricted by the DatagramSocket constructor to running between two ports on local machine. To use the program, run
java WriteServer
in one window; this will be the client. Then run
java WriteServer 1
This will be the server. Anything that is typed in the server window will be sent to the client window after a newline is received.
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
Strings in Java
HashMap get() Method in Java
StringBuilder Class in Java with Examples | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n24 May, 2018"
},
{
"code": null,
"e": 24931,
"s": 23948,
"text": "TCP/IP-style networking provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. TCP includes algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to inefficient way to transport data.Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicated point-to-point channel between themselves. To communicate, they establish a connection, transmit the data, and then close the connection. All data sent over the channel is received in the same order in which it was sent. This is guaranteed by the channel.In contrast, applications that communicate via datagrams send and receive completely independent packets of information. These clients and servers do not have and do not need a dedicated point-to-point channel. The delivery of datagrams to their destinations is not guaranteed. Nor is the order of their arrival."
},
{
"code": null,
"e": 24940,
"s": 24931,
"text": "Datagram"
},
{
"code": null,
"e": 25076,
"s": 24940,
"text": "A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed."
},
{
"code": null,
"e": 25124,
"s": 25076,
"text": "Datagrams plays a vital role as an alternative."
},
{
"code": null,
"e": 25336,
"s": 25124,
"text": "Datagrams are bundles of information passed between machines. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to catch it."
},
{
"code": null,
"e": 25532,
"s": 25336,
"text": "Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response and it is crucial point to note."
},
{
"code": null,
"e": 25632,
"s": 25532,
"text": "Java implements datagrams on top of the UDP (User Datagram Protocol) protocol by using two classes:"
},
{
"code": null,
"e": 25753,
"s": 25632,
"text": "DatagramPacket object is the data container.DatagramSocket is the mechanism used to send or receive the DatagramPackets."
},
{
"code": null,
"e": 25798,
"s": 25753,
"text": "DatagramPacket object is the data container."
},
{
"code": null,
"e": 25875,
"s": 25798,
"text": "DatagramSocket is the mechanism used to send or receive the DatagramPackets."
},
{
"code": null,
"e": 25896,
"s": 25875,
"text": "DatagramSocket Class"
},
{
"code": null,
"e": 25966,
"s": 25896,
"text": "DatagramSocket defines four public constructors. They are shown here:"
},
{
"code": null,
"e": 26085,
"s": 25966,
"text": "DatagramSocket( ) throws SocketException : It creates a DatagramSocket bound to any unused port on the local computer."
},
{
"code": null,
"e": 26200,
"s": 26085,
"text": "DatagramSocket(int port) throws SocketException : It creates a DatagramSocket bound to the port specified by port."
},
{
"code": null,
"e": 26349,
"s": 26200,
"text": "DatagramSocket(int port, InetAddress ipAddress) throws SocketException : It constructs a DatagramSocket bound to the specified port and InetAddress."
},
{
"code": null,
"e": 26481,
"s": 26349,
"text": "DatagramSocket(SocketAddress address) throws SocketException : It constructs a DatagramSocket bound to the specified SocketAddress."
},
{
"code": null,
"e": 26833,
"s": 26481,
"text": "SocketAddress is an abstract class that is implemented by the concrete class InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number. All can throw a SocketException if an error occurs while creating the socket. DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are shown here:"
},
{
"code": null,
"e": 26885,
"s": 26833,
"text": "void send(DatagramPacket packet) throws IOException"
},
{
"code": null,
"e": 26940,
"s": 26885,
"text": "void receive(DatagramPacket packet) throws IOException"
},
{
"code": null,
"e": 27221,
"s": 26940,
"text": "The send( ) method sends packet to the port specified by packet. The receive method waits for a packet to be received from the port specified by packet and returns the result.Other methods give you access to various attributes associated with a DatagramSocket. Here is a sampling:"
},
{
"code": null,
"e": 27242,
"s": 27221,
"text": "DatagramPacket Class"
},
{
"code": null,
"e": 27308,
"s": 27242,
"text": "DatagramPacket defines several constructors. Four are shown here:"
},
{
"code": null,
"e": 27472,
"s": 27308,
"text": "DatagramPacket(byte data[ ], int size) : It specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket"
},
{
"code": null,
"e": 27606,
"s": 27472,
"text": "DatagramPacket(byte data[ ], int offset, int size) : It allows you to specify an offset into the buffer at which data will be stored."
},
{
"code": null,
"e": 27811,
"s": 27606,
"text": "DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) : It specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent."
},
{
"code": null,
"e": 27967,
"s": 27811,
"text": "DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port) : It transmits packets beginning at the specified offset into the data."
},
{
"code": null,
"e": 28087,
"s": 27967,
"text": "Think of the first two forms as building an “in box, ” and the second two forms as stuffing and addressing an envelope."
},
{
"code": null,
"e": 28381,
"s": 28087,
"text": "DatagramPacket defines several methods, including those shown here, that give access to the address and port number of a packet, as well as the raw data and its length. In general, the get methods are used on packets that are received and the set methods are used on packets that will be sent."
},
{
"code": null,
"e": 28400,
"s": 28381,
"text": "A Datagram Example"
},
{
"code": null,
"e": 28617,
"s": 28400,
"text": "The following example implements a very simple networked communications client and server. Messages are typed into the window at the server and written across the network to the client side, where they are displayed."
},
{
"code": "// Java program to illustrate datagramsimport java.net.*;class WriteServer { // Specified server port public static int serverPort = 998; // Specified client port public static int clientPort = 999; public static int buffer_size = 1024; public static DatagramSocket ds; // an array of buffer_size public static byte buffer[] = new byte[buffer_size]; // Function for server public static void TheServer() throws Exception { int pos = 0; while (true) { int c = System.in.read(); switch (c) { case -1: // -1 is given then server quits and returns System.out.println(\"Server Quits.\"); return; case '\\r': break; // loop broken case '\\n': // send the data to client ds.send(new DatagramPacket(buffer, pos, InetAddress.getLocalHost(), clientPort)); pos = 0; break; default: // otherwise put the input in buffer array buffer[pos++] = (byte)c; } } } // Function for client public static void TheClient() throws Exception { while (true) { // first one is array and later is its size DatagramPacket p = new DatagramPacket(buffer, buffer.length); ds.receive(p); // printing the data which has been sent by the server System.out.println(new String(p.getData(), 0, p.getLength())); } } // main driver function public static void main(String args[]) throws Exception { // if WriteServer 1 passed then this will run the server function // otherwise client function will run if (args.length == 1) { ds = new DatagramSocket(serverPort); TheServer(); } else { ds = new DatagramSocket(clientPort); TheClient(); } }}",
"e": 30642,
"s": 28617,
"text": null
},
{
"code": null,
"e": 30781,
"s": 30642,
"text": "This sample program is restricted by the DatagramSocket constructor to running between two ports on local machine. To use the program, run"
},
{
"code": null,
"e": 30798,
"s": 30781,
"text": "java WriteServer"
},
{
"code": null,
"e": 30847,
"s": 30798,
"text": "in one window; this will be the client. Then run"
},
{
"code": null,
"e": 30866,
"s": 30847,
"text": "java WriteServer 1"
},
{
"code": null,
"e": 30998,
"s": 30866,
"text": "This will be the server. Anything that is typed in the server window will be sent to the client window after a newline is received."
},
{
"code": null,
"e": 31014,
"s": 30998,
"text": "Java-Networking"
},
{
"code": null,
"e": 31019,
"s": 31014,
"text": "Java"
},
{
"code": null,
"e": 31024,
"s": 31019,
"text": "Java"
},
{
"code": null,
"e": 31122,
"s": 31024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31131,
"s": 31122,
"text": "Comments"
},
{
"code": null,
"e": 31144,
"s": 31131,
"text": "Old Comments"
},
{
"code": null,
"e": 31190,
"s": 31144,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31211,
"s": 31190,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31226,
"s": 31211,
"text": "Stream In Java"
},
{
"code": null,
"e": 31245,
"s": 31226,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31262,
"s": 31245,
"text": "Generics in Java"
},
{
"code": null,
"e": 31292,
"s": 31262,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31335,
"s": 31292,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31351,
"s": 31335,
"text": "Strings in Java"
},
{
"code": null,
"e": 31380,
"s": 31351,
"text": "HashMap get() Method in Java"
}
] |
HTML Course | Building Main Content - Section 1 - GeeksforGeeks | 10 Aug, 2021
Course Navigation
We just completed building the header for our website. Let’s start building the main content for the website. As we described while creating the HTML layout of the website, the main content was divided into three sections as shown below:
HTML
<!-- Main content between Header and Footer --><main> <!-- Section 1 of Main content --> <section> </section> <!-- Section 2 of Main content --> <section> </section> <!-- Section 3 of Main content --> <section> </section></main>
In this post, we will build the section 1 of the main layout. The section 1 of the main layout is highlighted in the below image:
Let’s note down the content and some properties of the Section 1 that will be useful in designing:
Title: It contains a title “Welcome to Our Website”, which is aligned to the center.
Sample Text: It has a sample text or we can say a paragraph just below the title which is also aligned to center.
Let’s start writing HTML for the section 1 of our website, follow the below steps:
Give the section tag the class container to fix it width to 1200px and align it’s childrens to center.
Create a new div tag inside the section tag with an id “title“.
Add the title “Welcome to Our Website” inside an <h1> tag and assign it an id title.
Assign the sample tag below the title inside a paragraph <p> tag.
Below is the complete HTML code for Section 1 of Main layout:
HTML
<!-- Main content between Header and Footer --><main> <!-- Section 1 of Main content --> <section> <div id="welcome"> <h1 class="title">Welcome to our website</h1> <p> This is a <strong>Sample Webpage</strong>, a HTML and CSS template designed by the <a href="https://www.geeksforgeeks.org" target="_blank" rel="nofollow">GeeksforGeeks Team</a>. The photos in this template are designed by our <b>Graphic Design Team</b>. This template is designed to explain the basics of HTML and CSS in our first Web Design course. </p> </div> </section> <!-- Section 2 of Main content --> <section> </section> <!-- Section 3 of Main content --> <section> </section></main>
After adding the HTML codes the page index.html will look like as below:
Let’s add styles to the classes to make this look as shown in the template:
Styling div with id (#welcome): This div will include both the title and the sample text. So set it’s overflow to hidden and use “margin: 0px auto” to align it’s children to center. Also set it’s width to 1000px. Add below code to style.css:
css
#welcome{ overflow: hidden; width: 1000px; margin: 0px auto;}
Styling the title h1 tag: Give at top margin of 20px, padding of 20px and align it’s text to center. Add below code to style.css:
css
#welcome .title{ margin-top: 20px; padding: 20px; text-align: center;}
Styling the p tag for sample text: Give it a margin from bottom of 40px and align it’s text to center. Add below code to style.css:
css
#welcome p{ margin-bottom: 40px; text-align: center;}
The complete CSS for styling the section 1 of the main layout is given below:
CSS
/**********************************//* Styling Main content Section 1 *//**********************************/#welcome{ overflow: hidden; width: 1000px; margin: 0px auto;} #welcome .title{ margin-top: 20px; padding: 20px; text-align: center;} #welcome p{ margin-bottom: 40px; text-align: center;}
That’s it, on opening the index.html file in a browser now, you will see the below output:
Everything looks fine till now. But there seems to be some problem. The font’s in our project does not seem to be the same as that of the template. We have used the font “Roboto”, but it seems to be not working for some reason.This is because the browser does not support each and every font implicitly. We will have to explicitly define the source of the font within the head tags. Add the below line inside the head tags of index.html file:
HTML
<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>
After including the above line within the head tags. Reload your index.html in the browser:
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
shubham_singh
ysachin2314
HTML-course-basic
HTML5
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 30298,
"s": 30270,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 30318,
"s": 30298,
"text": "Course Navigation "
},
{
"code": null,
"e": 30558,
"s": 30318,
"text": "We just completed building the header for our website. Let’s start building the main content for the website. As we described while creating the HTML layout of the website, the main content was divided into three sections as shown below: "
},
{
"code": null,
"e": 30563,
"s": 30558,
"text": "HTML"
},
{
"code": "<!-- Main content between Header and Footer --><main> <!-- Section 1 of Main content --> <section> </section> <!-- Section 2 of Main content --> <section> </section> <!-- Section 3 of Main content --> <section> </section></main>",
"e": 30877,
"s": 30563,
"text": null
},
{
"code": null,
"e": 31009,
"s": 30877,
"text": "In this post, we will build the section 1 of the main layout. The section 1 of the main layout is highlighted in the below image: "
},
{
"code": null,
"e": 31110,
"s": 31009,
"text": "Let’s note down the content and some properties of the Section 1 that will be useful in designing: "
},
{
"code": null,
"e": 31195,
"s": 31110,
"text": "Title: It contains a title “Welcome to Our Website”, which is aligned to the center."
},
{
"code": null,
"e": 31309,
"s": 31195,
"text": "Sample Text: It has a sample text or we can say a paragraph just below the title which is also aligned to center."
},
{
"code": null,
"e": 31394,
"s": 31309,
"text": "Let’s start writing HTML for the section 1 of our website, follow the below steps: "
},
{
"code": null,
"e": 31497,
"s": 31394,
"text": "Give the section tag the class container to fix it width to 1200px and align it’s childrens to center."
},
{
"code": null,
"e": 31561,
"s": 31497,
"text": "Create a new div tag inside the section tag with an id “title“."
},
{
"code": null,
"e": 31648,
"s": 31561,
"text": "Add the title “Welcome to Our Website” inside an <h1> tag and assign it an id title. "
},
{
"code": null,
"e": 31714,
"s": 31648,
"text": "Assign the sample tag below the title inside a paragraph <p> tag."
},
{
"code": null,
"e": 31778,
"s": 31714,
"text": "Below is the complete HTML code for Section 1 of Main layout: "
},
{
"code": null,
"e": 31783,
"s": 31778,
"text": "HTML"
},
{
"code": "<!-- Main content between Header and Footer --><main> <!-- Section 1 of Main content --> <section> <div id=\"welcome\"> <h1 class=\"title\">Welcome to our website</h1> <p> This is a <strong>Sample Webpage</strong>, a HTML and CSS template designed by the <a href=\"https://www.geeksforgeeks.org\" target=\"_blank\" rel=\"nofollow\">GeeksforGeeks Team</a>. The photos in this template are designed by our <b>Graphic Design Team</b>. This template is designed to explain the basics of HTML and CSS in our first Web Design course. </p> </div> </section> <!-- Section 2 of Main content --> <section> </section> <!-- Section 3 of Main content --> <section> </section></main>",
"e": 32718,
"s": 31783,
"text": null
},
{
"code": null,
"e": 32793,
"s": 32718,
"text": "After adding the HTML codes the page index.html will look like as below: "
},
{
"code": null,
"e": 32871,
"s": 32793,
"text": "Let’s add styles to the classes to make this look as shown in the template: "
},
{
"code": null,
"e": 33115,
"s": 32871,
"text": "Styling div with id (#welcome): This div will include both the title and the sample text. So set it’s overflow to hidden and use “margin: 0px auto” to align it’s children to center. Also set it’s width to 1000px. Add below code to style.css: "
},
{
"code": null,
"e": 33119,
"s": 33115,
"text": "css"
},
{
"code": "#welcome{ overflow: hidden; width: 1000px; margin: 0px auto;}",
"e": 33190,
"s": 33119,
"text": null
},
{
"code": null,
"e": 33324,
"s": 33192,
"text": "Styling the title h1 tag: Give at top margin of 20px, padding of 20px and align it’s text to center. Add below code to style.css: "
},
{
"code": null,
"e": 33328,
"s": 33324,
"text": "css"
},
{
"code": "#welcome .title{ margin-top: 20px; padding: 20px; text-align: center;}",
"e": 33408,
"s": 33328,
"text": null
},
{
"code": null,
"e": 33544,
"s": 33410,
"text": "Styling the p tag for sample text: Give it a margin from bottom of 40px and align it’s text to center. Add below code to style.css: "
},
{
"code": null,
"e": 33548,
"s": 33544,
"text": "css"
},
{
"code": "#welcome p{ margin-bottom: 40px; text-align: center;}",
"e": 33608,
"s": 33548,
"text": null
},
{
"code": null,
"e": 33690,
"s": 33610,
"text": "The complete CSS for styling the section 1 of the main layout is given below: "
},
{
"code": null,
"e": 33694,
"s": 33690,
"text": "CSS"
},
{
"code": "/**********************************//* Styling Main content Section 1 *//**********************************/#welcome{ overflow: hidden; width: 1000px; margin: 0px auto;} #welcome .title{ margin-top: 20px; padding: 20px; text-align: center;} #welcome p{ margin-bottom: 40px; text-align: center;}",
"e": 34021,
"s": 33694,
"text": null
},
{
"code": null,
"e": 34114,
"s": 34021,
"text": "That’s it, on opening the index.html file in a browser now, you will see the below output: "
},
{
"code": null,
"e": 34559,
"s": 34114,
"text": "Everything looks fine till now. But there seems to be some problem. The font’s in our project does not seem to be the same as that of the template. We have used the font “Roboto”, but it seems to be not working for some reason.This is because the browser does not support each and every font implicitly. We will have to explicitly define the source of the font within the head tags. Add the below line inside the head tags of index.html file: "
},
{
"code": null,
"e": 34564,
"s": 34559,
"text": "HTML"
},
{
"code": "<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>",
"e": 34642,
"s": 34564,
"text": null
},
{
"code": null,
"e": 34736,
"s": 34642,
"text": "After including the above line within the head tags. Reload your index.html in the browser: "
},
{
"code": null,
"e": 34755,
"s": 34736,
"text": "Supported Browser:"
},
{
"code": null,
"e": 34769,
"s": 34755,
"text": "Google Chrome"
},
{
"code": null,
"e": 34784,
"s": 34769,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 34792,
"s": 34784,
"text": "Firefox"
},
{
"code": null,
"e": 34798,
"s": 34792,
"text": "Opera"
},
{
"code": null,
"e": 34805,
"s": 34798,
"text": "Safari"
},
{
"code": null,
"e": 34944,
"s": 34807,
"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": 34958,
"s": 34944,
"text": "shubham_singh"
},
{
"code": null,
"e": 34970,
"s": 34958,
"text": "ysachin2314"
},
{
"code": null,
"e": 34988,
"s": 34970,
"text": "HTML-course-basic"
},
{
"code": null,
"e": 34994,
"s": 34988,
"text": "HTML5"
},
{
"code": null,
"e": 34998,
"s": 34994,
"text": "CSS"
},
{
"code": null,
"e": 35003,
"s": 34998,
"text": "HTML"
},
{
"code": null,
"e": 35020,
"s": 35003,
"text": "Web Technologies"
},
{
"code": null,
"e": 35025,
"s": 35020,
"text": "HTML"
},
{
"code": null,
"e": 35123,
"s": 35025,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35132,
"s": 35123,
"text": "Comments"
},
{
"code": null,
"e": 35145,
"s": 35132,
"text": "Old Comments"
},
{
"code": null,
"e": 35207,
"s": 35145,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35257,
"s": 35207,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35315,
"s": 35257,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 35363,
"s": 35315,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35400,
"s": 35363,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 35462,
"s": 35400,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35512,
"s": 35462,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35572,
"s": 35512,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 35620,
"s": 35572,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Count substrings that starts with character X and ends with character Y - GeeksforGeeks | 28 Apr, 2021
Given a string str of n lowercase characters, the task is to count the number of substrings of str starting with character X and ending with character Y.Examples:
Input: str = "abbcaceghcak"
x = 'a', y = 'c'
Output: 5
abbc, abbcac, ac, abbcaceghc, aceghc
Input: str = "geeksforgeeks"
x = 'g', y = 'e'
Output: 6
Approach:
Initialize two counters i.e. tot_count to count the total number of substrings and count_x to count the number of strings that start with X.
Start traversing the string.
If the current character is X then increment the count of count_x.
If the current character is Y, it means a string ends at Y so increment the count of tot_count i.e.
tot_count = tot_count + count_x
It means that if there exists a Y then it will make a substring with all the X occurs before Y in the string. So, add the count of X to the total count.
Return total count.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to count substrings// starting with character X and ending// with character Y#include <bits/stdc++.h>using namespace std; // function to count substrings starting with// character X and ending with character Yint countSubstr(string str, int n, char x, char y){ // to store total count of // required substrings int tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far int count_x = 0; // traverse 'str' form left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] == y) tot_count += count_x; } // required count return tot_count;} // Driver codeint main(){ string str = "abbcaceghcak"; int n = str.size(); char x = 'a', y = 'c'; cout << "Count = " << countSubstr(str, n, x, y); return 0;}
// Java implementation to count// substrings starting with// character X and ending// with character Yimport java.util.*;import java.lang.*;import java.io.*; class GFG{// function to count substrings// starting with character X and// ending with character Ystatic int countSubstr(String str, int n, char x, char y){ // to store total count of // required substrings int tot_count = 0; // to store count of character // 'x' up to the point the // string 'str' has been // traversed so far int count_x = 0; // traverse 'str' form // left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str.charAt(i) == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str.charAt(i) == y) tot_count += count_x; } // required count return tot_count;} // Driver codepublic static void main(String args[]){ String str = "abbcaceghcak"; int n = str.length(); char x = 'a', y = 'c'; System.out.print ("Count = " + countSubstr(str, n, x, y));}} // This code is contributed// by Subhadeep
# Python 3 implementation to count substrings# starting with character X and ending# with character Y # function to count substrings starting with# character X and ending with character Ydef countSubstr(str, n, x, y): # to store total count of # required substrings tot_count = 0 # to store count of character 'x' # up to the point the string 'str' # has been traversed so far count_x = 0 # traverse 'str' form left to right for i in range(n): # if true, increment 'count_x' if str[i] == x: count_x += 1 # if true accumulate 'count_x' # to 'tot_count' if str[i] == y: tot_count += count_x # required count return tot_count # Driver Codestr = 'abbcaceghcak'n = len(str)x, y = 'a', 'c'print('Count =', countSubstr(str, n, x, y)) # This code is contributed SamyuktaSHegde
// C# implementation to count substrings// starting with character X and ending// with character Yusing System; class GFG{// function to count substrings starting// with character X and ending with character Ystatic int countSubstr(string str, int n, char x, char y){ // to store total count of // required substrings int tot_count = 0; // to store count of character 'x' up // to the point the string 'str' has // been traversed so far int count_x = 0; // traverse 'str' form left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] == y) tot_count += count_x; } // required count return tot_count;} // Driver codepublic static void Main(){ string str = "abbcaceghcak"; int n = str.Length; char x = 'a', y = 'c'; Console.Write("Count = " + countSubstr(str, n, x, y));}} // This code is contributed// by Akanksha Rai
<?php// PHP implementation to count substrings// starting with character X and ending// with character Y // function to count substrings starting with// character X and ending with character Yfunction countSubstr($str, $n, $x, $y){ // to store total count of // required substrings $tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far $count_x = 0; // traverse 'str' form left to right for ($i = 0; $i < $n; $i++) { // if true, increment 'count_x' if ($str[$i] == $x) $count_x++; // if true accumulate 'count_x' // to 'tot_count' if ($str[$i] == $y) $tot_count += $count_x; } // required count return $tot_count;} // Driver code$str = "abbcaceghcak";$n = strlen($str);$x = 'a'; $y = 'c'; echo "Count = ". countSubstr($str, $n, $x, $y); // This code is contributed// by Akanksha Rai
<script> // JavaScript implementation to count substrings // starting with character X and ending // with character Y // function to count substrings starting with // character X and ending with character Y function countSubstr(str, n, x, y) { // to store total count of // required substrings var tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far var count_x = 0; // traverse 'str' form left to right for (var i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] === x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] === y) tot_count += count_x; } // required count return tot_count; } // Driver code var str = "abbcaceghcak"; var n = str.length; var x = "a", y = "c"; document.write("Count = " + countSubstr(str, n, x, y)); </script>
Count = 5
tufan_gupta2000
SamyuktaSHegde
Akanksha_Rai
rdtank
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
Vigenère Cipher
How to Append a Character to a String in C
Convert character array to string in C++
sprintf() in C
Converting Roman Numerals to Decimal lying between 1 to 3999
Print all subsequences of a string
Find frequency of each word in a string in Python | [
{
"code": null,
"e": 24854,
"s": 24826,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 25019,
"s": 24854,
"text": "Given a string str of n lowercase characters, the task is to count the number of substrings of str starting with character X and ending with character Y.Examples: "
},
{
"code": null,
"e": 25184,
"s": 25019,
"text": "Input: str = \"abbcaceghcak\"\n x = 'a', y = 'c'\nOutput: 5\nabbc, abbcac, ac, abbcaceghc, aceghc\n\nInput: str = \"geeksforgeeks\"\n x = 'g', y = 'e'\nOutput: 6"
},
{
"code": null,
"e": 25198,
"s": 25186,
"text": "Approach: "
},
{
"code": null,
"e": 25339,
"s": 25198,
"text": "Initialize two counters i.e. tot_count to count the total number of substrings and count_x to count the number of strings that start with X."
},
{
"code": null,
"e": 25368,
"s": 25339,
"text": "Start traversing the string."
},
{
"code": null,
"e": 25435,
"s": 25368,
"text": "If the current character is X then increment the count of count_x."
},
{
"code": null,
"e": 25536,
"s": 25435,
"text": "If the current character is Y, it means a string ends at Y so increment the count of tot_count i.e. "
},
{
"code": null,
"e": 25568,
"s": 25536,
"text": "tot_count = tot_count + count_x"
},
{
"code": null,
"e": 25721,
"s": 25568,
"text": "It means that if there exists a Y then it will make a substring with all the X occurs before Y in the string. So, add the count of X to the total count."
},
{
"code": null,
"e": 25741,
"s": 25721,
"text": "Return total count."
},
{
"code": null,
"e": 25789,
"s": 25741,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 25793,
"s": 25789,
"text": "C++"
},
{
"code": null,
"e": 25798,
"s": 25793,
"text": "Java"
},
{
"code": null,
"e": 25806,
"s": 25798,
"text": "Python3"
},
{
"code": null,
"e": 25809,
"s": 25806,
"text": "C#"
},
{
"code": null,
"e": 25813,
"s": 25809,
"text": "PHP"
},
{
"code": null,
"e": 25824,
"s": 25813,
"text": "Javascript"
},
{
"code": "// C++ implementation to count substrings// starting with character X and ending// with character Y#include <bits/stdc++.h>using namespace std; // function to count substrings starting with// character X and ending with character Yint countSubstr(string str, int n, char x, char y){ // to store total count of // required substrings int tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far int count_x = 0; // traverse 'str' form left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] == y) tot_count += count_x; } // required count return tot_count;} // Driver codeint main(){ string str = \"abbcaceghcak\"; int n = str.size(); char x = 'a', y = 'c'; cout << \"Count = \" << countSubstr(str, n, x, y); return 0;}",
"e": 26844,
"s": 25824,
"text": null
},
{
"code": "// Java implementation to count// substrings starting with// character X and ending// with character Yimport java.util.*;import java.lang.*;import java.io.*; class GFG{// function to count substrings// starting with character X and// ending with character Ystatic int countSubstr(String str, int n, char x, char y){ // to store total count of // required substrings int tot_count = 0; // to store count of character // 'x' up to the point the // string 'str' has been // traversed so far int count_x = 0; // traverse 'str' form // left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str.charAt(i) == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str.charAt(i) == y) tot_count += count_x; } // required count return tot_count;} // Driver codepublic static void main(String args[]){ String str = \"abbcaceghcak\"; int n = str.length(); char x = 'a', y = 'c'; System.out.print (\"Count = \" + countSubstr(str, n, x, y));}} // This code is contributed// by Subhadeep",
"e": 28001,
"s": 26844,
"text": null
},
{
"code": "# Python 3 implementation to count substrings# starting with character X and ending# with character Y # function to count substrings starting with# character X and ending with character Ydef countSubstr(str, n, x, y): # to store total count of # required substrings tot_count = 0 # to store count of character 'x' # up to the point the string 'str' # has been traversed so far count_x = 0 # traverse 'str' form left to right for i in range(n): # if true, increment 'count_x' if str[i] == x: count_x += 1 # if true accumulate 'count_x' # to 'tot_count' if str[i] == y: tot_count += count_x # required count return tot_count # Driver Codestr = 'abbcaceghcak'n = len(str)x, y = 'a', 'c'print('Count =', countSubstr(str, n, x, y)) # This code is contributed SamyuktaSHegde",
"e": 28870,
"s": 28001,
"text": null
},
{
"code": "// C# implementation to count substrings// starting with character X and ending// with character Yusing System; class GFG{// function to count substrings starting// with character X and ending with character Ystatic int countSubstr(string str, int n, char x, char y){ // to store total count of // required substrings int tot_count = 0; // to store count of character 'x' up // to the point the string 'str' has // been traversed so far int count_x = 0; // traverse 'str' form left to right for (int i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] == x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] == y) tot_count += count_x; } // required count return tot_count;} // Driver codepublic static void Main(){ string str = \"abbcaceghcak\"; int n = str.Length; char x = 'a', y = 'c'; Console.Write(\"Count = \" + countSubstr(str, n, x, y));}} // This code is contributed// by Akanksha Rai",
"e": 29934,
"s": 28870,
"text": null
},
{
"code": "<?php// PHP implementation to count substrings// starting with character X and ending// with character Y // function to count substrings starting with// character X and ending with character Yfunction countSubstr($str, $n, $x, $y){ // to store total count of // required substrings $tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far $count_x = 0; // traverse 'str' form left to right for ($i = 0; $i < $n; $i++) { // if true, increment 'count_x' if ($str[$i] == $x) $count_x++; // if true accumulate 'count_x' // to 'tot_count' if ($str[$i] == $y) $tot_count += $count_x; } // required count return $tot_count;} // Driver code$str = \"abbcaceghcak\";$n = strlen($str);$x = 'a'; $y = 'c'; echo \"Count = \". countSubstr($str, $n, $x, $y); // This code is contributed// by Akanksha Rai",
"e": 30880,
"s": 29934,
"text": null
},
{
"code": "<script> // JavaScript implementation to count substrings // starting with character X and ending // with character Y // function to count substrings starting with // character X and ending with character Y function countSubstr(str, n, x, y) { // to store total count of // required substrings var tot_count = 0; // to store count of character 'x' // up to the point the string 'str' // has been traversed so far var count_x = 0; // traverse 'str' form left to right for (var i = 0; i < n; i++) { // if true, increment 'count_x' if (str[i] === x) count_x++; // if true accumulate 'count_x' // to 'tot_count' if (str[i] === y) tot_count += count_x; } // required count return tot_count; } // Driver code var str = \"abbcaceghcak\"; var n = str.length; var x = \"a\", y = \"c\"; document.write(\"Count = \" + countSubstr(str, n, x, y)); </script>",
"e": 31924,
"s": 30880,
"text": null
},
{
"code": null,
"e": 31934,
"s": 31924,
"text": "Count = 5"
},
{
"code": null,
"e": 31952,
"s": 31936,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 31967,
"s": 31952,
"text": "SamyuktaSHegde"
},
{
"code": null,
"e": 31980,
"s": 31967,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31987,
"s": 31980,
"text": "rdtank"
},
{
"code": null,
"e": 31995,
"s": 31987,
"text": "Strings"
},
{
"code": null,
"e": 32003,
"s": 31995,
"text": "Strings"
},
{
"code": null,
"e": 32101,
"s": 32003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32110,
"s": 32101,
"text": "Comments"
},
{
"code": null,
"e": 32123,
"s": 32110,
"text": "Old Comments"
},
{
"code": null,
"e": 32168,
"s": 32123,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 32180,
"s": 32168,
"text": "Hill Cipher"
},
{
"code": null,
"e": 32218,
"s": 32180,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 32235,
"s": 32218,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 32278,
"s": 32235,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 32319,
"s": 32278,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 32334,
"s": 32319,
"text": "sprintf() in C"
},
{
"code": null,
"e": 32395,
"s": 32334,
"text": "Converting Roman Numerals to Decimal lying between 1 to 3999"
},
{
"code": null,
"e": 32430,
"s": 32395,
"text": "Print all subsequences of a string"
}
] |
How to Create a Drop-Down Menu and a Slide Bar for your Favorite Visualization Tool | by Khuyen Tran | Towards Data Science | Imagine we are analyzing the trend population of countries in the world from 1960 to 2018 to predict the population in the next coming years.
To visualize the trend of the country, we choose Plotly for its simple and beautiful visualization. Start with ‘Vietnam’
import pandas as pd import datapane as dp import plotly.express as pxdata = pd.read_csv('population.csv')fig = px.line(data.set_index('Countries').loc['Vietnam'], labels={'index': 'Year', 'value': 'Population'}, title='Population Over Time', )fig.show()
Then the United States
fig = px.line(data.set_index('Countries').loc['United States'], labels={'index': 'Year', 'value': 'Population'}, title='Population Over Time', )fig.show()
Seems like the curve is linearly increasing, but we are not sure if the curve is linear for every country, so we want to keep visualizing more countries. Is there a faster way to visualize these countries instead of changing the name of the country in df.loc['location']? Wouldn’t it be nice to have a drop-down menu to choose the country you want to visualize?
This could be easily done with a small add-on: Jupyter Widget.
Widgets are eventful python objects that can give control like a slider, textbox, etc. We can use widgets to build interactive GUIs for our notebooks.
Start with installation
With pip
pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension
With conda
conda install -c conda-forge ipywidgets
Check out this link for further information about installation.
Import useful libraries
from ipywidgets import interact, interactive, fixed, interact_manualimport ipywidgets as widgets
Explore basic things we can do with interact. First, define a function that you want to explore. The following function returns x as the parameter x is changed.
def f(x): return x
Create a slide bar by passing a tuple (min, max) to x
interact(f, x=(0.0,10.0))
Create a dropdown menu by passing a list of strings
interact(f, x=['love','hate'])
Based on this, maybe we can create a function for our plot that changes based on the country?
def f(country): df.loc[country].iplot( xTitle='Year', yTitle='Population of {}'.format(country), title='Population Over Time' )
Represent countries with df.index
df.index
Create interact with one simple code.
interact(f, country=df.index)
Awesome! Seems like the population curves of some countries are linear. But we are also curious about how the distribution of populations in the world changes each year, could we create another function as a parameter? Absolutely!
Take the transpose of our previous graph and change country to year.
def f(year): fig = px.line(data.set_index('Countries').T.loc[str(year)], labels={'value':'Population in {}'.format(str(year))}, title= 'Population over time') fig.show() interact(f, year=list(data.T.index)[1:] )
If we prefer a slide bar, we could simply switch a list of years to a tuple (min year, max year)
interact(f, year=(1960, 2018))
That’s it! Now we could efficiently go through the distribution each year to see if the distribution has changed over time.
Congratulations! You have learned how to utilize Python Widgets to create a slide bar and drop-down menu for efficient visualization. I encourage you to try this out with any of your favorite visualization tools such as Matplotlib, Seaborn. Just a small twist in your code can save you a huge amount of time to invest in other important tasks of your data science projects.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: | [
{
"code": null,
"e": 313,
"s": 171,
"text": "Imagine we are analyzing the trend population of countries in the world from 1960 to 2018 to predict the population in the next coming years."
},
{
"code": null,
"e": 434,
"s": 313,
"text": "To visualize the trend of the country, we choose Plotly for its simple and beautiful visualization. Start with ‘Vietnam’"
},
{
"code": null,
"e": 726,
"s": 434,
"text": "import pandas as pd import datapane as dp import plotly.express as pxdata = pd.read_csv('population.csv')fig = px.line(data.set_index('Countries').loc['Vietnam'], labels={'index': 'Year', 'value': 'Population'}, title='Population Over Time', )fig.show()"
},
{
"code": null,
"e": 749,
"s": 726,
"text": "Then the United States"
},
{
"code": null,
"e": 943,
"s": 749,
"text": "fig = px.line(data.set_index('Countries').loc['United States'], labels={'index': 'Year', 'value': 'Population'}, title='Population Over Time', )fig.show()"
},
{
"code": null,
"e": 1305,
"s": 943,
"text": "Seems like the curve is linearly increasing, but we are not sure if the curve is linear for every country, so we want to keep visualizing more countries. Is there a faster way to visualize these countries instead of changing the name of the country in df.loc['location']? Wouldn’t it be nice to have a drop-down menu to choose the country you want to visualize?"
},
{
"code": null,
"e": 1368,
"s": 1305,
"text": "This could be easily done with a small add-on: Jupyter Widget."
},
{
"code": null,
"e": 1519,
"s": 1368,
"text": "Widgets are eventful python objects that can give control like a slider, textbox, etc. We can use widgets to build interactive GUIs for our notebooks."
},
{
"code": null,
"e": 1543,
"s": 1519,
"text": "Start with installation"
},
{
"code": null,
"e": 1552,
"s": 1543,
"text": "With pip"
},
{
"code": null,
"e": 1625,
"s": 1552,
"text": "pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension"
},
{
"code": null,
"e": 1636,
"s": 1625,
"text": "With conda"
},
{
"code": null,
"e": 1676,
"s": 1636,
"text": "conda install -c conda-forge ipywidgets"
},
{
"code": null,
"e": 1740,
"s": 1676,
"text": "Check out this link for further information about installation."
},
{
"code": null,
"e": 1764,
"s": 1740,
"text": "Import useful libraries"
},
{
"code": null,
"e": 1861,
"s": 1764,
"text": "from ipywidgets import interact, interactive, fixed, interact_manualimport ipywidgets as widgets"
},
{
"code": null,
"e": 2022,
"s": 1861,
"text": "Explore basic things we can do with interact. First, define a function that you want to explore. The following function returns x as the parameter x is changed."
},
{
"code": null,
"e": 2044,
"s": 2022,
"text": "def f(x): return x"
},
{
"code": null,
"e": 2098,
"s": 2044,
"text": "Create a slide bar by passing a tuple (min, max) to x"
},
{
"code": null,
"e": 2124,
"s": 2098,
"text": "interact(f, x=(0.0,10.0))"
},
{
"code": null,
"e": 2176,
"s": 2124,
"text": "Create a dropdown menu by passing a list of strings"
},
{
"code": null,
"e": 2207,
"s": 2176,
"text": "interact(f, x=['love','hate'])"
},
{
"code": null,
"e": 2301,
"s": 2207,
"text": "Based on this, maybe we can create a function for our plot that changes based on the country?"
},
{
"code": null,
"e": 2510,
"s": 2301,
"text": "def f(country): df.loc[country].iplot( xTitle='Year', yTitle='Population of {}'.format(country), title='Population Over Time' )"
},
{
"code": null,
"e": 2544,
"s": 2510,
"text": "Represent countries with df.index"
},
{
"code": null,
"e": 2553,
"s": 2544,
"text": "df.index"
},
{
"code": null,
"e": 2591,
"s": 2553,
"text": "Create interact with one simple code."
},
{
"code": null,
"e": 2621,
"s": 2591,
"text": "interact(f, country=df.index)"
},
{
"code": null,
"e": 2852,
"s": 2621,
"text": "Awesome! Seems like the population curves of some countries are linear. But we are also curious about how the distribution of populations in the world changes each year, could we create another function as a parameter? Absolutely!"
},
{
"code": null,
"e": 2921,
"s": 2852,
"text": "Take the transpose of our previous graph and change country to year."
},
{
"code": null,
"e": 3168,
"s": 2921,
"text": "def f(year): fig = px.line(data.set_index('Countries').T.loc[str(year)], labels={'value':'Population in {}'.format(str(year))}, title= 'Population over time') fig.show() interact(f, year=list(data.T.index)[1:] )"
},
{
"code": null,
"e": 3265,
"s": 3168,
"text": "If we prefer a slide bar, we could simply switch a list of years to a tuple (min year, max year)"
},
{
"code": null,
"e": 3296,
"s": 3265,
"text": "interact(f, year=(1960, 2018))"
},
{
"code": null,
"e": 3420,
"s": 3296,
"text": "That’s it! Now we could efficiently go through the distribution each year to see if the distribution has changed over time."
},
{
"code": null,
"e": 3794,
"s": 3420,
"text": "Congratulations! You have learned how to utilize Python Widgets to create a slide bar and drop-down menu for efficient visualization. I encourage you to try this out with any of your favorite visualization tools such as Matplotlib, Seaborn. Just a small twist in your code can save you a huge amount of time to invest in other important tasks of your data science projects."
},
{
"code": null,
"e": 3873,
"s": 3794,
"text": "Feel free to fork and play with the code for this article in this Github repo."
},
{
"code": null,
"e": 4033,
"s": 3873,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Missing number in matrix | Practice | GeeksforGeeks | Given a matrix of size n x n such that it has only one 0, Find the number to be placed in place of the 0 such that sum of the numbers in every row, column and two diagonals become equal.
Note: Diagonals should be only of the form matrix[i][i] and matrix[i][n - i - 1].
Example 1:
Input: matrix = {{5, 5}, {5, 0}}
Output: 5
Explanation: The matrix is
5 5
5 0
Therefore If we place 5 instead of 0, all
the element of matrix will become 5.
Therefore row 5+5=10, column 5+5=10 and
diagonal 5+5=10, all are equal.
Example 2:
Input: matrix = {{1, 2, 0}, {3, 1, 2},
{2, 3, 1}}
Output: -1
Explanation: It is not possible to insert
an element in place of 0 so that the
condition is satisfied.thus result is -1.
Your Task:
You don't need to read or print anyhting. Your task is to complete the function MissingNo() which takes the matrix as input parameter and returns the number which should be placed in place of 0 such that the condition gets satisfied. If not possible return -1.
Expected Time Complexity: O(n * n)
Expected Space Complexity: O(2 * n)
Constraints:
1 <= n <= 100
1 <= elements in the matrix <= 109
-1
tolstoyl7 months ago
The first test case where your code
failed:Input:
2
0 1
2 1Its Correct output is:
2And Your Code's output is:
-1
This is obviously wrong, it is enough to take the sum of the first column to see it.
0
VENKTESH KUMAR1 year ago
VENKTESH KUMAR
very nice question it took 1 hr to solve the problem
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": 414,
"s": 226,
"text": "Given a matrix of size n x n such that it has only one 0, Find the number to be placed in place of the 0 such that sum of the numbers in every row, column and two diagonals become equal. "
},
{
"code": null,
"e": 498,
"s": 414,
"text": "Note: Diagonals should be only of the form matrix[i][i] and matrix[i][n - i - 1].\n "
},
{
"code": null,
"e": 509,
"s": 498,
"text": "Example 1:"
},
{
"code": null,
"e": 740,
"s": 509,
"text": "Input: matrix = {{5, 5}, {5, 0}}\nOutput: 5\nExplanation: The matrix is\n5 5\n5 0\nTherefore If we place 5 instead of 0, all\nthe element of matrix will become 5. \nTherefore row 5+5=10, column 5+5=10 and \ndiagonal 5+5=10, all are equal."
},
{
"code": null,
"e": 751,
"s": 740,
"text": "Example 2:"
},
{
"code": null,
"e": 939,
"s": 751,
"text": "Input: matrix = {{1, 2, 0}, {3, 1, 2}, \n{2, 3, 1}}\nOutput: -1\nExplanation: It is not possible to insert \nan element in place of 0 so that the \ncondition is satisfied.thus result is -1. \n\n"
},
{
"code": null,
"e": 1213,
"s": 939,
"text": "Your Task:\nYou don't need to read or print anyhting. Your task is to complete the function MissingNo() which takes the matrix as input parameter and returns the number which should be placed in place of 0 such that the condition gets satisfied. If not possible return -1.\n "
},
{
"code": null,
"e": 1286,
"s": 1213,
"text": "Expected Time Complexity: O(n * n)\nExpected Space Complexity: O(2 * n)\n "
},
{
"code": null,
"e": 1348,
"s": 1286,
"text": "Constraints:\n1 <= n <= 100\n1 <= elements in the matrix <= 109"
},
{
"code": null,
"e": 1351,
"s": 1348,
"text": "-1"
},
{
"code": null,
"e": 1372,
"s": 1351,
"text": "tolstoyl7 months ago"
},
{
"code": null,
"e": 1408,
"s": 1372,
"text": "The first test case where your code"
},
{
"code": null,
"e": 1422,
"s": 1408,
"text": "failed:Input:"
},
{
"code": null,
"e": 1425,
"s": 1422,
"text": "2 "
},
{
"code": null,
"e": 1430,
"s": 1425,
"text": "0 1 "
},
{
"code": null,
"e": 1456,
"s": 1430,
"text": "2 1Its Correct output is:"
},
{
"code": null,
"e": 1484,
"s": 1456,
"text": "2And Your Code's output is:"
},
{
"code": null,
"e": 1487,
"s": 1484,
"text": "-1"
},
{
"code": null,
"e": 1572,
"s": 1487,
"text": "This is obviously wrong, it is enough to take the sum of the first column to see it."
},
{
"code": null,
"e": 1574,
"s": 1572,
"text": "0"
},
{
"code": null,
"e": 1599,
"s": 1574,
"text": "VENKTESH KUMAR1 year ago"
},
{
"code": null,
"e": 1614,
"s": 1599,
"text": "VENKTESH KUMAR"
},
{
"code": null,
"e": 1667,
"s": 1614,
"text": "very nice question it took 1 hr to solve the problem"
},
{
"code": null,
"e": 1813,
"s": 1667,
"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": 1849,
"s": 1813,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 1859,
"s": 1849,
"text": "\nProblem\n"
},
{
"code": null,
"e": 1869,
"s": 1859,
"text": "\nContest\n"
},
{
"code": null,
"e": 1932,
"s": 1869,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2080,
"s": 1932,
"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": 2288,
"s": 2080,
"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": 2394,
"s": 2288,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Get the top most document from a MongoDB collection | To get the topmost document, use find() along with limit(). To fetch only a single document, consider using limit(1). Let us create a collection with documents −
> db.demo681.insertOne({_id:101,Name:"Chris"});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo681.insertOne({_id:102,Name:"Bob"});
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo681.insertOne({_id:103,Name:"David"});
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo681.insertOne({_id:104,Name:"Bob"});
{ "acknowledged" : true, "insertedId" : 104 }
> db.demo681.insertOne({_id:105,Name:"Sam"});
{ "acknowledged" : true, "insertedId" : 105 }
Display all documents from a collection with the help of find() method −
> db.demo681.find();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris" }
{ "_id" : 102, "Name" : "Bob" }
{ "_id" : 103, "Name" : "David" }
{ "_id" : 104, "Name" : "Bob" }
{ "_id" : 105, "Name" : "Sam" }
Following is the query to get the topmost element −
> db.demo681.find().limit(1);
This will produce the following output −
{ "_id" : 101, "Name" : "Chris" } | [
{
"code": null,
"e": 1224,
"s": 1062,
"text": "To get the topmost document, use find() along with limit(). To fetch only a single document, consider using limit(1). Let us create a collection with documents −"
},
{
"code": null,
"e": 1688,
"s": 1224,
"text": "> db.demo681.insertOne({_id:101,Name:\"Chris\"});\n{ \"acknowledged\" : true, \"insertedId\" : 101 }\n> db.demo681.insertOne({_id:102,Name:\"Bob\"});\n{ \"acknowledged\" : true, \"insertedId\" : 102 }\n> db.demo681.insertOne({_id:103,Name:\"David\"});\n{ \"acknowledged\" : true, \"insertedId\" : 103 }\n> db.demo681.insertOne({_id:104,Name:\"Bob\"});\n{ \"acknowledged\" : true, \"insertedId\" : 104 }\n> db.demo681.insertOne({_id:105,Name:\"Sam\"});\n{ \"acknowledged\" : true, \"insertedId\" : 105 }"
},
{
"code": null,
"e": 1761,
"s": 1688,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1782,
"s": 1761,
"text": "> db.demo681.find();"
},
{
"code": null,
"e": 1823,
"s": 1782,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1987,
"s": 1823,
"text": "{ \"_id\" : 101, \"Name\" : \"Chris\" }\n{ \"_id\" : 102, \"Name\" : \"Bob\" }\n{ \"_id\" : 103, \"Name\" : \"David\" }\n{ \"_id\" : 104, \"Name\" : \"Bob\" }\n{ \"_id\" : 105, \"Name\" : \"Sam\" }"
},
{
"code": null,
"e": 2039,
"s": 1987,
"text": "Following is the query to get the topmost element −"
},
{
"code": null,
"e": 2069,
"s": 2039,
"text": "> db.demo681.find().limit(1);"
},
{
"code": null,
"e": 2110,
"s": 2069,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2144,
"s": 2110,
"text": "{ \"_id\" : 101, \"Name\" : \"Chris\" }"
}
] |
Collect.js partition() Method - GeeksforGeeks | 30 Nov, 2020
The partition() method is used to separate the collection elements according to the given callback function. The first array containing those elements that satisfy the predicate (condition) and the second array contains the remaining elements.
Syntax:
collect(array).partition(callback)
Parameters: The collect() method takes one argument that is converted into the collection and then the partition() method is applied to it. The partition() method holds the callback function as a parameter.
Return Value: This method returns the collection elements with partition.
Module Installation: Install collect.js module using the following command from the root directory of your project:
npm install collect.js
The below example illustrates the partition() method in collect.js:
Example 1: Filename: index.js
Javascript
// Requiring the moduleconst collect = require('collect.js'); // Creating collection objectconst collection = collect([1, 2, 3, 5, 6, 8, 9, 11, 17, 22]); // Calling partition function on collectionconst [odd, even] = collection.partition( element => element % 2 != 0); // Printing the odd & even valuesconsole.log(odd.all());console.log(even.all());
Run the index.js file using the following command:
node index.js
Output:
[ 2, 6, 8, 22 ]
[ 1, 3, 5, 9, 11, 17 ]
Example 2: Filename: index.js
Javascript
// Requiring the moduleconst collect = require('collect.js'); // Creating collection objectconst collection = collect(['Welcome', 'Geeks', 'GFG', 'GeeksforGeeks']); // Calling partition function on // collection objectconst [short, long] = collection.partition( element => element.length < 6); // Printing short valuesconsole.log(short.all()); // Printing long valuesconsole.log(long.all());
Run the index.js file using the following command:
node index.js
Output:
[ 'Geeks', 'GFG' ]
[ 'Welcome', 'GeeksforGeeks' ]
Collect.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n30 Nov, 2020"
},
{
"code": null,
"e": 25464,
"s": 25220,
"text": "The partition() method is used to separate the collection elements according to the given callback function. The first array containing those elements that satisfy the predicate (condition) and the second array contains the remaining elements."
},
{
"code": null,
"e": 25472,
"s": 25464,
"text": "Syntax:"
},
{
"code": null,
"e": 25507,
"s": 25472,
"text": "collect(array).partition(callback)"
},
{
"code": null,
"e": 25714,
"s": 25507,
"text": "Parameters: The collect() method takes one argument that is converted into the collection and then the partition() method is applied to it. The partition() method holds the callback function as a parameter."
},
{
"code": null,
"e": 25788,
"s": 25714,
"text": "Return Value: This method returns the collection elements with partition."
},
{
"code": null,
"e": 25904,
"s": 25788,
"text": "Module Installation: Install collect.js module using the following command from the root directory of your project:"
},
{
"code": null,
"e": 25927,
"s": 25904,
"text": "npm install collect.js"
},
{
"code": null,
"e": 25995,
"s": 25927,
"text": "The below example illustrates the partition() method in collect.js:"
},
{
"code": null,
"e": 26025,
"s": 25995,
"text": "Example 1: Filename: index.js"
},
{
"code": null,
"e": 26036,
"s": 26025,
"text": "Javascript"
},
{
"code": "// Requiring the moduleconst collect = require('collect.js'); // Creating collection objectconst collection = collect([1, 2, 3, 5, 6, 8, 9, 11, 17, 22]); // Calling partition function on collectionconst [odd, even] = collection.partition( element => element % 2 != 0); // Printing the odd & even valuesconsole.log(odd.all());console.log(even.all());",
"e": 26396,
"s": 26036,
"text": null
},
{
"code": null,
"e": 26447,
"s": 26396,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 26461,
"s": 26447,
"text": "node index.js"
},
{
"code": null,
"e": 26469,
"s": 26461,
"text": "Output:"
},
{
"code": null,
"e": 26508,
"s": 26469,
"text": "[ 2, 6, 8, 22 ]\n[ 1, 3, 5, 9, 11, 17 ]"
},
{
"code": null,
"e": 26538,
"s": 26508,
"text": "Example 2: Filename: index.js"
},
{
"code": null,
"e": 26549,
"s": 26538,
"text": "Javascript"
},
{
"code": "// Requiring the moduleconst collect = require('collect.js'); // Creating collection objectconst collection = collect(['Welcome', 'Geeks', 'GFG', 'GeeksforGeeks']); // Calling partition function on // collection objectconst [short, long] = collection.partition( element => element.length < 6); // Printing short valuesconsole.log(short.all()); // Printing long valuesconsole.log(long.all());",
"e": 26952,
"s": 26549,
"text": null
},
{
"code": null,
"e": 27003,
"s": 26952,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 27017,
"s": 27003,
"text": "node index.js"
},
{
"code": null,
"e": 27025,
"s": 27017,
"text": "Output:"
},
{
"code": null,
"e": 27075,
"s": 27025,
"text": "[ 'Geeks', 'GFG' ]\n[ 'Welcome', 'GeeksforGeeks' ]"
},
{
"code": null,
"e": 27086,
"s": 27075,
"text": "Collect.js"
},
{
"code": null,
"e": 27097,
"s": 27086,
"text": "JavaScript"
},
{
"code": null,
"e": 27114,
"s": 27097,
"text": "Web Technologies"
},
{
"code": null,
"e": 27212,
"s": 27114,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27221,
"s": 27212,
"text": "Comments"
},
{
"code": null,
"e": 27234,
"s": 27221,
"text": "Old Comments"
},
{
"code": null,
"e": 27295,
"s": 27234,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27336,
"s": 27295,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27390,
"s": 27336,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27447,
"s": 27390,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 27509,
"s": 27447,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27551,
"s": 27509,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27584,
"s": 27551,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27646,
"s": 27584,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27689,
"s": 27646,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Fitting a Neural Network Using Randomized Optimization in Python | by Genevieve Hayes | Towards Data Science | Python’s mlrose package provides functionality for implementing some of the most popular randomization and search algorithms, and applying them to a range of different optimization problem domains.
In this tutorial, we will discuss how mlrose can be used to find the optimal weights for machine learning models, such as neural networks and regression models. That is, to solve the machine learning weight optimization problem.
This is the third in a series of three tutorials about using mlrose to solve randomized optimization problems. Part 1 can be found here and Part 2 can be found here.
For a number of different machine learning models, the process of fitting the model parameters involves finding the parameter values that minimize a pre-specified loss function for a given training set.
Examples of such models include neural networks, linear regression models and logistic regression models, and the optimal model weights for such models are typically found using methods such as gradient descent.
However, the problem of fitting the parameters (or weights) of a machine learning model can also be viewed as a continuous-state optimization problem, where the loss function takes the role of the fitness function, and the goal is to minimize this function.
By framing the problem this way, we can use any of the randomized optimization algorithms that are suited to continuous-state optimization problems to fit the model parameters.
mlrose contains built-in functionality for solving the weight optimization problem for three types of machine learning models: (standard) neural networks, linear regression models and logistic regression models. This is done using the NeuralNetwork(), LinearRegression()and LogisticRegression() classes respectively.
Each of these classes includes a fit method, which implements the three steps for solving an optimization problem defined in the previous tutorials, for a given training set. That is,
Define a fitness function object.Define an optimization problem object.Select and run a randomized optimization algorithm.
Define a fitness function object.
Define an optimization problem object.
Select and run a randomized optimization algorithm.
However, when fitting a machine learning model, finding the optimal model weights is merely a means to an end.
We want to find the optimal model weights so that we can use our fitted model to predict the labels of future observations as accurately as possible, not because we are actually interested in knowing the optimal weight values.
As a result, the above mentioned classes also include a predict method, which, if called after the fit method, will predict the labels for a given test set using the fitted model.
The steps involved in solving a machine learning weight optimization problem with mlrose are then, typically:
Initialize a machine learning weight optimization problem object.Find the optimal model weights for a given training set by calling the fit method of the object initialized in Step 1.Predict the labels for a test set by calling the predict method of the object initialized in Step 1.
Initialize a machine learning weight optimization problem object.
Find the optimal model weights for a given training set by calling the fit method of the object initialized in Step 1.
Predict the labels for a test set by calling the predict method of the object initialized in Step 1.
To fit the model weights, the user can choose between using either randomized hill climbing, simulated annealing, the genetic algorithm or gradient descent.
[In mlrose, the gradient descent algorithm is only available for use in solving the machine learning weight optimization problem and has been included primarily for benchmarking purposes, since this is one of the most common algorithms used in fitting neural networks and regression models.]
We will now work through an example to illustrate how mlrose can be used to fit a neural network and a regression model to a given dataset.
Before starting with the example, you will need to import the mlrose and Numpy Python packages.
import mlroseimport numpy as np
The Iris dataset is a famous multivariate classification dataset first presented in a 1936 research paper by statistician and biologist Ronald Fisher.
It contains 150 observations of three classes (species) of iris flowers (50 observations of each class), with each observation providing the sepal length, sepal width, petal length and petal width (i.e. the feature values), as well as the class label (i.e. the target value), of each flower under consideration.
The Iris dataset is included with Python’s sklearn package.
The feature values and label of the first observation in the dataset are shown below, along with the maximum and minimum values of each of the features and the unique label values:
The feature values for Obs 0 are: [5.1 3.5 1.4 0.2]The feature names are: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']The target value for Obs 0 is: 0The target name for Obs 0 is: setosaThe minimum values of the four features are: [4.3 2. 1. 0.1]The maximum values of the four features are: [7.9 4.4 6.9 2.5]The unique target values are: [0 1 2]
From this we can see that all features in the Iris data set are numeric, albeit with different ranges, and that the class labels have been represented by integers.
In the next few sections we will show how mlrose can be used to fit a neural network and a logistic regression model to this dataset, to predict the species of an iris flower given its feature values.
Before we can fit any sort of machine learning model to a dataset, it is necessary to manipulate our data into the form expected by mlrose.
Each of the three machine learning models supported by mlrose expect to receive feature data in the form of a Numpy array, with one row per observation and numeric features only (any categorical features must be one-hot encoded before passing to the machine learning models).
The models also expect to receive the target values as either: a list of numeric values (for regression data); a list of 0–1 indicator values (for binary classification data); or as a Numpy array of one-hot encoded labels, with one row per observation (for multi-class classification data).
In the case of the Iris dataset, all of our features are numeric, so no one-hot encoding is required. However, it is necessary to one-hot encode the class labels.
In keeping with standard machine learning practice, it is also necessary to split the data into training and test subsets, and since the range of the Iris data varies considerably from feature to feature, to standardize the values of our feature variables.
These pre-processing steps are implemented below:
Once the data has been pre-processed, fitting a neural network in mlrose simply involves following the steps listed above.
Suppose we wish to fit a neural network classifier to the Iris dataset with one hidden layer containing 2 nodes and a ReLU activation function (mlrose supports the ReLU, identity, sigmoid and tanh activation functions).
For this example, we will use the Randomized Hill Climbing algorithm to find the optimal weights, with a maximum of 1000 iterations of the algorithm and 100 attempts to find a better set of weights at each step.
We will also include a bias term; use a step size (learning rate) of 0.0001 (to find neighbors of the current set of weights); and limit our weights to being in the range -5 to 5 (to reduce the landscape over which the algorithm must search in order to find the optimal weights).
This model is initialized and fitted to our pre-processed data below:
Once the model is fitted, we can use it to predict the labels for our training and test sets, and use these predictions to assess the model’s training and test accuracy.
Training accuracy: 0.45Test accuracy: 0.533333333333
In this case, our model achieves training accuracy of 45% and test accuracy of 53.3%. These accuracy levels are better than if the labels were selected at random, but still leave room for improvement.
We can potentially improve on the accuracy of our model by tuning the parameters we set when initializing the neural network object. Suppose we decide to change the optimization algorithm to gradient descent, but leave all other model parameters unchanged.
Training accuracy: 0.625Test accuracy: 0.566666666667
This results in a 39% increase in training accuracy to 62.5%, but a much smaller increase in test accuracy to 56.7%.
Linear and logistic regression models are special cases of neural networks. A linear regression is a regression neural network with no hidden layers and an identity activation function, while a logistic regression is a classification neural network with no hidden layers and a sigmoid activation function.
As a result, we could fit either of these models to our data using the NeuralNetwork() class, with parameters set appropriately.
For example, suppose we wished to fit a logistic regression to the Iris data using the randomized hill climbing algorithm and all other parameters set as for the example in the previous section. We could do this by initializing a NeuralNetwork() object like so:
However, for convenience, mlrose provides the LinearRegression() and LogisticRegression() wrapper classes, which simplify model initialization.
In the Iris dataset example, we can, thus, initialize and fit our logistic regression model as follows:
Training accuracy: 0.191666666667Test accuracy: 0.0666666666667
This model achieves 19.2% training accuracy and 6.7% test accuracy, which is worse than if we predicted the labels by selecting values at random.
Nevertheless, as in the previous section, we can potentially improve model accuracy by tuning the parameters set at initialization.
Suppose we increase our learning rate to 0.01.
Training accuracy: 0.683333333333Test accuracy: 0.7
This results in significant improvements to both training and test accuracy, with training accuracy levels now reaching 68.3% and test accuracy levels reaching 70%.
In this tutorial we discussed how mlrose can be used to find the optimal weights of three types of machine learning models: neural networks, linear regression models and logistic regression models.
Applying randomized optimization algorithms to the machine learning weight optimization problem is most certainly not the most common approach to solving this problem. However, it serves to demonstrate the versatility of the mlrose package and of randomized optimization algorithms in general.
To learn more about mlrose, visit the GitHub repository for this package, available here. | [
{
"code": null,
"e": 370,
"s": 172,
"text": "Python’s mlrose package provides functionality for implementing some of the most popular randomization and search algorithms, and applying them to a range of different optimization problem domains."
},
{
"code": null,
"e": 599,
"s": 370,
"text": "In this tutorial, we will discuss how mlrose can be used to find the optimal weights for machine learning models, such as neural networks and regression models. That is, to solve the machine learning weight optimization problem."
},
{
"code": null,
"e": 765,
"s": 599,
"text": "This is the third in a series of three tutorials about using mlrose to solve randomized optimization problems. Part 1 can be found here and Part 2 can be found here."
},
{
"code": null,
"e": 968,
"s": 765,
"text": "For a number of different machine learning models, the process of fitting the model parameters involves finding the parameter values that minimize a pre-specified loss function for a given training set."
},
{
"code": null,
"e": 1180,
"s": 968,
"text": "Examples of such models include neural networks, linear regression models and logistic regression models, and the optimal model weights for such models are typically found using methods such as gradient descent."
},
{
"code": null,
"e": 1438,
"s": 1180,
"text": "However, the problem of fitting the parameters (or weights) of a machine learning model can also be viewed as a continuous-state optimization problem, where the loss function takes the role of the fitness function, and the goal is to minimize this function."
},
{
"code": null,
"e": 1615,
"s": 1438,
"text": "By framing the problem this way, we can use any of the randomized optimization algorithms that are suited to continuous-state optimization problems to fit the model parameters."
},
{
"code": null,
"e": 1932,
"s": 1615,
"text": "mlrose contains built-in functionality for solving the weight optimization problem for three types of machine learning models: (standard) neural networks, linear regression models and logistic regression models. This is done using the NeuralNetwork(), LinearRegression()and LogisticRegression() classes respectively."
},
{
"code": null,
"e": 2116,
"s": 1932,
"text": "Each of these classes includes a fit method, which implements the three steps for solving an optimization problem defined in the previous tutorials, for a given training set. That is,"
},
{
"code": null,
"e": 2239,
"s": 2116,
"text": "Define a fitness function object.Define an optimization problem object.Select and run a randomized optimization algorithm."
},
{
"code": null,
"e": 2273,
"s": 2239,
"text": "Define a fitness function object."
},
{
"code": null,
"e": 2312,
"s": 2273,
"text": "Define an optimization problem object."
},
{
"code": null,
"e": 2364,
"s": 2312,
"text": "Select and run a randomized optimization algorithm."
},
{
"code": null,
"e": 2475,
"s": 2364,
"text": "However, when fitting a machine learning model, finding the optimal model weights is merely a means to an end."
},
{
"code": null,
"e": 2702,
"s": 2475,
"text": "We want to find the optimal model weights so that we can use our fitted model to predict the labels of future observations as accurately as possible, not because we are actually interested in knowing the optimal weight values."
},
{
"code": null,
"e": 2882,
"s": 2702,
"text": "As a result, the above mentioned classes also include a predict method, which, if called after the fit method, will predict the labels for a given test set using the fitted model."
},
{
"code": null,
"e": 2992,
"s": 2882,
"text": "The steps involved in solving a machine learning weight optimization problem with mlrose are then, typically:"
},
{
"code": null,
"e": 3276,
"s": 2992,
"text": "Initialize a machine learning weight optimization problem object.Find the optimal model weights for a given training set by calling the fit method of the object initialized in Step 1.Predict the labels for a test set by calling the predict method of the object initialized in Step 1."
},
{
"code": null,
"e": 3342,
"s": 3276,
"text": "Initialize a machine learning weight optimization problem object."
},
{
"code": null,
"e": 3461,
"s": 3342,
"text": "Find the optimal model weights for a given training set by calling the fit method of the object initialized in Step 1."
},
{
"code": null,
"e": 3562,
"s": 3461,
"text": "Predict the labels for a test set by calling the predict method of the object initialized in Step 1."
},
{
"code": null,
"e": 3719,
"s": 3562,
"text": "To fit the model weights, the user can choose between using either randomized hill climbing, simulated annealing, the genetic algorithm or gradient descent."
},
{
"code": null,
"e": 4011,
"s": 3719,
"text": "[In mlrose, the gradient descent algorithm is only available for use in solving the machine learning weight optimization problem and has been included primarily for benchmarking purposes, since this is one of the most common algorithms used in fitting neural networks and regression models.]"
},
{
"code": null,
"e": 4151,
"s": 4011,
"text": "We will now work through an example to illustrate how mlrose can be used to fit a neural network and a regression model to a given dataset."
},
{
"code": null,
"e": 4247,
"s": 4151,
"text": "Before starting with the example, you will need to import the mlrose and Numpy Python packages."
},
{
"code": null,
"e": 4279,
"s": 4247,
"text": "import mlroseimport numpy as np"
},
{
"code": null,
"e": 4430,
"s": 4279,
"text": "The Iris dataset is a famous multivariate classification dataset first presented in a 1936 research paper by statistician and biologist Ronald Fisher."
},
{
"code": null,
"e": 4742,
"s": 4430,
"text": "It contains 150 observations of three classes (species) of iris flowers (50 observations of each class), with each observation providing the sepal length, sepal width, petal length and petal width (i.e. the feature values), as well as the class label (i.e. the target value), of each flower under consideration."
},
{
"code": null,
"e": 4802,
"s": 4742,
"text": "The Iris dataset is included with Python’s sklearn package."
},
{
"code": null,
"e": 4983,
"s": 4802,
"text": "The feature values and label of the first observation in the dataset are shown below, along with the maximum and minimum values of each of the features and the unique label values:"
},
{
"code": null,
"e": 5371,
"s": 4983,
"text": "The feature values for Obs 0 are: [5.1 3.5 1.4 0.2]The feature names are: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']The target value for Obs 0 is: 0The target name for Obs 0 is: setosaThe minimum values of the four features are: [4.3 2. 1. 0.1]The maximum values of the four features are: [7.9 4.4 6.9 2.5]The unique target values are: [0 1 2]"
},
{
"code": null,
"e": 5535,
"s": 5371,
"text": "From this we can see that all features in the Iris data set are numeric, albeit with different ranges, and that the class labels have been represented by integers."
},
{
"code": null,
"e": 5736,
"s": 5535,
"text": "In the next few sections we will show how mlrose can be used to fit a neural network and a logistic regression model to this dataset, to predict the species of an iris flower given its feature values."
},
{
"code": null,
"e": 5876,
"s": 5736,
"text": "Before we can fit any sort of machine learning model to a dataset, it is necessary to manipulate our data into the form expected by mlrose."
},
{
"code": null,
"e": 6152,
"s": 5876,
"text": "Each of the three machine learning models supported by mlrose expect to receive feature data in the form of a Numpy array, with one row per observation and numeric features only (any categorical features must be one-hot encoded before passing to the machine learning models)."
},
{
"code": null,
"e": 6443,
"s": 6152,
"text": "The models also expect to receive the target values as either: a list of numeric values (for regression data); a list of 0–1 indicator values (for binary classification data); or as a Numpy array of one-hot encoded labels, with one row per observation (for multi-class classification data)."
},
{
"code": null,
"e": 6606,
"s": 6443,
"text": "In the case of the Iris dataset, all of our features are numeric, so no one-hot encoding is required. However, it is necessary to one-hot encode the class labels."
},
{
"code": null,
"e": 6863,
"s": 6606,
"text": "In keeping with standard machine learning practice, it is also necessary to split the data into training and test subsets, and since the range of the Iris data varies considerably from feature to feature, to standardize the values of our feature variables."
},
{
"code": null,
"e": 6913,
"s": 6863,
"text": "These pre-processing steps are implemented below:"
},
{
"code": null,
"e": 7036,
"s": 6913,
"text": "Once the data has been pre-processed, fitting a neural network in mlrose simply involves following the steps listed above."
},
{
"code": null,
"e": 7256,
"s": 7036,
"text": "Suppose we wish to fit a neural network classifier to the Iris dataset with one hidden layer containing 2 nodes and a ReLU activation function (mlrose supports the ReLU, identity, sigmoid and tanh activation functions)."
},
{
"code": null,
"e": 7468,
"s": 7256,
"text": "For this example, we will use the Randomized Hill Climbing algorithm to find the optimal weights, with a maximum of 1000 iterations of the algorithm and 100 attempts to find a better set of weights at each step."
},
{
"code": null,
"e": 7748,
"s": 7468,
"text": "We will also include a bias term; use a step size (learning rate) of 0.0001 (to find neighbors of the current set of weights); and limit our weights to being in the range -5 to 5 (to reduce the landscape over which the algorithm must search in order to find the optimal weights)."
},
{
"code": null,
"e": 7818,
"s": 7748,
"text": "This model is initialized and fitted to our pre-processed data below:"
},
{
"code": null,
"e": 7988,
"s": 7818,
"text": "Once the model is fitted, we can use it to predict the labels for our training and test sets, and use these predictions to assess the model’s training and test accuracy."
},
{
"code": null,
"e": 8041,
"s": 7988,
"text": "Training accuracy: 0.45Test accuracy: 0.533333333333"
},
{
"code": null,
"e": 8242,
"s": 8041,
"text": "In this case, our model achieves training accuracy of 45% and test accuracy of 53.3%. These accuracy levels are better than if the labels were selected at random, but still leave room for improvement."
},
{
"code": null,
"e": 8499,
"s": 8242,
"text": "We can potentially improve on the accuracy of our model by tuning the parameters we set when initializing the neural network object. Suppose we decide to change the optimization algorithm to gradient descent, but leave all other model parameters unchanged."
},
{
"code": null,
"e": 8553,
"s": 8499,
"text": "Training accuracy: 0.625Test accuracy: 0.566666666667"
},
{
"code": null,
"e": 8670,
"s": 8553,
"text": "This results in a 39% increase in training accuracy to 62.5%, but a much smaller increase in test accuracy to 56.7%."
},
{
"code": null,
"e": 8976,
"s": 8670,
"text": "Linear and logistic regression models are special cases of neural networks. A linear regression is a regression neural network with no hidden layers and an identity activation function, while a logistic regression is a classification neural network with no hidden layers and a sigmoid activation function."
},
{
"code": null,
"e": 9105,
"s": 8976,
"text": "As a result, we could fit either of these models to our data using the NeuralNetwork() class, with parameters set appropriately."
},
{
"code": null,
"e": 9367,
"s": 9105,
"text": "For example, suppose we wished to fit a logistic regression to the Iris data using the randomized hill climbing algorithm and all other parameters set as for the example in the previous section. We could do this by initializing a NeuralNetwork() object like so:"
},
{
"code": null,
"e": 9511,
"s": 9367,
"text": "However, for convenience, mlrose provides the LinearRegression() and LogisticRegression() wrapper classes, which simplify model initialization."
},
{
"code": null,
"e": 9615,
"s": 9511,
"text": "In the Iris dataset example, we can, thus, initialize and fit our logistic regression model as follows:"
},
{
"code": null,
"e": 9679,
"s": 9615,
"text": "Training accuracy: 0.191666666667Test accuracy: 0.0666666666667"
},
{
"code": null,
"e": 9825,
"s": 9679,
"text": "This model achieves 19.2% training accuracy and 6.7% test accuracy, which is worse than if we predicted the labels by selecting values at random."
},
{
"code": null,
"e": 9957,
"s": 9825,
"text": "Nevertheless, as in the previous section, we can potentially improve model accuracy by tuning the parameters set at initialization."
},
{
"code": null,
"e": 10004,
"s": 9957,
"text": "Suppose we increase our learning rate to 0.01."
},
{
"code": null,
"e": 10056,
"s": 10004,
"text": "Training accuracy: 0.683333333333Test accuracy: 0.7"
},
{
"code": null,
"e": 10221,
"s": 10056,
"text": "This results in significant improvements to both training and test accuracy, with training accuracy levels now reaching 68.3% and test accuracy levels reaching 70%."
},
{
"code": null,
"e": 10419,
"s": 10221,
"text": "In this tutorial we discussed how mlrose can be used to find the optimal weights of three types of machine learning models: neural networks, linear regression models and logistic regression models."
},
{
"code": null,
"e": 10713,
"s": 10419,
"text": "Applying randomized optimization algorithms to the machine learning weight optimization problem is most certainly not the most common approach to solving this problem. However, it serves to demonstrate the versatility of the mlrose package and of randomized optimization algorithms in general."
}
] |
C++ Program to compare two string using pointers - GeeksforGeeks | 04 Nov, 2018
Given two strings, compare the strings using pointers
Examples:
Input: str1 = geeks, str2 = geeks
Output: Both are equal
Input: str1 = hello, str2 = hellu
Output: Both are not equal
As their length are same but characters are different
The idea is to dereference given pointers, compare values and advance both of them.
Program:
// C++ Program to compare two strings using// Pointers#include <iostream>using namespace std; // Method to compare two string// using pointerbool compare(char *str1, char *str2){ while (*str1 == *str2) { if (*str1 == '\0' && *str2 == '\0') return true; str1++; str2++; } return false;} int main(){ // Declare and Initialize two strings char str1[] = "geeks"; char str2[] = "geeks"; if (compare(str1, str2) == 1) cout << str1 << " " << str2 << " are Equal"; else cout << str1 << " " << str2 << " are not Equal";}
geeks geeks are Equal
cpp-pointer
cpp-string
C++ Programs
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Handling the Divide by Zero Exception in C++
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 24448,
"s": 24420,
"text": "\n04 Nov, 2018"
},
{
"code": null,
"e": 24502,
"s": 24448,
"text": "Given two strings, compare the strings using pointers"
},
{
"code": null,
"e": 24512,
"s": 24502,
"text": "Examples:"
},
{
"code": null,
"e": 24685,
"s": 24512,
"text": "Input: str1 = geeks, str2 = geeks\nOutput: Both are equal\n\nInput: str1 = hello, str2 = hellu\nOutput: Both are not equal\nAs their length are same but characters are different"
},
{
"code": null,
"e": 24769,
"s": 24685,
"text": "The idea is to dereference given pointers, compare values and advance both of them."
},
{
"code": null,
"e": 24778,
"s": 24769,
"text": "Program:"
},
{
"code": "// C++ Program to compare two strings using// Pointers#include <iostream>using namespace std; // Method to compare two string// using pointerbool compare(char *str1, char *str2){ while (*str1 == *str2) { if (*str1 == '\\0' && *str2 == '\\0') return true; str1++; str2++; } return false;} int main(){ // Declare and Initialize two strings char str1[] = \"geeks\"; char str2[] = \"geeks\"; if (compare(str1, str2) == 1) cout << str1 << \" \" << str2 << \" are Equal\"; else cout << str1 << \" \" << str2 << \" are not Equal\";}",
"e": 25377,
"s": 24778,
"text": null
},
{
"code": null,
"e": 25400,
"s": 25377,
"text": "geeks geeks are Equal\n"
},
{
"code": null,
"e": 25412,
"s": 25400,
"text": "cpp-pointer"
},
{
"code": null,
"e": 25423,
"s": 25412,
"text": "cpp-string"
},
{
"code": null,
"e": 25436,
"s": 25423,
"text": "C++ Programs"
},
{
"code": null,
"e": 25444,
"s": 25436,
"text": "Strings"
},
{
"code": null,
"e": 25463,
"s": 25444,
"text": "Technical Scripter"
},
{
"code": null,
"e": 25471,
"s": 25463,
"text": "Strings"
},
{
"code": null,
"e": 25569,
"s": 25471,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25578,
"s": 25569,
"text": "Comments"
},
{
"code": null,
"e": 25591,
"s": 25578,
"text": "Old Comments"
},
{
"code": null,
"e": 25632,
"s": 25591,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 25653,
"s": 25632,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 25712,
"s": 25653,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 25724,
"s": 25712,
"text": "cout in C++"
},
{
"code": null,
"e": 25769,
"s": 25724,
"text": "Handling the Divide by Zero Exception in C++"
},
{
"code": null,
"e": 25794,
"s": 25769,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 25840,
"s": 25794,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 25874,
"s": 25840,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 25889,
"s": 25874,
"text": "C++ Data Types"
}
] |
MySQL IN Operator | The IN operator allows you to specify multiple values in a
WHERE clause.
The IN operator is a shorthand for multiple
OR conditions.
or:
The table below shows the complete "Customers" table from the Northwind sample database:
The following SQL statement selects all customers that are located in "Germany", "France"
or "UK":
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
The following SQL statement selects all customers that are from the same
countries as the suppliers:
Use the IN operator to select all the records where Country is either "Norway" or "France".
SELECT * FROM Customers
'France';
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 74,
"s": 0,
"text": "The IN operator allows you to specify multiple values in a \nWHERE clause."
},
{
"code": null,
"e": 134,
"s": 74,
"text": "The IN operator is a shorthand for multiple \nOR conditions."
},
{
"code": null,
"e": 138,
"s": 134,
"text": "or:"
},
{
"code": null,
"e": 227,
"s": 138,
"text": "The table below shows the complete \"Customers\" table from the Northwind sample database:"
},
{
"code": null,
"e": 327,
"s": 227,
"text": "The following SQL statement selects all customers that are located in \"Germany\", \"France\" \nor \"UK\":"
},
{
"code": null,
"e": 430,
"s": 327,
"text": "The following SQL statement selects all customers that are NOT located in \"Germany\", \"France\" or \"UK\":"
},
{
"code": null,
"e": 532,
"s": 430,
"text": "The following SQL statement selects all customers that are from the same \ncountries as the suppliers:"
},
{
"code": null,
"e": 624,
"s": 532,
"text": "Use the IN operator to select all the records where Country is either \"Norway\" or \"France\"."
},
{
"code": null,
"e": 661,
"s": 624,
"text": "SELECT * FROM Customers\n 'France';\n"
},
{
"code": null,
"e": 680,
"s": 661,
"text": "Start the Exercise"
},
{
"code": null,
"e": 713,
"s": 680,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 755,
"s": 713,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 862,
"s": 755,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 881,
"s": 862,
"text": "help@w3schools.com"
}
] |
Convert Infix to Postfix Expression | Infix expressions are readable and solvable by humans. We can easily distinguish the order of operators, and also can use the parenthesis to solve that part first during solving mathematical expressions. The computer cannot differentiate the operators and parenthesis easily, that’s why postfix conversion is needed.
To convert infix expression to postfix expression, we will use the stack data structure. By scanning the infix expression from left to right, when we will get any operand, simply add them to the postfix form, and for the operator and parenthesis, add them in the stack maintaining the precedence of them.
Note: Here we will consider only {+, −,∗,/, ^} operators, other operators are neglected.
Input:
The infix expression. x^y/(5*z)+2
Output:
Postfix Form Is: xy^5z*/2+
infixToPostfix(infix)
Input − Infix expression.
Output − Convert infix expression to postfix form.
Begin
initially push some special character say # into the stack
for each character ch from infix expression, do
if ch is alphanumeric character, then
add ch to postfix expression
else if ch = opening parenthesis (, then
push ( into stack
else if ch = ^, then //exponential operator of higher precedence
push ^ into the stack
else if ch = closing parenthesis ), then
while stack is not empty and stack top ≠ (,
do pop and add item from stack to postfix expression
done
pop ( also from the stack
else
while stack is not empty AND precedence of ch <= precedence of stack top element, do
pop and add into postfix expression
done
push the newly coming character.
done
while the stack contains some remaining characters, do
pop and add to the postfix expression
done
return postfix
End
#include<iostream>
#include<stack>
#include<locale> //for function isalnum()
using namespace std;
int preced(char ch) {
if(ch == '+' || ch == '-') {
return 1; //Precedence of + or - is 1
}else if(ch == '*' || ch == '/') {
return 2; //Precedence of * or / is 2
}else if(ch == '^') {
return 3; //Precedence of ^ is 3
}else {
return 0;
}
}
string inToPost(string infix ) {
stack<char> stk;
stk.push('#'); //add some extra character to avoid underflow
string postfix = ""; //initially the postfix string is empty
string::iterator it;
for(it = infix.begin(); it!=infix.end(); it++) {
if(isalnum(char(*it)))
postfix += *it; //add to postfix when character is letter or number
else if(*it == '(')
stk.push('(');
else if(*it == '^')
stk.push('^');
else if(*it == ')') {
while(stk.top() != '#' && stk.top() != '(') {
postfix += stk.top(); //store and pop until ( has found
stk.pop();
}
stk.pop(); //remove the '(' from stack
}else {
if(preced(*it) > preced(stk.top()))
stk.push(*it); //push if precedence is high
else {
while(stk.top() != '#' && preced(*it) <= preced(stk.top())) {
postfix += stk.top(); //store and pop until higher precedence is found
stk.pop();
}
stk.push(*it);
}
}
}
while(stk.top() != '#') {
postfix += stk.top(); //store and pop until stack is not empty.
stk.pop();
}
return postfix;
}
int main() {
string infix = "x^y/(5*z)+2";
cout << "Postfix Form Is: " << inToPost(infix) << endl;
}
Postfix Form Is: xy^5z*/2+ | [
{
"code": null,
"e": 1379,
"s": 1062,
"text": "Infix expressions are readable and solvable by humans. We can easily distinguish the order of operators, and also can use the parenthesis to solve that part first during solving mathematical expressions. The computer cannot differentiate the operators and parenthesis easily, that’s why postfix conversion is needed."
},
{
"code": null,
"e": 1684,
"s": 1379,
"text": "To convert infix expression to postfix expression, we will use the stack data structure. By scanning the infix expression from left to right, when we will get any operand, simply add them to the postfix form, and for the operator and parenthesis, add them in the stack maintaining the precedence of them."
},
{
"code": null,
"e": 1773,
"s": 1684,
"text": "Note: Here we will consider only {+, −,∗,/, ^} operators, other operators are neglected."
},
{
"code": null,
"e": 1849,
"s": 1773,
"text": "Input:\nThe infix expression. x^y/(5*z)+2\nOutput:\nPostfix Form Is: xy^5z*/2+"
},
{
"code": null,
"e": 1871,
"s": 1849,
"text": "infixToPostfix(infix)"
},
{
"code": null,
"e": 1897,
"s": 1871,
"text": "Input − Infix expression."
},
{
"code": null,
"e": 1948,
"s": 1897,
"text": "Output − Convert infix expression to postfix form."
},
{
"code": null,
"e": 2903,
"s": 1948,
"text": "Begin\n initially push some special character say # into the stack\n for each character ch from infix expression, do\n if ch is alphanumeric character, then\n add ch to postfix expression\n else if ch = opening parenthesis (, then\n push ( into stack\n else if ch = ^, then //exponential operator of higher precedence\n push ^ into the stack\n else if ch = closing parenthesis ), then\n while stack is not empty and stack top ≠ (,\n do pop and add item from stack to postfix expression\n done\n\n pop ( also from the stack\n else\n while stack is not empty AND precedence of ch <= precedence of stack top element, do\n pop and add into postfix expression\n done\n\n push the newly coming character.\n done\n\n while the stack contains some remaining characters, do\n pop and add to the postfix expression\n done\n return postfix\nEnd"
},
{
"code": null,
"e": 4702,
"s": 2903,
"text": "#include<iostream>\n#include<stack>\n#include<locale> //for function isalnum()\nusing namespace std;\n\nint preced(char ch) {\n if(ch == '+' || ch == '-') {\n return 1; //Precedence of + or - is 1\n }else if(ch == '*' || ch == '/') {\n return 2; //Precedence of * or / is 2\n }else if(ch == '^') {\n return 3; //Precedence of ^ is 3\n }else {\n return 0;\n }\n}\n\nstring inToPost(string infix ) {\n stack<char> stk;\n stk.push('#'); //add some extra character to avoid underflow\n string postfix = \"\"; //initially the postfix string is empty\n string::iterator it;\n\n for(it = infix.begin(); it!=infix.end(); it++) {\n if(isalnum(char(*it)))\n postfix += *it; //add to postfix when character is letter or number\n else if(*it == '(')\n stk.push('(');\n else if(*it == '^')\n stk.push('^');\n else if(*it == ')') {\n while(stk.top() != '#' && stk.top() != '(') {\n postfix += stk.top(); //store and pop until ( has found\n stk.pop();\n }\n stk.pop(); //remove the '(' from stack\n }else {\n if(preced(*it) > preced(stk.top()))\n stk.push(*it); //push if precedence is high\n else {\n while(stk.top() != '#' && preced(*it) <= preced(stk.top())) {\n postfix += stk.top(); //store and pop until higher precedence is found\n stk.pop();\n }\n stk.push(*it);\n }\n }\n }\n\n while(stk.top() != '#') {\n postfix += stk.top(); //store and pop until stack is not empty.\n stk.pop();\n }\n\n return postfix;\n}\n\nint main() {\n string infix = \"x^y/(5*z)+2\";\n cout << \"Postfix Form Is: \" << inToPost(infix) << endl;\n}"
},
{
"code": null,
"e": 4729,
"s": 4702,
"text": "Postfix Form Is: xy^5z*/2+"
}
] |
FROM_UNIXTIME() function in MySQL - GeeksforGeeks | 22 Dec, 2020
FROM_UNIXTIME() :This function in MySQL helps to return date /DateTime representation of a Unix timestamp. The format of returning value will be ‘YYYY-MM-DD HH:MM:SS’ or ‘YYYYMMDDHHMMSS’, depending on the context of the function.
Syntax :
FROM_UNIXTIME(unix_timestamp, format)
Parameters :The function can accept two arguments as follows.
unix_timestamp –It is an internal timestamp value and it’s value can be produced by UNIX_TIMESTAMP() function.
format –The way in which the resulting value will be formatted
Result :The function will return date /DateTime representation of a Unix timestamp. And the format of returning value will be ‘YYYY-MM-DD HH:MM:SS’ or ‘YYYYMMDDHHMMSS’, depending on the context of the function.
Example-1 :Working of FROM_UNIXTIME() function with one parameter.
SELECT FROM_UNIXTIME(599462400)
AS Unix;
Output :
Unix
Example-2 :Working of FROM_UNIXTIME() function with fractional seconds.
SELECT FROM_UNIXTIME(599462445.99999)
AS Unix;
Output :
Unix
Example-3 :Working of FROM_UNIXTIME() function when both parameters are passed.
When format is ‘%W, %D %M %Y’ –SELECT FROM_UNIXTIME(799462445, '%W, %D %M %Y')
AS Unix;Output :UnixTuesday, 2nd May 1995
SELECT FROM_UNIXTIME(799462445, '%W, %D %M %Y')
AS Unix;
Output :
Unix
When format is ‘%h:%i %p, %D %M %Y’ –SELECT FROM_UNIXTIME(799462445, '%h:%i %p, %D %M %Y')
AS Unix;Output :Unix06:54 PM, 2nd May 1995
SELECT FROM_UNIXTIME(799462445, '%h:%i %p, %D %M %Y')
AS Unix;
Output :
Unix
Example-4 :Working of FROM_UNIXTIME() function in Numeric context.
SELECT
FROM_UNIXTIME(846562400) As 'String_form',
FROM_UNIXTIME(846562400) + 1 As 'Numeric_form';
Output :
DBMS-SQL
mysql
Technical Scripter 2020
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?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
SQL Query to Convert VARCHAR to INT
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 - SELECT from Multiple Tables with MS SQL Server
SQL Query to Delete Duplicate Rows | [
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n22 Dec, 2020"
},
{
"code": null,
"e": 24498,
"s": 24268,
"text": "FROM_UNIXTIME() :This function in MySQL helps to return date /DateTime representation of a Unix timestamp. The format of returning value will be ‘YYYY-MM-DD HH:MM:SS’ or ‘YYYYMMDDHHMMSS’, depending on the context of the function."
},
{
"code": null,
"e": 24507,
"s": 24498,
"text": "Syntax :"
},
{
"code": null,
"e": 24545,
"s": 24507,
"text": "FROM_UNIXTIME(unix_timestamp, format)"
},
{
"code": null,
"e": 24607,
"s": 24545,
"text": "Parameters :The function can accept two arguments as follows."
},
{
"code": null,
"e": 24718,
"s": 24607,
"text": "unix_timestamp –It is an internal timestamp value and it’s value can be produced by UNIX_TIMESTAMP() function."
},
{
"code": null,
"e": 24781,
"s": 24718,
"text": "format –The way in which the resulting value will be formatted"
},
{
"code": null,
"e": 24992,
"s": 24781,
"text": "Result :The function will return date /DateTime representation of a Unix timestamp. And the format of returning value will be ‘YYYY-MM-DD HH:MM:SS’ or ‘YYYYMMDDHHMMSS’, depending on the context of the function."
},
{
"code": null,
"e": 25059,
"s": 24992,
"text": "Example-1 :Working of FROM_UNIXTIME() function with one parameter."
},
{
"code": null,
"e": 25101,
"s": 25059,
"text": "SELECT FROM_UNIXTIME(599462400) \nAS Unix;"
},
{
"code": null,
"e": 25110,
"s": 25101,
"text": "Output :"
},
{
"code": null,
"e": 25115,
"s": 25110,
"text": "Unix"
},
{
"code": null,
"e": 25187,
"s": 25115,
"text": "Example-2 :Working of FROM_UNIXTIME() function with fractional seconds."
},
{
"code": null,
"e": 25235,
"s": 25187,
"text": "SELECT FROM_UNIXTIME(599462445.99999) \nAS Unix;"
},
{
"code": null,
"e": 25244,
"s": 25235,
"text": "Output :"
},
{
"code": null,
"e": 25249,
"s": 25244,
"text": "Unix"
},
{
"code": null,
"e": 25329,
"s": 25249,
"text": "Example-3 :Working of FROM_UNIXTIME() function when both parameters are passed."
},
{
"code": null,
"e": 25451,
"s": 25329,
"text": "When format is ‘%W, %D %M %Y’ –SELECT FROM_UNIXTIME(799462445, '%W, %D %M %Y') \nAS Unix;Output :UnixTuesday, 2nd May 1995"
},
{
"code": null,
"e": 25509,
"s": 25451,
"text": "SELECT FROM_UNIXTIME(799462445, '%W, %D %M %Y') \nAS Unix;"
},
{
"code": null,
"e": 25518,
"s": 25509,
"text": "Output :"
},
{
"code": null,
"e": 25523,
"s": 25518,
"text": "Unix"
},
{
"code": null,
"e": 25658,
"s": 25523,
"text": "When format is ‘%h:%i %p, %D %M %Y’ –SELECT FROM_UNIXTIME(799462445, '%h:%i %p, %D %M %Y') \nAS Unix;Output :Unix06:54 PM, 2nd May 1995"
},
{
"code": null,
"e": 25722,
"s": 25658,
"text": "SELECT FROM_UNIXTIME(799462445, '%h:%i %p, %D %M %Y') \nAS Unix;"
},
{
"code": null,
"e": 25731,
"s": 25722,
"text": "Output :"
},
{
"code": null,
"e": 25736,
"s": 25731,
"text": "Unix"
},
{
"code": null,
"e": 25803,
"s": 25736,
"text": "Example-4 :Working of FROM_UNIXTIME() function in Numeric context."
},
{
"code": null,
"e": 25903,
"s": 25803,
"text": "SELECT \nFROM_UNIXTIME(846562400) As 'String_form',\nFROM_UNIXTIME(846562400) + 1 As 'Numeric_form';"
},
{
"code": null,
"e": 25912,
"s": 25903,
"text": "Output :"
},
{
"code": null,
"e": 25921,
"s": 25912,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 25927,
"s": 25921,
"text": "mysql"
},
{
"code": null,
"e": 25951,
"s": 25927,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 25955,
"s": 25951,
"text": "SQL"
},
{
"code": null,
"e": 25959,
"s": 25955,
"text": "SQL"
},
{
"code": null,
"e": 26057,
"s": 25959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26123,
"s": 26057,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26155,
"s": 26123,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26233,
"s": 26155,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26250,
"s": 26233,
"text": "SQL using Python"
},
{
"code": null,
"e": 26265,
"s": 26250,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 26301,
"s": 26265,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 26367,
"s": 26301,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 26429,
"s": 26367,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
},
{
"code": null,
"e": 26482,
"s": 26429,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
] |
Exploratory Data Analysis: A Practical Guide and Template for Structured Data | by Jiahao Weng | Towards Data Science | Very often, it is not the drawing that is most difficult, but rather what to draw on a blank white piece of paper that stumps people.
Similarly for data science, one may wonder how to get started after receiving a dataset. This is where Exploratory Data Analysis (EDA) comes to the rescue.
According to Wikipedia, EDA “is an approach to analyzing datasets to summarize their main characteristics, often with visual methods”. In my own words, it is about knowing your data, gaining a certain amount of familiarity with the data, before one starts to extract insights from it.
Since EDA is such a crucial initial step for all data science projects, the lazy me decided to write a code template for performing EDA on structured datasets. The idea is to spend less time coding and focus more on the analysis of data itself. Scroll down to the bottom for the link to the code, but do read on to find out more about EDA and understand what the code does.
Before we delve into EDA, it is important to first get a sense of where EDA fits in the whole data science process.
With reference to the process chart from Wikipedia, after the data has been collected, it undergoes some processing before being cleaned and EDA is then performed. Notice that after EDA, we may go back to processing and cleaning of data, i.e., this can be an iterative process. Subsequently, we can then use the cleaned dataset and knowledge from EDA to perform modelling and reporting.
We can, therefore, understand the objectives of EDA as such:
To gain an understanding of data and find clues from the data,
to formulate assumptions and hypothesis for our modelling; andto check the quality of data for further processing and cleaning if necessary.
to formulate assumptions and hypothesis for our modelling; and
to check the quality of data for further processing and cleaning if necessary.
To better illustrate the concept of EDA, we shall be using the Rossmann store sales “train.csv” data from Kaggle. Keeping in mind that the problem statement is to forecast store sales, our EDA objectives are, therefore:
To check for features that can help in forecasting sales; andTo check for anomalies or outliers that may impact our forecasting model.
To check for features that can help in forecasting sales; and
To check for anomalies or outliers that may impact our forecasting model.
Our code template shall perform the following steps:
Preview dataCheck total number of entries and column typesCheck any null valuesCheck duplicate entriesPlot distribution of numeric data (univariate and pairwise joint distribution)Plot count distribution of categorical dataAnalyse time series of numeric data by daily, monthly and yearly frequencies
Preview data
Check total number of entries and column types
Check any null values
Check duplicate entries
Plot distribution of numeric data (univariate and pairwise joint distribution)
Plot count distribution of categorical data
Analyse time series of numeric data by daily, monthly and yearly frequencies
The necessary dependencies are as such:
import pandas as pdimport numpy as npimport matplotlibimport matplotlib.pyplot as pltimport seaborn as snsimport missingno%matplotlib inline
To start off, we read in our dataset and generate a simple preview and statistics of our data.
df = pd.read_csv('train.csv')df.info()df.head()
The output shows that we have around 1 million entries with 9 columns. No null values but some of the columns’ data type should be changed. As we shall see later, setting the data types correctly can aid us in our data science processes. In a nutshell, there are three common types of data type (categorical, numeric and datetime) and we have different EDA procedures for each of them.
In our preliminary processing, we changed the data types in the following way:
Set the identifier Store as string.
For columns that are categorical, i.e., columns that take on a limited, and usually fixed, number of possible values, we set their type as “category”. E.g., gender, blood type and country are all categorical data.
For columns that are numeric, we can either set their type as “int64” (integer) or “float64” (floating point number). E.g., sales, temperature and number of people are all numeric data.
Set Date as “datetime64” data type.
# set identifier "Store" as stringdf['Store'] = df['Store'].astype('str')# set categorical datadf['DayOfWeek'] = df['DayOfWeek'].astype('category')df['Open'] = df['Open'].astype('category')df['Promo'] = df['Promo'].astype('category')df['StateHoliday'] = df['StateHoliday'].astype(str).str.strip().astype('category')df['SchoolHoliday'] = df['SchoolHoliday'].astype('category')# set datetime datadf['Date'] = pd.to_datetime(df['Date'])
After setting the data types, we are ready to let the fun (a.k.a. EDA) begin.
To set up the party, we just have to copy, paste and run the code template that contains the various functions and subsequently, run the function eda that takes in a Pandas dataframe as input.
eda(df)
And that’s it! Simple :)
Let’s now go through the salient parts of the output to understand how to make use of our EDA results.
In our case, there is no entry with missing values.
However, in the event of missing values, the code will generate a chart similar to the one below. Notice the white spaces under CustomerID and Description; those are the missing values. Thus, in one glance, we are able to know the extent of our missing values issue.
The portion of code relevant for checking missing values is as follows.
# generate preview of entries with null valuesif df.isnull().any(axis=None): print("\nPreview of data with null values:\nxxxxxxxxxxxxx") print(df[df.isnull().any(axis=1)].head(3)) missingno.matrix(df) plt.show()
In our case, there are also no duplicated entries, which the code will point out directly by printing the output “No duplicated entries found”.
In the event of duplicated entries, the output will show the number of duplicated entries and a preview of these entries.
Code for checking duplicated entries:
# generate count statistics of duplicate entriesif len(df[df.duplicated()]) > 0: print("No. of duplicated entries: ", len(df[df.duplicated()])) print(df[df.duplicated(keep=False)].sort_values(by=list(df.columns)).head())else: print("No duplicated entries found")
Should there be any missing values or duplicated entries, you should decide on the cleaning steps required before proceeding further to the other parts of EDA.
For reference on how to treat missing values, you may wish to refer to this article by Jun Wu.
For duplicated entries, check that they are indeed duplicated and drop them by the following code.
df.drop_duplicates(inplace=True)
Our main EDA objective for categorical data is to know the unique values and their corresponding count.
Using the Rossmann store sales e.g., the column Promo indicates whether a store is running a promotion on that day. Running a count of Promo by its unique values shows that promotions are held quite often, taking up around 40% (388,080 / 1,017,209) of store days. This may indicate that Promo is an important feature in forecasting sales.
The function generating the EDA for categorical data is categorical_eda.
def categorical_eda(df): """Given dataframe, generate EDA of categorical data""" print("To check: Unique count of non-numeric data") print(df.select_dtypes(include=['category']).nunique()) top5(df) # Plot count distribution of categorical data for col in df.select_dtypes(include='category').columns: fig = sns.catplot(x=col, kind="count", data=df) fig.set_xticklabels(rotation=90) plt.show()
For numeric data, our EDA approach is as follows:
Plot univariate distribution of each numeric dataIf categorical data are available, plot univariate distribution by each categorical valuePlot pairwise joint distribution of numeric data
Plot univariate distribution of each numeric data
If categorical data are available, plot univariate distribution by each categorical value
Plot pairwise joint distribution of numeric data
Prior to running the eda function, we created a new column ave_sales by dividing Sales on Customers, so that we can analyse the average sales per customer per store day.
The first output for our numeric data EDA shows some simple distribution statistics that include mean, standard deviation and quartiles.
Some of the points that we can derive from the output include:
No negative values for all numeric data. If there is any negative value, it may mean that we have to further investigate since sales and number of customers are unlikely to be negative, and we may have to then clean the data.
The max values for the numeric data are quite far off from the 75 percentile, indicating that we may have outliers.
The boxplots further confirm that there is/are outlier(s) with Sales more than 40,000 or Customers greater than 7,000. We may, therefore, conduct a check to see if this is an error or were there other special circumstances leading to the exceptional figures.
We have also plotted violin plots for each numeric data by category values to investigate for e.g., the effect of Promo on Sales.
From the violin plot above, we can infer that on days of promotion, sales typically increase as seen from the wider sections of the violin plot. The wide section of the plot near 0 Sales for Promo=0 is probably due to closed stores. Running the eda function again later after removing entries with Open=0 shows that the wide section near 0 is no longer present, thereby confirming our hypothesis.
The last output for numeric data EDA is a pairwise joint distribution plot.
To generate further insights, we ran the function numeric_eda and added a parameter hue=‘DayOfWeek’. This allows us to color our pairwise plot by each day of the week.
numeric_eda(df, hue='DayOfWeek')
By incorporating the DayOfWeek into the plot, we noticed that Sunday’s ave_sales (represent by pink color) is relatively more constant than the other days. This is, therefore, something that can be further investigated and considered as a predictor.
Lastly, we also plotted time series charts to check for trends and seasonality.
For ease of analysis, our code automatically sums up the numeric data by daily, monthly and yearly frequency before plotting the charts. It achieves this through Pandas’ resample method.
In our case, the yearly chart is not useful as the data only contains partial 2015 data, hence we have left it out from the screenshots.
From the daily plot, we can see that there are outliers towards the end of December 2013. This is also reflected in the monthly plot.
The monthly plot also shows that there is some seasonality, namely lower sales in February that is probably due to short month effect, as well as higher sales towards end of year. If we are predicting monthly sales, our forecasting would have to take this seasonality effect into consideration.
Through the examples above, we hope to have demonstrated how EDA is used to formulate assumptions and hypothesis for our modelling, and to check the quality of data for further processing and cleaning.
In case you missed the code template link, here it is again.
Lastly, do note that depending on your data science problem statement, you may wish to perform additional EDA steps. Nonetheless, the code template should be able to cover the basic EDA and get you up to speed quickly.
If you are also looking at performing EDA for text data, please do check out this great comprehensive article by neptune.ai on EDA for Natural Language Processing. In the article, the author illustrated nearly all the major techniques that you can use to understand your text data.
Thanks for reading and I hope the code and article are useful. Please also feel free to comment with any questions or suggestions you may have. | [
{
"code": null,
"e": 306,
"s": 172,
"text": "Very often, it is not the drawing that is most difficult, but rather what to draw on a blank white piece of paper that stumps people."
},
{
"code": null,
"e": 462,
"s": 306,
"text": "Similarly for data science, one may wonder how to get started after receiving a dataset. This is where Exploratory Data Analysis (EDA) comes to the rescue."
},
{
"code": null,
"e": 747,
"s": 462,
"text": "According to Wikipedia, EDA “is an approach to analyzing datasets to summarize their main characteristics, often with visual methods”. In my own words, it is about knowing your data, gaining a certain amount of familiarity with the data, before one starts to extract insights from it."
},
{
"code": null,
"e": 1121,
"s": 747,
"text": "Since EDA is such a crucial initial step for all data science projects, the lazy me decided to write a code template for performing EDA on structured datasets. The idea is to spend less time coding and focus more on the analysis of data itself. Scroll down to the bottom for the link to the code, but do read on to find out more about EDA and understand what the code does."
},
{
"code": null,
"e": 1237,
"s": 1121,
"text": "Before we delve into EDA, it is important to first get a sense of where EDA fits in the whole data science process."
},
{
"code": null,
"e": 1624,
"s": 1237,
"text": "With reference to the process chart from Wikipedia, after the data has been collected, it undergoes some processing before being cleaned and EDA is then performed. Notice that after EDA, we may go back to processing and cleaning of data, i.e., this can be an iterative process. Subsequently, we can then use the cleaned dataset and knowledge from EDA to perform modelling and reporting."
},
{
"code": null,
"e": 1685,
"s": 1624,
"text": "We can, therefore, understand the objectives of EDA as such:"
},
{
"code": null,
"e": 1748,
"s": 1685,
"text": "To gain an understanding of data and find clues from the data,"
},
{
"code": null,
"e": 1889,
"s": 1748,
"text": "to formulate assumptions and hypothesis for our modelling; andto check the quality of data for further processing and cleaning if necessary."
},
{
"code": null,
"e": 1952,
"s": 1889,
"text": "to formulate assumptions and hypothesis for our modelling; and"
},
{
"code": null,
"e": 2031,
"s": 1952,
"text": "to check the quality of data for further processing and cleaning if necessary."
},
{
"code": null,
"e": 2251,
"s": 2031,
"text": "To better illustrate the concept of EDA, we shall be using the Rossmann store sales “train.csv” data from Kaggle. Keeping in mind that the problem statement is to forecast store sales, our EDA objectives are, therefore:"
},
{
"code": null,
"e": 2386,
"s": 2251,
"text": "To check for features that can help in forecasting sales; andTo check for anomalies or outliers that may impact our forecasting model."
},
{
"code": null,
"e": 2448,
"s": 2386,
"text": "To check for features that can help in forecasting sales; and"
},
{
"code": null,
"e": 2522,
"s": 2448,
"text": "To check for anomalies or outliers that may impact our forecasting model."
},
{
"code": null,
"e": 2575,
"s": 2522,
"text": "Our code template shall perform the following steps:"
},
{
"code": null,
"e": 2875,
"s": 2575,
"text": "Preview dataCheck total number of entries and column typesCheck any null valuesCheck duplicate entriesPlot distribution of numeric data (univariate and pairwise joint distribution)Plot count distribution of categorical dataAnalyse time series of numeric data by daily, monthly and yearly frequencies"
},
{
"code": null,
"e": 2888,
"s": 2875,
"text": "Preview data"
},
{
"code": null,
"e": 2935,
"s": 2888,
"text": "Check total number of entries and column types"
},
{
"code": null,
"e": 2957,
"s": 2935,
"text": "Check any null values"
},
{
"code": null,
"e": 2981,
"s": 2957,
"text": "Check duplicate entries"
},
{
"code": null,
"e": 3060,
"s": 2981,
"text": "Plot distribution of numeric data (univariate and pairwise joint distribution)"
},
{
"code": null,
"e": 3104,
"s": 3060,
"text": "Plot count distribution of categorical data"
},
{
"code": null,
"e": 3181,
"s": 3104,
"text": "Analyse time series of numeric data by daily, monthly and yearly frequencies"
},
{
"code": null,
"e": 3221,
"s": 3181,
"text": "The necessary dependencies are as such:"
},
{
"code": null,
"e": 3362,
"s": 3221,
"text": "import pandas as pdimport numpy as npimport matplotlibimport matplotlib.pyplot as pltimport seaborn as snsimport missingno%matplotlib inline"
},
{
"code": null,
"e": 3457,
"s": 3362,
"text": "To start off, we read in our dataset and generate a simple preview and statistics of our data."
},
{
"code": null,
"e": 3505,
"s": 3457,
"text": "df = pd.read_csv('train.csv')df.info()df.head()"
},
{
"code": null,
"e": 3891,
"s": 3505,
"text": "The output shows that we have around 1 million entries with 9 columns. No null values but some of the columns’ data type should be changed. As we shall see later, setting the data types correctly can aid us in our data science processes. In a nutshell, there are three common types of data type (categorical, numeric and datetime) and we have different EDA procedures for each of them."
},
{
"code": null,
"e": 3970,
"s": 3891,
"text": "In our preliminary processing, we changed the data types in the following way:"
},
{
"code": null,
"e": 4006,
"s": 3970,
"text": "Set the identifier Store as string."
},
{
"code": null,
"e": 4220,
"s": 4006,
"text": "For columns that are categorical, i.e., columns that take on a limited, and usually fixed, number of possible values, we set their type as “category”. E.g., gender, blood type and country are all categorical data."
},
{
"code": null,
"e": 4406,
"s": 4220,
"text": "For columns that are numeric, we can either set their type as “int64” (integer) or “float64” (floating point number). E.g., sales, temperature and number of people are all numeric data."
},
{
"code": null,
"e": 4442,
"s": 4406,
"text": "Set Date as “datetime64” data type."
},
{
"code": null,
"e": 4876,
"s": 4442,
"text": "# set identifier \"Store\" as stringdf['Store'] = df['Store'].astype('str')# set categorical datadf['DayOfWeek'] = df['DayOfWeek'].astype('category')df['Open'] = df['Open'].astype('category')df['Promo'] = df['Promo'].astype('category')df['StateHoliday'] = df['StateHoliday'].astype(str).str.strip().astype('category')df['SchoolHoliday'] = df['SchoolHoliday'].astype('category')# set datetime datadf['Date'] = pd.to_datetime(df['Date'])"
},
{
"code": null,
"e": 4954,
"s": 4876,
"text": "After setting the data types, we are ready to let the fun (a.k.a. EDA) begin."
},
{
"code": null,
"e": 5147,
"s": 4954,
"text": "To set up the party, we just have to copy, paste and run the code template that contains the various functions and subsequently, run the function eda that takes in a Pandas dataframe as input."
},
{
"code": null,
"e": 5155,
"s": 5147,
"text": "eda(df)"
},
{
"code": null,
"e": 5180,
"s": 5155,
"text": "And that’s it! Simple :)"
},
{
"code": null,
"e": 5283,
"s": 5180,
"text": "Let’s now go through the salient parts of the output to understand how to make use of our EDA results."
},
{
"code": null,
"e": 5335,
"s": 5283,
"text": "In our case, there is no entry with missing values."
},
{
"code": null,
"e": 5602,
"s": 5335,
"text": "However, in the event of missing values, the code will generate a chart similar to the one below. Notice the white spaces under CustomerID and Description; those are the missing values. Thus, in one glance, we are able to know the extent of our missing values issue."
},
{
"code": null,
"e": 5674,
"s": 5602,
"text": "The portion of code relevant for checking missing values is as follows."
},
{
"code": null,
"e": 5898,
"s": 5674,
"text": "# generate preview of entries with null valuesif df.isnull().any(axis=None): print(\"\\nPreview of data with null values:\\nxxxxxxxxxxxxx\") print(df[df.isnull().any(axis=1)].head(3)) missingno.matrix(df) plt.show()"
},
{
"code": null,
"e": 6042,
"s": 5898,
"text": "In our case, there are also no duplicated entries, which the code will point out directly by printing the output “No duplicated entries found”."
},
{
"code": null,
"e": 6164,
"s": 6042,
"text": "In the event of duplicated entries, the output will show the number of duplicated entries and a preview of these entries."
},
{
"code": null,
"e": 6202,
"s": 6164,
"text": "Code for checking duplicated entries:"
},
{
"code": null,
"e": 6474,
"s": 6202,
"text": "# generate count statistics of duplicate entriesif len(df[df.duplicated()]) > 0: print(\"No. of duplicated entries: \", len(df[df.duplicated()])) print(df[df.duplicated(keep=False)].sort_values(by=list(df.columns)).head())else: print(\"No duplicated entries found\")"
},
{
"code": null,
"e": 6634,
"s": 6474,
"text": "Should there be any missing values or duplicated entries, you should decide on the cleaning steps required before proceeding further to the other parts of EDA."
},
{
"code": null,
"e": 6729,
"s": 6634,
"text": "For reference on how to treat missing values, you may wish to refer to this article by Jun Wu."
},
{
"code": null,
"e": 6828,
"s": 6729,
"text": "For duplicated entries, check that they are indeed duplicated and drop them by the following code."
},
{
"code": null,
"e": 6861,
"s": 6828,
"text": "df.drop_duplicates(inplace=True)"
},
{
"code": null,
"e": 6965,
"s": 6861,
"text": "Our main EDA objective for categorical data is to know the unique values and their corresponding count."
},
{
"code": null,
"e": 7304,
"s": 6965,
"text": "Using the Rossmann store sales e.g., the column Promo indicates whether a store is running a promotion on that day. Running a count of Promo by its unique values shows that promotions are held quite often, taking up around 40% (388,080 / 1,017,209) of store days. This may indicate that Promo is an important feature in forecasting sales."
},
{
"code": null,
"e": 7377,
"s": 7304,
"text": "The function generating the EDA for categorical data is categorical_eda."
},
{
"code": null,
"e": 7809,
"s": 7377,
"text": "def categorical_eda(df): \"\"\"Given dataframe, generate EDA of categorical data\"\"\" print(\"To check: Unique count of non-numeric data\") print(df.select_dtypes(include=['category']).nunique()) top5(df) # Plot count distribution of categorical data for col in df.select_dtypes(include='category').columns: fig = sns.catplot(x=col, kind=\"count\", data=df) fig.set_xticklabels(rotation=90) plt.show()"
},
{
"code": null,
"e": 7859,
"s": 7809,
"text": "For numeric data, our EDA approach is as follows:"
},
{
"code": null,
"e": 8046,
"s": 7859,
"text": "Plot univariate distribution of each numeric dataIf categorical data are available, plot univariate distribution by each categorical valuePlot pairwise joint distribution of numeric data"
},
{
"code": null,
"e": 8096,
"s": 8046,
"text": "Plot univariate distribution of each numeric data"
},
{
"code": null,
"e": 8186,
"s": 8096,
"text": "If categorical data are available, plot univariate distribution by each categorical value"
},
{
"code": null,
"e": 8235,
"s": 8186,
"text": "Plot pairwise joint distribution of numeric data"
},
{
"code": null,
"e": 8405,
"s": 8235,
"text": "Prior to running the eda function, we created a new column ave_sales by dividing Sales on Customers, so that we can analyse the average sales per customer per store day."
},
{
"code": null,
"e": 8542,
"s": 8405,
"text": "The first output for our numeric data EDA shows some simple distribution statistics that include mean, standard deviation and quartiles."
},
{
"code": null,
"e": 8605,
"s": 8542,
"text": "Some of the points that we can derive from the output include:"
},
{
"code": null,
"e": 8831,
"s": 8605,
"text": "No negative values for all numeric data. If there is any negative value, it may mean that we have to further investigate since sales and number of customers are unlikely to be negative, and we may have to then clean the data."
},
{
"code": null,
"e": 8947,
"s": 8831,
"text": "The max values for the numeric data are quite far off from the 75 percentile, indicating that we may have outliers."
},
{
"code": null,
"e": 9206,
"s": 8947,
"text": "The boxplots further confirm that there is/are outlier(s) with Sales more than 40,000 or Customers greater than 7,000. We may, therefore, conduct a check to see if this is an error or were there other special circumstances leading to the exceptional figures."
},
{
"code": null,
"e": 9336,
"s": 9206,
"text": "We have also plotted violin plots for each numeric data by category values to investigate for e.g., the effect of Promo on Sales."
},
{
"code": null,
"e": 9733,
"s": 9336,
"text": "From the violin plot above, we can infer that on days of promotion, sales typically increase as seen from the wider sections of the violin plot. The wide section of the plot near 0 Sales for Promo=0 is probably due to closed stores. Running the eda function again later after removing entries with Open=0 shows that the wide section near 0 is no longer present, thereby confirming our hypothesis."
},
{
"code": null,
"e": 9809,
"s": 9733,
"text": "The last output for numeric data EDA is a pairwise joint distribution plot."
},
{
"code": null,
"e": 9977,
"s": 9809,
"text": "To generate further insights, we ran the function numeric_eda and added a parameter hue=‘DayOfWeek’. This allows us to color our pairwise plot by each day of the week."
},
{
"code": null,
"e": 10010,
"s": 9977,
"text": "numeric_eda(df, hue='DayOfWeek')"
},
{
"code": null,
"e": 10260,
"s": 10010,
"text": "By incorporating the DayOfWeek into the plot, we noticed that Sunday’s ave_sales (represent by pink color) is relatively more constant than the other days. This is, therefore, something that can be further investigated and considered as a predictor."
},
{
"code": null,
"e": 10340,
"s": 10260,
"text": "Lastly, we also plotted time series charts to check for trends and seasonality."
},
{
"code": null,
"e": 10527,
"s": 10340,
"text": "For ease of analysis, our code automatically sums up the numeric data by daily, monthly and yearly frequency before plotting the charts. It achieves this through Pandas’ resample method."
},
{
"code": null,
"e": 10664,
"s": 10527,
"text": "In our case, the yearly chart is not useful as the data only contains partial 2015 data, hence we have left it out from the screenshots."
},
{
"code": null,
"e": 10798,
"s": 10664,
"text": "From the daily plot, we can see that there are outliers towards the end of December 2013. This is also reflected in the monthly plot."
},
{
"code": null,
"e": 11093,
"s": 10798,
"text": "The monthly plot also shows that there is some seasonality, namely lower sales in February that is probably due to short month effect, as well as higher sales towards end of year. If we are predicting monthly sales, our forecasting would have to take this seasonality effect into consideration."
},
{
"code": null,
"e": 11295,
"s": 11093,
"text": "Through the examples above, we hope to have demonstrated how EDA is used to formulate assumptions and hypothesis for our modelling, and to check the quality of data for further processing and cleaning."
},
{
"code": null,
"e": 11356,
"s": 11295,
"text": "In case you missed the code template link, here it is again."
},
{
"code": null,
"e": 11575,
"s": 11356,
"text": "Lastly, do note that depending on your data science problem statement, you may wish to perform additional EDA steps. Nonetheless, the code template should be able to cover the basic EDA and get you up to speed quickly."
},
{
"code": null,
"e": 11857,
"s": 11575,
"text": "If you are also looking at performing EDA for text data, please do check out this great comprehensive article by neptune.ai on EDA for Natural Language Processing. In the article, the author illustrated nearly all the major techniques that you can use to understand your text data."
}
] |
Count of subarrays having sum equal to its length - GeeksforGeeks | 18 May, 2021
Given an array arr[] of size N, the task is to find the number of subarrays having the sum of its elements equal to the number of elements in it.
Examples:
Input: N = 3, arr[] = {1, 0, 2}Output: 3Explanation:Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., 1) {1}, sum = 1, length = 1.2) {0, 2}, sum = 2, length = 2.3) {1, 0, 2}, sum = 3, length = 3.
Input: N = 3, arr[] = {1, 1, 0}Output: 3Explanation:Total number of subarrays are 6 i.e. {1}, {1}, {0}, {1, 1}, {1, 0}, {1, 1, 0}.Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., 1) {1}, sum = 1, length = 1.2) {1}, sum = 1, length = 1.3) {1, 1}, sum = 2, length = 2.
Naive Approach: The idea is to generate all the subarrays of the array and if the sum of elements of the subarray is equal to the number of elements in it then count this subarray. Print the count after checking all the subarrays.
Time Complexity: O(N2)Auxiliary Space: O(N)
Efficient Approach: This problem can be converted into a simpler problem by using observation. If all the elements of the array are decremented by 1, then all the subarrays of array arr[] with a sum equal to its number of elements are same as finding the number of subarrays with sum 0 in the new array(formed by decrementing all the elements of arr[ ] by 1). Below are the steps:
Decrement all the array elements by 1.Initialize a prefix array with prefix[0] = arr[0].Traverse the given array arr[] from left to right, starting from index 1 and update a prefix sum array as pref[i] = pref[i-1] + arr[i].Initialize the answer to 0.Iterate the prefix array pref[] from left to right and increment the answer by the value of the current element in the map.Increment the value of the current element in the map.Print the value of answer after the above steps.
Decrement all the array elements by 1.
Initialize a prefix array with prefix[0] = arr[0].
Traverse the given array arr[] from left to right, starting from index 1 and update a prefix sum array as pref[i] = pref[i-1] + arr[i].
Initialize the answer to 0.
Iterate the prefix array pref[] from left to right and increment the answer by the value of the current element in the map.
Increment the value of the current element in the map.
Print the value of answer after the above steps.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that counts the subarrays// with sum of its elements as its lengthint countOfSubarray(int arr[], int N){ // Decrementing all the elements // of the array by 1 for (int i = 0; i < N; i++) arr[i]--; // Making prefix sum array int pref[N]; pref[0] = arr[0]; for (int i = 1; i < N; i++) pref[i] = pref[i - 1] + arr[i]; // Declare map to store count of // elements upto current element map<int, int> mp; int answer = 0; // To count all the subarrays // whose prefix sum is 0 mp[0]++; // Iterate the array for (int i = 0; i < N; i++) { // Increment answer by count of // current element of prefix array answer += mp[pref[i]]; mp[pref[i]]++; } // Return the answer return answer;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 0 }; int N = sizeof arr / sizeof arr[0]; // Function call cout << countOfSubarray(arr, N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function that counts the subarrays// with sum of its elements as its lengthstatic int countOfSubarray(int arr[], int N){ // Decrementing all the elements // of the array by 1 for (int i = 0; i < N; i++) arr[i]--; // Making prefix sum array int []pref = new int[N]; pref[0] = arr[0]; for (int i = 1; i < N; i++) pref[i] = pref[i - 1] + arr[i]; // Declare map to store count of // elements upto current element HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); int answer = 0; // To count all the subarrays // whose prefix sum is 0 mp.put(0, 1); // Iterate the array for (int i = 0; i < N; i++) { // Increment answer by count of // current element of prefix array if(mp.containsKey(pref[i])) { answer += mp.get(pref[i]); mp.put(pref[i], mp.get(pref[i]) + 1); } else { mp.put(pref[i], 1); } } // Return the answer return answer;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 1, 1, 0 }; int N = arr.length; // Function call System.out.print(countOfSubarray(arr, N));}} // This code is contributed by sapnasingh4991
# Python3 program for the above approachfrom collections import defaultdict # Function that counts the subarrays# with sum of its elements as its lengthdef countOfSubarray(arr, N): # Decrementing all the elements # of the array by 1 for i in range(N): arr[i] -= 1 # Making prefix sum array pref = [0] * N pref[0] = arr[0] for i in range(1, N): pref[i] = pref[i - 1] + arr[i] # Declare map to store count of # elements upto current element mp = defaultdict(lambda : 0) answer = 0 # To count all the subarrays # whose prefix sum is 0 mp[0] += 1 # Iterate the array for i in range(N): # Increment answer by count of # current element of prefix array answer += mp[pref[i]] mp[pref[i]] += 1 # Return the answer return answer # Driver Code # Given array arr[]arr = [ 1, 1, 0 ]N = len(arr) # Function callprint(countOfSubarray(arr, N)) # This code is contributed by Shivam Singh
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that counts the subarrays// with sum of its elements as its lengthstatic int countOfSubarray(int []arr, int N){ // Decrementing all the elements // of the array by 1 for (int i = 0; i < N; i++) arr[i]--; // Making prefix sum array int []pref = new int[N]; pref[0] = arr[0]; for (int i = 1; i < N; i++) pref[i] = pref[i - 1] + arr[i]; // Declare map to store count of // elements upto current element Dictionary<int, int> mp = new Dictionary<int, int>(); int answer = 0; // To count all the subarrays // whose prefix sum is 0 mp.Add(0, 1); // Iterate the array for (int i = 0; i < N; i++) { // Increment answer by count of // current element of prefix array if(mp.ContainsKey(pref[i])) { answer += mp[pref[i]]; mp[pref[i]]= mp[pref[i]] + 1; } else { mp.Add(pref[i], 1); } } // Return the answer return answer;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 1, 1, 0 }; int N = arr.Length; // Function call Console.Write(countOfSubarray(arr, N));}} // This code is contributed by sapnasingh4991
<script>// Js program for the above approach // Function that counts the subarrays// with sum of its elements as its lengthfunction countOfSubarray( arr, N){ // Decrementing all the elements // of the array by 1 for (let i = 0; i < N; i++) arr[i]--; // Making prefix sum array let pref = []; pref[0] = arr[0]; for (let i = 1; i < N; i++) pref[i] = pref[i - 1] + arr[i]; // Declare map to store count of // elements upto current element let mp = new Map; let answer = 0; // To count all the subarrays // whose prefix sum is 0 if(mp[0]) mp[0]++; else mp[0] = 1; // Iterate the array for (let i = 0; i < N; i++) { // Increment answer by count of // current element of prefix array if(mp[pref[i]]){ answer += mp[pref[i]]; mp[pref[i]]++; } } // Return the answer return answer;} // Driver Code// Given array arr[]let arr = [ 1, 1, 0 ];let N = arr.length;// Function calldocument.write(countOfSubarray(arr, N)); </script>
3
Time Complexity: O(N * Log(N))Auxiliary Space: O(N)
sapnasingh4991
rohitsingh07052
cpp-map
subarray
subarray-sum
Arrays
Competitive Programming
Dynamic Programming
Greedy
Mathematical
Arrays
Dynamic Programming
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Top 10 Algorithms and Data Structures for Competitive Programming
Bits manipulation (Important tactics) | [
{
"code": null,
"e": 25438,
"s": 25410,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 25584,
"s": 25438,
"text": "Given an array arr[] of size N, the task is to find the number of subarrays having the sum of its elements equal to the number of elements in it."
},
{
"code": null,
"e": 25594,
"s": 25584,
"text": "Examples:"
},
{
"code": null,
"e": 25913,
"s": 25594,
"text": "Input: N = 3, arr[] = {1, 0, 2}Output: 3Explanation:Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., 1) {1}, sum = 1, length = 1.2) {0, 2}, sum = 2, length = 2.3) {1, 0, 2}, sum = 3, length = 3."
},
{
"code": null,
"e": 26225,
"s": 25913,
"text": "Input: N = 3, arr[] = {1, 1, 0}Output: 3Explanation:Total number of subarrays are 6 i.e. {1}, {1}, {0}, {1, 1}, {1, 0}, {1, 1, 0}.Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., 1) {1}, sum = 1, length = 1.2) {1}, sum = 1, length = 1.3) {1, 1}, sum = 2, length = 2."
},
{
"code": null,
"e": 26456,
"s": 26225,
"text": "Naive Approach: The idea is to generate all the subarrays of the array and if the sum of elements of the subarray is equal to the number of elements in it then count this subarray. Print the count after checking all the subarrays."
},
{
"code": null,
"e": 26500,
"s": 26456,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 26881,
"s": 26500,
"text": "Efficient Approach: This problem can be converted into a simpler problem by using observation. If all the elements of the array are decremented by 1, then all the subarrays of array arr[] with a sum equal to its number of elements are same as finding the number of subarrays with sum 0 in the new array(formed by decrementing all the elements of arr[ ] by 1). Below are the steps:"
},
{
"code": null,
"e": 27357,
"s": 26881,
"text": "Decrement all the array elements by 1.Initialize a prefix array with prefix[0] = arr[0].Traverse the given array arr[] from left to right, starting from index 1 and update a prefix sum array as pref[i] = pref[i-1] + arr[i].Initialize the answer to 0.Iterate the prefix array pref[] from left to right and increment the answer by the value of the current element in the map.Increment the value of the current element in the map.Print the value of answer after the above steps."
},
{
"code": null,
"e": 27396,
"s": 27357,
"text": "Decrement all the array elements by 1."
},
{
"code": null,
"e": 27447,
"s": 27396,
"text": "Initialize a prefix array with prefix[0] = arr[0]."
},
{
"code": null,
"e": 27583,
"s": 27447,
"text": "Traverse the given array arr[] from left to right, starting from index 1 and update a prefix sum array as pref[i] = pref[i-1] + arr[i]."
},
{
"code": null,
"e": 27611,
"s": 27583,
"text": "Initialize the answer to 0."
},
{
"code": null,
"e": 27735,
"s": 27611,
"text": "Iterate the prefix array pref[] from left to right and increment the answer by the value of the current element in the map."
},
{
"code": null,
"e": 27790,
"s": 27735,
"text": "Increment the value of the current element in the map."
},
{
"code": null,
"e": 27839,
"s": 27790,
"text": "Print the value of answer after the above steps."
},
{
"code": null,
"e": 27890,
"s": 27839,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27894,
"s": 27890,
"text": "C++"
},
{
"code": null,
"e": 27899,
"s": 27894,
"text": "Java"
},
{
"code": null,
"e": 27907,
"s": 27899,
"text": "Python3"
},
{
"code": null,
"e": 27910,
"s": 27907,
"text": "C#"
},
{
"code": null,
"e": 27921,
"s": 27910,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that counts the subarrays// with sum of its elements as its lengthint countOfSubarray(int arr[], int N){ // Decrementing all the elements // of the array by 1 for (int i = 0; i < N; i++) arr[i]--; // Making prefix sum array int pref[N]; pref[0] = arr[0]; for (int i = 1; i < N; i++) pref[i] = pref[i - 1] + arr[i]; // Declare map to store count of // elements upto current element map<int, int> mp; int answer = 0; // To count all the subarrays // whose prefix sum is 0 mp[0]++; // Iterate the array for (int i = 0; i < N; i++) { // Increment answer by count of // current element of prefix array answer += mp[pref[i]]; mp[pref[i]]++; } // Return the answer return answer;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 1, 0 }; int N = sizeof arr / sizeof arr[0]; // Function call cout << countOfSubarray(arr, N); return 0;}",
"e": 28983,
"s": 27921,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function that counts the subarrays// with sum of its elements as its lengthstatic int countOfSubarray(int arr[], int N){ // Decrementing all the elements // of the array by 1 for (int i = 0; i < N; i++) arr[i]--; // Making prefix sum array int []pref = new int[N]; pref[0] = arr[0]; for (int i = 1; i < N; i++) pref[i] = pref[i - 1] + arr[i]; // Declare map to store count of // elements upto current element HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); int answer = 0; // To count all the subarrays // whose prefix sum is 0 mp.put(0, 1); // Iterate the array for (int i = 0; i < N; i++) { // Increment answer by count of // current element of prefix array if(mp.containsKey(pref[i])) { answer += mp.get(pref[i]); mp.put(pref[i], mp.get(pref[i]) + 1); } else { mp.put(pref[i], 1); } } // Return the answer return answer;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 1, 1, 0 }; int N = arr.length; // Function call System.out.print(countOfSubarray(arr, N));}} // This code is contributed by sapnasingh4991",
"e": 30375,
"s": 28983,
"text": null
},
{
"code": "# Python3 program for the above approachfrom collections import defaultdict # Function that counts the subarrays# with sum of its elements as its lengthdef countOfSubarray(arr, N): # Decrementing all the elements # of the array by 1 for i in range(N): arr[i] -= 1 # Making prefix sum array pref = [0] * N pref[0] = arr[0] for i in range(1, N): pref[i] = pref[i - 1] + arr[i] # Declare map to store count of # elements upto current element mp = defaultdict(lambda : 0) answer = 0 # To count all the subarrays # whose prefix sum is 0 mp[0] += 1 # Iterate the array for i in range(N): # Increment answer by count of # current element of prefix array answer += mp[pref[i]] mp[pref[i]] += 1 # Return the answer return answer # Driver Code # Given array arr[]arr = [ 1, 1, 0 ]N = len(arr) # Function callprint(countOfSubarray(arr, N)) # This code is contributed by Shivam Singh",
"e": 31351,
"s": 30375,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that counts the subarrays// with sum of its elements as its lengthstatic int countOfSubarray(int []arr, int N){ // Decrementing all the elements // of the array by 1 for (int i = 0; i < N; i++) arr[i]--; // Making prefix sum array int []pref = new int[N]; pref[0] = arr[0]; for (int i = 1; i < N; i++) pref[i] = pref[i - 1] + arr[i]; // Declare map to store count of // elements upto current element Dictionary<int, int> mp = new Dictionary<int, int>(); int answer = 0; // To count all the subarrays // whose prefix sum is 0 mp.Add(0, 1); // Iterate the array for (int i = 0; i < N; i++) { // Increment answer by count of // current element of prefix array if(mp.ContainsKey(pref[i])) { answer += mp[pref[i]]; mp[pref[i]]= mp[pref[i]] + 1; } else { mp.Add(pref[i], 1); } } // Return the answer return answer;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 1, 1, 0 }; int N = arr.Length; // Function call Console.Write(countOfSubarray(arr, N));}} // This code is contributed by sapnasingh4991",
"e": 32735,
"s": 31351,
"text": null
},
{
"code": "<script>// Js program for the above approach // Function that counts the subarrays// with sum of its elements as its lengthfunction countOfSubarray( arr, N){ // Decrementing all the elements // of the array by 1 for (let i = 0; i < N; i++) arr[i]--; // Making prefix sum array let pref = []; pref[0] = arr[0]; for (let i = 1; i < N; i++) pref[i] = pref[i - 1] + arr[i]; // Declare map to store count of // elements upto current element let mp = new Map; let answer = 0; // To count all the subarrays // whose prefix sum is 0 if(mp[0]) mp[0]++; else mp[0] = 1; // Iterate the array for (let i = 0; i < N; i++) { // Increment answer by count of // current element of prefix array if(mp[pref[i]]){ answer += mp[pref[i]]; mp[pref[i]]++; } } // Return the answer return answer;} // Driver Code// Given array arr[]let arr = [ 1, 1, 0 ];let N = arr.length;// Function calldocument.write(countOfSubarray(arr, N)); </script>",
"e": 33779,
"s": 32735,
"text": null
},
{
"code": null,
"e": 33781,
"s": 33779,
"text": "3"
},
{
"code": null,
"e": 33835,
"s": 33783,
"text": "Time Complexity: O(N * Log(N))Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33850,
"s": 33835,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 33866,
"s": 33850,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 33874,
"s": 33866,
"text": "cpp-map"
},
{
"code": null,
"e": 33883,
"s": 33874,
"text": "subarray"
},
{
"code": null,
"e": 33896,
"s": 33883,
"text": "subarray-sum"
},
{
"code": null,
"e": 33903,
"s": 33896,
"text": "Arrays"
},
{
"code": null,
"e": 33927,
"s": 33903,
"text": "Competitive Programming"
},
{
"code": null,
"e": 33947,
"s": 33927,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33954,
"s": 33947,
"text": "Greedy"
},
{
"code": null,
"e": 33967,
"s": 33954,
"text": "Mathematical"
},
{
"code": null,
"e": 33974,
"s": 33967,
"text": "Arrays"
},
{
"code": null,
"e": 33994,
"s": 33974,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34001,
"s": 33994,
"text": "Greedy"
},
{
"code": null,
"e": 34014,
"s": 34001,
"text": "Mathematical"
},
{
"code": null,
"e": 34112,
"s": 34014,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34180,
"s": 34112,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34224,
"s": 34180,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34256,
"s": 34224,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34279,
"s": 34256,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34293,
"s": 34279,
"text": "Linear Search"
},
{
"code": null,
"e": 34336,
"s": 34293,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 34379,
"s": 34336,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 34420,
"s": 34379,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 34486,
"s": 34420,
"text": "Top 10 Algorithms and Data Structures for Competitive Programming"
}
] |
How to click on image in selenium webdriver Python? | We can click on an image with Selenium webdriver in Python using the method click. First of all, we have to identify the image with the help of any of the locators like id, class, name, css, xpath, and so on. An image in the html code is represented by the img tagname.
Let us see the html code of an image element.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class ImageClk{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.tutorialspoint.com/index.htm");
// identify image
WebElement l = driver.findElement(By.xpath("//img[@alt='Tutorialspoint']"));
String s = l.getAttribute("title");
System.out.println("Title attribute value is :" + s);
l.click();
driver.quit();
}
} | [
{
"code": null,
"e": 1332,
"s": 1062,
"text": "We can click on an image with Selenium webdriver in Python using the method click. First of all, we have to identify the image with the help of any of the locators like id, class, name, css, xpath, and so on. An image in the html code is represented by the img tagname."
},
{
"code": null,
"e": 1378,
"s": 1332,
"text": "Let us see the html code of an image element."
},
{
"code": null,
"e": 2220,
"s": 1378,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class ImageClk{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify image\n WebElement l = driver.findElement(By.xpath(\"//img[@alt='Tutorialspoint']\"));\n String s = l.getAttribute(\"title\");\n System.out.println(\"Title attribute value is :\" + s);\n l.click();\n driver.quit();\n }\n}"
}
] |
Tryit Editor v3.7 | HTML file paths
Tryit: relative url | [
{
"code": null,
"e": 26,
"s": 10,
"text": "HTML file paths"
}
] |
Data Scientists, The 5 Graph Algorithms that you should know | by Rahul Agarwal | Towards Data Science | We as data scientists have gotten quite comfortable with Pandas or SQL or any other relational database.
We are used to seeing our users in rows with their attributes as columns. But does the real world really behave like that?
In a connected world, users cannot be considered as independent entities. They have got certain relationships between each other and we would sometimes like to include such relationships while building our machine learning models.
Now while in a relational database, we cannot use such relations between different rows(users), in a graph database it is fairly trivial to do that.
In this post, I am going to be talking about some of the most important graph algorithms you should know and how to implement them using Python.
Also, here is a Graph Analytics for Big Data course on Coursera by UCSanDiego which I highly recommend to learn the basics of graph theory.
We all know how clustering works?
You can think of Connected Components in very layman’s terms as a sort of a hard clustering algorithm which finds clusters/islands in related/connected data.
As a concrete example: Say you have data about roads joining any two cities in the world. And you need to find out all the continents in the world and which city they contain.
How will you achieve that? Come on give some thought.
The connected components algorithm that we use to do this is based on a special case of BFS/DFS. I won’t talk much about how it works here, but we will see how to get the code up and running using Networkx.
From a Retail Perspective: Let us say, we have a lot of customers using a lot of accounts. One way in which we can use the Connected components algorithm is to find out distinct families in our dataset.
We can assume edges(roads) between CustomerIDs based on same credit card usage, or same address or same mobile number, etc. Once we have those connections, we can then run the connected component algorithm on the same to create individual clusters to which we can then assign a family ID.
We can then use these family IDs to provide personalized recommendations based on family needs. We can also use this family ID to fuel our classification algorithms by creating grouped features based on family.
From a Finance Perspective: Another use case would be to capture fraud using these family IDs. If an account has done fraud in the past, it is highly probable that the connected accounts are also susceptible to fraud.
The possibilities are only limited by your own imagination.
We will be using the Networkx module in Python for creating and analyzing our graphs.
Let us start with an example graph which we are using for our purpose. Contains cities and distance information between them.
We first start by creating a list of edges along with the distances which we will add as the weight of the edge:
edgelist = [['Mannheim', 'Frankfurt', 85], ['Mannheim', 'Karlsruhe', 80], ['Erfurt', 'Wurzburg', 186], ['Munchen', 'Numberg', 167], ['Munchen', 'Augsburg', 84], ['Munchen', 'Kassel', 502], ['Numberg', 'Stuttgart', 183], ['Numberg', 'Wurzburg', 103], ['Numberg', 'Munchen', 167], ['Stuttgart', 'Numberg', 183], ['Augsburg', 'Munchen', 84], ['Augsburg', 'Karlsruhe', 250], ['Kassel', 'Munchen', 502], ['Kassel', 'Frankfurt', 173], ['Frankfurt', 'Mannheim', 85], ['Frankfurt', 'Wurzburg', 217], ['Frankfurt', 'Kassel', 173], ['Wurzburg', 'Numberg', 103], ['Wurzburg', 'Erfurt', 186], ['Wurzburg', 'Frankfurt', 217], ['Karlsruhe', 'Mannheim', 80], ['Karlsruhe', 'Augsburg', 250],["Mumbai", "Delhi",400],["Delhi", "Kolkata",500],["Kolkata", "Bangalore",600],["TX", "NY",1200],["ALB", "NY",800]]
Let us create a graph using Networkx:
g = nx.Graph()for edge in edgelist: g.add_edge(edge[0],edge[1], weight = edge[2])
Now we want to find out distinct continents and their cities from this graph.
We can now do this using the connected components algorithm as:
for i, x in enumerate(nx.connected_components(g)): print("cc"+str(i)+":",x)------------------------------------------------------------cc0: {'Frankfurt', 'Kassel', 'Munchen', 'Numberg', 'Erfurt', 'Stuttgart', 'Karlsruhe', 'Wurzburg', 'Mannheim', 'Augsburg'}cc1: {'Kolkata', 'Bangalore', 'Mumbai', 'Delhi'}cc2: {'ALB', 'NY', 'TX'}
As you can see we are able to find distinct components in our data. Just by using Edges and Vertices. This algorithm could be run on different data to satisfy any use case that I presented above.
Continuing with the above example only, we are given a graph with the cities of Germany and the respective distance between them.
You want to find out how to go from Frankfurt (The starting node) to Munchen by covering the shortest distance.
The algorithm that we use for this problem is called Dijkstra. In Dijkstra’s own words:
What is the shortest way to travel from Rotterdam to Groningen, in general: from given city to given city. It is the algorithm for the shortest path, which I designed in about twenty minutes. One morning I was shopping in Amsterdam with my young fiancée, and tired, we sat down on the café terrace to drink a cup of coffee and I was just thinking about whether I could do this, and I then designed the algorithm for the shortest path. As I said, it was a twenty-minute invention. In fact, it was published in ’59, three years later. The publication is still readable, it is, in fact, quite nice. One of the reasons that it is so nice was that I designed it without pencil and paper. I learned later that one of the advantages of designing without pencil and paper is that you are almost forced to avoid all avoidable complexities. Eventually that algorithm became, to my great amazement, one of the cornerstones of my fame.
— Edsger Dijkstra, in an interview with Philip L. Frana, Communications of the ACM, 2001[3]
Variations of the Dijkstra algorithm is used extensively in Google Maps to find the shortest routes.
You are in a Walmart Store. You have different Aisles and distance between all the aisles. You want to provide the shortest pathway to the customer from Aisle A to Aisle D.
You have seen how LinkedIn shows up 1st-degree connections, 2nd-degree connections. What goes on behind the scenes?
print(nx.shortest_path(g, 'Stuttgart','Frankfurt',weight='weight'))print(nx.shortest_path_length(g, 'Stuttgart','Frankfurt',weight='weight'))--------------------------------------------------------['Stuttgart', 'Numberg', 'Wurzburg', 'Frankfurt']503
You can also find Shortest paths between all pairs using:
for x in nx.all_pairs_dijkstra_path(g,weight='weight'): print(x)--------------------------------------------------------('Mannheim', {'Mannheim': ['Mannheim'], 'Frankfurt': ['Mannheim', 'Frankfurt'], 'Karlsruhe': ['Mannheim', 'Karlsruhe'], 'Augsburg': ['Mannheim', 'Karlsruhe', 'Augsburg'], 'Kassel': ['Mannheim', 'Frankfurt', 'Kassel'], 'Wurzburg': ['Mannheim', 'Frankfurt', 'Wurzburg'], 'Munchen': ['Mannheim', 'Karlsruhe', 'Augsburg', 'Munchen'], 'Erfurt': ['Mannheim', 'Frankfurt', 'Wurzburg', 'Erfurt'], 'Numberg': ['Mannheim', 'Frankfurt', 'Wurzburg', 'Numberg'], 'Stuttgart': ['Mannheim', 'Frankfurt', 'Wurzburg', 'Numberg', 'Stuttgart']})('Frankfurt', {'Frankfurt': ['Frankfurt'], 'Mannheim': ['Frankfurt', 'Mannheim'], 'Kassel': ['Frankfurt', 'Kassel'], 'Wurzburg': ['Frankfurt', 'Wurzburg'], 'Karlsruhe': ['Frankfurt', 'Mannheim', 'Karlsruhe'], 'Augsburg': ['Frankfurt', 'Mannheim', 'Karlsruhe', 'Augsburg'], 'Munchen': ['Frankfurt', 'Wurzburg', 'Numberg', 'Munchen'], 'Erfurt': ['Frankfurt', 'Wurzburg', 'Erfurt'], 'Numberg': ['Frankfurt', 'Wurzburg', 'Numberg'], 'Stuttgart': ['Frankfurt', 'Wurzburg', 'Numberg', 'Stuttgart']})....
Now we have another problem. We work for a water pipe laying company or an internet fiber company. We need to connect all the cities in the graph we have using the minimum amount of wire/pipe. How do we do this?
Minimum spanning trees have direct applications in the design of networks, including computer networks, telecommunications networks, transportation networks, water supply networks, and electrical grids (which they were first invented for)
MST is used for approximating the traveling salesman problem
Clustering — First construct MST and then determine a threshold value for breaking some edges in the MST using Intercluster distances and Intracluster distances.
Image Segmentation — It was used for Image segmentation where we first construct an MST on a graph where pixels are nodes and distances between pixels are based on some similarity measure(color, intensity, etc.)
# nx.minimum_spanning_tree(g) returns a instance of type graphnx.draw_networkx(nx.minimum_spanning_tree(g))
As you can see the above is the wire we gotta lay.
This is the page sorting algorithm that powered google for a long time. It assigns scores to pages based on the number and quality of incoming and outgoing links.
Pagerank can be used anywhere where we want to estimate node importance in any network.
It has been used for finding the most influential papers using citations.
Has been used by Google to rank pages
It can be used to rank tweets- User and Tweets as nodes. Create Link between user if user A follows user B and Link between user and Tweets if user tweets/retweets a tweet.
Recommendation engines
For this exercise, we are going to be using Facebook data. We have a file of edges/links between facebook users. We first create the FB graph using:
# reading the datasetfb = nx.read_edgelist('../input/facebook-combined.txt', create_using = nx.Graph(), nodetype = int)
This is how it looks:
pos = nx.spring_layout(fb)import warningswarnings.filterwarnings('ignore')plt.style.use('fivethirtyeight')plt.rcParams['figure.figsize'] = (20, 15)plt.axis('off')nx.draw_networkx(fb, pos, with_labels = False, node_size = 35)plt.show()
Now we want to find the users having high influence capability.
Intuitively, the Pagerank algorithm will give a higher score to a user who has a lot of friends who in turn have a lot of FB Friends.
pageranks = nx.pagerank(fb)print(pageranks)------------------------------------------------------{0: 0.006289602618466542, 1: 0.00023590202311540972, 2: 0.00020310565091694562, 3: 0.00022552359869430617, 4: 0.00023849264701222462,........}
We can get the sorted PageRank or most influential users using:
import operatorsorted_pagerank = sorted(pageranks.items(), key=operator.itemgetter(1),reverse = True)print(sorted_pagerank)------------------------------------------------------[(3437, 0.007614586844749603), (107, 0.006936420955866114), (1684, 0.0063671621383068295), (0, 0.006289602618466542), (1912, 0.0038769716008844974), (348, 0.0023480969727805783), (686, 0.0022193592598000193), (3980, 0.002170323579009993), (414, 0.0018002990470702262), (698, 0.0013171153138368807), (483, 0.0012974283300616082), (3830, 0.0011844348977671688), (376, 0.0009014073664792464), (2047, 0.000841029154597401), (56, 0.0008039024292749443), (25, 0.000800412660519768), (828, 0.0007886905420662135), (322, 0.0007867992190291396),......]
The above IDs are for the most influential users.
We can see the subgraph for the most influential user:
first_degree_connected_nodes = list(fb.neighbors(3437))second_degree_connected_nodes = []for x in first_degree_connected_nodes: second_degree_connected_nodes+=list(fb.neighbors(x))second_degree_connected_nodes.remove(3437)second_degree_connected_nodes = list(set(second_degree_connected_nodes))subgraph_3437 = nx.subgraph(fb,first_degree_connected_nodes+second_degree_connected_nodes)pos = nx.spring_layout(subgraph_3437)node_color = ['yellow' if v == 3437 else 'red' for v in subgraph_3437]node_size = [1000 if v == 3437 else 35 for v in subgraph_3437]plt.style.use('fivethirtyeight')plt.rcParams['figure.figsize'] = (20, 15)plt.axis('off')nx.draw_networkx(subgraph_3437, pos, with_labels = False, node_color=node_color,node_size=node_size )plt.show()
There are a lot of centrality measures which you can use as features to your machine learning models. I will talk about two of them. You can look at other measures here.
Betweenness Centrality: It is not only the users who have the most friends that are important, the users who connect one geography to another are also important as that lets users see content from diverse geographies. Betweenness centrality quantifies how many times a particular node comes in the shortest chosen path between two other nodes.
Degree Centrality: It is simply the number of connections for a node.
Centrality measures can be used as a feature in any machine learning model.
Here is the code for finding the Betweenness centrality for the subgraph.
pos = nx.spring_layout(subgraph_3437)betweennessCentrality = nx.betweenness_centrality(subgraph_3437,normalized=True, endpoints=True)node_size = [v * 10000 for v in betweennessCentrality.values()]plt.figure(figsize=(20,20))nx.draw_networkx(subgraph_3437, pos=pos, with_labels=False, node_size=node_size )plt.axis('off')
You can see the nodes sized by their betweenness centrality values here. They can be thought of as information passers. Breaking any of the nodes with a high betweenness Centrality will break the graph into many parts.
In this post, I talked about some of the most influential graph algorithms that have changed the way we live.
With the advent of so much social data, network analysis could help a lot in improving our models and generating value.
And even understanding a little more about the world.
There are a lot of graph algorithms out there, but these are the ones I like the most. Do look into the algorithms in more detail if you like. In this post, I just wanted to get the required breadth into the area.
Let me know if you feel I have left your favorite algorithm in the comments.
Here is the Kaggle Kernel with the whole code.
If you want to read up more on Graph Algorithms here is a Graph Analytics for Big Data course on Coursera by UCSanDiego which I highly recommend to learn the basics of graph theory.
Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. | [
{
"code": null,
"e": 277,
"s": 172,
"text": "We as data scientists have gotten quite comfortable with Pandas or SQL or any other relational database."
},
{
"code": null,
"e": 400,
"s": 277,
"text": "We are used to seeing our users in rows with their attributes as columns. But does the real world really behave like that?"
},
{
"code": null,
"e": 631,
"s": 400,
"text": "In a connected world, users cannot be considered as independent entities. They have got certain relationships between each other and we would sometimes like to include such relationships while building our machine learning models."
},
{
"code": null,
"e": 780,
"s": 631,
"text": "Now while in a relational database, we cannot use such relations between different rows(users), in a graph database it is fairly trivial to do that."
},
{
"code": null,
"e": 925,
"s": 780,
"text": "In this post, I am going to be talking about some of the most important graph algorithms you should know and how to implement them using Python."
},
{
"code": null,
"e": 1065,
"s": 925,
"text": "Also, here is a Graph Analytics for Big Data course on Coursera by UCSanDiego which I highly recommend to learn the basics of graph theory."
},
{
"code": null,
"e": 1099,
"s": 1065,
"text": "We all know how clustering works?"
},
{
"code": null,
"e": 1257,
"s": 1099,
"text": "You can think of Connected Components in very layman’s terms as a sort of a hard clustering algorithm which finds clusters/islands in related/connected data."
},
{
"code": null,
"e": 1433,
"s": 1257,
"text": "As a concrete example: Say you have data about roads joining any two cities in the world. And you need to find out all the continents in the world and which city they contain."
},
{
"code": null,
"e": 1487,
"s": 1433,
"text": "How will you achieve that? Come on give some thought."
},
{
"code": null,
"e": 1694,
"s": 1487,
"text": "The connected components algorithm that we use to do this is based on a special case of BFS/DFS. I won’t talk much about how it works here, but we will see how to get the code up and running using Networkx."
},
{
"code": null,
"e": 1897,
"s": 1694,
"text": "From a Retail Perspective: Let us say, we have a lot of customers using a lot of accounts. One way in which we can use the Connected components algorithm is to find out distinct families in our dataset."
},
{
"code": null,
"e": 2186,
"s": 1897,
"text": "We can assume edges(roads) between CustomerIDs based on same credit card usage, or same address or same mobile number, etc. Once we have those connections, we can then run the connected component algorithm on the same to create individual clusters to which we can then assign a family ID."
},
{
"code": null,
"e": 2397,
"s": 2186,
"text": "We can then use these family IDs to provide personalized recommendations based on family needs. We can also use this family ID to fuel our classification algorithms by creating grouped features based on family."
},
{
"code": null,
"e": 2615,
"s": 2397,
"text": "From a Finance Perspective: Another use case would be to capture fraud using these family IDs. If an account has done fraud in the past, it is highly probable that the connected accounts are also susceptible to fraud."
},
{
"code": null,
"e": 2675,
"s": 2615,
"text": "The possibilities are only limited by your own imagination."
},
{
"code": null,
"e": 2761,
"s": 2675,
"text": "We will be using the Networkx module in Python for creating and analyzing our graphs."
},
{
"code": null,
"e": 2887,
"s": 2761,
"text": "Let us start with an example graph which we are using for our purpose. Contains cities and distance information between them."
},
{
"code": null,
"e": 3000,
"s": 2887,
"text": "We first start by creating a list of edges along with the distances which we will add as the weight of the edge:"
},
{
"code": null,
"e": 3790,
"s": 3000,
"text": "edgelist = [['Mannheim', 'Frankfurt', 85], ['Mannheim', 'Karlsruhe', 80], ['Erfurt', 'Wurzburg', 186], ['Munchen', 'Numberg', 167], ['Munchen', 'Augsburg', 84], ['Munchen', 'Kassel', 502], ['Numberg', 'Stuttgart', 183], ['Numberg', 'Wurzburg', 103], ['Numberg', 'Munchen', 167], ['Stuttgart', 'Numberg', 183], ['Augsburg', 'Munchen', 84], ['Augsburg', 'Karlsruhe', 250], ['Kassel', 'Munchen', 502], ['Kassel', 'Frankfurt', 173], ['Frankfurt', 'Mannheim', 85], ['Frankfurt', 'Wurzburg', 217], ['Frankfurt', 'Kassel', 173], ['Wurzburg', 'Numberg', 103], ['Wurzburg', 'Erfurt', 186], ['Wurzburg', 'Frankfurt', 217], ['Karlsruhe', 'Mannheim', 80], ['Karlsruhe', 'Augsburg', 250],[\"Mumbai\", \"Delhi\",400],[\"Delhi\", \"Kolkata\",500],[\"Kolkata\", \"Bangalore\",600],[\"TX\", \"NY\",1200],[\"ALB\", \"NY\",800]]"
},
{
"code": null,
"e": 3828,
"s": 3790,
"text": "Let us create a graph using Networkx:"
},
{
"code": null,
"e": 3913,
"s": 3828,
"text": "g = nx.Graph()for edge in edgelist: g.add_edge(edge[0],edge[1], weight = edge[2])"
},
{
"code": null,
"e": 3991,
"s": 3913,
"text": "Now we want to find out distinct continents and their cities from this graph."
},
{
"code": null,
"e": 4055,
"s": 3991,
"text": "We can now do this using the connected components algorithm as:"
},
{
"code": null,
"e": 4388,
"s": 4055,
"text": "for i, x in enumerate(nx.connected_components(g)): print(\"cc\"+str(i)+\":\",x)------------------------------------------------------------cc0: {'Frankfurt', 'Kassel', 'Munchen', 'Numberg', 'Erfurt', 'Stuttgart', 'Karlsruhe', 'Wurzburg', 'Mannheim', 'Augsburg'}cc1: {'Kolkata', 'Bangalore', 'Mumbai', 'Delhi'}cc2: {'ALB', 'NY', 'TX'}"
},
{
"code": null,
"e": 4584,
"s": 4388,
"text": "As you can see we are able to find distinct components in our data. Just by using Edges and Vertices. This algorithm could be run on different data to satisfy any use case that I presented above."
},
{
"code": null,
"e": 4714,
"s": 4584,
"text": "Continuing with the above example only, we are given a graph with the cities of Germany and the respective distance between them."
},
{
"code": null,
"e": 4826,
"s": 4714,
"text": "You want to find out how to go from Frankfurt (The starting node) to Munchen by covering the shortest distance."
},
{
"code": null,
"e": 4914,
"s": 4826,
"text": "The algorithm that we use for this problem is called Dijkstra. In Dijkstra’s own words:"
},
{
"code": null,
"e": 5840,
"s": 4914,
"text": "What is the shortest way to travel from Rotterdam to Groningen, in general: from given city to given city. It is the algorithm for the shortest path, which I designed in about twenty minutes. One morning I was shopping in Amsterdam with my young fiancée, and tired, we sat down on the café terrace to drink a cup of coffee and I was just thinking about whether I could do this, and I then designed the algorithm for the shortest path. As I said, it was a twenty-minute invention. In fact, it was published in ’59, three years later. The publication is still readable, it is, in fact, quite nice. One of the reasons that it is so nice was that I designed it without pencil and paper. I learned later that one of the advantages of designing without pencil and paper is that you are almost forced to avoid all avoidable complexities. Eventually that algorithm became, to my great amazement, one of the cornerstones of my fame."
},
{
"code": null,
"e": 5932,
"s": 5840,
"text": "— Edsger Dijkstra, in an interview with Philip L. Frana, Communications of the ACM, 2001[3]"
},
{
"code": null,
"e": 6033,
"s": 5932,
"text": "Variations of the Dijkstra algorithm is used extensively in Google Maps to find the shortest routes."
},
{
"code": null,
"e": 6206,
"s": 6033,
"text": "You are in a Walmart Store. You have different Aisles and distance between all the aisles. You want to provide the shortest pathway to the customer from Aisle A to Aisle D."
},
{
"code": null,
"e": 6322,
"s": 6206,
"text": "You have seen how LinkedIn shows up 1st-degree connections, 2nd-degree connections. What goes on behind the scenes?"
},
{
"code": null,
"e": 6572,
"s": 6322,
"text": "print(nx.shortest_path(g, 'Stuttgart','Frankfurt',weight='weight'))print(nx.shortest_path_length(g, 'Stuttgart','Frankfurt',weight='weight'))--------------------------------------------------------['Stuttgart', 'Numberg', 'Wurzburg', 'Frankfurt']503"
},
{
"code": null,
"e": 6630,
"s": 6572,
"text": "You can also find Shortest paths between all pairs using:"
},
{
"code": null,
"e": 7777,
"s": 6630,
"text": "for x in nx.all_pairs_dijkstra_path(g,weight='weight'): print(x)--------------------------------------------------------('Mannheim', {'Mannheim': ['Mannheim'], 'Frankfurt': ['Mannheim', 'Frankfurt'], 'Karlsruhe': ['Mannheim', 'Karlsruhe'], 'Augsburg': ['Mannheim', 'Karlsruhe', 'Augsburg'], 'Kassel': ['Mannheim', 'Frankfurt', 'Kassel'], 'Wurzburg': ['Mannheim', 'Frankfurt', 'Wurzburg'], 'Munchen': ['Mannheim', 'Karlsruhe', 'Augsburg', 'Munchen'], 'Erfurt': ['Mannheim', 'Frankfurt', 'Wurzburg', 'Erfurt'], 'Numberg': ['Mannheim', 'Frankfurt', 'Wurzburg', 'Numberg'], 'Stuttgart': ['Mannheim', 'Frankfurt', 'Wurzburg', 'Numberg', 'Stuttgart']})('Frankfurt', {'Frankfurt': ['Frankfurt'], 'Mannheim': ['Frankfurt', 'Mannheim'], 'Kassel': ['Frankfurt', 'Kassel'], 'Wurzburg': ['Frankfurt', 'Wurzburg'], 'Karlsruhe': ['Frankfurt', 'Mannheim', 'Karlsruhe'], 'Augsburg': ['Frankfurt', 'Mannheim', 'Karlsruhe', 'Augsburg'], 'Munchen': ['Frankfurt', 'Wurzburg', 'Numberg', 'Munchen'], 'Erfurt': ['Frankfurt', 'Wurzburg', 'Erfurt'], 'Numberg': ['Frankfurt', 'Wurzburg', 'Numberg'], 'Stuttgart': ['Frankfurt', 'Wurzburg', 'Numberg', 'Stuttgart']})...."
},
{
"code": null,
"e": 7989,
"s": 7777,
"text": "Now we have another problem. We work for a water pipe laying company or an internet fiber company. We need to connect all the cities in the graph we have using the minimum amount of wire/pipe. How do we do this?"
},
{
"code": null,
"e": 8228,
"s": 7989,
"text": "Minimum spanning trees have direct applications in the design of networks, including computer networks, telecommunications networks, transportation networks, water supply networks, and electrical grids (which they were first invented for)"
},
{
"code": null,
"e": 8289,
"s": 8228,
"text": "MST is used for approximating the traveling salesman problem"
},
{
"code": null,
"e": 8451,
"s": 8289,
"text": "Clustering — First construct MST and then determine a threshold value for breaking some edges in the MST using Intercluster distances and Intracluster distances."
},
{
"code": null,
"e": 8663,
"s": 8451,
"text": "Image Segmentation — It was used for Image segmentation where we first construct an MST on a graph where pixels are nodes and distances between pixels are based on some similarity measure(color, intensity, etc.)"
},
{
"code": null,
"e": 8771,
"s": 8663,
"text": "# nx.minimum_spanning_tree(g) returns a instance of type graphnx.draw_networkx(nx.minimum_spanning_tree(g))"
},
{
"code": null,
"e": 8822,
"s": 8771,
"text": "As you can see the above is the wire we gotta lay."
},
{
"code": null,
"e": 8985,
"s": 8822,
"text": "This is the page sorting algorithm that powered google for a long time. It assigns scores to pages based on the number and quality of incoming and outgoing links."
},
{
"code": null,
"e": 9073,
"s": 8985,
"text": "Pagerank can be used anywhere where we want to estimate node importance in any network."
},
{
"code": null,
"e": 9147,
"s": 9073,
"text": "It has been used for finding the most influential papers using citations."
},
{
"code": null,
"e": 9185,
"s": 9147,
"text": "Has been used by Google to rank pages"
},
{
"code": null,
"e": 9358,
"s": 9185,
"text": "It can be used to rank tweets- User and Tweets as nodes. Create Link between user if user A follows user B and Link between user and Tweets if user tweets/retweets a tweet."
},
{
"code": null,
"e": 9381,
"s": 9358,
"text": "Recommendation engines"
},
{
"code": null,
"e": 9530,
"s": 9381,
"text": "For this exercise, we are going to be using Facebook data. We have a file of edges/links between facebook users. We first create the FB graph using:"
},
{
"code": null,
"e": 9650,
"s": 9530,
"text": "# reading the datasetfb = nx.read_edgelist('../input/facebook-combined.txt', create_using = nx.Graph(), nodetype = int)"
},
{
"code": null,
"e": 9672,
"s": 9650,
"text": "This is how it looks:"
},
{
"code": null,
"e": 9907,
"s": 9672,
"text": "pos = nx.spring_layout(fb)import warningswarnings.filterwarnings('ignore')plt.style.use('fivethirtyeight')plt.rcParams['figure.figsize'] = (20, 15)plt.axis('off')nx.draw_networkx(fb, pos, with_labels = False, node_size = 35)plt.show()"
},
{
"code": null,
"e": 9971,
"s": 9907,
"text": "Now we want to find the users having high influence capability."
},
{
"code": null,
"e": 10105,
"s": 9971,
"text": "Intuitively, the Pagerank algorithm will give a higher score to a user who has a lot of friends who in turn have a lot of FB Friends."
},
{
"code": null,
"e": 10345,
"s": 10105,
"text": "pageranks = nx.pagerank(fb)print(pageranks)------------------------------------------------------{0: 0.006289602618466542, 1: 0.00023590202311540972, 2: 0.00020310565091694562, 3: 0.00022552359869430617, 4: 0.00023849264701222462,........}"
},
{
"code": null,
"e": 10409,
"s": 10345,
"text": "We can get the sorted PageRank or most influential users using:"
},
{
"code": null,
"e": 11130,
"s": 10409,
"text": "import operatorsorted_pagerank = sorted(pageranks.items(), key=operator.itemgetter(1),reverse = True)print(sorted_pagerank)------------------------------------------------------[(3437, 0.007614586844749603), (107, 0.006936420955866114), (1684, 0.0063671621383068295), (0, 0.006289602618466542), (1912, 0.0038769716008844974), (348, 0.0023480969727805783), (686, 0.0022193592598000193), (3980, 0.002170323579009993), (414, 0.0018002990470702262), (698, 0.0013171153138368807), (483, 0.0012974283300616082), (3830, 0.0011844348977671688), (376, 0.0009014073664792464), (2047, 0.000841029154597401), (56, 0.0008039024292749443), (25, 0.000800412660519768), (828, 0.0007886905420662135), (322, 0.0007867992190291396),......]"
},
{
"code": null,
"e": 11180,
"s": 11130,
"text": "The above IDs are for the most influential users."
},
{
"code": null,
"e": 11235,
"s": 11180,
"text": "We can see the subgraph for the most influential user:"
},
{
"code": null,
"e": 11992,
"s": 11235,
"text": "first_degree_connected_nodes = list(fb.neighbors(3437))second_degree_connected_nodes = []for x in first_degree_connected_nodes: second_degree_connected_nodes+=list(fb.neighbors(x))second_degree_connected_nodes.remove(3437)second_degree_connected_nodes = list(set(second_degree_connected_nodes))subgraph_3437 = nx.subgraph(fb,first_degree_connected_nodes+second_degree_connected_nodes)pos = nx.spring_layout(subgraph_3437)node_color = ['yellow' if v == 3437 else 'red' for v in subgraph_3437]node_size = [1000 if v == 3437 else 35 for v in subgraph_3437]plt.style.use('fivethirtyeight')plt.rcParams['figure.figsize'] = (20, 15)plt.axis('off')nx.draw_networkx(subgraph_3437, pos, with_labels = False, node_color=node_color,node_size=node_size )plt.show()"
},
{
"code": null,
"e": 12162,
"s": 11992,
"text": "There are a lot of centrality measures which you can use as features to your machine learning models. I will talk about two of them. You can look at other measures here."
},
{
"code": null,
"e": 12506,
"s": 12162,
"text": "Betweenness Centrality: It is not only the users who have the most friends that are important, the users who connect one geography to another are also important as that lets users see content from diverse geographies. Betweenness centrality quantifies how many times a particular node comes in the shortest chosen path between two other nodes."
},
{
"code": null,
"e": 12576,
"s": 12506,
"text": "Degree Centrality: It is simply the number of connections for a node."
},
{
"code": null,
"e": 12652,
"s": 12576,
"text": "Centrality measures can be used as a feature in any machine learning model."
},
{
"code": null,
"e": 12726,
"s": 12652,
"text": "Here is the code for finding the Betweenness centrality for the subgraph."
},
{
"code": null,
"e": 13063,
"s": 12726,
"text": "pos = nx.spring_layout(subgraph_3437)betweennessCentrality = nx.betweenness_centrality(subgraph_3437,normalized=True, endpoints=True)node_size = [v * 10000 for v in betweennessCentrality.values()]plt.figure(figsize=(20,20))nx.draw_networkx(subgraph_3437, pos=pos, with_labels=False, node_size=node_size )plt.axis('off')"
},
{
"code": null,
"e": 13282,
"s": 13063,
"text": "You can see the nodes sized by their betweenness centrality values here. They can be thought of as information passers. Breaking any of the nodes with a high betweenness Centrality will break the graph into many parts."
},
{
"code": null,
"e": 13392,
"s": 13282,
"text": "In this post, I talked about some of the most influential graph algorithms that have changed the way we live."
},
{
"code": null,
"e": 13512,
"s": 13392,
"text": "With the advent of so much social data, network analysis could help a lot in improving our models and generating value."
},
{
"code": null,
"e": 13566,
"s": 13512,
"text": "And even understanding a little more about the world."
},
{
"code": null,
"e": 13780,
"s": 13566,
"text": "There are a lot of graph algorithms out there, but these are the ones I like the most. Do look into the algorithms in more detail if you like. In this post, I just wanted to get the required breadth into the area."
},
{
"code": null,
"e": 13857,
"s": 13780,
"text": "Let me know if you feel I have left your favorite algorithm in the comments."
},
{
"code": null,
"e": 13904,
"s": 13857,
"text": "Here is the Kaggle Kernel with the whole code."
},
{
"code": null,
"e": 14086,
"s": 13904,
"text": "If you want to read up more on Graph Algorithms here is a Graph Analytics for Big Data course on Coursera by UCSanDiego which I highly recommend to learn the basics of graph theory."
}
] |
How to Create a Strip Chart in R? - GeeksforGeeks | 14 Feb, 2022
In this article, we will be throwing light on the various methodologies to create a strip chart using various functions and its arguments in the R programming language.
In this approach to create a strip chart of the numeric vector, the user needs to simply call the stripchart() function which is an inbuilt function of the R language. Then the user needs to pass the given vector for which the strip chart is needed and further by completing these previous steps the trip chart of the given vector will be returned.
stripchart() function: This function is used to create a strip chart of the given data.
Syntax: stripchart(vector)
Parameter: vector: It is the numeric vector
Example:
In this example, we are creating a strip chart of the vector containing 1000 random numeric values using the stripchart() function in the R programming language.
R
# Create Datax<-c(rnorm(1000)) # Create strip chartstripchart(x)
Output:
In this method of creating the strip chart without overlapping of points, the user needs to call the stripchart() function with the data to simply create the strip chart, and further, the user also needs to use the method argument of this function and set this as “jitter” to get the resulting strip chart with none overlapping individual points.
Syntax: stripchart(data,method=’jitter’)
Parameters:
Data: Data provided to create the strip chart
method: the method to be used to separate coincident points. The default method “overplot” causes such points to be overplotted, but it is also possible to specify “jitter” to jitter the points
Example: In this example, we are creating a strip chart without overlapping the points using the stripchart() function with the method argument set to be “jitter” in the R language.
R
# Create Datax<-c(rnorm(100)) # Create strip chartstripchart(x,method='jitter')
Output:
We can also set the method parameter to be stacked in the case if the user needs to none overlapping individual points in the stripchart, here the points will be plotted as they are in stack in the R programming language
Syntax: stripchart(data,method=’stack’)
Parameters:
Data: Data provided to create the strip chart
method: the method to be used to separate coincident points.
Example: In this example, we are creating a strip chat without overlapping the points using the stripchart() function with the method argument set to be “stack” of the iris sepal width data in the R language.
R
# Create Datax<-Orange$age # Create strip chartstripchart(x,method='stack')
Output:
Under this method to create a vertical strip chart, the user needs to call the stripchart() function with its vertical argument, where the vertical argument should be initialized to true as by default if the value is false to get the resulting strip chart as a vertical strip chart of the given data in R language.
Syntax: stripchart(data,method,vertical=TRUE)
Parameters:
Data: Data provided to create the strip chart
method: the method to be used to separate coincident points.
vertical: when vertical is TRUE the plots are drawn vertically rather than the default horizontal.
Example: In this example, we are creating a vertical strip chart using the vertical argument of the stripchart() function of the given data in the R programming language.
R
# Create Datax<-c(rnorm(100)) # Create strip chartstripchart(x,method='jitter',vertical = TRUE)
Output:
In this approach to create the strip chart of the multiple data, the user simply has to create a list of the multiple data together in a single variable and then pass that variable as the parameter of the stripchart() function to get the strip chart of the all the provided data in R language.
Example: In this example, we are creating a strip chart of the multiple data provided in the method jitter and in the vertical form using the stripchart() function in the R language.
R
# Create Datagfg<-list(x=Orange$age,y=Orange$circumference) # Create strip chartstripchart(gfg,method='jitter', col=c('red','blue'), vertical = TRUE)
Output:
sumitgumber28
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 25020,
"s": 24851,
"text": "In this article, we will be throwing light on the various methodologies to create a strip chart using various functions and its arguments in the R programming language."
},
{
"code": null,
"e": 25369,
"s": 25020,
"text": "In this approach to create a strip chart of the numeric vector, the user needs to simply call the stripchart() function which is an inbuilt function of the R language. Then the user needs to pass the given vector for which the strip chart is needed and further by completing these previous steps the trip chart of the given vector will be returned."
},
{
"code": null,
"e": 25457,
"s": 25369,
"text": "stripchart() function: This function is used to create a strip chart of the given data."
},
{
"code": null,
"e": 25484,
"s": 25457,
"text": "Syntax: stripchart(vector)"
},
{
"code": null,
"e": 25528,
"s": 25484,
"text": "Parameter: vector: It is the numeric vector"
},
{
"code": null,
"e": 25537,
"s": 25528,
"text": "Example:"
},
{
"code": null,
"e": 25699,
"s": 25537,
"text": "In this example, we are creating a strip chart of the vector containing 1000 random numeric values using the stripchart() function in the R programming language."
},
{
"code": null,
"e": 25701,
"s": 25699,
"text": "R"
},
{
"code": "# Create Datax<-c(rnorm(1000)) # Create strip chartstripchart(x)",
"e": 25766,
"s": 25701,
"text": null
},
{
"code": null,
"e": 25774,
"s": 25766,
"text": "Output:"
},
{
"code": null,
"e": 26121,
"s": 25774,
"text": "In this method of creating the strip chart without overlapping of points, the user needs to call the stripchart() function with the data to simply create the strip chart, and further, the user also needs to use the method argument of this function and set this as “jitter” to get the resulting strip chart with none overlapping individual points."
},
{
"code": null,
"e": 26162,
"s": 26121,
"text": "Syntax: stripchart(data,method=’jitter’)"
},
{
"code": null,
"e": 26174,
"s": 26162,
"text": "Parameters:"
},
{
"code": null,
"e": 26220,
"s": 26174,
"text": "Data: Data provided to create the strip chart"
},
{
"code": null,
"e": 26414,
"s": 26220,
"text": "method: the method to be used to separate coincident points. The default method “overplot” causes such points to be overplotted, but it is also possible to specify “jitter” to jitter the points"
},
{
"code": null,
"e": 26596,
"s": 26414,
"text": "Example: In this example, we are creating a strip chart without overlapping the points using the stripchart() function with the method argument set to be “jitter” in the R language."
},
{
"code": null,
"e": 26598,
"s": 26596,
"text": "R"
},
{
"code": "# Create Datax<-c(rnorm(100)) # Create strip chartstripchart(x,method='jitter')",
"e": 26678,
"s": 26598,
"text": null
},
{
"code": null,
"e": 26686,
"s": 26678,
"text": "Output:"
},
{
"code": null,
"e": 26908,
"s": 26686,
"text": "We can also set the method parameter to be stacked in the case if the user needs to none overlapping individual points in the stripchart, here the points will be plotted as they are in stack in the R programming language "
},
{
"code": null,
"e": 26948,
"s": 26908,
"text": "Syntax: stripchart(data,method=’stack’)"
},
{
"code": null,
"e": 26960,
"s": 26948,
"text": "Parameters:"
},
{
"code": null,
"e": 27006,
"s": 26960,
"text": "Data: Data provided to create the strip chart"
},
{
"code": null,
"e": 27067,
"s": 27006,
"text": "method: the method to be used to separate coincident points."
},
{
"code": null,
"e": 27276,
"s": 27067,
"text": "Example: In this example, we are creating a strip chat without overlapping the points using the stripchart() function with the method argument set to be “stack” of the iris sepal width data in the R language."
},
{
"code": null,
"e": 27278,
"s": 27276,
"text": "R"
},
{
"code": "# Create Datax<-Orange$age # Create strip chartstripchart(x,method='stack')",
"e": 27354,
"s": 27278,
"text": null
},
{
"code": null,
"e": 27362,
"s": 27354,
"text": "Output:"
},
{
"code": null,
"e": 27677,
"s": 27362,
"text": "Under this method to create a vertical strip chart, the user needs to call the stripchart() function with its vertical argument, where the vertical argument should be initialized to true as by default if the value is false to get the resulting strip chart as a vertical strip chart of the given data in R language."
},
{
"code": null,
"e": 27723,
"s": 27677,
"text": "Syntax: stripchart(data,method,vertical=TRUE)"
},
{
"code": null,
"e": 27735,
"s": 27723,
"text": "Parameters:"
},
{
"code": null,
"e": 27781,
"s": 27735,
"text": "Data: Data provided to create the strip chart"
},
{
"code": null,
"e": 27842,
"s": 27781,
"text": "method: the method to be used to separate coincident points."
},
{
"code": null,
"e": 27941,
"s": 27842,
"text": "vertical: when vertical is TRUE the plots are drawn vertically rather than the default horizontal."
},
{
"code": null,
"e": 28112,
"s": 27941,
"text": "Example: In this example, we are creating a vertical strip chart using the vertical argument of the stripchart() function of the given data in the R programming language."
},
{
"code": null,
"e": 28114,
"s": 28112,
"text": "R"
},
{
"code": "# Create Datax<-c(rnorm(100)) # Create strip chartstripchart(x,method='jitter',vertical = TRUE)",
"e": 28210,
"s": 28114,
"text": null
},
{
"code": null,
"e": 28218,
"s": 28210,
"text": "Output:"
},
{
"code": null,
"e": 28512,
"s": 28218,
"text": "In this approach to create the strip chart of the multiple data, the user simply has to create a list of the multiple data together in a single variable and then pass that variable as the parameter of the stripchart() function to get the strip chart of the all the provided data in R language."
},
{
"code": null,
"e": 28695,
"s": 28512,
"text": "Example: In this example, we are creating a strip chart of the multiple data provided in the method jitter and in the vertical form using the stripchart() function in the R language."
},
{
"code": null,
"e": 28697,
"s": 28695,
"text": "R"
},
{
"code": "# Create Datagfg<-list(x=Orange$age,y=Orange$circumference) # Create strip chartstripchart(gfg,method='jitter', col=c('red','blue'), vertical = TRUE)",
"e": 28867,
"s": 28697,
"text": null
},
{
"code": null,
"e": 28875,
"s": 28867,
"text": "Output:"
},
{
"code": null,
"e": 28889,
"s": 28875,
"text": "sumitgumber28"
},
{
"code": null,
"e": 28896,
"s": 28889,
"text": "Picked"
},
{
"code": null,
"e": 28907,
"s": 28896,
"text": "R Language"
},
{
"code": null,
"e": 29005,
"s": 28907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29014,
"s": 29005,
"text": "Comments"
},
{
"code": null,
"e": 29027,
"s": 29014,
"text": "Old Comments"
},
{
"code": null,
"e": 29079,
"s": 29027,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29117,
"s": 29079,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29152,
"s": 29117,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29210,
"s": 29152,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29253,
"s": 29210,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29302,
"s": 29253,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29352,
"s": 29302,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 29369,
"s": 29352,
"text": "R - if statement"
},
{
"code": null,
"e": 29406,
"s": 29369,
"text": "How to import an Excel File into R ?"
}
] |
Manacher’s Algorithm | To find the longest palindromic substring from a string, we can use Manacher’s Algorithm. By selecting each character, we will try to find if there any palindrome using left and right pointer. There is another array to store information, from that information we can easily find how long the palindrome is. For each character, the array will store information. After traversing the whole string, we can find the longest palindromic subsequence from the created array.
The time complexity of this algorithm is O(n).
Input:
String: “levelup”
Output:
Longest palindrome is: level
longestPalindrome(text)
Input − The text to find the longest palindrome
Output − The longest common palindrome in the text
Begin
n := text size
if n = 0, then
return null string
n := 2n+1
define array longPal of size n
longPal[0] := 0 and longPal[1] := 1
centerIndex := 1
rightIndex := 2
right := 0
maxPalLength := 0
maxCenterIndex := 0
start := -1 and end := -1, diff := -1
for right := 2 to n-1, do
left := 2*centerIndex – right
longPal[right] := 0
diff := rightIndex – right
if diff > 0, then
longPal[right] := minimum(longPal[left], diff)
while (right + longPal[right]) < n AND (right - longPal[right]) > 0 AND
(right + longPal[right]+1)mod 2 = 0 OR
text[(right + longPal[right] + 1)/2] = text[(right - longPal[right]-1)/2], do
increase longPal[right] by 1
done
if longPal[right] > maxPalLength, then
maxPalLength := longPal[right]
maxCenterIndex := right
if (right + longPal[right]) > rightIndex, then
centerIndex := right
rightIndex := right + longPal[right]
done
start := (maxCenterIndex – maxPalLength)/2
end := start + maxPalLength – 1
palindrome = substring of text[start..end]
return palindrome
End
#include<iostream>
using namespace std;
int min(int a, int b) {
return (a<b)?a:b;
}
string longestPalindrome(string mainString) {
int n = mainString.size();
if(n == 0)
return "";
n = 2*n + 1; //count the next position
int longPal[n]; //array to store longest palindrome length
longPal[0] = 0; longPal[1] = 1;
int centerIndex = 1;
int rightIndex = 2;
int right = 0, left;
int maxPalLength = 0, maxCenterIndex = 0;
int start = -1, end = -1, diff = -1;
for (right = 2; right < n; right++) {
left = 2*centerIndex-right; //calculate left position using center and right
longPal[right] = 0;
diff = rightIndex - right;
if(diff > 0)
longPal[right] = min(longPal[left], diff);
while ( ((right + longPal[right]) < n && (right - longPal[right]) > 0) &&
( ((right + longPal[right] + 1) % 2 == 0) ||
(mainString[(right + longPal[right] + 1)/2] == mainString[(right - longPal[right] - 1)/2] ))) {
longPal[right]++;
}
if(longPal[right] > maxPalLength) { //max palindrome length
maxPalLength = longPal[right];
axCenterIndex = right;
}
if (right + longPal[right] > rightIndex) {
centerIndex = right;
rightIndex = right + longPal[right];
}
}
start = (maxCenterIndex - maxPalLength)/2;
end = start + maxPalLength - 1;
string palindrome;
for(int i=start; i<=end; i++)
palindrome += mainString[i];
return palindrome;
}
int main(int argc, char *argv[]) {
string mainString, palindrome;
cout << "Enter String:";
cin >> mainString;
palindrome = longestPalindrome(mainString);
cout << "Longest palindrome is: " << palindrome << endl;
}
Enter String: levelup
Longest palindrome is: level | [
{
"code": null,
"e": 1530,
"s": 1062,
"text": "To find the longest palindromic substring from a string, we can use Manacher’s Algorithm. By selecting each character, we will try to find if there any palindrome using left and right pointer. There is another array to store information, from that information we can easily find how long the palindrome is. For each character, the array will store information. After traversing the whole string, we can find the longest palindromic subsequence from the created array."
},
{
"code": null,
"e": 1577,
"s": 1530,
"text": "The time complexity of this algorithm is O(n)."
},
{
"code": null,
"e": 1639,
"s": 1577,
"text": "Input:\nString: “levelup”\nOutput:\nLongest palindrome is: level"
},
{
"code": null,
"e": 1663,
"s": 1639,
"text": "longestPalindrome(text)"
},
{
"code": null,
"e": 1711,
"s": 1663,
"text": "Input − The text to find the longest palindrome"
},
{
"code": null,
"e": 1762,
"s": 1711,
"text": "Output − The longest common palindrome in the text"
},
{
"code": null,
"e": 2942,
"s": 1762,
"text": "Begin\n n := text size\n if n = 0, then\n return null string\n n := 2n+1\n\n define array longPal of size n\n longPal[0] := 0 and longPal[1] := 1\n centerIndex := 1\n rightIndex := 2\n right := 0\n maxPalLength := 0\n maxCenterIndex := 0\n start := -1 and end := -1, diff := -1\n\n for right := 2 to n-1, do\n left := 2*centerIndex – right\n longPal[right] := 0\n diff := rightIndex – right\n if diff > 0, then\n longPal[right] := minimum(longPal[left], diff)\n while (right + longPal[right]) < n AND (right - longPal[right]) > 0 AND\n (right + longPal[right]+1)mod 2 = 0 OR\n text[(right + longPal[right] + 1)/2] = text[(right - longPal[right]-1)/2], do\n increase longPal[right] by 1\n done\n\n if longPal[right] > maxPalLength, then\n maxPalLength := longPal[right]\n maxCenterIndex := right\n if (right + longPal[right]) > rightIndex, then\n centerIndex := right\n rightIndex := right + longPal[right]\n done\n start := (maxCenterIndex – maxPalLength)/2\n end := start + maxPalLength – 1\n\n palindrome = substring of text[start..end]\n return palindrome\nEnd"
},
{
"code": null,
"e": 4682,
"s": 2942,
"text": "#include<iostream>\nusing namespace std;\n\nint min(int a, int b) {\n return (a<b)?a:b;\n}\n\nstring longestPalindrome(string mainString) {\n int n = mainString.size();\n if(n == 0)\n return \"\";\n n = 2*n + 1; //count the next position\n int longPal[n]; //array to store longest palindrome length\n longPal[0] = 0; longPal[1] = 1;\n int centerIndex = 1;\n int rightIndex = 2;\n int right = 0, left;\n int maxPalLength = 0, maxCenterIndex = 0;\n int start = -1, end = -1, diff = -1;\n\n for (right = 2; right < n; right++) {\n left = 2*centerIndex-right; //calculate left position using center and right\n longPal[right] = 0;\n diff = rightIndex - right;\n\n if(diff > 0)\n longPal[right] = min(longPal[left], diff);\n while ( ((right + longPal[right]) < n && (right - longPal[right]) > 0) &&\n ( ((right + longPal[right] + 1) % 2 == 0) ||\n (mainString[(right + longPal[right] + 1)/2] == mainString[(right - longPal[right] - 1)/2] ))) {\n longPal[right]++;\n }\n\n if(longPal[right] > maxPalLength) { //max palindrome length\n maxPalLength = longPal[right];\n axCenterIndex = right;\n }\n\n if (right + longPal[right] > rightIndex) {\n centerIndex = right;\n rightIndex = right + longPal[right];\n }\n }\n\n start = (maxCenterIndex - maxPalLength)/2;\n end = start + maxPalLength - 1;\n string palindrome;\n\n for(int i=start; i<=end; i++)\n palindrome += mainString[i];\n return palindrome;\n}\n\nint main(int argc, char *argv[]) {\n string mainString, palindrome;\n cout << \"Enter String:\";\n cin >> mainString;\n palindrome = longestPalindrome(mainString);\n cout << \"Longest palindrome is: \" << palindrome << endl;\n}"
},
{
"code": null,
"e": 4733,
"s": 4682,
"text": "Enter String: levelup\nLongest palindrome is: level"
}
] |
How to change the app language programmatically in android? | This example demonstrates how do I in change the app language programmatically android.
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="@string/hello_world"
android:textSize="30dp"
android:textStyle="bold"
android:textColor="@color/colorPrimary"
android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setAppLocale("bg");
setContentView(R.layout.activity_main);
}
private void setAppLocale(String localeCode){
Resources resources = getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
Configuration config = resources.getConfiguration();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){
config.setLocale(new Locale(localeCode.toLowerCase()));
} else {
config.locale = new Locale(localeCode.toLowerCase());
}
resources.updateConfiguration(config, dm);
}
}
Step 4 − Right click on res → Click New → File. Name the file as value-bg/strings.xml and add following code
<resources>
<string name="app_name">Sample</string>
<string name="hello_world">дравей свят</string>
</resources>
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "This example demonstrates how do I in change the app language programmatically android."
},
{
"code": null,
"e": 1279,
"s": 1150,
"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": 1344,
"s": 1279,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1966,
"s": 1344,
"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=\"@string/hello_world\"\n android:textSize=\"30dp\"\n android:textStyle=\"bold\"\n android:textColor=\"@color/colorPrimary\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2023,
"s": 1966,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2992,
"s": 2023,
"text": "import android.content.res.Configuration;\nimport android.content.res.Resources;\nimport android.os.Build;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.DisplayMetrics;\nimport java.util.Locale;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setAppLocale(\"bg\");\n setContentView(R.layout.activity_main);\n }\n private void setAppLocale(String localeCode){\n Resources resources = getResources();\n DisplayMetrics dm = resources.getDisplayMetrics();\n Configuration config = resources.getConfiguration();\n if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){\n config.setLocale(new Locale(localeCode.toLowerCase()));\n } else {\n config.locale = new Locale(localeCode.toLowerCase());\n }\n resources.updateConfiguration(config, dm);\n }\n}"
},
{
"code": null,
"e": 3101,
"s": 2992,
"text": "Step 4 − Right click on res → Click New → File. Name the file as value-bg/strings.xml and add following code"
},
{
"code": null,
"e": 3221,
"s": 3101,
"text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"hello_world\">дравей свят</string>\n</resources>"
},
{
"code": null,
"e": 3276,
"s": 3221,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3946,
"s": 3276,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4293,
"s": 3946,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4334,
"s": 4293,
"text": "Click here to download the project code."
}
] |
Python | Extract unique tuples from list, Order Irrespective - GeeksforGeeks | 11 Nov, 2019
Sometimes, while working with data, we can have a problem in which we need to check for similar records and eradicate them. When elements are ordered, this case has been discussed before. But sometimes, we might have to ignore the order and has to be removed in case similar elements occur. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + set()The combination of above functionalities can be clubbed to perform this particular task. In this, we check for each pair and add to a set for reference to check if it has existed before and add if it’s a new one.
# Python3 code to demonstrate working of# Extract unique tuples from list(Order Irrespective)# using list comprehension + set() # initialize tuples list test_list = [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)] # printing original list print("The original list : " + str(test_list)) # Extract unique tuples from list(Order Irrespective)# using list comprehension + set()res = set() temp = [res.add((a, b)) for (a, b) in test_list if (a, b) and (b, a) not in res] # printing resultprint("The list after duplicated removal : " + str(list(res)))
The original list : [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]
The list after duplicated removal : [(4, 5), (1, 3), (1, 10)]
Method #2 : Using frozenset()Another method to perform this particular task is to use frozenset(). This function eliminates internally the similar elements irrespective of order.
# Python3 code to demonstrate working of# Extract unique tuples from list(Order Irrespective)# using frozenset() # initialize tuples list test_list = [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)] # printing original list print("The original list : " + str(test_list)) # Extract unique tuples from list(Order Irrespective)# using frozenset()res = set(tuple(frozenset(sub)) for sub in set(test_list)) # printing resultprint("The list after duplicated removal : " + str(list(res)))
The original list : [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]
The list after duplicated removal : [(4, 5), (1, 3), (1, 10)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to print without newline in Python? | [
{
"code": null,
"e": 24513,
"s": 24485,
"text": "\n11 Nov, 2019"
},
{
"code": null,
"e": 24868,
"s": 24513,
"text": "Sometimes, while working with data, we can have a problem in which we need to check for similar records and eradicate them. When elements are ordered, this case has been discussed before. But sometimes, we might have to ignore the order and has to be removed in case similar elements occur. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 25125,
"s": 24868,
"text": "Method #1 : Using list comprehension + set()The combination of above functionalities can be clubbed to perform this particular task. In this, we check for each pair and add to a set for reference to check if it has existed before and add if it’s a new one."
},
{
"code": "# Python3 code to demonstrate working of# Extract unique tuples from list(Order Irrespective)# using list comprehension + set() # initialize tuples list test_list = [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)] # printing original list print(\"The original list : \" + str(test_list)) # Extract unique tuples from list(Order Irrespective)# using list comprehension + set()res = set() temp = [res.add((a, b)) for (a, b) in test_list if (a, b) and (b, a) not in res] # printing resultprint(\"The list after duplicated removal : \" + str(list(res)))",
"e": 25682,
"s": 25125,
"text": null
},
{
"code": null,
"e": 25807,
"s": 25682,
"text": "The original list : [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]\nThe list after duplicated removal : [(4, 5), (1, 3), (1, 10)]\n"
},
{
"code": null,
"e": 25988,
"s": 25809,
"text": "Method #2 : Using frozenset()Another method to perform this particular task is to use frozenset(). This function eliminates internally the similar elements irrespective of order."
},
{
"code": "# Python3 code to demonstrate working of# Extract unique tuples from list(Order Irrespective)# using frozenset() # initialize tuples list test_list = [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)] # printing original list print(\"The original list : \" + str(test_list)) # Extract unique tuples from list(Order Irrespective)# using frozenset()res = set(tuple(frozenset(sub)) for sub in set(test_list)) # printing resultprint(\"The list after duplicated removal : \" + str(list(res)))",
"e": 26467,
"s": 25988,
"text": null
},
{
"code": null,
"e": 26592,
"s": 26467,
"text": "The original list : [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]\nThe list after duplicated removal : [(4, 5), (1, 3), (1, 10)]\n"
},
{
"code": null,
"e": 26613,
"s": 26592,
"text": "Python list-programs"
},
{
"code": null,
"e": 26620,
"s": 26613,
"text": "Python"
},
{
"code": null,
"e": 26636,
"s": 26620,
"text": "Python Programs"
},
{
"code": null,
"e": 26734,
"s": 26636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26743,
"s": 26734,
"text": "Comments"
},
{
"code": null,
"e": 26756,
"s": 26743,
"text": "Old Comments"
},
{
"code": null,
"e": 26774,
"s": 26756,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26809,
"s": 26774,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26831,
"s": 26809,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26863,
"s": 26831,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26905,
"s": 26863,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26927,
"s": 26905,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26973,
"s": 26927,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27011,
"s": 26973,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 27068,
"s": 27011,
"text": "Python program to check whether a number is Prime or not"
}
] |
\dagger - Tex Command | \dagger - Used to draw dagger symbol.
{ \dagger }
\dagger command draws dagger symbol.
\dagger
†
\dagger
†
\dagger
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8024,
"s": 7986,
"text": "\\dagger - Used to draw dagger symbol."
},
{
"code": null,
"e": 8036,
"s": 8024,
"text": "{ \\dagger }"
},
{
"code": null,
"e": 8073,
"s": 8036,
"text": "\\dagger command draws dagger symbol."
},
{
"code": null,
"e": 8088,
"s": 8073,
"text": "\n\\dagger\n\n†\n\n\n"
},
{
"code": null,
"e": 8101,
"s": 8088,
"text": "\\dagger\n\n†\n\n"
},
{
"code": null,
"e": 8109,
"s": 8101,
"text": "\\dagger"
},
{
"code": null,
"e": 8141,
"s": 8109,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8154,
"s": 8141,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8187,
"s": 8154,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8200,
"s": 8187,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8232,
"s": 8200,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8268,
"s": 8232,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8303,
"s": 8268,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8320,
"s": 8303,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8353,
"s": 8320,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8367,
"s": 8353,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8399,
"s": 8367,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8414,
"s": 8399,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8421,
"s": 8414,
"text": " Print"
},
{
"code": null,
"e": 8432,
"s": 8421,
"text": " Add Notes"
}
] |
Serialization and Deserialization in Java with Example - GeeksforGeeks | 07 Oct, 2021
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.The ObjectOutputStream class contains writeObject() method for serializing an Object.
public final void writeObject(Object obj)
throws IOException
The ObjectInputStream class contains readObject() method for deserializing an object.
public final Object readObject()
throws IOException,
ClassNotFoundException
Advantages of Serialization1. To save/persist state of an object.2. To travel an object across a network.
Only the objects of those classes can be serialized which are implementing java.io.Serializable interface.Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and Remote.
Points to remember1. If a parent class has implemented Serializable interface then child class doesn’t need to implement it but vice-versa is not true.2. Only non-static data members are saved via Serialization process.3. Static data members and transient data members are not saved via Serialization process.So, if you don’t want to save value of a non-static data member then make it transient.4. Constructor of object is never called when an object is deserialized.5. Associated objects must be implementing Serializable interface.Example :
class A implements Serializable{
// B also implements Serializable
// interface.
B ob=new B();
}
SerialVersionUIDThe Serialization runtime associates a version number with each Serializable class called a SerialVersionUID, which is used during Deserialization to verify that sender and receiver of a serialized object have loaded classes for that object which are compatible with respect to serialization. If the receiver has loaded a class for the object that has different UID than that of corresponding sender’s class, the Deserialization will result in an InvalidClassException. A Serializable class can declare its own UID explicitly by declaring a field name.It must be static, final and of type long.i.e- ANY-ACCESS-MODIFIER static final long serialVersionUID=42L;
If a serializable class doesn’t explicitly declare a serialVersionUID, then the serialization runtime will calculate a default one for that class based on various aspects of class, as described in Java Object Serialization Specification. However it is strongly recommended that all serializable classes explicitly declare serialVersionUID value, since its computation is highly sensitive to class details that may vary depending on compiler implementations, any change in class or using different id may affect the serialized data.
It is also recommended to use private modifier for UID since it is not useful as inherited member.
serialverThe serialver is a tool that comes with JDK. It is used to get serialVersionUID number for Java classes.You can run the following command to get serialVersionUID
serialver [-classpath classpath] [-show] [classname...]
Example 1:
// Java code for serialization and deserialization // of a Java objectimport java.io.*; class Demo implements java.io.Serializable{ public int a; public String b; // Default constructor public Demo(int a, String b) { this.a = a; this.b = b; } } class Test{ public static void main(String[] args) { Demo object = new Demo(1, "geeksforgeeks"); String filename = "file.ser"; // Serialization try { //Saving of object in a file FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); // Method for serialization of object out.writeObject(object); out.close(); file.close(); System.out.println("Object has been serialized"); } catch(IOException ex) { System.out.println("IOException is caught"); } Demo object1 = null; // Deserialization try { // Reading the object from a file FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); // Method for deserialization of object object1 = (Demo)in.readObject(); in.close(); file.close(); System.out.println("Object has been deserialized "); System.out.println("a = " + object1.a); System.out.println("b = " + object1.b); } catch(IOException ex) { System.out.println("IOException is caught"); } catch(ClassNotFoundException ex) { System.out.println("ClassNotFoundException is caught"); } }}
Output :
Object has been serialized
Object has been deserialized
a = 1
b = geeksforgeeks
Example 2:
// Java code for serialization and deserialization // of a Java objectimport java.io.*; class Emp implements Serializable {private static final long serialversionUID = 129348938L; transient int a; static int b; String name; int age; // Default constructorpublic Emp(String name, int age, int a, int b) { this.name = name; this.age = age; this.a = a; this.b = b; } } public class SerialExample {public static void printdata(Emp object1) { System.out.println("name = " + object1.name); System.out.println("age = " + object1.age); System.out.println("a = " + object1.a); System.out.println("b = " + object1.b); } public static void main(String[] args) { Emp object = new Emp("ab", 20, 2, 1000); String filename = "shubham.txt"; // Serialization try { // Saving of object in a file FileOutputStream file = new FileOutputStream (filename); ObjectOutputStream out = new ObjectOutputStream (file); // Method for serialization of object out.writeObject(object); out.close(); file.close(); System.out.println("Object has been serialized\n" + "Data before Deserialization."); printdata(object); // value of static variable changed object.b = 2000; } catch (IOException ex) { System.out.println("IOException is caught"); } object = null; // Deserialization try { // Reading the object from a file FileInputStream file = new FileInputStream (filename); ObjectInputStream in = new ObjectInputStream (file); // Method for deserialization of object object = (Emp)in.readObject(); in.close(); file.close(); System.out.println("Object has been deserialized\n" + "Data after Deserialization."); printdata(object); // System.out.println("z = " + object1.z); } catch (IOException ex) { System.out.println("IOException is caught"); } catch (ClassNotFoundException ex) { System.out.println("ClassNotFoundException" + " is caught"); } }}
Output:
Object has been serialized
Data before Deserialization.
name = ab
age = 20
a = 2
b = 1000
Object has been deserialized
Data after Deserialization.
name = ab
age = 20
a = 0
b = 2000
Description for Output:You have seen while deserializing the object the values of a and b has changed. The reason being a was marked as transient and b was static.In case of transient variables:- A variable defined with transient keyword is not serialized during serialization process.This variable will be initialized with default value during deserialization. (e.g: for objects it is null, for int it is 0).In case of static Variables:- A variable defined with static keyword is not serialized during serialization process.This variable will be loaded with current value defined in the class during deserialization.
This article is contributed by Mehak Narang and Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vandanakumari5
sagar0719kumar
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
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 | [
{
"code": null,
"e": 22941,
"s": 22913,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 23188,
"s": 22941,
"text": "Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object."
},
{
"code": null,
"e": 23324,
"s": 23188,
"text": "The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform."
},
{
"code": null,
"e": 23493,
"s": 23324,
"text": "To make a Java object serializable we implement the java.io.Serializable interface.The ObjectOutputStream class contains writeObject() method for serializing an Object."
},
{
"code": null,
"e": 23577,
"s": 23493,
"text": "public final void writeObject(Object obj)\n throws IOException"
},
{
"code": null,
"e": 23663,
"s": 23577,
"text": "The ObjectInputStream class contains readObject() method for deserializing an object."
},
{
"code": null,
"e": 23773,
"s": 23663,
"text": "public final Object readObject()\n throws IOException,\n ClassNotFoundException\n"
},
{
"code": null,
"e": 23879,
"s": 23773,
"text": "Advantages of Serialization1. To save/persist state of an object.2. To travel an object across a network."
},
{
"code": null,
"e": 24212,
"s": 23879,
"text": "Only the objects of those classes can be serialized which are implementing java.io.Serializable interface.Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and Remote."
},
{
"code": null,
"e": 24756,
"s": 24212,
"text": "Points to remember1. If a parent class has implemented Serializable interface then child class doesn’t need to implement it but vice-versa is not true.2. Only non-static data members are saved via Serialization process.3. Static data members and transient data members are not saved via Serialization process.So, if you don’t want to save value of a non-static data member then make it transient.4. Constructor of object is never called when an object is deserialized.5. Associated objects must be implementing Serializable interface.Example :"
},
{
"code": null,
"e": 24857,
"s": 24756,
"text": "class A implements Serializable{\n\n// B also implements Serializable\n// interface.\nB ob=new B(); \n}\n"
},
{
"code": null,
"e": 25532,
"s": 24857,
"text": "SerialVersionUIDThe Serialization runtime associates a version number with each Serializable class called a SerialVersionUID, which is used during Deserialization to verify that sender and receiver of a serialized object have loaded classes for that object which are compatible with respect to serialization. If the receiver has loaded a class for the object that has different UID than that of corresponding sender’s class, the Deserialization will result in an InvalidClassException. A Serializable class can declare its own UID explicitly by declaring a field name.It must be static, final and of type long.i.e- ANY-ACCESS-MODIFIER static final long serialVersionUID=42L;"
},
{
"code": null,
"e": 26064,
"s": 25532,
"text": "If a serializable class doesn’t explicitly declare a serialVersionUID, then the serialization runtime will calculate a default one for that class based on various aspects of class, as described in Java Object Serialization Specification. However it is strongly recommended that all serializable classes explicitly declare serialVersionUID value, since its computation is highly sensitive to class details that may vary depending on compiler implementations, any change in class or using different id may affect the serialized data."
},
{
"code": null,
"e": 26163,
"s": 26064,
"text": "It is also recommended to use private modifier for UID since it is not useful as inherited member."
},
{
"code": null,
"e": 26334,
"s": 26163,
"text": "serialverThe serialver is a tool that comes with JDK. It is used to get serialVersionUID number for Java classes.You can run the following command to get serialVersionUID"
},
{
"code": null,
"e": 26390,
"s": 26334,
"text": "serialver [-classpath classpath] [-show] [classname...]"
},
{
"code": null,
"e": 26401,
"s": 26390,
"text": "Example 1:"
},
{
"code": "// Java code for serialization and deserialization // of a Java objectimport java.io.*; class Demo implements java.io.Serializable{ public int a; public String b; // Default constructor public Demo(int a, String b) { this.a = a; this.b = b; } } class Test{ public static void main(String[] args) { Demo object = new Demo(1, \"geeksforgeeks\"); String filename = \"file.ser\"; // Serialization try { //Saving of object in a file FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); // Method for serialization of object out.writeObject(object); out.close(); file.close(); System.out.println(\"Object has been serialized\"); } catch(IOException ex) { System.out.println(\"IOException is caught\"); } Demo object1 = null; // Deserialization try { // Reading the object from a file FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); // Method for deserialization of object object1 = (Demo)in.readObject(); in.close(); file.close(); System.out.println(\"Object has been deserialized \"); System.out.println(\"a = \" + object1.a); System.out.println(\"b = \" + object1.b); } catch(IOException ex) { System.out.println(\"IOException is caught\"); } catch(ClassNotFoundException ex) { System.out.println(\"ClassNotFoundException is caught\"); } }}",
"e": 28297,
"s": 26401,
"text": null
},
{
"code": null,
"e": 28306,
"s": 28297,
"text": "Output :"
},
{
"code": null,
"e": 28387,
"s": 28306,
"text": "Object has been serialized\nObject has been deserialized \na = 1\nb = geeksforgeeks"
},
{
"code": null,
"e": 28400,
"s": 28389,
"text": "Example 2:"
},
{
"code": "// Java code for serialization and deserialization // of a Java objectimport java.io.*; class Emp implements Serializable {private static final long serialversionUID = 129348938L; transient int a; static int b; String name; int age; // Default constructorpublic Emp(String name, int age, int a, int b) { this.name = name; this.age = age; this.a = a; this.b = b; } } public class SerialExample {public static void printdata(Emp object1) { System.out.println(\"name = \" + object1.name); System.out.println(\"age = \" + object1.age); System.out.println(\"a = \" + object1.a); System.out.println(\"b = \" + object1.b); } public static void main(String[] args) { Emp object = new Emp(\"ab\", 20, 2, 1000); String filename = \"shubham.txt\"; // Serialization try { // Saving of object in a file FileOutputStream file = new FileOutputStream (filename); ObjectOutputStream out = new ObjectOutputStream (file); // Method for serialization of object out.writeObject(object); out.close(); file.close(); System.out.println(\"Object has been serialized\\n\" + \"Data before Deserialization.\"); printdata(object); // value of static variable changed object.b = 2000; } catch (IOException ex) { System.out.println(\"IOException is caught\"); } object = null; // Deserialization try { // Reading the object from a file FileInputStream file = new FileInputStream (filename); ObjectInputStream in = new ObjectInputStream (file); // Method for deserialization of object object = (Emp)in.readObject(); in.close(); file.close(); System.out.println(\"Object has been deserialized\\n\" + \"Data after Deserialization.\"); printdata(object); // System.out.println(\"z = \" + object1.z); } catch (IOException ex) { System.out.println(\"IOException is caught\"); } catch (ClassNotFoundException ex) { System.out.println(\"ClassNotFoundException\" + \" is caught\"); } }}",
"e": 30998,
"s": 28400,
"text": null
},
{
"code": null,
"e": 31006,
"s": 30998,
"text": "Output:"
},
{
"code": null,
"e": 31188,
"s": 31006,
"text": "Object has been serialized\nData before Deserialization.\nname = ab\nage = 20\na = 2\nb = 1000\nObject has been deserialized\nData after Deserialization.\nname = ab\nage = 20\na = 0\nb = 2000\n"
},
{
"code": null,
"e": 31806,
"s": 31188,
"text": "Description for Output:You have seen while deserializing the object the values of a and b has changed. The reason being a was marked as transient and b was static.In case of transient variables:- A variable defined with transient keyword is not serialized during serialization process.This variable will be initialized with default value during deserialization. (e.g: for objects it is null, for int it is 0).In case of static Variables:- A variable defined with static keyword is not serialized during serialization process.This variable will be loaded with current value defined in the class during deserialization."
},
{
"code": null,
"e": 32246,
"s": 31806,
"text": "This article is contributed by Mehak Narang and Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32261,
"s": 32246,
"text": "vandanakumari5"
},
{
"code": null,
"e": 32276,
"s": 32261,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 32281,
"s": 32276,
"text": "Java"
},
{
"code": null,
"e": 32286,
"s": 32281,
"text": "Java"
},
{
"code": null,
"e": 32384,
"s": 32286,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32393,
"s": 32384,
"text": "Comments"
},
{
"code": null,
"e": 32406,
"s": 32393,
"text": "Old Comments"
},
{
"code": null,
"e": 32421,
"s": 32406,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32465,
"s": 32421,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32487,
"s": 32465,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32512,
"s": 32487,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32548,
"s": 32512,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 32599,
"s": 32548,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 32629,
"s": 32599,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32660,
"s": 32629,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32692,
"s": 32660,
"text": "Initialize an ArrayList in Java"
}
] |
Another Stage Of Visualization: Be Reactive with Dash | by Jiwon Jeong | Towards Data Science | Dash is an open source python library which enables us to create web applications with Plotly. It makes it easy to build an interactive visualization with simple reactive decorators like a dropdown, a slider bar, and markdown text data. We can even update the plots according to the input data with callbacks, and all these functions are available without Javascript or HTML directly. Plotly is a very powerful tool that enables us to make an informative and effective plot in a handy way and Dash can be considered as a stage for showcasing awesome visualization.
Today I’m going to show you how to create a dashboard with Plotly. And we’ll make a time series line plot and add a dropdown and a slider bar interacting with the plot. There is nice documentation on how to use this library, but I find it could be hard to read the example codes and utilize them at first. So this could be a kind bridge for you to understand how to use Dash with Plotly.
To build a dashboard, we need to install some packages as follows.
pip install plotly==2.5.1pip install dash==0.21.0pip install dash-core-components==0.22.1pip install dash-html-components==0.10.0pip install dash-renderer==0.12.1
As I said above, dash-core-components allows us to build not only graphs but also a dropdown and a text box so that we can update the components accordingly. dash-html-components enables us to use HTML & CSS with Python. It helps us to place HTML components such as Div, H1, and H2 on our dashboard.
If this is your first time using Dash and HTML syntax, it can be a bit complex and hard to read. Therefore I’d recommend you to take the following script as a skeleton guide to Dash. From now on, what we’re going to do is filling this out step by step.
First things first, we import the libraries. You can add other libraries as you need. And then we initialize Dash by calling the Dash class. This is like putting a blank whiteboard on our table and what we are doing is building up additional applications on that board.
# Step 1. Launch the applicationapp = dash.Dash()# Step 2. Import the datasetdf = pd.read_csv('finance-charts-apple.csv')
Now let’s bring some ingredients from the CSV file with pandas. The dataset we’re going to use is the Apple stock price data which is available here.
I won’t cover the details on Plotly itself, but you can find a nice tutorial for Plotly from this video if it’s necessary. You can also learn how to make a 3D plot or Choropleth Map in the series of the video. Here we’ll make a line plot which shows fluctuations in the stock price.
# Step 3. Create a plotly figuretrace_1 = go.Scatter(x = st.Date, y = st['AAPL.High'], name = 'AAPL HIGH', line = dict(width = 2, color = 'rgb(229, 151, 50)'))layout = go.Layout(title = 'Time Series Plot', hovermode = 'closest')fig = go.Figure(data = [trace_1], layout = layout)
Now, it’s time for dash-html-components to come into play. We first put a division and then bring the graph inside it. id is giving a name to this component so that we can call it by its name. You’ll understand what this is for later. And then we make a server to run in step 6. If we set the debug mode equals true, we can easily change and update the app while the server is running.
# Step 4. Create a Dash layoutapp.layout = html.Div([ dcc.Graph(id = 'plot', figure = fig) ])# Step 6. Add the server clauseif __name__ == '__main__': app.run_server(debug = True)
Let’s save this script with the name of app.py and import it on the terminal (or anaconda prompt). Note that the working directory should be the same with where you saved the file.
C:\Users\jjone\Dash> python app.py
If there is no typo or syntax error, you’ll see the localhost address. You can copy and paste it or you can just type localhost:8050 on a new web tab.
We can also have additional components such as putting text data just like HTML. You can find what kind of elements are available here. Let’s put a simple heading and a paragraph on our page.
# Step 4. Create a Dash layoutapp.layout = html.Div([ # adding a header and a paragraph html.Div([ html.H1("This is my first dashboard"), html.P("Learning Dash is so interesting!!") ], style = {'padding' : '50px' , 'backgroundColor' : '#3aaab2'}),# adding a plot dcc.Graph(id = 'plot', figure = fig) ])
On top of the graph, I’m going to put one more division and add a header and a paragraph inside it. We have two major components, html.Div and dcc.Graph. Inside html.Div, there are two additional components, header ( html.H1 ) and a paragraph ( html.P ). We can change the margin of the components or the background color with the style attribute. It should be designated in a dictionary format supporting CSS properties.
Please pay extra care where the parenthesis starts and ends. It’s important to understand the range of the paragraph for each component. As there are so many parenthesizes and square brackets, it can be confusing at first. And It’s so easy to make a syntax mistake as well.
Put this code at step 4 in our template and see the result. We can simply check the outcome by pressing F5 if the server isn’t shut down.
Now I hope you get the idea of what the dash components and the HTML components are. How to put multiple components and how they go along with together.
Let’s try making a dropdown on our dashboard this time. We’re going to make another plot which changes its y-axis according to the given option. By the documentation of dash components, we can putDropdown as follows.
As you can see, the options should be in the format of a dictionary. In our case, the options will be the columns only with the continuous variables, from the 2nd column to the 10th. With the list comprehension, we can make the option dictionary in just one line.
features = st.columns[1:-1]opts = [{'label' : i, 'value' : i} for i in features]
Now instead of the HTML components, we’re going to put the dropdown component at the bottom of the plot. Take a look at the bold font first because others are just for decorating the major two applications.value is the default value of the dropdown.
# Step 4. Create a Dash layoutapp.layout = html.Div([ # adding a plot dcc.Graph(id = 'plot', figure = fig), # dropdown html.P([ html.Label("Choose a feature"), dcc.Dropdown(id = 'opt', options = opts, value = opts[0]) ], style = {'width': '400px', 'fontSize' : '20px', 'padding-left' : '100px', 'display': 'inline-block'}) ])
And just as what we did before, we can replace this code at step 4 in our template and check the outcome.
To update the graph according to the choice of the dropdown, we need to make a connection between input data (the dropdown) and output data (the graph). This will be done by adding a callback function in step 5.
# Step 5. Add callback functions@app.callback(Output('plot', 'figure'), [Input('opt', 'value')])
Do you remember what id we gave to each component? plot and opt. Therefore we can call them with their name as shown above. We take the input data from the options by the name of opt and give the output to the line plot by the name of plot.
def update_figure(X): trace_2 = go.Scatter(x = st.Date, y = st[X], name = X, line = dict(width = 2, color = 'rgb(106, 181, 135)')) fig = go.Figure(data = [trace_1, trace_2], layout = layout) return fig
So we take the input data and then return the output as we want by creating an update function. What is our input data here? It’s the name of the feature variable selected from the dropdown, and we are to make it as the y-axis of our second line plot. As there is nothing to be changed with the trace_1, we can simply add trace_2 to the data list. Now if we put this code at step 5 and rerun app.py, the result will be is shown below.
I’d like to briefly talk about a callback before we move on to the next section. Because it’s one of the most frequently used functions while programming any kind of applications. In a nutshell, a callback is a function that is executed later when it gets the real execution command and it’s usually for the purpose of updating. Callback functions don’t work right after they get the command. These people are kind of lazy. They will do their work after the other command lines are executed and we call them back again with the real execution command.
See how our update_figure() works. This function does his work not right after we import this app but when we give the actual input signal to it by “calling back.” This is what a callback function is. It’s totally fine you use this without understanding but I hope you get the rough idea here. You can also find more details from this article.
Lastly, let’s try a range slider. We’ll add a year range slider to the plot, and it’s very similar to dropdowns. Let’s check the documentation of dash components first.
I think you can easily get the idea by this time. The key point here is how to make a mark dictionary. As the date period starts from (Feb 17 2015) to (Feb 17 2017), I’d like to add 7 marks between the period as follows.
st['Date'] = pd.to_datetime(st.Date)dates = ['2015-02-17', '2015-05-17', '2015-08-17', '2015-11-17', '2016-02-17', '2016-05-17', '2016-08-17', '2016-11-17', '2017-02-17']date_mark = {i : dates[i] for i in range(0, 9)}
Now we can simply put the range slider at the dropdown place. I’ll name it as slider this time. min and max are the minimum and the maximum of the slider and value is the default setting of the slider. Again, all the other parts are designing the HTML components with CSS style.
# Step 4. Create a Dash layoutapp.layout = html.Div([ # adding a plot dcc.Graph(id = 'plot', figure = fig), # range slider html.P([ html.Label("Time Period"), dcc.RangeSlider(id = 'slider', marks = date_mark, min = 0, max = 8, value = [3, 4]) ], style = {'width' : '80%', 'fontSize' : '20px', 'padding-left' : '100px', 'display': 'inline-block'}) ])
After making a slider, what will be the next step? Connecting it to the plot! Again we’ll take the input data from the slider and return the output to the plot. But this time, there is a small trick here. Did you notice that the default value of the slider is a list with two values? Please check the code box above again. value = [3, 4] Different from the dropdown component, the range slider takes two values in a list. Therefore when we get the input data from the slider, there will be two values of the starting and ending value (X[0] , X[1])
# Step 5. Add callback functions@app.callback(Output('plot', 'figure'), [Input('slider', 'value')])def update_figure(X): st2 = st[(st.Date > dates[X[0]]) & (st.Date < dates[X[1]])] trace_1 = go.Scatter(x = st2.Date, y = st2['AAPL.High'], name = 'AAPL HIGH', line = dict(width = 2, color = 'rgb(229, 151, 50)')) fig = go.Figure(data = [trace_1], layout = layout) return fig
Now we’ll filter the data and update the plot with the given period. If you reload the web page again, you’ll see the same result with me.
I think we covered quite a lot of things so far. From putting a graph to adding a callback. Now why don’t we bring it all together? I’d recommend you to review the script below step by step. You can combine all the components of the graph, the dropdown and the slider at step 4 just like replacing and changing modules.
Are you ready to see how our first dashboard looks like? 😃😃🙌🙌 BOOM!!
Great work! Did you enjoy building a dashboard? I hope now you become comfortable reading and understanding other Dash code examples. Dash provides such a nice guide so feel free to explore the sites on your own. You can also check other stuff available in Dash by Plotly.
medium.com
So far our application is locally hosted on your machine. To make it available to other people, we need to deploy it on the web. There are two choices you can take, App authorization and deploying it to Heroku. The first one requires us to install the dash-auth package an there are two different types of authentication, HTTP Basic Auth or Plotly OAuth. You can follow this tutorial.
Another way is by using the hosting platforms such as Heroku, AWS, Google Cloud Platform and so on. Heroku is the easiest way for deploying and you can follow this tutorial. The other platforms are just the same with Heroku.
Beside dropdown, we can also add other components such as text area or uploading data. I recommend you to explore what kind of dash components are available. You can also add as many HTML components as you want and design your board in a much fancier way with CSS properties. If you need to learn some basics of HTML & CSS, you can find a great tutorial from this video.
Thank you for reading and I hope you found this post interesting. If there’s anything need to be corrected, please share your insight with us. I’m always open to talk so feel free to leave comments below and share your thoughts. I also share interesting and useful resources on LinkedIn so feel free to follow and reach me out. I’ll be back again with another interesting story next time! | [
{
"code": null,
"e": 736,
"s": 171,
"text": "Dash is an open source python library which enables us to create web applications with Plotly. It makes it easy to build an interactive visualization with simple reactive decorators like a dropdown, a slider bar, and markdown text data. We can even update the plots according to the input data with callbacks, and all these functions are available without Javascript or HTML directly. Plotly is a very powerful tool that enables us to make an informative and effective plot in a handy way and Dash can be considered as a stage for showcasing awesome visualization."
},
{
"code": null,
"e": 1124,
"s": 736,
"text": "Today I’m going to show you how to create a dashboard with Plotly. And we’ll make a time series line plot and add a dropdown and a slider bar interacting with the plot. There is nice documentation on how to use this library, but I find it could be hard to read the example codes and utilize them at first. So this could be a kind bridge for you to understand how to use Dash with Plotly."
},
{
"code": null,
"e": 1191,
"s": 1124,
"text": "To build a dashboard, we need to install some packages as follows."
},
{
"code": null,
"e": 1354,
"s": 1191,
"text": "pip install plotly==2.5.1pip install dash==0.21.0pip install dash-core-components==0.22.1pip install dash-html-components==0.10.0pip install dash-renderer==0.12.1"
},
{
"code": null,
"e": 1654,
"s": 1354,
"text": "As I said above, dash-core-components allows us to build not only graphs but also a dropdown and a text box so that we can update the components accordingly. dash-html-components enables us to use HTML & CSS with Python. It helps us to place HTML components such as Div, H1, and H2 on our dashboard."
},
{
"code": null,
"e": 1907,
"s": 1654,
"text": "If this is your first time using Dash and HTML syntax, it can be a bit complex and hard to read. Therefore I’d recommend you to take the following script as a skeleton guide to Dash. From now on, what we’re going to do is filling this out step by step."
},
{
"code": null,
"e": 2177,
"s": 1907,
"text": "First things first, we import the libraries. You can add other libraries as you need. And then we initialize Dash by calling the Dash class. This is like putting a blank whiteboard on our table and what we are doing is building up additional applications on that board."
},
{
"code": null,
"e": 2299,
"s": 2177,
"text": "# Step 1. Launch the applicationapp = dash.Dash()# Step 2. Import the datasetdf = pd.read_csv('finance-charts-apple.csv')"
},
{
"code": null,
"e": 2449,
"s": 2299,
"text": "Now let’s bring some ingredients from the CSV file with pandas. The dataset we’re going to use is the Apple stock price data which is available here."
},
{
"code": null,
"e": 2732,
"s": 2449,
"text": "I won’t cover the details on Plotly itself, but you can find a nice tutorial for Plotly from this video if it’s necessary. You can also learn how to make a 3D plot or Choropleth Map in the series of the video. Here we’ll make a line plot which shows fluctuations in the stock price."
},
{
"code": null,
"e": 3098,
"s": 2732,
"text": "# Step 3. Create a plotly figuretrace_1 = go.Scatter(x = st.Date, y = st['AAPL.High'], name = 'AAPL HIGH', line = dict(width = 2, color = 'rgb(229, 151, 50)'))layout = go.Layout(title = 'Time Series Plot', hovermode = 'closest')fig = go.Figure(data = [trace_1], layout = layout)"
},
{
"code": null,
"e": 3484,
"s": 3098,
"text": "Now, it’s time for dash-html-components to come into play. We first put a division and then bring the graph inside it. id is giving a name to this component so that we can call it by its name. You’ll understand what this is for later. And then we make a server to run in step 6. If we set the debug mode equals true, we can easily change and update the app while the server is running."
},
{
"code": null,
"e": 3703,
"s": 3484,
"text": "# Step 4. Create a Dash layoutapp.layout = html.Div([ dcc.Graph(id = 'plot', figure = fig) ])# Step 6. Add the server clauseif __name__ == '__main__': app.run_server(debug = True)"
},
{
"code": null,
"e": 3884,
"s": 3703,
"text": "Let’s save this script with the name of app.py and import it on the terminal (or anaconda prompt). Note that the working directory should be the same with where you saved the file."
},
{
"code": null,
"e": 3919,
"s": 3884,
"text": "C:\\Users\\jjone\\Dash> python app.py"
},
{
"code": null,
"e": 4070,
"s": 3919,
"text": "If there is no typo or syntax error, you’ll see the localhost address. You can copy and paste it or you can just type localhost:8050 on a new web tab."
},
{
"code": null,
"e": 4262,
"s": 4070,
"text": "We can also have additional components such as putting text data just like HTML. You can find what kind of elements are available here. Let’s put a simple heading and a paragraph on our page."
},
{
"code": null,
"e": 4750,
"s": 4262,
"text": "# Step 4. Create a Dash layoutapp.layout = html.Div([ # adding a header and a paragraph html.Div([ html.H1(\"This is my first dashboard\"), html.P(\"Learning Dash is so interesting!!\") ], style = {'padding' : '50px' , 'backgroundColor' : '#3aaab2'}),# adding a plot dcc.Graph(id = 'plot', figure = fig) ])"
},
{
"code": null,
"e": 5172,
"s": 4750,
"text": "On top of the graph, I’m going to put one more division and add a header and a paragraph inside it. We have two major components, html.Div and dcc.Graph. Inside html.Div, there are two additional components, header ( html.H1 ) and a paragraph ( html.P ). We can change the margin of the components or the background color with the style attribute. It should be designated in a dictionary format supporting CSS properties."
},
{
"code": null,
"e": 5446,
"s": 5172,
"text": "Please pay extra care where the parenthesis starts and ends. It’s important to understand the range of the paragraph for each component. As there are so many parenthesizes and square brackets, it can be confusing at first. And It’s so easy to make a syntax mistake as well."
},
{
"code": null,
"e": 5584,
"s": 5446,
"text": "Put this code at step 4 in our template and see the result. We can simply check the outcome by pressing F5 if the server isn’t shut down."
},
{
"code": null,
"e": 5737,
"s": 5584,
"text": "Now I hope you get the idea of what the dash components and the HTML components are. How to put multiple components and how they go along with together."
},
{
"code": null,
"e": 5954,
"s": 5737,
"text": "Let’s try making a dropdown on our dashboard this time. We’re going to make another plot which changes its y-axis according to the given option. By the documentation of dash components, we can putDropdown as follows."
},
{
"code": null,
"e": 6218,
"s": 5954,
"text": "As you can see, the options should be in the format of a dictionary. In our case, the options will be the columns only with the continuous variables, from the 2nd column to the 10th. With the list comprehension, we can make the option dictionary in just one line."
},
{
"code": null,
"e": 6299,
"s": 6218,
"text": "features = st.columns[1:-1]opts = [{'label' : i, 'value' : i} for i in features]"
},
{
"code": null,
"e": 6549,
"s": 6299,
"text": "Now instead of the HTML components, we’re going to put the dropdown component at the bottom of the plot. Take a look at the bold font first because others are just for decorating the major two applications.value is the default value of the dropdown."
},
{
"code": null,
"e": 7187,
"s": 6549,
"text": "# Step 4. Create a Dash layoutapp.layout = html.Div([ # adding a plot dcc.Graph(id = 'plot', figure = fig), # dropdown html.P([ html.Label(\"Choose a feature\"), dcc.Dropdown(id = 'opt', options = opts, value = opts[0]) ], style = {'width': '400px', 'fontSize' : '20px', 'padding-left' : '100px', 'display': 'inline-block'}) ])"
},
{
"code": null,
"e": 7293,
"s": 7187,
"text": "And just as what we did before, we can replace this code at step 4 in our template and check the outcome."
},
{
"code": null,
"e": 7505,
"s": 7293,
"text": "To update the graph according to the choice of the dropdown, we need to make a connection between input data (the dropdown) and output data (the graph). This will be done by adding a callback function in step 5."
},
{
"code": null,
"e": 7614,
"s": 7505,
"text": "# Step 5. Add callback functions@app.callback(Output('plot', 'figure'), [Input('opt', 'value')])"
},
{
"code": null,
"e": 7855,
"s": 7614,
"text": "Do you remember what id we gave to each component? plot and opt. Therefore we can call them with their name as shown above. We take the input data from the options by the name of opt and give the output to the line plot by the name of plot."
},
{
"code": null,
"e": 8147,
"s": 7855,
"text": "def update_figure(X): trace_2 = go.Scatter(x = st.Date, y = st[X], name = X, line = dict(width = 2, color = 'rgb(106, 181, 135)')) fig = go.Figure(data = [trace_1, trace_2], layout = layout) return fig"
},
{
"code": null,
"e": 8582,
"s": 8147,
"text": "So we take the input data and then return the output as we want by creating an update function. What is our input data here? It’s the name of the feature variable selected from the dropdown, and we are to make it as the y-axis of our second line plot. As there is nothing to be changed with the trace_1, we can simply add trace_2 to the data list. Now if we put this code at step 5 and rerun app.py, the result will be is shown below."
},
{
"code": null,
"e": 9134,
"s": 8582,
"text": "I’d like to briefly talk about a callback before we move on to the next section. Because it’s one of the most frequently used functions while programming any kind of applications. In a nutshell, a callback is a function that is executed later when it gets the real execution command and it’s usually for the purpose of updating. Callback functions don’t work right after they get the command. These people are kind of lazy. They will do their work after the other command lines are executed and we call them back again with the real execution command."
},
{
"code": null,
"e": 9478,
"s": 9134,
"text": "See how our update_figure() works. This function does his work not right after we import this app but when we give the actual input signal to it by “calling back.” This is what a callback function is. It’s totally fine you use this without understanding but I hope you get the rough idea here. You can also find more details from this article."
},
{
"code": null,
"e": 9647,
"s": 9478,
"text": "Lastly, let’s try a range slider. We’ll add a year range slider to the plot, and it’s very similar to dropdowns. Let’s check the documentation of dash components first."
},
{
"code": null,
"e": 9868,
"s": 9647,
"text": "I think you can easily get the idea by this time. The key point here is how to make a mark dictionary. As the date period starts from (Feb 17 2015) to (Feb 17 2017), I’d like to add 7 marks between the period as follows."
},
{
"code": null,
"e": 10104,
"s": 9868,
"text": "st['Date'] = pd.to_datetime(st.Date)dates = ['2015-02-17', '2015-05-17', '2015-08-17', '2015-11-17', '2016-02-17', '2016-05-17', '2016-08-17', '2016-11-17', '2017-02-17']date_mark = {i : dates[i] for i in range(0, 9)}"
},
{
"code": null,
"e": 10383,
"s": 10104,
"text": "Now we can simply put the range slider at the dropdown place. I’ll name it as slider this time. min and max are the minimum and the maximum of the slider and value is the default setting of the slider. Again, all the other parts are designing the HTML components with CSS style."
},
{
"code": null,
"e": 11121,
"s": 10383,
"text": "# Step 4. Create a Dash layoutapp.layout = html.Div([ # adding a plot dcc.Graph(id = 'plot', figure = fig), # range slider html.P([ html.Label(\"Time Period\"), dcc.RangeSlider(id = 'slider', marks = date_mark, min = 0, max = 8, value = [3, 4]) ], style = {'width' : '80%', 'fontSize' : '20px', 'padding-left' : '100px', 'display': 'inline-block'}) ])"
},
{
"code": null,
"e": 11669,
"s": 11121,
"text": "After making a slider, what will be the next step? Connecting it to the plot! Again we’ll take the input data from the slider and return the output to the plot. But this time, there is a small trick here. Did you notice that the default value of the slider is a list with two values? Please check the code box above again. value = [3, 4] Different from the dropdown component, the range slider takes two values in a list. Therefore when we get the input data from the slider, there will be two values of the starting and ending value (X[0] , X[1])"
},
{
"code": null,
"e": 12147,
"s": 11669,
"text": "# Step 5. Add callback functions@app.callback(Output('plot', 'figure'), [Input('slider', 'value')])def update_figure(X): st2 = st[(st.Date > dates[X[0]]) & (st.Date < dates[X[1]])] trace_1 = go.Scatter(x = st2.Date, y = st2['AAPL.High'], name = 'AAPL HIGH', line = dict(width = 2, color = 'rgb(229, 151, 50)')) fig = go.Figure(data = [trace_1], layout = layout) return fig"
},
{
"code": null,
"e": 12286,
"s": 12147,
"text": "Now we’ll filter the data and update the plot with the given period. If you reload the web page again, you’ll see the same result with me."
},
{
"code": null,
"e": 12606,
"s": 12286,
"text": "I think we covered quite a lot of things so far. From putting a graph to adding a callback. Now why don’t we bring it all together? I’d recommend you to review the script below step by step. You can combine all the components of the graph, the dropdown and the slider at step 4 just like replacing and changing modules."
},
{
"code": null,
"e": 12675,
"s": 12606,
"text": "Are you ready to see how our first dashboard looks like? 😃😃🙌🙌 BOOM!!"
},
{
"code": null,
"e": 12948,
"s": 12675,
"text": "Great work! Did you enjoy building a dashboard? I hope now you become comfortable reading and understanding other Dash code examples. Dash provides such a nice guide so feel free to explore the sites on your own. You can also check other stuff available in Dash by Plotly."
},
{
"code": null,
"e": 12959,
"s": 12948,
"text": "medium.com"
},
{
"code": null,
"e": 13344,
"s": 12959,
"text": "So far our application is locally hosted on your machine. To make it available to other people, we need to deploy it on the web. There are two choices you can take, App authorization and deploying it to Heroku. The first one requires us to install the dash-auth package an there are two different types of authentication, HTTP Basic Auth or Plotly OAuth. You can follow this tutorial."
},
{
"code": null,
"e": 13569,
"s": 13344,
"text": "Another way is by using the hosting platforms such as Heroku, AWS, Google Cloud Platform and so on. Heroku is the easiest way for deploying and you can follow this tutorial. The other platforms are just the same with Heroku."
},
{
"code": null,
"e": 13940,
"s": 13569,
"text": "Beside dropdown, we can also add other components such as text area or uploading data. I recommend you to explore what kind of dash components are available. You can also add as many HTML components as you want and design your board in a much fancier way with CSS properties. If you need to learn some basics of HTML & CSS, you can find a great tutorial from this video."
}
] |
Stop and Wait protocol, its problems and solutions - GeeksforGeeks | 08 Jun, 2021
It is the simplest flow control method in which the sender will send the packet and then wait for the acknowledgement by the receiver that it has received the packet then it will send the next packet.
Stop and wait protocol is very easy to implement.
Total time taken to send is,
Ttotal = Tt(data) + Tp + Tq + Tprocess + Tt(ack) + Tp
( since, Tq and Tprocess = 0)
Ttotal = Tt(data) + 2Tp + Tt(ack)
Ttotal = Tt(data) + 2Tp
(when Tt(ack) is negligible)
Efficiency
= useful time / total cycle time
= Tt / (Tt+2Tp)
= 1 / (1+2a) [a = Tp/Tt]
Note: Stop and wait is better for less distance. Hence it is a good protocol for LAN. Stop and wait is favorable for bigger packets.
What if the data packet is lost in between ?
According to sender, receiver is busy but actually data is lost.Receiver will assume, no packet has been sent by sender.Both will be waiting for each other and there will be a deadlock.
According to sender, receiver is busy but actually data is lost.
Receiver will assume, no packet has been sent by sender.
Both will be waiting for each other and there will be a deadlock.
Need for timeout timer: A timer is applied and the receiver will wait till the timeout timer for the data after that it will confirm that the data has been lost.
What if the data packet has been lost ? After timeout timer expires, sender will assume that the data is lost but actually the acknowledgement is lost. By assuming this it will send the data packet again but according to receiver it is a new data packet, hence it will give rise to duplicate packet problem.
To eliminate duplicate packet problem sequence number is added to the data packet. So using packet numbers it can easily determine the duplicate packets.
What if there is a delay in receiving acknowledgement ?
According to sender, the acknowledgement of packet 1 is delayed and packet 2 has been lost. But the receiver assumes that the acknowledgement that has been received was of packet 2. This problem is called missing packet problem. Missing packet problem can be solved if acknowledgements also have numbers.
sagar0719kumar
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
RSA Algorithm in Cryptography
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Socket Programming in Python
ACID Properties in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Normal Forms in DBMS
Differences between TCP and UDP | [
{
"code": null,
"e": 24236,
"s": 24208,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 24438,
"s": 24236,
"text": "It is the simplest flow control method in which the sender will send the packet and then wait for the acknowledgement by the receiver that it has received the packet then it will send the next packet. "
},
{
"code": null,
"e": 24489,
"s": 24438,
"text": "Stop and wait protocol is very easy to implement. "
},
{
"code": null,
"e": 24522,
"s": 24491,
"text": "Total time taken to send is, "
},
{
"code": null,
"e": 24705,
"s": 24522,
"text": "Ttotal = Tt(data) + Tp + Tq + Tprocess + Tt(ack) + Tp \n\n( since, Tq and Tprocess = 0)\n\nTtotal = Tt(data) + 2Tp + Tt(ack)\nTtotal = Tt(data) + 2Tp \n\n(when Tt(ack) is negligible) "
},
{
"code": null,
"e": 24798,
"s": 24707,
"text": "Efficiency \n= useful time / total cycle time \n= Tt / (Tt+2Tp)\n= 1 / (1+2a) [a = Tp/Tt] "
},
{
"code": null,
"e": 24932,
"s": 24798,
"text": "Note: Stop and wait is better for less distance. Hence it is a good protocol for LAN. Stop and wait is favorable for bigger packets. "
},
{
"code": null,
"e": 24978,
"s": 24932,
"text": "What if the data packet is lost in between ? "
},
{
"code": null,
"e": 25168,
"s": 24982,
"text": "According to sender, receiver is busy but actually data is lost.Receiver will assume, no packet has been sent by sender.Both will be waiting for each other and there will be a deadlock."
},
{
"code": null,
"e": 25233,
"s": 25168,
"text": "According to sender, receiver is busy but actually data is lost."
},
{
"code": null,
"e": 25290,
"s": 25233,
"text": "Receiver will assume, no packet has been sent by sender."
},
{
"code": null,
"e": 25356,
"s": 25290,
"text": "Both will be waiting for each other and there will be a deadlock."
},
{
"code": null,
"e": 25519,
"s": 25356,
"text": "Need for timeout timer: A timer is applied and the receiver will wait till the timeout timer for the data after that it will confirm that the data has been lost. "
},
{
"code": null,
"e": 25828,
"s": 25519,
"text": "What if the data packet has been lost ? After timeout timer expires, sender will assume that the data is lost but actually the acknowledgement is lost. By assuming this it will send the data packet again but according to receiver it is a new data packet, hence it will give rise to duplicate packet problem. "
},
{
"code": null,
"e": 25983,
"s": 25828,
"text": "To eliminate duplicate packet problem sequence number is added to the data packet. So using packet numbers it can easily determine the duplicate packets. "
},
{
"code": null,
"e": 26040,
"s": 25983,
"text": "What if there is a delay in receiving acknowledgement ? "
},
{
"code": null,
"e": 26348,
"s": 26042,
"text": "According to sender, the acknowledgement of packet 1 is delayed and packet 2 has been lost. But the receiver assumes that the acknowledgement that has been received was of packet 2. This problem is called missing packet problem. Missing packet problem can be solved if acknowledgements also have numbers. "
},
{
"code": null,
"e": 26363,
"s": 26348,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 26381,
"s": 26363,
"text": "Computer Networks"
},
{
"code": null,
"e": 26389,
"s": 26381,
"text": "GATE CS"
},
{
"code": null,
"e": 26407,
"s": 26389,
"text": "Computer Networks"
},
{
"code": null,
"e": 26505,
"s": 26407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26514,
"s": 26505,
"text": "Comments"
},
{
"code": null,
"e": 26527,
"s": 26514,
"text": "Old Comments"
},
{
"code": null,
"e": 26565,
"s": 26527,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26595,
"s": 26565,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 26627,
"s": 26595,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 26666,
"s": 26627,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 26695,
"s": 26666,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 26719,
"s": 26695,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 26746,
"s": 26719,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 26795,
"s": 26746,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 26816,
"s": 26795,
"text": "Normal Forms in DBMS"
}
] |
Get the date/time of the last change to a MySQL database? | You can get the date/time of the last change to a MySQL database with the help of INFORMATION_SCHEMA.TABLES. The syntax is as follows −
SELECT update_time
FROM information_schema.tables
WHERE table_schema = 'yourDatabaseName’'
AND table_name = 'yourTableName’;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table TblUpdate
-> (
-> Id int not null auto_increment primary key,
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.49 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into TblUpdate(Name) values('John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into TblUpdate(Name) values('Carol');
Query OK, 1 row affected (0.22 sec)
Now you can display all records from the table using select statement. The query is as follows −
mysql> select *from TblUpdate;
+----+-------+
| Id | Name |
+----+-------+
| 1 | John |
| 2 | Carol |
+----+-------+
2 rows in set (0.00 sec)
Now you can update the table using the following query −
mysql> update TblUpdate set Name = 'James' where Id=2;
Query OK, 1 row affected (0.15 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Therefore, we just updated our table above. Now get the date/time of the last change to a MySQL database using the following query −
mysql> SELECT update_time
-> FROM information_schema.tables
-> WHERE table_schema = 'sample'
-> AND table_name = 'TblUpdate'
-> ;
The following is the output displaying we updated the database on 2019-02-09 22:49:44 −
+---------------------+
| UPDATE_TIME |
+---------------------+
| 2019-02-09 22:49:44 |
+---------------------+
1 row in set (0.89 sec) | [
{
"code": null,
"e": 1198,
"s": 1062,
"text": "You can get the date/time of the last change to a MySQL database with the help of INFORMATION_SCHEMA.TABLES. The syntax is as follows −"
},
{
"code": null,
"e": 1323,
"s": 1198,
"text": "SELECT update_time\nFROM information_schema.tables\nWHERE table_schema = 'yourDatabaseName’'\nAND table_name = 'yourTableName’;"
},
{
"code": null,
"e": 1422,
"s": 1323,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1579,
"s": 1422,
"text": "mysql> create table TblUpdate\n -> (\n -> Id int not null auto_increment primary key,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.49 sec)"
},
{
"code": null,
"e": 1660,
"s": 1579,
"text": "Insert some records in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 1835,
"s": 1660,
"text": "mysql> insert into TblUpdate(Name) values('John');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into TblUpdate(Name) values('Carol');\nQuery OK, 1 row affected (0.22 sec)"
},
{
"code": null,
"e": 1932,
"s": 1835,
"text": "Now you can display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 1963,
"s": 1932,
"text": "mysql> select *from TblUpdate;"
},
{
"code": null,
"e": 2074,
"s": 1963,
"text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | John |\n| 2 | Carol |\n+----+-------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2131,
"s": 2074,
"text": "Now you can update the table using the following query −"
},
{
"code": null,
"e": 2261,
"s": 2131,
"text": "mysql> update TblUpdate set Name = 'James' where Id=2;\nQuery OK, 1 row affected (0.15 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 2394,
"s": 2261,
"text": "Therefore, we just updated our table above. Now get the date/time of the last change to a MySQL database using the following query −"
},
{
"code": null,
"e": 2536,
"s": 2394,
"text": "mysql> SELECT update_time\n -> FROM information_schema.tables\n -> WHERE table_schema = 'sample'\n -> AND table_name = 'TblUpdate'\n -> ;"
},
{
"code": null,
"e": 2624,
"s": 2536,
"text": "The following is the output displaying we updated the database on 2019-02-09 22:49:44 −"
},
{
"code": null,
"e": 2768,
"s": 2624,
"text": "+---------------------+\n| UPDATE_TIME |\n+---------------------+\n| 2019-02-09 22:49:44 |\n+---------------------+\n1 row in set (0.89 sec)"
}
] |
LISP - Error Handling | In Common LISP terminology, exceptions are called conditions.
In fact, conditions are more general than exceptions in traditional programming languages, because a condition represents any occurrence, error, or not, which might affect various levels of function call stack.
Condition handling mechanism in LISP, handles such situations in such a way that conditions are used to signal warning (say by printing an warning) while the upper level code on the call stack can continue its work.
The condition handling system in LISP has three parts −
Signalling a condition
Handling the condition
Restart the process
Let us take up an example of handling a condition arising out of divide by zero condition, to explain the concepts here.
You need to take the following steps for handling a condition −
Define the Condition − "A condition is an object whose class indicates the general nature of the condition and whose instance data carries information about the details of the particular circumstances that lead to the condition being signalled".
The define-condition macro is used for defining a condition, which has the following syntax −
Define the Condition − "A condition is an object whose class indicates the general nature of the condition and whose instance data carries information about the details of the particular circumstances that lead to the condition being signalled".
The define-condition macro is used for defining a condition, which has the following syntax −
(define-condition condition-name (error)
((text :initarg :text :reader text))
)
New condition objects are created with MAKE-CONDITION macro, which initializes the slots of the new condition based on the :initargs argument.
New condition objects are created with MAKE-CONDITION macro, which initializes the slots of the new condition based on the :initargs argument.
In our example, the following code defines the condition −
(define-condition on-division-by-zero (error)
((message :initarg :message :reader message))
)
Writing the Handlers − a condition handler is a code that are used for handling the condition signalled thereon. It is generally written in one of the higher level functions that call the erroring function. When a condition is signalled, the signalling mechanism searches for an appropriate handler based on the condition's class.
Each handler consists of −
Type specifier, that indicates the type of condition it can handle
A function that takes a single argument, the condition
When a condition is signalled, the signalling mechanism finds the most recently established handler that is compatible with the condition type and calls its function.
The macro handler-case establishes a condition handler. The basic form of a handler-case −
Writing the Handlers − a condition handler is a code that are used for handling the condition signalled thereon. It is generally written in one of the higher level functions that call the erroring function. When a condition is signalled, the signalling mechanism searches for an appropriate handler based on the condition's class.
Each handler consists of −
Type specifier, that indicates the type of condition it can handle
A function that takes a single argument, the condition
When a condition is signalled, the signalling mechanism finds the most recently established handler that is compatible with the condition type and calls its function.
The macro handler-case establishes a condition handler. The basic form of a handler-case −
(handler-case expression error-clause*)
Where, each error clause is of the form −
condition-type ([var]) code)
Restarting Phase
This is the code that actually recovers your program from errors, and condition handlers can then handle a condition by invoking an appropriate restart. The restart code is generally place in middle-level or low-level functions and the condition handlers are placed into the upper levels of the application.
The handler-bind macro allows you to provide a restart function, and allows you to continue at the lower level functions without unwinding the function call stack. In other words, the flow of control will still be in the lower level function.
The basic form of handler-bind is as follows −
Restarting Phase
This is the code that actually recovers your program from errors, and condition handlers can then handle a condition by invoking an appropriate restart. The restart code is generally place in middle-level or low-level functions and the condition handlers are placed into the upper levels of the application.
The handler-bind macro allows you to provide a restart function, and allows you to continue at the lower level functions without unwinding the function call stack. In other words, the flow of control will still be in the lower level function.
The basic form of handler-bind is as follows −
(handler-bind (binding*) form*)
Where each binding is a list of the following −
a condition type
a handler function of one argument
The invoke-restart macro finds and invokes the most recently bound restart function with the specified name as argument.
You can have multiple restarts.
In this example, we demonstrate the above concepts by writing a function named division-function, which will create an error condition if the divisor argument is zero. We have three anonymous functions that provide three ways to come out of it - by returning a value 1, by sending a divisor 2 and recalculating, or by returning 1.
Create a new source code file named main.lisp and type the following code in it.
(define-condition on-division-by-zero (error)
((message :initarg :message :reader message))
)
(defun handle-infinity ()
(restart-case
(let ((result 0))
(setf result (division-function 10 0))
(format t "Value: ~a~%" result)
)
(just-continue () nil)
)
)
(defun division-function (value1 value2)
(restart-case
(if (/= value2 0)
(/ value1 value2)
(error 'on-division-by-zero :message "denominator is zero")
)
(return-zero () 0)
(return-value (r) r)
(recalc-using (d) (division-function value1 d))
)
)
(defun high-level-code ()
(handler-bind
(
(on-division-by-zero
#'(lambda (c)
(format t "error signaled: ~a~%" (message c))
(invoke-restart 'return-zero)
)
)
(handle-infinity)
)
)
)
(handler-bind
(
(on-division-by-zero
#'(lambda (c)
(format t "error signaled: ~a~%" (message c))
(invoke-restart 'return-value 1)
)
)
)
(handle-infinity)
)
(handler-bind
(
(on-division-by-zero
#'(lambda (c)
(format t "error signaled: ~a~%" (message c))
(invoke-restart 'recalc-using 2)
)
)
)
(handle-infinity)
)
(handler-bind
(
(on-division-by-zero
#'(lambda (c)
(format t "error signaled: ~a~%" (message c))
(invoke-restart 'just-continue)
)
)
)
(handle-infinity)
)
(format t "Done."))
When you execute the code, it returns the following result −
error signaled: denominator is zero
Value: 1
error signaled: denominator is zero
Value: 5
error signaled: denominator is zero
Done.
Apart from the 'Condition System', as discussed above, Common LISP also provides various functions that may be called for signalling an error. Handling of an error, when signalled, is however, implementation-dependent.
The following table provides commonly used functions signalling warnings, breaks, non-fatal and fatal errors.
The user program specifies an error message (a string). The functions process this message and may/may not display it to the user.
The error messages should be constructed by applying the format function, should not contain a newline character at either the beginning or end, and need not indicate error, as the LISP system will take care of these according to its preferred style.
error format-string &rest args
It signals a fatal error. It is impossible to continue from this kind of error; thus error will never return to its caller.
cerror continue-format-string error-format-string &rest args
It signals an error and enters the debugger. However, it allows the program to be continued from the debugger after resolving the error.
warn format-string &rest args
it prints an error message but normally doesn't go into the debugger
break &optional format-string &rest args
It prints the message and goes directly into the debugger, without allowing any possibility of interception by programmed error-handling facilities
In this example, the factorial function calculates factorial of a number; however, if the argument is negative, it raises an error condition.
Create a new source code file named main.lisp and type the following code in it.
(defun factorial (x)
(cond ((or (not (typep x 'integer)) (minusp x))
(error "~S is a negative number." x))
((zerop x) 1)
(t (* x (factorial (- x 1))))
)
)
(write(factorial 5))
(terpri)
(write(factorial -1))
When you execute the code, it returns the following result −
120
*** - -1 is a negative number.
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2122,
"s": 2060,
"text": "In Common LISP terminology, exceptions are called conditions."
},
{
"code": null,
"e": 2333,
"s": 2122,
"text": "In fact, conditions are more general than exceptions in traditional programming languages, because a condition represents any occurrence, error, or not, which might affect various levels of function call stack."
},
{
"code": null,
"e": 2549,
"s": 2333,
"text": "Condition handling mechanism in LISP, handles such situations in such a way that conditions are used to signal warning (say by printing an warning) while the upper level code on the call stack can continue its work."
},
{
"code": null,
"e": 2605,
"s": 2549,
"text": "The condition handling system in LISP has three parts −"
},
{
"code": null,
"e": 2628,
"s": 2605,
"text": "Signalling a condition"
},
{
"code": null,
"e": 2651,
"s": 2628,
"text": "Handling the condition"
},
{
"code": null,
"e": 2671,
"s": 2651,
"text": "Restart the process"
},
{
"code": null,
"e": 2792,
"s": 2671,
"text": "Let us take up an example of handling a condition arising out of divide by zero condition, to explain the concepts here."
},
{
"code": null,
"e": 2856,
"s": 2792,
"text": "You need to take the following steps for handling a condition −"
},
{
"code": null,
"e": 3196,
"s": 2856,
"text": "Define the Condition − \"A condition is an object whose class indicates the general nature of the condition and whose instance data carries information about the details of the particular circumstances that lead to the condition being signalled\".\nThe define-condition macro is used for defining a condition, which has the following syntax −"
},
{
"code": null,
"e": 3442,
"s": 3196,
"text": "Define the Condition − \"A condition is an object whose class indicates the general nature of the condition and whose instance data carries information about the details of the particular circumstances that lead to the condition being signalled\"."
},
{
"code": null,
"e": 3536,
"s": 3442,
"text": "The define-condition macro is used for defining a condition, which has the following syntax −"
},
{
"code": null,
"e": 3620,
"s": 3536,
"text": "(define-condition condition-name (error)\n ((text :initarg :text :reader text))\n)\n"
},
{
"code": null,
"e": 3763,
"s": 3620,
"text": "New condition objects are created with MAKE-CONDITION macro, which initializes the slots of the new condition based on the :initargs argument."
},
{
"code": null,
"e": 3906,
"s": 3763,
"text": "New condition objects are created with MAKE-CONDITION macro, which initializes the slots of the new condition based on the :initargs argument."
},
{
"code": null,
"e": 3965,
"s": 3906,
"text": "In our example, the following code defines the condition −"
},
{
"code": null,
"e": 4062,
"s": 3965,
"text": "(define-condition on-division-by-zero (error)\n ((message :initarg :message :reader message))\n)"
},
{
"code": null,
"e": 4802,
"s": 4062,
"text": "Writing the Handlers − a condition handler is a code that are used for handling the condition signalled thereon. It is generally written in one of the higher level functions that call the erroring function. When a condition is signalled, the signalling mechanism searches for an appropriate handler based on the condition's class.\nEach handler consists of −\n\nType specifier, that indicates the type of condition it can handle\nA function that takes a single argument, the condition\n\nWhen a condition is signalled, the signalling mechanism finds the most recently established handler that is compatible with the condition type and calls its function.\nThe macro handler-case establishes a condition handler. The basic form of a handler-case −"
},
{
"code": null,
"e": 5133,
"s": 4802,
"text": "Writing the Handlers − a condition handler is a code that are used for handling the condition signalled thereon. It is generally written in one of the higher level functions that call the erroring function. When a condition is signalled, the signalling mechanism searches for an appropriate handler based on the condition's class."
},
{
"code": null,
"e": 5160,
"s": 5133,
"text": "Each handler consists of −"
},
{
"code": null,
"e": 5227,
"s": 5160,
"text": "Type specifier, that indicates the type of condition it can handle"
},
{
"code": null,
"e": 5282,
"s": 5227,
"text": "A function that takes a single argument, the condition"
},
{
"code": null,
"e": 5449,
"s": 5282,
"text": "When a condition is signalled, the signalling mechanism finds the most recently established handler that is compatible with the condition type and calls its function."
},
{
"code": null,
"e": 5540,
"s": 5449,
"text": "The macro handler-case establishes a condition handler. The basic form of a handler-case −"
},
{
"code": null,
"e": 5581,
"s": 5540,
"text": "(handler-case expression error-clause*)\n"
},
{
"code": null,
"e": 5623,
"s": 5581,
"text": "Where, each error clause is of the form −"
},
{
"code": null,
"e": 5653,
"s": 5623,
"text": "condition-type ([var]) code)\n"
},
{
"code": null,
"e": 6269,
"s": 5653,
"text": "Restarting Phase\nThis is the code that actually recovers your program from errors, and condition handlers can then handle a condition by invoking an appropriate restart. The restart code is generally place in middle-level or low-level functions and the condition handlers are placed into the upper levels of the application.\nThe handler-bind macro allows you to provide a restart function, and allows you to continue at the lower level functions without unwinding the function call stack. In other words, the flow of control will still be in the lower level function.\nThe basic form of handler-bind is as follows −\n"
},
{
"code": null,
"e": 6286,
"s": 6269,
"text": "Restarting Phase"
},
{
"code": null,
"e": 6594,
"s": 6286,
"text": "This is the code that actually recovers your program from errors, and condition handlers can then handle a condition by invoking an appropriate restart. The restart code is generally place in middle-level or low-level functions and the condition handlers are placed into the upper levels of the application."
},
{
"code": null,
"e": 6837,
"s": 6594,
"text": "The handler-bind macro allows you to provide a restart function, and allows you to continue at the lower level functions without unwinding the function call stack. In other words, the flow of control will still be in the lower level function."
},
{
"code": null,
"e": 6884,
"s": 6837,
"text": "The basic form of handler-bind is as follows −"
},
{
"code": null,
"e": 6917,
"s": 6884,
"text": "(handler-bind (binding*) form*)\n"
},
{
"code": null,
"e": 6965,
"s": 6917,
"text": "Where each binding is a list of the following −"
},
{
"code": null,
"e": 6982,
"s": 6965,
"text": "a condition type"
},
{
"code": null,
"e": 7017,
"s": 6982,
"text": "a handler function of one argument"
},
{
"code": null,
"e": 7138,
"s": 7017,
"text": "The invoke-restart macro finds and invokes the most recently bound restart function with the specified name as argument."
},
{
"code": null,
"e": 7170,
"s": 7138,
"text": "You can have multiple restarts."
},
{
"code": null,
"e": 7501,
"s": 7170,
"text": "In this example, we demonstrate the above concepts by writing a function named division-function, which will create an error condition if the divisor argument is zero. We have three anonymous functions that provide three ways to come out of it - by returning a value 1, by sending a divisor 2 and recalculating, or by returning 1."
},
{
"code": null,
"e": 7582,
"s": 7501,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 9150,
"s": 7582,
"text": "(define-condition on-division-by-zero (error)\n ((message :initarg :message :reader message))\n)\n \n(defun handle-infinity ()\n (restart-case\n (let ((result 0))\n (setf result (division-function 10 0))\n (format t \"Value: ~a~%\" result)\n )\n (just-continue () nil)\n )\n)\n \n(defun division-function (value1 value2)\n (restart-case\n (if (/= value2 0)\n (/ value1 value2)\n (error 'on-division-by-zero :message \"denominator is zero\")\n )\n\n (return-zero () 0)\n (return-value (r) r)\n (recalc-using (d) (division-function value1 d))\n )\n)\n\n(defun high-level-code ()\n (handler-bind\n (\n (on-division-by-zero\n #'(lambda (c)\n (format t \"error signaled: ~a~%\" (message c))\n (invoke-restart 'return-zero)\n )\n )\n (handle-infinity)\n )\n )\n)\n\n(handler-bind\n (\n (on-division-by-zero\n #'(lambda (c)\n (format t \"error signaled: ~a~%\" (message c))\n (invoke-restart 'return-value 1)\n )\n )\n )\n (handle-infinity)\n)\n\n(handler-bind\n (\n (on-division-by-zero\n #'(lambda (c)\n (format t \"error signaled: ~a~%\" (message c))\n (invoke-restart 'recalc-using 2)\n )\n )\n )\n (handle-infinity)\n)\n\n(handler-bind\n (\n (on-division-by-zero\n #'(lambda (c)\n (format t \"error signaled: ~a~%\" (message c))\n (invoke-restart 'just-continue)\n )\n )\n )\n (handle-infinity)\n)\n\n(format t \"Done.\"))"
},
{
"code": null,
"e": 9211,
"s": 9150,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 9344,
"s": 9211,
"text": "error signaled: denominator is zero\nValue: 1\nerror signaled: denominator is zero\nValue: 5\nerror signaled: denominator is zero\nDone.\n"
},
{
"code": null,
"e": 9563,
"s": 9344,
"text": "Apart from the 'Condition System', as discussed above, Common LISP also provides various functions that may be called for signalling an error. Handling of an error, when signalled, is however, implementation-dependent."
},
{
"code": null,
"e": 9673,
"s": 9563,
"text": "The following table provides commonly used functions signalling warnings, breaks, non-fatal and fatal errors."
},
{
"code": null,
"e": 9804,
"s": 9673,
"text": "The user program specifies an error message (a string). The functions process this message and may/may not display it to the user."
},
{
"code": null,
"e": 10055,
"s": 9804,
"text": "The error messages should be constructed by applying the format function, should not contain a newline character at either the beginning or end, and need not indicate error, as the LISP system will take care of these according to its preferred style."
},
{
"code": null,
"e": 10086,
"s": 10055,
"text": "error format-string &rest args"
},
{
"code": null,
"e": 10210,
"s": 10086,
"text": "It signals a fatal error. It is impossible to continue from this kind of error; thus error will never return to its caller."
},
{
"code": null,
"e": 10271,
"s": 10210,
"text": "cerror continue-format-string error-format-string &rest args"
},
{
"code": null,
"e": 10408,
"s": 10271,
"text": "It signals an error and enters the debugger. However, it allows the program to be continued from the debugger after resolving the error."
},
{
"code": null,
"e": 10438,
"s": 10408,
"text": "warn format-string &rest args"
},
{
"code": null,
"e": 10507,
"s": 10438,
"text": "it prints an error message but normally doesn't go into the debugger"
},
{
"code": null,
"e": 10548,
"s": 10507,
"text": "break &optional format-string &rest args"
},
{
"code": null,
"e": 10696,
"s": 10548,
"text": "It prints the message and goes directly into the debugger, without allowing any possibility of interception by programmed error-handling facilities"
},
{
"code": null,
"e": 10838,
"s": 10696,
"text": "In this example, the factorial function calculates factorial of a number; however, if the argument is negative, it raises an error condition."
},
{
"code": null,
"e": 10919,
"s": 10838,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 11151,
"s": 10919,
"text": "(defun factorial (x)\n (cond ((or (not (typep x 'integer)) (minusp x))\n (error \"~S is a negative number.\" x))\n ((zerop x) 1)\n (t (* x (factorial (- x 1))))\n )\n)\n\n(write(factorial 5))\n(terpri)\n(write(factorial -1))"
},
{
"code": null,
"e": 11212,
"s": 11151,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 11248,
"s": 11212,
"text": "120\n*** - -1 is a negative number.\n"
},
{
"code": null,
"e": 11281,
"s": 11248,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 11296,
"s": 11281,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 11303,
"s": 11296,
"text": " Print"
},
{
"code": null,
"e": 11314,
"s": 11303,
"text": " Add Notes"
}
] |
How to Use Group By and Partition By in SQL | by Chi Nguyen | Towards Data Science | When I first learned SQL, I had a problem of differentiating between PARTITION BY and GROUP BY, as they both have a function for grouping. I believe many people who begin to work with SQL may encounter the same problem. Therefore, in this article I want to share with you some examples of using PARTITION BY, and the difference between it and GROUP BY in a select statement.
Firstly, I create a simple dataset with 4 columns. The df table below describes the amount of money and type of fruit that each employee in different functions will bring in their company trip.
The following is the syntax of Partition By:
SELECT expression 1, expression 2, ...aggregate function () OVER (PARTITION BY expression 1 order_clause frame_clause)FROM table
When we want to do an aggregation on a specific column, we can apply PARTITION BY clause with the OVER clause. Let’s look at the example below to see how the dataset has been transformed.
In the example, I want to calculate the total and average amount of money that each function brings for the trip. What you can see in the screenshot is the result of my PARTITION BY query.
Now, if I use GROUP BY instead of PARTITION BY in the above case, what would the result look like?
First, the syntax of GROUP BY can be written as:
SELECT expression 1, expression 2aggregate function ()FROM tablesWHERE conditionsGROUP BY expression 1, expression 2
When I apply this to the query to find the total and average amount of money in each function, the aggregated output is similar to a PARTITION BY clause. However, as you notice, there is a difference in the figure 3 and figure 4 result.
GROUP BY gives per function in the company a result (Figure 4). Meanwhile, as we have 7 records in the df table, PARTITION BY retrieves all 7 rows with total_amount and average_amount in each row (Figure 3). Therefore, in conclusion, the PARTITION BY retrieves all the records in the table, while the GROUP BY only returns a limited number.
One more thing is that GROUP BY does not allow to add columns which are not parts of GROUP BY clause in select statement. However, with PARTITION BY clause, we can add required columns.
We can combine PARTITION BY and ROW NUMBER to have the row number sorted by a specific value. For example, if I want to see which person in each function brings the most amount of money, I can easily find out by applying the ROW_NUMBER function to each team and getting each person’s amount of money ordered by descending values.
PARTITION BY + ROWS UNBOUNDED PRECEDING
For easier imagination, I will begin with an example to explain the idea of this section.
I created a new table named df8.
By applying ROW_NUMBER, I got the row number value sorted by amount of money for each employee in each function. Basically until this step, as you can see in figure 7, everything is similar to the example above.
However, as I want to calculate one more column, which is the average money amount of the current row and the higher value amount before the current row in partition. For example in the figure 8, we can see that:
In the Tech team, Sam alone has an average cumulative amount of 400000.
However, in row number 2 of the Tech team, the average cumulative amount is 340050, which equals the average of (Hoang’s amount + Sam’s amount).
In row number 3, the money amount of Dung is lower than Hoang and Sam, so his average cumulative amount is average of (Hoang’s, Sam’s and Dung’s amount)
=> This is a general idea of how ROWS UNBOUNDED PRECEDING and PARTITION BY clause are used together.
PARTITION BY + ROWS BETWEEN CURRENT ROW AND 1
The usage of this combination is to calculate the aggregated values (average, sum, etc) of the current row and the following row in partition. Let’s continue to work with df9 data to see how this is done.
From figure 9, we can figure out that:
In Tech function row number 1, the average cumulative amount of Sam is 340050, which equals the average amount of her and her following person (Hoang) in row number 2.
Then, the average cumulative amount of Hoang is the average of Hoang’s amount and Dung’s amount in row number 3.
In this article, I provided my understanding of PARTITION BY and GROUP BY along with some different cases of using PARTITION BY. I hope the above information will be helpful for you. | [
{
"code": null,
"e": 546,
"s": 171,
"text": "When I first learned SQL, I had a problem of differentiating between PARTITION BY and GROUP BY, as they both have a function for grouping. I believe many people who begin to work with SQL may encounter the same problem. Therefore, in this article I want to share with you some examples of using PARTITION BY, and the difference between it and GROUP BY in a select statement."
},
{
"code": null,
"e": 740,
"s": 546,
"text": "Firstly, I create a simple dataset with 4 columns. The df table below describes the amount of money and type of fruit that each employee in different functions will bring in their company trip."
},
{
"code": null,
"e": 785,
"s": 740,
"text": "The following is the syntax of Partition By:"
},
{
"code": null,
"e": 914,
"s": 785,
"text": "SELECT expression 1, expression 2, ...aggregate function () OVER (PARTITION BY expression 1 order_clause frame_clause)FROM table"
},
{
"code": null,
"e": 1102,
"s": 914,
"text": "When we want to do an aggregation on a specific column, we can apply PARTITION BY clause with the OVER clause. Let’s look at the example below to see how the dataset has been transformed."
},
{
"code": null,
"e": 1291,
"s": 1102,
"text": "In the example, I want to calculate the total and average amount of money that each function brings for the trip. What you can see in the screenshot is the result of my PARTITION BY query."
},
{
"code": null,
"e": 1390,
"s": 1291,
"text": "Now, if I use GROUP BY instead of PARTITION BY in the above case, what would the result look like?"
},
{
"code": null,
"e": 1439,
"s": 1390,
"text": "First, the syntax of GROUP BY can be written as:"
},
{
"code": null,
"e": 1556,
"s": 1439,
"text": "SELECT expression 1, expression 2aggregate function ()FROM tablesWHERE conditionsGROUP BY expression 1, expression 2"
},
{
"code": null,
"e": 1793,
"s": 1556,
"text": "When I apply this to the query to find the total and average amount of money in each function, the aggregated output is similar to a PARTITION BY clause. However, as you notice, there is a difference in the figure 3 and figure 4 result."
},
{
"code": null,
"e": 2134,
"s": 1793,
"text": "GROUP BY gives per function in the company a result (Figure 4). Meanwhile, as we have 7 records in the df table, PARTITION BY retrieves all 7 rows with total_amount and average_amount in each row (Figure 3). Therefore, in conclusion, the PARTITION BY retrieves all the records in the table, while the GROUP BY only returns a limited number."
},
{
"code": null,
"e": 2320,
"s": 2134,
"text": "One more thing is that GROUP BY does not allow to add columns which are not parts of GROUP BY clause in select statement. However, with PARTITION BY clause, we can add required columns."
},
{
"code": null,
"e": 2650,
"s": 2320,
"text": "We can combine PARTITION BY and ROW NUMBER to have the row number sorted by a specific value. For example, if I want to see which person in each function brings the most amount of money, I can easily find out by applying the ROW_NUMBER function to each team and getting each person’s amount of money ordered by descending values."
},
{
"code": null,
"e": 2690,
"s": 2650,
"text": "PARTITION BY + ROWS UNBOUNDED PRECEDING"
},
{
"code": null,
"e": 2780,
"s": 2690,
"text": "For easier imagination, I will begin with an example to explain the idea of this section."
},
{
"code": null,
"e": 2813,
"s": 2780,
"text": "I created a new table named df8."
},
{
"code": null,
"e": 3025,
"s": 2813,
"text": "By applying ROW_NUMBER, I got the row number value sorted by amount of money for each employee in each function. Basically until this step, as you can see in figure 7, everything is similar to the example above."
},
{
"code": null,
"e": 3238,
"s": 3025,
"text": "However, as I want to calculate one more column, which is the average money amount of the current row and the higher value amount before the current row in partition. For example in the figure 8, we can see that:"
},
{
"code": null,
"e": 3310,
"s": 3238,
"text": "In the Tech team, Sam alone has an average cumulative amount of 400000."
},
{
"code": null,
"e": 3455,
"s": 3310,
"text": "However, in row number 2 of the Tech team, the average cumulative amount is 340050, which equals the average of (Hoang’s amount + Sam’s amount)."
},
{
"code": null,
"e": 3608,
"s": 3455,
"text": "In row number 3, the money amount of Dung is lower than Hoang and Sam, so his average cumulative amount is average of (Hoang’s, Sam’s and Dung’s amount)"
},
{
"code": null,
"e": 3709,
"s": 3608,
"text": "=> This is a general idea of how ROWS UNBOUNDED PRECEDING and PARTITION BY clause are used together."
},
{
"code": null,
"e": 3755,
"s": 3709,
"text": "PARTITION BY + ROWS BETWEEN CURRENT ROW AND 1"
},
{
"code": null,
"e": 3960,
"s": 3755,
"text": "The usage of this combination is to calculate the aggregated values (average, sum, etc) of the current row and the following row in partition. Let’s continue to work with df9 data to see how this is done."
},
{
"code": null,
"e": 3999,
"s": 3960,
"text": "From figure 9, we can figure out that:"
},
{
"code": null,
"e": 4167,
"s": 3999,
"text": "In Tech function row number 1, the average cumulative amount of Sam is 340050, which equals the average amount of her and her following person (Hoang) in row number 2."
},
{
"code": null,
"e": 4280,
"s": 4167,
"text": "Then, the average cumulative amount of Hoang is the average of Hoang’s amount and Dung’s amount in row number 3."
}
] |
Delete Node in a BST in C++ | Suppose we have a binary search tree. We will take one key k, and we have to delete the given key k from the BST, and return the updated BST. So if the tree is like −
And the key k = 3, then the output tree will be −
To solve this, we will follow these steps −
Define a method called deleteRoot() to delete the root node, this will work as follows
Define a method called deleteRoot() to delete the root node, this will work as follows
if root is null, then return null
if root is null, then return null
if root has no right subtree, then return left of root
if root has no right subtree, then return left of root
x := inorder successor of root
x := inorder successor of root
set left of x as left := left of root
set left of x as left := left of root
return right of root
return right of root
The delete method will be like
The delete method will be like
if root is null or value of root is key, then return deleteRoot(root)
if root is null or value of root is key, then return deleteRoot(root)
curr := root
curr := root
Create one infinite loop, and execute the followingx := value of curr nodeif key < x, thenif left of curr = null or value of left of curr = key, thenleft of curr := deleteRoot(left of curr) and come out from the loop.curr := left of currotherwiseif right of curr = null or value of right of curr = key, thenright of curr := deleteRoot(right of curr) and come out from loop.curr := right of curr
Create one infinite loop, and execute the following
x := value of curr node
x := value of curr node
if key < x, thenif left of curr = null or value of left of curr = key, thenleft of curr := deleteRoot(left of curr) and come out from the loop.curr := left of curr
if key < x, then
if left of curr = null or value of left of curr = key, thenleft of curr := deleteRoot(left of curr) and come out from the loop.
if left of curr = null or value of left of curr = key, then
left of curr := deleteRoot(left of curr) and come out from the loop.
left of curr := deleteRoot(left of curr) and come out from the loop.
curr := left of curr
curr := left of curr
otherwiseif right of curr = null or value of right of curr = key, thenright of curr := deleteRoot(right of curr) and come out from loop.curr := right of curr
otherwise
if right of curr = null or value of right of curr = key, thenright of curr := deleteRoot(right of curr) and come out from loop.
if right of curr = null or value of right of curr = key, then
right of curr := deleteRoot(right of curr) and come out from loop.
right of curr := deleteRoot(right of curr) and come out from loop.
curr := right of curr
curr := right of curr
return root
return root
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
} else {
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
} else {
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
}
else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr == NULL || curr->val == 0){
cout << "null" << ", ";
} else {
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == NULL || root->val == key) return deleteRoot(root);
TreeNode* curr = root;
while(1) {
int x = curr->val;
if(key < x){
if(curr->left == NULL || curr->left->val == key){
curr->left = deleteRoot(curr->left);
break;
}
curr = curr->left;
} else {
if(curr->right == NULL || curr->right->val == key){
curr->right = deleteRoot(curr->right);
break;
}
curr = curr->right;
}
}
return root;
}
TreeNode* deleteRoot(TreeNode* root){
if(!root || root->val == 0)return NULL;
if(root->right == NULL) return root->left;
TreeNode* x = root->right;
while(x->left)x = x->left;
x->left = root->left;
return root->right;
}
};
main(){
vector<int> v = {5,3,6,2,4,NULL,7};
TreeNode *root = make_tree(v);
Solution ob;
tree_level_trav(ob.deleteNode(root, 3));
}
[5,3,6,2,4,null,7]
3
[5, 4, 6, 2, null, 7, ] | [
{
"code": null,
"e": 1229,
"s": 1062,
"text": "Suppose we have a binary search tree. We will take one key k, and we have to delete the given key k from the BST, and return the updated BST. So if the tree is like −"
},
{
"code": null,
"e": 1279,
"s": 1229,
"text": "And the key k = 3, then the output tree will be −"
},
{
"code": null,
"e": 1323,
"s": 1279,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1410,
"s": 1323,
"text": "Define a method called deleteRoot() to delete the root node, this will work as follows"
},
{
"code": null,
"e": 1497,
"s": 1410,
"text": "Define a method called deleteRoot() to delete the root node, this will work as follows"
},
{
"code": null,
"e": 1531,
"s": 1497,
"text": "if root is null, then return null"
},
{
"code": null,
"e": 1565,
"s": 1531,
"text": "if root is null, then return null"
},
{
"code": null,
"e": 1620,
"s": 1565,
"text": "if root has no right subtree, then return left of root"
},
{
"code": null,
"e": 1675,
"s": 1620,
"text": "if root has no right subtree, then return left of root"
},
{
"code": null,
"e": 1706,
"s": 1675,
"text": "x := inorder successor of root"
},
{
"code": null,
"e": 1737,
"s": 1706,
"text": "x := inorder successor of root"
},
{
"code": null,
"e": 1775,
"s": 1737,
"text": "set left of x as left := left of root"
},
{
"code": null,
"e": 1813,
"s": 1775,
"text": "set left of x as left := left of root"
},
{
"code": null,
"e": 1834,
"s": 1813,
"text": "return right of root"
},
{
"code": null,
"e": 1855,
"s": 1834,
"text": "return right of root"
},
{
"code": null,
"e": 1886,
"s": 1855,
"text": "The delete method will be like"
},
{
"code": null,
"e": 1917,
"s": 1886,
"text": "The delete method will be like"
},
{
"code": null,
"e": 1987,
"s": 1917,
"text": "if root is null or value of root is key, then return deleteRoot(root)"
},
{
"code": null,
"e": 2057,
"s": 1987,
"text": "if root is null or value of root is key, then return deleteRoot(root)"
},
{
"code": null,
"e": 2070,
"s": 2057,
"text": "curr := root"
},
{
"code": null,
"e": 2083,
"s": 2070,
"text": "curr := root"
},
{
"code": null,
"e": 2478,
"s": 2083,
"text": "Create one infinite loop, and execute the followingx := value of curr nodeif key < x, thenif left of curr = null or value of left of curr = key, thenleft of curr := deleteRoot(left of curr) and come out from the loop.curr := left of currotherwiseif right of curr = null or value of right of curr = key, thenright of curr := deleteRoot(right of curr) and come out from loop.curr := right of curr"
},
{
"code": null,
"e": 2530,
"s": 2478,
"text": "Create one infinite loop, and execute the following"
},
{
"code": null,
"e": 2554,
"s": 2530,
"text": "x := value of curr node"
},
{
"code": null,
"e": 2578,
"s": 2554,
"text": "x := value of curr node"
},
{
"code": null,
"e": 2742,
"s": 2578,
"text": "if key < x, thenif left of curr = null or value of left of curr = key, thenleft of curr := deleteRoot(left of curr) and come out from the loop.curr := left of curr"
},
{
"code": null,
"e": 2759,
"s": 2742,
"text": "if key < x, then"
},
{
"code": null,
"e": 2887,
"s": 2759,
"text": "if left of curr = null or value of left of curr = key, thenleft of curr := deleteRoot(left of curr) and come out from the loop."
},
{
"code": null,
"e": 2947,
"s": 2887,
"text": "if left of curr = null or value of left of curr = key, then"
},
{
"code": null,
"e": 3016,
"s": 2947,
"text": "left of curr := deleteRoot(left of curr) and come out from the loop."
},
{
"code": null,
"e": 3085,
"s": 3016,
"text": "left of curr := deleteRoot(left of curr) and come out from the loop."
},
{
"code": null,
"e": 3106,
"s": 3085,
"text": "curr := left of curr"
},
{
"code": null,
"e": 3127,
"s": 3106,
"text": "curr := left of curr"
},
{
"code": null,
"e": 3285,
"s": 3127,
"text": "otherwiseif right of curr = null or value of right of curr = key, thenright of curr := deleteRoot(right of curr) and come out from loop.curr := right of curr"
},
{
"code": null,
"e": 3295,
"s": 3285,
"text": "otherwise"
},
{
"code": null,
"e": 3423,
"s": 3295,
"text": "if right of curr = null or value of right of curr = key, thenright of curr := deleteRoot(right of curr) and come out from loop."
},
{
"code": null,
"e": 3485,
"s": 3423,
"text": "if right of curr = null or value of right of curr = key, then"
},
{
"code": null,
"e": 3552,
"s": 3485,
"text": "right of curr := deleteRoot(right of curr) and come out from loop."
},
{
"code": null,
"e": 3619,
"s": 3552,
"text": "right of curr := deleteRoot(right of curr) and come out from loop."
},
{
"code": null,
"e": 3641,
"s": 3619,
"text": "curr := right of curr"
},
{
"code": null,
"e": 3663,
"s": 3641,
"text": "curr := right of curr"
},
{
"code": null,
"e": 3675,
"s": 3663,
"text": "return root"
},
{
"code": null,
"e": 3687,
"s": 3675,
"text": "return root"
},
{
"code": null,
"e": 3757,
"s": 3687,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3768,
"s": 3757,
"text": " Live Demo"
},
{
"code": null,
"e": 6422,
"s": 3768,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TreeNode{\n public:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = NULL;\n right = NULL;\n }\n};\nvoid insert(TreeNode **root, int val){\n queue<TreeNode*> q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n } else {\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n } else {\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector<int> v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n insert(&root, v[i]);\n }\n return root;\n}\nvoid tree_level_trav(TreeNode*root){\n if (root == NULL) return;\n cout << \"[\";\n queue<TreeNode *> q;\n TreeNode *curr;\n q.push(root);\n q.push(NULL);\n while (q.size() > 1) {\n curr = q.front();\n q.pop();\n if (curr == NULL){\n q.push(NULL);\n }\n else {\n if(curr->left)\n q.push(curr->left);\n if(curr->right)\n q.push(curr->right);\n if(curr == NULL || curr->val == 0){\n cout << \"null\" << \", \";\n } else {\n cout << curr->val << \", \";\n }\n }\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\n public:\n TreeNode* deleteNode(TreeNode* root, int key) {\n if(root == NULL || root->val == key) return deleteRoot(root);\n TreeNode* curr = root;\n while(1) {\n int x = curr->val;\n if(key < x){\n if(curr->left == NULL || curr->left->val == key){\n curr->left = deleteRoot(curr->left);\n break;\n }\n curr = curr->left;\n } else {\n if(curr->right == NULL || curr->right->val == key){\n curr->right = deleteRoot(curr->right);\n break;\n }\n curr = curr->right;\n }\n }\n return root;\n }\n TreeNode* deleteRoot(TreeNode* root){\n if(!root || root->val == 0)return NULL;\n if(root->right == NULL) return root->left;\n TreeNode* x = root->right;\n while(x->left)x = x->left;\n x->left = root->left;\n return root->right;\n }\n };\nmain(){\n vector<int> v = {5,3,6,2,4,NULL,7};\n TreeNode *root = make_tree(v);\n Solution ob;\n tree_level_trav(ob.deleteNode(root, 3));\n}"
},
{
"code": null,
"e": 6443,
"s": 6422,
"text": "[5,3,6,2,4,null,7]\n3"
},
{
"code": null,
"e": 6467,
"s": 6443,
"text": "[5, 4, 6, 2, null, 7, ]"
}
] |
Memoization using decorators in Python | 25 May, 2022
Recursion is a programming technique where a function calls itself repeatedly till a termination condition is met. Some of the examples where recursion is used are calculation of fibonacci series, factorial, etc. But the issue with them is that in the recursion tree, there can be chances that the sub-problem that is already solved is being solved again, which adds to overhead.Memoization is a technique of recording the intermediate results so that it can be used to avoid repeated calculations and speed up the programs. It can be used to optimize the programs that use recursion. In Python, memoization can be done with the help of function decorators. Let us take the example of calculating the factorial of a number. The simple program below uses recursion to solve the problem:
Python3
# Simple recursive program to find factorialdef facto(num): if num == 1: return 1 else: return num * facto(num-1) print(facto(5))print(facto(5)) # again performing same calculation
120
120
The above program can be optimized by memoization using decorators.
Python3
# Factorial program with memoization using# decorators. # A decorator function for function 'f' passed# as parametermemory = {}def memoize_factorial(f): # This inner function has access to memory # and 'f' def inner(num): if num not in memory: memory[num] = f(num) print('result saved in memory') else: print('returning result from saved memory') return memory[num] return inner @memoize_factorialdef facto(num): if num == 1: return 1 else: return num * facto(num-1) print(facto(5))print(facto(5)) # directly coming from saved memory
result saved in memory
result saved in memory
result saved in memory
result saved in memory
result saved in memory
120
returning result from saved memory
120
Explanation: 1. A function called memoize_factorial has been defined. Its main purpose is to store the intermediate results in the variable called memory. 2. The second function called facto is the function to calculate the factorial. It has been annotated by a decorator(the function memoize_factorial). The facto has access to the memory variable as a result of the concept of closures. The annotation is equivalent to writing,
facto = memoize_factorial(facto)
3. When facto(5) is called, the recursive operations take place in addition to the storage of intermediate results. Every time a calculation needs to be done, it is checked if the result is available in memory. If yes, then it is used, else, the value is calculated and is stored in memory. 4. We can verify the fact that memoization actually works, please see the output of this program.
manishkumaru6ux
abgupta
Memoization
Python Decorators
Dynamic Programming
Python
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 841,
"s": 54,
"text": "Recursion is a programming technique where a function calls itself repeatedly till a termination condition is met. Some of the examples where recursion is used are calculation of fibonacci series, factorial, etc. But the issue with them is that in the recursion tree, there can be chances that the sub-problem that is already solved is being solved again, which adds to overhead.Memoization is a technique of recording the intermediate results so that it can be used to avoid repeated calculations and speed up the programs. It can be used to optimize the programs that use recursion. In Python, memoization can be done with the help of function decorators. Let us take the example of calculating the factorial of a number. The simple program below uses recursion to solve the problem: "
},
{
"code": null,
"e": 849,
"s": 841,
"text": "Python3"
},
{
"code": "# Simple recursive program to find factorialdef facto(num): if num == 1: return 1 else: return num * facto(num-1) print(facto(5))print(facto(5)) # again performing same calculation",
"e": 1059,
"s": 849,
"text": null
},
{
"code": null,
"e": 1068,
"s": 1059,
"text": "120\n120\n"
},
{
"code": null,
"e": 1137,
"s": 1068,
"text": "The above program can be optimized by memoization using decorators. "
},
{
"code": null,
"e": 1145,
"s": 1137,
"text": "Python3"
},
{
"code": "# Factorial program with memoization using# decorators. # A decorator function for function 'f' passed# as parametermemory = {}def memoize_factorial(f): # This inner function has access to memory # and 'f' def inner(num): if num not in memory: memory[num] = f(num) print('result saved in memory') else: print('returning result from saved memory') return memory[num] return inner @memoize_factorialdef facto(num): if num == 1: return 1 else: return num * facto(num-1) print(facto(5))print(facto(5)) # directly coming from saved memory",
"e": 1775,
"s": 1145,
"text": null
},
{
"code": null,
"e": 1934,
"s": 1775,
"text": "result saved in memory\nresult saved in memory\nresult saved in memory\nresult saved in memory\nresult saved in memory\n120\nreturning result from saved memory\n120\n"
},
{
"code": null,
"e": 2365,
"s": 1934,
"text": "Explanation: 1. A function called memoize_factorial has been defined. Its main purpose is to store the intermediate results in the variable called memory. 2. The second function called facto is the function to calculate the factorial. It has been annotated by a decorator(the function memoize_factorial). The facto has access to the memory variable as a result of the concept of closures. The annotation is equivalent to writing, "
},
{
"code": null,
"e": 2398,
"s": 2365,
"text": "facto = memoize_factorial(facto)"
},
{
"code": null,
"e": 2788,
"s": 2398,
"text": "3. When facto(5) is called, the recursive operations take place in addition to the storage of intermediate results. Every time a calculation needs to be done, it is checked if the result is available in memory. If yes, then it is used, else, the value is calculated and is stored in memory. 4. We can verify the fact that memoization actually works, please see the output of this program. "
},
{
"code": null,
"e": 2804,
"s": 2788,
"text": "manishkumaru6ux"
},
{
"code": null,
"e": 2812,
"s": 2804,
"text": "abgupta"
},
{
"code": null,
"e": 2824,
"s": 2812,
"text": "Memoization"
},
{
"code": null,
"e": 2842,
"s": 2824,
"text": "Python Decorators"
},
{
"code": null,
"e": 2862,
"s": 2842,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 2869,
"s": 2862,
"text": "Python"
},
{
"code": null,
"e": 2889,
"s": 2869,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 2987,
"s": 2889,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3019,
"s": 2987,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 3049,
"s": 3019,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 3078,
"s": 3049,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 3112,
"s": 3078,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 3139,
"s": 3112,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 3167,
"s": 3139,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3217,
"s": 3167,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3239,
"s": 3217,
"text": "Python map() function"
},
{
"code": null,
"e": 3283,
"s": 3239,
"text": "How to get column names in Pandas dataframe"
}
] |
How to declare a pointer to a function? | 28 May, 2017
Well, we assume that you know what does it mean by pointer in C. So how do we create a pointer to an integer in C?Huh..it is pretty simple..
int * ptrInteger; /*We have put a * operator between int
and ptrInteger to create a pointer.*/
Here ptrInteger is a pointer to integer. If you understand this, then logically we should not have any problem in declaring a pointer to a function
So let us first see ..how do we declare a function? For example,
int foo(int);
Here foo is a function that returns int and takes one argument of int type. So as a logical guy will think, by putting a * operator between int and foo(int) should create a pointer to a function i.e.
int * foo(int);
But Oops..C operator precedence also plays role here ..so in this case, operator () will take priority over operator *. And the above declaration will mean – a function foo with one argument of int type and return value of int * i.e. integer pointer. So it did something that we didn’t want to do.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
So as a next logical step, we have to bind operator * with foo somehow. And for this, we would change the default precedence of C operators using () operator.
int (*foo)(int);
That’s it. Here * operator is with foo which is a function name. And it did the same that we wanted to do.
So that wasn’t as difficult as we thought earlier!
C-Pointers
pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs
C Language Introduction | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 193,
"s": 52,
"text": "Well, we assume that you know what does it mean by pointer in C. So how do we create a pointer to an integer in C?Huh..it is pretty simple.."
},
{
"code": null,
"e": 310,
"s": 193,
"text": "int * ptrInteger; /*We have put a * operator between int \n and ptrInteger to create a pointer.*/\n"
},
{
"code": null,
"e": 459,
"s": 310,
"text": "Here ptrInteger is a pointer to integer. If you understand this, then logically we should not have any problem in declaring a pointer to a function "
},
{
"code": null,
"e": 524,
"s": 459,
"text": "So let us first see ..how do we declare a function? For example,"
},
{
"code": null,
"e": 539,
"s": 524,
"text": "int foo(int);\n"
},
{
"code": null,
"e": 739,
"s": 539,
"text": "Here foo is a function that returns int and takes one argument of int type. So as a logical guy will think, by putting a * operator between int and foo(int) should create a pointer to a function i.e."
},
{
"code": null,
"e": 756,
"s": 739,
"text": "int * foo(int);\n"
},
{
"code": null,
"e": 1055,
"s": 756,
"text": "But Oops..C operator precedence also plays role here ..so in this case, operator () will take priority over operator *. And the above declaration will mean – a function foo with one argument of int type and return value of int * i.e. integer pointer. So it did something that we didn’t want to do. "
},
{
"code": null,
"e": 1064,
"s": 1055,
"text": "Chapters"
},
{
"code": null,
"e": 1091,
"s": 1064,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1141,
"s": 1091,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1164,
"s": 1141,
"text": "captions off, selected"
},
{
"code": null,
"e": 1172,
"s": 1164,
"text": "English"
},
{
"code": null,
"e": 1196,
"s": 1172,
"text": "This is a modal window."
},
{
"code": null,
"e": 1265,
"s": 1196,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1287,
"s": 1265,
"text": "End of dialog window."
},
{
"code": null,
"e": 1446,
"s": 1287,
"text": "So as a next logical step, we have to bind operator * with foo somehow. And for this, we would change the default precedence of C operators using () operator."
},
{
"code": null,
"e": 1464,
"s": 1446,
"text": "int (*foo)(int);\n"
},
{
"code": null,
"e": 1571,
"s": 1464,
"text": "That’s it. Here * operator is with foo which is a function name. And it did the same that we wanted to do."
},
{
"code": null,
"e": 1622,
"s": 1571,
"text": "So that wasn’t as difficult as we thought earlier!"
},
{
"code": null,
"e": 1633,
"s": 1622,
"text": "C-Pointers"
},
{
"code": null,
"e": 1641,
"s": 1633,
"text": "pointer"
},
{
"code": null,
"e": 1652,
"s": 1641,
"text": "C Language"
},
{
"code": null,
"e": 1750,
"s": 1652,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1767,
"s": 1750,
"text": "Substring in C++"
},
{
"code": null,
"e": 1802,
"s": 1767,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 1848,
"s": 1802,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 1893,
"s": 1848,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 1918,
"s": 1893,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1966,
"s": 1918,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1994,
"s": 1966,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 2021,
"s": 1994,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 2049,
"s": 2021,
"text": "Memory Layout of C Programs"
}
] |
Write custom aggregation function in Pandas | 20 Aug, 2020
Pandas in python in widely used for Data Analysis purpose and it consists of some fine data structures like Dataframe and Series. There are several functions in pandas that proves to be a great help for a programmer one of them is an aggregate function. This function returns a single value from multiple values taken as input which are grouped together on certain criteria. A few of the aggregate functions are average, count, maximum, among others.
Syntax: DataFrame.agg(func=None, axis=0, *args, **kwargs)
Parameters:
axis: {0 or ‘index’, 1 or ‘columns’} = 0 or ‘index’ means the function is applied to each column and 1 or ‘columns’ means the function is applied to each row.
func: function, str, list or dict = It describes the function that is to be used for aggregation. Accepted combinations are: function, string function name (str), list of functions (list/dict).
*args: It specifies the positional arguments to pass to the function.
**kwargs: It specifies the keyword arguments to pass to the function.
Return: This function can return scalar, Series or Dataframe. The return is scalar when Series.agg is called with a single function, it is Series when Dataframe.agg is called with a single function, it will be Dataframe when Dataframe.agg is called with several functions.
Let’s create a Dataframe:
Python3
# import pandas libraryimport pandas as pd # create a Dataframedf = pd.DataFrame([[10, 20, 30], [40, 50, 60], [70, 80, 90], [100,110,120]], columns=['Col_A', 'Col_B', 'Col_C'])# show the dataframedf
Output:
Now, let’s perform some operations:
1. Performing aggregation over the rows: This performs aggregate functions over the rows of the Dataframe. As you can see in the below examples, the example 1 has two keywords inside the aggregate function, sum and min. The sum adds up the first (10,40,70,100), second (20,50,80,110) and third (30,60,90,120) element of each row separately and print it, the min finds the minimum number among the elements of rows and print it. Similar process is with the second example.
Example 1:
Python3
df.agg(['sum', 'min'])
Output:
Example 2:
Python3
df.agg(['sum', 'min', 'max'])
Output:
2. Performing aggregation per column: This performs aggregate function on the columns, the columns are selected particularly as shown in the examples. In the first example, two columns are selected, ‘Col_A’ and ‘Col_B’ and operations are to be performed on them. For Col_A, the minimum value and the summed up value is calculated and for the Col_B, minimum and maximum value is calculated. Similar process is with example 2.
Example 1:
Python3
df.agg({'Col_A' : ['sum', 'min'], 'Col_B' : ['min', 'max']})
Output:
Example 2:
Python3
df.agg({'Col_A' : ['sum', 'min'], 'Col_B' : ['min', 'max'], 'Col_C' : ['sum', 'mean']})
Output:
Note: It will print NaN if a particular aggregation is not performed on a particular column.
3. Performing aggregation over the columns: This performs aggregate function over the columns. As shown in example 1, the mean of first (10,20,30), second (40,50,60), third (70,80,90) and fourth (100,110,120) elements of each column is calculated separately and printed.
Example:
Python3
df.agg("mean", axis = "columns")
Output:
4. Custom Aggregate function: Sometimes it becomes a need to create our own aggregate function.
Example: Consider a data frame consisting of student id (stu_id), subject code (sub_code) and marks (marks).
Python3
# import pandas libraryimport pandas as pd # Creating DataFramedf = pd.DataFrame( {'stud_id' : [101, 102, 103, 104, 101, 102, 103, 104], 'sub_code' : ['CSE6001', 'CSE6001', 'CSE6001', 'CSE6001', 'CSE6002', 'CSE6002', 'CSE6002', 'CSE6002'], 'marks' : [77, 86, 55, 90, 65, 90, 80, 67]}) # Printing DataFramedf
Output:
Now if you need to calculate the total marks (marks of two subjects) of each student (unique stu_id). This process can be done using custom aggregate function. Here my custom aggregate function is ‘total’.
Python3
# Importing reduce for # rolling computationsfrom functools import reduce # define a Custom aggregation # function for finding totaldef total(series): return reduce(lambda x, y: x + y, series) # Grouping the output according to # student id and printing the corresponding # total marks and to check whether the# output is correct or not, sum function # is also used to print the sum.df.groupby('stud_id').agg({'marks': ['sum', total]})
Output:
As you can see, both the columns have same values of total marks, so our aggregate function is correctly calculating the total marks in this case.
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 479,
"s": 28,
"text": "Pandas in python in widely used for Data Analysis purpose and it consists of some fine data structures like Dataframe and Series. There are several functions in pandas that proves to be a great help for a programmer one of them is an aggregate function. This function returns a single value from multiple values taken as input which are grouped together on certain criteria. A few of the aggregate functions are average, count, maximum, among others."
},
{
"code": null,
"e": 537,
"s": 479,
"text": "Syntax: DataFrame.agg(func=None, axis=0, *args, **kwargs)"
},
{
"code": null,
"e": 549,
"s": 537,
"text": "Parameters:"
},
{
"code": null,
"e": 708,
"s": 549,
"text": "axis: {0 or ‘index’, 1 or ‘columns’} = 0 or ‘index’ means the function is applied to each column and 1 or ‘columns’ means the function is applied to each row."
},
{
"code": null,
"e": 902,
"s": 708,
"text": "func: function, str, list or dict = It describes the function that is to be used for aggregation. Accepted combinations are: function, string function name (str), list of functions (list/dict)."
},
{
"code": null,
"e": 972,
"s": 902,
"text": "*args: It specifies the positional arguments to pass to the function."
},
{
"code": null,
"e": 1042,
"s": 972,
"text": "**kwargs: It specifies the keyword arguments to pass to the function."
},
{
"code": null,
"e": 1315,
"s": 1042,
"text": "Return: This function can return scalar, Series or Dataframe. The return is scalar when Series.agg is called with a single function, it is Series when Dataframe.agg is called with a single function, it will be Dataframe when Dataframe.agg is called with several functions."
},
{
"code": null,
"e": 1341,
"s": 1315,
"text": "Let’s create a Dataframe:"
},
{
"code": null,
"e": 1349,
"s": 1341,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create a Dataframedf = pd.DataFrame([[10, 20, 30], [40, 50, 60], [70, 80, 90], [100,110,120]], columns=['Col_A', 'Col_B', 'Col_C'])# show the dataframedf",
"e": 1641,
"s": 1349,
"text": null
},
{
"code": null,
"e": 1649,
"s": 1641,
"text": "Output:"
},
{
"code": null,
"e": 1685,
"s": 1649,
"text": "Now, let’s perform some operations:"
},
{
"code": null,
"e": 2157,
"s": 1685,
"text": "1. Performing aggregation over the rows: This performs aggregate functions over the rows of the Dataframe. As you can see in the below examples, the example 1 has two keywords inside the aggregate function, sum and min. The sum adds up the first (10,40,70,100), second (20,50,80,110) and third (30,60,90,120) element of each row separately and print it, the min finds the minimum number among the elements of rows and print it. Similar process is with the second example."
},
{
"code": null,
"e": 2168,
"s": 2157,
"text": "Example 1:"
},
{
"code": null,
"e": 2176,
"s": 2168,
"text": "Python3"
},
{
"code": "df.agg(['sum', 'min'])",
"e": 2199,
"s": 2176,
"text": null
},
{
"code": null,
"e": 2207,
"s": 2199,
"text": "Output:"
},
{
"code": null,
"e": 2218,
"s": 2207,
"text": "Example 2:"
},
{
"code": null,
"e": 2226,
"s": 2218,
"text": "Python3"
},
{
"code": "df.agg(['sum', 'min', 'max'])",
"e": 2256,
"s": 2226,
"text": null
},
{
"code": null,
"e": 2264,
"s": 2256,
"text": "Output:"
},
{
"code": null,
"e": 2689,
"s": 2264,
"text": "2. Performing aggregation per column: This performs aggregate function on the columns, the columns are selected particularly as shown in the examples. In the first example, two columns are selected, ‘Col_A’ and ‘Col_B’ and operations are to be performed on them. For Col_A, the minimum value and the summed up value is calculated and for the Col_B, minimum and maximum value is calculated. Similar process is with example 2."
},
{
"code": null,
"e": 2700,
"s": 2689,
"text": "Example 1:"
},
{
"code": null,
"e": 2708,
"s": 2700,
"text": "Python3"
},
{
"code": "df.agg({'Col_A' : ['sum', 'min'], 'Col_B' : ['min', 'max']})",
"e": 2777,
"s": 2708,
"text": null
},
{
"code": null,
"e": 2785,
"s": 2777,
"text": "Output:"
},
{
"code": null,
"e": 2796,
"s": 2785,
"text": "Example 2:"
},
{
"code": null,
"e": 2804,
"s": 2796,
"text": "Python3"
},
{
"code": "df.agg({'Col_A' : ['sum', 'min'], 'Col_B' : ['min', 'max'], 'Col_C' : ['sum', 'mean']})",
"e": 2906,
"s": 2804,
"text": null
},
{
"code": null,
"e": 2914,
"s": 2906,
"text": "Output:"
},
{
"code": null,
"e": 3007,
"s": 2914,
"text": "Note: It will print NaN if a particular aggregation is not performed on a particular column."
},
{
"code": null,
"e": 3279,
"s": 3007,
"text": "3. Performing aggregation over the columns: This performs aggregate function over the columns. As shown in example 1, the mean of first (10,20,30), second (40,50,60), third (70,80,90) and fourth (100,110,120) elements of each column is calculated separately and printed. "
},
{
"code": null,
"e": 3288,
"s": 3279,
"text": "Example:"
},
{
"code": null,
"e": 3296,
"s": 3288,
"text": "Python3"
},
{
"code": "df.agg(\"mean\", axis = \"columns\")",
"e": 3329,
"s": 3296,
"text": null
},
{
"code": null,
"e": 3337,
"s": 3329,
"text": "Output:"
},
{
"code": null,
"e": 3434,
"s": 3337,
"text": "4. Custom Aggregate function: Sometimes it becomes a need to create our own aggregate function. "
},
{
"code": null,
"e": 3544,
"s": 3434,
"text": "Example: Consider a data frame consisting of student id (stu_id), subject code (sub_code) and marks (marks). "
},
{
"code": null,
"e": 3552,
"s": 3544,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # Creating DataFramedf = pd.DataFrame( {'stud_id' : [101, 102, 103, 104, 101, 102, 103, 104], 'sub_code' : ['CSE6001', 'CSE6001', 'CSE6001', 'CSE6001', 'CSE6002', 'CSE6002', 'CSE6002', 'CSE6002'], 'marks' : [77, 86, 55, 90, 65, 90, 80, 67]}) # Printing DataFramedf",
"e": 3945,
"s": 3552,
"text": null
},
{
"code": null,
"e": 3953,
"s": 3945,
"text": "Output:"
},
{
"code": null,
"e": 4159,
"s": 3953,
"text": "Now if you need to calculate the total marks (marks of two subjects) of each student (unique stu_id). This process can be done using custom aggregate function. Here my custom aggregate function is ‘total’."
},
{
"code": null,
"e": 4167,
"s": 4159,
"text": "Python3"
},
{
"code": "# Importing reduce for # rolling computationsfrom functools import reduce # define a Custom aggregation # function for finding totaldef total(series): return reduce(lambda x, y: x + y, series) # Grouping the output according to # student id and printing the corresponding # total marks and to check whether the# output is correct or not, sum function # is also used to print the sum.df.groupby('stud_id').agg({'marks': ['sum', total]})",
"e": 4610,
"s": 4167,
"text": null
},
{
"code": null,
"e": 4618,
"s": 4610,
"text": "Output:"
},
{
"code": null,
"e": 4765,
"s": 4618,
"text": "As you can see, both the columns have same values of total marks, so our aggregate function is correctly calculating the total marks in this case."
},
{
"code": null,
"e": 4779,
"s": 4765,
"text": "Python-pandas"
},
{
"code": null,
"e": 4786,
"s": 4779,
"text": "Python"
}
] |
How to get the MAC and IP address of a connected client in PHP? | 23 Feb, 2022
What is a MAC address?MAC is the abbreviation of “Media Access Control” and it is a 48-bit physical address associated with every networking device. It is printed on the NIC(Network Interface Card) and is globally unique for every networking device. MAC address is used by the data-link layer to route a data packet from source to destination.
What is an IP address?An Internet Protocol(IP) address also known as a logical address is given by the internet service provider(ISP) which uniquely identifies a system over the network. IP address keeps on changing time to time.
How to get the IP address of the connected client in PHP: $_SERVER is a PHP superglobal variable which holds information about the header, path and script locations. Superglobal variables are the predefined variables which are always accessible. These superglobals store information in the form of associative-array, and here we are going to fetch the ‘REMOTE_ADDR’ key of the $_SERVER associative array to get the client’s IP Address. ‘REMOTE_ADDR’ returns the client’s IP address
Example 1: This example illustrates how to get Client’s IP Address using $_SERVER[‘REMOTE_ADDR’].
<?php // PHP program to get IP address of client$IP = $_SERVER['REMOTE_ADDR']; // $IP stores the ip address of clientecho "Client's IP address is: $IP"; // Print the ip address of client?>
Output:
Client's IP address is: ::1
Note: For an online IDE, it may show runtime error or it will not show any output because private domains don’t share their IP. For localhost, IP address is 127.0.0.1 that is a loopback address and so the client’s IP address is ::1.
How to get the MAC address of the connected client in PHP: The ‘exec()’ is a function which is used to run an external program in PHP. It returns the last line from the result of the command. To get the MAC address, pass the parameter ‘getmac’ which returns the MAC address of the client. ‘getmac’ is a CMD command to get the MAC address.
Example 2: This example get the MAC Address using exec() function.
<?php // PHP code to get the MAC address of Server$MAC = exec('getmac'); // Storing 'getmac' value in $MAC$MAC = strtok($MAC, ' '); // Updating $MAC value using strtok function, // strtok is used to split the string into tokens// split character of strtok is defined as a space// because getmac returns transport name after// MAC address echo "MAC address of Server is: $MAC";?>
Output:
MAC address of Server is: 00-20-10-2A-03-0A
Note: This code will not work on online IDE, because ‘getmac’ is a CMD command. Try running it on localhost.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
abelchavez20211
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 396,
"s": 52,
"text": "What is a MAC address?MAC is the abbreviation of “Media Access Control” and it is a 48-bit physical address associated with every networking device. It is printed on the NIC(Network Interface Card) and is globally unique for every networking device. MAC address is used by the data-link layer to route a data packet from source to destination."
},
{
"code": null,
"e": 626,
"s": 396,
"text": "What is an IP address?An Internet Protocol(IP) address also known as a logical address is given by the internet service provider(ISP) which uniquely identifies a system over the network. IP address keeps on changing time to time."
},
{
"code": null,
"e": 1108,
"s": 626,
"text": "How to get the IP address of the connected client in PHP: $_SERVER is a PHP superglobal variable which holds information about the header, path and script locations. Superglobal variables are the predefined variables which are always accessible. These superglobals store information in the form of associative-array, and here we are going to fetch the ‘REMOTE_ADDR’ key of the $_SERVER associative array to get the client’s IP Address. ‘REMOTE_ADDR’ returns the client’s IP address"
},
{
"code": null,
"e": 1206,
"s": 1108,
"text": "Example 1: This example illustrates how to get Client’s IP Address using $_SERVER[‘REMOTE_ADDR’]."
},
{
"code": "<?php // PHP program to get IP address of client$IP = $_SERVER['REMOTE_ADDR']; // $IP stores the ip address of clientecho \"Client's IP address is: $IP\"; // Print the ip address of client?>",
"e": 1398,
"s": 1206,
"text": null
},
{
"code": null,
"e": 1406,
"s": 1398,
"text": "Output:"
},
{
"code": null,
"e": 1435,
"s": 1406,
"text": "Client's IP address is: ::1\n"
},
{
"code": null,
"e": 1668,
"s": 1435,
"text": "Note: For an online IDE, it may show runtime error or it will not show any output because private domains don’t share their IP. For localhost, IP address is 127.0.0.1 that is a loopback address and so the client’s IP address is ::1."
},
{
"code": null,
"e": 2007,
"s": 1668,
"text": "How to get the MAC address of the connected client in PHP: The ‘exec()’ is a function which is used to run an external program in PHP. It returns the last line from the result of the command. To get the MAC address, pass the parameter ‘getmac’ which returns the MAC address of the client. ‘getmac’ is a CMD command to get the MAC address."
},
{
"code": null,
"e": 2074,
"s": 2007,
"text": "Example 2: This example get the MAC Address using exec() function."
},
{
"code": "<?php // PHP code to get the MAC address of Server$MAC = exec('getmac'); // Storing 'getmac' value in $MAC$MAC = strtok($MAC, ' '); // Updating $MAC value using strtok function, // strtok is used to split the string into tokens// split character of strtok is defined as a space// because getmac returns transport name after// MAC address echo \"MAC address of Server is: $MAC\";?>",
"e": 2458,
"s": 2074,
"text": null
},
{
"code": null,
"e": 2466,
"s": 2458,
"text": "Output:"
},
{
"code": null,
"e": 2511,
"s": 2466,
"text": "MAC address of Server is: 00-20-10-2A-03-0A\n"
},
{
"code": null,
"e": 2620,
"s": 2511,
"text": "Note: This code will not work on online IDE, because ‘getmac’ is a CMD command. Try running it on localhost."
},
{
"code": null,
"e": 2789,
"s": 2620,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 2805,
"s": 2789,
"text": "abelchavez20211"
},
{
"code": null,
"e": 2812,
"s": 2805,
"text": "Picked"
},
{
"code": null,
"e": 2816,
"s": 2812,
"text": "PHP"
},
{
"code": null,
"e": 2829,
"s": 2816,
"text": "PHP Programs"
},
{
"code": null,
"e": 2846,
"s": 2829,
"text": "Web Technologies"
},
{
"code": null,
"e": 2873,
"s": 2846,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2877,
"s": 2873,
"text": "PHP"
},
{
"code": null,
"e": 2975,
"s": 2877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3015,
"s": 2975,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3060,
"s": 3015,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3108,
"s": 3060,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 3160,
"s": 3108,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 3193,
"s": 3160,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 3233,
"s": 3193,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3285,
"s": 3233,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 3333,
"s": 3285,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 3385,
"s": 3333,
"text": "Split a comma delimited string into an array in PHP"
}
] |
Find a Mother Vertex in a Graph | 30 Jun, 2022
What is a Mother Vertex? A mother vertex in a graph G = (V, E) is a vertex v such that all other vertices in G can be reached by a path from v.
Example:
Input : Below Graph
Output : 5
There can be more than one mother vertices in a graph. We need to output anyone of them. For example, in the below graph, vertices 0, 1, and 2 are mother vertices.
We strongly recommend you to minimize your browser and try this yourself first.
How to find mother vertex?
Case 1:- Undirected Connected Graph : In this case, all the vertices are mother vertices as we can reach to all the other nodes in the graph.
Case 2:- Undirected/Directed Disconnected Graph : In this case, there is no mother vertices as we cannot reach to all the other nodes in the graph.
Case 3:- Directed Connected Graph : In this case, we have to find a vertex -v in the graph such that we can reach to all the other nodes in the graph through a directed path.
A Naive approach : A trivial approach will be to perform a DFS/BFS on all the vertices and find whether we can reach all the vertices from that vertex. This approach takes O(V(E+V)) time, which is very inefficient for large graphs.
Can we do better? We can find a mother vertex in O(V+E) time. The idea is based on Kosaraju’s Strongly Connected Component Algorithm. In a graph of strongly connected components, mother vertices are always vertices of source component in component graph. The idea is based on below fact.If there exist mother vertex (or vertices), then one of the mother vertices is the last finished vertex in DFS. (Or a mother vertex has the maximum finish time in DFS traversal).A vertex is said to be finished in DFS if a recursive call for its DFS is over, i.e., all descendants of the vertex have been visited.
How does the above idea work? Let the last finished vertex be v. Basically, we need to prove that there cannot be an edge from another vertex u to v if u is not another mother vertex (Or there cannot exist a non-mother vertex u such that u-→v is an edge). There can be two possibilities.
Recursive DFS call is made for u before v. If an edge u-→v exists, then v must have finished before u because v is reachable through u and a vertex finishes after all its descendants.Recursive DFS call is made for v before u. In this case also, if an edge u-→v exists, then either v must finish before u (which contradicts our assumption that v is finished at the end) OR u should be reachable from v (which means u is another mother vertex).
Recursive DFS call is made for u before v. If an edge u-→v exists, then v must have finished before u because v is reachable through u and a vertex finishes after all its descendants.
Recursive DFS call is made for v before u. In this case also, if an edge u-→v exists, then either v must finish before u (which contradicts our assumption that v is finished at the end) OR u should be reachable from v (which means u is another mother vertex).
Algorithm :
Do DFS traversal of the given graph. While doing traversal keep track of last finished vertex ‘v’. This step takes O(V+E) time.If there exist mother vertex (or vertices), then v must be one (or one of them). Check if v is a mother vertex by doing DFS/BFS from v. This step also takes O(V+E) time.
Do DFS traversal of the given graph. While doing traversal keep track of last finished vertex ‘v’. This step takes O(V+E) time.
If there exist mother vertex (or vertices), then v must be one (or one of them). Check if v is a mother vertex by doing DFS/BFS from v. This step also takes O(V+E) time.
Below is the implementation of above algorithm.
C++
Java
Python3
C#
Javascript
// C++ program to find a mother vertex in O(V+E) time#include <bits/stdc++.h>using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // adjacency lists // A recursive function to print DFS starting from v void DFSUtil(int v, vector<bool> &visited);public: Graph(int V); void addEdge(int v, int w); int findMother();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} // A recursive function to print DFS starting from vvoid Graph::DFSUtil(int v, vector<bool> &visited){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // Returns a mother vertex if exists. Otherwise returns -1int Graph::findMother(){ // visited[] is used for DFS. Initially all are // initialized as not visited vector <bool> visited(V, false); // To store last finished vertex (or mother vertex) int v = 0; // Do a DFS traversal and find the last finished // vertex for (int i = 0; i < V; i++) { if (visited[i] == false) { DFSUtil(i, visited); v = i; } } // If there exist mother vertex (or vertices) in given // graph, then v must be one (or one of them) // Now check if v is actually a mother vertex (or graph // has a mother vertex). We basically check if every vertex // is reachable from v or not. // Reset all values in visited[] as false and do // DFS beginning from v to check if all vertices are // reachable from it or not. fill(visited.begin(), visited.end(), false); DFSUtil(v, visited); for (int i=0; i<V; i++) if (visited[i] == false) return -1; return v;} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(4, 1); g.addEdge(6, 4); g.addEdge(5, 6); g.addEdge(5, 2); g.addEdge(6, 0); cout << "A mother vertex is " << g.findMother(); return 0;}
// Java program to find a mother// vertex in O(V+E) timeimport java.util.*; class GFG{ static void addEdge(int u, int v, ArrayList<ArrayList<Integer>> adj){ adj.get(u).add(v);} // A recursive function to print DFS starting from vstatic void DFSUtil(ArrayList<ArrayList<Integer>> g, int v, boolean[] visited){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(int x : g.get(v)) { if (!visited[x]) { DFSUtil(g, x, visited); } }} // Returns a mother vertex if exists.// Otherwise returns -1static int motherVertex(ArrayList<ArrayList<Integer>>g, int V){ // visited[] is used for DFS. Initially // all are initialized as not visited boolean[] visited = new boolean[V]; // To store last finished vertex // (or mother vertex) int v = -1; for(int i = 0; i < V; i++) { if (!visited[i]) { DFSUtil(g, i, visited); v = i; } } // If there exist mother vertex (or vertices) // in given graph, then v must be one // (or one of them) // Now check if v is actually a mother // vertex (or graph has a mother vertex). // We basically check if every vertex // is reachable from v or not. // Reset all values in visited[] as false // and do DFS beginning from v to check // if all vertices are reachable from // it or not. boolean[] check = new boolean[V]; DFSUtil(g, v, check); for(boolean val : check) { if (!val) { return -1; } } return v;} // Driver code public static void main(String[] args) { int V = 7; int E = 8; ArrayList< ArrayList<Integer>> adj = new ArrayList< ArrayList<Integer>>(); for(int i = 0; i < V; i++) { adj.add(new ArrayList<Integer>()); } addEdge(0, 1,adj); addEdge(0, 2,adj); addEdge(1, 3,adj); addEdge(4, 1,adj); addEdge(6, 4,adj); addEdge(5, 6,adj); addEdge(5, 2,adj); addEdge(6, 0,adj); System.out.println("The mother vertex is " + motherVertex(adj, V));}} // This code is contributed by Tanay Shah
# program to find a mother vertex in O(V+E) timefrom collections import defaultdict # This class represents a directed graph using adjacency list# representationclass Graph: def __init__(self,vertices): self.V = vertices #No. of vertices self.graph = defaultdict(list) # default dictionary # A recursive function to print DFS starting from v def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) # Add w to the list of v def addEdge(self, v, w): self.graph[v].append(w) # Returns a mother vertex if exists. Otherwise returns -1 def findMother(self): # visited[] is used for DFS. Initially all are # initialized as not visited visited =[False]*(self.V) # To store last finished vertex (or mother vertex) v=0 # Do a DFS traversal and find the last finished # vertex for i in range(self.V): if visited[i]==False: self.DFSUtil(i,visited) v = i # If there exist mother vertex (or vertices) in given # graph, then v must be one (or one of them) # Now check if v is actually a mother vertex (or graph # has a mother vertex). We basically check if every vertex # is reachable from v or not. # Reset all values in visited[] as false and do # DFS beginning from v to check if all vertices are # reachable from it or not. visited = [False]*(self.V) self.DFSUtil(v, visited) if any(i == False for i in visited): return -1 else: return v # Create a graph given in the above diagramg = Graph(7)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 3)g.addEdge(4, 1)g.addEdge(6, 4)g.addEdge(5, 6)g.addEdge(5, 2)g.addEdge(6, 0)print ("A mother vertex is " + str(g.findMother())) # This code is contributed by Neelam Yadav
// C# program to find a mother// vertex in O(V+E) timeusing System;using System.Collections.Generic; class GFG{ static void addEdge(int u, int v, List<List<int>> adj){ adj[u].Add(v);} // A recursive function to print DFS starting from vstatic void DFSUtil(List<List<int>> g, int v, bool[] visited){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach(int x in g[v]) { if (!visited[x]) { DFSUtil(g, x, visited); } }} // Returns a mother vertex if exists.// Otherwise returns -1static int motherVertex(List<List<int>>g, int V){ // visited[] is used for DFS. Initially // all are initialized as not visited bool[] visited = new bool[V]; // To store last finished vertex // (or mother vertex) int v = -1; for(int i = 0; i < V; i++) { if (!visited[i]) { DFSUtil(g, i, visited); v = i; } } // If there exist mother vertex (or vertices) // in given graph, then v must be one // (or one of them) // Now check if v is actually a mother // vertex (or graph has a mother vertex). // We basically check if every vertex // is reachable from v or not. // Reset all values in visited[] as false // and do DFS beginning from v to check // if all vertices are reachable from // it or not. bool[] check = new bool[V]; DFSUtil(g, v, check); foreach(bool val in check) { if (!val) { return -1; } } return v;} // Driver code public static void Main(String[] args) { int V = 7; int E = 8; List< List<int>> adj = new List<List<int>>(); for(int i = 0; i < V; i++) { adj.Add(new List<int>()); } addEdge(0, 1,adj); addEdge(0, 2,adj); addEdge(1, 3,adj); addEdge(4, 1,adj); addEdge(6, 4,adj); addEdge(5, 6,adj); addEdge(5, 2,adj); addEdge(6, 0,adj); Console.WriteLine("The mother vertex is " + motherVertex(adj, V));}} // This code is contributed by Rajput-Ji
<script> // Javascript program to find a mother // vertex in O(V+E) time function addEdge(u, v, adj) { adj[u].push(v); } // A recursive function to print DFS starting from v function DFSUtil(g, v, visited) { // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(let x in g[v]) { if (!visited[x]) { DFSUtil(g, x, visited); } } } // Returns a mother vertex if exists. // Otherwise returns -1 function motherVertex(g, V) { // visited[] is used for DFS. Initially // all are initialized as not visited let visited = new Array(V); for(let i = 0; i < V; i++) { visited[i] = false; } // To store last finished vertex // (or mother vertex) let v = -1; for(let i = 0; i < V; i++) { if (!visited[i]) { DFSUtil(g, i, visited); v = i; } } // If there exist mother vertex (or vertices) // in given graph, then v must be one // (or one of them) // Now check if v is actually a mother // vertex (or graph has a mother vertex). // We basically check if every vertex // is reachable from v or not. // Reset all values in visited[] as false // and do DFS beginning from v to check // if all vertices are reachable from // it or not. let check = new Array(V); for(let i = 0; i < V; i++) { check[i] = false; } DFSUtil(g, v, check); for(let val in check) { if (!val) { return -1; } } return v-1; } let V = 7; let E = 8; let adj = []; for(let i = 0; i < V; i++) { adj.push([]); } addEdge(0, 1,adj); addEdge(0, 2,adj); addEdge(1, 3,adj); addEdge(4, 1,adj); addEdge(6, 4,adj); addEdge(5, 6,adj); addEdge(5, 2,adj); addEdge(6, 0,adj); document.write("The mother vertex is " + motherVertex(adj, V)); // This code is contributed by divyesh072019.</script>
A mother vertex is 5
Time Complexity : O(V + E)
This article is contributed by Rachit Belwariar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ShubhamDixit
tanayshah2399
khushboogoyal499
Rajput-Ji
kalrap615
amartyaniel20
divyesh072019
hardikkoriintern
DFS
graph-connectivity
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Detect Cycle in a Directed Graph
Introduction to Data Structures
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Minimum number of swaps required to sort an array
Bellman–Ford Algorithm | DP-23
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 198,
"s": 54,
"text": "What is a Mother Vertex? A mother vertex in a graph G = (V, E) is a vertex v such that all other vertices in G can be reached by a path from v."
},
{
"code": null,
"e": 208,
"s": 198,
"text": "Example: "
},
{
"code": null,
"e": 240,
"s": 208,
"text": "Input : Below Graph\nOutput : 5"
},
{
"code": null,
"e": 405,
"s": 240,
"text": "There can be more than one mother vertices in a graph. We need to output anyone of them. For example, in the below graph, vertices 0, 1, and 2 are mother vertices. "
},
{
"code": null,
"e": 485,
"s": 405,
"text": "We strongly recommend you to minimize your browser and try this yourself first."
},
{
"code": null,
"e": 513,
"s": 485,
"text": "How to find mother vertex? "
},
{
"code": null,
"e": 655,
"s": 513,
"text": "Case 1:- Undirected Connected Graph : In this case, all the vertices are mother vertices as we can reach to all the other nodes in the graph."
},
{
"code": null,
"e": 803,
"s": 655,
"text": "Case 2:- Undirected/Directed Disconnected Graph : In this case, there is no mother vertices as we cannot reach to all the other nodes in the graph."
},
{
"code": null,
"e": 978,
"s": 803,
"text": "Case 3:- Directed Connected Graph : In this case, we have to find a vertex -v in the graph such that we can reach to all the other nodes in the graph through a directed path."
},
{
"code": null,
"e": 1210,
"s": 978,
"text": "A Naive approach : A trivial approach will be to perform a DFS/BFS on all the vertices and find whether we can reach all the vertices from that vertex. This approach takes O(V(E+V)) time, which is very inefficient for large graphs."
},
{
"code": null,
"e": 1811,
"s": 1210,
"text": "Can we do better? We can find a mother vertex in O(V+E) time. The idea is based on Kosaraju’s Strongly Connected Component Algorithm. In a graph of strongly connected components, mother vertices are always vertices of source component in component graph. The idea is based on below fact.If there exist mother vertex (or vertices), then one of the mother vertices is the last finished vertex in DFS. (Or a mother vertex has the maximum finish time in DFS traversal).A vertex is said to be finished in DFS if a recursive call for its DFS is over, i.e., all descendants of the vertex have been visited. "
},
{
"code": null,
"e": 2099,
"s": 1811,
"text": "How does the above idea work? Let the last finished vertex be v. Basically, we need to prove that there cannot be an edge from another vertex u to v if u is not another mother vertex (Or there cannot exist a non-mother vertex u such that u-→v is an edge). There can be two possibilities."
},
{
"code": null,
"e": 2542,
"s": 2099,
"text": "Recursive DFS call is made for u before v. If an edge u-→v exists, then v must have finished before u because v is reachable through u and a vertex finishes after all its descendants.Recursive DFS call is made for v before u. In this case also, if an edge u-→v exists, then either v must finish before u (which contradicts our assumption that v is finished at the end) OR u should be reachable from v (which means u is another mother vertex)."
},
{
"code": null,
"e": 2726,
"s": 2542,
"text": "Recursive DFS call is made for u before v. If an edge u-→v exists, then v must have finished before u because v is reachable through u and a vertex finishes after all its descendants."
},
{
"code": null,
"e": 2986,
"s": 2726,
"text": "Recursive DFS call is made for v before u. In this case also, if an edge u-→v exists, then either v must finish before u (which contradicts our assumption that v is finished at the end) OR u should be reachable from v (which means u is another mother vertex)."
},
{
"code": null,
"e": 2999,
"s": 2986,
"text": "Algorithm : "
},
{
"code": null,
"e": 3296,
"s": 2999,
"text": "Do DFS traversal of the given graph. While doing traversal keep track of last finished vertex ‘v’. This step takes O(V+E) time.If there exist mother vertex (or vertices), then v must be one (or one of them). Check if v is a mother vertex by doing DFS/BFS from v. This step also takes O(V+E) time."
},
{
"code": null,
"e": 3424,
"s": 3296,
"text": "Do DFS traversal of the given graph. While doing traversal keep track of last finished vertex ‘v’. This step takes O(V+E) time."
},
{
"code": null,
"e": 3594,
"s": 3424,
"text": "If there exist mother vertex (or vertices), then v must be one (or one of them). Check if v is a mother vertex by doing DFS/BFS from v. This step also takes O(V+E) time."
},
{
"code": null,
"e": 3643,
"s": 3594,
"text": "Below is the implementation of above algorithm. "
},
{
"code": null,
"e": 3647,
"s": 3643,
"text": "C++"
},
{
"code": null,
"e": 3652,
"s": 3647,
"text": "Java"
},
{
"code": null,
"e": 3660,
"s": 3652,
"text": "Python3"
},
{
"code": null,
"e": 3663,
"s": 3660,
"text": "C#"
},
{
"code": null,
"e": 3674,
"s": 3663,
"text": "Javascript"
},
{
"code": "// C++ program to find a mother vertex in O(V+E) time#include <bits/stdc++.h>using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // adjacency lists // A recursive function to print DFS starting from v void DFSUtil(int v, vector<bool> &visited);public: Graph(int V); void addEdge(int v, int w); int findMother();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} // A recursive function to print DFS starting from vvoid Graph::DFSUtil(int v, vector<bool> &visited){ // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // Returns a mother vertex if exists. Otherwise returns -1int Graph::findMother(){ // visited[] is used for DFS. Initially all are // initialized as not visited vector <bool> visited(V, false); // To store last finished vertex (or mother vertex) int v = 0; // Do a DFS traversal and find the last finished // vertex for (int i = 0; i < V; i++) { if (visited[i] == false) { DFSUtil(i, visited); v = i; } } // If there exist mother vertex (or vertices) in given // graph, then v must be one (or one of them) // Now check if v is actually a mother vertex (or graph // has a mother vertex). We basically check if every vertex // is reachable from v or not. // Reset all values in visited[] as false and do // DFS beginning from v to check if all vertices are // reachable from it or not. fill(visited.begin(), visited.end(), false); DFSUtil(v, visited); for (int i=0; i<V; i++) if (visited[i] == false) return -1; return v;} // Driver program to test above functionsint main(){ // Create a graph given in the above diagram Graph g(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(4, 1); g.addEdge(6, 4); g.addEdge(5, 6); g.addEdge(5, 2); g.addEdge(6, 0); cout << \"A mother vertex is \" << g.findMother(); return 0;}",
"e": 5959,
"s": 3674,
"text": null
},
{
"code": "// Java program to find a mother// vertex in O(V+E) timeimport java.util.*; class GFG{ static void addEdge(int u, int v, ArrayList<ArrayList<Integer>> adj){ adj.get(u).add(v);} // A recursive function to print DFS starting from vstatic void DFSUtil(ArrayList<ArrayList<Integer>> g, int v, boolean[] visited){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(int x : g.get(v)) { if (!visited[x]) { DFSUtil(g, x, visited); } }} // Returns a mother vertex if exists.// Otherwise returns -1static int motherVertex(ArrayList<ArrayList<Integer>>g, int V){ // visited[] is used for DFS. Initially // all are initialized as not visited boolean[] visited = new boolean[V]; // To store last finished vertex // (or mother vertex) int v = -1; for(int i = 0; i < V; i++) { if (!visited[i]) { DFSUtil(g, i, visited); v = i; } } // If there exist mother vertex (or vertices) // in given graph, then v must be one // (or one of them) // Now check if v is actually a mother // vertex (or graph has a mother vertex). // We basically check if every vertex // is reachable from v or not. // Reset all values in visited[] as false // and do DFS beginning from v to check // if all vertices are reachable from // it or not. boolean[] check = new boolean[V]; DFSUtil(g, v, check); for(boolean val : check) { if (!val) { return -1; } } return v;} // Driver code public static void main(String[] args) { int V = 7; int E = 8; ArrayList< ArrayList<Integer>> adj = new ArrayList< ArrayList<Integer>>(); for(int i = 0; i < V; i++) { adj.add(new ArrayList<Integer>()); } addEdge(0, 1,adj); addEdge(0, 2,adj); addEdge(1, 3,adj); addEdge(4, 1,adj); addEdge(6, 4,adj); addEdge(5, 6,adj); addEdge(5, 2,adj); addEdge(6, 0,adj); System.out.println(\"The mother vertex is \" + motherVertex(adj, V));}} // This code is contributed by Tanay Shah",
"e": 8257,
"s": 5959,
"text": null
},
{
"code": "# program to find a mother vertex in O(V+E) timefrom collections import defaultdict # This class represents a directed graph using adjacency list# representationclass Graph: def __init__(self,vertices): self.V = vertices #No. of vertices self.graph = defaultdict(list) # default dictionary # A recursive function to print DFS starting from v def DFSUtil(self, v, visited): # Mark the current node as visited and print it visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) # Add w to the list of v def addEdge(self, v, w): self.graph[v].append(w) # Returns a mother vertex if exists. Otherwise returns -1 def findMother(self): # visited[] is used for DFS. Initially all are # initialized as not visited visited =[False]*(self.V) # To store last finished vertex (or mother vertex) v=0 # Do a DFS traversal and find the last finished # vertex for i in range(self.V): if visited[i]==False: self.DFSUtil(i,visited) v = i # If there exist mother vertex (or vertices) in given # graph, then v must be one (or one of them) # Now check if v is actually a mother vertex (or graph # has a mother vertex). We basically check if every vertex # is reachable from v or not. # Reset all values in visited[] as false and do # DFS beginning from v to check if all vertices are # reachable from it or not. visited = [False]*(self.V) self.DFSUtil(v, visited) if any(i == False for i in visited): return -1 else: return v # Create a graph given in the above diagramg = Graph(7)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 3)g.addEdge(4, 1)g.addEdge(6, 4)g.addEdge(5, 6)g.addEdge(5, 2)g.addEdge(6, 0)print (\"A mother vertex is \" + str(g.findMother())) # This code is contributed by Neelam Yadav",
"e": 10332,
"s": 8257,
"text": null
},
{
"code": "// C# program to find a mother// vertex in O(V+E) timeusing System;using System.Collections.Generic; class GFG{ static void addEdge(int u, int v, List<List<int>> adj){ adj[u].Add(v);} // A recursive function to print DFS starting from vstatic void DFSUtil(List<List<int>> g, int v, bool[] visited){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach(int x in g[v]) { if (!visited[x]) { DFSUtil(g, x, visited); } }} // Returns a mother vertex if exists.// Otherwise returns -1static int motherVertex(List<List<int>>g, int V){ // visited[] is used for DFS. Initially // all are initialized as not visited bool[] visited = new bool[V]; // To store last finished vertex // (or mother vertex) int v = -1; for(int i = 0; i < V; i++) { if (!visited[i]) { DFSUtil(g, i, visited); v = i; } } // If there exist mother vertex (or vertices) // in given graph, then v must be one // (or one of them) // Now check if v is actually a mother // vertex (or graph has a mother vertex). // We basically check if every vertex // is reachable from v or not. // Reset all values in visited[] as false // and do DFS beginning from v to check // if all vertices are reachable from // it or not. bool[] check = new bool[V]; DFSUtil(g, v, check); foreach(bool val in check) { if (!val) { return -1; } } return v;} // Driver code public static void Main(String[] args) { int V = 7; int E = 8; List< List<int>> adj = new List<List<int>>(); for(int i = 0; i < V; i++) { adj.Add(new List<int>()); } addEdge(0, 1,adj); addEdge(0, 2,adj); addEdge(1, 3,adj); addEdge(4, 1,adj); addEdge(6, 4,adj); addEdge(5, 6,adj); addEdge(5, 2,adj); addEdge(6, 0,adj); Console.WriteLine(\"The mother vertex is \" + motherVertex(adj, V));}} // This code is contributed by Rajput-Ji",
"e": 12519,
"s": 10332,
"text": null
},
{
"code": "<script> // Javascript program to find a mother // vertex in O(V+E) time function addEdge(u, v, adj) { adj[u].push(v); } // A recursive function to print DFS starting from v function DFSUtil(g, v, visited) { // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(let x in g[v]) { if (!visited[x]) { DFSUtil(g, x, visited); } } } // Returns a mother vertex if exists. // Otherwise returns -1 function motherVertex(g, V) { // visited[] is used for DFS. Initially // all are initialized as not visited let visited = new Array(V); for(let i = 0; i < V; i++) { visited[i] = false; } // To store last finished vertex // (or mother vertex) let v = -1; for(let i = 0; i < V; i++) { if (!visited[i]) { DFSUtil(g, i, visited); v = i; } } // If there exist mother vertex (or vertices) // in given graph, then v must be one // (or one of them) // Now check if v is actually a mother // vertex (or graph has a mother vertex). // We basically check if every vertex // is reachable from v or not. // Reset all values in visited[] as false // and do DFS beginning from v to check // if all vertices are reachable from // it or not. let check = new Array(V); for(let i = 0; i < V; i++) { check[i] = false; } DFSUtil(g, v, check); for(let val in check) { if (!val) { return -1; } } return v-1; } let V = 7; let E = 8; let adj = []; for(let i = 0; i < V; i++) { adj.push([]); } addEdge(0, 1,adj); addEdge(0, 2,adj); addEdge(1, 3,adj); addEdge(4, 1,adj); addEdge(6, 4,adj); addEdge(5, 6,adj); addEdge(5, 2,adj); addEdge(6, 0,adj); document.write(\"The mother vertex is \" + motherVertex(adj, V)); // This code is contributed by divyesh072019.</script>",
"e": 14823,
"s": 12519,
"text": null
},
{
"code": null,
"e": 14844,
"s": 14823,
"text": "A mother vertex is 5"
},
{
"code": null,
"e": 14871,
"s": 14844,
"text": "Time Complexity : O(V + E)"
},
{
"code": null,
"e": 15045,
"s": 14871,
"text": "This article is contributed by Rachit Belwariar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 15058,
"s": 15045,
"text": "ShubhamDixit"
},
{
"code": null,
"e": 15072,
"s": 15058,
"text": "tanayshah2399"
},
{
"code": null,
"e": 15089,
"s": 15072,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 15099,
"s": 15089,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 15109,
"s": 15099,
"text": "kalrap615"
},
{
"code": null,
"e": 15123,
"s": 15109,
"text": "amartyaniel20"
},
{
"code": null,
"e": 15137,
"s": 15123,
"text": "divyesh072019"
},
{
"code": null,
"e": 15154,
"s": 15137,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 15158,
"s": 15154,
"text": "DFS"
},
{
"code": null,
"e": 15177,
"s": 15158,
"text": "graph-connectivity"
},
{
"code": null,
"e": 15183,
"s": 15177,
"text": "Graph"
},
{
"code": null,
"e": 15187,
"s": 15183,
"text": "DFS"
},
{
"code": null,
"e": 15193,
"s": 15187,
"text": "Graph"
},
{
"code": null,
"e": 15291,
"s": 15193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15349,
"s": 15291,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 15369,
"s": 15349,
"text": "Topological Sorting"
},
{
"code": null,
"e": 15444,
"s": 15369,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 15477,
"s": 15444,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 15509,
"s": 15477,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 15542,
"s": 15509,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 15610,
"s": 15542,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 15660,
"s": 15610,
"text": "Minimum number of swaps required to sort an array"
},
{
"code": null,
"e": 15691,
"s": 15660,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
ProgressBar in Kotlin | 01 Sep, 2021
Android ProgressBar is a user interface control that indicates the progress of an operation. For example, downloading a file, uploading a file on the internet we can see the progress bar to estimate the time remaining in operation. There are two modes of ProgressBar:
Determinate ProgressBar
Indeterminate ProgressBar
In common, we use the Determinate progress mode in ProgressBar because it shows the quantity of progress that has occurred like the (%) percentage of the file downloaded, how much data was uploaded or downloaded on the internet, etc. If we have to use determinate we set the style of the progress bar as below:
XML
<ProgressBar android:id="@+id/pBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" />
Here, we don’t get the idea of the progress of work means how much it has been completed or How long it will take to complete. We can use indeterminate progressBar like below by setting the indeterminate attribute as true.
XML
<ProgressBar android:id="@+id/pBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:indeterminate="true"/>
XML Attributes
Description
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- adding progress bar --> <ProgressBar android:id="@+id/progress_Bar" style="?android:attr/progressBarStyle" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_marginLeft="70dp" android:layout_marginTop="150dp" android:indeterminate = "true" android:max="100" android:minWidth="200dp" android:minHeight="50dp" android:visibility="invisible" android:layout_centerInParent="true" android:progress="0" android:layout_marginStart="70dp" /> <!-- adding textview which will show the progress --> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/progress_Bar" android:layout_centerHorizontal="true" /> <!-- adding button to start the progress --> <Button android:id="@+id/show_button" android:layout_width="191dp" android:layout_height="wrap_content" android:layout_below="@+id/text_view" android:layout_marginLeft="70dp" android:layout_marginTop="20dp" android:text="Progress Bar" android:layout_centerHorizontal="true" android:layout_marginStart="70dp" /> </RelativeLayout>
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.ProgressBarimport android.widget.TextViewimport android.os.Handler class MainActivity : AppCompatActivity() { private var progressBar: ProgressBar? = null private var i = 0 private var txtView: TextView? = null private val handler = Handler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding progressbar by its id progressBar = findViewById<ProgressBar>(R.id.progress_Bar) as ProgressBar // finding textview by its id txtView = findViewById<TextView>(R.id.text_view) // finding button by its id val btn = findViewById<Button>(R.id.show_button) // handling click on button btn.setOnClickListener { // Before clicking the button the progress bar will invisible // so we have to change the visibility of the progress bar to visible // setting the progressbar visibility to visible progressBar.visibility = View.VISIBLE i = progressBar.progress Thread(Runnable { // this loop will run until the value of i becomes 99 while (i < 100) { i += 1 // Update the progress bar and display the current value handler.post(Runnable { progressBar.progress = i // setting current progress to the textview txtView!!.text = i.toString() + "/" + progressBar.max }) try { Thread.sleep(100) } catch (e: InterruptedException) { e.printStackTrace() } } // setting the visibility of the progressbar to invisible // or you can use View.GONE instead of invisible // View.GONE will remove the progressbar progressBar.visibility = View.INVISIBLE }).start() } }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Pushpender007
ruhelaa48
Android-Bars
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 297,
"s": 28,
"text": "Android ProgressBar is a user interface control that indicates the progress of an operation. For example, downloading a file, uploading a file on the internet we can see the progress bar to estimate the time remaining in operation. There are two modes of ProgressBar: "
},
{
"code": null,
"e": 321,
"s": 297,
"text": "Determinate ProgressBar"
},
{
"code": null,
"e": 347,
"s": 321,
"text": "Indeterminate ProgressBar"
},
{
"code": null,
"e": 659,
"s": 347,
"text": "In common, we use the Determinate progress mode in ProgressBar because it shows the quantity of progress that has occurred like the (%) percentage of the file downloaded, how much data was uploaded or downloaded on the internet, etc. If we have to use determinate we set the style of the progress bar as below: "
},
{
"code": null,
"e": 663,
"s": 659,
"text": "XML"
},
{
"code": "<ProgressBar android:id=\"@+id/pBar\" style=\"?android:attr/progressBarStyleHorizontal\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" />",
"e": 836,
"s": 663,
"text": null
},
{
"code": null,
"e": 1060,
"s": 836,
"text": "Here, we don’t get the idea of the progress of work means how much it has been completed or How long it will take to complete. We can use indeterminate progressBar like below by setting the indeterminate attribute as true. "
},
{
"code": null,
"e": 1064,
"s": 1060,
"text": "XML"
},
{
"code": "<ProgressBar android:id=\"@+id/pBar\" style=\"?android:attr/progressBarStyleHorizontal\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:indeterminate=\"true\"/>",
"e": 1268,
"s": 1064,
"text": null
},
{
"code": null,
"e": 1283,
"s": 1268,
"text": "XML Attributes"
},
{
"code": null,
"e": 1295,
"s": 1283,
"text": "Description"
},
{
"code": null,
"e": 1299,
"s": 1295,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- adding progress bar --> <ProgressBar android:id=\"@+id/progress_Bar\" style=\"?android:attr/progressBarStyle\" android:layout_width=\"200dp\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"70dp\" android:layout_marginTop=\"150dp\" android:indeterminate = \"true\" android:max=\"100\" android:minWidth=\"200dp\" android:minHeight=\"50dp\" android:visibility=\"invisible\" android:layout_centerInParent=\"true\" android:progress=\"0\" android:layout_marginStart=\"70dp\" /> <!-- adding textview which will show the progress --> <TextView android:id=\"@+id/text_view\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/progress_Bar\" android:layout_centerHorizontal=\"true\" /> <!-- adding button to start the progress --> <Button android:id=\"@+id/show_button\" android:layout_width=\"191dp\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/text_view\" android:layout_marginLeft=\"70dp\" android:layout_marginTop=\"20dp\" android:text=\"Progress Bar\" android:layout_centerHorizontal=\"true\" android:layout_marginStart=\"70dp\" /> </RelativeLayout>",
"e": 2945,
"s": 1299,
"text": null
},
{
"code": null,
"e": 2952,
"s": 2945,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.ProgressBarimport android.widget.TextViewimport android.os.Handler class MainActivity : AppCompatActivity() { private var progressBar: ProgressBar? = null private var i = 0 private var txtView: TextView? = null private val handler = Handler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding progressbar by its id progressBar = findViewById<ProgressBar>(R.id.progress_Bar) as ProgressBar // finding textview by its id txtView = findViewById<TextView>(R.id.text_view) // finding button by its id val btn = findViewById<Button>(R.id.show_button) // handling click on button btn.setOnClickListener { // Before clicking the button the progress bar will invisible // so we have to change the visibility of the progress bar to visible // setting the progressbar visibility to visible progressBar.visibility = View.VISIBLE i = progressBar.progress Thread(Runnable { // this loop will run until the value of i becomes 99 while (i < 100) { i += 1 // Update the progress bar and display the current value handler.post(Runnable { progressBar.progress = i // setting current progress to the textview txtView!!.text = i.toString() + \"/\" + progressBar.max }) try { Thread.sleep(100) } catch (e: InterruptedException) { e.printStackTrace() } } // setting the visibility of the progressbar to invisible // or you can use View.GONE instead of invisible // View.GONE will remove the progressbar progressBar.visibility = View.INVISIBLE }).start() } }}",
"e": 5241,
"s": 2952,
"text": null
},
{
"code": null,
"e": 5245,
"s": 5241,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 5957,
"s": 5245,
"text": null
},
{
"code": null,
"e": 5971,
"s": 5957,
"text": "Pushpender007"
},
{
"code": null,
"e": 5981,
"s": 5971,
"text": "ruhelaa48"
},
{
"code": null,
"e": 5994,
"s": 5981,
"text": "Android-Bars"
},
{
"code": null,
"e": 6009,
"s": 5994,
"text": "Kotlin Android"
},
{
"code": null,
"e": 6016,
"s": 6009,
"text": "Picked"
},
{
"code": null,
"e": 6024,
"s": 6016,
"text": "Android"
},
{
"code": null,
"e": 6031,
"s": 6024,
"text": "Kotlin"
},
{
"code": null,
"e": 6039,
"s": 6031,
"text": "Android"
}
] |
Random Number Generator in Solidity using keccak256 | 11 May, 2022
Random numbers are numbers that occur in a sequence with the following two mandatory conditions:
The values are uniformly distributed over a set interval.One cannot predict future values based on past outputs.
The values are uniformly distributed over a set interval.
One cannot predict future values based on past outputs.
Example: In the below example, we have created a contract with a function that will generate a random number. Below is the step by step description of the entire process to be followed.
Step 1: Take the instance of now, the msg.sender, and an incrementing nonce.
Step 2: “pack” the inputs and use keccak256() to convert into 256-bit hash.
Step 3: Convert that hash to an uint, and then use % 100 to take only the last 2 digits. This will give us a totally random number between 0 and 99.
Solidity
// Solidity program to// demonstrate on how// to generate a random numberpragma solidity ^0.6.6; // Creating a contractcontract GeeksForGeeksRandom{ // Initializing the state variableuint randNonce = 0; // Defining a function to generate// a random numberfunction randMod(uint _modulus) internal returns(uint){ // increase nonce randNonce++; return uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % _ modulus; }}
Input:
100
Output:
Note: The alias “now” for block.timestamp in the line below was removed in the version 0.7.0 , you can use block.timestamp in place of now
return uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % _modulus;
Possible attacks with this approach:
In Ethereum, all nodes are trying to solve the problem and verify the transaction. Once a node verifies it, it broadcasts it to the network.
Suppose we create a DApp where we flip a coin where the head is the winning side. We use the above function to predict heads or tails. If I were running a node, I could publish a transaction only to my own node and not share it. I will run the randMod function or the coin flip function until I will and will only share the transaction after I have won.
One way to solve this would be to use an oracle to access a random number function from outside the Ethereum blockchain. There are other cryptographic algorithms and third party functions that can be utilized, but they are not safe or should be audited.
simranarora5sos
nirban256
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 151,
"s": 54,
"text": "Random numbers are numbers that occur in a sequence with the following two mandatory conditions:"
},
{
"code": null,
"e": 264,
"s": 151,
"text": "The values are uniformly distributed over a set interval.One cannot predict future values based on past outputs."
},
{
"code": null,
"e": 322,
"s": 264,
"text": "The values are uniformly distributed over a set interval."
},
{
"code": null,
"e": 378,
"s": 322,
"text": "One cannot predict future values based on past outputs."
},
{
"code": null,
"e": 564,
"s": 378,
"text": "Example: In the below example, we have created a contract with a function that will generate a random number. Below is the step by step description of the entire process to be followed."
},
{
"code": null,
"e": 641,
"s": 564,
"text": "Step 1: Take the instance of now, the msg.sender, and an incrementing nonce."
},
{
"code": null,
"e": 717,
"s": 641,
"text": "Step 2: “pack” the inputs and use keccak256() to convert into 256-bit hash."
},
{
"code": null,
"e": 866,
"s": 717,
"text": "Step 3: Convert that hash to an uint, and then use % 100 to take only the last 2 digits. This will give us a totally random number between 0 and 99."
},
{
"code": null,
"e": 875,
"s": 866,
"text": "Solidity"
},
{
"code": "// Solidity program to// demonstrate on how// to generate a random numberpragma solidity ^0.6.6; // Creating a contractcontract GeeksForGeeksRandom{ // Initializing the state variableuint randNonce = 0; // Defining a function to generate// a random numberfunction randMod(uint _modulus) internal returns(uint){ // increase nonce randNonce++; return uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % _ modulus; }}",
"e": 1432,
"s": 875,
"text": null
},
{
"code": null,
"e": 1442,
"s": 1435,
"text": "Input:"
},
{
"code": null,
"e": 1449,
"s": 1444,
"text": "100 "
},
{
"code": null,
"e": 1457,
"s": 1449,
"text": "Output:"
},
{
"code": null,
"e": 1602,
"s": 1459,
"text": "Note: The alias “now” for block.timestamp in the line below was removed in the version 0.7.0 , you can use block.timestamp in place of now"
},
{
"code": null,
"e": 1683,
"s": 1602,
"text": "return uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % _modulus;"
},
{
"code": null,
"e": 1720,
"s": 1683,
"text": "Possible attacks with this approach:"
},
{
"code": null,
"e": 1861,
"s": 1720,
"text": "In Ethereum, all nodes are trying to solve the problem and verify the transaction. Once a node verifies it, it broadcasts it to the network."
},
{
"code": null,
"e": 2217,
"s": 1863,
"text": "Suppose we create a DApp where we flip a coin where the head is the winning side. We use the above function to predict heads or tails. If I were running a node, I could publish a transaction only to my own node and not share it. I will run the randMod function or the coin flip function until I will and will only share the transaction after I have won."
},
{
"code": null,
"e": 2473,
"s": 2219,
"text": "One way to solve this would be to use an oracle to access a random number function from outside the Ethereum blockchain. There are other cryptographic algorithms and third party functions that can be utilized, but they are not safe or should be audited."
},
{
"code": null,
"e": 2491,
"s": 2475,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2501,
"s": 2491,
"text": "nirban256"
},
{
"code": null,
"e": 2512,
"s": 2501,
"text": "Blockchain"
},
{
"code": null,
"e": 2521,
"s": 2512,
"text": "Solidity"
}
] |
PyQtGraph – Setting Horizontal Range of Plot Window | 13 Sep, 2021
In this article we will see how we can set the horizontal range of the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. Horizontal range of the plot window is the range in which the view of horizontal axis lies i.e x-axis. A chart has an x-axis range and a y-axis range to show the correlation between two different data sets. The x-axis is the horizontal category line. Changes to the x-axis adjust the categories within this axis.
We can create a plot window with the help of command given below
# creating a pyqtgraph plot window
window = pg.plot()
In order to do this we use setXRange method with the plot window object
Syntax : window.setXRange(a, b)
Argument : It takes two integer as argument
Return : It returns None
Below is the implementation
# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np import time # creating a pyqtgraph plot windowwindow = pg.plot() # titletitle = "GeeksforGeeks PyQtGraph" # setting window titlewindow.setWindowTitle(title) # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6# with bar colors = greenbargraph1 = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph1) # setting horizontal rangewindow.setXRange(0, 30) # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
Output :
sagar0719kumar
Python-gui
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 943,
"s": 28,
"text": "In this article we will see how we can set the horizontal range of the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. Horizontal range of the plot window is the range in which the view of horizontal axis lies i.e x-axis. A chart has an x-axis range and a y-axis range to show the correlation between two different data sets. The x-axis is the horizontal category line. Changes to the x-axis adjust the categories within this axis."
},
{
"code": null,
"e": 1008,
"s": 943,
"text": "We can create a plot window with the help of command given below"
},
{
"code": null,
"e": 1063,
"s": 1008,
"text": "# creating a pyqtgraph plot window\nwindow = pg.plot()\n"
},
{
"code": null,
"e": 1135,
"s": 1063,
"text": "In order to do this we use setXRange method with the plot window object"
},
{
"code": null,
"e": 1167,
"s": 1135,
"text": "Syntax : window.setXRange(a, b)"
},
{
"code": null,
"e": 1211,
"s": 1167,
"text": "Argument : It takes two integer as argument"
},
{
"code": null,
"e": 1236,
"s": 1211,
"text": "Return : It returns None"
},
{
"code": null,
"e": 1264,
"s": 1236,
"text": "Below is the implementation"
},
{
"code": "# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np import time # creating a pyqtgraph plot windowwindow = pg.plot() # titletitle = \"GeeksforGeeks PyQtGraph\" # setting window titlewindow.setWindowTitle(title) # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6# with bar colors = greenbargraph1 = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph1) # setting horizontal rangewindow.setXRange(0, 30) # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() ",
"e": 2331,
"s": 1264,
"text": null
},
{
"code": null,
"e": 2340,
"s": 2331,
"text": "Output :"
},
{
"code": null,
"e": 2355,
"s": 2340,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2366,
"s": 2355,
"text": "Python-gui"
},
{
"code": null,
"e": 2383,
"s": 2366,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 2390,
"s": 2383,
"text": "Python"
}
] |
Python Pandas - Finding the uncommon rows between two DataFrames | To find the uncommon rows between two DataFrames, use the concat() method. Let us first import the required library with alias −
import pandas as pd
Create DataFrame1 with two columns −
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Reg_Price": [1000, 1500, 1100, 800, 1100, 900]
}
)
Create DataFrame2 with two columns −
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Reg_Price": [1000, 1300, 1000, 800, 1100, 800]
}
)
Finding uncommon rows between two DataFrames and concatenate the result −
print"\nUncommon rows between two DataFrames...\n",pd.concat([dataFrame1,dataFrame2]).drop_duplicates(keep=False)
Following is the code −
import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Reg_Price": [1000, 1500, 1100, 800, 1100, 900]
}
)
print"DataFrame1 ...\n",dataFrame1
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Reg_Price": [1000, 1300, 1000, 800, 1100, 800]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# finding uncommon rows between two DataFrames and concat the result
print"\nUncommon rows between two DataFrames...\n",pd.concat([dataFrame1,dataFrame2]).drop_duplicates(keep=False)
This will produce the following output −
DataFrame1 ...
Car Reg_Price
0 BMW 1000
1 Lexus 1500
2 Audi 1100
3 Tesla 800
4 Bentley 1100
5 Jaguar 900
DataFrame2 ...
Car Reg_Price
0 BMW 1000
1 Lexus 1300
2 Audi 1000
3 Tesla 800
4 Bentley 1100
5 Jaguar 800
Uncommon rows between two DataFrames...
Car Reg_Price
1 Lexus 1500
2 Audi 1100
5 Jaguar 900
1 Lexus 1300
2 Audi 1000
5 Jaguar 800 | [
{
"code": null,
"e": 1316,
"s": 1187,
"text": "To find the uncommon rows between two DataFrames, use the concat() method. Let us first import the required library with alias −"
},
{
"code": null,
"e": 1336,
"s": 1316,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1373,
"s": 1336,
"text": "Create DataFrame1 with two columns −"
},
{
"code": null,
"e": 1535,
"s": 1373,
"text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Reg_Price\": [1000, 1500, 1100, 800, 1100, 900]\n }\n)"
},
{
"code": null,
"e": 1572,
"s": 1535,
"text": "Create DataFrame2 with two columns −"
},
{
"code": null,
"e": 1734,
"s": 1572,
"text": "dataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Reg_Price\": [1000, 1300, 1000, 800, 1100, 800]\n }\n)"
},
{
"code": null,
"e": 1808,
"s": 1734,
"text": "Finding uncommon rows between two DataFrames and concatenate the result −"
},
{
"code": null,
"e": 1923,
"s": 1808,
"text": "print\"\\nUncommon rows between two DataFrames...\\n\",pd.concat([dataFrame1,dataFrame2]).drop_duplicates(keep=False)\n"
},
{
"code": null,
"e": 1947,
"s": 1923,
"text": "Following is the code −"
},
{
"code": null,
"e": 2594,
"s": 1947,
"text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Reg_Price\": [1000, 1500, 1100, 800, 1100, 900]\n }\n)\n\nprint\"DataFrame1 ...\\n\",dataFrame1\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Reg_Price\": [1000, 1300, 1000, 800, 1100, 800]\n }\n)\n\nprint\"\\nDataFrame2 ...\\n\",dataFrame2\n\n# finding uncommon rows between two DataFrames and concat the result\nprint\"\\nUncommon rows between two DataFrames...\\n\",pd.concat([dataFrame1,dataFrame2]).drop_duplicates(keep=False)\n\n\n"
},
{
"code": null,
"e": 2635,
"s": 2594,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3183,
"s": 2635,
"text": "DataFrame1 ...\n Car Reg_Price\n0 BMW 1000\n1 Lexus 1500\n2 Audi 1100\n3 Tesla 800\n4 Bentley 1100\n5 Jaguar 900\n\nDataFrame2 ...\n Car Reg_Price\n0 BMW 1000\n1 Lexus 1300\n2 Audi 1000\n3 Tesla 800\n4 Bentley 1100\n5 Jaguar 800\n\nUncommon rows between two DataFrames...\n Car Reg_Price\n1 Lexus 1500\n2 Audi 1100\n5 Jaguar 900\n1 Lexus 1300\n2 Audi 1000\n5 Jaguar 800"
}
] |
CSS Preprocessor | LESS | 27 May, 2020
LESS stands for Leaner Style Sheets. It is a backward-compatible language extension for CSS. It allows us to use features like variables, nesting, mixins, etc, all in a CSS-compatible syntax. LESS is influenced by SASS and has influenced the newer “SCSS” syntax of SASS. LESS was used in Bootstrap 3 but was replaced by SASS in Bootstrap 4.
Pre-Requisites:
HTML
CSS
System Requirements
Operating System: Cross-platform
Browser Support: IE (Internet Explorer 8+), Firefox, Google Chrome, Safari.
File Type: All LESS files must have the .less file extension.
Working: A web browser does not understand the LESS code itself. That is why you will require a LESS pre-processor to change LESS codes into simple standard CSS code.
Working Steps:
Write the LESS code in a file.
Compile the LESS code into CSS code using the command lessc input.less output.less.
Include the compiled CSS file in the html file.
Features:
Variables: Variables can be used to store CSS value that may be reused. They are initialized with @.@lt-gray: #ddd;@background-dark: #512DA8;@carousel-item-height: 300px;
@lt-gray: #ddd;@background-dark: #512DA8;@carousel-item-height: 300px;
Mixins: Mixins are a way of including a bunch of properties from one rule-set into another rule-set.zero-margin { margin:0px auto; background:@white;} .row-header { .zero-margin; padding:0px auto;} .row-content { .zero-margin; border-bottom: 1px ridge; min-height:400px; padding: 50px 0px 50px 0px;}
zero-margin { margin:0px auto; background:@white;} .row-header { .zero-margin; padding:0px auto;} .row-content { .zero-margin; border-bottom: 1px ridge; min-height:400px; padding: 50px 0px 50px 0px;}
Nesting: LESS gives you the ability to use nesting..carousel { background:@background-dark; .carousel-item { height: @carousel-item-height; img { position: absolute; top: 0; left: 0; min-height: 300px; } }}
.carousel { background:@background-dark; .carousel-item { height: @carousel-item-height; img { position: absolute; top: 0; left: 0; min-height: 300px; } }}
Mathematical Operations: Arithmetical operations +, -, *, / can operate on any number, color or variable..carousel-item { height: @carousel-item-height;} .carousel-item .item-large { height: @carousel-item-height *2;}
.carousel-item { height: @carousel-item-height;} .carousel-item .item-large { height: @carousel-item-height *2;}
Functions: LESS provides a variety of functions like math, list, string, color operations, color blending etc.@width: 0.8; .class { width: percentage(@width); // Returns `80%` color: saturate(@base, 5%); background-color: spin(lighten(@base, 25%), 8);}
@width: 0.8; .class { width: percentage(@width); // Returns `80%` color: saturate(@base, 5%); background-color: spin(lighten(@base, 25%), 8);}
Example: File name gfg.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>LESS</title> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="./css/style.css"> </head> <body> <div class="head">Welcome to GeeksforGeeks. <ul class="list"> <li class="a">Algo</li> <li>DS</li> <li class="a">Languages</li> <li>Interviews</li> <li>CS subjects</li> </ul> </div> </body> </html>
File name style.less
@color-primary: #009900;@font-pri: Sans-Serif;@font-sec: Helvetica; body{ color: @color-primary; font-size: 40px;} .list{ font-family: @font-pri; font-size: 20px; .a{ font-family: @font-sec; font-size: 10px; }}
File name style.css which we get after transpiling style.less
body { color: #009900; font-size: 40px;}.list { font-family: Sans-Serif; font-size: 20px;}.list .a { font-family: Helvetica; font-size: 10px;}
Output:
Advantages:
LESS is cross-browser compatible.
LESS provides a list of operators making it easy for users to code.
Maintenance is easy due to the use of variables.
Disadvantages:
LESS provides fewer frameworks as compared to SASS.
It can be tricky to those who are new to CSS.
CSS-Misc
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2020"
},
{
"code": null,
"e": 369,
"s": 28,
"text": "LESS stands for Leaner Style Sheets. It is a backward-compatible language extension for CSS. It allows us to use features like variables, nesting, mixins, etc, all in a CSS-compatible syntax. LESS is influenced by SASS and has influenced the newer “SCSS” syntax of SASS. LESS was used in Bootstrap 3 but was replaced by SASS in Bootstrap 4."
},
{
"code": null,
"e": 385,
"s": 369,
"text": "Pre-Requisites:"
},
{
"code": null,
"e": 390,
"s": 385,
"text": "HTML"
},
{
"code": null,
"e": 394,
"s": 390,
"text": "CSS"
},
{
"code": null,
"e": 414,
"s": 394,
"text": "System Requirements"
},
{
"code": null,
"e": 447,
"s": 414,
"text": "Operating System: Cross-platform"
},
{
"code": null,
"e": 523,
"s": 447,
"text": "Browser Support: IE (Internet Explorer 8+), Firefox, Google Chrome, Safari."
},
{
"code": null,
"e": 585,
"s": 523,
"text": "File Type: All LESS files must have the .less file extension."
},
{
"code": null,
"e": 752,
"s": 585,
"text": "Working: A web browser does not understand the LESS code itself. That is why you will require a LESS pre-processor to change LESS codes into simple standard CSS code."
},
{
"code": null,
"e": 767,
"s": 752,
"text": "Working Steps:"
},
{
"code": null,
"e": 798,
"s": 767,
"text": "Write the LESS code in a file."
},
{
"code": null,
"e": 882,
"s": 798,
"text": "Compile the LESS code into CSS code using the command lessc input.less output.less."
},
{
"code": null,
"e": 930,
"s": 882,
"text": "Include the compiled CSS file in the html file."
},
{
"code": null,
"e": 940,
"s": 930,
"text": "Features:"
},
{
"code": null,
"e": 1111,
"s": 940,
"text": "Variables: Variables can be used to store CSS value that may be reused. They are initialized with @.@lt-gray: #ddd;@background-dark: #512DA8;@carousel-item-height: 300px;"
},
{
"code": "@lt-gray: #ddd;@background-dark: #512DA8;@carousel-item-height: 300px;",
"e": 1182,
"s": 1111,
"text": null
},
{
"code": null,
"e": 1508,
"s": 1182,
"text": "Mixins: Mixins are a way of including a bunch of properties from one rule-set into another rule-set.zero-margin { margin:0px auto; background:@white;} .row-header { .zero-margin; padding:0px auto;} .row-content { .zero-margin; border-bottom: 1px ridge; min-height:400px; padding: 50px 0px 50px 0px;}"
},
{
"code": "zero-margin { margin:0px auto; background:@white;} .row-header { .zero-margin; padding:0px auto;} .row-content { .zero-margin; border-bottom: 1px ridge; min-height:400px; padding: 50px 0px 50px 0px;}",
"e": 1734,
"s": 1508,
"text": null
},
{
"code": null,
"e": 2017,
"s": 1734,
"text": "Nesting: LESS gives you the ability to use nesting..carousel { background:@background-dark; .carousel-item { height: @carousel-item-height; img { position: absolute; top: 0; left: 0; min-height: 300px; } }}"
},
{
"code": ".carousel { background:@background-dark; .carousel-item { height: @carousel-item-height; img { position: absolute; top: 0; left: 0; min-height: 300px; } }}",
"e": 2249,
"s": 2017,
"text": null
},
{
"code": null,
"e": 2474,
"s": 2249,
"text": "Mathematical Operations: Arithmetical operations +, -, *, / can operate on any number, color or variable..carousel-item { height: @carousel-item-height;} .carousel-item .item-large { height: @carousel-item-height *2;}"
},
{
"code": ".carousel-item { height: @carousel-item-height;} .carousel-item .item-large { height: @carousel-item-height *2;}",
"e": 2594,
"s": 2474,
"text": null
},
{
"code": null,
"e": 2857,
"s": 2594,
"text": "Functions: LESS provides a variety of functions like math, list, string, color operations, color blending etc.@width: 0.8; .class { width: percentage(@width); // Returns `80%` color: saturate(@base, 5%); background-color: spin(lighten(@base, 25%), 8);}"
},
{
"code": "@width: 0.8; .class { width: percentage(@width); // Returns `80%` color: saturate(@base, 5%); background-color: spin(lighten(@base, 25%), 8);}",
"e": 3010,
"s": 2857,
"text": null
},
{
"code": null,
"e": 3038,
"s": 3010,
"text": "Example: File name gfg.html"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"/> <title>LESS</title> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"./css/style.css\"> </head> <body> <div class=\"head\">Welcome to GeeksforGeeks. <ul class=\"list\"> <li class=\"a\">Algo</li> <li>DS</li> <li class=\"a\">Languages</li> <li>Interviews</li> <li>CS subjects</li> </ul> </div> </body> </html> ",
"e": 3703,
"s": 3038,
"text": null
},
{
"code": null,
"e": 3724,
"s": 3703,
"text": "File name style.less"
},
{
"code": "@color-primary: #009900;@font-pri: Sans-Serif;@font-sec: Helvetica; body{ color: @color-primary; font-size: 40px;} .list{ font-family: @font-pri; font-size: 20px; .a{ font-family: @font-sec; font-size: 10px; }}",
"e": 3969,
"s": 3724,
"text": null
},
{
"code": null,
"e": 4031,
"s": 3969,
"text": "File name style.css which we get after transpiling style.less"
},
{
"code": "body { color: #009900; font-size: 40px;}.list { font-family: Sans-Serif; font-size: 20px;}.list .a { font-family: Helvetica; font-size: 10px;}",
"e": 4180,
"s": 4031,
"text": null
},
{
"code": null,
"e": 4188,
"s": 4180,
"text": "Output:"
},
{
"code": null,
"e": 4200,
"s": 4188,
"text": "Advantages:"
},
{
"code": null,
"e": 4234,
"s": 4200,
"text": "LESS is cross-browser compatible."
},
{
"code": null,
"e": 4302,
"s": 4234,
"text": "LESS provides a list of operators making it easy for users to code."
},
{
"code": null,
"e": 4351,
"s": 4302,
"text": "Maintenance is easy due to the use of variables."
},
{
"code": null,
"e": 4366,
"s": 4351,
"text": "Disadvantages:"
},
{
"code": null,
"e": 4418,
"s": 4366,
"text": "LESS provides fewer frameworks as compared to SASS."
},
{
"code": null,
"e": 4464,
"s": 4418,
"text": "It can be tricky to those who are new to CSS."
},
{
"code": null,
"e": 4473,
"s": 4464,
"text": "CSS-Misc"
},
{
"code": null,
"e": 4477,
"s": 4473,
"text": "CSS"
},
{
"code": null,
"e": 4494,
"s": 4477,
"text": "Web Technologies"
},
{
"code": null,
"e": 4592,
"s": 4494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4629,
"s": 4592,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 4668,
"s": 4629,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4707,
"s": 4668,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4771,
"s": 4707,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 4832,
"s": 4771,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4865,
"s": 4832,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4926,
"s": 4865,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4969,
"s": 4926,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 5041,
"s": 4969,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Google Charts - Table Chart | Table chart helps in rendering a table which can be sorted and paged. Table cells can be formatted using format strings, or by directly inserting HTML as cell values. Numeric values are right-aligned by default; boolean values are displayed as check marks or cross marks. Users can select single rows either with the keyboard or the mouse. Column headers can be used for sorting. The header row remains fixed during scrolling. The table fires events corresponding to user interaction. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used Table class to show Table based chart.
//table chart
var chart = new google.visualization.Table(document.getElementById('container'));
googlecharts_table_chart.htm
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
</script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['table']});
</script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
</div>
<script language = "JavaScript">
function drawChart() {
// Define the chart to be drawn.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time Employee');
data.addRows([
['Mike', {v: 10000, f: '$10,000'}, true],
['Jim', {v:8000, f: '$8,000'}, false],
['Alice', {v: 12500, f: '$12,500'}, true],
['Bob', {v: 7000, f: '$7,000'}, true]
]);
var options = {
showRowNumber: true,
width: '100%',
height: '100%'
};
// Instantiate and draw the chart.
var chart = new google.visualization.Table(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
Verify the result. | [
{
"code": null,
"e": 3024,
"s": 2395,
"text": "Table chart helps in rendering a table which can be sorted and paged. Table cells can be formatted using format strings, or by directly inserting HTML as cell values. Numeric values are right-aligned by default; boolean values are displayed as check marks or cross marks. Users can select single rows either with the keyboard or the mouse. Column headers can be used for sorting. The header row remains fixed during scrolling. The table fires events corresponding to user interaction. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example."
},
{
"code": null,
"e": 3074,
"s": 3024,
"text": "We've used Table class to show Table based chart."
},
{
"code": null,
"e": 3171,
"s": 3074,
"text": "//table chart\nvar chart = new google.visualization.Table(document.getElementById('container'));\n"
},
{
"code": null,
"e": 3200,
"s": 3171,
"text": "googlecharts_table_chart.htm"
},
{
"code": null,
"e": 4657,
"s": 3200,
"text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\">\n </script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['table']}); \n </script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Name');\n data.addColumn('number', 'Salary');\n data.addColumn('boolean', 'Full Time Employee');\n data.addRows([\n ['Mike', {v: 10000, f: '$10,000'}, true],\n ['Jim', {v:8000, f: '$8,000'}, false],\n ['Alice', {v: 12500, f: '$12,500'}, true],\n ['Bob', {v: 7000, f: '$7,000'}, true]\n ]);\n\n var options = {\n showRowNumber: true,\n width: '100%', \n height: '100%'\n };\n \n // Instantiate and draw the chart.\n var chart = new google.visualization.Table(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>"
}
] |
Sum of Bitwise OR of all pairs in a given array | 25 Nov, 2021
Given an array “arr[0..n-1]” of integers. The task is to calculate the sum of Bitwise OR of all pairs, i.e. calculate the sum of “arr[i] | arr[j]” for all the pairs in the given array where i < j. Here ‘|’ is a bitwise OR operator. Expected time complexity is O(n).Examples :
Input: arr[] = {5, 10, 15}
Output: 15
Required Value = (5 | 10) + (5 | 15) + (10 | 15)
= 15 + 15 + 15
= 45
Input: arr[] = {1, 2, 3, 4}
Output: 3
Required Value = (1 | 2) + (1 | 3) + (1 | 4) +
(2 | 3) + (2 | 4) + (3 | 4)
= 3 + 3 + 5 + 3 + 6 + 7
= 27
A Brute Force approach is to run two loops and time complexity is O(n2).
C++
Java
Python3
C#
PHP
Javascript
// A Simple C++ program to compute sum of bitwise OR// of all pairs#include <bits/stdc++.h>using namespace std; // Returns value of "arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]"int pairORSum(int arr[], int n){ int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) such that // i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] | arr[j]; return ans;} // Driver program to test above functionint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << pairORSum(arr, n) << endl; return 0;}
// A Simple Java program to compute// sum of bitwise OR of all pairsimport java.io.*; class GFG { // Returns value of "arr[0] | arr[1] + // arr[0] | arr[2] + ... arr[i] | arr[j] + // ..... arr[n-2] | arr[n-1]" static int pairORSum(int arr[], int n) { int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] | arr[j]; return ans; } // Driver program to test above function public static void main(String args[]) { int arr[] = { 1, 2, 3, 4 }; int n = arr.length; System.out.println(pairORSum(arr, n)); }}
# A Simple Python 3 program to compute# sum of bitwise OR of all pairs # Returns value of "arr[0] | arr[1] +# arr[0] | arr[2] + ... arr[i] | arr[j] +# ..... arr[n-2] | arr[n-1]"def pairORSum(arr, n) : ans = 0 # Initialize result # Consider all pairs (arr[i], arr[j) # such that i < j for i in range(0, n) : for j in range((i + 1), n) : ans = ans + arr[i] | arr[j] return ans # Driver program to test above functionarr = [1, 2, 3, 4]n = len(arr)print(pairORSum(arr, n))
// A Simple C# program to compute// sum of bitwise OR of all pairsusing System; class GFG { // Returns value of "arr[0] | arr[1] + // arr[0] | arr[2] + ... arr[i] | arr[j] + // ..... arr[n-2] | arr[n-1]" static int pairORSum(int[] arr, int n) { int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] | arr[j]; return ans; } // Driver program to test above function public static void Main() { int[] arr = { 1, 2, 3, 4 }; int n = arr.Length; Console.Write(pairORSum(arr, n)); }}
<?php// A Simple PHP program to// compute sum of bitwise// OR of all pairs // Returns value of "arr[0] |// arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + .....// arr[n-2] | arr[n-1]" function pairORSum($arr, $n){ // Initialize result $ans = 0; // Consider all pairs (arr[i], // arr[j) such that i < j for ($i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) $ans += $arr[$i] | $arr[$j]; return $ans;} // Driver Code$arr = array(1, 2, 3, 4);$n = sizeof($arr) ;echo pairORSum($arr, $n), "\n"; ?>
<script> // A Simple Javascript program to compute sum of bitwise OR// of all pairs // Returns value of "arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]"function pairORSum(arr, n){ var ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) such that // i < j for (var i = 0; i < n; i++) for (var j = i + 1; j < n; j++) ans += arr[i] | arr[j]; return ans;} // Driver program to test above functionvar arr = [1, 2, 3, 4];var n = arr.length;document.write( pairORSum(arr, n)); </script>
Output:
27
Time Complexity: O(n2)
Auxiliary Space: O(1)
An Efficient Solution can solve this problem in O(n) time. The assumption here is that integers are represented using 32 bits.The idea is to count number of set bits at every i’th position (i>=0 && i<=31). Any i’th bit of the AND of two numbers is 1 iff the corresponding bit in both the numbers is equal to 1. Let k1 be the count of set bits at i’th position. Total number of pairs with i’th set bit would be k1C2 = k1*(k1-1)/2 (Count k1 means there are k1 numbers that have i’th set bit). Every such pair adds 2i to total sum. Similarly, there are total k0 values that don’t have set bits at i’th position. Now each element (which have not set the bit at the i’th position can make pair with k1 elements (ie., those elements which have set bits at the i’th position), So there are total k1 * k0 pairs and every such pair also adds 2i to total sum.sum = sum + (1<<i) * (k1*(k1-1)/2) + (1<<i) * (k1*k0) This idea is similar to finding sum of bit differences among all pairs. Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// An efficient C++ program to compute sum of bitwise OR// of all pairs#include <bits/stdc++.h>using namespace std;typedef long long int LLI; // Returns value of "arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]" LLI pairORSum(LLI arr[], LLI n){ LLI ans = 0; // Initialize result // Traverse over all bits for (LLI i = 0; i < 32; i++) { // Count number of elements with the i'th bit set(ie., 1) LLI k1 = 0; // Initialize the count // Count number of elements with i’th bit not-set(ie., 0) ` LLI k0 = 0; // Initialize the count for (LLI j = 0; j < n; j++) { if ((arr[j] & (1 << i))) // if i'th bit is set k1++; else k0++; } // There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, ans = ans + (1 << i) * (k1 * (k1 - 1) / 2) + (1 << i) * (k1 * k0); } return ans;} // Driver program to test the above function int main() { LLI arr[] = { 1, 2, 3, 4 }; LLI n = sizeof(arr) / sizeof(arr[0]); cout << pairORSum(arr, n) << endl; return 0;}
// An efficient Java program to compute// sum of bitwise OR of all pairsimport java.io.*; class GFG { // Returns value of "arr[0] | arr[1] + arr[0] | arr[2] + // ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]" static int pairORSum(int arr[], int n) { int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with the ith bit set(ie., 1) int k1 = 0; // Initialize the count // Count number of elements with ith bit not-set(ie., 0) ` int k0 = 0; // Initialize the count for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) // if i'th bit is set k1++; else k0++; } // There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, ans = ans + (1 << i) * (k1 * (k1 - 1) / 2) + (1 << i) * (k1 * k0); } return ans; } // Driver program to test above function public static void main(String args[]) { int arr[] = { 1, 2, 3, 4 }; int n = arr.length; System.out.println(pairORSum(arr, n)); }}
# An efficient Python 3 program to# compute the sum of bitwise OR of all pairs # Returns value of "arr[0] | arr[1] + arr[0] | arr[2] +# ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]" def pairORSum(arr, n) : # Initialize result ans = 0 # Traverse over all bits for i in range(0, 32) : # Count number of elements with the i'th bit set(ie., 1) k1 = 0 # Count number of elements with i’th bit not-set(ie., 0) ` k0 = 0 for j in range(0, n) : if( (arr[j] & (1<<i)) ): # if i'th bit is set k1 = k1 + 1 else : k0 = k0 + 1 # There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 # There are k0 not-set bits and k1 set bits so total pairs will be k1 * k0. # Every pair adds 2 ^ i to the answer. Therefore, ans = ans + (1<<i) * (k1*(k1-1)//2) + (1<<i) * (k1 * k0) return ans # Driver program to test above functionarr = [1, 2, 3, 4]n = len(arr)print(pairORSum(arr, n))
// An efficient C# program to compute// sum of bitwise OR of all pairsusing System; class GFG { // Returns value of "arr[0] | arr[1] + arr[0] | arr[2] + // ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]" static int pairORSum(int[] arr, int n) { int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with the ith bit set(ie., 1) int k1 = 0; // Initialize the count // Count number of elements with ith bit not-set(ie., 0) ` int k0 = 0; // Initialize the count for (int j = 0; j < n; j++) { // if i'th bit is set if ((arr[j] & (1 << i)) != 0) k1++; else k0++; } // There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, ans = ans + (1 << i) * (k1 * (k1 - 1) / 2) + (1 << i) * (k1 * k0); } return ans; } // Driver program to test above function public static void Main() { int[] arr = new int[] { 1, 2, 3, 4 }; int n = arr.Length; Console.Write(pairORSum(arr, n)); }}
<?php// An efficient PHP program to compute// sum of bitwise OR of all pairs // Returns value of "arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]" function pairORSum($arr, $n){ $ans = 0; // Initialize result // Traverse over all bits for ( $i = 0; $i < 32; $i++){ // Count number of elements with the ith bit set(ie., 1) $k1 = 0; // Initialize the count // Count number of elements with ith bit not-set(ie., 0) ` $k0 = 0; // Initialize the count for ( $j = 0; $j < $n; $j++){ if ( ($arr[$j] & (1 << $i))) // if i'th bit is set $k1++; else $k0++; } // There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, $ans = $ans + (1<<$i) * ($k1*($k1-1)/2) + (1<<$i) * ($k1*$k0) ; } return $ans; } // Driver Code $arr = array(1, 2, 3, 4); $n = sizeof($arr); echo pairORSum($arr, $n) ; ?>
<script> // An efficient Javascript program// to compute sum of bitwise OR// of all pairs // Returns value of "arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]" function pairORSum( arr, n){ var ans = 0; // Initialize result // Traverse over all bits for (var i = 0; i < 32; i++) { // Count number of elements // with the i'th bit set(ie., 1) var k1 = 0; // Initialize the count // Count number of elements with // i’th bit not-set(ie., 0) ` var k0 = 0; // Initialize the count for (var j = 0; j < n; j++) { if ((arr[j] & (1 << i))) // if i'th bit is set k1++; else k0++; } // There are k1 set bits, // means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and // k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, ans = ans + (1 << i) * (k1 * (k1 - 1) / 2) + (1 << i) * (k1 * k0); } return ans;} // Driver program to test the above functionvar arr = [1, 2, 3, 4];var n = arr.length;document.write( pairORSum(arr, n)); </script>
Output:
27
Time Complexity: O(n * 32)
Auxiliary Space: O(1)
itsok
rrrtnx
subhammahato348
Bitwise-OR
Arrays
Bit Magic
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "Given an array “arr[0..n-1]” of integers. The task is to calculate the sum of Bitwise OR of all pairs, i.e. calculate the sum of “arr[i] | arr[j]” for all the pairs in the given array where i < j. Here ‘|’ is a bitwise OR operator. Expected time complexity is O(n).Examples : "
},
{
"code": null,
"e": 656,
"s": 306,
"text": "Input: arr[] = {5, 10, 15}\nOutput: 15\nRequired Value = (5 | 10) + (5 | 15) + (10 | 15) \n = 15 + 15 + 15 \n = 45\n\nInput: arr[] = {1, 2, 3, 4}\nOutput: 3\nRequired Value = (1 | 2) + (1 | 3) + (1 | 4) + \n (2 | 3) + (2 | 4) + (3 | 4) \n = 3 + 3 + 5 + 3 + 6 + 7\n = 27"
},
{
"code": null,
"e": 733,
"s": 658,
"text": "A Brute Force approach is to run two loops and time complexity is O(n2). "
},
{
"code": null,
"e": 737,
"s": 733,
"text": "C++"
},
{
"code": null,
"e": 742,
"s": 737,
"text": "Java"
},
{
"code": null,
"e": 750,
"s": 742,
"text": "Python3"
},
{
"code": null,
"e": 753,
"s": 750,
"text": "C#"
},
{
"code": null,
"e": 757,
"s": 753,
"text": "PHP"
},
{
"code": null,
"e": 768,
"s": 757,
"text": "Javascript"
},
{
"code": "// A Simple C++ program to compute sum of bitwise OR// of all pairs#include <bits/stdc++.h>using namespace std; // Returns value of \"arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]\"int pairORSum(int arr[], int n){ int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) such that // i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] | arr[j]; return ans;} // Driver program to test above functionint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << pairORSum(arr, n) << endl; return 0;}",
"e": 1421,
"s": 768,
"text": null
},
{
"code": "// A Simple Java program to compute// sum of bitwise OR of all pairsimport java.io.*; class GFG { // Returns value of \"arr[0] | arr[1] + // arr[0] | arr[2] + ... arr[i] | arr[j] + // ..... arr[n-2] | arr[n-1]\" static int pairORSum(int arr[], int n) { int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] | arr[j]; return ans; } // Driver program to test above function public static void main(String args[]) { int arr[] = { 1, 2, 3, 4 }; int n = arr.length; System.out.println(pairORSum(arr, n)); }}",
"e": 2149,
"s": 1421,
"text": null
},
{
"code": "# A Simple Python 3 program to compute# sum of bitwise OR of all pairs # Returns value of \"arr[0] | arr[1] +# arr[0] | arr[2] + ... arr[i] | arr[j] +# ..... arr[n-2] | arr[n-1]\"def pairORSum(arr, n) : ans = 0 # Initialize result # Consider all pairs (arr[i], arr[j) # such that i < j for i in range(0, n) : for j in range((i + 1), n) : ans = ans + arr[i] | arr[j] return ans # Driver program to test above functionarr = [1, 2, 3, 4]n = len(arr)print(pairORSum(arr, n))",
"e": 2653,
"s": 2149,
"text": null
},
{
"code": "// A Simple C# program to compute// sum of bitwise OR of all pairsusing System; class GFG { // Returns value of \"arr[0] | arr[1] + // arr[0] | arr[2] + ... arr[i] | arr[j] + // ..... arr[n-2] | arr[n-1]\" static int pairORSum(int[] arr, int n) { int ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) // such that i < j for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) ans += arr[i] | arr[j]; return ans; } // Driver program to test above function public static void Main() { int[] arr = { 1, 2, 3, 4 }; int n = arr.Length; Console.Write(pairORSum(arr, n)); }}",
"e": 3358,
"s": 2653,
"text": null
},
{
"code": "<?php// A Simple PHP program to// compute sum of bitwise// OR of all pairs // Returns value of \"arr[0] |// arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + .....// arr[n-2] | arr[n-1]\" function pairORSum($arr, $n){ // Initialize result $ans = 0; // Consider all pairs (arr[i], // arr[j) such that i < j for ($i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) $ans += $arr[$i] | $arr[$j]; return $ans;} // Driver Code$arr = array(1, 2, 3, 4);$n = sizeof($arr) ;echo pairORSum($arr, $n), \"\\n\"; ?>",
"e": 3895,
"s": 3358,
"text": null
},
{
"code": "<script> // A Simple Javascript program to compute sum of bitwise OR// of all pairs // Returns value of \"arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]\"function pairORSum(arr, n){ var ans = 0; // Initialize result // Consider all pairs (arr[i], arr[j) such that // i < j for (var i = 0; i < n; i++) for (var j = i + 1; j < n; j++) ans += arr[i] | arr[j]; return ans;} // Driver program to test above functionvar arr = [1, 2, 3, 4];var n = arr.length;document.write( pairORSum(arr, n)); </script>",
"e": 4467,
"s": 3895,
"text": null
},
{
"code": null,
"e": 4477,
"s": 4467,
"text": "Output: "
},
{
"code": null,
"e": 4480,
"s": 4477,
"text": "27"
},
{
"code": null,
"e": 4503,
"s": 4480,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 4525,
"s": 4503,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5553,
"s": 4525,
"text": "An Efficient Solution can solve this problem in O(n) time. The assumption here is that integers are represented using 32 bits.The idea is to count number of set bits at every i’th position (i>=0 && i<=31). Any i’th bit of the AND of two numbers is 1 iff the corresponding bit in both the numbers is equal to 1. Let k1 be the count of set bits at i’th position. Total number of pairs with i’th set bit would be k1C2 = k1*(k1-1)/2 (Count k1 means there are k1 numbers that have i’th set bit). Every such pair adds 2i to total sum. Similarly, there are total k0 values that don’t have set bits at i’th position. Now each element (which have not set the bit at the i’th position can make pair with k1 elements (ie., those elements which have set bits at the i’th position), So there are total k1 * k0 pairs and every such pair also adds 2i to total sum.sum = sum + (1<<i) * (k1*(k1-1)/2) + (1<<i) * (k1*k0) This idea is similar to finding sum of bit differences among all pairs. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5557,
"s": 5553,
"text": "C++"
},
{
"code": null,
"e": 5562,
"s": 5557,
"text": "Java"
},
{
"code": null,
"e": 5570,
"s": 5562,
"text": "Python3"
},
{
"code": null,
"e": 5573,
"s": 5570,
"text": "C#"
},
{
"code": null,
"e": 5577,
"s": 5573,
"text": "PHP"
},
{
"code": null,
"e": 5588,
"s": 5577,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to compute sum of bitwise OR// of all pairs#include <bits/stdc++.h>using namespace std;typedef long long int LLI; // Returns value of \"arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]\" LLI pairORSum(LLI arr[], LLI n){ LLI ans = 0; // Initialize result // Traverse over all bits for (LLI i = 0; i < 32; i++) { // Count number of elements with the i'th bit set(ie., 1) LLI k1 = 0; // Initialize the count // Count number of elements with i’th bit not-set(ie., 0) ` LLI k0 = 0; // Initialize the count for (LLI j = 0; j < n; j++) { if ((arr[j] & (1 << i))) // if i'th bit is set k1++; else k0++; } // There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, ans = ans + (1 << i) * (k1 * (k1 - 1) / 2) + (1 << i) * (k1 * k0); } return ans;} // Driver program to test the above function int main() { LLI arr[] = { 1, 2, 3, 4 }; LLI n = sizeof(arr) / sizeof(arr[0]); cout << pairORSum(arr, n) << endl; return 0;}",
"e": 6839,
"s": 5588,
"text": null
},
{
"code": "// An efficient Java program to compute// sum of bitwise OR of all pairsimport java.io.*; class GFG { // Returns value of \"arr[0] | arr[1] + arr[0] | arr[2] + // ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]\" static int pairORSum(int arr[], int n) { int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with the ith bit set(ie., 1) int k1 = 0; // Initialize the count // Count number of elements with ith bit not-set(ie., 0) ` int k0 = 0; // Initialize the count for (int j = 0; j < n; j++) { if ((arr[j] & (1 << i)) != 0) // if i'th bit is set k1++; else k0++; } // There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, ans = ans + (1 << i) * (k1 * (k1 - 1) / 2) + (1 << i) * (k1 * k0); } return ans; } // Driver program to test above function public static void main(String args[]) { int arr[] = { 1, 2, 3, 4 }; int n = arr.length; System.out.println(pairORSum(arr, n)); }}",
"e": 8173,
"s": 6839,
"text": null
},
{
"code": "# An efficient Python 3 program to# compute the sum of bitwise OR of all pairs # Returns value of \"arr[0] | arr[1] + arr[0] | arr[2] +# ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]\" def pairORSum(arr, n) : # Initialize result ans = 0 # Traverse over all bits for i in range(0, 32) : # Count number of elements with the i'th bit set(ie., 1) k1 = 0 # Count number of elements with i’th bit not-set(ie., 0) ` k0 = 0 for j in range(0, n) : if( (arr[j] & (1<<i)) ): # if i'th bit is set k1 = k1 + 1 else : k0 = k0 + 1 # There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 # There are k0 not-set bits and k1 set bits so total pairs will be k1 * k0. # Every pair adds 2 ^ i to the answer. Therefore, ans = ans + (1<<i) * (k1*(k1-1)//2) + (1<<i) * (k1 * k0) return ans # Driver program to test above functionarr = [1, 2, 3, 4]n = len(arr)print(pairORSum(arr, n))",
"e": 9230,
"s": 8173,
"text": null
},
{
"code": "// An efficient C# program to compute// sum of bitwise OR of all pairsusing System; class GFG { // Returns value of \"arr[0] | arr[1] + arr[0] | arr[2] + // ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]\" static int pairORSum(int[] arr, int n) { int ans = 0; // Initialize result // Traverse over all bits for (int i = 0; i < 32; i++) { // Count number of elements with the ith bit set(ie., 1) int k1 = 0; // Initialize the count // Count number of elements with ith bit not-set(ie., 0) ` int k0 = 0; // Initialize the count for (int j = 0; j < n; j++) { // if i'th bit is set if ((arr[j] & (1 << i)) != 0) k1++; else k0++; } // There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, ans = ans + (1 << i) * (k1 * (k1 - 1) / 2) + (1 << i) * (k1 * k0); } return ans; } // Driver program to test above function public static void Main() { int[] arr = new int[] { 1, 2, 3, 4 }; int n = arr.Length; Console.Write(pairORSum(arr, n)); }}",
"e": 10565,
"s": 9230,
"text": null
},
{
"code": "<?php// An efficient PHP program to compute// sum of bitwise OR of all pairs // Returns value of \"arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]\" function pairORSum($arr, $n){ $ans = 0; // Initialize result // Traverse over all bits for ( $i = 0; $i < 32; $i++){ // Count number of elements with the ith bit set(ie., 1) $k1 = 0; // Initialize the count // Count number of elements with ith bit not-set(ie., 0) ` $k0 = 0; // Initialize the count for ( $j = 0; $j < $n; $j++){ if ( ($arr[$j] & (1 << $i))) // if i'th bit is set $k1++; else $k0++; } // There are k1 set bits, means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, $ans = $ans + (1<<$i) * ($k1*($k1-1)/2) + (1<<$i) * ($k1*$k0) ; } return $ans; } // Driver Code $arr = array(1, 2, 3, 4); $n = sizeof($arr); echo pairORSum($arr, $n) ; ?>",
"e": 11635,
"s": 10565,
"text": null
},
{
"code": "<script> // An efficient Javascript program// to compute sum of bitwise OR// of all pairs // Returns value of \"arr[0] | arr[1] + arr[0] | arr[2] +// ... arr[i] | arr[j] + ..... arr[n-2] | arr[n-1]\" function pairORSum( arr, n){ var ans = 0; // Initialize result // Traverse over all bits for (var i = 0; i < 32; i++) { // Count number of elements // with the i'th bit set(ie., 1) var k1 = 0; // Initialize the count // Count number of elements with // i’th bit not-set(ie., 0) ` var k0 = 0; // Initialize the count for (var j = 0; j < n; j++) { if ((arr[j] & (1 << i))) // if i'th bit is set k1++; else k0++; } // There are k1 set bits, // means k1(k1-1)/2 pairs. k1C2 // There are k0 not-set bits and // k1 set bits so total pairs will be k1*k0. // Every pair adds 2^i to the answer. Therefore, ans = ans + (1 << i) * (k1 * (k1 - 1) / 2) + (1 << i) * (k1 * k0); } return ans;} // Driver program to test the above functionvar arr = [1, 2, 3, 4];var n = arr.length;document.write( pairORSum(arr, n)); </script>",
"e": 12824,
"s": 11635,
"text": null
},
{
"code": null,
"e": 12834,
"s": 12824,
"text": "Output: "
},
{
"code": null,
"e": 12837,
"s": 12834,
"text": "27"
},
{
"code": null,
"e": 12865,
"s": 12837,
"text": " Time Complexity: O(n * 32)"
},
{
"code": null,
"e": 12887,
"s": 12865,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12893,
"s": 12887,
"text": "itsok"
},
{
"code": null,
"e": 12900,
"s": 12893,
"text": "rrrtnx"
},
{
"code": null,
"e": 12916,
"s": 12900,
"text": "subhammahato348"
},
{
"code": null,
"e": 12927,
"s": 12916,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 12934,
"s": 12927,
"text": "Arrays"
},
{
"code": null,
"e": 12944,
"s": 12934,
"text": "Bit Magic"
},
{
"code": null,
"e": 12951,
"s": 12944,
"text": "Arrays"
},
{
"code": null,
"e": 12961,
"s": 12951,
"text": "Bit Magic"
},
{
"code": null,
"e": 13059,
"s": 12961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13091,
"s": 13059,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 13116,
"s": 13091,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 13163,
"s": 13116,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 13227,
"s": 13163,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 13258,
"s": 13227,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 13285,
"s": 13258,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 13331,
"s": 13285,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 13399,
"s": 13331,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 13428,
"s": 13399,
"text": "Count set bits in an integer"
}
] |
Basics of OHLC charts with Python’s Matplotlib | by Thiago Carvalho | Towards Data Science | With a history going back to the 18th century, Open-High-Low-Close (OHLC) charts are among the most popular financial analysis tools, typically used to illustrate stock prices over time.
In this article, we’ll see how to build an OHLC chart with Matplotlib from scratch, explore the advantages and limitations of this visualization, and get a look at a more straightforward approach with mplfinance.
The chart is composed of a series of vertical lines that pack four critical variables about the price; The minimum, maximum, initial, and ending values over time, commonly measured in hours, days, or weeks.
OHLC is very similar to Candlestick charts as they both display the same information and are used to illustrate the price over time. Usually of a stock, currency, bond, commodity, and others.
They slightly differ in how they display the data; OHLC open price is always on the stick's left side and the close price on the right.
Candlesticks don’t have markers on the left or right. They have a box.
The box's filling represents the price's direction. Usually, a filled or red box means the price went down (Bearish market), so the open price is the rectangle's top part.
An empty or green box means the opposite (Bullish market), and the top part of the box is the closing price.
Let’s start building our OHLC chart. First, we’ll import the required libraries.
import pandas as pdimport matplotlib.pyplot as pltimport numpy as npimport math
The data in this example comes from a Kaggle dataset titled S&P 500 stock data.
df = pd.read_csv('../data/all_stocks_5yr.csv')df.head()
It’s an extensive dataset, and we won’t be plotting all this data at once, so before we start, let’s select a smaller subset.
# filter Apple stocksdf_apple = df[df['Name'] == 'AAPL'].copy()# convert date column from string to datedf_apple['date'] = pd.to_datetime(df_apple['date']) # filter records after 2017df_apple = df_apple[df_apple['date'].dt.year > 2017] df_apple.reset_index(inplace=True)
Now let’s plot the sticks. They should extend from the lowest to the highest price.
Instead of using the date as our x, we’ll create a NumPy array for it. That array will go from 0 to the length of our data frame. It’s easier to manipulate a numerical sequence, which will help position the sticks and the markers for open/close prices.
To draw the lines, we’ll iterate through our data frame, plotting a line for each record of data.
x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): plt.plot([x[idx], x[idx]], [val['low'], val['high']])plt.show()
Awesome, now we can add the markers.
x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): # high/low lines plt.plot([x[idx], x[idx]], [val['low'], val['high']], color='black') # open marker plt.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color='black') # close marker plt.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color='black')plt.show()
There it is! It’s pretty easy to plot an OHLC chart with Matplotlib. Unlike candlesticks, you don’t need color or different fillings in the symbols to understand the visualization.
In its simplest form, this chart is readable and relatively straightforward.
They are not necessary but can take our visualization to another level.
We’ll add a variable with green color at the beginning of the loop; then we’ll add a condition to check if the open price was higher than the closing price; when true, we’ll change the color to red.
x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): color = '#2CA453' if val['open'] > val['close']: color= '#F04730' plt.plot([x[idx], x[idx]], [val['low'], val['high']], color=color) plt.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color=color) plt.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color)plt.show()
Adding color to our OHLC charts makes the past trends way more visible and our visualization more insightful.
Our visualization already looks great, but the x-axis is useless as it is.
Using a numerical sequence as our x helped drawing the lines and markers, but we can’t tell the dates like this.
We’ll use x to position our ticks and the dates as the labels. We also need to consider that if we print every date, our x-axis will be unreadable, so we’ll skip some values when plotting.
x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): color = '#2CA453' if val['open'] > val['close']: color= '#F04730' plt.plot([x[idx], x[idx]], [val['low'], val['high']], color=color) plt.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color=color) plt.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color) # ticksplt.xticks(x[::3], df_apple.date.dt.date[::3])plt.show()
That’s great! Now we can add some styling to our visualization to make it more appealing.
x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): color = '#2CA453' if val['open'] > val['close']: color= '#F04730' plt.plot([x[idx], x[idx]], [val['low'], val['high']], color=color) plt.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color=color) plt.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color) # ticksplt.xticks(x[::3], df_apple.date.dt.date[::3])ax.set_xticks(x, minor=True)# labelsplt.ylabel('USD')# gridax.xaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)# remove spinesax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)# titleplt.title('Apple Stock Price', loc='left', fontsize=20)plt.show()
OHLC charts are a great starting point for analysis since they give us a decent overview on which we can build upon.
You can plot some predicted prices, confidence intervals, moving averages, trades volume, and many more variables and statistics to complement your visualization.
Building our visualization from scratch with Matplotlib gives us a lot of freedom.
x = np.arange(0,len(df_apple))fig, (ax, ax2) = plt.subplots(2, figsize=(12,8), gridspec_kw={'height_ratios': [4, 1]})for idx, val in df_apple.iterrows(): color = '#2CA453' if val['open'] > val['close']: color= '#F04730' ax.plot([x[idx], x[idx]], [val['low'], val['high']], color=color) ax.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color=color) ax.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color) # ticks top plotax2.set_xticks(x[::3])ax2.set_xticklabels(df_apple.date.dt.date[::3])ax.set_xticks(x, minor=True)# labelsax.set_ylabel('USD')ax2.set_ylabel('Volume')# gridax.xaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)ax2.set_axisbelow(True)ax2.yaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)# remove spinesax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['top'].set_visible(False)ax2.spines['right'].set_visible(False)ax2.spines['left'].set_visible(False)# plot volumeax2.bar(x, df_apple['volume'], color='lightgrey')# get max volume + 10%mx = df_apple['volume'].max()*1.1# define tick locations - 0 to max in 4 stepsyticks_ax2 = np.arange(0, mx+1, mx/4)# create labels for ticks. Replace 1.000.000 by 'mi'yticks_labels_ax2 = ['{:.2f} mi'.format(i/1000000) for i in yticks_ax2]ax2.yaxis.tick_right() # Move ticks to the left side# plot y ticks / skip first and last values (0 and max)plt.yticks(yticks_ax2[1:-1], yticks_labels_ax2[1:-1])plt.ylim(0,mx) # titleax.set_title('Apple Stock Price\n', loc='left', fontsize=20)# no spacing between the subplotsplt.subplots_adjust(wspace=0, hspace=0)plt.show()
At the beginning of the article, I mentioned an easier way to plot OHLC charts. mplfinance is an excellent pack of utilities for financial visualizations.
pip install --upgrade mplfinance
Let’s take a look at how easy it is to use it.
The data frame should contain the fields: Open, Close, High, Low, and Volume. It also should have a DateTime index.
Our data has the proper fields, so we only need to change the index.
import mplfinance as mpfdf_google = df[df['Name'] == 'GOOGL'].copy()df_google['date'] = pd.to_datetime(df_google['date'])df_google = df_google[df_google['date'] > pd.to_datetime('2017-12-31')]df_google = df_google.set_index('date')mpf.plot(df_google)
Just like that, we have our OHLC chart!
We can also add lines for moving average and visualize the volume with a single line of code.
mpf.plot(df_google,type='candle',mav=(3, 5),volume=True, title='Google')
Matplotlib Finance utilities are easier to use than drawing the chart from scratch, but they are not easily customizable.
For most quick analysis, you need a functional and readable chart, and mplfinance will be more than enough.
For other more specific constraints, when you need to add a particular component to your visualization or customize the style to follow some design standards, mplfinance may fall short.
Those are the cases where drawing the chart from scratch with Matplotlib pays off. We can easily add, modify, or remove any part of the visualization, making it a great tool to have under your belt.
Thanks for reading my article. I hope you enjoyed it!
Check out more Python DataViz tutorials.
References:mplfinance;mplfinance — Styles and Customizations;
Matplotlib — Subplots Gridspec; Matplotlib —x-ticks, y-ticks; Matplotlib — Ticks right; Matplotlib — Spines; Matplotlib — Gridlines, W3;Matplotlib — Lines;Matplotlib — Bars; | [
{
"code": null,
"e": 359,
"s": 172,
"text": "With a history going back to the 18th century, Open-High-Low-Close (OHLC) charts are among the most popular financial analysis tools, typically used to illustrate stock prices over time."
},
{
"code": null,
"e": 572,
"s": 359,
"text": "In this article, we’ll see how to build an OHLC chart with Matplotlib from scratch, explore the advantages and limitations of this visualization, and get a look at a more straightforward approach with mplfinance."
},
{
"code": null,
"e": 779,
"s": 572,
"text": "The chart is composed of a series of vertical lines that pack four critical variables about the price; The minimum, maximum, initial, and ending values over time, commonly measured in hours, days, or weeks."
},
{
"code": null,
"e": 971,
"s": 779,
"text": "OHLC is very similar to Candlestick charts as they both display the same information and are used to illustrate the price over time. Usually of a stock, currency, bond, commodity, and others."
},
{
"code": null,
"e": 1107,
"s": 971,
"text": "They slightly differ in how they display the data; OHLC open price is always on the stick's left side and the close price on the right."
},
{
"code": null,
"e": 1178,
"s": 1107,
"text": "Candlesticks don’t have markers on the left or right. They have a box."
},
{
"code": null,
"e": 1350,
"s": 1178,
"text": "The box's filling represents the price's direction. Usually, a filled or red box means the price went down (Bearish market), so the open price is the rectangle's top part."
},
{
"code": null,
"e": 1459,
"s": 1350,
"text": "An empty or green box means the opposite (Bullish market), and the top part of the box is the closing price."
},
{
"code": null,
"e": 1540,
"s": 1459,
"text": "Let’s start building our OHLC chart. First, we’ll import the required libraries."
},
{
"code": null,
"e": 1620,
"s": 1540,
"text": "import pandas as pdimport matplotlib.pyplot as pltimport numpy as npimport math"
},
{
"code": null,
"e": 1700,
"s": 1620,
"text": "The data in this example comes from a Kaggle dataset titled S&P 500 stock data."
},
{
"code": null,
"e": 1756,
"s": 1700,
"text": "df = pd.read_csv('../data/all_stocks_5yr.csv')df.head()"
},
{
"code": null,
"e": 1882,
"s": 1756,
"text": "It’s an extensive dataset, and we won’t be plotting all this data at once, so before we start, let’s select a smaller subset."
},
{
"code": null,
"e": 2153,
"s": 1882,
"text": "# filter Apple stocksdf_apple = df[df['Name'] == 'AAPL'].copy()# convert date column from string to datedf_apple['date'] = pd.to_datetime(df_apple['date']) # filter records after 2017df_apple = df_apple[df_apple['date'].dt.year > 2017] df_apple.reset_index(inplace=True)"
},
{
"code": null,
"e": 2237,
"s": 2153,
"text": "Now let’s plot the sticks. They should extend from the lowest to the highest price."
},
{
"code": null,
"e": 2490,
"s": 2237,
"text": "Instead of using the date as our x, we’ll create a NumPy array for it. That array will go from 0 to the length of our data frame. It’s easier to manipulate a numerical sequence, which will help position the sticks and the markers for open/close prices."
},
{
"code": null,
"e": 2588,
"s": 2490,
"text": "To draw the lines, we’ll iterate through our data frame, plotting a line for each record of data."
},
{
"code": null,
"e": 2763,
"s": 2588,
"text": "x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): plt.plot([x[idx], x[idx]], [val['low'], val['high']])plt.show()"
},
{
"code": null,
"e": 2800,
"s": 2763,
"text": "Awesome, now we can add the markers."
},
{
"code": null,
"e": 3279,
"s": 2800,
"text": "x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): # high/low lines plt.plot([x[idx], x[idx]], [val['low'], val['high']], color='black') # open marker plt.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color='black') # close marker plt.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color='black')plt.show()"
},
{
"code": null,
"e": 3460,
"s": 3279,
"text": "There it is! It’s pretty easy to plot an OHLC chart with Matplotlib. Unlike candlesticks, you don’t need color or different fillings in the symbols to understand the visualization."
},
{
"code": null,
"e": 3537,
"s": 3460,
"text": "In its simplest form, this chart is readable and relatively straightforward."
},
{
"code": null,
"e": 3609,
"s": 3537,
"text": "They are not necessary but can take our visualization to another level."
},
{
"code": null,
"e": 3808,
"s": 3609,
"text": "We’ll add a variable with green color at the beginning of the loop; then we’ll add a condition to check if the open price was higher than the closing price; when true, we’ll change the color to red."
},
{
"code": null,
"e": 4298,
"s": 3808,
"text": "x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): color = '#2CA453' if val['open'] > val['close']: color= '#F04730' plt.plot([x[idx], x[idx]], [val['low'], val['high']], color=color) plt.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color=color) plt.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color)plt.show()"
},
{
"code": null,
"e": 4408,
"s": 4298,
"text": "Adding color to our OHLC charts makes the past trends way more visible and our visualization more insightful."
},
{
"code": null,
"e": 4483,
"s": 4408,
"text": "Our visualization already looks great, but the x-axis is useless as it is."
},
{
"code": null,
"e": 4596,
"s": 4483,
"text": "Using a numerical sequence as our x helped drawing the lines and markers, but we can’t tell the dates like this."
},
{
"code": null,
"e": 4785,
"s": 4596,
"text": "We’ll use x to position our ticks and the dates as the labels. We also need to consider that if we print every date, our x-axis will be unreadable, so we’ll skip some values when plotting."
},
{
"code": null,
"e": 5332,
"s": 4785,
"text": "x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): color = '#2CA453' if val['open'] > val['close']: color= '#F04730' plt.plot([x[idx], x[idx]], [val['low'], val['high']], color=color) plt.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color=color) plt.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color) # ticksplt.xticks(x[::3], df_apple.date.dt.date[::3])plt.show()"
},
{
"code": null,
"e": 5422,
"s": 5332,
"text": "That’s great! Now we can add some styling to our visualization to make it more appealing."
},
{
"code": null,
"e": 6172,
"s": 5422,
"text": "x = np.arange(0,len(df_apple))fig, ax = plt.subplots(1, figsize=(12,6))for idx, val in df_apple.iterrows(): color = '#2CA453' if val['open'] > val['close']: color= '#F04730' plt.plot([x[idx], x[idx]], [val['low'], val['high']], color=color) plt.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color=color) plt.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color) # ticksplt.xticks(x[::3], df_apple.date.dt.date[::3])ax.set_xticks(x, minor=True)# labelsplt.ylabel('USD')# gridax.xaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)# remove spinesax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)# titleplt.title('Apple Stock Price', loc='left', fontsize=20)plt.show()"
},
{
"code": null,
"e": 6289,
"s": 6172,
"text": "OHLC charts are a great starting point for analysis since they give us a decent overview on which we can build upon."
},
{
"code": null,
"e": 6452,
"s": 6289,
"text": "You can plot some predicted prices, confidence intervals, moving averages, trades volume, and many more variables and statistics to complement your visualization."
},
{
"code": null,
"e": 6535,
"s": 6452,
"text": "Building our visualization from scratch with Matplotlib gives us a lot of freedom."
},
{
"code": null,
"e": 8169,
"s": 6535,
"text": "x = np.arange(0,len(df_apple))fig, (ax, ax2) = plt.subplots(2, figsize=(12,8), gridspec_kw={'height_ratios': [4, 1]})for idx, val in df_apple.iterrows(): color = '#2CA453' if val['open'] > val['close']: color= '#F04730' ax.plot([x[idx], x[idx]], [val['low'], val['high']], color=color) ax.plot([x[idx], x[idx]-0.1], [val['open'], val['open']], color=color) ax.plot([x[idx], x[idx]+0.1], [val['close'], val['close']], color=color) # ticks top plotax2.set_xticks(x[::3])ax2.set_xticklabels(df_apple.date.dt.date[::3])ax.set_xticks(x, minor=True)# labelsax.set_ylabel('USD')ax2.set_ylabel('Volume')# gridax.xaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)ax2.set_axisbelow(True)ax2.yaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)# remove spinesax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['top'].set_visible(False)ax2.spines['right'].set_visible(False)ax2.spines['left'].set_visible(False)# plot volumeax2.bar(x, df_apple['volume'], color='lightgrey')# get max volume + 10%mx = df_apple['volume'].max()*1.1# define tick locations - 0 to max in 4 stepsyticks_ax2 = np.arange(0, mx+1, mx/4)# create labels for ticks. Replace 1.000.000 by 'mi'yticks_labels_ax2 = ['{:.2f} mi'.format(i/1000000) for i in yticks_ax2]ax2.yaxis.tick_right() # Move ticks to the left side# plot y ticks / skip first and last values (0 and max)plt.yticks(yticks_ax2[1:-1], yticks_labels_ax2[1:-1])plt.ylim(0,mx) # titleax.set_title('Apple Stock Price\\n', loc='left', fontsize=20)# no spacing between the subplotsplt.subplots_adjust(wspace=0, hspace=0)plt.show()"
},
{
"code": null,
"e": 8324,
"s": 8169,
"text": "At the beginning of the article, I mentioned an easier way to plot OHLC charts. mplfinance is an excellent pack of utilities for financial visualizations."
},
{
"code": null,
"e": 8357,
"s": 8324,
"text": "pip install --upgrade mplfinance"
},
{
"code": null,
"e": 8404,
"s": 8357,
"text": "Let’s take a look at how easy it is to use it."
},
{
"code": null,
"e": 8520,
"s": 8404,
"text": "The data frame should contain the fields: Open, Close, High, Low, and Volume. It also should have a DateTime index."
},
{
"code": null,
"e": 8589,
"s": 8520,
"text": "Our data has the proper fields, so we only need to change the index."
},
{
"code": null,
"e": 8840,
"s": 8589,
"text": "import mplfinance as mpfdf_google = df[df['Name'] == 'GOOGL'].copy()df_google['date'] = pd.to_datetime(df_google['date'])df_google = df_google[df_google['date'] > pd.to_datetime('2017-12-31')]df_google = df_google.set_index('date')mpf.plot(df_google)"
},
{
"code": null,
"e": 8880,
"s": 8840,
"text": "Just like that, we have our OHLC chart!"
},
{
"code": null,
"e": 8974,
"s": 8880,
"text": "We can also add lines for moving average and visualize the volume with a single line of code."
},
{
"code": null,
"e": 9047,
"s": 8974,
"text": "mpf.plot(df_google,type='candle',mav=(3, 5),volume=True, title='Google')"
},
{
"code": null,
"e": 9169,
"s": 9047,
"text": "Matplotlib Finance utilities are easier to use than drawing the chart from scratch, but they are not easily customizable."
},
{
"code": null,
"e": 9277,
"s": 9169,
"text": "For most quick analysis, you need a functional and readable chart, and mplfinance will be more than enough."
},
{
"code": null,
"e": 9463,
"s": 9277,
"text": "For other more specific constraints, when you need to add a particular component to your visualization or customize the style to follow some design standards, mplfinance may fall short."
},
{
"code": null,
"e": 9662,
"s": 9463,
"text": "Those are the cases where drawing the chart from scratch with Matplotlib pays off. We can easily add, modify, or remove any part of the visualization, making it a great tool to have under your belt."
},
{
"code": null,
"e": 9716,
"s": 9662,
"text": "Thanks for reading my article. I hope you enjoyed it!"
},
{
"code": null,
"e": 9757,
"s": 9716,
"text": "Check out more Python DataViz tutorials."
},
{
"code": null,
"e": 9819,
"s": 9757,
"text": "References:mplfinance;mplfinance — Styles and Customizations;"
}
] |
Switch-Case Statements in Python 3.10 | Towards Data Science | Python 3.10 is beginning to fill-out with plenty of fascinating new features. One of those, in particular, caught my attention — structural pattern matching — or as most of us will know it, switch/case statements.
Switch-statements have been absent from Python despite being a common feature of most languages.
Back in 2006, PEP 3103 was raised, recommending the implementation of a switch-case statement. However, after a poll at PyCon 2007 received no support for the feature, the Python devs dropped it.
Fast-forward to 2020, and Guido van Rossum, the creator of Python, committed the first documentation showing the new switch-statements, which have been named Structural Pattern Matching, as found in PEP 634.
What we have here is much more than a simple switch-case statement, however (hence match-case), as we will see soon.
Let’s take a look at how this new logic works.
> Structural Pattern Matching - Intro - Another Example - Real Use-Case With JSON
The pattern matching takes a value following match and allows us to write out several potential cases, each defined by case. Where we find a match between the match-case we will execute the respective code.
For example:
http_code = "418"match http_code: case "200": print("OK") do_something_good() case "404": print("Not Found") do_something_bad() case "418": print("I'm a teapot") make_coffee() case _: print("Code not found")
Here we’re checking multiple conditions and performing different operations based on what value we’re finding inside http_code.
Immediately it’s evident that yes, we can build the same logic using a chunk of if-elif-else statements:
http_code = "418"if http_code == "418": print("OK") do_something_good()elif http_code == "404": print("Not Found") do_something_bad()elif http_code == "418" print("I'm a teapot") make_coffee()else: print("Code not found")
However, by using the match-case statement we remove the repetition of http_code ==Which can look much cleaner when testing for many different conditions.
We can find some great examples of using the match-case statement to improve code readability in PEP 635. One of those is this example showing us how to use match-case to check the type and structure of our subject:
match x: case host, port: mode = "http" case host, port, mode: pass
Here we expect to receive connection details in a tuple format and assign the given values to the correct variables.
In this case, if the connection mode is not defined within the tuple (e.g., only two values have been provided — the host and port), we assume that the connection mode is “http”.
However, in other cases, we may expect that the mode is explicitly defined. So rather we might receive a tuple like (<host>, <port>, "ftp") — in which case we would not want to set mode to “http”.
Now, if we wanted to write this same logic using an if-else statement, we would get this:
if isinstance(x, tuple) and len(x) == 2: host, port = x mode = "http"elif isinstance(x, tuple) and len(x) == 3: host, port, mode = x
Which option is preferred may vary, but for me, the match-case implementation looks much cleaner.
Another use-case that looks interesting is the ability to parse dictionary objects differently based on their structure. A great test use-case of this is parsing the SQuAD 2 dataset.
The SQuAD 2 dataset is an incredibly popular set of question-answer pairs used for training machine-learning models for question-answering. We can download the data with:
import requests
import json
url = 'https://rajpurkar.github.io/SQuAD-explorer/dataset/'
file = 'train-v2.0.json'
res = requests.get(f'{url}{file}')
# write to file
with open(file, 'wb') as f:
for chunk in res.iter_content(chunk_size=4):
f.write(chunk)
If we take a look at the structure of SQuAD, there are clearly a few levels to it, which we’ll need to consider when parsing:
The problem that we have is that not all samples use the same dictionary format.
If we look at the last few samples we will see that the qas list contains both answers and plausible_answers — whereas the earlier samples contained just answers:
Let’s try applying the new match-case statements to build a cleaner alternative to the heavy if-else logic required to deal with this. First, we load the data:
The SQuAD JSON contains multiple layers. After accessing squad['data'] we need to iterate through each group of questions, then through each paragraph, then through each qas (question-answers) — this looks like:
And this is where things get interesting. Using if-else logic, we get something like this:
new_squad = []
for group in squad['data']:
for paragraph in group['paragraphs']:
for qa in paragraph['qas']:
question = qa['question']
if 'answers' in qa.keys() and len(qa['answers']) > 0:
answers = qa['answers'][0]['text']
elif 'plausible_answers' in qa.keys() and len(qa['plausible_answers']) > 0:
answers = qa['plausible_answers'][0]['text']
else:
answers = None
new_squad.append((question, answers))
new_squad[:5], new_squad[-5:]
([('When did Beyonce start becoming popular?', 'in the late 1990s'),
('What areas did Beyonce compete in when she was growing up?',
'singing and dancing'),
("When did Beyonce leave Destiny's Child and become a solo singer?", '2003'),
('In what city and state did Beyonce grow up? ', 'Houston, Texas'),
('In which decade did Beyonce become famous?', 'late 1990s')],
[('Physics has broadly agreed on the definition of what?', 'matter'),
('Who coined the term partonic matter?', 'Alfvén'),
('What is another name for anti-matter?', 'Gk. common matter'),
('Matter usually does not need to be used in conjunction with what?',
'a specifying modifier'),
('What field of study has a variety of unusual contexts?', 'physics')])
It’s not beautiful, but it works. Now let’s rewrite this with some match-case logic:
It definitely looks a lot less busy and is a pretty cool alternative to the original version of the parsing logic.
That’s all for this quick look at the new structural pattern matching being introduced to Python 3.10! The full release is expected in early October 2021.
Personally, I think this new syntax looks really good — although I’m 50/50 on it at the moment. Once more users begin coding with match-case, I’m confident that the community will quickly establish a consensus and best-practices.
But for now, it looks cool — I’m excited!
I hope you’ve enjoyed the article. Let me know if you have any questions or suggestions via Twitter or in the comments below! If you’re interested in more content like this, I post on YouTube too.
Thanks for reading!
If you’re interested in reading about a few of the other new features coming with Python 3.10, check out my other article covering a few of the best:
towardsdatascience.com
🤖 70% Discount on the NLP With Transformers Course | [
{
"code": null,
"e": 386,
"s": 172,
"text": "Python 3.10 is beginning to fill-out with plenty of fascinating new features. One of those, in particular, caught my attention — structural pattern matching — or as most of us will know it, switch/case statements."
},
{
"code": null,
"e": 483,
"s": 386,
"text": "Switch-statements have been absent from Python despite being a common feature of most languages."
},
{
"code": null,
"e": 679,
"s": 483,
"text": "Back in 2006, PEP 3103 was raised, recommending the implementation of a switch-case statement. However, after a poll at PyCon 2007 received no support for the feature, the Python devs dropped it."
},
{
"code": null,
"e": 887,
"s": 679,
"text": "Fast-forward to 2020, and Guido van Rossum, the creator of Python, committed the first documentation showing the new switch-statements, which have been named Structural Pattern Matching, as found in PEP 634."
},
{
"code": null,
"e": 1004,
"s": 887,
"text": "What we have here is much more than a simple switch-case statement, however (hence match-case), as we will see soon."
},
{
"code": null,
"e": 1051,
"s": 1004,
"text": "Let’s take a look at how this new logic works."
},
{
"code": null,
"e": 1136,
"s": 1051,
"text": "> Structural Pattern Matching - Intro - Another Example - Real Use-Case With JSON"
},
{
"code": null,
"e": 1343,
"s": 1136,
"text": "The pattern matching takes a value following match and allows us to write out several potential cases, each defined by case. Where we find a match between the match-case we will execute the respective code."
},
{
"code": null,
"e": 1356,
"s": 1343,
"text": "For example:"
},
{
"code": null,
"e": 1625,
"s": 1356,
"text": "http_code = \"418\"match http_code: case \"200\": print(\"OK\") do_something_good() case \"404\": print(\"Not Found\") do_something_bad() case \"418\": print(\"I'm a teapot\") make_coffee() case _: print(\"Code not found\")"
},
{
"code": null,
"e": 1753,
"s": 1625,
"text": "Here we’re checking multiple conditions and performing different operations based on what value we’re finding inside http_code."
},
{
"code": null,
"e": 1858,
"s": 1753,
"text": "Immediately it’s evident that yes, we can build the same logic using a chunk of if-elif-else statements:"
},
{
"code": null,
"e": 2101,
"s": 1858,
"text": "http_code = \"418\"if http_code == \"418\": print(\"OK\") do_something_good()elif http_code == \"404\": print(\"Not Found\") do_something_bad()elif http_code == \"418\" print(\"I'm a teapot\") make_coffee()else: print(\"Code not found\")"
},
{
"code": null,
"e": 2256,
"s": 2101,
"text": "However, by using the match-case statement we remove the repetition of http_code ==Which can look much cleaner when testing for many different conditions."
},
{
"code": null,
"e": 2472,
"s": 2256,
"text": "We can find some great examples of using the match-case statement to improve code readability in PEP 635. One of those is this example showing us how to use match-case to check the type and structure of our subject:"
},
{
"code": null,
"e": 2560,
"s": 2472,
"text": "match x: case host, port: mode = \"http\" case host, port, mode: pass"
},
{
"code": null,
"e": 2677,
"s": 2560,
"text": "Here we expect to receive connection details in a tuple format and assign the given values to the correct variables."
},
{
"code": null,
"e": 2856,
"s": 2677,
"text": "In this case, if the connection mode is not defined within the tuple (e.g., only two values have been provided — the host and port), we assume that the connection mode is “http”."
},
{
"code": null,
"e": 3053,
"s": 2856,
"text": "However, in other cases, we may expect that the mode is explicitly defined. So rather we might receive a tuple like (<host>, <port>, \"ftp\") — in which case we would not want to set mode to “http”."
},
{
"code": null,
"e": 3143,
"s": 3053,
"text": "Now, if we wanted to write this same logic using an if-else statement, we would get this:"
},
{
"code": null,
"e": 3285,
"s": 3143,
"text": "if isinstance(x, tuple) and len(x) == 2: host, port = x mode = \"http\"elif isinstance(x, tuple) and len(x) == 3: host, port, mode = x"
},
{
"code": null,
"e": 3383,
"s": 3285,
"text": "Which option is preferred may vary, but for me, the match-case implementation looks much cleaner."
},
{
"code": null,
"e": 3566,
"s": 3383,
"text": "Another use-case that looks interesting is the ability to parse dictionary objects differently based on their structure. A great test use-case of this is parsing the SQuAD 2 dataset."
},
{
"code": null,
"e": 3737,
"s": 3566,
"text": "The SQuAD 2 dataset is an incredibly popular set of question-answer pairs used for training machine-learning models for question-answering. We can download the data with:"
},
{
"code": null,
"e": 3766,
"s": 3737,
"text": "import requests\nimport json\n"
},
{
"code": null,
"e": 3852,
"s": 3766,
"text": "url = 'https://rajpurkar.github.io/SQuAD-explorer/dataset/'\nfile = 'train-v2.0.json'\n"
},
{
"code": null,
"e": 4004,
"s": 3852,
"text": "res = requests.get(f'{url}{file}')\n# write to file\nwith open(file, 'wb') as f:\n for chunk in res.iter_content(chunk_size=4):\n f.write(chunk)\n"
},
{
"code": null,
"e": 4130,
"s": 4004,
"text": "If we take a look at the structure of SQuAD, there are clearly a few levels to it, which we’ll need to consider when parsing:"
},
{
"code": null,
"e": 4211,
"s": 4130,
"text": "The problem that we have is that not all samples use the same dictionary format."
},
{
"code": null,
"e": 4374,
"s": 4211,
"text": "If we look at the last few samples we will see that the qas list contains both answers and plausible_answers — whereas the earlier samples contained just answers:"
},
{
"code": null,
"e": 4534,
"s": 4374,
"text": "Let’s try applying the new match-case statements to build a cleaner alternative to the heavy if-else logic required to deal with this. First, we load the data:"
},
{
"code": null,
"e": 4746,
"s": 4534,
"text": "The SQuAD JSON contains multiple layers. After accessing squad['data'] we need to iterate through each group of questions, then through each paragraph, then through each qas (question-answers) — this looks like:"
},
{
"code": null,
"e": 4837,
"s": 4746,
"text": "And this is where things get interesting. Using if-else logic, we get something like this:"
},
{
"code": null,
"e": 5394,
"s": 4837,
"text": "new_squad = []\n\nfor group in squad['data']:\n for paragraph in group['paragraphs']:\n for qa in paragraph['qas']:\n question = qa['question']\n if 'answers' in qa.keys() and len(qa['answers']) > 0:\n answers = qa['answers'][0]['text']\n elif 'plausible_answers' in qa.keys() and len(qa['plausible_answers']) > 0:\n answers = qa['plausible_answers'][0]['text']\n else:\n answers = None\n new_squad.append((question, answers))\n\nnew_squad[:5], new_squad[-5:]\n"
},
{
"code": null,
"e": 6138,
"s": 5394,
"text": "([('When did Beyonce start becoming popular?', 'in the late 1990s'),\n ('What areas did Beyonce compete in when she was growing up?',\n 'singing and dancing'),\n (\"When did Beyonce leave Destiny's Child and become a solo singer?\", '2003'),\n ('In what city and state did Beyonce grow up? ', 'Houston, Texas'),\n ('In which decade did Beyonce become famous?', 'late 1990s')],\n [('Physics has broadly agreed on the definition of what?', 'matter'),\n ('Who coined the term partonic matter?', 'Alfvén'),\n ('What is another name for anti-matter?', 'Gk. common matter'),\n ('Matter usually does not need to be used in conjunction with what?',\n 'a specifying modifier'),\n ('What field of study has a variety of unusual contexts?', 'physics')])"
},
{
"code": null,
"e": 6223,
"s": 6138,
"text": "It’s not beautiful, but it works. Now let’s rewrite this with some match-case logic:"
},
{
"code": null,
"e": 6338,
"s": 6223,
"text": "It definitely looks a lot less busy and is a pretty cool alternative to the original version of the parsing logic."
},
{
"code": null,
"e": 6493,
"s": 6338,
"text": "That’s all for this quick look at the new structural pattern matching being introduced to Python 3.10! The full release is expected in early October 2021."
},
{
"code": null,
"e": 6723,
"s": 6493,
"text": "Personally, I think this new syntax looks really good — although I’m 50/50 on it at the moment. Once more users begin coding with match-case, I’m confident that the community will quickly establish a consensus and best-practices."
},
{
"code": null,
"e": 6765,
"s": 6723,
"text": "But for now, it looks cool — I’m excited!"
},
{
"code": null,
"e": 6962,
"s": 6765,
"text": "I hope you’ve enjoyed the article. Let me know if you have any questions or suggestions via Twitter or in the comments below! If you’re interested in more content like this, I post on YouTube too."
},
{
"code": null,
"e": 6982,
"s": 6962,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 7132,
"s": 6982,
"text": "If you’re interested in reading about a few of the other new features coming with Python 3.10, check out my other article covering a few of the best:"
},
{
"code": null,
"e": 7155,
"s": 7132,
"text": "towardsdatascience.com"
}
] |
How to find a network adapter driver version using PowerShell? | To find the network adapter driver version using PowerShell, we can use the Get-NetAdapter cmdlet. First, let look at how the network adapter driver version looks like from GUI.
Get-NetAdapter will retrieve all the Physical and Virtual network adapters unless specified.
This cmdlet has a property called DriverVersion, DriverDate, and DriverProvider. You can select it.
Get-NetAdapter | Select Name, InterfaceDescription,DriverVersion, DriverDate, DriverProvider
Name : Wi-Fi
InterfaceDescription : Intel(R) Wi-Fi 6 AX201 160MHz
DriverVersion : 21.80.2.1
DriverDate : 2020-02-25
DriverProvider : Intel
Name : VMware Network Adapter VMnet1
InterfaceDescription : VMware Virtual Ethernet Adapter for VMnet1
DriverVersion : 14.0.0.3
DriverDate : 2019-08-08
DriverProvider : VMware, Inc.
Name : VMware Network Adapter VMnet8
InterfaceDescription : VMware Virtual Ethernet Adapter for VMnet8
DriverVersion : 14.0.0.3
DriverDate : 2019-08-08
DriverProvider : VMware, Inc. | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "To find the network adapter driver version using PowerShell, we can use the Get-NetAdapter cmdlet. First, let look at how the network adapter driver version looks like from GUI."
},
{
"code": null,
"e": 1333,
"s": 1240,
"text": "Get-NetAdapter will retrieve all the Physical and Virtual network adapters unless specified."
},
{
"code": null,
"e": 1433,
"s": 1333,
"text": "This cmdlet has a property called DriverVersion, DriverDate, and DriverProvider. You can select it."
},
{
"code": null,
"e": 1526,
"s": 1433,
"text": "Get-NetAdapter | Select Name, InterfaceDescription,DriverVersion, DriverDate, DriverProvider"
},
{
"code": null,
"e": 2191,
"s": 1526,
"text": "Name : Wi-Fi\nInterfaceDescription : Intel(R) Wi-Fi 6 AX201 160MHz\nDriverVersion : 21.80.2.1\nDriverDate : 2020-02-25\nDriverProvider : Intel\nName : VMware Network Adapter VMnet1\nInterfaceDescription : VMware Virtual Ethernet Adapter for VMnet1\nDriverVersion : 14.0.0.3\nDriverDate : 2019-08-08\nDriverProvider : VMware, Inc.\nName : VMware Network Adapter VMnet8\nInterfaceDescription : VMware Virtual Ethernet Adapter for VMnet8\nDriverVersion : 14.0.0.3\nDriverDate : 2019-08-08\nDriverProvider : VMware, Inc."
}
] |
Apex - Environment | In this chapter, we will understand the environment for our Salesforce Apex development. It is assumed that you already have a Salesforce edition set up for doing Apex development.
You can develop the Apex code in either Sandbox or Developer edition of Salesforce. A Sandbox organization is a copy of your organization in which you can write code and test it without taking the risk of data modification or disturbing the normal functionality. As per the standard industrial practice, you have to develop the code in Sandbox and then deploy it to the Production environment.
For this tutorial, we will be using the Developer edition of Salesforce. In the Developer edition, you will not have the option of creating a Sandbox organization. The Sandbox features are available in other editions of Salesforce.
In all the editions, we can use any of the following three tools to develop the code −
Force.com Developer Console
Force.com IDE
Code Editor in the Salesforce User Interface
Note − We will be utilizing the Developer Console throughout our tutorial for code execution as it is simple and user friendly for learning.
The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your Salesforce organization.
Follow these steps to open the Developer Console −
Step 1 − Go to Name → Developer Console
Step 2 − Click on "Developer Console" and a window will appear as in the following screenshot.
Following are a few operations that can be performed using the Developer Console.
Writing and compiling code − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Writing and compiling code − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Debugging − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Debugging − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported.
Testing − You can view debug logs and set checkpoints that aid in debugging.
Testing − You can view debug logs and set checkpoints that aid in debugging.
Checking performance − You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage.
Checking performance − You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage.
SOQL queries − You can inspect debug logs to locate performance bottlenecks.
SOQL queries − You can inspect debug logs to locate performance bottlenecks.
Color coding and autocomplete − The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names.
Color coding and autocomplete − The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names.
All the code snippets mentioned in this tutorial need to be executed in the developer console. Follow these steps to execute steps in Developer Console.
Step 1 − Login to the Salesforce.com using login.salesforce.com. Copy the code snippets mentioned in the tutorial. For now, we will use the following sample code.
String myString = 'MyString';
System.debug('Value of String Variable'+myString);
Step 2 − To open the Developer Console, click on Name → Developer Console and then click on Execute Anonymous as shown below.
Step 3 − In this step, a window will appear and you can paste the code there.
Step 4 − When we click on Execute, the debug logs will open. Once the log appears in window as shown below, then click on the log record.
Then type 'USER' in the window as shown below and the output statement will appear in the debug window. This 'USER' statement is used for filtering the output.
So basically, you will be following all the above mentioned steps to execute any code
snippet in this tutorial.
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2233,
"s": 2052,
"text": "In this chapter, we will understand the environment for our Salesforce Apex development. It is assumed that you already have a Salesforce edition set up for doing Apex development."
},
{
"code": null,
"e": 2627,
"s": 2233,
"text": "You can develop the Apex code in either Sandbox or Developer edition of Salesforce. A Sandbox organization is a copy of your organization in which you can write code and test it without taking the risk of data modification or disturbing the normal functionality. As per the standard industrial practice, you have to develop the code in Sandbox and then deploy it to the Production environment."
},
{
"code": null,
"e": 2859,
"s": 2627,
"text": "For this tutorial, we will be using the Developer edition of Salesforce. In the Developer edition, you will not have the option of creating a Sandbox organization. The Sandbox features are available in other editions of Salesforce."
},
{
"code": null,
"e": 2946,
"s": 2859,
"text": "In all the editions, we can use any of the following three tools to develop the code −"
},
{
"code": null,
"e": 2974,
"s": 2946,
"text": "Force.com Developer Console"
},
{
"code": null,
"e": 2988,
"s": 2974,
"text": "Force.com IDE"
},
{
"code": null,
"e": 3033,
"s": 2988,
"text": "Code Editor in the Salesforce User Interface"
},
{
"code": null,
"e": 3174,
"s": 3033,
"text": "Note − We will be utilizing the Developer Console throughout our tutorial for code execution as it is simple and user friendly for learning."
},
{
"code": null,
"e": 3349,
"s": 3174,
"text": "The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your Salesforce organization."
},
{
"code": null,
"e": 3400,
"s": 3349,
"text": "Follow these steps to open the Developer Console −"
},
{
"code": null,
"e": 3440,
"s": 3400,
"text": "Step 1 − Go to Name → Developer Console"
},
{
"code": null,
"e": 3535,
"s": 3440,
"text": "Step 2 − Click on \"Developer Console\" and a window will appear as in the following screenshot."
},
{
"code": null,
"e": 3617,
"s": 3535,
"text": "Following are a few operations that can be performed using the Developer Console."
},
{
"code": null,
"e": 3810,
"s": 3617,
"text": "Writing and compiling code − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported."
},
{
"code": null,
"e": 4003,
"s": 3810,
"text": "Writing and compiling code − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported."
},
{
"code": null,
"e": 4179,
"s": 4003,
"text": "Debugging − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported."
},
{
"code": null,
"e": 4355,
"s": 4179,
"text": "Debugging − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported."
},
{
"code": null,
"e": 4432,
"s": 4355,
"text": "Testing − You can view debug logs and set checkpoints that aid in debugging."
},
{
"code": null,
"e": 4509,
"s": 4432,
"text": "Testing − You can view debug logs and set checkpoints that aid in debugging."
},
{
"code": null,
"e": 4684,
"s": 4509,
"text": "Checking performance − You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage."
},
{
"code": null,
"e": 4859,
"s": 4684,
"text": "Checking performance − You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage."
},
{
"code": null,
"e": 4937,
"s": 4859,
"text": "SOQL queries − You can inspect debug logs to locate performance bottlenecks. "
},
{
"code": null,
"e": 5015,
"s": 4937,
"text": "SOQL queries − You can inspect debug logs to locate performance bottlenecks. "
},
{
"code": null,
"e": 5187,
"s": 5015,
"text": "Color coding and autocomplete − The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names."
},
{
"code": null,
"e": 5359,
"s": 5187,
"text": "Color coding and autocomplete − The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names."
},
{
"code": null,
"e": 5512,
"s": 5359,
"text": "All the code snippets mentioned in this tutorial need to be executed in the developer console. Follow these steps to execute steps in Developer Console."
},
{
"code": null,
"e": 5675,
"s": 5512,
"text": "Step 1 − Login to the Salesforce.com using login.salesforce.com. Copy the code snippets mentioned in the tutorial. For now, we will use the following sample code."
},
{
"code": null,
"e": 5756,
"s": 5675,
"text": "String myString = 'MyString';\nSystem.debug('Value of String Variable'+myString);"
},
{
"code": null,
"e": 5882,
"s": 5756,
"text": "Step 2 − To open the Developer Console, click on Name → Developer Console and then click on Execute Anonymous as shown below."
},
{
"code": null,
"e": 5960,
"s": 5882,
"text": "Step 3 − In this step, a window will appear and you can paste the code there."
},
{
"code": null,
"e": 6098,
"s": 5960,
"text": "Step 4 − When we click on Execute, the debug logs will open. Once the log appears in window as shown below, then click on the log record."
},
{
"code": null,
"e": 6258,
"s": 6098,
"text": "Then type 'USER' in the window as shown below and the output statement will appear in the debug window. This 'USER' statement is used for filtering the output."
},
{
"code": null,
"e": 6370,
"s": 6258,
"text": "So basically, you will be following all the above mentioned steps to execute any code\nsnippet in this tutorial."
},
{
"code": null,
"e": 6403,
"s": 6370,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6416,
"s": 6403,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 6448,
"s": 6416,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6456,
"s": 6448,
"text": " Uplatz"
},
{
"code": null,
"e": 6489,
"s": 6456,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6514,
"s": 6489,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 6547,
"s": 6514,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6562,
"s": 6547,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 6595,
"s": 6562,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6608,
"s": 6595,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 6643,
"s": 6608,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6655,
"s": 6643,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 6662,
"s": 6655,
"text": " Print"
},
{
"code": null,
"e": 6673,
"s": 6662,
"text": " Add Notes"
}
] |
Minimum number of Edges to be added to a Graph to satisfy the given condition - GeeksforGeeks | 30 Jun, 2021
Given a graph consisting of N nodes numbered from 0 to N – 1 and M edges in the form of pairs {a, b}, the task is to find the minimum number of edges to be added to the graph such that if there exists a path from any node a to node b, then there should be paths from node a to nodes [ a + 1, a + 2, a + 3, ..., b – 1] as well.
Examples:
Input: N = 7, M = 3, Edges[][] = {{1, 5}, {2, 4}, {3, 4}} Output: 1 Explanation: There is a path from 1 to 5. So there should be paths from 1 to 2, 3 and 4 as well. Adding an edge {1, 2} will be sufficient to reach the other two nodes of the graph.
Input: N = 8, M = 3 Edges[][] = {{1, 2}, {2, 3}, {3, 4}} Output: 0
Approach:The idea is to use a Disjoint Set or Union find. Each component in the disjoint set should have consecutive nodes. This can be done by maintaining maximum_node[] and minimum_node[] arrays to store the maximum and minimum value of nodes in each component respectively. Follow the steps below to solve the problem:
Create a structure for the disjoint set union.
Initialize the answer as 0 and iterate over all the nodes in the graph to get the component of the current node.
If the component is not visited, then mark it as visited.
Now, Iterate from minimum value to maximum value of that component and check if the the nodes are in the same component with the current node or not and combine them into one component and increment the answer by 1.
Finally, print the answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>#define MOD 1000000007 #define int long long intusing namespace std; // Disjoint Set Unionstruct dsu { // Stores the parent // of each node vector<int> parent; // Storing maximum value // in each component vector<int> maximum_node; // Stores the minimum value // in each component vector<int> minimum_node; // Stores the visited nodes vector<int> visited; // Function to initialize the // values in vectors void init(int n) { // Initialize the size of // vectors as n parent.resize(n); maximum_node.resize(n); minimum_node.resize(n); visited.resize(n); for (int i = 0; i < n; i++) { // Initially every component // has only one node parent[i] = i; maximum_node[i] = i; minimum_node[i] = i; // Mark unvisited visited[i] = 0; } } // Function to get identifier node // (superparent) for each component int getsuperparent(int x) { // If parent of a node is that // node itself then the node is // superparent of that component return x == parent[x] ? x : parent[x] = getsuperparent(parent[x]); } // Function to perform union of two // different components void unite(int x, int y) { int superparent_x = getsuperparent(x); int superparent_y = getsuperparent(y); // Set superparent of y as the // parent of superparent of x parent[superparent_x] = superparent_y; // Update the maximum node // in the component containing y maximum_node[superparent_y] = max(maximum_node[superparent_y], maximum_node[superparent_x]); // Update the minimum node // in the component containing y minimum_node[superparent_y] = min(minimum_node[superparent_y], minimum_node[superparent_x]); }} G; // Function to find the minimum number// of edges to be added to the Graphint minimumEdgesToBeAdded(int n){ // Stores the answer int answer = 0; // Iterate over all nodes for (int i = 0; i < n; i++) { // Get the superparent of // the current node int temp = G.getsuperparent(i); // If the node is not visited if (!G.visited[temp]) { // Set the node as visited G.visited[temp] = 1; // Iterate from the minimum // value to maximum value in // the current component for (int j = G.minimum_node[temp]; j <= G.maximum_node[temp]; j++) { // If the nodes are in // different components if (G.getsuperparent(j) != G.getsuperparent(i)) { // Unite them G.unite(i, j); // Increment the answer answer++; } } } } // Return the answer return answer;} // Driver Codeint32_t main(){ int N = 7, M = 3; G.init(N); // Insert edges G.unite(1, 5); G.unite(2, 4); G.unite(3, 4); cout << minimumEdgesToBeAdded(N); return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ static final int MOD = 1000000007; // Disjoint Set Unionstatic class dsu{ public dsu(){} // Stores the parent // of each node int[] parent; // Storing maximum value // in each component int[] maximum_node; // Stores the minimum value // in each component int[] minimum_node; // Stores the visited nodes int[] visited; // Function to initialize the // values in vectors void init(int n) { // Initialize the size of // vectors as n parent = new int[n]; maximum_node = new int[n]; minimum_node = new int[n]; visited = new int[n]; for(int i = 0; i < n; i++) { // Initially every component // has only one node parent[i] = i; maximum_node[i] = i; minimum_node[i] = i; // Mark unvisited visited[i] = 0; } } // Function to get identifier node // (superparent) for each component int getsuperparent(int x) { // If parent of a node is that // node itself then the node is // superparent of that component if(x == parent[x]) return x; else { parent[x] = getsuperparent(parent[x]); return parent[x]; } } // Function to perform union of two // different components void unite(int x, int y) { int superparent_x = getsuperparent(x); int superparent_y = getsuperparent(y); // Set superparent of y as the // parent of superparent of x parent[superparent_x] = superparent_y; // Update the maximum node // in the component containing y maximum_node[superparent_y] = Math.max( maximum_node[superparent_y], maximum_node[superparent_x]); // Update the minimum node // in the component containing y minimum_node[superparent_y] = Math.min( minimum_node[superparent_y], minimum_node[superparent_x]); }}; static dsu G = new dsu(); // Function to find the minimum number// of edges to be added to the Graphstatic int minimumEdgesToBeAdded(int n){ // Stores the answer int answer = 0; // Iterate over all nodes for(int i = 0; i < n; i++) { // Get the superparent of // the current node int temp = G.getsuperparent(i); // If the node is not visited if (G.visited[temp] == 0) { // Set the node as visited G.visited[temp] = 1; // Iterate from the minimum // value to maximum value in // the current component for(int j = G.minimum_node[temp]; j <= G.maximum_node[temp]; j++) { // If the nodes are in // different components if (G.getsuperparent(j) != G.getsuperparent(i)) { // Unite them G.unite(i, j); // Increment the answer answer++; } } } } // Return the answer return answer;} // Driver Codepublic static void main(String[] args){ int N = 7; G.init(N); // Insert edges G.unite(1, 5); G.unite(2, 4); G.unite(3, 4); System.out.print(minimumEdgesToBeAdded(N));}} // This code is contributed by 29AjayKumar
# Python3 program to implement# the above approachMOD = 1000000007 # Disjoint Set Unionclass dsu: # Function to initialize the # values in vectors def __init__(self, n: int) -> None: # Stores the parent # of each node self.parent = [i for i in range(n)] # Storing maximum value # in each component self.maximum_node = [i for i in range(n)] # Stores the minimum value # in each component self.minimum_node = [i for i in range(n)] # Stores the visited nodes self.visited = [0] * n # Function to get identifier node # (superparent) for each component def getsuperparent(self, x: int) -> int: # If parent of a node is that # node itself then the node is # superparent of that component if x == self.parent[x]: return x else: self.parent[x] = self.getsuperparent( self.parent[x]) return self.parent[x] # Function to perform union of two # different components def unite(self, x: int, y: int) -> None: superparent_x = self.getsuperparent(x) superparent_y = self.getsuperparent(y) # Set superparent of y as the # parent of superparent of x self.parent[superparent_x] = superparent_y # Update the maximum node # in the component containing y self.maximum_node[superparent_y] = max( self.maximum_node[superparent_y], self.maximum_node[superparent_x]) # Update the minimum node # in the component containing y self.minimum_node[superparent_y] = min( self.minimum_node[superparent_y], self.minimum_node[superparent_x]) # Function to find the minimum number# of edges to be added to the Graphdef minimumEdgesToBeAdded(n: int) -> int: global G # Stores the answer answer = 0 # Iterate over all nodes for i in range(n): # Get the superparent of # the current node temp = G.getsuperparent(i) # If the node is not visited if (not G.visited[temp]): # Set the node as visited G.visited[temp] = 1 # Iterate from the minimum # value to maximum value in # the current component for j in range(G.minimum_node[temp], G.maximum_node[temp] + 1): # If the nodes are in # different components if (G.getsuperparent(j) != G.getsuperparent(i)): # Unite them G.unite(i, j) # Increment the answer answer += 1 # Return the answer return answer # Driver Codeif __name__ == "__main__": N = 7 M = 3 G = dsu(N) # Insert edges G.unite(1, 5) G.unite(2, 4) G.unite(3, 4) print(minimumEdgesToBeAdded(N)) # This code is contributed by sanjeev2552
// C# program to implement// the above approachusing System; class GFG{ //static readonly int MOD = 1000000007; // Disjoint Set Unionclass dsu{ public dsu(){} // Stores the parent // of each node public int[] parent; // Storing maximum value // in each component public int[] maximum_node; // Stores the minimum value // in each component public int[] minimum_node; // Stores the visited nodes public int[] visited; // Function to initialize the // values in vectors public void init(int n) { // Initialize the size of // vectors as n parent = new int[n]; maximum_node = new int[n]; minimum_node = new int[n]; visited = new int[n]; for(int i = 0; i < n; i++) { // Initially every component // has only one node parent[i] = i; maximum_node[i] = i; minimum_node[i] = i; // Mark unvisited visited[i] = 0; } } // Function to get identifier node // (superparent) for each component public int getsuperparent(int x) { // If parent of a node is that // node itself then the node is // superparent of that component if(x == parent[x]) return x; else { parent[x] = getsuperparent(parent[x]); return parent[x]; } } // Function to perform union of two // different components public void unite(int x, int y) { int superparent_x = getsuperparent(x); int superparent_y = getsuperparent(y); // Set superparent of y as the // parent of superparent of x parent[superparent_x] = superparent_y; // Update the maximum node // in the component containing y maximum_node[superparent_y] = Math.Max( maximum_node[superparent_y], maximum_node[superparent_x]); // Update the minimum node // in the component containing y minimum_node[superparent_y] = Math.Min( minimum_node[superparent_y], minimum_node[superparent_x]); }}; static dsu G = new dsu(); // Function to find the minimum number// of edges to be added to the Graphstatic int minimumEdgesToBeAdded(int n){ // Stores the answer int answer = 0; // Iterate over all nodes for(int i = 0; i < n; i++) { // Get the superparent of // the current node int temp = G.getsuperparent(i); // If the node is not visited if (G.visited[temp] == 0) { // Set the node as visited G.visited[temp] = 1; // Iterate from the minimum // value to maximum value in // the current component for(int j = G.minimum_node[temp]; j <= G.maximum_node[temp]; j++) { // If the nodes are in // different components if (G.getsuperparent(j) != G.getsuperparent(i)) { // Unite them G.unite(i, j); // Increment the answer answer++; } } } } // Return the answer return answer;} // Driver Codepublic static void Main(String[] args){ int N = 7; G.init(N); // Insert edges G.unite(1, 5); G.unite(2, 4); G.unite(3, 4); Console.Write(minimumEdgesToBeAdded(N));}} // This code is contributed by Rajput-Ji
<script> // Javascript program to implement// the above approach var MOD = 1000000007; // Stores the parent// of each nodevar parent = [];// Storing maximum value// in each componentvar maximum_node = [];// Stores the minimum value// in each componentvar minimum_node = [];// Stores the visited nodesvar visited = [];// Function to initialize the// values in vectorsfunction init(n){ // Initialize the size of // vectors as n parent = Array(n); maximum_node = Array(n); minimum_node = Array(n); visited = Array(n); for(var i = 0; i < n; i++) { // Initially every component // has only one node parent[i] = i; maximum_node[i] = i; minimum_node[i] = i; // Mark unvisited visited[i] = 0; }}// Function to get identifier node// (superparent) for each componentfunction getsuperparent(x){ // If parent of a node is that // node itself then the node is // superparent of that component if(x == parent[x]) return x; else { parent[x] = getsuperparent(parent[x]); return parent[x]; }}// Function to perform union of two// different componentsfunction unite(x, y){ var superparent_x = getsuperparent(x); var superparent_y = getsuperparent(y); // Set superparent of y as the // parent of superparent of x parent[superparent_x] = superparent_y; // Update the maximum node // in the component containing y maximum_node[superparent_y] = Math.max( maximum_node[superparent_y], maximum_node[superparent_x]); // Update the minimum node // in the component containing y minimum_node[superparent_y] = Math.min( minimum_node[superparent_y], minimum_node[superparent_x]);} // Function to find the minimum number// of edges to be added to the Graphfunction minimumEdgesToBeAdded(n){ // Stores the answer var answer = 0; // Iterate over all nodes for(var i = 0; i < n; i++) { // Get the superparent of // the current node var temp = getsuperparent(i); // If the node is not visited if (visited[temp] == 0) { // Set the node as visited visited[temp] = 1; // Iterate from the minimum // value to maximum value in // the current component for(var j = minimum_node[temp]; j <= maximum_node[temp]; j++) { // If the nodes are in // different components if (getsuperparent(j) != getsuperparent(i)) { // Unite them unite(i, j); // Increment the answer answer++; } } } } // Return the answer return answer;} // Driver Codevar N = 7;init(N);// Insert edgesunite(1, 5);unite(2, 4);unite(3, 4);document.write(minimumEdgesToBeAdded(N)); </script>
1
Time Complexity: O(N), where N is the number of nodes in the graph.Auxiliary Space: O(N)
29AjayKumar
Rajput-Ji
sanjeev2552
rrrtnx
disjoint-set
union-find
Data Structures
Graph
Data Structures
Graph
union-find
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Tree Data Structure
Program to implement Singly Linked List in C++ using class
TCS NQT Coding Sheet
Hash Functions and list/types of Hash functions
Building an undirected graph and finding shortest path using Dictionaries in Python
Breadth First Search or BFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Depth First Search or DFS for a Graph
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 | [
{
"code": null,
"e": 24637,
"s": 24609,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 24964,
"s": 24637,
"text": "Given a graph consisting of N nodes numbered from 0 to N – 1 and M edges in the form of pairs {a, b}, the task is to find the minimum number of edges to be added to the graph such that if there exists a path from any node a to node b, then there should be paths from node a to nodes [ a + 1, a + 2, a + 3, ..., b – 1] as well."
},
{
"code": null,
"e": 24976,
"s": 24964,
"text": "Examples: "
},
{
"code": null,
"e": 25225,
"s": 24976,
"text": "Input: N = 7, M = 3, Edges[][] = {{1, 5}, {2, 4}, {3, 4}} Output: 1 Explanation: There is a path from 1 to 5. So there should be paths from 1 to 2, 3 and 4 as well. Adding an edge {1, 2} will be sufficient to reach the other two nodes of the graph."
},
{
"code": null,
"e": 25294,
"s": 25225,
"text": "Input: N = 8, M = 3 Edges[][] = {{1, 2}, {2, 3}, {3, 4}} Output: 0 "
},
{
"code": null,
"e": 25616,
"s": 25294,
"text": "Approach:The idea is to use a Disjoint Set or Union find. Each component in the disjoint set should have consecutive nodes. This can be done by maintaining maximum_node[] and minimum_node[] arrays to store the maximum and minimum value of nodes in each component respectively. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25663,
"s": 25616,
"text": "Create a structure for the disjoint set union."
},
{
"code": null,
"e": 25776,
"s": 25663,
"text": "Initialize the answer as 0 and iterate over all the nodes in the graph to get the component of the current node."
},
{
"code": null,
"e": 25834,
"s": 25776,
"text": "If the component is not visited, then mark it as visited."
},
{
"code": null,
"e": 26050,
"s": 25834,
"text": "Now, Iterate from minimum value to maximum value of that component and check if the the nodes are in the same component with the current node or not and combine them into one component and increment the answer by 1."
},
{
"code": null,
"e": 26077,
"s": 26050,
"text": "Finally, print the answer."
},
{
"code": null,
"e": 26128,
"s": 26077,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26132,
"s": 26128,
"text": "C++"
},
{
"code": null,
"e": 26137,
"s": 26132,
"text": "Java"
},
{
"code": null,
"e": 26145,
"s": 26137,
"text": "Python3"
},
{
"code": null,
"e": 26148,
"s": 26145,
"text": "C#"
},
{
"code": null,
"e": 26159,
"s": 26148,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>#define MOD 1000000007 #define int long long intusing namespace std; // Disjoint Set Unionstruct dsu { // Stores the parent // of each node vector<int> parent; // Storing maximum value // in each component vector<int> maximum_node; // Stores the minimum value // in each component vector<int> minimum_node; // Stores the visited nodes vector<int> visited; // Function to initialize the // values in vectors void init(int n) { // Initialize the size of // vectors as n parent.resize(n); maximum_node.resize(n); minimum_node.resize(n); visited.resize(n); for (int i = 0; i < n; i++) { // Initially every component // has only one node parent[i] = i; maximum_node[i] = i; minimum_node[i] = i; // Mark unvisited visited[i] = 0; } } // Function to get identifier node // (superparent) for each component int getsuperparent(int x) { // If parent of a node is that // node itself then the node is // superparent of that component return x == parent[x] ? x : parent[x] = getsuperparent(parent[x]); } // Function to perform union of two // different components void unite(int x, int y) { int superparent_x = getsuperparent(x); int superparent_y = getsuperparent(y); // Set superparent of y as the // parent of superparent of x parent[superparent_x] = superparent_y; // Update the maximum node // in the component containing y maximum_node[superparent_y] = max(maximum_node[superparent_y], maximum_node[superparent_x]); // Update the minimum node // in the component containing y minimum_node[superparent_y] = min(minimum_node[superparent_y], minimum_node[superparent_x]); }} G; // Function to find the minimum number// of edges to be added to the Graphint minimumEdgesToBeAdded(int n){ // Stores the answer int answer = 0; // Iterate over all nodes for (int i = 0; i < n; i++) { // Get the superparent of // the current node int temp = G.getsuperparent(i); // If the node is not visited if (!G.visited[temp]) { // Set the node as visited G.visited[temp] = 1; // Iterate from the minimum // value to maximum value in // the current component for (int j = G.minimum_node[temp]; j <= G.maximum_node[temp]; j++) { // If the nodes are in // different components if (G.getsuperparent(j) != G.getsuperparent(i)) { // Unite them G.unite(i, j); // Increment the answer answer++; } } } } // Return the answer return answer;} // Driver Codeint32_t main(){ int N = 7, M = 3; G.init(N); // Insert edges G.unite(1, 5); G.unite(2, 4); G.unite(3, 4); cout << minimumEdgesToBeAdded(N); return 0;}",
"e": 29492,
"s": 26159,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ static final int MOD = 1000000007; // Disjoint Set Unionstatic class dsu{ public dsu(){} // Stores the parent // of each node int[] parent; // Storing maximum value // in each component int[] maximum_node; // Stores the minimum value // in each component int[] minimum_node; // Stores the visited nodes int[] visited; // Function to initialize the // values in vectors void init(int n) { // Initialize the size of // vectors as n parent = new int[n]; maximum_node = new int[n]; minimum_node = new int[n]; visited = new int[n]; for(int i = 0; i < n; i++) { // Initially every component // has only one node parent[i] = i; maximum_node[i] = i; minimum_node[i] = i; // Mark unvisited visited[i] = 0; } } // Function to get identifier node // (superparent) for each component int getsuperparent(int x) { // If parent of a node is that // node itself then the node is // superparent of that component if(x == parent[x]) return x; else { parent[x] = getsuperparent(parent[x]); return parent[x]; } } // Function to perform union of two // different components void unite(int x, int y) { int superparent_x = getsuperparent(x); int superparent_y = getsuperparent(y); // Set superparent of y as the // parent of superparent of x parent[superparent_x] = superparent_y; // Update the maximum node // in the component containing y maximum_node[superparent_y] = Math.max( maximum_node[superparent_y], maximum_node[superparent_x]); // Update the minimum node // in the component containing y minimum_node[superparent_y] = Math.min( minimum_node[superparent_y], minimum_node[superparent_x]); }}; static dsu G = new dsu(); // Function to find the minimum number// of edges to be added to the Graphstatic int minimumEdgesToBeAdded(int n){ // Stores the answer int answer = 0; // Iterate over all nodes for(int i = 0; i < n; i++) { // Get the superparent of // the current node int temp = G.getsuperparent(i); // If the node is not visited if (G.visited[temp] == 0) { // Set the node as visited G.visited[temp] = 1; // Iterate from the minimum // value to maximum value in // the current component for(int j = G.minimum_node[temp]; j <= G.maximum_node[temp]; j++) { // If the nodes are in // different components if (G.getsuperparent(j) != G.getsuperparent(i)) { // Unite them G.unite(i, j); // Increment the answer answer++; } } } } // Return the answer return answer;} // Driver Codepublic static void main(String[] args){ int N = 7; G.init(N); // Insert edges G.unite(1, 5); G.unite(2, 4); G.unite(3, 4); System.out.print(minimumEdgesToBeAdded(N));}} // This code is contributed by 29AjayKumar",
"e": 33040,
"s": 29492,
"text": null
},
{
"code": "# Python3 program to implement# the above approachMOD = 1000000007 # Disjoint Set Unionclass dsu: # Function to initialize the # values in vectors def __init__(self, n: int) -> None: # Stores the parent # of each node self.parent = [i for i in range(n)] # Storing maximum value # in each component self.maximum_node = [i for i in range(n)] # Stores the minimum value # in each component self.minimum_node = [i for i in range(n)] # Stores the visited nodes self.visited = [0] * n # Function to get identifier node # (superparent) for each component def getsuperparent(self, x: int) -> int: # If parent of a node is that # node itself then the node is # superparent of that component if x == self.parent[x]: return x else: self.parent[x] = self.getsuperparent( self.parent[x]) return self.parent[x] # Function to perform union of two # different components def unite(self, x: int, y: int) -> None: superparent_x = self.getsuperparent(x) superparent_y = self.getsuperparent(y) # Set superparent of y as the # parent of superparent of x self.parent[superparent_x] = superparent_y # Update the maximum node # in the component containing y self.maximum_node[superparent_y] = max( self.maximum_node[superparent_y], self.maximum_node[superparent_x]) # Update the minimum node # in the component containing y self.minimum_node[superparent_y] = min( self.minimum_node[superparent_y], self.minimum_node[superparent_x]) # Function to find the minimum number# of edges to be added to the Graphdef minimumEdgesToBeAdded(n: int) -> int: global G # Stores the answer answer = 0 # Iterate over all nodes for i in range(n): # Get the superparent of # the current node temp = G.getsuperparent(i) # If the node is not visited if (not G.visited[temp]): # Set the node as visited G.visited[temp] = 1 # Iterate from the minimum # value to maximum value in # the current component for j in range(G.minimum_node[temp], G.maximum_node[temp] + 1): # If the nodes are in # different components if (G.getsuperparent(j) != G.getsuperparent(i)): # Unite them G.unite(i, j) # Increment the answer answer += 1 # Return the answer return answer # Driver Codeif __name__ == \"__main__\": N = 7 M = 3 G = dsu(N) # Insert edges G.unite(1, 5) G.unite(2, 4) G.unite(3, 4) print(minimumEdgesToBeAdded(N)) # This code is contributed by sanjeev2552",
"e": 36067,
"s": 33040,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System; class GFG{ //static readonly int MOD = 1000000007; // Disjoint Set Unionclass dsu{ public dsu(){} // Stores the parent // of each node public int[] parent; // Storing maximum value // in each component public int[] maximum_node; // Stores the minimum value // in each component public int[] minimum_node; // Stores the visited nodes public int[] visited; // Function to initialize the // values in vectors public void init(int n) { // Initialize the size of // vectors as n parent = new int[n]; maximum_node = new int[n]; minimum_node = new int[n]; visited = new int[n]; for(int i = 0; i < n; i++) { // Initially every component // has only one node parent[i] = i; maximum_node[i] = i; minimum_node[i] = i; // Mark unvisited visited[i] = 0; } } // Function to get identifier node // (superparent) for each component public int getsuperparent(int x) { // If parent of a node is that // node itself then the node is // superparent of that component if(x == parent[x]) return x; else { parent[x] = getsuperparent(parent[x]); return parent[x]; } } // Function to perform union of two // different components public void unite(int x, int y) { int superparent_x = getsuperparent(x); int superparent_y = getsuperparent(y); // Set superparent of y as the // parent of superparent of x parent[superparent_x] = superparent_y; // Update the maximum node // in the component containing y maximum_node[superparent_y] = Math.Max( maximum_node[superparent_y], maximum_node[superparent_x]); // Update the minimum node // in the component containing y minimum_node[superparent_y] = Math.Min( minimum_node[superparent_y], minimum_node[superparent_x]); }}; static dsu G = new dsu(); // Function to find the minimum number// of edges to be added to the Graphstatic int minimumEdgesToBeAdded(int n){ // Stores the answer int answer = 0; // Iterate over all nodes for(int i = 0; i < n; i++) { // Get the superparent of // the current node int temp = G.getsuperparent(i); // If the node is not visited if (G.visited[temp] == 0) { // Set the node as visited G.visited[temp] = 1; // Iterate from the minimum // value to maximum value in // the current component for(int j = G.minimum_node[temp]; j <= G.maximum_node[temp]; j++) { // If the nodes are in // different components if (G.getsuperparent(j) != G.getsuperparent(i)) { // Unite them G.unite(i, j); // Increment the answer answer++; } } } } // Return the answer return answer;} // Driver Codepublic static void Main(String[] args){ int N = 7; G.init(N); // Insert edges G.unite(1, 5); G.unite(2, 4); G.unite(3, 4); Console.Write(minimumEdgesToBeAdded(N));}} // This code is contributed by Rajput-Ji",
"e": 39649,
"s": 36067,
"text": null
},
{
"code": "<script> // Javascript program to implement// the above approach var MOD = 1000000007; // Stores the parent// of each nodevar parent = [];// Storing maximum value// in each componentvar maximum_node = [];// Stores the minimum value// in each componentvar minimum_node = [];// Stores the visited nodesvar visited = [];// Function to initialize the// values in vectorsfunction init(n){ // Initialize the size of // vectors as n parent = Array(n); maximum_node = Array(n); minimum_node = Array(n); visited = Array(n); for(var i = 0; i < n; i++) { // Initially every component // has only one node parent[i] = i; maximum_node[i] = i; minimum_node[i] = i; // Mark unvisited visited[i] = 0; }}// Function to get identifier node// (superparent) for each componentfunction getsuperparent(x){ // If parent of a node is that // node itself then the node is // superparent of that component if(x == parent[x]) return x; else { parent[x] = getsuperparent(parent[x]); return parent[x]; }}// Function to perform union of two// different componentsfunction unite(x, y){ var superparent_x = getsuperparent(x); var superparent_y = getsuperparent(y); // Set superparent of y as the // parent of superparent of x parent[superparent_x] = superparent_y; // Update the maximum node // in the component containing y maximum_node[superparent_y] = Math.max( maximum_node[superparent_y], maximum_node[superparent_x]); // Update the minimum node // in the component containing y minimum_node[superparent_y] = Math.min( minimum_node[superparent_y], minimum_node[superparent_x]);} // Function to find the minimum number// of edges to be added to the Graphfunction minimumEdgesToBeAdded(n){ // Stores the answer var answer = 0; // Iterate over all nodes for(var i = 0; i < n; i++) { // Get the superparent of // the current node var temp = getsuperparent(i); // If the node is not visited if (visited[temp] == 0) { // Set the node as visited visited[temp] = 1; // Iterate from the minimum // value to maximum value in // the current component for(var j = minimum_node[temp]; j <= maximum_node[temp]; j++) { // If the nodes are in // different components if (getsuperparent(j) != getsuperparent(i)) { // Unite them unite(i, j); // Increment the answer answer++; } } } } // Return the answer return answer;} // Driver Codevar N = 7;init(N);// Insert edgesunite(1, 5);unite(2, 4);unite(3, 4);document.write(minimumEdgesToBeAdded(N)); </script>",
"e": 42677,
"s": 39649,
"text": null
},
{
"code": null,
"e": 42679,
"s": 42677,
"text": "1"
},
{
"code": null,
"e": 42771,
"s": 42681,
"text": "Time Complexity: O(N), where N is the number of nodes in the graph.Auxiliary Space: O(N) "
},
{
"code": null,
"e": 42783,
"s": 42771,
"text": "29AjayKumar"
},
{
"code": null,
"e": 42793,
"s": 42783,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 42805,
"s": 42793,
"text": "sanjeev2552"
},
{
"code": null,
"e": 42812,
"s": 42805,
"text": "rrrtnx"
},
{
"code": null,
"e": 42825,
"s": 42812,
"text": "disjoint-set"
},
{
"code": null,
"e": 42836,
"s": 42825,
"text": "union-find"
},
{
"code": null,
"e": 42852,
"s": 42836,
"text": "Data Structures"
},
{
"code": null,
"e": 42858,
"s": 42852,
"text": "Graph"
},
{
"code": null,
"e": 42874,
"s": 42858,
"text": "Data Structures"
},
{
"code": null,
"e": 42880,
"s": 42874,
"text": "Graph"
},
{
"code": null,
"e": 42891,
"s": 42880,
"text": "union-find"
},
{
"code": null,
"e": 42989,
"s": 42891,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42998,
"s": 42989,
"text": "Comments"
},
{
"code": null,
"e": 43011,
"s": 42998,
"text": "Old Comments"
},
{
"code": null,
"e": 43047,
"s": 43011,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 43106,
"s": 43047,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 43127,
"s": 43106,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 43175,
"s": 43127,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 43259,
"s": 43175,
"text": "Building an undirected graph and finding shortest path using Dictionaries in Python"
},
{
"code": null,
"e": 43299,
"s": 43259,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 43350,
"s": 43299,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 43388,
"s": 43350,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 43439,
"s": 43388,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
}
] |
Bayesball: Bayesian analysis of batting average | by Ricky Kim | Towards Data Science | *In addition to short code blocks I will attach, you can find the link for the whole Jupyter Notebook at the end of this post.
One of the topics in data science or statistics I found interesting, but having difficulty understanding is Bayesian analysis. During the course of my General Assembly’s Data Science Immersive boot camp, I have had a chance to explore Bayesian statistics, but I really think I need some review and reinforcement.
This is my personal endeavour to have a better understanding of Bayesian thinking, and how it can be applied to real-life cases.
For this post, I am mainly inspired by a Youtube series by Rasmus Bååth, “Introduction to Bayesian data analysis”. He is really good at giving you an intuitive understanding of Bayesian analysis, not by bombarding you with all the complicated formulas, but by providing you with a thought-process of Bayesian statistics.
The topic I chose for this post is baseball. To be honest, I’m not a big sports fan. I rarely watch sports. As a Korean, baseball is the most famous sports in Korea, and I believe there are some Korean players in MLB as well. It’s a bit embarrassing to admit, but I have heard of Chan-Ho Park, but that’s about it.
Then why choose baseball?
“I don’t know whether you know it, but baseball’s appeal is decimal points. No other sport relies as totally on continuity, statistics, orderliness of these. Baseball fans pay more attention to numbers than CPAs.” — Sportswriter Jim Murray
They say baseball is probably the world’s best documented sports. The history has cumulated records in the past hundred years of the baseball statistics. However having collected stats alone doesn’t make baseball interesting in terms of statistics. Maybe the more important aspect is the individual nature of the game. For example, during an at-bat, who is playing in the outfield has very little effect on whether or not the batter can hit a home run. In other sports, especially football and basketball, the meaning of individual statistics can be diluted by the importance of what is going on elsewhere on the field or the court. This is what makes baseball stats useful for player comparison.
Baseball stats consist of numerous metrics, some of them straight-forward, some of them quite advanced. The metric I chose to take a look at is batting average(AVG). In baseball, the batting average is defined by the number of hits divided by at bats. It is usually reported to three decimal places.
There can be criticism on batting average, but according to C. Trent Rosecrans, “Still, what batting average does have over all the other statistics is history and context. We all know what a .300 hitter is, we know how bad a .200 hitter is and how great a .400 hitter is.”
It seems like the regular season hasn’t started yet, and will start soon (29th of March). But there’s spring training. In Major League Baseball (MLB), spring training is a series of practices and exhibition games preceding the start of the regular season.
The questions I would try to answer are as follows:
How I should interpret batting average from 2018 spring training
How can I compare two players on their batting average
Before I jump into code, I will briefly touch on what Rasmus Bååth explained in his videos.
We first need three things to implement Bayesian analysis.1. Data2. Generative Model3. Prior
In my case, the data will be the batting average records from 2018 spring training. The data is simply what we observed.
A Generative Model is the model that generates data when given parameters as input. The parameters are values you’ll need to generate a distribution. For example, if you know the mean and the standard deviation, you can easily generate normally distributed data of your chosen size by running below code. We will see other types of distribution later to use in Bayesian analysis.
import matplotlib.pyplot as pltimport numpy as npmu, sigma = 0, 0.1 # mean and standard deviations = np.random.normal(mu, sigma, 1000)plt.hist(s)
In the case of Bayesian analysis, we inverse the generative model and try to infer parameters with observed data.
Finally, Prior is the information that the model has before seeing the data. Is any probability equally likely? Or do we have some prior data that we can utilise? Or is there any educated guess that we can make?
I will first define a function to scrape Fox Sports’ stats page for a player. I defined it as to be able to extract BATTING stats for either spring training or regular season.
import pandas as pdimport seaborn as snsimport requestsfrom bs4 import BeautifulSoupplt.style.use('fivethirtyeight')%matplotlib inline%config InlineBackend.figure_format = 'retina'def batting_stats(url,season): r = requests.get(url) soup = BeautifulSoup(r.text, 'lxml') table = soup.find_all("table",{"class": "wisbb_standardTable tablesorter"})[0] table_head = soup.find_all("thead",{"class": "wisbb_tableHeader"})[0] if season == 'spring': row_height = len(table.find_all('tr')[:-1]) else: row_height = len(table.find_all('tr')[:-2]) result_df = pd.DataFrame(columns=[row.text.strip() for row in table_head.find_all('th')], index = range(0,row_height)) row_marker = 0 for row in table.find_all('tr')[:-1]: column_marker = 0 columns = row.find_all('td') for column in columns: result_df.iat[row_marker,column_marker] = column.text.strip() column_marker += 1 row_marker += 1 return result_df
Now let’s see who I should choose for analysis.
The above screen is spring training stats page for NY Mets (As I have already admitted, I know little about baseball, and I chose NY Mets because I liked the logo). If you arrange the players by their batting average (AVG), you can see Dominic Smith (DS) as the first, and Gavin Cecchini (GC) as the second. Are they good players? I don’t know. But by looking at the AVG only, DS is the best with 1.000 AVG.
But by some googling, I found out that “In recent years, the league-wide batting average has typically hovered around .260”. If so, then the AVG for DS and GC seems too high. By further looking at At-Bats (AB), Hits (H) of both players, it is clear that DS had only 1 AB and CS had 7. And also by looking further at AB for other players, the highest AB is 13 for 2018, and in 2017 the maximum AB is 60 within NY Mets.
Let’s assume that I know nothing about their past performance, and the only data I observed is 2018 spring training. And I don’t know what value range I should expect from AVG. Based on this, how should I interpret the stats from 2018 spring training?
Let’s scrape the spring training stats for DS.
ds_url_st = "https://www.foxsports.com/mlb/dominic-smith-player-stats?seasonType=3"dominic_smith_spring = batting_stats(ds_url_st,'spring')dominic_smith_spring.iloc[-1]
n_draw = 20000prior_ni = pd.Series(np.random.uniform(0, 1, size = n_draw)) plt.figure(figsize=(8,5))plt.hist(prior_ni)plt.title('Uniform distribution(0,1)')plt.xlabel('Prior on AVG')plt.ylabel('Frequency')
The prior represents our beliefs before we see the data. In the above distribution, any probability is almost equally likely (There are slight differences due to the random generation). Thus this means I know nothing about the player, and I don’t even have any educated guess to make about AVG. I assume that 0.000 AVG is equally like as 1.000 AVG or any other probability between 0 and 1.
Now the data we observed says there was 1 AB, and 1 H, hence 1.000 AVG. This can be represented by Binomial distribution. A random variable X that has a binomial distribution represents the number of successes in a sequence of n independent yes/no trials, each of which yields success with probability p. In case of AVG, AVG is the probability of success, AB is the number of trials, and H is the number of success.
Keeping these in mind, we can define our inverse generative model.
We will randomly pick one probability value from the uniform distribution we defined, and use this value as a parameter for our generative model. Let’s say the value we randomly picked is 0.230, this means 23% chance of success in Binomial distribution. The number of trials is 1 (DS has 1 AB), and if the result of the generative model matches the result we observed (in this case, DS has 1 H), then we keep the probability value 0.230. If we repeat this generation and filtering, we will finally get a distribution of probability that has generated the same result as we observed.
This becomes our Posterior.
def posterior(n_try, k_success, prior): hit = list() for p in prior: hit.append(np.random.binomial(n_try, p)) posterior = prior[list(map(lambda x: x == k_success, hit))] plt.figure(figsize=(8,5)) plt.hist(posterior) plt.title('Posterior distribution') plt.xlabel('Posterior on AVG') plt.ylabel('Frequency') print('Number of draws left: %d, Posterior mean: %.3f, Posterior median: %.3f, Posterior 95%% quantile interval: %.3f-%.3f' % (len(posterior), posterior.mean(), posterior.median(), posterior.quantile(.025), posterior.quantile(.975)))ds_n_trials = int(dominic_smith_spring[['AB','H']].iloc[-1][0])ds_k_success = int(dominic_smith_spring[['AB','H']].iloc[-1][1])posterior(ds_n_trials, ds_k_success, prior_ni)
95% quantile interval in posterior distribution is called credible interval and should be seen slightly different from confidence interval in Frequentists’ sense. There is another credible interval you can use, and I will get back to this when I mention Pymc3.
One major distinction between Bayesian’s credible interval and Frequentist’s confidence interval is their interpretation. The Bayesian probability reflects a person’s subjective beliefs. Following this approach, we can make the claim that true parameter is inside a credible interval with measurable probability. This property is appealing because it enables you to make a direct probability statement about parameters. Many people find this concept to be a more natural way of understanding a probability interval, which is also easier to explain. A confidence interval, on the other hand, enables you to make a claim that the interval covers the true parameter. If we gather a new sample, and calculate the confidence interval, and repeat this many times, 95% of those intervals we calculated will have true AVG value within the interval.
Credible Interval: “Given our observed data, there is a 95% probability that the true value of AVG falls within the credible interval”
Confidence Interval: “There is a 95% probability that when I compute confidence interval from data of this sort, the true value of AVG will fall within the confidence interval.”
Note the difference: the credible interval is a statement of probability about the parameter value given fixed bounds. The confidence interval is a probability about the bounds given a fixed parameter value.
Often in real-life, what we would like to know is about the true parameters not about the bounds, in that case, the Bayesian credible interval is the right way to go. In this case, we are interested in true AVG of the player.
With above posterior distribution, I am 95% certain that DS true AVG will be somewhere between 0.155 to 0.987. But that is a very broad statement to make. In other words, I am not quite certain about the true AVG of DS, after I observe just one trial with no prior knowledge.
For the second scenario, let’s assume that we know spring training stats from previous year.
dominic_smith_spring.iloc[-2:]
Now we have 2017 spring training stats, and our prior should reflect this knowledge. This is not a uniform distribution anymore since we know that in 2017 spring training, DS’s AVG was 0.167.
The Beta distribution is a continuous probability distribution having two parameters, alpha and beta. One of its most common uses is to model one’s uncertainty about the probability of success of an experiment. In particular, the conditional distribution of X, conditional on having observed k successes out of n trials, is a Beta distribution with parameters k+1 as alpha and n−k+1 as beta.
n_draw = 20000prior_trials = int(dominic_smith_spring.iloc[3].AB)prior_success = int(dominic_smith_spring.iloc[3].H)prior_i = pd.Series(np.random.beta(prior_success+1, prior_trials-prior_success+1, size = n_draw)) plt.figure(figsize=(8,5))plt.hist(prior_i)plt.title('Beta distribution(a=%d, b=%d)' % (prior_success+1,prior_trials-prior_success+1))plt.xlabel('Prior on AVG')plt.ylabel('Frequency')
posterior(ds_n_trials, ds_k_success, prior_i)
The 95% quantile region has been narrowed compared to the posterior with the uniform prior in Scenario 1. Now I can say that I am 95% certain that the true AVG of DS will lie between 0.095 to 0.340. However, considering that above 0.300 AVG is often called best hitters, the statement means that the player can be either worst hitter or the best hitter. We need more data to narrow our region of credibility.
For this scenario, let’s assume that I not only have stats from 2017 spring training, but also stats from 2017 regular season. How does this affect my statement after I get the posterior?
ds_url = "https://www.foxsports.com/mlb/dominic-smith-player-stats?seasonType=1"dominic_smith_reg = batting_stats(ds_url,'regular')dominic_smith = dominic_smith_reg.append(dominic_smith_spring.iloc[3], ignore_index=True)dominic_smith
ds_prior_trials = pd.to_numeric(dominic_smith.AB).sum()ds_prior_success = pd.to_numeric(dominic_smith.H).sum()n_draw = 20000prior_i_02 = pd.Series(np.random.beta(ds_prior_success+1, ds_prior_trials-ds_prior_success+1, size = n_draw)) plt.figure(figsize=(8,5))plt.hist(prior_i_02)plt.title('Beta distribution(a=%d, b=%d)' % (ds_prior_success+1,ds_prior_trials-ds_prior_success+1))plt.xlabel('Prior on AVG')plt.ylabel('Frequency')
posterior(ds_n_trials, ds_k_success, prior_i_02)
Now I can say that I am 95% certain that the true AVG of DS will lie between 0.146 to 0.258. It may not be pin-point but compared to Scenario 1 and 2, the credible interval is much narrower now.
I want to compare two players and see who’s better in terms of AVG. The data I observed is result from 2018 spring training, and the prior knowledge I have is of 2017 spring training and regular season. Now I want to compare DS to GC.
Up until Scenario 3, I simulated the sampling by rejecting all the parameters which yielded the result different from what I observed. But this type of random sample generation and filtering is often computationally expensive, and slow to run. But luckily, there’s a tool that we can use to enable the sampler spends more time in regions of high probability, raising efficiency. Probabilistic programming tools such as Pymc3 can efficiently handle sampling procedure by making use of clever algorithms such as HMC-NUTS.
Let’s first start by scraping stats for Gavin Cecchini from Fox Sports.
gc_url_st = "https://www.foxsports.com/mlb/gavin-cecchini-player-stats?seasonType=3"gc_url_reg = "https://www.foxsports.com/mlb/gavin-cecchini-player-stats?seasonType=1"gavin_cecchini_spring = batting_stats(gc_url_st,'spring')gavin_cecchini_reg = batting_stats(gc_url_reg,'regular')gc_n_trials = int(gavin_cecchini_spring.iloc[1].AB)gc_k_success = int(gavin_cecchini_spring.iloc[1].H)gc_prior = pd.DataFrame(gavin_cecchini_reg.iloc[1]).transpose().append(gavin_cecchini_spring.iloc[0])gc_prior
gc_prior_trials = pd.to_numeric(gc_prior.AB).sum()gc_prior_success = pd.to_numeric(gc_prior.H).sum()def observed_data_generator(n_try,observed_data): result = np.ones(observed_data) fails = n_try - observed_data result = np.append(result, np.zeros(fails)) return resultds_observed = observed_data_generator(ds_n_trials,ds_k_success)gc_observed = observed_data_generator(gc_n_trials,gc_k_success)
Now we are ready to fit a Pymc3 model.
import pymc3 as pmwith pm.Model() as model_a: D_p = pm.Beta('DS_AVG', ds_prior_success+1, ds_prior_trials-ds_prior_success+1) G_p = pm.Beta('GC_AVG', gc_prior_success+1, gc_prior_trials-gc_prior_success+1) DS = pm.Bernoulli('DS', p=D_p, observed=ds_observed) GC = pm.Bernoulli('GC', p=G_p, observed=gc_observed) DvG = pm.Deterministic('DvG', D_p - G_p) start = pm.find_MAP() trace = pm.sample(10000, start=start)pm.plot_posterior(trace, varnames=['DS_AVG','GC_AVG','DvG'],ref_val=0)
If we plot the posterior distributions of DS_AVG, GC_AVG, and DvG (DS_AVG — GC_AVG) using plot_posterior function in Pymc3, we see the term HPD instead of quantile. Highest Probability Density (HPD) interval is another type of credible interval we can use with posteriors. HPD interval chooses the narrowest interval, which will involve choosing those values of highest probability density including the mode.
Again I found another post by Rasmus Bååth provides an easy-to-understand visual comparison of quantile interval and highest density interval. Below are the mode and the highest density intervals covering 95% of the probability density for the six different posterior distributions.
The quantile interval includes the median, and having 50% of the probability to its left and 50% to its right and the quantile interval leaving, say, 2.5% probability on either side (in case of 95% credible interval).
In the case of batting average for DS and GC, it looks like the mode and the median is not that different, and if so HPD interval will be similar to quantile interval. Let’s see how they look.
pm.summary(trace)
We can see that both for DS and GC, HPD interval and quantile interval is either exactly the same or slightly different in decimal places.
The question I wanted to answer was who is the better player in terms of AVG, and I should say I can’t be certain. At least, I can’t be 95% certain that these two players are different in terms of AVG. The difference I calculated and plotted shows that the difference of AVG of two players (DS — GC, so if DvG is more positive then it means DS is better, else if DvG is more negative then it means GC is better), can be somewhere between -0.162 to 0.033.
This interval includes 0.000 which represents there is no difference between two players’ AVG. Thus, there is some evidence that GC is better than DS (since the DvG posterior distribution has a larger region in negative area than in the positive area), but I can’t be 95% certain that these two players are different in terms of AVG.
Maybe with more data, I might be able to be certain about their difference. After all, that is the essence of Bayesian thinking. It is not that the truth doesn’t exist, but it is that we can’t know it perfectly, and all we could hope to do is update our understanding as more and more evidence became available.
Thank you for reading, and you can find the whole Jupyter Notebook from the below link. | [
{
"code": null,
"e": 298,
"s": 171,
"text": "*In addition to short code blocks I will attach, you can find the link for the whole Jupyter Notebook at the end of this post."
},
{
"code": null,
"e": 611,
"s": 298,
"text": "One of the topics in data science or statistics I found interesting, but having difficulty understanding is Bayesian analysis. During the course of my General Assembly’s Data Science Immersive boot camp, I have had a chance to explore Bayesian statistics, but I really think I need some review and reinforcement."
},
{
"code": null,
"e": 740,
"s": 611,
"text": "This is my personal endeavour to have a better understanding of Bayesian thinking, and how it can be applied to real-life cases."
},
{
"code": null,
"e": 1063,
"s": 740,
"text": "For this post, I am mainly inspired by a Youtube series by Rasmus Bååth, “Introduction to Bayesian data analysis”. He is really good at giving you an intuitive understanding of Bayesian analysis, not by bombarding you with all the complicated formulas, but by providing you with a thought-process of Bayesian statistics."
},
{
"code": null,
"e": 1378,
"s": 1063,
"text": "The topic I chose for this post is baseball. To be honest, I’m not a big sports fan. I rarely watch sports. As a Korean, baseball is the most famous sports in Korea, and I believe there are some Korean players in MLB as well. It’s a bit embarrassing to admit, but I have heard of Chan-Ho Park, but that’s about it."
},
{
"code": null,
"e": 1404,
"s": 1378,
"text": "Then why choose baseball?"
},
{
"code": null,
"e": 1644,
"s": 1404,
"text": "“I don’t know whether you know it, but baseball’s appeal is decimal points. No other sport relies as totally on continuity, statistics, orderliness of these. Baseball fans pay more attention to numbers than CPAs.” — Sportswriter Jim Murray"
},
{
"code": null,
"e": 2341,
"s": 1644,
"text": "They say baseball is probably the world’s best documented sports. The history has cumulated records in the past hundred years of the baseball statistics. However having collected stats alone doesn’t make baseball interesting in terms of statistics. Maybe the more important aspect is the individual nature of the game. For example, during an at-bat, who is playing in the outfield has very little effect on whether or not the batter can hit a home run. In other sports, especially football and basketball, the meaning of individual statistics can be diluted by the importance of what is going on elsewhere on the field or the court. This is what makes baseball stats useful for player comparison."
},
{
"code": null,
"e": 2641,
"s": 2341,
"text": "Baseball stats consist of numerous metrics, some of them straight-forward, some of them quite advanced. The metric I chose to take a look at is batting average(AVG). In baseball, the batting average is defined by the number of hits divided by at bats. It is usually reported to three decimal places."
},
{
"code": null,
"e": 2915,
"s": 2641,
"text": "There can be criticism on batting average, but according to C. Trent Rosecrans, “Still, what batting average does have over all the other statistics is history and context. We all know what a .300 hitter is, we know how bad a .200 hitter is and how great a .400 hitter is.”"
},
{
"code": null,
"e": 3171,
"s": 2915,
"text": "It seems like the regular season hasn’t started yet, and will start soon (29th of March). But there’s spring training. In Major League Baseball (MLB), spring training is a series of practices and exhibition games preceding the start of the regular season."
},
{
"code": null,
"e": 3223,
"s": 3171,
"text": "The questions I would try to answer are as follows:"
},
{
"code": null,
"e": 3288,
"s": 3223,
"text": "How I should interpret batting average from 2018 spring training"
},
{
"code": null,
"e": 3343,
"s": 3288,
"text": "How can I compare two players on their batting average"
},
{
"code": null,
"e": 3437,
"s": 3343,
"text": "Before I jump into code, I will briefly touch on what Rasmus Bååth explained in his videos."
},
{
"code": null,
"e": 3530,
"s": 3437,
"text": "We first need three things to implement Bayesian analysis.1. Data2. Generative Model3. Prior"
},
{
"code": null,
"e": 3651,
"s": 3530,
"text": "In my case, the data will be the batting average records from 2018 spring training. The data is simply what we observed."
},
{
"code": null,
"e": 4031,
"s": 3651,
"text": "A Generative Model is the model that generates data when given parameters as input. The parameters are values you’ll need to generate a distribution. For example, if you know the mean and the standard deviation, you can easily generate normally distributed data of your chosen size by running below code. We will see other types of distribution later to use in Bayesian analysis."
},
{
"code": null,
"e": 4177,
"s": 4031,
"text": "import matplotlib.pyplot as pltimport numpy as npmu, sigma = 0, 0.1 # mean and standard deviations = np.random.normal(mu, sigma, 1000)plt.hist(s)"
},
{
"code": null,
"e": 4291,
"s": 4177,
"text": "In the case of Bayesian analysis, we inverse the generative model and try to infer parameters with observed data."
},
{
"code": null,
"e": 4503,
"s": 4291,
"text": "Finally, Prior is the information that the model has before seeing the data. Is any probability equally likely? Or do we have some prior data that we can utilise? Or is there any educated guess that we can make?"
},
{
"code": null,
"e": 4679,
"s": 4503,
"text": "I will first define a function to scrape Fox Sports’ stats page for a player. I defined it as to be able to extract BATTING stats for either spring training or regular season."
},
{
"code": null,
"e": 5670,
"s": 4679,
"text": "import pandas as pdimport seaborn as snsimport requestsfrom bs4 import BeautifulSoupplt.style.use('fivethirtyeight')%matplotlib inline%config InlineBackend.figure_format = 'retina'def batting_stats(url,season): r = requests.get(url) soup = BeautifulSoup(r.text, 'lxml') table = soup.find_all(\"table\",{\"class\": \"wisbb_standardTable tablesorter\"})[0] table_head = soup.find_all(\"thead\",{\"class\": \"wisbb_tableHeader\"})[0] if season == 'spring': row_height = len(table.find_all('tr')[:-1]) else: row_height = len(table.find_all('tr')[:-2]) result_df = pd.DataFrame(columns=[row.text.strip() for row in table_head.find_all('th')], index = range(0,row_height)) row_marker = 0 for row in table.find_all('tr')[:-1]: column_marker = 0 columns = row.find_all('td') for column in columns: result_df.iat[row_marker,column_marker] = column.text.strip() column_marker += 1 row_marker += 1 return result_df"
},
{
"code": null,
"e": 5718,
"s": 5670,
"text": "Now let’s see who I should choose for analysis."
},
{
"code": null,
"e": 6126,
"s": 5718,
"text": "The above screen is spring training stats page for NY Mets (As I have already admitted, I know little about baseball, and I chose NY Mets because I liked the logo). If you arrange the players by their batting average (AVG), you can see Dominic Smith (DS) as the first, and Gavin Cecchini (GC) as the second. Are they good players? I don’t know. But by looking at the AVG only, DS is the best with 1.000 AVG."
},
{
"code": null,
"e": 6544,
"s": 6126,
"text": "But by some googling, I found out that “In recent years, the league-wide batting average has typically hovered around .260”. If so, then the AVG for DS and GC seems too high. By further looking at At-Bats (AB), Hits (H) of both players, it is clear that DS had only 1 AB and CS had 7. And also by looking further at AB for other players, the highest AB is 13 for 2018, and in 2017 the maximum AB is 60 within NY Mets."
},
{
"code": null,
"e": 6796,
"s": 6544,
"text": "Let’s assume that I know nothing about their past performance, and the only data I observed is 2018 spring training. And I don’t know what value range I should expect from AVG. Based on this, how should I interpret the stats from 2018 spring training?"
},
{
"code": null,
"e": 6843,
"s": 6796,
"text": "Let’s scrape the spring training stats for DS."
},
{
"code": null,
"e": 7012,
"s": 6843,
"text": "ds_url_st = \"https://www.foxsports.com/mlb/dominic-smith-player-stats?seasonType=3\"dominic_smith_spring = batting_stats(ds_url_st,'spring')dominic_smith_spring.iloc[-1]"
},
{
"code": null,
"e": 7218,
"s": 7012,
"text": "n_draw = 20000prior_ni = pd.Series(np.random.uniform(0, 1, size = n_draw)) plt.figure(figsize=(8,5))plt.hist(prior_ni)plt.title('Uniform distribution(0,1)')plt.xlabel('Prior on AVG')plt.ylabel('Frequency')"
},
{
"code": null,
"e": 7608,
"s": 7218,
"text": "The prior represents our beliefs before we see the data. In the above distribution, any probability is almost equally likely (There are slight differences due to the random generation). Thus this means I know nothing about the player, and I don’t even have any educated guess to make about AVG. I assume that 0.000 AVG is equally like as 1.000 AVG or any other probability between 0 and 1."
},
{
"code": null,
"e": 8024,
"s": 7608,
"text": "Now the data we observed says there was 1 AB, and 1 H, hence 1.000 AVG. This can be represented by Binomial distribution. A random variable X that has a binomial distribution represents the number of successes in a sequence of n independent yes/no trials, each of which yields success with probability p. In case of AVG, AVG is the probability of success, AB is the number of trials, and H is the number of success."
},
{
"code": null,
"e": 8091,
"s": 8024,
"text": "Keeping these in mind, we can define our inverse generative model."
},
{
"code": null,
"e": 8674,
"s": 8091,
"text": "We will randomly pick one probability value from the uniform distribution we defined, and use this value as a parameter for our generative model. Let’s say the value we randomly picked is 0.230, this means 23% chance of success in Binomial distribution. The number of trials is 1 (DS has 1 AB), and if the result of the generative model matches the result we observed (in this case, DS has 1 H), then we keep the probability value 0.230. If we repeat this generation and filtering, we will finally get a distribution of probability that has generated the same result as we observed."
},
{
"code": null,
"e": 8702,
"s": 8674,
"text": "This becomes our Posterior."
},
{
"code": null,
"e": 9456,
"s": 8702,
"text": "def posterior(n_try, k_success, prior): hit = list() for p in prior: hit.append(np.random.binomial(n_try, p)) posterior = prior[list(map(lambda x: x == k_success, hit))] plt.figure(figsize=(8,5)) plt.hist(posterior) plt.title('Posterior distribution') plt.xlabel('Posterior on AVG') plt.ylabel('Frequency') print('Number of draws left: %d, Posterior mean: %.3f, Posterior median: %.3f, Posterior 95%% quantile interval: %.3f-%.3f' % (len(posterior), posterior.mean(), posterior.median(), posterior.quantile(.025), posterior.quantile(.975)))ds_n_trials = int(dominic_smith_spring[['AB','H']].iloc[-1][0])ds_k_success = int(dominic_smith_spring[['AB','H']].iloc[-1][1])posterior(ds_n_trials, ds_k_success, prior_ni)"
},
{
"code": null,
"e": 9717,
"s": 9456,
"text": "95% quantile interval in posterior distribution is called credible interval and should be seen slightly different from confidence interval in Frequentists’ sense. There is another credible interval you can use, and I will get back to this when I mention Pymc3."
},
{
"code": null,
"e": 10558,
"s": 9717,
"text": "One major distinction between Bayesian’s credible interval and Frequentist’s confidence interval is their interpretation. The Bayesian probability reflects a person’s subjective beliefs. Following this approach, we can make the claim that true parameter is inside a credible interval with measurable probability. This property is appealing because it enables you to make a direct probability statement about parameters. Many people find this concept to be a more natural way of understanding a probability interval, which is also easier to explain. A confidence interval, on the other hand, enables you to make a claim that the interval covers the true parameter. If we gather a new sample, and calculate the confidence interval, and repeat this many times, 95% of those intervals we calculated will have true AVG value within the interval."
},
{
"code": null,
"e": 10693,
"s": 10558,
"text": "Credible Interval: “Given our observed data, there is a 95% probability that the true value of AVG falls within the credible interval”"
},
{
"code": null,
"e": 10871,
"s": 10693,
"text": "Confidence Interval: “There is a 95% probability that when I compute confidence interval from data of this sort, the true value of AVG will fall within the confidence interval.”"
},
{
"code": null,
"e": 11079,
"s": 10871,
"text": "Note the difference: the credible interval is a statement of probability about the parameter value given fixed bounds. The confidence interval is a probability about the bounds given a fixed parameter value."
},
{
"code": null,
"e": 11305,
"s": 11079,
"text": "Often in real-life, what we would like to know is about the true parameters not about the bounds, in that case, the Bayesian credible interval is the right way to go. In this case, we are interested in true AVG of the player."
},
{
"code": null,
"e": 11581,
"s": 11305,
"text": "With above posterior distribution, I am 95% certain that DS true AVG will be somewhere between 0.155 to 0.987. But that is a very broad statement to make. In other words, I am not quite certain about the true AVG of DS, after I observe just one trial with no prior knowledge."
},
{
"code": null,
"e": 11674,
"s": 11581,
"text": "For the second scenario, let’s assume that we know spring training stats from previous year."
},
{
"code": null,
"e": 11705,
"s": 11674,
"text": "dominic_smith_spring.iloc[-2:]"
},
{
"code": null,
"e": 11897,
"s": 11705,
"text": "Now we have 2017 spring training stats, and our prior should reflect this knowledge. This is not a uniform distribution anymore since we know that in 2017 spring training, DS’s AVG was 0.167."
},
{
"code": null,
"e": 12289,
"s": 11897,
"text": "The Beta distribution is a continuous probability distribution having two parameters, alpha and beta. One of its most common uses is to model one’s uncertainty about the probability of success of an experiment. In particular, the conditional distribution of X, conditional on having observed k successes out of n trials, is a Beta distribution with parameters k+1 as alpha and n−k+1 as beta."
},
{
"code": null,
"e": 12686,
"s": 12289,
"text": "n_draw = 20000prior_trials = int(dominic_smith_spring.iloc[3].AB)prior_success = int(dominic_smith_spring.iloc[3].H)prior_i = pd.Series(np.random.beta(prior_success+1, prior_trials-prior_success+1, size = n_draw)) plt.figure(figsize=(8,5))plt.hist(prior_i)plt.title('Beta distribution(a=%d, b=%d)' % (prior_success+1,prior_trials-prior_success+1))plt.xlabel('Prior on AVG')plt.ylabel('Frequency')"
},
{
"code": null,
"e": 12732,
"s": 12686,
"text": "posterior(ds_n_trials, ds_k_success, prior_i)"
},
{
"code": null,
"e": 13141,
"s": 12732,
"text": "The 95% quantile region has been narrowed compared to the posterior with the uniform prior in Scenario 1. Now I can say that I am 95% certain that the true AVG of DS will lie between 0.095 to 0.340. However, considering that above 0.300 AVG is often called best hitters, the statement means that the player can be either worst hitter or the best hitter. We need more data to narrow our region of credibility."
},
{
"code": null,
"e": 13329,
"s": 13141,
"text": "For this scenario, let’s assume that I not only have stats from 2017 spring training, but also stats from 2017 regular season. How does this affect my statement after I get the posterior?"
},
{
"code": null,
"e": 13563,
"s": 13329,
"text": "ds_url = \"https://www.foxsports.com/mlb/dominic-smith-player-stats?seasonType=1\"dominic_smith_reg = batting_stats(ds_url,'regular')dominic_smith = dominic_smith_reg.append(dominic_smith_spring.iloc[3], ignore_index=True)dominic_smith"
},
{
"code": null,
"e": 13992,
"s": 13563,
"text": "ds_prior_trials = pd.to_numeric(dominic_smith.AB).sum()ds_prior_success = pd.to_numeric(dominic_smith.H).sum()n_draw = 20000prior_i_02 = pd.Series(np.random.beta(ds_prior_success+1, ds_prior_trials-ds_prior_success+1, size = n_draw)) plt.figure(figsize=(8,5))plt.hist(prior_i_02)plt.title('Beta distribution(a=%d, b=%d)' % (ds_prior_success+1,ds_prior_trials-ds_prior_success+1))plt.xlabel('Prior on AVG')plt.ylabel('Frequency')"
},
{
"code": null,
"e": 14041,
"s": 13992,
"text": "posterior(ds_n_trials, ds_k_success, prior_i_02)"
},
{
"code": null,
"e": 14236,
"s": 14041,
"text": "Now I can say that I am 95% certain that the true AVG of DS will lie between 0.146 to 0.258. It may not be pin-point but compared to Scenario 1 and 2, the credible interval is much narrower now."
},
{
"code": null,
"e": 14471,
"s": 14236,
"text": "I want to compare two players and see who’s better in terms of AVG. The data I observed is result from 2018 spring training, and the prior knowledge I have is of 2017 spring training and regular season. Now I want to compare DS to GC."
},
{
"code": null,
"e": 14991,
"s": 14471,
"text": "Up until Scenario 3, I simulated the sampling by rejecting all the parameters which yielded the result different from what I observed. But this type of random sample generation and filtering is often computationally expensive, and slow to run. But luckily, there’s a tool that we can use to enable the sampler spends more time in regions of high probability, raising efficiency. Probabilistic programming tools such as Pymc3 can efficiently handle sampling procedure by making use of clever algorithms such as HMC-NUTS."
},
{
"code": null,
"e": 15063,
"s": 14991,
"text": "Let’s first start by scraping stats for Gavin Cecchini from Fox Sports."
},
{
"code": null,
"e": 15557,
"s": 15063,
"text": "gc_url_st = \"https://www.foxsports.com/mlb/gavin-cecchini-player-stats?seasonType=3\"gc_url_reg = \"https://www.foxsports.com/mlb/gavin-cecchini-player-stats?seasonType=1\"gavin_cecchini_spring = batting_stats(gc_url_st,'spring')gavin_cecchini_reg = batting_stats(gc_url_reg,'regular')gc_n_trials = int(gavin_cecchini_spring.iloc[1].AB)gc_k_success = int(gavin_cecchini_spring.iloc[1].H)gc_prior = pd.DataFrame(gavin_cecchini_reg.iloc[1]).transpose().append(gavin_cecchini_spring.iloc[0])gc_prior"
},
{
"code": null,
"e": 15965,
"s": 15557,
"text": "gc_prior_trials = pd.to_numeric(gc_prior.AB).sum()gc_prior_success = pd.to_numeric(gc_prior.H).sum()def observed_data_generator(n_try,observed_data): result = np.ones(observed_data) fails = n_try - observed_data result = np.append(result, np.zeros(fails)) return resultds_observed = observed_data_generator(ds_n_trials,ds_k_success)gc_observed = observed_data_generator(gc_n_trials,gc_k_success)"
},
{
"code": null,
"e": 16004,
"s": 15965,
"text": "Now we are ready to fit a Pymc3 model."
},
{
"code": null,
"e": 16513,
"s": 16004,
"text": "import pymc3 as pmwith pm.Model() as model_a: D_p = pm.Beta('DS_AVG', ds_prior_success+1, ds_prior_trials-ds_prior_success+1) G_p = pm.Beta('GC_AVG', gc_prior_success+1, gc_prior_trials-gc_prior_success+1) DS = pm.Bernoulli('DS', p=D_p, observed=ds_observed) GC = pm.Bernoulli('GC', p=G_p, observed=gc_observed) DvG = pm.Deterministic('DvG', D_p - G_p) start = pm.find_MAP() trace = pm.sample(10000, start=start)pm.plot_posterior(trace, varnames=['DS_AVG','GC_AVG','DvG'],ref_val=0)"
},
{
"code": null,
"e": 16923,
"s": 16513,
"text": "If we plot the posterior distributions of DS_AVG, GC_AVG, and DvG (DS_AVG — GC_AVG) using plot_posterior function in Pymc3, we see the term HPD instead of quantile. Highest Probability Density (HPD) interval is another type of credible interval we can use with posteriors. HPD interval chooses the narrowest interval, which will involve choosing those values of highest probability density including the mode."
},
{
"code": null,
"e": 17208,
"s": 16923,
"text": "Again I found another post by Rasmus Bååth provides an easy-to-understand visual comparison of quantile interval and highest density interval. Below are the mode and the highest density intervals covering 95% of the probability density for the six different posterior distributions."
},
{
"code": null,
"e": 17426,
"s": 17208,
"text": "The quantile interval includes the median, and having 50% of the probability to its left and 50% to its right and the quantile interval leaving, say, 2.5% probability on either side (in case of 95% credible interval)."
},
{
"code": null,
"e": 17619,
"s": 17426,
"text": "In the case of batting average for DS and GC, it looks like the mode and the median is not that different, and if so HPD interval will be similar to quantile interval. Let’s see how they look."
},
{
"code": null,
"e": 17637,
"s": 17619,
"text": "pm.summary(trace)"
},
{
"code": null,
"e": 17776,
"s": 17637,
"text": "We can see that both for DS and GC, HPD interval and quantile interval is either exactly the same or slightly different in decimal places."
},
{
"code": null,
"e": 18231,
"s": 17776,
"text": "The question I wanted to answer was who is the better player in terms of AVG, and I should say I can’t be certain. At least, I can’t be 95% certain that these two players are different in terms of AVG. The difference I calculated and plotted shows that the difference of AVG of two players (DS — GC, so if DvG is more positive then it means DS is better, else if DvG is more negative then it means GC is better), can be somewhere between -0.162 to 0.033."
},
{
"code": null,
"e": 18565,
"s": 18231,
"text": "This interval includes 0.000 which represents there is no difference between two players’ AVG. Thus, there is some evidence that GC is better than DS (since the DvG posterior distribution has a larger region in negative area than in the positive area), but I can’t be 95% certain that these two players are different in terms of AVG."
},
{
"code": null,
"e": 18877,
"s": 18565,
"text": "Maybe with more data, I might be able to be certain about their difference. After all, that is the essence of Bayesian thinking. It is not that the truth doesn’t exist, but it is that we can’t know it perfectly, and all we could hope to do is update our understanding as more and more evidence became available."
}
] |
How to install a certificate to the certificate store using PowerShell? | To install the certificate using PowerShell, we need to use the Import-Certificate command. For example, we have a certificate stored at the location C:\temp\Mycert.cer and we need to install it in the Personal store of the local machine.
Import-Certificate -FilePath C:\Temp\Mycert.cer `
-CertStoreLocation Cert:\LocalMachine\My\
You can also use the below method.
PS C:\> Set-Location Cert:\LocalMachine\My\
PS Cert:\LocalMachine\My\> Import-Certificate -FilePath C:\Temp\Mycert.cer
To install a certificate on the remote computer, use the Invoke-Command method.
Invoke-Command -ComputerName RemoteServer1 -ScriptBlock {Import-Certificate -FilePath C:\Temp\Mycert.cer `
-CertStoreLocation Cert:\LocalMachine\My\ }
The above command will install the certificate on RemoteServer1 from the path C:\temp of the remote server to the personal store of the remote machine. | [
{
"code": null,
"e": 1301,
"s": 1062,
"text": "To install the certificate using PowerShell, we need to use the Import-Certificate command. For example, we have a certificate stored at the location C:\\temp\\Mycert.cer and we need to install it in the Personal store of the local machine."
},
{
"code": null,
"e": 1396,
"s": 1301,
"text": "Import-Certificate -FilePath C:\\Temp\\Mycert.cer `\n -CertStoreLocation Cert:\\LocalMachine\\My\\"
},
{
"code": null,
"e": 1431,
"s": 1396,
"text": "You can also use the below method."
},
{
"code": null,
"e": 1550,
"s": 1431,
"text": "PS C:\\> Set-Location Cert:\\LocalMachine\\My\\\nPS Cert:\\LocalMachine\\My\\> Import-Certificate -FilePath C:\\Temp\\Mycert.cer"
},
{
"code": null,
"e": 1630,
"s": 1550,
"text": "To install a certificate on the remote computer, use the Invoke-Command method."
},
{
"code": null,
"e": 1785,
"s": 1630,
"text": "Invoke-Command -ComputerName RemoteServer1 -ScriptBlock {Import-Certificate -FilePath C:\\Temp\\Mycert.cer `\n -CertStoreLocation Cert:\\LocalMachine\\My\\ }"
},
{
"code": null,
"e": 1937,
"s": 1785,
"text": "The above command will install the certificate on RemoteServer1 from the path C:\\temp of the remote server to the personal store of the remote machine."
}
] |
DateTime.AddHours() Method in C# - GeeksforGeeks | 21 Jan, 2019
This method is used to return a new DateTime that adds the specified number of hours to the value of this instance.
Syntax:
public DateTime AddHours (double value);
Here, the value is the number of whole and fractional hours. The value parameter can be negative or positive.
Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the number of hours represented by value.
Exception: This method will give ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue.
Below programs illustrate the use of DateTime.AddDays(Double) Method:
Example 1:
// C# program to demonstrate the// DateTime.AddHours(Double) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // adding the 5.50 hours // using AddHours() method; DateTime date2 = date1.AddHours(5.50); // Display the date1 Console.WriteLine("DateTime before operation:"+ " {0:y} {0:dd}, {0:t}", date1); // Display the date2 Console.WriteLine("\nDateTime after operation: "+ "{0:y} {0:dd}, {0:t}", date2); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
DateTime before operation: 2010 January 01, 04:00
DateTime after operation: 2010 January 01, 09:30
Example 2: For ArgumentOutOfRangeException
// C# program to demonstrate the// DateTime.AddHours(Double) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime // and initialize with MinValue DateTime date1 = DateTime.MaxValue; // Display the date1 Console.WriteLine("DateTime before operation: "+ "{0:y} {0:dd}, {0:t}", date1); // adding the TimeSpan of 5 days // using AddHours() method; DateTime date2 = date1.AddHours(5); // Display the date2 System.Console.WriteLine("\nDateTime after operation:"+ " {0:y} {0:dd}, {0:t}", date2); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("\nThe resulting DateTime is "+ "greater than the DateTime.MaxValue "); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
DateTime before operation: 9999 December 31, 23:59
The resulting DateTime is greater than the DateTime.MaxValue
Exception Thrown: System.ArgumentOutOfRangeException
Note:
This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.
The fractional part of the value is the fractional part of a minute. For example, 7.5 is equivalent to 7 minutes, 30 seconds, 0 milliseconds, and 0 ticks.
The value parameter is rounded to the nearest millisecond.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addhours?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n21 Jan, 2019"
},
{
"code": null,
"e": 24418,
"s": 24302,
"text": "This method is used to return a new DateTime that adds the specified number of hours to the value of this instance."
},
{
"code": null,
"e": 24426,
"s": 24418,
"text": "Syntax:"
},
{
"code": null,
"e": 24467,
"s": 24426,
"text": "public DateTime AddHours (double value);"
},
{
"code": null,
"e": 24577,
"s": 24467,
"text": "Here, the value is the number of whole and fractional hours. The value parameter can be negative or positive."
},
{
"code": null,
"e": 24740,
"s": 24577,
"text": "Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the number of hours represented by value."
},
{
"code": null,
"e": 24875,
"s": 24740,
"text": "Exception: This method will give ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue."
},
{
"code": null,
"e": 24945,
"s": 24875,
"text": "Below programs illustrate the use of DateTime.AddDays(Double) Method:"
},
{
"code": null,
"e": 24956,
"s": 24945,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTime.AddHours(Double) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 1, 1, 4, 0, 15); // adding the 5.50 hours // using AddHours() method; DateTime date2 = date1.AddHours(5.50); // Display the date1 Console.WriteLine(\"DateTime before operation:\"+ \" {0:y} {0:dd}, {0:t}\", date1); // Display the date2 Console.WriteLine(\"\\nDateTime after operation: \"+ \"{0:y} {0:dd}, {0:t}\", date2); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 25908,
"s": 24956,
"text": null
},
{
"code": null,
"e": 26009,
"s": 25908,
"text": "DateTime before operation: 2010 January 01, 04:00\n\nDateTime after operation: 2010 January 01, 09:30\n"
},
{
"code": null,
"e": 26052,
"s": 26009,
"text": "Example 2: For ArgumentOutOfRangeException"
},
{
"code": "// C# program to demonstrate the// DateTime.AddHours(Double) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime // and initialize with MinValue DateTime date1 = DateTime.MaxValue; // Display the date1 Console.WriteLine(\"DateTime before operation: \"+ \"{0:y} {0:dd}, {0:t}\", date1); // adding the TimeSpan of 5 days // using AddHours() method; DateTime date2 = date1.AddHours(5); // Display the date2 System.Console.WriteLine(\"\\nDateTime after operation:\"+ \" {0:y} {0:dd}, {0:t}\", date2); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"\\nThe resulting DateTime is \"+ \"greater than the DateTime.MaxValue \"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 27139,
"s": 26052,
"text": null
},
{
"code": null,
"e": 27307,
"s": 27139,
"text": "DateTime before operation: 9999 December 31, 23:59\n\nThe resulting DateTime is greater than the DateTime.MaxValue \nException Thrown: System.ArgumentOutOfRangeException\n"
},
{
"code": null,
"e": 27313,
"s": 27307,
"text": "Note:"
},
{
"code": null,
"e": 27449,
"s": 27313,
"text": "This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation."
},
{
"code": null,
"e": 27604,
"s": 27449,
"text": "The fractional part of the value is the fractional part of a minute. For example, 7.5 is equivalent to 7 minutes, 30 seconds, 0 milliseconds, and 0 ticks."
},
{
"code": null,
"e": 27663,
"s": 27604,
"text": "The value parameter is rounded to the nearest millisecond."
},
{
"code": null,
"e": 27674,
"s": 27663,
"text": "Reference:"
},
{
"code": null,
"e": 27767,
"s": 27674,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addhours?view=netframework-4.7.2"
},
{
"code": null,
"e": 27790,
"s": 27767,
"text": "CSharp DateTime Struct"
},
{
"code": null,
"e": 27804,
"s": 27790,
"text": "CSharp-method"
},
{
"code": null,
"e": 27807,
"s": 27804,
"text": "C#"
},
{
"code": null,
"e": 27905,
"s": 27807,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27923,
"s": 27905,
"text": "Destructors in C#"
},
{
"code": null,
"e": 27946,
"s": 27923,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27974,
"s": 27946,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28014,
"s": 27974,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28057,
"s": 28014,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28079,
"s": 28057,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28096,
"s": 28079,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28112,
"s": 28096,
"text": "C# | List Class"
},
{
"code": null,
"e": 28162,
"s": 28112,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
Groovy - Continue Statement | The continue statement complements the break statement. Its use is restricted to while and for loops. When a continue statement is executed, control is immediately passed to the test condition of the nearest enclosing loop to determine whether the loop should continue. All subsequent statements in the body of the loop are ignored for that particular loop iteration.
The following diagram shows the diagrammatic explanation of the continue statement −
Following is an example of the continue statement −
class Example {
static void main(String[] args) {
int[] array = [0,1,2,3];
for(int i in array) {
if(i == 2)
continue;
println(i);
}
}
}
The output of the above code would be −
0
1
3
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2606,
"s": 2238,
"text": "The continue statement complements the break statement. Its use is restricted to while and for loops. When a continue statement is executed, control is immediately passed to the test condition of the nearest enclosing loop to determine whether the loop should continue. All subsequent statements in the body of the loop are ignored for that particular loop iteration."
},
{
"code": null,
"e": 2691,
"s": 2606,
"text": "The following diagram shows the diagrammatic explanation of the continue statement −"
},
{
"code": null,
"e": 2743,
"s": 2691,
"text": "Following is an example of the continue statement −"
},
{
"code": null,
"e": 2933,
"s": 2743,
"text": "class Example {\n static void main(String[] args) {\n int[] array = [0,1,2,3];\n\t\t\n for(int i in array) {\n if(i == 2)\n continue;\n println(i);\n }\n }\n}"
},
{
"code": null,
"e": 2973,
"s": 2933,
"text": "The output of the above code would be −"
},
{
"code": null,
"e": 2982,
"s": 2973,
"text": "0 \n1 \n3\n"
},
{
"code": null,
"e": 3015,
"s": 2982,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3033,
"s": 3015,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 3068,
"s": 3033,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3086,
"s": 3068,
"text": " Packt Publishing"
},
{
"code": null,
"e": 3093,
"s": 3086,
"text": " Print"
},
{
"code": null,
"e": 3104,
"s": 3093,
"text": " Add Notes"
}
] |
Audio processing using Pydub and Google Speech Recognition API in Python | In this tutorial, we are going to work with the audio files. We will breakdown the audio into chunks to recognize the content in it. We will store the content of the audio files in text files as well. Install the following modules using the below commands.
pip install pydub
If you run the above command, you will get the following successful message
Collecting pydub
Downloading https://files.pythonhosted.org/packages/79/db/eaf620b73a1eec3c8c6f8f5
b0b236a50f9da88ad57802154b7ba7664d0b8/pydub-0.23.1-py2.py3-none-any.whl
Installing collected packages: pydub
Successfully installed pydub-0.23.1
pip install audioread
If you run the above command, you will get the following successful message.
Collecting audioread
Downloading https://files.pythonhosted.org/packages/2e/0b/940ea7861e0e9049f09dcfd
72a90c9ae55f697c17c299a323f0148f913d2/audioread-2.1.8.tar.gz
Building wheels for collected packages: audioread
Building wheel for audioread (setup.py): started
Building wheel for audioread (setup.py): finished with status 'done'
Created wheel for audioread: filename=audioread-2.1.8-cp37-none-any.whl size=2309
8 sha256=92b6f46d6b4726e7a13233dc9d84744ba74e23187123e67f663650f24390dc9d
Stored in directory: C:\Users\hafeezulkareem\AppData\Local\pip\Cache\wheels\b9\64
\09\0b6417df9d8ba8bc61a7d2553c5cebd714ec169644c88fc012
Successfully built audioread
Installing collected packages: audioread
Successfully installed audioread-2.1.8
pip install SpeechRecognition
If you run the above command, you will get the following successful message.
Collecting SpeechRecognition
Downloading https://files.pythonhosted.org/packages/26/e1/7f5678cd94ec1234269d237
56dbdaa4c8cfaed973412f88ae8adf7893a50/SpeechRecognition-3.8.1-py2.py3-none-any.whl
(32.8MB)
Installing collected packages: SpeechRecognition
Successfully installed SpeechRecognition-3.8.1
We have two steps in the process.
Breaking the audio into chunks.
Breaking the audio into chunks.
We have to extract the content using SpeechRecognition.
We have to extract the content using SpeechRecognition.
Take one audio file from your library. Let's start the code.
# importing the module
import pydub
import speech_recognition
# getting the audio file
audio = pydub.AudioSegment.from_wav('audio.wav')
# length of the audio in milliseconds
audio_length = len(audio)
print(f'Audio Length: {audio_length}')
# chunk counter
chunk_counter = 1
audio_text = open('audio_text.txt', 'w+')
# setting where to slice the audio
point = 60000
# overlap - remaining audio after slicing
rem = 8000
# initialising variables to track chunks and ending
flag = 0
start = 0
end = 0
# iterating through the audio with incrementing of rem
for i in range(0, 2 * audio_length, point):
# in first iteration end = rem
if i == 0:
start = 0
end = point
else:
# other iterations
start = end - rem
end = start + point
# if end is greater than audio_length
if end >= audio_length:
end = audio_length
# to indicate stop
flag = 1
# getting a chunk from the audio
chunk = audio[start:end]
# chunk name
chunk_name = f'chunk_{chunk_counter}'
# storing the chunk to local storage
chunk.export(chunk_name, format = 'wav')
# printing the chunk
print(f'{chunk_name} start: {start} end: {end}')
# incrementing chunk counter
chunk_counter += 1
# recognising text from the audio
# initialising the recognizer
recognizer = speech_recognition.Recognizer()
# creating a listened audio
with speech_recognition.AudioFile(chunk_name) as chunk_audio:
chunk_listened = recognizer.listen(chunk_audio)
# recognizing content from the audio
try:
# getting content from the chunk
content = recognizer.recognize_google(chunk_listened)
# writing to the file
audio_text.write(content + '\n')
# if not recognized
except speech_recognition.UnknownValueError:
print('Audio is not recognized')
# internet error
except speech_recognition.RequestError as Error:
print('Can\'t connect to the internet')
# checking the flag
if flag == 1:
audio_text.close()
break
If you run the above code, you will get the following results.
Audio Length: 480052
chunk_1 start: 0 end: 60000
chunk_2 start: 52000 end: 112000
chunk_3 start: 104000 end: 164000
chunk_4 start: 156000 end: 216000
chunk_5 start: 208000 end: 268000
chunk_6 start: 260000 end: 320000
chunk_7 start: 312000 end: 372000
chunk_8 start: 364000 end: 424000
chunk_9 start: 416000 end: 476000
chunk_10 start: 468000 end: 480052
Checking the file content.
# opening the file in read mode
with open('audio_text.txt', 'r') as file:
print(file.read())
If you run the above code, you will get the following result.
English and I am here in San Francisco I am back in San Francisco last week we were
in Texas at a teaching country and The Reader of the teaching conference was a plan
e Re
improve teaching as a result you are
house backup file with bad it had some
English is coming soon one day only time
12 o1 a.m.
everything about her English now or powering on my email list
sports in your city check your email email
Harjeet girlfriend
next Tuesday
checking the year enjoying office English keep listening keep smiling keep enjoying
your English learning
If you have any doubts regarding the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1319,
"s": 1062,
"text": "In this tutorial, we are going to work with the audio files. We will breakdown the audio into chunks to recognize the content in it. We will store the content of the audio files in text files as well. Install the following modules using the below commands."
},
{
"code": null,
"e": 1337,
"s": 1319,
"text": "pip install pydub"
},
{
"code": null,
"e": 1413,
"s": 1337,
"text": "If you run the above command, you will get the following successful message"
},
{
"code": null,
"e": 1657,
"s": 1413,
"text": "Collecting pydub\nDownloading https://files.pythonhosted.org/packages/79/db/eaf620b73a1eec3c8c6f8f5\nb0b236a50f9da88ad57802154b7ba7664d0b8/pydub-0.23.1-py2.py3-none-any.whl\nInstalling collected packages: pydub\nSuccessfully installed pydub-0.23.1"
},
{
"code": null,
"e": 1679,
"s": 1657,
"text": "pip install audioread"
},
{
"code": null,
"e": 1756,
"s": 1679,
"text": "If you run the above command, you will get the following successful message."
},
{
"code": null,
"e": 2490,
"s": 1756,
"text": "Collecting audioread\nDownloading https://files.pythonhosted.org/packages/2e/0b/940ea7861e0e9049f09dcfd\n72a90c9ae55f697c17c299a323f0148f913d2/audioread-2.1.8.tar.gz\nBuilding wheels for collected packages: audioread\nBuilding wheel for audioread (setup.py): started\nBuilding wheel for audioread (setup.py): finished with status 'done'\nCreated wheel for audioread: filename=audioread-2.1.8-cp37-none-any.whl size=2309\n8 sha256=92b6f46d6b4726e7a13233dc9d84744ba74e23187123e67f663650f24390dc9d\nStored in directory: C:\\Users\\hafeezulkareem\\AppData\\Local\\pip\\Cache\\wheels\\b9\\64\n\\09\\0b6417df9d8ba8bc61a7d2553c5cebd714ec169644c88fc012\nSuccessfully built audioread\nInstalling collected packages: audioread\nSuccessfully installed audioread-2.1.8"
},
{
"code": null,
"e": 2520,
"s": 2490,
"text": "pip install SpeechRecognition"
},
{
"code": null,
"e": 2597,
"s": 2520,
"text": "If you run the above command, you will get the following successful message."
},
{
"code": null,
"e": 2896,
"s": 2597,
"text": "Collecting SpeechRecognition\nDownloading https://files.pythonhosted.org/packages/26/e1/7f5678cd94ec1234269d237\n56dbdaa4c8cfaed973412f88ae8adf7893a50/SpeechRecognition-3.8.1-py2.py3-none-any.whl\n(32.8MB)\nInstalling collected packages: SpeechRecognition\nSuccessfully installed SpeechRecognition-3.8.1"
},
{
"code": null,
"e": 2930,
"s": 2896,
"text": "We have two steps in the process."
},
{
"code": null,
"e": 2962,
"s": 2930,
"text": "Breaking the audio into chunks."
},
{
"code": null,
"e": 2994,
"s": 2962,
"text": "Breaking the audio into chunks."
},
{
"code": null,
"e": 3050,
"s": 2994,
"text": "We have to extract the content using SpeechRecognition."
},
{
"code": null,
"e": 3106,
"s": 3050,
"text": "We have to extract the content using SpeechRecognition."
},
{
"code": null,
"e": 3167,
"s": 3106,
"text": "Take one audio file from your library. Let's start the code."
},
{
"code": null,
"e": 5180,
"s": 3167,
"text": "# importing the module\nimport pydub\nimport speech_recognition\n# getting the audio file\naudio = pydub.AudioSegment.from_wav('audio.wav')\n# length of the audio in milliseconds\naudio_length = len(audio)\nprint(f'Audio Length: {audio_length}')\n# chunk counter\nchunk_counter = 1\naudio_text = open('audio_text.txt', 'w+')\n# setting where to slice the audio\npoint = 60000\n# overlap - remaining audio after slicing\nrem = 8000\n# initialising variables to track chunks and ending\nflag = 0\nstart = 0\nend = 0\n# iterating through the audio with incrementing of rem\nfor i in range(0, 2 * audio_length, point):\n # in first iteration end = rem\n if i == 0:\n start = 0\n end = point\n else:\n # other iterations\n start = end - rem\n end = start + point\n # if end is greater than audio_length\n if end >= audio_length:\n end = audio_length\n # to indicate stop\n flag = 1\n # getting a chunk from the audio\n chunk = audio[start:end]\n # chunk name\n chunk_name = f'chunk_{chunk_counter}'\n # storing the chunk to local storage\n chunk.export(chunk_name, format = 'wav')\n # printing the chunk\n print(f'{chunk_name} start: {start} end: {end}')\n # incrementing chunk counter\n chunk_counter += 1\n # recognising text from the audio\n # initialising the recognizer\n recognizer = speech_recognition.Recognizer()\n # creating a listened audio\n with speech_recognition.AudioFile(chunk_name) as chunk_audio:\n chunk_listened = recognizer.listen(chunk_audio)\n # recognizing content from the audio\n try:\n # getting content from the chunk\n content = recognizer.recognize_google(chunk_listened)\n # writing to the file\n audio_text.write(content + '\\n')\n # if not recognized\n except speech_recognition.UnknownValueError:\n print('Audio is not recognized')\n # internet error\n except speech_recognition.RequestError as Error:\n print('Can\\'t connect to the internet')\n # checking the flag\n if flag == 1:\n audio_text.close()\n break"
},
{
"code": null,
"e": 5243,
"s": 5180,
"text": "If you run the above code, you will get the following results."
},
{
"code": null,
"e": 5598,
"s": 5243,
"text": "Audio Length: 480052\nchunk_1 start: 0 end: 60000\nchunk_2 start: 52000 end: 112000\nchunk_3 start: 104000 end: 164000\nchunk_4 start: 156000 end: 216000\nchunk_5 start: 208000 end: 268000\nchunk_6 start: 260000 end: 320000\nchunk_7 start: 312000 end: 372000\nchunk_8 start: 364000 end: 424000\nchunk_9 start: 416000 end: 476000\nchunk_10 start: 468000 end: 480052"
},
{
"code": null,
"e": 5625,
"s": 5598,
"text": "Checking the file content."
},
{
"code": null,
"e": 5721,
"s": 5625,
"text": "# opening the file in read mode\nwith open('audio_text.txt', 'r') as file:\n print(file.read())"
},
{
"code": null,
"e": 5783,
"s": 5721,
"text": "If you run the above code, you will get the following result."
},
{
"code": null,
"e": 6327,
"s": 5783,
"text": "English and I am here in San Francisco I am back in San Francisco last week we were\nin Texas at a teaching country and The Reader of the teaching conference was a plan\ne Re\nimprove teaching as a result you are\nhouse backup file with bad it had some\nEnglish is coming soon one day only time\n12 o1 a.m.\neverything about her English now or powering on my email list\nsports in your city check your email email\nHarjeet girlfriend\nnext Tuesday\nchecking the year enjoying office English keep listening keep smiling keep enjoying\nyour English learning"
},
{
"code": null,
"e": 6411,
"s": 6327,
"text": "If you have any doubts regarding the tutorial, mention them in the comment section."
}
] |
Root to Leaf Paths | Practice | GeeksforGeeks | Given a Binary Tree of size N, you need to find all the possible paths from root node to all the leaf node's of the binary tree.
Example 1:
Input:
1
/ \
2 3
Output: 1 2 #1 3 #
Explanation:
All possible paths:
1->2
1->3
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output: 10 20 40 #10 20 60 #10 30 #
Your Task:
Your task is to complete the function Paths() that takes the root node as an argument and return all the possible path. (All the path are printed '#' separated by the driver's code.)
Note: The return type
cpp: vector
java: ArrayList>
python: list of list
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(H).
Note: H is the height of the tree.
Constraints:
1<=N<=103
Note: The Input/Ouput format and Example given, are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.
+1
keshavlad212 weeks ago
class Tree{
ArrayList<ArrayList<Integer>>ans=new ArrayList<>();
ArrayList<Integer>temp=new ArrayList<>();
public ArrayList<ArrayList<Integer>> Paths(Node root){
path(root);
return ans;
}
public void path(Node root){
if(root == null ){
return ;
}
temp.add(root.data);
if(root.left==null && root.right == null){
ans.add(new ArrayList<Integer>(temp));
}
path(root.left);
path(root.right);
temp.remove(temp.size()-1); // while going back remove //last element from arrayList
}
}
0
hk22578533 weeks ago
simple c++ soln
void getpaths(Node* root, vector<int> &path, vector<vector<int>> &res)
{
if(root == NULL) return;
path.push_back(root->data);
if(!root->left && !root->right)
{
res.push_back(path);
}
getpaths(root->left, path, res);
getpaths(root->right, path, res);
path.pop_back();
}
vector<vector<int>> Paths(Node* root)
{
vector<int> path;
vector<vector<int>> res;
getpaths(root, path, res);
return res;
}
0
amishasahu3281 month ago
void solve(Node *node, vector<vector<int>> &ans, vector<int> &v)
{
if(node == NULL)
return;
v.push_back(node->data);
if(node->left == NULL && node->right == NULL)
{
ans.push_back(v);
v.pop_back();
return;
}
solve(node->left, ans, v);
solve(node->right, ans, v);
v.pop_back();
return;
}
vector<vector<int>> Paths(Node* root)
{
// Code here
vector<vector<int>> ans;
vector<int> v;
solve(root, ans, v);
return ans;
}
0
moryasivam1 month ago
void bb(Node* root,vector<vector<int>>&v1,vector<int>v){ if(!root) return ; v.push_back(root->data); if(!root->left && !root->right){ v1.push_back(v); v.pop_back(); return ; } bb(root->left,v1,v); bb(root->right,v1,v); return ;}
vector<vector<int>> Paths(Node* root){ vector<int>v; vector<vector<int>>v1; if(!root) return v1; bb(root,v1,v); return v1;}
0
ranjanchinmoy1 month ago
What is wrong with this code???
vector<vector<int>>ans;
void dfs(Node* node,vector<int>curr)
{
if(node==NULL)
return;
curr.push_back(node->data);
if(node->left==NULL && node->right==NULL)
{
ans.push_back(curr);
}
dfs(node->left,curr);
dfs(node->right,curr);
curr.pop_back();
}
vector<vector<int>> Paths(Node* root)
{
vector<int>curr;
dfs(root,curr);
return ans;
}
0
owaischem2 months ago
PYTHON SOLUTION:
TIME TAKEN:0.2/1.4
def Paths(root): def traversal(root): if root==None: return None stack.append(root.data) if root.left: traversal(root.left) if root.left==None and root.right==None: list1.append(stack.copy()) if root.right: traversal(root.right) stack.pop() list1=[] stack=[] traversal(root) return list1
+1
deepakjoshicscoder2 months ago
C++ SOLUTION:
void solve(Node* root , vector<vector<int>> &v1 , vector<int> &v ){ if(!root){ return; } v.push_back(root->data); if(!root->left and !root->right){ v1.push_back(v); v.pop_back(); return; } solve(root->left , v1 , v); solve(root->right , v1 , v); v.pop_back(); return;}vector<vector<int>> Paths(Node* root){ // Code here vector<vector<int>> v1; vector<int> v; if(!root) return v1; solve(root , v1 , v); return v1;
}
+1
tarun2002ts0213 months ago
void solve(Node* root,vector<vector<int>>&v1,vector<int>&v){ if(root==NULL) return; v.push_back(root->data); if(!root->left && !root->right) { v1.push_back(v); v.pop_back(); return; } solve(root->left,v1,v); solve(root->right,v1,v); v.pop_back(); return;}vector<vector<int>> Paths(Node* root){ // Code here vector<vector<int>>v1; if(root==NULL) return v1; vector<int>v; solve(root,v1,v); return v1;}
-1
shiva10903 months ago
void printPaths(Node* root , vector<int> &v , vector<vector<int>>& ans)
{
if(root == NULL)return;
if(root->left == NULL && root->right == NULL)
{
ans.push_back(v);
if(v.size() > 0)
v.pop_back();
return;
}
printPaths(root->left , v , ans);
printPaths(root->right , v , ans);
if(v.size() > 0)
v.pop_back();
return;
}
vector<vector<int>> Paths(Node* root)
{
// Code here
vector<vector<int>> ans;
vector<int> v;
printPaths(root , v , ans);
return ans;
}
0
anirudh1587cse194 months ago
void put(Node*root,vector<vector<int>>&v,vector<int>&v1){ if(root==NULL) { return; } v1.push_back(root->data); if(root->left==NULL&&root->right==NULL) { v.push_back(v1); v1.pop_back(); return; } put(root->left,v,v1); put(root->right,v,v1); v1.pop_back(); return; }vector<vector<int>> Paths(Node* root){ // Code here vector<vector<int>>v; vector<int>v1; put(root,v,v1); return v;}
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": 367,
"s": 238,
"text": "Given a Binary Tree of size N, you need to find all the possible paths from root node to all the leaf node's of the binary tree."
},
{
"code": null,
"e": 378,
"s": 367,
"text": "Example 1:"
},
{
"code": null,
"e": 484,
"s": 378,
"text": "Input:\n 1\n / \\\n 2 3\nOutput: 1 2 #1 3 #\nExplanation: \nAll possible paths:\n1->2\n1->3\n\n"
},
{
"code": null,
"e": 495,
"s": 484,
"text": "Example 2:"
},
{
"code": null,
"e": 603,
"s": 495,
"text": "Input:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput: 10 20 40 #10 20 60 #10 30 #\n\n"
},
{
"code": null,
"e": 797,
"s": 603,
"text": "Your Task:\nYour task is to complete the function Paths() that takes the root node as an argument and return all the possible path. (All the path are printed '#' separated by the driver's code.)"
},
{
"code": null,
"e": 869,
"s": 797,
"text": "Note: The return type\ncpp: vector\njava: ArrayList>\npython: list of list"
},
{
"code": null,
"e": 968,
"s": 869,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(H).\nNote: H is the height of the tree."
},
{
"code": null,
"e": 991,
"s": 968,
"text": "Constraints:\n1<=N<=103"
},
{
"code": null,
"e": 1310,
"s": 991,
"text": "Note: The Input/Ouput format and Example given, are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1313,
"s": 1310,
"text": "+1"
},
{
"code": null,
"e": 1336,
"s": 1313,
"text": "keshavlad212 weeks ago"
},
{
"code": null,
"e": 1964,
"s": 1336,
"text": "class Tree{\n ArrayList<ArrayList<Integer>>ans=new ArrayList<>();\n ArrayList<Integer>temp=new ArrayList<>();\n public ArrayList<ArrayList<Integer>> Paths(Node root){\n path(root);\n return ans;\n }\n public void path(Node root){\n if(root == null ){\n return ;\n }\n temp.add(root.data);\n if(root.left==null && root.right == null){\n ans.add(new ArrayList<Integer>(temp));\n }\n path(root.left);\n path(root.right);\n temp.remove(temp.size()-1); // while going back remove \t\t\t \t\t//last element from arrayList\n \n }\n \n}"
},
{
"code": null,
"e": 1966,
"s": 1964,
"text": "0"
},
{
"code": null,
"e": 1987,
"s": 1966,
"text": "hk22578533 weeks ago"
},
{
"code": null,
"e": 2003,
"s": 1987,
"text": "simple c++ soln"
},
{
"code": null,
"e": 2472,
"s": 2003,
"text": " void getpaths(Node* root, vector<int> &path, vector<vector<int>> &res)\n {\n if(root == NULL) return;\n path.push_back(root->data);\n if(!root->left && !root->right)\n {\n res.push_back(path);\n }\n \n getpaths(root->left, path, res);\n getpaths(root->right, path, res);\n path.pop_back();\n }\n \nvector<vector<int>> Paths(Node* root)\n{\n vector<int> path;\n vector<vector<int>> res;\n getpaths(root, path, res);\n return res;\n}"
},
{
"code": null,
"e": 2474,
"s": 2472,
"text": "0"
},
{
"code": null,
"e": 2499,
"s": 2474,
"text": "amishasahu3281 month ago"
},
{
"code": null,
"e": 3012,
"s": 2499,
"text": "void solve(Node *node, vector<vector<int>> &ans, vector<int> &v)\n {\n if(node == NULL)\n return;\n v.push_back(node->data);\n if(node->left == NULL && node->right == NULL)\n {\n ans.push_back(v);\n v.pop_back();\n return;\n }\n solve(node->left, ans, v);\n solve(node->right, ans, v);\n v.pop_back();\n return;\n }\nvector<vector<int>> Paths(Node* root)\n{\n // Code here\n vector<vector<int>> ans;\n vector<int> v;\n solve(root, ans, v);\n return ans;\n}"
},
{
"code": null,
"e": 3014,
"s": 3012,
"text": "0"
},
{
"code": null,
"e": 3036,
"s": 3014,
"text": "moryasivam1 month ago"
},
{
"code": null,
"e": 3325,
"s": 3036,
"text": "void bb(Node* root,vector<vector<int>>&v1,vector<int>v){ if(!root) return ; v.push_back(root->data); if(!root->left && !root->right){ v1.push_back(v); v.pop_back(); return ; } bb(root->left,v1,v); bb(root->right,v1,v); return ;}"
},
{
"code": null,
"e": 3454,
"s": 3325,
"text": "vector<vector<int>> Paths(Node* root){ vector<int>v; vector<vector<int>>v1; if(!root) return v1; bb(root,v1,v); return v1;}"
},
{
"code": null,
"e": 3456,
"s": 3454,
"text": "0"
},
{
"code": null,
"e": 3481,
"s": 3456,
"text": "ranjanchinmoy1 month ago"
},
{
"code": null,
"e": 3514,
"s": 3481,
"text": "What is wrong with this code??? "
},
{
"code": null,
"e": 3918,
"s": 3514,
"text": "vector<vector<int>>ans;\n void dfs(Node* node,vector<int>curr)\n {\n if(node==NULL)\n return;\n curr.push_back(node->data);\n if(node->left==NULL && node->right==NULL)\n {\n ans.push_back(curr);\n }\n dfs(node->left,curr);\n dfs(node->right,curr);\n curr.pop_back();\n }\nvector<vector<int>> Paths(Node* root)\n{\n vector<int>curr;\n dfs(root,curr);\n return ans;\n}"
},
{
"code": null,
"e": 3920,
"s": 3918,
"text": "0"
},
{
"code": null,
"e": 3942,
"s": 3920,
"text": "owaischem2 months ago"
},
{
"code": null,
"e": 3959,
"s": 3942,
"text": "PYTHON SOLUTION:"
},
{
"code": null,
"e": 3978,
"s": 3959,
"text": "TIME TAKEN:0.2/1.4"
},
{
"code": null,
"e": 4403,
"s": 3980,
"text": "def Paths(root): def traversal(root): if root==None: return None stack.append(root.data) if root.left: traversal(root.left) if root.left==None and root.right==None: list1.append(stack.copy()) if root.right: traversal(root.right) stack.pop() list1=[] stack=[] traversal(root) return list1"
},
{
"code": null,
"e": 4406,
"s": 4403,
"text": "+1"
},
{
"code": null,
"e": 4437,
"s": 4406,
"text": "deepakjoshicscoder2 months ago"
},
{
"code": null,
"e": 4451,
"s": 4437,
"text": "C++ SOLUTION:"
},
{
"code": null,
"e": 4921,
"s": 4451,
"text": "void solve(Node* root , vector<vector<int>> &v1 , vector<int> &v ){ if(!root){ return; } v.push_back(root->data); if(!root->left and !root->right){ v1.push_back(v); v.pop_back(); return; } solve(root->left , v1 , v); solve(root->right , v1 , v); v.pop_back(); return;}vector<vector<int>> Paths(Node* root){ // Code here vector<vector<int>> v1; vector<int> v; if(!root) return v1; solve(root , v1 , v); return v1;"
},
{
"code": null,
"e": 4923,
"s": 4921,
"text": "}"
},
{
"code": null,
"e": 4926,
"s": 4923,
"text": "+1"
},
{
"code": null,
"e": 4953,
"s": 4926,
"text": "tarun2002ts0213 months ago"
},
{
"code": null,
"e": 5415,
"s": 4953,
"text": "void solve(Node* root,vector<vector<int>>&v1,vector<int>&v){ if(root==NULL) return; v.push_back(root->data); if(!root->left && !root->right) { v1.push_back(v); v.pop_back(); return; } solve(root->left,v1,v); solve(root->right,v1,v); v.pop_back(); return;}vector<vector<int>> Paths(Node* root){ // Code here vector<vector<int>>v1; if(root==NULL) return v1; vector<int>v; solve(root,v1,v); return v1;}"
},
{
"code": null,
"e": 5418,
"s": 5415,
"text": "-1"
},
{
"code": null,
"e": 5440,
"s": 5418,
"text": "shiva10903 months ago"
},
{
"code": null,
"e": 6005,
"s": 5440,
"text": "void printPaths(Node* root , vector<int> &v , vector<vector<int>>& ans)\n{\n if(root == NULL)return;\n \n if(root->left == NULL && root->right == NULL)\n {\n ans.push_back(v);\n if(v.size() > 0)\n v.pop_back();\n return;\n }\n \n printPaths(root->left , v , ans);\n printPaths(root->right , v , ans);\n \n if(v.size() > 0)\n v.pop_back();\n \n return;\n}\nvector<vector<int>> Paths(Node* root)\n{\n // Code here\n vector<vector<int>> ans;\n vector<int> v;\n \n printPaths(root , v , ans);\n return ans;\n}\n"
},
{
"code": null,
"e": 6007,
"s": 6005,
"text": "0"
},
{
"code": null,
"e": 6036,
"s": 6007,
"text": "anirudh1587cse194 months ago"
},
{
"code": null,
"e": 6477,
"s": 6036,
"text": "void put(Node*root,vector<vector<int>>&v,vector<int>&v1){ if(root==NULL) { return; } v1.push_back(root->data); if(root->left==NULL&&root->right==NULL) { v.push_back(v1); v1.pop_back(); return; } put(root->left,v,v1); put(root->right,v,v1); v1.pop_back(); return; }vector<vector<int>> Paths(Node* root){ // Code here vector<vector<int>>v; vector<int>v1; put(root,v,v1); return v;}"
},
{
"code": null,
"e": 6623,
"s": 6477,
"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": 6659,
"s": 6623,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6669,
"s": 6659,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6679,
"s": 6669,
"text": "\nContest\n"
},
{
"code": null,
"e": 6742,
"s": 6679,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6890,
"s": 6742,
"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": 7098,
"s": 6890,
"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": 7204,
"s": 7098,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Static Variables in C | Static variables are initialized only once. The compiler persists with the variable till the end of the program. Static variables can be defined inside or outside the function. They are local to the block. The default value of static variables is zero. The static variables are alive till the execution of the program.
Here is the syntax of static variables in C language,
static datatype variable_name = value;
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
value − Any value to initialize the variable. By default, it is zero.
Here is an example of static variable in C language,
Live Demo
#include <stdio.h>
int main() {
auto int a = -28;
static int b = 8;
printf("The value of auto variable : %d\n", a);
printf("The value of static variable b : %d\n",b);
if(a!=0)
printf("The sum of static variable and auto variable : %d\n",(b+a));
return 0;
}
Here is the output
The value of auto variable : -28
The value of static variable b : 8
The sum of static variable and auto variable : -20 | [
{
"code": null,
"e": 1381,
"s": 1062,
"text": "Static variables are initialized only once. The compiler persists with the variable till the end of the program. Static variables can be defined inside or outside the function. They are local to the block. The default value of static variables is zero. The static variables are alive till the execution of the program."
},
{
"code": null,
"e": 1435,
"s": 1381,
"text": "Here is the syntax of static variables in C language,"
},
{
"code": null,
"e": 1474,
"s": 1435,
"text": "static datatype variable_name = value;"
},
{
"code": null,
"e": 1480,
"s": 1474,
"text": "Here,"
},
{
"code": null,
"e": 1543,
"s": 1480,
"text": "datatype − The datatype of variable like int, char, float etc."
},
{
"code": null,
"e": 1603,
"s": 1543,
"text": "variable_name − This is the name of variable given by user."
},
{
"code": null,
"e": 1673,
"s": 1603,
"text": "value − Any value to initialize the variable. By default, it is zero."
},
{
"code": null,
"e": 1726,
"s": 1673,
"text": "Here is an example of static variable in C language,"
},
{
"code": null,
"e": 1737,
"s": 1726,
"text": " Live Demo"
},
{
"code": null,
"e": 2019,
"s": 1737,
"text": "#include <stdio.h>\n\nint main() {\n auto int a = -28;\n static int b = 8;\n\n printf(\"The value of auto variable : %d\\n\", a);\n printf(\"The value of static variable b : %d\\n\",b);\n\n if(a!=0)\n printf(\"The sum of static variable and auto variable : %d\\n\",(b+a));\n\n return 0;\n}"
},
{
"code": null,
"e": 2038,
"s": 2019,
"text": "Here is the output"
},
{
"code": null,
"e": 2157,
"s": 2038,
"text": "The value of auto variable : -28\nThe value of static variable b : 8\nThe sum of static variable and auto variable : -20"
}
] |
ByteBuffer flip() methods in Java with Examples - GeeksforGeeks | 27 Jun, 2019
The flip() method of java.nio.ByteBuffer Class is used to flip this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations.
For example:
buf.put(magic); // Prepend header
in.read(buf); // Read data into rest of buffer
buf.flip(); // Flip buffer
out.write(buf); // Write header + data to channel
This method is often used in conjunction with the compact method when transferring data from one place to another.
Syntax:
public ByteBuffer flip()
Return Value: This method returns this buffer.
Below are the examples to illustrate the flip() method:
Examples 1:
// Java program to demonstrate// flip() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the byte array byte[] bb = { 10, 20, 30 }; // wrap the byte array into floatBuffer // using wrap() method ByteBuffer byteBuffer = ByteBuffer.wrap(bb); // set position at index 1 byteBuffer.position(1); // print the byte buffer System.out.println("ByteBuffer before flip: " + Arrays.toString(byteBuffer.array()) + "\nPosition: " + byteBuffer.position() + "\nLimit: " + byteBuffer.limit()); // Flip the byteBuffer // using flip() method byteBuffer.flip(); // print the byte buffer System.out.println("\nByteBuffer after flip: " + Arrays.toString(byteBuffer.array()) + "\nPosition: " + byteBuffer.position() + "\nLimit: " + byteBuffer.limit()); }}
ByteBuffer before flip: [10, 20, 30]
Position: 1
Limit: 3
ByteBuffer after flip: [10, 20, 30]
Position: 0
Limit: 1
ByteBuffer before flip: [10, 20, 30]
Position: 1
Limit: 3
ByteBuffer after flip: [10, 20, 30]
Position: 0
Limit: 1
Examples 2:
// Java program to demonstrate// flip() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // defining and allocating ByteBuffer // using allocate() method ByteBuffer byteBuffer = ByteBuffer.allocate(4); // put byte value in byteBuffer // using put() method byteBuffer.put((byte)20); byteBuffer.put((byte)30); // print the byte buffer System.out.println("ByteBuffer before flip: " + Arrays.toString(byteBuffer.array()) + "\nPosition: " + byteBuffer.position() + "\nLimit: " + byteBuffer.limit()); // Flip the byteBuffer // using flip() method byteBuffer.flip(); // print the byte buffer System.out.println("\nByteBuffer after flip: " + Arrays.toString(byteBuffer.array()) + "\nPosition: " + byteBuffer.position() + "\nLimit: " + byteBuffer.limit()); }}
ByteBuffer before flip: [20, 30, 0, 0]
Position: 2
Limit: 4
ByteBuffer after flip: [20, 30, 0, 0]
Position: 0
Limit: 2
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#flip–
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Multithreading in Java
Singleton Class in Java
LinkedList in Java
Stack Class in Java | [
{
"code": null,
"e": 24554,
"s": 24526,
"text": "\n27 Jun, 2019"
},
{
"code": null,
"e": 24896,
"s": 24554,
"text": "The flip() method of java.nio.ByteBuffer Class is used to flip this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations."
},
{
"code": null,
"e": 24909,
"s": 24896,
"text": "For example:"
},
{
"code": null,
"e": 25086,
"s": 24909,
"text": "buf.put(magic); // Prepend header\nin.read(buf); // Read data into rest of buffer\nbuf.flip(); // Flip buffer\nout.write(buf); // Write header + data to channel\n"
},
{
"code": null,
"e": 25201,
"s": 25086,
"text": "This method is often used in conjunction with the compact method when transferring data from one place to another."
},
{
"code": null,
"e": 25209,
"s": 25201,
"text": "Syntax:"
},
{
"code": null,
"e": 25234,
"s": 25209,
"text": "public ByteBuffer flip()"
},
{
"code": null,
"e": 25281,
"s": 25234,
"text": "Return Value: This method returns this buffer."
},
{
"code": null,
"e": 25337,
"s": 25281,
"text": "Below are the examples to illustrate the flip() method:"
},
{
"code": null,
"e": 25349,
"s": 25337,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// flip() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the byte array byte[] bb = { 10, 20, 30 }; // wrap the byte array into floatBuffer // using wrap() method ByteBuffer byteBuffer = ByteBuffer.wrap(bb); // set position at index 1 byteBuffer.position(1); // print the byte buffer System.out.println(\"ByteBuffer before flip: \" + Arrays.toString(byteBuffer.array()) + \"\\nPosition: \" + byteBuffer.position() + \"\\nLimit: \" + byteBuffer.limit()); // Flip the byteBuffer // using flip() method byteBuffer.flip(); // print the byte buffer System.out.println(\"\\nByteBuffer after flip: \" + Arrays.toString(byteBuffer.array()) + \"\\nPosition: \" + byteBuffer.position() + \"\\nLimit: \" + byteBuffer.limit()); }}",
"e": 26442,
"s": 25349,
"text": null
},
{
"code": null,
"e": 26559,
"s": 26442,
"text": "ByteBuffer before flip: [10, 20, 30]\nPosition: 1\nLimit: 3\n\nByteBuffer after flip: [10, 20, 30]\nPosition: 0\nLimit: 1\n"
},
{
"code": null,
"e": 26676,
"s": 26559,
"text": "ByteBuffer before flip: [10, 20, 30]\nPosition: 1\nLimit: 3\n\nByteBuffer after flip: [10, 20, 30]\nPosition: 0\nLimit: 1\n"
},
{
"code": null,
"e": 26688,
"s": 26676,
"text": "Examples 2:"
},
{
"code": "// Java program to demonstrate// flip() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // defining and allocating ByteBuffer // using allocate() method ByteBuffer byteBuffer = ByteBuffer.allocate(4); // put byte value in byteBuffer // using put() method byteBuffer.put((byte)20); byteBuffer.put((byte)30); // print the byte buffer System.out.println(\"ByteBuffer before flip: \" + Arrays.toString(byteBuffer.array()) + \"\\nPosition: \" + byteBuffer.position() + \"\\nLimit: \" + byteBuffer.limit()); // Flip the byteBuffer // using flip() method byteBuffer.flip(); // print the byte buffer System.out.println(\"\\nByteBuffer after flip: \" + Arrays.toString(byteBuffer.array()) + \"\\nPosition: \" + byteBuffer.position() + \"\\nLimit: \" + byteBuffer.limit()); }}",
"e": 27768,
"s": 26688,
"text": null
},
{
"code": null,
"e": 27889,
"s": 27768,
"text": "ByteBuffer before flip: [20, 30, 0, 0]\nPosition: 2\nLimit: 4\n\nByteBuffer after flip: [20, 30, 0, 0]\nPosition: 0\nLimit: 2\n"
},
{
"code": null,
"e": 27973,
"s": 27889,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#flip–"
},
{
"code": null,
"e": 27989,
"s": 27973,
"text": "Java-ByteBuffer"
},
{
"code": null,
"e": 28004,
"s": 27989,
"text": "Java-Functions"
},
{
"code": null,
"e": 28021,
"s": 28004,
"text": "Java-NIO package"
},
{
"code": null,
"e": 28026,
"s": 28021,
"text": "Java"
},
{
"code": null,
"e": 28031,
"s": 28026,
"text": "Java"
},
{
"code": null,
"e": 28129,
"s": 28031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28138,
"s": 28129,
"text": "Comments"
},
{
"code": null,
"e": 28151,
"s": 28138,
"text": "Old Comments"
},
{
"code": null,
"e": 28181,
"s": 28151,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28213,
"s": 28181,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28232,
"s": 28213,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28250,
"s": 28232,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28281,
"s": 28250,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28313,
"s": 28281,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28336,
"s": 28313,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 28360,
"s": 28336,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 28379,
"s": 28360,
"text": "LinkedList in Java"
}
] |
Setting-up Apache Spark in Standalone Mode | by Rahuldubey | Towards Data Science | In this post we are going to setup Apache Spark in Standalone cluster mode. Apache Spark is a framework which is used to solve Big Data problems like Data Processing, Feature Engineering, Machine learning and working with streaming data. Apache Spark provides a way to distribute your work load with several worker nodes either using Standalone, YARN or MESOS Cluster manager for parallel computation. Simplest of them is Standalone Cluster manager which doesn’t require much tinkering with configuration files to setup your own processing cluster.
I’ll not cover conceptual details in this post but rather practical ones. For a cluster with multiple nodes, I’ll use two nodes with one machine having Ubuntu installed standalone and other machine have VM installed with Bridged Adapter activated. If Bridged Adapter is not activated, follow the steps below.
To check your if your IP address is being shared with VMs, open and login to your VM machine and type in terminal:
#If "ifconfig" not installed$ sudo apt-get install net-tools$ ifconfig
You should see your IP address same as your host machine.
Once we are done with setting basic network configuration, we need to set Apache Spark environment by installing binaries, dependencies and adding system path to Apache Spark directory as well as python directory to run Shell scripts provided in bin directory of Spark to start clusters.
-----PYTHON SETUP-----#Check if "python3" is installed$ python3 --version#If "pyhon3" not installed, then type commands below#This will install python 3.6.9$ sudo apt-get install python3.6#Check if pip is installed, since we might need it in future$ pip3 --version#If pip3 not installed, then type commands below$ sudo apt install python3-pip#Also install some other dependencies$sudo apt-get install python3-numpy python3-matplotlib python3-scipy-----JAVA SETUP----#Check if JAVA is installed, this is required by Spark which works #underneath it.$ java -version#If not installed, type the command below#This will install JAVA-11$ sudo apt install default-jdk#Once JAVA installed, add it to the environment path$ sudo update-alternatives --config java#copy the path from above command and paste it to environment as #"JAVA_HOME=/path/to/JAVA"$ sudo nano /etc/environment
We need to setup SSH-key using SSH-keygen to allow Spark access the machines with pre-authorisation.
#Install ssh$ sudo apt-get install openssh-server openssh-client#Edit the sshd_config file to allow certain permissions$ sudo nano /etc/ssh/sshd_configPermitRootLogin yesPubkeyAuthentication yesPasswordAuthentication yes#Restart sshd services to reflect the changes in file$ services sshd restart
All the steps till now needs to be done on all the nodes. We need to generate public key now and copy it to other nodes for password-less authentication.
Perform steps below only for node on which you are going to start Spark master.
# Generate key with rsa algorithm#This will create a .ssh directory at /home/usr$ ssh-keygen -t rsa#Skip paraphrase and other information by pressing "ENTER"#Copy id_rsa.pub public key using scp to all other nodes' root #directories. This will ask you to enter password for root@worker_1_IP #and root@worker_2_IP first time.$ scp .ssh/id_rsa.pub root@worker_1_IP:$ scp .ssh/id_rsa.pub root@worker_2_IP:#Change to root directory by typing "cd ~".#Switch to root@worker_1_IP and root@worker_2_IP and copy id_rsa.pub #from root directory to home directory of user.$ ssh root@worker_1_IP (and for worker_2 also)$ cp id_rsa.pub /home/usr/.ssh/authorized_keys#Above step will ask you to overwrite key if already present.#Once done with above steps, check if password-less authorisation #works from your Master node.$ ssh usr@worker_1_IP$ ssh usr@worker_2_IPNOTE: I would advice you to keep the user name for the machines in VM same if security is not an issue because the Spark requires Master node user (in my case "rahul") to be given permission for login as usr@worker_1_IP and usr@worker_2_IP where usr has to be same (in my case "rahul").#Another alternative is to create users on salve machines with sudo permissions.
Below, we install Apache Spark and tinker with Configuration files to setup clusters. We have installed all the dependencies and network configuration to get Spark run error free. Perform these steps for all nodes.
#Download Apache Spark-3.0.1 with hadoop2.7 tar file$ wget https://downloads.apache.org/spark/spark-3.0.1/spark-3.0.1-bin-hadoop2.7 tgz#Check if tar file is present$ ls -la#Extract the tar file$ tar xvf spark-*#Move the file to /opt/spark$ sudo mv spark-3.0.1-bin-hadoop2.7 /opt/spark#/opt/spark is going to be your SPARK_HOME directory. Also add #python3 directory path as PYSPARK_PYTHON. These change are to be #done in .profile file$ sudo nano .profile#Add following variables and pathexport SPARK_HOME=/opt/sparkexport PATH=$PATH:$SPARK_HOME/bin:$SPARK_HOME/sbinexport PYSPARK_PYTHON=/usr/bin/python3#save and close .profile file and recompile it$ source .profile
Now we edit configuration files for only Master node. Do not perform these steps on slave nodes.
#Copy and edit spark-env.sh.template and slave.template file$ cp $SPARK_HOME/conf/spark-env.sh.template $SPARK_HOME/conf/spark- env.sh$cp $SPARK_HOME/conf/slaves.template $SPARK_HOME/conf/slaves#Open spark-env.sh file and add JAVA_HOME and other configurations #like Memory or CPU core numbers$ sudo nano $SPARK_HOME/conf/spark-env.sh#add at the end of the fileexport JAVA_HOME=/path/to/JAVA or $JAVA_HOME(from /etc/environment)export SPARK_MASTER_HOST=master_IP#Open slaves file and add IP address of slaves. Delete "localhost" #if presentworker_1_IPworker_2_IP#Save the file above and run command below to check if all nodes #starts$ $SPARK_HOME/sbin/start-all.sh#Go to web browser and typehttp://127.0.0.1:8080/#This will show the number of workers, their running status, their configuration and other information.#To stop the Master and workers$ $SPARK_HOME/sbin/stop-all.sh#To start SPARK SHELL which will run SCALA programming language#Quit it using ":q" and enter$ $SPARK_HOME/bin/spark-shell#To start SPARK SHELL with PYTHON programming language# Quit it using "exit()" and enter$ $SPARK_HOME/bin/pyspark
We can check if our cluster if functioning by submitting an application. A Spark Application detects SparkContext instance which holds the SparkConf object which specifies whether the application has to run in Local processes or Cluster processes. We will cover this in future posts, but for now just run the code below to calculate the value of Pi.
#IP=MASTER node IP address#PORT=7077 for me#You can check your master address by opening #https://127.0.0.1:8080/$ MASTER=spark://IP:PORT $SPARK_HOME/bin/run-example org.apache.spark.examples.SparkPi#You should get a value and bunch of warnings
You should see the similar screen on Spark UI as shown below.
In this post, we have learnt how to setup your own cluster environment in Apache Spark and how to submit a simple application to it and navigate the states of nodes using Spark UI. In the next posts I’ll explain how to configure your applications to get executed in the cluster environment and save their results in the form of RDDs (Resilient Distributed Datasets). | [
{
"code": null,
"e": 721,
"s": 172,
"text": "In this post we are going to setup Apache Spark in Standalone cluster mode. Apache Spark is a framework which is used to solve Big Data problems like Data Processing, Feature Engineering, Machine learning and working with streaming data. Apache Spark provides a way to distribute your work load with several worker nodes either using Standalone, YARN or MESOS Cluster manager for parallel computation. Simplest of them is Standalone Cluster manager which doesn’t require much tinkering with configuration files to setup your own processing cluster."
},
{
"code": null,
"e": 1030,
"s": 721,
"text": "I’ll not cover conceptual details in this post but rather practical ones. For a cluster with multiple nodes, I’ll use two nodes with one machine having Ubuntu installed standalone and other machine have VM installed with Bridged Adapter activated. If Bridged Adapter is not activated, follow the steps below."
},
{
"code": null,
"e": 1145,
"s": 1030,
"text": "To check your if your IP address is being shared with VMs, open and login to your VM machine and type in terminal:"
},
{
"code": null,
"e": 1216,
"s": 1145,
"text": "#If \"ifconfig\" not installed$ sudo apt-get install net-tools$ ifconfig"
},
{
"code": null,
"e": 1274,
"s": 1216,
"text": "You should see your IP address same as your host machine."
},
{
"code": null,
"e": 1562,
"s": 1274,
"text": "Once we are done with setting basic network configuration, we need to set Apache Spark environment by installing binaries, dependencies and adding system path to Apache Spark directory as well as python directory to run Shell scripts provided in bin directory of Spark to start clusters."
},
{
"code": null,
"e": 2434,
"s": 1562,
"text": "-----PYTHON SETUP-----#Check if \"python3\" is installed$ python3 --version#If \"pyhon3\" not installed, then type commands below#This will install python 3.6.9$ sudo apt-get install python3.6#Check if pip is installed, since we might need it in future$ pip3 --version#If pip3 not installed, then type commands below$ sudo apt install python3-pip#Also install some other dependencies$sudo apt-get install python3-numpy python3-matplotlib python3-scipy-----JAVA SETUP----#Check if JAVA is installed, this is required by Spark which works #underneath it.$ java -version#If not installed, type the command below#This will install JAVA-11$ sudo apt install default-jdk#Once JAVA installed, add it to the environment path$ sudo update-alternatives --config java#copy the path from above command and paste it to environment as #\"JAVA_HOME=/path/to/JAVA\"$ sudo nano /etc/environment"
},
{
"code": null,
"e": 2535,
"s": 2434,
"text": "We need to setup SSH-key using SSH-keygen to allow Spark access the machines with pre-authorisation."
},
{
"code": null,
"e": 2832,
"s": 2535,
"text": "#Install ssh$ sudo apt-get install openssh-server openssh-client#Edit the sshd_config file to allow certain permissions$ sudo nano /etc/ssh/sshd_configPermitRootLogin yesPubkeyAuthentication yesPasswordAuthentication yes#Restart sshd services to reflect the changes in file$ services sshd restart"
},
{
"code": null,
"e": 2986,
"s": 2832,
"text": "All the steps till now needs to be done on all the nodes. We need to generate public key now and copy it to other nodes for password-less authentication."
},
{
"code": null,
"e": 3066,
"s": 2986,
"text": "Perform steps below only for node on which you are going to start Spark master."
},
{
"code": null,
"e": 4284,
"s": 3066,
"text": "# Generate key with rsa algorithm#This will create a .ssh directory at /home/usr$ ssh-keygen -t rsa#Skip paraphrase and other information by pressing \"ENTER\"#Copy id_rsa.pub public key using scp to all other nodes' root #directories. This will ask you to enter password for root@worker_1_IP #and root@worker_2_IP first time.$ scp .ssh/id_rsa.pub root@worker_1_IP:$ scp .ssh/id_rsa.pub root@worker_2_IP:#Change to root directory by typing \"cd ~\".#Switch to root@worker_1_IP and root@worker_2_IP and copy id_rsa.pub #from root directory to home directory of user.$ ssh root@worker_1_IP (and for worker_2 also)$ cp id_rsa.pub /home/usr/.ssh/authorized_keys#Above step will ask you to overwrite key if already present.#Once done with above steps, check if password-less authorisation #works from your Master node.$ ssh usr@worker_1_IP$ ssh usr@worker_2_IPNOTE: I would advice you to keep the user name for the machines in VM same if security is not an issue because the Spark requires Master node user (in my case \"rahul\") to be given permission for login as usr@worker_1_IP and usr@worker_2_IP where usr has to be same (in my case \"rahul\").#Another alternative is to create users on salve machines with sudo permissions."
},
{
"code": null,
"e": 4499,
"s": 4284,
"text": "Below, we install Apache Spark and tinker with Configuration files to setup clusters. We have installed all the dependencies and network configuration to get Spark run error free. Perform these steps for all nodes."
},
{
"code": null,
"e": 5167,
"s": 4499,
"text": "#Download Apache Spark-3.0.1 with hadoop2.7 tar file$ wget https://downloads.apache.org/spark/spark-3.0.1/spark-3.0.1-bin-hadoop2.7 tgz#Check if tar file is present$ ls -la#Extract the tar file$ tar xvf spark-*#Move the file to /opt/spark$ sudo mv spark-3.0.1-bin-hadoop2.7 /opt/spark#/opt/spark is going to be your SPARK_HOME directory. Also add #python3 directory path as PYSPARK_PYTHON. These change are to be #done in .profile file$ sudo nano .profile#Add following variables and pathexport SPARK_HOME=/opt/sparkexport PATH=$PATH:$SPARK_HOME/bin:$SPARK_HOME/sbinexport PYSPARK_PYTHON=/usr/bin/python3#save and close .profile file and recompile it$ source .profile"
},
{
"code": null,
"e": 5264,
"s": 5167,
"text": "Now we edit configuration files for only Master node. Do not perform these steps on slave nodes."
},
{
"code": null,
"e": 6377,
"s": 5264,
"text": "#Copy and edit spark-env.sh.template and slave.template file$ cp $SPARK_HOME/conf/spark-env.sh.template $SPARK_HOME/conf/spark- env.sh$cp $SPARK_HOME/conf/slaves.template $SPARK_HOME/conf/slaves#Open spark-env.sh file and add JAVA_HOME and other configurations #like Memory or CPU core numbers$ sudo nano $SPARK_HOME/conf/spark-env.sh#add at the end of the fileexport JAVA_HOME=/path/to/JAVA or $JAVA_HOME(from /etc/environment)export SPARK_MASTER_HOST=master_IP#Open slaves file and add IP address of slaves. Delete \"localhost\" #if presentworker_1_IPworker_2_IP#Save the file above and run command below to check if all nodes #starts$ $SPARK_HOME/sbin/start-all.sh#Go to web browser and typehttp://127.0.0.1:8080/#This will show the number of workers, their running status, their configuration and other information.#To stop the Master and workers$ $SPARK_HOME/sbin/stop-all.sh#To start SPARK SHELL which will run SCALA programming language#Quit it using \":q\" and enter$ $SPARK_HOME/bin/spark-shell#To start SPARK SHELL with PYTHON programming language# Quit it using \"exit()\" and enter$ $SPARK_HOME/bin/pyspark"
},
{
"code": null,
"e": 6727,
"s": 6377,
"text": "We can check if our cluster if functioning by submitting an application. A Spark Application detects SparkContext instance which holds the SparkConf object which specifies whether the application has to run in Local processes or Cluster processes. We will cover this in future posts, but for now just run the code below to calculate the value of Pi."
},
{
"code": null,
"e": 6972,
"s": 6727,
"text": "#IP=MASTER node IP address#PORT=7077 for me#You can check your master address by opening #https://127.0.0.1:8080/$ MASTER=spark://IP:PORT $SPARK_HOME/bin/run-example org.apache.spark.examples.SparkPi#You should get a value and bunch of warnings"
},
{
"code": null,
"e": 7034,
"s": 6972,
"text": "You should see the similar screen on Spark UI as shown below."
}
] |
Counting numbers after decimal point in JavaScript | We are required to write a JavaScript function that takes in a number which may be an integer or a floating-point number. If it's a floating-point number, we have to return the count of numbers after the decimal point. Otherwise we should return 0.
For our example, we are considering two numbers −
const num1 = 1.123456789;
const num2 = 123456789;
Following is the code −
const num1 = 1.123456789;
const num2 = 123456789;
const decimalCount = num => {
// Convert to String
const numStr = String(num);
// String Contains Decimal
if (numStr.includes('.')) {
return numStr.split('.')[1].length;
};
// String Does Not Contain Decimal
return 0;
}
console.log(decimalCount(num1)) // 9
console.log(decimalCount(num2)) // 0
This will produce the following output in console −
9
0 | [
{
"code": null,
"e": 1311,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a number which may be an integer or a floating-point number. If it's a floating-point number, we have to return the count of numbers after the decimal point. Otherwise we should return 0."
},
{
"code": null,
"e": 1361,
"s": 1311,
"text": "For our example, we are considering two numbers −"
},
{
"code": null,
"e": 1411,
"s": 1361,
"text": "const num1 = 1.123456789;\nconst num2 = 123456789;"
},
{
"code": null,
"e": 1435,
"s": 1411,
"text": "Following is the code −"
},
{
"code": null,
"e": 1806,
"s": 1435,
"text": "const num1 = 1.123456789;\nconst num2 = 123456789;\nconst decimalCount = num => {\n // Convert to String\n const numStr = String(num);\n // String Contains Decimal\n if (numStr.includes('.')) {\n return numStr.split('.')[1].length;\n };\n // String Does Not Contain Decimal\n return 0;\n}\nconsole.log(decimalCount(num1)) // 9\nconsole.log(decimalCount(num2)) // 0"
},
{
"code": null,
"e": 1858,
"s": 1806,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 1862,
"s": 1858,
"text": "9\n0"
}
] |
Capitalize text with CSS | To capitalize text with CSS, use the capitalize property. You can try to run the following code to capitalize text:
<html>
<head>
</head>
<body>
<p style = "text-transform:capitalize;">
India
</p>
</body>
</html> | [
{
"code": null,
"e": 1178,
"s": 1062,
"text": "To capitalize text with CSS, use the capitalize property. You can try to run the following code to capitalize text:"
},
{
"code": null,
"e": 1308,
"s": 1178,
"text": "<html>\n <head>\n </head>\n <body>\n <p style = \"text-transform:capitalize;\">\n India\n </p>\n </body>\n</html>"
}
] |
Neo4j - Sum Function | It takes a set of rows and a <property-name> of a node or relationship as an input and finds the summation value from the given <property-name> column of given rows.
Following is the syntax of the SUM() function.
SUM(<property-name>)
Following is a sample Cypher query which demonstrates the usage of the function SUM() in Neo4j. Here we are trying to calculate the SUM of the salaries of the employees
MATCH (n:employee) RETURN SUM(n.sal)
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2505,
"s": 2339,
"text": "It takes a set of rows and a <property-name> of a node or relationship as an input and finds the summation value from the given <property-name> column of given rows."
},
{
"code": null,
"e": 2552,
"s": 2505,
"text": "Following is the syntax of the SUM() function."
},
{
"code": null,
"e": 2574,
"s": 2552,
"text": "SUM(<property-name>)\n"
},
{
"code": null,
"e": 2743,
"s": 2574,
"text": "Following is a sample Cypher query which demonstrates the usage of the function SUM() in Neo4j. Here we are trying to calculate the SUM of the salaries of the employees"
},
{
"code": null,
"e": 2781,
"s": 2743,
"text": "MATCH (n:employee) RETURN SUM(n.sal) "
},
{
"code": null,
"e": 2841,
"s": 2781,
"text": "To execute the above query, carry out the following steps −"
},
{
"code": null,
"e": 3019,
"s": 2841,
"text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot."
},
{
"code": null,
"e": 3172,
"s": 3019,
"text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 3221,
"s": 3172,
"text": "On executing, you will get the following result."
},
{
"code": null,
"e": 3228,
"s": 3221,
"text": " Print"
},
{
"code": null,
"e": 3239,
"s": 3228,
"text": " Add Notes"
}
] |
Classifying Images of Alcoholic Beverages with fast.ai | Towards Data Science | Having starting immersing myself in the updated fast.ai v2 deep learning course, I felt it would be ideal to apply and document what I have learnt so far. In this article, I will be sharing about how I trained a deep learning (CNN) classifier to distinguish the different types of popular alcoholic beverages.
An important highlight of this walkthrough is that it details the latest instructions on how to utilize the updated Microsoft Azure Bing Search V7 API, since key changes were implemented as of 30 Oct 2020.
GitHub Repo
Jupyter Notebook (Full Version)
Jupyter Notebook (Clean version)
Section 1 — Setup
Section 2 — Downloading Image Data
Section 3 — Preparing Image Datasets
Section 4 — Training the Model
Section 5 — Cleaning the Data
Section 6 — Using Image Classifier for Inference
Section 7 — Deployment as Web App
First things first, I would highly recommend running this notebook on Google Colab. To find out more about Google Colab setup, please visit this link.
Once this notebook is open on Google Colab, do switch on the GPU accelerator for the notebook by heading to the top menu and clicking Runtime > Change runtime type > Select GPU for Hardware Accelerator.
Next, mount your Google Drive on your Google Colab runtime. A link will appear for you to click and retrieve your authorization code. After granting permission to Google Drive File Stream, copy the code provided, paste it in the field under ‘Enter your Authorization Code’, and press Enter.
from google.colab import drivedrive.mount('/content/drive/')
The next step is to install the fast.ai dependencies. I found this combination of dependency versions to be working smoothly on Google Colab.
!pip install fastai==2.0.19!pip install fastai2==0.0.30!pip install fastcore==1.3.1!pip install -Uqq fastbookimport fastbookfrom fastbook import *fastbook.setup_book()from fastai.vision.widgets import *import warningswarnings.filterwarnings("ignore")import requestsimport matplotlib.pyplot as pltimport PIL.Imagefrom io import BytesIOimport osfrom IPython.display import Imagefrom IPython.core.display import HTML
We then create a path to store the images that we are about to download. Note that the resultant directory path will be /content/images.
try: os.mkdir('images')except: pass
After that, we need to retrieve the API key for Azure Bing Search V7, since we will be using it to pull image datasets from Bing. To find out more about setting up the Bing Search API key in the Microsoft Azure Portal, please have a look at the README file in my GitHub repo, as well as the Microsoft Azure Bing Search API quickstart guide.
subscription_key = "XXX" #Replace XXX with your own API keysearch_url = "https://api.bing.microsoft.com/v7.0/images/search"headers = {"Ocp-Apim-Subscription-Key" : subscription_key}
Once the key has been entered into the subscription_key variable, we can retrieve a set of image URLs related to the keyword of your choice. For example, to find a set of images for whisky, we run the following code:
search_term = "whisky"#Add in count parameter so that max number of images (150) is #retrieved upon each API call. Otherwise, default is 35.params = {"q": search_term, "license": "public", "imageType": "photo", "count":"150"}response = requests.get(search_url, headers=headers, params=params)response.raise_for_status()# Return json filesearch_results = response.json()# Create a set of thumbnails for visualizationthumbnail_urls = [img["thumbnailUrl"] for img in search_results["value"][:16]]
We can create a 4 x 4 grid plot of thumbnails to visualize the images retrieved, allowing us to verify that the images do represent our keyword whisky. From what is displayed, it does look very much like good ol’ whisky to me.
f, axes = plt.subplots(4, 4)for i in range(4): for j in range(4): image_data = requests.get(thumbnail_urls[i+4*j]) image_data.raise_for_status() image = Image.open(BytesIO(image_data.content)) axes[i][j].imshow(image) axes[i][j].axis("off")plt.show()
The next step is to collate the list of image URLs from the search results JSON file. The key that is associated with the image URL is contentUrl.
img_urls = [img['contentUrl'] for img in search_results["value"]]len(img_urls)
The len function should return us a list of 150 image URLs related to the keyword whisky. We then download and display a single image from a URL into the destination file named whisky_test.jpg inside our images folder.
dest = 'images/whisky_test.jpg'download_url(img_urls[1], dest)img = Image.open(dest)img.to_thumb(224,224)
We got ourselves a whisky image above, showing that the chunks of code above worked perfectly. We are now ready for the main action.
Update: As the image download method is dynamic, please refer to the fast.ai Images section to find out what is the latest approach for image downloads
It would be interesting to distinguish the images of common alcohol types, namely whisky, wine and beer. To do that, we first define the three alcohol types in a list, and create a Path to store the images we are going to download shortly.
alcohol_types = ['whisky','wine','beer']path = Path('alcohol')
For each of the three alcohol types, we create a subpath to store the images, and we proceed to download the images from the image URLs collated.
if not path.exists(): path.mkdir() for alc_type in alcohol_types: dest = (path/alc_type) dest.mkdir(exist_ok=True) search_term = alc_type params = {"q":search_term, "license":"public", "imageType":"photo", "count":"150"} response = requests.get(search_url, headers=headers, params=params) response.raise_for_status() search_results = response.json() img_urls = [img['contentUrl'] for img in search_results["value"]] # Downloading images from the list of image URLs download_images(dest, urls=img_urls)
We should now have the images downloaded within the respective folders with the label of the alcohol type. To confirm this, we can utilize the get_image_files function.
img_files = get_image_files(path)img_files(#445) [Path('alcohol/beer/00000069.jpeg'),Path('alcohol/beer/00000007.jpg'),Path('alcohol/beer/00000092.jpg'),Path('alcohol/beer/00000054.jpg'),Path('alcohol/beer/00000082.jpg'),Path('alcohol/beer/00000071.jpg'),Path('alcohol/beer/00000045.jpg'),Path('alcohol/beer/00000134.jpg'),Path('alcohol/beer/00000061.jpg'),Path('alcohol/beer/00000138.jpg')...]
Another method to verify the downloads is to click on the Files icon on the left navigation bar of the Google Colab screen, and navigate to content>alcohol to see the respective folders.
After that, we need to check whether the files we downloaded are corrupt or not. Fortunately, fastai provides a convenient way to do just that, via theverify_images function.
failed = verify_images(img_files)failed
We can then proceed to remove these corrupt files (if any) from our dataset, using the map and unlink methods.
failed.map(Path.unlink)
fastai has a flexible system called the data block API. With this API, we can fully customize the creation of the DataLoaders object. DataLoaders can store whatever DataLoader objects we place in it, and it is used to generate training and validation sets subsequently.
In my interpretation, DataLoaders is essentially an object that stores information about the data we will run our model on. The DataBlock is basically a template function for creating DataLoaders.
alcohols = DataBlock( blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, splitter=RandomSplitter(valid_pct=0.2, seed=1), get_y=parent_label, item_tfms=Resize(128))
Let’s go through the above code part by part:
blocks=(ImageBlock, CategoryBlock)
This blocks tuple indicates the data types for our independent and dependent variables respectively. Since our aim here is to classify images, our independent variable is images (ImageBlock) while our dependent variable is categories/labels (CategoryBlock)
get_items=get_image_files
The get_items argument specifies the function to be used in order to extract the file paths of the images in our dataset. Recall we earlier used the fastai built-in get_image_files to get the file paths into the variable img_files. This get_image_files function takes a path (which we will specify later), and returns a list of all of the images in that path.
splitter=RandomSplitter(valid_pct=0.2, seed=1)
The splitter method will split the dataset into training and validation sets. We specify RandomSplitter to ensure that it is split randomly, and the valid_pct argument within it is there to indicate what percentage of the dataset is to be allocated as a validation set. The random seed can also be set within the RandomSplitter for reproducibility of results.
get_y=parent_label
parent_label is a function provided by fastai to get the name of the folder the image files are located in. Since we have placed our images in folders with the respective alcohol type name, this parent_label will be returning the folder names of whisky, wine and beer.
item_tfms=Resize(128)
We normally use resize images into a square as it is easier to do so, since original images can come in different height/width and aspect ratio. To do this, we perform a transformation on each item (item_tfms) by resizing it into squares of 128x128 pixels.
Now that all the details and arguments have been provided, we can then proceed to initiate the DataLoaders with the following single line of code. Notice that the argument for dataloaders is the path where our images are stored i.e. alcohol folder path.
dls = alcohols.dataloaders(path)
Let’s have a brief look at the images by showing a subset batch of 10 images inside our validation set
Note: The following display of image thumbnails is a good way to validate whether the data download was performed correctly. Previously when I ran this code, I realise that I did not update the search_term accordingly, resulting in all images being that of whisky. If done correctly, the following batch should show a myriad of the images from different categories.
dls.valid.show_batch(max_n=12, nrows=2)
Before proceeding further, it is important to talk about the concept of data augmentation. In order to enrich our training dataset, we can create random variations of our input data, such that they appear different, but do not actually change the original meaning and representation of the data.
A common way to do this includes RandomResizedCrop, which grabs a random subset of the original image. We use unique=True to have the same image repeated with different versions of theRandomResizedCrop transformation.
What happens is that on each epoch (which is one complete pass through all of our images in the dataset), we randomly select a different part of each image. This means that our model can learn to recognize different features in our images. It also reflects how images work in the real world, since different photos of the same item may be framed in slightly different ways. The benefit of using item transformation is that it in turn helps to prevent overfitting.
The min_scale parameter specified determines how much of the image to select at minimum each time. With all the above decided, we can create a new DataBlock object using the .new method, and running it to give us a new DataLoaders object named dls.
alcohols = alcohols.new(item_tfms=RandomResizedCrop(128, min_scale=0.3))dls = alcohols.dataloaders(path)dls.train.show_batch(max_n=8, nrows=2, unique=True)
Following the item transformation (item_tfms), we run batch transformation (batch_tfms) where we apply a standard set of data augmentation transformations (aug_transforms()) on the batch of the individual items.
The difference between item_tfms and batch_tfms is that item_tfms performs the transformation on every individual item (e.g. image), whereas batch_tfms runs transformation on an entire batch of items.
The following code illustrates the effects of the augmentation transformation aug_transforms on a single input image. You will be able to observe some form of rotation, perspective warping and contrast changes.
alcohols = alcohols.new(item_tfms=Resize(128), batch_tfms=aug_transforms())dls = alcohols.dataloaders(path)dls.train.show_batch(max_n=8, nrows=2, unique=True)
Now that the images are prepared (albeit not cleaned yet), we can start the training to build a simple deep learning model right off the bat. First we prepare the DataLoaders object with the following code. In this iteration, we resize and crop our images at sizes of 224x224 pixel, with min_scale of 0.5.
alcohols = alcohols.new( item_tfms=RandomResizedCrop(224, min_scale=0.5), batch_tfms=aug_transforms())dls = alcohols.dataloaders(path)
Convoluted neural network (CNN) is the de facto type of neural network used for image classification, and that is what we will be using. In terms of the architecture, I arbitrarily chose resnet34 (i.e. 34 layers deep) for the cnn_learner fast.ai function. Details of resnet can be found here.
We are using the .fine_tune method instead of .fit because we are leveraging on the pretrained resnet model to perform transfer learning. We specify the number of epochs to be 4 (i.e. argument inside .fine_tune).
learn = cnn_learner(dls, resnet34, metrics=error_rate)learn.fine_tune(4)
From the above, we can see that after training our CNN learner for a couple of minutes, we obtain an error_rate of 0.229 (i.e. 77.1% accuracy). Not a bad start, given that we have not yet cleaned our dataset.
Using the Confusion Matrix allows for better visualization of the results.
interpretation = ClassificationInterpretation.from_learner(learn)interpretation.plot_confusion_matrix()
fast.ai also provides a easy method that allows us to find out which are the images where there was the highest loss. The loss is a number that is higher if the model is incorrect (especially if it is also confident of its incorrect answer), or if it is correct, but not confident of its correct answer. These helps us identify the images which the model had trouble with.
interpretation.plot_top_losses(5, nrows=1)
From the above, it appears that some of the problem stems from the fact that several actual labels were labelled incorrectly, instead of the predictions being wrong.
For example, the image in the middle of the row is quite clearly that of a pint of beer (which is exactly what the model predicted). However, the actual label assigned to it was whisky, which is incorrect. This highlights the importance of having correctly labeled data (as much as possible) before training any kind of machine learning model.
Notice that we ran the model before cleaning the data. In fact, doing so makes the data cleaning even easier subsequently. As shown above, the plot_top_losses can already indicate which are the images that the model has most trouble with.
The data cleaning process is made easy with the in-built fast.ai ImageClassifierCleaner Graphical User Interface (GUI) widget.
cleaner = ImageClassifierCleaner(learn)cleaner
The row of images displayed are the images where the loss was highest, and this GUI gives you an opportunity to review and amend them.
The cleaning is done by selecting a dropdown option for each of the images above, and then running the ‘cleaning’ code iteratively. I took some time to figure this out since the online explanations were unclear, so here are some further details:
Step 1: After a row of images is loaded in the cleaner output cell (e.g. Training set for Wine category), select a dropdown option for the images that you wish to edit, based on your own judgement. The options consist of deleting the image from the dataset, or moving the image into a new category. If no changes are needed, there is no need to select any option since the default option is <Keep>.
Step 2: Once you are done updating the options for the row of images on display, run the following ‘cleaning’ code to execute the changes.
# Delete images marked as deletefor idx in cleaner.delete(): cleaner.fns[idx].unlink() # Update category of image to the newly specified category by moving # it into the appropriate folderfor idx,cat in cleaner.change(): shutil.copyfile(cleaner.fns[idx], path/cat)
cleaner.delete removes the images you have tagged as <Delete>, while cleaner.change shifts the image into the folder with the updated label.
Step 3: Head back to the cleaner cell with the row of images again, and switch to a new set of images via the dropdown menu e.g. Validation set of Beer category, or Training Set of Whisky category
Step 4: After the new row of images is loaded, select the relevant dropdown options for each of the images, and then re-run the ‘cleaning’ code
Step 5: Repeat steps 3 and 4 iteratively for each dataset until all the datasets have been reviewed at least once.
dls = alcohols.dataloaders(path)learn = cnn_learner(dls, resnet34, metrics=error_rate)learn.fine_tune(4)
With just a little bit of data cleaning (mostly by removing irrelevant images with the .unlink method), we see a huge improvement in the error_rate (decreased from 0.229 to 0.096). This means that the accuracy has increased from the earlier 77.1% (before data cleaning) to the current 90.4%.
interpretation = ClassificationInterpretation.from_learner(learn)interpretation.plot_confusion_matrix()
From the confusion matrix above, we can clearly see that the model has become better at distinguishing between the three types of alcohol beverages.
After the training is complete, we want to export the model so that the architecture, trained parameters and DataLoaders setup is saved. All these will be saved into a pickle (.pkl) file.
learn.export()path = Path()path.ls(file_exts='.pkl')(#1) [Path('export.pkl')]
After loading the pickle file containing the information of our deep learning image classification model, we can use it to infer (or predict) the label of new images. The model is now loaded into the learner variable learn_inf.
learn_inf = load_learner(path/'export.pkl')
We use a sample image to test our model
# Sample imageims = ['https://alcohaul.sg/products/i/400/5f7edfe79ae56e6d7b8b49cf_0.jpg']dest = 'images/test_whisky.jpg'download_url(ims[0], dest)im = Image.open(dest)im.to_thumb(224,224)
Our sample image is that of a Hibiki Harmony whisky. Let’s see if our model is able to recognize its category.
learn_inf.predict('images/test_whisky.jpg')('whisky', tensor(1), tensor([4.1783e-04, 9.9951e-01, 7.0310e-05]))learn_inf.dls.vocab['beer', 'whisky', 'wine']
Looks like all is good. The model is able to determine with high confidence that the test image represents an image of a whisky (with a probability of 99.95%).
Let’s briefly explore the deployment of the model. We first create a button for users to upload new images which they wish to classify.
We then make use of the PIL.Image.create method to retrieve the uploaded image and store it in the img variable
btn_upload = widgets.FileUpload()btn_upload
# Retrieving the uploaded imageimg = PIL.Image.create(btn_upload.data[-1])
We then setup an Output widget to display the uploaded image.
out_pl = widgets.Output()out_pl.clear_output()with out_pl: display(img.to_thumb(224,224))out_pl
The user has uploaded a Talisker 18 whisky image. It is now time to once again test the classification ability of the model we have built.
pred,pred_idx,probs = learn_inf.predict(img)lbl_pred = widgets.Label()lbl_pred.value = f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}'lbl_pred
From the above, we can see that our model is indeed predicting the image to be that of a whisky (with 99.65% probability). We can now continue building our web app by including a Run button for users to click and initiate the classification process.
btn_run = widgets.Button(description='Classify Image')btn_runButton(description='Classify Image', style=ButtonStyle())
We then setup a callback such that the button above can carry out a specific function upon click. What we want is that whenever the user clicks ‘Classify Image’ for the image he/she uploaded, the classification model will run and then generate a classification prediction.
def on_click_classify(change): img = PIL.Image.create(btn_upload.data[-1]) out_pl.clear_output() with out_pl: display(img.to_thumb(128,128)) pred,pred_idx,probs = learn_inf.predict(img) lbl_pred.value = f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}'btn_run.on_click(on_click_classify)
And now, putting it all together inside a VBox so that the widgets are arranged nicely in a vertical web app template within our notebook.
VBox([widgets.Label('Select your alcohol!'), btn_upload, btn_run, out_pl, lbl_pred]
In order to deploy this app outside of this notebook, we can make use of Voila to create a form of real standalone app (built upon Jupyter notebook).
As this aspect is beyond the scope of this notebook, please feel free to explore the details of Voila here.
With that, we have come to the end of this tutorial. We discussed an end-to-end modeling experience, from fast.ai and Google Colab setup, to data ingestion, and all the way to setting up a simple web app for the model we built.
I will continue to post further walkthroughs as I continue my fast.ai learning journey. Meanwhile, time for a drink. Cheers!
I welcome you to join me on a data science learning journey! Follow this Medium page and check out my GitHub to stay in the loop of more exciting data science content. | [
{
"code": null,
"e": 481,
"s": 171,
"text": "Having starting immersing myself in the updated fast.ai v2 deep learning course, I felt it would be ideal to apply and document what I have learnt so far. In this article, I will be sharing about how I trained a deep learning (CNN) classifier to distinguish the different types of popular alcoholic beverages."
},
{
"code": null,
"e": 687,
"s": 481,
"text": "An important highlight of this walkthrough is that it details the latest instructions on how to utilize the updated Microsoft Azure Bing Search V7 API, since key changes were implemented as of 30 Oct 2020."
},
{
"code": null,
"e": 699,
"s": 687,
"text": "GitHub Repo"
},
{
"code": null,
"e": 731,
"s": 699,
"text": "Jupyter Notebook (Full Version)"
},
{
"code": null,
"e": 764,
"s": 731,
"text": "Jupyter Notebook (Clean version)"
},
{
"code": null,
"e": 782,
"s": 764,
"text": "Section 1 — Setup"
},
{
"code": null,
"e": 817,
"s": 782,
"text": "Section 2 — Downloading Image Data"
},
{
"code": null,
"e": 854,
"s": 817,
"text": "Section 3 — Preparing Image Datasets"
},
{
"code": null,
"e": 885,
"s": 854,
"text": "Section 4 — Training the Model"
},
{
"code": null,
"e": 915,
"s": 885,
"text": "Section 5 — Cleaning the Data"
},
{
"code": null,
"e": 964,
"s": 915,
"text": "Section 6 — Using Image Classifier for Inference"
},
{
"code": null,
"e": 998,
"s": 964,
"text": "Section 7 — Deployment as Web App"
},
{
"code": null,
"e": 1149,
"s": 998,
"text": "First things first, I would highly recommend running this notebook on Google Colab. To find out more about Google Colab setup, please visit this link."
},
{
"code": null,
"e": 1352,
"s": 1149,
"text": "Once this notebook is open on Google Colab, do switch on the GPU accelerator for the notebook by heading to the top menu and clicking Runtime > Change runtime type > Select GPU for Hardware Accelerator."
},
{
"code": null,
"e": 1643,
"s": 1352,
"text": "Next, mount your Google Drive on your Google Colab runtime. A link will appear for you to click and retrieve your authorization code. After granting permission to Google Drive File Stream, copy the code provided, paste it in the field under ‘Enter your Authorization Code’, and press Enter."
},
{
"code": null,
"e": 1704,
"s": 1643,
"text": "from google.colab import drivedrive.mount('/content/drive/')"
},
{
"code": null,
"e": 1846,
"s": 1704,
"text": "The next step is to install the fast.ai dependencies. I found this combination of dependency versions to be working smoothly on Google Colab."
},
{
"code": null,
"e": 2260,
"s": 1846,
"text": "!pip install fastai==2.0.19!pip install fastai2==0.0.30!pip install fastcore==1.3.1!pip install -Uqq fastbookimport fastbookfrom fastbook import *fastbook.setup_book()from fastai.vision.widgets import *import warningswarnings.filterwarnings(\"ignore\")import requestsimport matplotlib.pyplot as pltimport PIL.Imagefrom io import BytesIOimport osfrom IPython.display import Imagefrom IPython.core.display import HTML"
},
{
"code": null,
"e": 2397,
"s": 2260,
"text": "We then create a path to store the images that we are about to download. Note that the resultant directory path will be /content/images."
},
{
"code": null,
"e": 2435,
"s": 2397,
"text": "try: os.mkdir('images')except: pass"
},
{
"code": null,
"e": 2776,
"s": 2435,
"text": "After that, we need to retrieve the API key for Azure Bing Search V7, since we will be using it to pull image datasets from Bing. To find out more about setting up the Bing Search API key in the Microsoft Azure Portal, please have a look at the README file in my GitHub repo, as well as the Microsoft Azure Bing Search API quickstart guide."
},
{
"code": null,
"e": 2958,
"s": 2776,
"text": "subscription_key = \"XXX\" #Replace XXX with your own API keysearch_url = \"https://api.bing.microsoft.com/v7.0/images/search\"headers = {\"Ocp-Apim-Subscription-Key\" : subscription_key}"
},
{
"code": null,
"e": 3175,
"s": 2958,
"text": "Once the key has been entered into the subscription_key variable, we can retrieve a set of image URLs related to the keyword of your choice. For example, to find a set of images for whisky, we run the following code:"
},
{
"code": null,
"e": 3671,
"s": 3175,
"text": "search_term = \"whisky\"#Add in count parameter so that max number of images (150) is #retrieved upon each API call. Otherwise, default is 35.params = {\"q\": search_term, \"license\": \"public\", \"imageType\": \"photo\", \"count\":\"150\"}response = requests.get(search_url, headers=headers, params=params)response.raise_for_status()# Return json filesearch_results = response.json()# Create a set of thumbnails for visualizationthumbnail_urls = [img[\"thumbnailUrl\"] for img in search_results[\"value\"][:16]]"
},
{
"code": null,
"e": 3898,
"s": 3671,
"text": "We can create a 4 x 4 grid plot of thumbnails to visualize the images retrieved, allowing us to verify that the images do represent our keyword whisky. From what is displayed, it does look very much like good ol’ whisky to me."
},
{
"code": null,
"e": 4195,
"s": 3898,
"text": "f, axes = plt.subplots(4, 4)for i in range(4): for j in range(4): image_data = requests.get(thumbnail_urls[i+4*j]) image_data.raise_for_status() image = Image.open(BytesIO(image_data.content)) axes[i][j].imshow(image) axes[i][j].axis(\"off\")plt.show()"
},
{
"code": null,
"e": 4342,
"s": 4195,
"text": "The next step is to collate the list of image URLs from the search results JSON file. The key that is associated with the image URL is contentUrl."
},
{
"code": null,
"e": 4421,
"s": 4342,
"text": "img_urls = [img['contentUrl'] for img in search_results[\"value\"]]len(img_urls)"
},
{
"code": null,
"e": 4640,
"s": 4421,
"text": "The len function should return us a list of 150 image URLs related to the keyword whisky. We then download and display a single image from a URL into the destination file named whisky_test.jpg inside our images folder."
},
{
"code": null,
"e": 4746,
"s": 4640,
"text": "dest = 'images/whisky_test.jpg'download_url(img_urls[1], dest)img = Image.open(dest)img.to_thumb(224,224)"
},
{
"code": null,
"e": 4879,
"s": 4746,
"text": "We got ourselves a whisky image above, showing that the chunks of code above worked perfectly. We are now ready for the main action."
},
{
"code": null,
"e": 5031,
"s": 4879,
"text": "Update: As the image download method is dynamic, please refer to the fast.ai Images section to find out what is the latest approach for image downloads"
},
{
"code": null,
"e": 5271,
"s": 5031,
"text": "It would be interesting to distinguish the images of common alcohol types, namely whisky, wine and beer. To do that, we first define the three alcohol types in a list, and create a Path to store the images we are going to download shortly."
},
{
"code": null,
"e": 5334,
"s": 5271,
"text": "alcohol_types = ['whisky','wine','beer']path = Path('alcohol')"
},
{
"code": null,
"e": 5480,
"s": 5334,
"text": "For each of the three alcohol types, we create a subpath to store the images, and we proceed to download the images from the image URLs collated."
},
{
"code": null,
"e": 6137,
"s": 5480,
"text": "if not path.exists(): path.mkdir() for alc_type in alcohol_types: dest = (path/alc_type) dest.mkdir(exist_ok=True) search_term = alc_type params = {\"q\":search_term, \"license\":\"public\", \"imageType\":\"photo\", \"count\":\"150\"} response = requests.get(search_url, headers=headers, params=params) response.raise_for_status() search_results = response.json() img_urls = [img['contentUrl'] for img in search_results[\"value\"]] # Downloading images from the list of image URLs download_images(dest, urls=img_urls)"
},
{
"code": null,
"e": 6306,
"s": 6137,
"text": "We should now have the images downloaded within the respective folders with the label of the alcohol type. To confirm this, we can utilize the get_image_files function."
},
{
"code": null,
"e": 6701,
"s": 6306,
"text": "img_files = get_image_files(path)img_files(#445) [Path('alcohol/beer/00000069.jpeg'),Path('alcohol/beer/00000007.jpg'),Path('alcohol/beer/00000092.jpg'),Path('alcohol/beer/00000054.jpg'),Path('alcohol/beer/00000082.jpg'),Path('alcohol/beer/00000071.jpg'),Path('alcohol/beer/00000045.jpg'),Path('alcohol/beer/00000134.jpg'),Path('alcohol/beer/00000061.jpg'),Path('alcohol/beer/00000138.jpg')...]"
},
{
"code": null,
"e": 6888,
"s": 6701,
"text": "Another method to verify the downloads is to click on the Files icon on the left navigation bar of the Google Colab screen, and navigate to content>alcohol to see the respective folders."
},
{
"code": null,
"e": 7063,
"s": 6888,
"text": "After that, we need to check whether the files we downloaded are corrupt or not. Fortunately, fastai provides a convenient way to do just that, via theverify_images function."
},
{
"code": null,
"e": 7103,
"s": 7063,
"text": "failed = verify_images(img_files)failed"
},
{
"code": null,
"e": 7214,
"s": 7103,
"text": "We can then proceed to remove these corrupt files (if any) from our dataset, using the map and unlink methods."
},
{
"code": null,
"e": 7238,
"s": 7214,
"text": "failed.map(Path.unlink)"
},
{
"code": null,
"e": 7508,
"s": 7238,
"text": "fastai has a flexible system called the data block API. With this API, we can fully customize the creation of the DataLoaders object. DataLoaders can store whatever DataLoader objects we place in it, and it is used to generate training and validation sets subsequently."
},
{
"code": null,
"e": 7705,
"s": 7508,
"text": "In my interpretation, DataLoaders is essentially an object that stores information about the data we will run our model on. The DataBlock is basically a template function for creating DataLoaders."
},
{
"code": null,
"e": 7898,
"s": 7705,
"text": "alcohols = DataBlock( blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, splitter=RandomSplitter(valid_pct=0.2, seed=1), get_y=parent_label, item_tfms=Resize(128))"
},
{
"code": null,
"e": 7944,
"s": 7898,
"text": "Let’s go through the above code part by part:"
},
{
"code": null,
"e": 7979,
"s": 7944,
"text": "blocks=(ImageBlock, CategoryBlock)"
},
{
"code": null,
"e": 8236,
"s": 7979,
"text": "This blocks tuple indicates the data types for our independent and dependent variables respectively. Since our aim here is to classify images, our independent variable is images (ImageBlock) while our dependent variable is categories/labels (CategoryBlock)"
},
{
"code": null,
"e": 8262,
"s": 8236,
"text": "get_items=get_image_files"
},
{
"code": null,
"e": 8622,
"s": 8262,
"text": "The get_items argument specifies the function to be used in order to extract the file paths of the images in our dataset. Recall we earlier used the fastai built-in get_image_files to get the file paths into the variable img_files. This get_image_files function takes a path (which we will specify later), and returns a list of all of the images in that path."
},
{
"code": null,
"e": 8669,
"s": 8622,
"text": "splitter=RandomSplitter(valid_pct=0.2, seed=1)"
},
{
"code": null,
"e": 9029,
"s": 8669,
"text": "The splitter method will split the dataset into training and validation sets. We specify RandomSplitter to ensure that it is split randomly, and the valid_pct argument within it is there to indicate what percentage of the dataset is to be allocated as a validation set. The random seed can also be set within the RandomSplitter for reproducibility of results."
},
{
"code": null,
"e": 9048,
"s": 9029,
"text": "get_y=parent_label"
},
{
"code": null,
"e": 9317,
"s": 9048,
"text": "parent_label is a function provided by fastai to get the name of the folder the image files are located in. Since we have placed our images in folders with the respective alcohol type name, this parent_label will be returning the folder names of whisky, wine and beer."
},
{
"code": null,
"e": 9339,
"s": 9317,
"text": "item_tfms=Resize(128)"
},
{
"code": null,
"e": 9596,
"s": 9339,
"text": "We normally use resize images into a square as it is easier to do so, since original images can come in different height/width and aspect ratio. To do this, we perform a transformation on each item (item_tfms) by resizing it into squares of 128x128 pixels."
},
{
"code": null,
"e": 9850,
"s": 9596,
"text": "Now that all the details and arguments have been provided, we can then proceed to initiate the DataLoaders with the following single line of code. Notice that the argument for dataloaders is the path where our images are stored i.e. alcohol folder path."
},
{
"code": null,
"e": 9883,
"s": 9850,
"text": "dls = alcohols.dataloaders(path)"
},
{
"code": null,
"e": 9986,
"s": 9883,
"text": "Let’s have a brief look at the images by showing a subset batch of 10 images inside our validation set"
},
{
"code": null,
"e": 10352,
"s": 9986,
"text": "Note: The following display of image thumbnails is a good way to validate whether the data download was performed correctly. Previously when I ran this code, I realise that I did not update the search_term accordingly, resulting in all images being that of whisky. If done correctly, the following batch should show a myriad of the images from different categories."
},
{
"code": null,
"e": 10392,
"s": 10352,
"text": "dls.valid.show_batch(max_n=12, nrows=2)"
},
{
"code": null,
"e": 10688,
"s": 10392,
"text": "Before proceeding further, it is important to talk about the concept of data augmentation. In order to enrich our training dataset, we can create random variations of our input data, such that they appear different, but do not actually change the original meaning and representation of the data."
},
{
"code": null,
"e": 10906,
"s": 10688,
"text": "A common way to do this includes RandomResizedCrop, which grabs a random subset of the original image. We use unique=True to have the same image repeated with different versions of theRandomResizedCrop transformation."
},
{
"code": null,
"e": 11370,
"s": 10906,
"text": "What happens is that on each epoch (which is one complete pass through all of our images in the dataset), we randomly select a different part of each image. This means that our model can learn to recognize different features in our images. It also reflects how images work in the real world, since different photos of the same item may be framed in slightly different ways. The benefit of using item transformation is that it in turn helps to prevent overfitting."
},
{
"code": null,
"e": 11619,
"s": 11370,
"text": "The min_scale parameter specified determines how much of the image to select at minimum each time. With all the above decided, we can create a new DataBlock object using the .new method, and running it to give us a new DataLoaders object named dls."
},
{
"code": null,
"e": 11775,
"s": 11619,
"text": "alcohols = alcohols.new(item_tfms=RandomResizedCrop(128, min_scale=0.3))dls = alcohols.dataloaders(path)dls.train.show_batch(max_n=8, nrows=2, unique=True)"
},
{
"code": null,
"e": 11987,
"s": 11775,
"text": "Following the item transformation (item_tfms), we run batch transformation (batch_tfms) where we apply a standard set of data augmentation transformations (aug_transforms()) on the batch of the individual items."
},
{
"code": null,
"e": 12188,
"s": 11987,
"text": "The difference between item_tfms and batch_tfms is that item_tfms performs the transformation on every individual item (e.g. image), whereas batch_tfms runs transformation on an entire batch of items."
},
{
"code": null,
"e": 12399,
"s": 12188,
"text": "The following code illustrates the effects of the augmentation transformation aug_transforms on a single input image. You will be able to observe some form of rotation, perspective warping and contrast changes."
},
{
"code": null,
"e": 12558,
"s": 12399,
"text": "alcohols = alcohols.new(item_tfms=Resize(128), batch_tfms=aug_transforms())dls = alcohols.dataloaders(path)dls.train.show_batch(max_n=8, nrows=2, unique=True)"
},
{
"code": null,
"e": 12864,
"s": 12558,
"text": "Now that the images are prepared (albeit not cleaned yet), we can start the training to build a simple deep learning model right off the bat. First we prepare the DataLoaders object with the following code. In this iteration, we resize and crop our images at sizes of 224x224 pixel, with min_scale of 0.5."
},
{
"code": null,
"e": 13005,
"s": 12864,
"text": "alcohols = alcohols.new( item_tfms=RandomResizedCrop(224, min_scale=0.5), batch_tfms=aug_transforms())dls = alcohols.dataloaders(path)"
},
{
"code": null,
"e": 13298,
"s": 13005,
"text": "Convoluted neural network (CNN) is the de facto type of neural network used for image classification, and that is what we will be using. In terms of the architecture, I arbitrarily chose resnet34 (i.e. 34 layers deep) for the cnn_learner fast.ai function. Details of resnet can be found here."
},
{
"code": null,
"e": 13511,
"s": 13298,
"text": "We are using the .fine_tune method instead of .fit because we are leveraging on the pretrained resnet model to perform transfer learning. We specify the number of epochs to be 4 (i.e. argument inside .fine_tune)."
},
{
"code": null,
"e": 13584,
"s": 13511,
"text": "learn = cnn_learner(dls, resnet34, metrics=error_rate)learn.fine_tune(4)"
},
{
"code": null,
"e": 13793,
"s": 13584,
"text": "From the above, we can see that after training our CNN learner for a couple of minutes, we obtain an error_rate of 0.229 (i.e. 77.1% accuracy). Not a bad start, given that we have not yet cleaned our dataset."
},
{
"code": null,
"e": 13868,
"s": 13793,
"text": "Using the Confusion Matrix allows for better visualization of the results."
},
{
"code": null,
"e": 13972,
"s": 13868,
"text": "interpretation = ClassificationInterpretation.from_learner(learn)interpretation.plot_confusion_matrix()"
},
{
"code": null,
"e": 14345,
"s": 13972,
"text": "fast.ai also provides a easy method that allows us to find out which are the images where there was the highest loss. The loss is a number that is higher if the model is incorrect (especially if it is also confident of its incorrect answer), or if it is correct, but not confident of its correct answer. These helps us identify the images which the model had trouble with."
},
{
"code": null,
"e": 14388,
"s": 14345,
"text": "interpretation.plot_top_losses(5, nrows=1)"
},
{
"code": null,
"e": 14554,
"s": 14388,
"text": "From the above, it appears that some of the problem stems from the fact that several actual labels were labelled incorrectly, instead of the predictions being wrong."
},
{
"code": null,
"e": 14898,
"s": 14554,
"text": "For example, the image in the middle of the row is quite clearly that of a pint of beer (which is exactly what the model predicted). However, the actual label assigned to it was whisky, which is incorrect. This highlights the importance of having correctly labeled data (as much as possible) before training any kind of machine learning model."
},
{
"code": null,
"e": 15137,
"s": 14898,
"text": "Notice that we ran the model before cleaning the data. In fact, doing so makes the data cleaning even easier subsequently. As shown above, the plot_top_losses can already indicate which are the images that the model has most trouble with."
},
{
"code": null,
"e": 15264,
"s": 15137,
"text": "The data cleaning process is made easy with the in-built fast.ai ImageClassifierCleaner Graphical User Interface (GUI) widget."
},
{
"code": null,
"e": 15311,
"s": 15264,
"text": "cleaner = ImageClassifierCleaner(learn)cleaner"
},
{
"code": null,
"e": 15446,
"s": 15311,
"text": "The row of images displayed are the images where the loss was highest, and this GUI gives you an opportunity to review and amend them."
},
{
"code": null,
"e": 15692,
"s": 15446,
"text": "The cleaning is done by selecting a dropdown option for each of the images above, and then running the ‘cleaning’ code iteratively. I took some time to figure this out since the online explanations were unclear, so here are some further details:"
},
{
"code": null,
"e": 16091,
"s": 15692,
"text": "Step 1: After a row of images is loaded in the cleaner output cell (e.g. Training set for Wine category), select a dropdown option for the images that you wish to edit, based on your own judgement. The options consist of deleting the image from the dataset, or moving the image into a new category. If no changes are needed, there is no need to select any option since the default option is <Keep>."
},
{
"code": null,
"e": 16230,
"s": 16091,
"text": "Step 2: Once you are done updating the options for the row of images on display, run the following ‘cleaning’ code to execute the changes."
},
{
"code": null,
"e": 16498,
"s": 16230,
"text": "# Delete images marked as deletefor idx in cleaner.delete(): cleaner.fns[idx].unlink() # Update category of image to the newly specified category by moving # it into the appropriate folderfor idx,cat in cleaner.change(): shutil.copyfile(cleaner.fns[idx], path/cat)"
},
{
"code": null,
"e": 16639,
"s": 16498,
"text": "cleaner.delete removes the images you have tagged as <Delete>, while cleaner.change shifts the image into the folder with the updated label."
},
{
"code": null,
"e": 16836,
"s": 16639,
"text": "Step 3: Head back to the cleaner cell with the row of images again, and switch to a new set of images via the dropdown menu e.g. Validation set of Beer category, or Training Set of Whisky category"
},
{
"code": null,
"e": 16980,
"s": 16836,
"text": "Step 4: After the new row of images is loaded, select the relevant dropdown options for each of the images, and then re-run the ‘cleaning’ code"
},
{
"code": null,
"e": 17095,
"s": 16980,
"text": "Step 5: Repeat steps 3 and 4 iteratively for each dataset until all the datasets have been reviewed at least once."
},
{
"code": null,
"e": 17200,
"s": 17095,
"text": "dls = alcohols.dataloaders(path)learn = cnn_learner(dls, resnet34, metrics=error_rate)learn.fine_tune(4)"
},
{
"code": null,
"e": 17492,
"s": 17200,
"text": "With just a little bit of data cleaning (mostly by removing irrelevant images with the .unlink method), we see a huge improvement in the error_rate (decreased from 0.229 to 0.096). This means that the accuracy has increased from the earlier 77.1% (before data cleaning) to the current 90.4%."
},
{
"code": null,
"e": 17596,
"s": 17492,
"text": "interpretation = ClassificationInterpretation.from_learner(learn)interpretation.plot_confusion_matrix()"
},
{
"code": null,
"e": 17745,
"s": 17596,
"text": "From the confusion matrix above, we can clearly see that the model has become better at distinguishing between the three types of alcohol beverages."
},
{
"code": null,
"e": 17933,
"s": 17745,
"text": "After the training is complete, we want to export the model so that the architecture, trained parameters and DataLoaders setup is saved. All these will be saved into a pickle (.pkl) file."
},
{
"code": null,
"e": 18011,
"s": 17933,
"text": "learn.export()path = Path()path.ls(file_exts='.pkl')(#1) [Path('export.pkl')]"
},
{
"code": null,
"e": 18239,
"s": 18011,
"text": "After loading the pickle file containing the information of our deep learning image classification model, we can use it to infer (or predict) the label of new images. The model is now loaded into the learner variable learn_inf."
},
{
"code": null,
"e": 18283,
"s": 18239,
"text": "learn_inf = load_learner(path/'export.pkl')"
},
{
"code": null,
"e": 18323,
"s": 18283,
"text": "We use a sample image to test our model"
},
{
"code": null,
"e": 18511,
"s": 18323,
"text": "# Sample imageims = ['https://alcohaul.sg/products/i/400/5f7edfe79ae56e6d7b8b49cf_0.jpg']dest = 'images/test_whisky.jpg'download_url(ims[0], dest)im = Image.open(dest)im.to_thumb(224,224)"
},
{
"code": null,
"e": 18622,
"s": 18511,
"text": "Our sample image is that of a Hibiki Harmony whisky. Let’s see if our model is able to recognize its category."
},
{
"code": null,
"e": 18778,
"s": 18622,
"text": "learn_inf.predict('images/test_whisky.jpg')('whisky', tensor(1), tensor([4.1783e-04, 9.9951e-01, 7.0310e-05]))learn_inf.dls.vocab['beer', 'whisky', 'wine']"
},
{
"code": null,
"e": 18938,
"s": 18778,
"text": "Looks like all is good. The model is able to determine with high confidence that the test image represents an image of a whisky (with a probability of 99.95%)."
},
{
"code": null,
"e": 19074,
"s": 18938,
"text": "Let’s briefly explore the deployment of the model. We first create a button for users to upload new images which they wish to classify."
},
{
"code": null,
"e": 19186,
"s": 19074,
"text": "We then make use of the PIL.Image.create method to retrieve the uploaded image and store it in the img variable"
},
{
"code": null,
"e": 19230,
"s": 19186,
"text": "btn_upload = widgets.FileUpload()btn_upload"
},
{
"code": null,
"e": 19305,
"s": 19230,
"text": "# Retrieving the uploaded imageimg = PIL.Image.create(btn_upload.data[-1])"
},
{
"code": null,
"e": 19367,
"s": 19305,
"text": "We then setup an Output widget to display the uploaded image."
},
{
"code": null,
"e": 19463,
"s": 19367,
"text": "out_pl = widgets.Output()out_pl.clear_output()with out_pl: display(img.to_thumb(224,224))out_pl"
},
{
"code": null,
"e": 19602,
"s": 19463,
"text": "The user has uploaded a Talisker 18 whisky image. It is now time to once again test the classification ability of the model we have built."
},
{
"code": null,
"e": 19756,
"s": 19602,
"text": "pred,pred_idx,probs = learn_inf.predict(img)lbl_pred = widgets.Label()lbl_pred.value = f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}'lbl_pred"
},
{
"code": null,
"e": 20006,
"s": 19756,
"text": "From the above, we can see that our model is indeed predicting the image to be that of a whisky (with 99.65% probability). We can now continue building our web app by including a Run button for users to click and initiate the classification process."
},
{
"code": null,
"e": 20125,
"s": 20006,
"text": "btn_run = widgets.Button(description='Classify Image')btn_runButton(description='Classify Image', style=ButtonStyle())"
},
{
"code": null,
"e": 20398,
"s": 20125,
"text": "We then setup a callback such that the button above can carry out a specific function upon click. What we want is that whenever the user clicks ‘Classify Image’ for the image he/she uploaded, the classification model will run and then generate a classification prediction."
},
{
"code": null,
"e": 20710,
"s": 20398,
"text": "def on_click_classify(change): img = PIL.Image.create(btn_upload.data[-1]) out_pl.clear_output() with out_pl: display(img.to_thumb(128,128)) pred,pred_idx,probs = learn_inf.predict(img) lbl_pred.value = f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}'btn_run.on_click(on_click_classify)"
},
{
"code": null,
"e": 20849,
"s": 20710,
"text": "And now, putting it all together inside a VBox so that the widgets are arranged nicely in a vertical web app template within our notebook."
},
{
"code": null,
"e": 20939,
"s": 20849,
"text": "VBox([widgets.Label('Select your alcohol!'), btn_upload, btn_run, out_pl, lbl_pred]"
},
{
"code": null,
"e": 21089,
"s": 20939,
"text": "In order to deploy this app outside of this notebook, we can make use of Voila to create a form of real standalone app (built upon Jupyter notebook)."
},
{
"code": null,
"e": 21197,
"s": 21089,
"text": "As this aspect is beyond the scope of this notebook, please feel free to explore the details of Voila here."
},
{
"code": null,
"e": 21425,
"s": 21197,
"text": "With that, we have come to the end of this tutorial. We discussed an end-to-end modeling experience, from fast.ai and Google Colab setup, to data ingestion, and all the way to setting up a simple web app for the model we built."
},
{
"code": null,
"e": 21550,
"s": 21425,
"text": "I will continue to post further walkthroughs as I continue my fast.ai learning journey. Meanwhile, time for a drink. Cheers!"
}
] |
How to catch LookupError Exception in Python? | LookupError Exception is the Base class for errors raised when something can’t be found. The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError.
An IndexError is raised when a sequence reference is out of range.
The given code is rewritten as follows to catch the exception and find its type
import sys
try:
foo = [a, s, d, f, g]
print foo[5]
except IndexError as e:
print e
print sys.exc_type
C:/Users/TutorialsPoint1~.py
list index out of range
<type 'exceptions.IndexError'> | [
{
"code": null,
"e": 1285,
"s": 1062,
"text": "LookupError Exception is the Base class for errors raised when something can’t be found. The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError."
},
{
"code": null,
"e": 1352,
"s": 1285,
"text": "An IndexError is raised when a sequence reference is out of range."
},
{
"code": null,
"e": 1432,
"s": 1352,
"text": "The given code is rewritten as follows to catch the exception and find its type"
},
{
"code": null,
"e": 1534,
"s": 1432,
"text": "import sys\ntry:\nfoo = [a, s, d, f, g]\nprint foo[5]\nexcept IndexError as e:\nprint e\nprint sys.exc_type"
},
{
"code": null,
"e": 1618,
"s": 1534,
"text": "C:/Users/TutorialsPoint1~.py\nlist index out of range\n<type 'exceptions.IndexError'>"
}
] |
NumPy - Array From Numerical Ranges | In this chapter, we will see how to create an array from numerical ranges.
This function returns an ndarray object containing evenly spaced values within a given range. The format of the function is as follows −
numpy.arange(start, stop, step, dtype)
The constructor takes the following parameters.
start
The start of an interval. If omitted, defaults to 0
stop
The end of an interval (not including this number)
step
Spacing between values, default is 1
dtype
Data type of resulting ndarray. If not given, data type of input is used
The following examples show how you can use this function.
import numpy as np
x = np.arange(5)
print x
Its output would be as follows −
[0 1 2 3 4]
import numpy as np
# dtype set
x = np.arange(5, dtype = float)
print x
Here, the output would be −
[0. 1. 2. 3. 4.]
# start and stop parameters set
import numpy as np
x = np.arange(10,20,2)
print x
Its output is as follows −
[10 12 14 16 18]
This function is similar to arange() function. In this function, instead of step size, the number of evenly spaced values between the interval is specified. The usage of this function is as follows −
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
The constructor takes the following parameters.
start
The starting value of the sequence
stop
The end value of the sequence, included in the sequence if endpoint set to true
num
The number of evenly spaced samples to be generated. Default is 50
endpoint
True by default, hence the stop value is included in the sequence. If false, it is not included
retstep
If true, returns samples and step between the consecutive numbers
dtype
Data type of output ndarray
The following examples demonstrate the use linspace function.
import numpy as np
x = np.linspace(10,20,5)
print x
Its output would be −
[10. 12.5 15. 17.5 20.]
# endpoint set to false
import numpy as np
x = np.linspace(10,20, 5, endpoint = False)
print x
The output would be −
[10. 12. 14. 16. 18.]
# find retstep value
import numpy as np
x = np.linspace(1,2,5, retstep = True)
print x
# retstep here is 0.25
Now, the output would be −
(array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)
This function returns an ndarray object that contains the numbers that are evenly spaced on a log scale. Start and stop endpoints of the scale are indices of the base, usually 10.
numpy.logspace(start, stop, num, endpoint, base, dtype)
Following parameters determine the output of logspace function.
start
The starting point of the sequence is basestart
stop
The final value of sequence is basestop
num
The number of values between the range. Default is 50
endpoint
If true, stop is the last value in the range
base
Base of log space, default is 10
dtype
Data type of output array. If not given, it depends upon other input arguments
The following examples will help you understand the logspace function.
import numpy as np
# default base is 10
a = np.logspace(1.0, 2.0, num = 10)
print a
Its output would be as follows −
[ 10. 12.91549665 16.68100537 21.5443469 27.82559402
35.93813664 46.41588834 59.94842503 77.42636827 100. ]
# set base of log space to 2
import numpy as np
a = np.logspace(1,10,num = 10, base = 2)
print a
Now, the output would be −
[ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]
63 Lectures
6 hours
Abhilash Nelson
19 Lectures
8 hours
DATAhill Solutions Srinivas Reddy
12 Lectures
3 hours
DATAhill Solutions Srinivas Reddy
10 Lectures
2.5 hours
Akbar Khan
20 Lectures
2 hours
Pruthviraja L
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2318,
"s": 2243,
"text": "In this chapter, we will see how to create an array from numerical ranges."
},
{
"code": null,
"e": 2455,
"s": 2318,
"text": "This function returns an ndarray object containing evenly spaced values within a given range. The format of the function is as follows −"
},
{
"code": null,
"e": 2495,
"s": 2455,
"text": "numpy.arange(start, stop, step, dtype)\n"
},
{
"code": null,
"e": 2543,
"s": 2495,
"text": "The constructor takes the following parameters."
},
{
"code": null,
"e": 2549,
"s": 2543,
"text": "start"
},
{
"code": null,
"e": 2601,
"s": 2549,
"text": "The start of an interval. If omitted, defaults to 0"
},
{
"code": null,
"e": 2606,
"s": 2601,
"text": "stop"
},
{
"code": null,
"e": 2657,
"s": 2606,
"text": "The end of an interval (not including this number)"
},
{
"code": null,
"e": 2662,
"s": 2657,
"text": "step"
},
{
"code": null,
"e": 2699,
"s": 2662,
"text": "Spacing between values, default is 1"
},
{
"code": null,
"e": 2705,
"s": 2699,
"text": "dtype"
},
{
"code": null,
"e": 2778,
"s": 2705,
"text": "Data type of resulting ndarray. If not given, data type of input is used"
},
{
"code": null,
"e": 2837,
"s": 2778,
"text": "The following examples show how you can use this function."
},
{
"code": null,
"e": 2883,
"s": 2837,
"text": "import numpy as np \nx = np.arange(5) \nprint x"
},
{
"code": null,
"e": 2916,
"s": 2883,
"text": "Its output would be as follows −"
},
{
"code": null,
"e": 2933,
"s": 2916,
"text": "[0 1 2 3 4]\n"
},
{
"code": null,
"e": 3006,
"s": 2933,
"text": "import numpy as np \n# dtype set \nx = np.arange(5, dtype = float)\nprint x"
},
{
"code": null,
"e": 3034,
"s": 3006,
"text": "Here, the output would be −"
},
{
"code": null,
"e": 3057,
"s": 3034,
"text": "[0. 1. 2. 3. 4.] \n"
},
{
"code": null,
"e": 3142,
"s": 3057,
"text": "# start and stop parameters set \nimport numpy as np \nx = np.arange(10,20,2) \nprint x"
},
{
"code": null,
"e": 3169,
"s": 3142,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3192,
"s": 3169,
"text": "[10 12 14 16 18] \n"
},
{
"code": null,
"e": 3392,
"s": 3192,
"text": "This function is similar to arange() function. In this function, instead of step size, the number of evenly spaced values between the interval is specified. The usage of this function is as follows −"
},
{
"code": null,
"e": 3452,
"s": 3392,
"text": "numpy.linspace(start, stop, num, endpoint, retstep, dtype)\n"
},
{
"code": null,
"e": 3500,
"s": 3452,
"text": "The constructor takes the following parameters."
},
{
"code": null,
"e": 3506,
"s": 3500,
"text": "start"
},
{
"code": null,
"e": 3541,
"s": 3506,
"text": "The starting value of the sequence"
},
{
"code": null,
"e": 3546,
"s": 3541,
"text": "stop"
},
{
"code": null,
"e": 3626,
"s": 3546,
"text": "The end value of the sequence, included in the sequence if endpoint set to true"
},
{
"code": null,
"e": 3630,
"s": 3626,
"text": "num"
},
{
"code": null,
"e": 3697,
"s": 3630,
"text": "The number of evenly spaced samples to be generated. Default is 50"
},
{
"code": null,
"e": 3706,
"s": 3697,
"text": "endpoint"
},
{
"code": null,
"e": 3802,
"s": 3706,
"text": "True by default, hence the stop value is included in the sequence. If false, it is not included"
},
{
"code": null,
"e": 3810,
"s": 3802,
"text": "retstep"
},
{
"code": null,
"e": 3876,
"s": 3810,
"text": "If true, returns samples and step between the consecutive numbers"
},
{
"code": null,
"e": 3882,
"s": 3876,
"text": "dtype"
},
{
"code": null,
"e": 3910,
"s": 3882,
"text": "Data type of output ndarray"
},
{
"code": null,
"e": 3972,
"s": 3910,
"text": "The following examples demonstrate the use linspace function."
},
{
"code": null,
"e": 4026,
"s": 3972,
"text": "import numpy as np \nx = np.linspace(10,20,5) \nprint x"
},
{
"code": null,
"e": 4048,
"s": 4026,
"text": "Its output would be −"
},
{
"code": null,
"e": 4080,
"s": 4048,
"text": "[10. 12.5 15. 17.5 20.]\n"
},
{
"code": null,
"e": 4178,
"s": 4080,
"text": "# endpoint set to false \nimport numpy as np \nx = np.linspace(10,20, 5, endpoint = False) \nprint x"
},
{
"code": null,
"e": 4200,
"s": 4178,
"text": "The output would be −"
},
{
"code": null,
"e": 4231,
"s": 4200,
"text": "[10. 12. 14. 16. 18.]\n"
},
{
"code": null,
"e": 4346,
"s": 4231,
"text": "# find retstep value \nimport numpy as np \n\nx = np.linspace(1,2,5, retstep = True) \nprint x \n# retstep here is 0.25"
},
{
"code": null,
"e": 4373,
"s": 4346,
"text": "Now, the output would be −"
},
{
"code": null,
"e": 4425,
"s": 4373,
"text": "(array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)\n"
},
{
"code": null,
"e": 4605,
"s": 4425,
"text": "This function returns an ndarray object that contains the numbers that are evenly spaced on a log scale. Start and stop endpoints of the scale are indices of the base, usually 10."
},
{
"code": null,
"e": 4662,
"s": 4605,
"text": "numpy.logspace(start, stop, num, endpoint, base, dtype)\n"
},
{
"code": null,
"e": 4726,
"s": 4662,
"text": "Following parameters determine the output of logspace function."
},
{
"code": null,
"e": 4732,
"s": 4726,
"text": "start"
},
{
"code": null,
"e": 4780,
"s": 4732,
"text": "The starting point of the sequence is basestart"
},
{
"code": null,
"e": 4785,
"s": 4780,
"text": "stop"
},
{
"code": null,
"e": 4825,
"s": 4785,
"text": "The final value of sequence is basestop"
},
{
"code": null,
"e": 4829,
"s": 4825,
"text": "num"
},
{
"code": null,
"e": 4883,
"s": 4829,
"text": "The number of values between the range. Default is 50"
},
{
"code": null,
"e": 4892,
"s": 4883,
"text": "endpoint"
},
{
"code": null,
"e": 4937,
"s": 4892,
"text": "If true, stop is the last value in the range"
},
{
"code": null,
"e": 4942,
"s": 4937,
"text": "base"
},
{
"code": null,
"e": 4975,
"s": 4942,
"text": "Base of log space, default is 10"
},
{
"code": null,
"e": 4981,
"s": 4975,
"text": "dtype"
},
{
"code": null,
"e": 5060,
"s": 4981,
"text": "Data type of output array. If not given, it depends upon other input arguments"
},
{
"code": null,
"e": 5131,
"s": 5060,
"text": "The following examples will help you understand the logspace function."
},
{
"code": null,
"e": 5218,
"s": 5131,
"text": "import numpy as np \n# default base is 10 \na = np.logspace(1.0, 2.0, num = 10) \nprint a"
},
{
"code": null,
"e": 5251,
"s": 5218,
"text": "Its output would be as follows −"
},
{
"code": null,
"e": 5405,
"s": 5251,
"text": "[ 10. 12.91549665 16.68100537 21.5443469 27.82559402 \n 35.93813664 46.41588834 59.94842503 77.42636827 100. ]\n"
},
{
"code": null,
"e": 5505,
"s": 5405,
"text": "# set base of log space to 2 \nimport numpy as np \na = np.logspace(1,10,num = 10, base = 2) \nprint a"
},
{
"code": null,
"e": 5532,
"s": 5505,
"text": "Now, the output would be −"
},
{
"code": null,
"e": 5605,
"s": 5532,
"text": "[ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.] \n"
},
{
"code": null,
"e": 5638,
"s": 5605,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5655,
"s": 5638,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5688,
"s": 5655,
"text": "\n 19 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5723,
"s": 5688,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 5756,
"s": 5723,
"text": "\n 12 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5791,
"s": 5756,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 5826,
"s": 5791,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5838,
"s": 5826,
"text": " Akbar Khan"
},
{
"code": null,
"e": 5871,
"s": 5838,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5886,
"s": 5871,
"text": " Pruthviraja L"
},
{
"code": null,
"e": 5919,
"s": 5886,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5926,
"s": 5919,
"text": " Anmol"
},
{
"code": null,
"e": 5933,
"s": 5926,
"text": " Print"
},
{
"code": null,
"e": 5944,
"s": 5933,
"text": " Add Notes"
}
] |
Minimum length of subsequence having unit GCD - GeeksforGeeks | 22 Jun, 2021
Given an array arr[] of N positive integers. The task is to find the length of the shortest sub-sequence such that the GCD of the subsequence is 1. If none of the sub-sequence has GCD 1, then print “-1“.
Examples:
Input: arr[] = {2, 6, 12, 3}Output: 2 Explanation:The GCD of 2, 3 = 1, which is the smallest length of subsequence like 2.
Input: arr[] = {2, 4}Output: -1Explanation:GCD of 2, 4 = 2
Naive Approach: The idea is to generate all possible subsequences of the given array and print the length of that subsequence whose GCD is unity and has a minimum length. If none of the sub-sequences has GCD 1, then print “-1“.
Time Complexity: O(2N) Auxiliary Space: O(1)
Efficient Approach: There are 2 key observations for solving this problem:
Two numbers will have their GCD equal to one only when their prime factors are different.Any positive number which is less than 109 can have a maximum of 9 prime factors. For Example 2×3×5×7×11×13×17×19×23 = 22, 30, 92, 870. If we multiply this number by the next prime number, which is 29, it will be greater than 10^9.
Two numbers will have their GCD equal to one only when their prime factors are different.
Any positive number which is less than 109 can have a maximum of 9 prime factors. For Example 2×3×5×7×11×13×17×19×23 = 22, 30, 92, 870. If we multiply this number by the next prime number, which is 29, it will be greater than 10^9.
Follow the steps below to solve the problem:
Express the numbers as the product of its prime factors. Since we have a maximum of 9 prime factors, we can use the concept of Bitmask to store the state of the number. For Example, prime factors of 12 are 2 and 3. This can be expressed in binary as 11 (Ignoring the preceding zeroes), meaning two prime factors are there for this number.For every number in the input array, check if any other number has the corresponding bit set or not. This could be achieved using Bitwise AND operation. The resultant of this operation is another state of our solution space.Now use the concept of Dynamic Programming to memorize the states. The idea is to use an array to store the states of the solution space. This works since only 9 bits could be set a time, and an array of size 1024 could capture all the states of the solution space.Every state uses dynamic programming to store the shortest way to reach that state.If the Bitwise AND of any two states is equal to 0, then the GCD is equal to one, i.e., if there is a possibility to reach state 0 from the current state, then it will have the minimum length sub-sequence and print that length otherwise print “-1”.
Express the numbers as the product of its prime factors. Since we have a maximum of 9 prime factors, we can use the concept of Bitmask to store the state of the number. For Example, prime factors of 12 are 2 and 3. This can be expressed in binary as 11 (Ignoring the preceding zeroes), meaning two prime factors are there for this number.
For every number in the input array, check if any other number has the corresponding bit set or not. This could be achieved using Bitwise AND operation. The resultant of this operation is another state of our solution space.
Now use the concept of Dynamic Programming to memorize the states. The idea is to use an array to store the states of the solution space. This works since only 9 bits could be set a time, and an array of size 1024 could capture all the states of the solution space.
Every state uses dynamic programming to store the shortest way to reach that state.
If the Bitwise AND of any two states is equal to 0, then the GCD is equal to one, i.e., if there is a possibility to reach state 0 from the current state, then it will have the minimum length sub-sequence and print that length otherwise print “-1”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds the prime// factors of a numbervector<int> findPrimeFactors(int n){ // To store the prime factor vector<int> primeFactors(9, 0); int j = 0; // 2s that divide n if (n % 2 == 0) { primeFactors[j++] = 2; while (n % 2 == 0) n >>= 1; } // N must be odd at this point // Skip one element for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { // Update the prime factor primeFactors[j++] = i; while (n % i == 0) n /= i; } } // If n is a prime number // greater than 2 if (n > 2) primeFactors[j++] = n; vector<int> PrimeFactors(j); for(int i = 0; i < j; i++) { PrimeFactors[i] = primeFactors[i]; } return PrimeFactors;} // Function that finds the shortest// subsequencevoid findShortestSubsequence(vector<int> &dp, vector<int> a, int index, vector<int> primeFactors){ int n = a.size(); for (int j = index; j < n; j++) { int bitmask = 0; for (int p = 0; p < primeFactors.size(); p++) { // Check if the prime factor // of first number, is also // the prime factor of the // rest numbers in array if ((a[j] % primeFactors[p]) == 0) { // Set corresponding bit // of prime factor to 1, // it means both these // numbers have the // same prime factor bitmask ^= (1 << p); } } for (int i = 0; i < dp.size(); i++) { // If no states encountered // so far continue for this // combination of bits if (dp[i] == n + 1) continue; // Update this state with // minimum ways to reach // this state dp[bitmask & i] = min(dp[bitmask & i], dp[i] + 1); } }} // Function that print the minimum// length of subsequencevoid printMinimumLength(vector<int> a){ int Min = a.size() + 1; for (int i = 0; i < a.size() - 1; i++) { // Find the prime factors of // the first number vector<int> primeFactors = findPrimeFactors(a[i]); int n = primeFactors.size(); // Initialize the array with // maximum steps, size of the // array + 1 for instance vector<int> dp(1 << n, a.size() + 1); // Express the prime factors // in bit representation // Total number of set bits is // equal to the total number // of prime factors int setBits = (1 << n) - 1; // Indicates there is one // way to reach the number // under consideration dp[setBits] = 1; findShortestSubsequence(dp, a, i + 1, primeFactors); // State 0 corresponds // to gcd of 1 Min = min(dp[0], Min); } // If not found such subsequence // then print "-1" if (Min == (a.size() + 1)) cout << -1 << endl; // Else print the length else cout << Min << endl;} // Driver codeint main(){ // Given array arr[] vector<int> arr = { 2, 6, 12, 3 }; // Function Call printMinimumLength(arr); return 0;} // This code is contributed by divyeshrabadiya07
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function that finds the prime // factors of a number private static int[] findPrimeFactors(int n) { // To store the prime factor int[] primeFactors = new int[9]; int j = 0; // 2s that divide n if (n % 2 == 0) { primeFactors[j++] = 2; while (n % 2 == 0) n >>= 1; } // N must be odd at this point // Skip one element for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { // Update the prime factor primeFactors[j++] = i; while (n % i == 0) n /= i; } } // If n is a prime number // greater than 2 if (n > 2) primeFactors[j++] = n; return Arrays.copyOfRange(primeFactors, 0, j); } // Function that finds the shortest // subsequence private static void findShortestSubsequence(int[] dp, int[] a, int index, int[] primeFactors) { int n = a.length; for (int j = index; j < n; j++) { int bitmask = 0; for (int p = 0; p < primeFactors.length; p++) { // Check if the prime factor // of first number, is also // the prime factor of the // rest numbers in array if (a[j] % primeFactors[p] == 0) { // Set corresponding bit // of prime factor to 1, // it means both these // numbers have the // same prime factor bitmask ^= (1 << p); } } for (int i = 0; i < dp.length; i++) { // If no states encountered // so far continue for this // combination of bits if (dp[i] == n + 1) continue; // Update this state with // minimum ways to reach // this state dp[bitmask & i] = Math.min(dp[bitmask & i], dp[i] + 1); } } } // Function that print the minimum // length of subsequence private static void printMinimumLength(int[] a) { int min = a.length + 1; for (int i = 0; i < a.length - 1; i++) { // Find the prime factors of // the first number int[] primeFactors = findPrimeFactors(a[i]); int n = primeFactors.length; int[] dp = new int[1 << n]; // Initialize the array with // maximum steps, size of the // array + 1 for instance Arrays.fill(dp, a.length + 1); // Express the prime factors // in bit representation // Total number of set bits is // equal to the total number // of prime factors int setBits = (1 << n) - 1; // Indicates there is one // way to reach the number // under consideration dp[setBits] = 1; findShortestSubsequence(dp, a, i + 1, primeFactors); // State 0 corresponds // to gcd of 1 min = Math.min(dp[0], min); } // If not found such subsequence // then print "-1" if (min == a.length + 1) System.out.println(-1); // Else print the length else System.out.println(min); } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 2, 6, 12, 3 }; // Function Call printMinimumLength(arr); }}
# Python3 program for the above approach # Function that finds the prime# factors of a numberdef findPrimeFactors(n): # To store the prime factor primeFactors = [0 for i in range(9)] j = 0 # 2s that divide n if (n % 2 == 0): primeFactors[j] = 2 j += 1 while (n % 2 == 0): n >>= 1 # N must be odd at this point # Skip one element i = 3 while (i * i <= n): if (n % i == 0): # Update the prime factor primeFactors[j] = i j += 1 while(n % i == 0): n //= i i += 2 # If n is a prime number # greater than 2 if (n > 2): primeFactors[j] = n j += 1 for i in range(0, j + 1): primeFactors[i] = 0 return primeFactors # Function that finds the shortest# subsequencedef findShortestSubsequence(dp, a, index, primeFactors): n = len(a) for j in range(index, n): bitmask = 0 for p in range(len(primeFactors)): # Check if the prime factor # of first number, is also # the prime factor of the # rest numbers in array if (primeFactors[p] != 0 and a[j] % primeFactors[p] == 0): # Set corresponding bit # of prime factor to 1, # it means both these # numbers have the # same prime factor bitmask ^= (1 << p) for i in range(len(dp)): # If no states encountered # so far continue for this # combination of bits if (dp[i] == n + 1): continue # Update this state with # minimum ways to reach # this state dp[bitmask & i] = min(dp[bitmask & i], dp[i] + 1) # Function that print the minimum# length of subsequencedef printMinimumLength(a): mn = len(a) + 1 for i in range(len(a) - 1): # Find the prime factors of # the first number primeFactors = findPrimeFactors(a[i]) n = len(primeFactors) dp = [0 for i in range(1 << n)] # Initialize the array with # maximum steps, size of the # array + 1 for instance dp = [len(a) + 1 for i in range(len(dp))] # Express the prime factors # in bit representation # Total number of set bits is # equal to the total number # of prime factors setBits = (1 << n) - 1 # Indicates there is one # way to reach the number # under consideration dp[setBits] = 1 findShortestSubsequence(dp, a, i + 1, primeFactors) # State 0 corresponds # to gcd of 1 mn = min(dp[0], mn) # If not found such subsequence # then print "-1" if (mn == len(a) + 1): print(-1) # Else print the length else: print(mn) # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 2, 6, 12, 3 ] # Function Call printMinimumLength(arr) # This code is contributed by bgangwar59
// C# program for// the above approachusing System;class GFG{ // Function that finds the prime// factors of a numberprivate static int[] findPrimeFactors(int n){ // To store the prime factor int[] primeFactors = new int[9]; int j = 0; // 2s that divide n if (n % 2 == 0) { primeFactors[j++] = 2; while (n % 2 == 0) n >>= 1; } // N must be odd at this point // Skip one element for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { // Update the prime factor primeFactors[j++] = i; while (n % i == 0) n /= i; } } // If n is a prime number // greater than 2 if (n > 2) primeFactors[j++] = n; int []temp = new int[j]; Array.Copy(primeFactors, temp, j); return temp;} // Function that finds the shortest// subsequenceprivate static void findShortestSubsequence(int[] dp, int[] a, int index, int[] primeFactors){ int n = a.Length; for (int j = index; j < n; j++) { int bitmask = 0; for (int p = 0; p < primeFactors.Length; p++) { // Check if the prime factor // of first number, is also // the prime factor of the // rest numbers in array if (a[j] % primeFactors[p] == 0) { // Set corresponding bit // of prime factor to 1, // it means both these // numbers have the // same prime factor bitmask ^= (1 << p); } } for (int i = 0; i < dp.Length; i++) { // If no states encountered // so far continue for this // combination of bits if (dp[i] == n + 1) continue; // Update this state with // minimum ways to reach // this state dp[bitmask & i] = Math.Min(dp[bitmask & i], dp[i] + 1); } }} // Function that print the minimum// length of subsequenceprivate static void printMinimumLength(int[] a){ int min = a.Length + 1; for (int i = 0; i < a.Length - 1; i++) { // Find the prime factors of // the first number int[] primeFactors = findPrimeFactors(a[i]); int n = primeFactors.Length; int[] dp = new int[1 << n]; // Initialize the array with // maximum steps, size of the // array + 1 for instance for(i = 0; i < dp.Length; i++) dp[i] = a.Length + 1; // Express the prime factors // in bit representation // Total number of set bits is // equal to the total number // of prime factors int setBits = (1 << n) - 1; // Indicates there is one // way to reach the number // under consideration dp[setBits] = 1; findShortestSubsequence(dp, a, i + 1, primeFactors); // State 0 corresponds // to gcd of 1 min = Math.Min(dp[0], min); } // If not found such subsequence // then print "-1" if (min == a.Length + 1) Console.WriteLine(-1); // Else print the length else Console.WriteLine(min);} // Driver Codepublic static void Main(String[] args){ // Given array []arr int[] arr = {2, 6, 12, 3}; // Function Call printMinimumLength(arr);}} // This code is contributed by Rajput-Ji
<script>// Javascript program for the above approach // Function that finds the prime// factors of a numberfunction findPrimeFactors(n){ // To store the prime factor let primeFactors = new Array(9).fill(0); let j = 0; // 2s that divide n if (n % 2 == 0) { primeFactors[j++] = 2; while (n % 2 == 0) n >>= 1; } // N must be odd at this point // Skip one element for (let i = 3; i * i <= n; i += 2) { if (n % i == 0) { // Update the prime factor primeFactors[j++] = i; while (n % i == 0) n /= i; } } // If n is a prime number // greater than 2 if (n > 2) primeFactors[j++] = n; let PrimeFactors = new Array(j); for(let i = 0; i < j; i++) { PrimeFactors[i] = primeFactors[i]; } return PrimeFactors;} // Function that finds the shortest// subsequencefunction findShortestSubsequence(dp, a, index, primeFactors){ let n = a.length; for (let j = index; j < n; j++) { let bitmask = 0; for (let p = 0; p < primeFactors.length; p++) { // Check if the prime factor // of first number, is also // the prime factor of the // rest numbers in array if ((a[j] % primeFactors[p]) == 0) { // Set corresponding bit // of prime factor to 1, // it means both these // numbers have the // same prime factor bitmask ^= (1 << p); } } for (let i = 0; i < dp.length; i++) { // If no states encountered // so far continue for this // combination of bits if (dp[i] == n + 1) continue; // Update this state with // minimum ways to reach // this state dp[bitmask & i] = Math.min(dp[bitmask & i], dp[i] + 1); } }} // Function that print the minimum// length of subsequencefunction prletMinimumLength(a){ let Min = a.length + 1; for (let i = 0; i < a.length - 1; i++) { // Find the prime factors of // the first number let primeFactors = findPrimeFactors(a[i]); let n = primeFactors.length; // Initialize the array with // maximum steps, size of the // array + 1 for instance let dp = new Array(1 << n); for(let i = 0; i < dp.length; i++){ dp[i] = a.length + 1 } // Express the prime factors // in bit representation // Total number of set bits is // equal to the total number // of prime factors let setBits = (1 << n) - 1; // Indicates there is one // way to reach the number // under consideration dp[setBits] = 1; findShortestSubsequence(dp, a, i + 1, primeFactors); // State 0 corresponds // to gcd of 1 Min = Math.min(dp[0], Min); } // If not found such subsequence // then print "-1" if (Min == (a.length + 1)) document.write(-1 + "<br>"); // Else print the length else document.write(Min + "<br>");} // Driver code // Given array arr[] let arr = [ 2, 6, 12, 3 ]; // Function Call prletMinimumLength(arr); // This code is contributed by _saurabh_jaiswal</script>
2
Time Complexity: O(N2)Auxiliary Space: O(1)
jithin
Rajput-Ji
bgangwar59
divyeshrabadiya07
gfgking
khushboogoyal499
Algorithms-Dynamic Programming
Bitwise-AND
GCD-LCM
subsequence
Arrays
Bit Magic
Dynamic Programming
Mathematical
Arrays
Dynamic Programming
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division | [
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 24634,
"s": 24429,
"text": "Given an array arr[] of N positive integers. The task is to find the length of the shortest sub-sequence such that the GCD of the subsequence is 1. If none of the sub-sequence has GCD 1, then print “-1“. "
},
{
"code": null,
"e": 24644,
"s": 24634,
"text": "Examples:"
},
{
"code": null,
"e": 24768,
"s": 24644,
"text": "Input: arr[] = {2, 6, 12, 3}Output: 2 Explanation:The GCD of 2, 3 = 1, which is the smallest length of subsequence like 2."
},
{
"code": null,
"e": 24828,
"s": 24768,
"text": "Input: arr[] = {2, 4}Output: -1Explanation:GCD of 2, 4 = 2 "
},
{
"code": null,
"e": 25056,
"s": 24828,
"text": "Naive Approach: The idea is to generate all possible subsequences of the given array and print the length of that subsequence whose GCD is unity and has a minimum length. If none of the sub-sequences has GCD 1, then print “-1“."
},
{
"code": null,
"e": 25103,
"s": 25056,
"text": "Time Complexity: O(2N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 25179,
"s": 25103,
"text": "Efficient Approach: There are 2 key observations for solving this problem: "
},
{
"code": null,
"e": 25500,
"s": 25179,
"text": "Two numbers will have their GCD equal to one only when their prime factors are different.Any positive number which is less than 109 can have a maximum of 9 prime factors. For Example 2×3×5×7×11×13×17×19×23 = 22, 30, 92, 870. If we multiply this number by the next prime number, which is 29, it will be greater than 10^9."
},
{
"code": null,
"e": 25590,
"s": 25500,
"text": "Two numbers will have their GCD equal to one only when their prime factors are different."
},
{
"code": null,
"e": 25822,
"s": 25590,
"text": "Any positive number which is less than 109 can have a maximum of 9 prime factors. For Example 2×3×5×7×11×13×17×19×23 = 22, 30, 92, 870. If we multiply this number by the next prime number, which is 29, it will be greater than 10^9."
},
{
"code": null,
"e": 25867,
"s": 25822,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27026,
"s": 25867,
"text": "Express the numbers as the product of its prime factors. Since we have a maximum of 9 prime factors, we can use the concept of Bitmask to store the state of the number. For Example, prime factors of 12 are 2 and 3. This can be expressed in binary as 11 (Ignoring the preceding zeroes), meaning two prime factors are there for this number.For every number in the input array, check if any other number has the corresponding bit set or not. This could be achieved using Bitwise AND operation. The resultant of this operation is another state of our solution space.Now use the concept of Dynamic Programming to memorize the states. The idea is to use an array to store the states of the solution space. This works since only 9 bits could be set a time, and an array of size 1024 could capture all the states of the solution space.Every state uses dynamic programming to store the shortest way to reach that state.If the Bitwise AND of any two states is equal to 0, then the GCD is equal to one, i.e., if there is a possibility to reach state 0 from the current state, then it will have the minimum length sub-sequence and print that length otherwise print “-1”."
},
{
"code": null,
"e": 27365,
"s": 27026,
"text": "Express the numbers as the product of its prime factors. Since we have a maximum of 9 prime factors, we can use the concept of Bitmask to store the state of the number. For Example, prime factors of 12 are 2 and 3. This can be expressed in binary as 11 (Ignoring the preceding zeroes), meaning two prime factors are there for this number."
},
{
"code": null,
"e": 27590,
"s": 27365,
"text": "For every number in the input array, check if any other number has the corresponding bit set or not. This could be achieved using Bitwise AND operation. The resultant of this operation is another state of our solution space."
},
{
"code": null,
"e": 27856,
"s": 27590,
"text": "Now use the concept of Dynamic Programming to memorize the states. The idea is to use an array to store the states of the solution space. This works since only 9 bits could be set a time, and an array of size 1024 could capture all the states of the solution space."
},
{
"code": null,
"e": 27940,
"s": 27856,
"text": "Every state uses dynamic programming to store the shortest way to reach that state."
},
{
"code": null,
"e": 28189,
"s": 27940,
"text": "If the Bitwise AND of any two states is equal to 0, then the GCD is equal to one, i.e., if there is a possibility to reach state 0 from the current state, then it will have the minimum length sub-sequence and print that length otherwise print “-1”."
},
{
"code": null,
"e": 28240,
"s": 28189,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28244,
"s": 28240,
"text": "C++"
},
{
"code": null,
"e": 28249,
"s": 28244,
"text": "Java"
},
{
"code": null,
"e": 28257,
"s": 28249,
"text": "Python3"
},
{
"code": null,
"e": 28260,
"s": 28257,
"text": "C#"
},
{
"code": null,
"e": 28271,
"s": 28260,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds the prime// factors of a numbervector<int> findPrimeFactors(int n){ // To store the prime factor vector<int> primeFactors(9, 0); int j = 0; // 2s that divide n if (n % 2 == 0) { primeFactors[j++] = 2; while (n % 2 == 0) n >>= 1; } // N must be odd at this point // Skip one element for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { // Update the prime factor primeFactors[j++] = i; while (n % i == 0) n /= i; } } // If n is a prime number // greater than 2 if (n > 2) primeFactors[j++] = n; vector<int> PrimeFactors(j); for(int i = 0; i < j; i++) { PrimeFactors[i] = primeFactors[i]; } return PrimeFactors;} // Function that finds the shortest// subsequencevoid findShortestSubsequence(vector<int> &dp, vector<int> a, int index, vector<int> primeFactors){ int n = a.size(); for (int j = index; j < n; j++) { int bitmask = 0; for (int p = 0; p < primeFactors.size(); p++) { // Check if the prime factor // of first number, is also // the prime factor of the // rest numbers in array if ((a[j] % primeFactors[p]) == 0) { // Set corresponding bit // of prime factor to 1, // it means both these // numbers have the // same prime factor bitmask ^= (1 << p); } } for (int i = 0; i < dp.size(); i++) { // If no states encountered // so far continue for this // combination of bits if (dp[i] == n + 1) continue; // Update this state with // minimum ways to reach // this state dp[bitmask & i] = min(dp[bitmask & i], dp[i] + 1); } }} // Function that print the minimum// length of subsequencevoid printMinimumLength(vector<int> a){ int Min = a.size() + 1; for (int i = 0; i < a.size() - 1; i++) { // Find the prime factors of // the first number vector<int> primeFactors = findPrimeFactors(a[i]); int n = primeFactors.size(); // Initialize the array with // maximum steps, size of the // array + 1 for instance vector<int> dp(1 << n, a.size() + 1); // Express the prime factors // in bit representation // Total number of set bits is // equal to the total number // of prime factors int setBits = (1 << n) - 1; // Indicates there is one // way to reach the number // under consideration dp[setBits] = 1; findShortestSubsequence(dp, a, i + 1, primeFactors); // State 0 corresponds // to gcd of 1 Min = min(dp[0], Min); } // If not found such subsequence // then print \"-1\" if (Min == (a.size() + 1)) cout << -1 << endl; // Else print the length else cout << Min << endl;} // Driver codeint main(){ // Given array arr[] vector<int> arr = { 2, 6, 12, 3 }; // Function Call printMinimumLength(arr); return 0;} // This code is contributed by divyeshrabadiya07",
"e": 31767,
"s": 28271,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function that finds the prime // factors of a number private static int[] findPrimeFactors(int n) { // To store the prime factor int[] primeFactors = new int[9]; int j = 0; // 2s that divide n if (n % 2 == 0) { primeFactors[j++] = 2; while (n % 2 == 0) n >>= 1; } // N must be odd at this point // Skip one element for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { // Update the prime factor primeFactors[j++] = i; while (n % i == 0) n /= i; } } // If n is a prime number // greater than 2 if (n > 2) primeFactors[j++] = n; return Arrays.copyOfRange(primeFactors, 0, j); } // Function that finds the shortest // subsequence private static void findShortestSubsequence(int[] dp, int[] a, int index, int[] primeFactors) { int n = a.length; for (int j = index; j < n; j++) { int bitmask = 0; for (int p = 0; p < primeFactors.length; p++) { // Check if the prime factor // of first number, is also // the prime factor of the // rest numbers in array if (a[j] % primeFactors[p] == 0) { // Set corresponding bit // of prime factor to 1, // it means both these // numbers have the // same prime factor bitmask ^= (1 << p); } } for (int i = 0; i < dp.length; i++) { // If no states encountered // so far continue for this // combination of bits if (dp[i] == n + 1) continue; // Update this state with // minimum ways to reach // this state dp[bitmask & i] = Math.min(dp[bitmask & i], dp[i] + 1); } } } // Function that print the minimum // length of subsequence private static void printMinimumLength(int[] a) { int min = a.length + 1; for (int i = 0; i < a.length - 1; i++) { // Find the prime factors of // the first number int[] primeFactors = findPrimeFactors(a[i]); int n = primeFactors.length; int[] dp = new int[1 << n]; // Initialize the array with // maximum steps, size of the // array + 1 for instance Arrays.fill(dp, a.length + 1); // Express the prime factors // in bit representation // Total number of set bits is // equal to the total number // of prime factors int setBits = (1 << n) - 1; // Indicates there is one // way to reach the number // under consideration dp[setBits] = 1; findShortestSubsequence(dp, a, i + 1, primeFactors); // State 0 corresponds // to gcd of 1 min = Math.min(dp[0], min); } // If not found such subsequence // then print \"-1\" if (min == a.length + 1) System.out.println(-1); // Else print the length else System.out.println(min); } // Driver Code public static void main(String[] args) { // Given array arr[] int[] arr = { 2, 6, 12, 3 }; // Function Call printMinimumLength(arr); }}",
"e": 35696,
"s": 31767,
"text": null
},
{
"code": "# Python3 program for the above approach # Function that finds the prime# factors of a numberdef findPrimeFactors(n): # To store the prime factor primeFactors = [0 for i in range(9)] j = 0 # 2s that divide n if (n % 2 == 0): primeFactors[j] = 2 j += 1 while (n % 2 == 0): n >>= 1 # N must be odd at this point # Skip one element i = 3 while (i * i <= n): if (n % i == 0): # Update the prime factor primeFactors[j] = i j += 1 while(n % i == 0): n //= i i += 2 # If n is a prime number # greater than 2 if (n > 2): primeFactors[j] = n j += 1 for i in range(0, j + 1): primeFactors[i] = 0 return primeFactors # Function that finds the shortest# subsequencedef findShortestSubsequence(dp, a, index, primeFactors): n = len(a) for j in range(index, n): bitmask = 0 for p in range(len(primeFactors)): # Check if the prime factor # of first number, is also # the prime factor of the # rest numbers in array if (primeFactors[p] != 0 and a[j] % primeFactors[p] == 0): # Set corresponding bit # of prime factor to 1, # it means both these # numbers have the # same prime factor bitmask ^= (1 << p) for i in range(len(dp)): # If no states encountered # so far continue for this # combination of bits if (dp[i] == n + 1): continue # Update this state with # minimum ways to reach # this state dp[bitmask & i] = min(dp[bitmask & i], dp[i] + 1) # Function that print the minimum# length of subsequencedef printMinimumLength(a): mn = len(a) + 1 for i in range(len(a) - 1): # Find the prime factors of # the first number primeFactors = findPrimeFactors(a[i]) n = len(primeFactors) dp = [0 for i in range(1 << n)] # Initialize the array with # maximum steps, size of the # array + 1 for instance dp = [len(a) + 1 for i in range(len(dp))] # Express the prime factors # in bit representation # Total number of set bits is # equal to the total number # of prime factors setBits = (1 << n) - 1 # Indicates there is one # way to reach the number # under consideration dp[setBits] = 1 findShortestSubsequence(dp, a, i + 1, primeFactors) # State 0 corresponds # to gcd of 1 mn = min(dp[0], mn) # If not found such subsequence # then print \"-1\" if (mn == len(a) + 1): print(-1) # Else print the length else: print(mn) # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [ 2, 6, 12, 3 ] # Function Call printMinimumLength(arr) # This code is contributed by bgangwar59",
"e": 38961,
"s": 35696,
"text": null
},
{
"code": "// C# program for// the above approachusing System;class GFG{ // Function that finds the prime// factors of a numberprivate static int[] findPrimeFactors(int n){ // To store the prime factor int[] primeFactors = new int[9]; int j = 0; // 2s that divide n if (n % 2 == 0) { primeFactors[j++] = 2; while (n % 2 == 0) n >>= 1; } // N must be odd at this point // Skip one element for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { // Update the prime factor primeFactors[j++] = i; while (n % i == 0) n /= i; } } // If n is a prime number // greater than 2 if (n > 2) primeFactors[j++] = n; int []temp = new int[j]; Array.Copy(primeFactors, temp, j); return temp;} // Function that finds the shortest// subsequenceprivate static void findShortestSubsequence(int[] dp, int[] a, int index, int[] primeFactors){ int n = a.Length; for (int j = index; j < n; j++) { int bitmask = 0; for (int p = 0; p < primeFactors.Length; p++) { // Check if the prime factor // of first number, is also // the prime factor of the // rest numbers in array if (a[j] % primeFactors[p] == 0) { // Set corresponding bit // of prime factor to 1, // it means both these // numbers have the // same prime factor bitmask ^= (1 << p); } } for (int i = 0; i < dp.Length; i++) { // If no states encountered // so far continue for this // combination of bits if (dp[i] == n + 1) continue; // Update this state with // minimum ways to reach // this state dp[bitmask & i] = Math.Min(dp[bitmask & i], dp[i] + 1); } }} // Function that print the minimum// length of subsequenceprivate static void printMinimumLength(int[] a){ int min = a.Length + 1; for (int i = 0; i < a.Length - 1; i++) { // Find the prime factors of // the first number int[] primeFactors = findPrimeFactors(a[i]); int n = primeFactors.Length; int[] dp = new int[1 << n]; // Initialize the array with // maximum steps, size of the // array + 1 for instance for(i = 0; i < dp.Length; i++) dp[i] = a.Length + 1; // Express the prime factors // in bit representation // Total number of set bits is // equal to the total number // of prime factors int setBits = (1 << n) - 1; // Indicates there is one // way to reach the number // under consideration dp[setBits] = 1; findShortestSubsequence(dp, a, i + 1, primeFactors); // State 0 corresponds // to gcd of 1 min = Math.Min(dp[0], min); } // If not found such subsequence // then print \"-1\" if (min == a.Length + 1) Console.WriteLine(-1); // Else print the length else Console.WriteLine(min);} // Driver Codepublic static void Main(String[] args){ // Given array []arr int[] arr = {2, 6, 12, 3}; // Function Call printMinimumLength(arr);}} // This code is contributed by Rajput-Ji",
"e": 42139,
"s": 38961,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function that finds the prime// factors of a numberfunction findPrimeFactors(n){ // To store the prime factor let primeFactors = new Array(9).fill(0); let j = 0; // 2s that divide n if (n % 2 == 0) { primeFactors[j++] = 2; while (n % 2 == 0) n >>= 1; } // N must be odd at this point // Skip one element for (let i = 3; i * i <= n; i += 2) { if (n % i == 0) { // Update the prime factor primeFactors[j++] = i; while (n % i == 0) n /= i; } } // If n is a prime number // greater than 2 if (n > 2) primeFactors[j++] = n; let PrimeFactors = new Array(j); for(let i = 0; i < j; i++) { PrimeFactors[i] = primeFactors[i]; } return PrimeFactors;} // Function that finds the shortest// subsequencefunction findShortestSubsequence(dp, a, index, primeFactors){ let n = a.length; for (let j = index; j < n; j++) { let bitmask = 0; for (let p = 0; p < primeFactors.length; p++) { // Check if the prime factor // of first number, is also // the prime factor of the // rest numbers in array if ((a[j] % primeFactors[p]) == 0) { // Set corresponding bit // of prime factor to 1, // it means both these // numbers have the // same prime factor bitmask ^= (1 << p); } } for (let i = 0; i < dp.length; i++) { // If no states encountered // so far continue for this // combination of bits if (dp[i] == n + 1) continue; // Update this state with // minimum ways to reach // this state dp[bitmask & i] = Math.min(dp[bitmask & i], dp[i] + 1); } }} // Function that print the minimum// length of subsequencefunction prletMinimumLength(a){ let Min = a.length + 1; for (let i = 0; i < a.length - 1; i++) { // Find the prime factors of // the first number let primeFactors = findPrimeFactors(a[i]); let n = primeFactors.length; // Initialize the array with // maximum steps, size of the // array + 1 for instance let dp = new Array(1 << n); for(let i = 0; i < dp.length; i++){ dp[i] = a.length + 1 } // Express the prime factors // in bit representation // Total number of set bits is // equal to the total number // of prime factors let setBits = (1 << n) - 1; // Indicates there is one // way to reach the number // under consideration dp[setBits] = 1; findShortestSubsequence(dp, a, i + 1, primeFactors); // State 0 corresponds // to gcd of 1 Min = Math.min(dp[0], Min); } // If not found such subsequence // then print \"-1\" if (Min == (a.length + 1)) document.write(-1 + \"<br>\"); // Else print the length else document.write(Min + \"<br>\");} // Driver code // Given array arr[] let arr = [ 2, 6, 12, 3 ]; // Function Call prletMinimumLength(arr); // This code is contributed by _saurabh_jaiswal</script>",
"e": 45576,
"s": 42139,
"text": null
},
{
"code": null,
"e": 45578,
"s": 45576,
"text": "2"
},
{
"code": null,
"e": 45623,
"s": 45578,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 45630,
"s": 45623,
"text": "jithin"
},
{
"code": null,
"e": 45640,
"s": 45630,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 45651,
"s": 45640,
"text": "bgangwar59"
},
{
"code": null,
"e": 45669,
"s": 45651,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 45677,
"s": 45669,
"text": "gfgking"
},
{
"code": null,
"e": 45694,
"s": 45677,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 45725,
"s": 45694,
"text": "Algorithms-Dynamic Programming"
},
{
"code": null,
"e": 45737,
"s": 45725,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 45745,
"s": 45737,
"text": "GCD-LCM"
},
{
"code": null,
"e": 45757,
"s": 45745,
"text": "subsequence"
},
{
"code": null,
"e": 45764,
"s": 45757,
"text": "Arrays"
},
{
"code": null,
"e": 45774,
"s": 45764,
"text": "Bit Magic"
},
{
"code": null,
"e": 45794,
"s": 45774,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 45807,
"s": 45794,
"text": "Mathematical"
},
{
"code": null,
"e": 45814,
"s": 45807,
"text": "Arrays"
},
{
"code": null,
"e": 45834,
"s": 45814,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 45847,
"s": 45834,
"text": "Mathematical"
},
{
"code": null,
"e": 45857,
"s": 45847,
"text": "Bit Magic"
},
{
"code": null,
"e": 45955,
"s": 45857,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45964,
"s": 45955,
"text": "Comments"
},
{
"code": null,
"e": 45977,
"s": 45964,
"text": "Old Comments"
},
{
"code": null,
"e": 45998,
"s": 45977,
"text": "Next Greater Element"
},
{
"code": null,
"e": 46023,
"s": 45998,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 46050,
"s": 46023,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 46099,
"s": 46050,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 46137,
"s": 46099,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 46164,
"s": 46137,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 46210,
"s": 46164,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 46278,
"s": 46210,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 46307,
"s": 46278,
"text": "Count set bits in an integer"
}
] |
Explain HTML formatting in PowerShell? | HTML is another form of output in PowerShell. It is the rich form of output and you can use various CSS styles to make the output more interactive. We will use the Convertto-HTML cmdlet to convert the output in the HTML format.
Here is the Syntax of the Convertto-HTML cmdlet.
ConvertTo-Html
[-InputObject <PSObject>]
[[-Property] <Object[]>]
[[-Body] <String[]>]
[[-Head] <String[]>]
[[-Title] <String>]
[-As <String>]
[-CssUri <Uri>]
[-PostContent <String[]>]
[-PreContent <String[]>]
[-Meta <Hashtable>]
[-Charset <String>]
[-Transitional]
[<CommonParameters>]
ConvertTo-Html
[-InputObject <PSObject>]
[[-Property] <Object[]>]
[-As <String>]
[-Fragment]
[-PostContent <String[]>]
[-PreContent <String[]>]
[<CommonParameters>]
Let's take one simple example of Convertto-HTML with InputObject parameter.
ConvertTo-Html -InputObject (Get-Date)
The output will be on the same console.
PS C:\WINDOWS\system32> ConvertTo-Html -InputObject (Get-Date)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML TABLE<title>
</head><body>
<table>
<colgroup><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/></colgroup>
<tr><th>DisplayHint</th><th>DateTime</th><th>Date</th><th>Day</th><th>DayOfWeek</th><th>DayOfYear</th><th>Hour</th><th>Kind<th><th>Millisecond</th><
th>Minute</th><th>Month</th><th>Second</th><th>Ticks</th><th>TimeOfDay</th><th>Year</th></tr>
<tr><td>DateTime</td><td>17 June 2020 08:33:06</td><td>17-06-2020 00:00:00</td><td>17</td><td>Wednesday</td><td>169</td><td>8</td><td>Local</td><td>8
29</td><td>33</td><td>6</td><td>6</td><td>637279795868299280</td><td>08:33:06.8299280</td><td>2020</td></tr>
</table>
</body></html>
So, you need to redirect the output in the .html extension.
ConvertTo-Html -InputObject (Get-Date) > C:\temp\dateoutput.html
Here, You can also use the Pipeline as the Input Object. An example is shown below.
Below we will convert Get-Service output to HTML format.
Get-Service | Select Name, Status, StartType | ConvertTo-Html | Out-File Servicesoutput.html
When you check the output in a file called ServicesOutput.html, HTML file will be as below.
You can also check the content of the HTML by right click and edit with Notepad, Notepad++ or any compatible editor.
The HTML file will be as below in the editor. You can see that the title “HTML Table”, it is added automatically. You can change the title in the editor but it won’t help as it will be overwritten to default every time you run the script.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML TABLE</title>
</head><body>
<table>
<colgroup><col/><col/><col/></colgroup>
<tr><th>Name</th><th>Status</th><th>StartType</th></tr>
<tr><td>AarSvc_69f5c</td><td>Stopped</td><td>Manual</td></tr>
<tr><td>AdobeARMservice</td><td>Running</td><td>Automatic</td></tr>
<tr><td>AdobeFlashPlayerUpdateSvc</td><td>Stopped</td><td>Manual</td></tr>
<tr><td>AJRouter</td><td>Stopped</td><td>Manual</td></tr>
<tr><td>ALG</td><td>Stopped</td><td>Manual</td></tr>
<tr><td>AppIDSvc</td><td>Stopped</td><td>Manual</td></tr>
<tr><td>Appinfo</td><td>Running</td<td>Manual</td></tr>
<tr><td>AppMgmt</td><td>Stopped</td><td>Manual</td></tr>
<tr><td>AppReadiness</td><td>Stopped</td><td>Manual</td></tr>
<tr><td>AppVClient</td><td>Stopped</td><td>Disabled</td></tr>
So to add the title in the script, you need to use the –Title parameter. For example,
Get-Service | Select Name, Status, StartType | ConvertTo-Html -Title "Services Output" | Out-File Servicesoutput.html
When you check the output, you will can see the title.
And the HTML file of the above output in the editor, you can see the new title now.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Services Output</title>
</head><body>
<table>
Instead of using Pipeline properties in Get-Services output, you can also use the Convertto-HTML properties to select the output from the previous command.
For example,
Get-Service | ConvertTo-Html -Property Name, Status, Starttype -Title "Services Output" | Out-File Servicesoutput.html
It will yield the same result as the above HTML output.
If you need to add the description before the result, you need to use –PreContent parameter. For example,
Get-Service | ConvertTo-Html -Property Name, Status, Starttype -Title "Services Output" -PreContent "Services Output" | Out-File Servicesoutput.html
You can twik the precontent with the HTML headers. For example,
Get-Service | ConvertTo-Html -Property Name, Status, Starttype -Title "Services Output" -PreContent "<h1><center>Services Output</center></h1>" | Out-File Servicesoutput.html
Output
In the above example, we have put the header and center alignment for the PreContent. Similarly, you can use the PostContent to display the title at the bottom. For example,
Get-Service | ConvertTo-Html -Property Name, Status, Starttype -Title "Services Output" -PreContent "<h1><center>Services Output</center></h1>" -PostContent "<div align=right><b>From: PowerShell Scripter</b></div>" | Out-File Servicesoutput.html | [
{
"code": null,
"e": 1290,
"s": 1062,
"text": "HTML is another form of output in PowerShell. It is the rich form of output and you can use various CSS styles to make the output more interactive. We will use the Convertto-HTML cmdlet to convert the output in the HTML format."
},
{
"code": null,
"e": 1339,
"s": 1290,
"text": "Here is the Syntax of the Convertto-HTML cmdlet."
},
{
"code": null,
"e": 1872,
"s": 1339,
"text": "ConvertTo-Html\n [-InputObject <PSObject>]\n [[-Property] <Object[]>]\n [[-Body] <String[]>]\n [[-Head] <String[]>]\n [[-Title] <String>]\n [-As <String>]\n [-CssUri <Uri>]\n [-PostContent <String[]>]\n [-PreContent <String[]>]\n [-Meta <Hashtable>]\n [-Charset <String>]\n [-Transitional]\n [<CommonParameters>]\n\nConvertTo-Html\n [-InputObject <PSObject>]\n [[-Property] <Object[]>]\n [-As <String>]\n [-Fragment]\n [-PostContent <String[]>]\n [-PreContent <String[]>]\n [<CommonParameters>]"
},
{
"code": null,
"e": 1948,
"s": 1872,
"text": "Let's take one simple example of Convertto-HTML with InputObject parameter."
},
{
"code": null,
"e": 1988,
"s": 1948,
"text": "ConvertTo-Html -InputObject (Get-Date)\n"
},
{
"code": null,
"e": 2028,
"s": 1988,
"text": "The output will be on the same console."
},
{
"code": null,
"e": 2938,
"s": 2028,
"text": "PS C:\\WINDOWS\\system32> ConvertTo-Html -InputObject (Get-Date)\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>HTML TABLE<title>\n</head><body>\n<table>\n<colgroup><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/></colgroup>\n<tr><th>DisplayHint</th><th>DateTime</th><th>Date</th><th>Day</th><th>DayOfWeek</th><th>DayOfYear</th><th>Hour</th><th>Kind<th><th>Millisecond</th><\nth>Minute</th><th>Month</th><th>Second</th><th>Ticks</th><th>TimeOfDay</th><th>Year</th></tr>\n<tr><td>DateTime</td><td>17 June 2020 08:33:06</td><td>17-06-2020 00:00:00</td><td>17</td><td>Wednesday</td><td>169</td><td>8</td><td>Local</td><td>8\n29</td><td>33</td><td>6</td><td>6</td><td>637279795868299280</td><td>08:33:06.8299280</td><td>2020</td></tr>\n</table>\n</body></html>"
},
{
"code": null,
"e": 2998,
"s": 2938,
"text": "So, you need to redirect the output in the .html extension."
},
{
"code": null,
"e": 3064,
"s": 2998,
"text": "ConvertTo-Html -InputObject (Get-Date) > C:\\temp\\dateoutput.html\n"
},
{
"code": null,
"e": 3148,
"s": 3064,
"text": "Here, You can also use the Pipeline as the Input Object. An example is shown below."
},
{
"code": null,
"e": 3205,
"s": 3148,
"text": "Below we will convert Get-Service output to HTML format."
},
{
"code": null,
"e": 3298,
"s": 3205,
"text": "Get-Service | Select Name, Status, StartType | ConvertTo-Html | Out-File Servicesoutput.html"
},
{
"code": null,
"e": 3390,
"s": 3298,
"text": "When you check the output in a file called ServicesOutput.html, HTML file will be as below."
},
{
"code": null,
"e": 3507,
"s": 3390,
"text": "You can also check the content of the HTML by right click and edit with Notepad, Notepad++ or any compatible editor."
},
{
"code": null,
"e": 3746,
"s": 3507,
"text": "The HTML file will be as below in the editor. You can see that the title “HTML Table”, it is added automatically. You can change the title in the editor but it won’t help as it will be overwritten to default every time you run the script."
},
{
"code": null,
"e": 4662,
"s": 3746,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>HTML TABLE</title>\n</head><body>\n<table>\n<colgroup><col/><col/><col/></colgroup>\n<tr><th>Name</th><th>Status</th><th>StartType</th></tr>\n<tr><td>AarSvc_69f5c</td><td>Stopped</td><td>Manual</td></tr>\n<tr><td>AdobeARMservice</td><td>Running</td><td>Automatic</td></tr>\n<tr><td>AdobeFlashPlayerUpdateSvc</td><td>Stopped</td><td>Manual</td></tr>\n<tr><td>AJRouter</td><td>Stopped</td><td>Manual</td></tr>\n<tr><td>ALG</td><td>Stopped</td><td>Manual</td></tr>\n<tr><td>AppIDSvc</td><td>Stopped</td><td>Manual</td></tr>\n<tr><td>Appinfo</td><td>Running</td<td>Manual</td></tr>\n<tr><td>AppMgmt</td><td>Stopped</td><td>Manual</td></tr>\n<tr><td>AppReadiness</td><td>Stopped</td><td>Manual</td></tr>\n<tr><td>AppVClient</td><td>Stopped</td><td>Disabled</td></tr>"
},
{
"code": null,
"e": 4748,
"s": 4662,
"text": "So to add the title in the script, you need to use the –Title parameter. For example,"
},
{
"code": null,
"e": 4867,
"s": 4748,
"text": "Get-Service | Select Name, Status, StartType | ConvertTo-Html -Title \"Services Output\" | Out-File Servicesoutput.html\n"
},
{
"code": null,
"e": 4922,
"s": 4867,
"text": "When you check the output, you will can see the title."
},
{
"code": null,
"e": 5006,
"s": 4922,
"text": "And the HTML file of the above output in the editor, you can see the new title now."
},
{
"code": null,
"e": 5220,
"s": 5006,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>Services Output</title>\n</head><body>\n<table>"
},
{
"code": null,
"e": 5376,
"s": 5220,
"text": "Instead of using Pipeline properties in Get-Services output, you can also use the Convertto-HTML properties to select the output from the previous command."
},
{
"code": null,
"e": 5389,
"s": 5376,
"text": "For example,"
},
{
"code": null,
"e": 5510,
"s": 5389,
"text": "Get-Service | ConvertTo-Html -Property Name, Status, Starttype -Title \"Services Output\" | Out-File Servicesoutput.html\n"
},
{
"code": null,
"e": 5566,
"s": 5510,
"text": "It will yield the same result as the above HTML output."
},
{
"code": null,
"e": 5672,
"s": 5566,
"text": "If you need to add the description before the result, you need to use –PreContent parameter. For example,"
},
{
"code": null,
"e": 5822,
"s": 5672,
"text": "Get-Service | ConvertTo-Html -Property Name, Status, Starttype -Title \"Services Output\" -PreContent \"Services Output\" | Out-File Servicesoutput.html"
},
{
"code": null,
"e": 5886,
"s": 5822,
"text": "You can twik the precontent with the HTML headers. For example,"
},
{
"code": null,
"e": 6062,
"s": 5886,
"text": "Get-Service | ConvertTo-Html -Property Name, Status, Starttype -Title \"Services Output\" -PreContent \"<h1><center>Services Output</center></h1>\" | Out-File Servicesoutput.html\n"
},
{
"code": null,
"e": 6069,
"s": 6062,
"text": "Output"
},
{
"code": null,
"e": 6243,
"s": 6069,
"text": "In the above example, we have put the header and center alignment for the PreContent. Similarly, you can use the PostContent to display the title at the bottom. For example,"
},
{
"code": null,
"e": 6489,
"s": 6243,
"text": "Get-Service | ConvertTo-Html -Property Name, Status, Starttype -Title \"Services Output\" -PreContent \"<h1><center>Services Output</center></h1>\" -PostContent \"<div align=right><b>From: PowerShell Scripter</b></div>\" | Out-File Servicesoutput.html"
}
] |
Check whether a number is Good prime or not | 14 May, 2021
Given a positive integer N, the task is to check whether the given number is good prime or not. If the given number is good prime print ‘YES’ Otherwise Print ‘NO’.
Good Prime: In Mathematics, a good prime is a prime number whose square is greater than the product of any two primes at the same number of positions before and after it in the sequence of primes. In other word, A prime Pn is said to be good prime if it for every 1 <= i < n.
The first few good primes are: 5, 11, 17, 29, 37, 41, 53, 59, 67, 71, 97, 101, 127, 149, 179, 191, 223, ....
Examples:
Input: N = 5 Output: YES Explanation: 5 is a good prime number since 5^2 = 25 is greater than 3.7 = 21 and 2.11 = 22.
Input: N = 20 Output: NO
Approach:
1. Get the number N.
2. Initialise prev_prime = N-1 and next_prime = N+1
3. Iterate the loop while prev_prime is greater than or equal to 2. And check for both next_prime and prev_prime are prime of not using prime number.
4. If both are not prime, then repeat step 2 and 3.
5. If both next_prime and prev_prime are prime, then check N^2 > next_prime . prev_prime or not.
If Not then number is not good prime and stop the execution and return NO.
If Yes then repeat the step 2, 3, 4 and 5.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if a number// is good prime or not#include<bits/stdc++.h>using namespace std; // Function to check if a// number is Prime or notbool isPrime (int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can // skip middle five numbers in loop if (n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true;} // Function to check if the// given number is Good primebool isGoodprime (int n){ // Smallest good prime is 5 // So the number less than 5 // can not be a Good prime if (n < 5) return false; int prev_prime = n - 1; int next_prime = n + 1; while (prev_prime >= 2) { // Calculate first prime number < n while (!isPrime(prev_prime)) { prev_prime--; } // Calculate first prime number > n while (!isPrime(next_prime)) { next_prime++; } // Check if product of next_prime // and prev_prime is less than n^2 if ((prev_prime * next_prime) >= n * n) return false; prev_prime -= 1; next_prime += 1; } return true;} // Driver codeint main(){ int n = 11; if (isGoodprime(n)) cout << "YES"; else cout << "NO"; return 0;} // This code is contributed by himanshu77
// Java program to check if a number is// good prime or notclass GFG{ // Function to check if a// number is prime or notstatic boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true;} // Function to check if the given// number is good prime or notstatic boolean isGoodrprime(int n){ // Smallest good prime is 5 // So the number less than 5 // can not be a good prime if (n < 5) return false; int prev_prime = n - 1; int next_prime = n + 1; while (prev_prime >= 2) { // Calculate first prime number < n while (!isPrime(prev_prime)) { prev_prime--; } // Calculate first prime number > n while (!isPrime(next_prime)) { next_prime++; } // Check if product of next_prime // and prev_prime // is less than n^2 if ((prev_prime * next_prime) >= n * n) return false; prev_prime -= 1; next_prime += 1; } return true;} // Driver codepublic static void main(String []args){ int n = 11; if (isGoodrprime(n)) System.out.println("YES"); else System.out.println("NO");}} // This code is contributed by amal kumar choubey
# Python3 program to check if a number is# good prime or not # Utility function to check# if a number is prime or notdef isPrime(n): # Corner cases if (n <= 1): return False if (n <= 3): return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0): return False i = 5 while (i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return False i = i + 6 return True # Function to check if the given number# is good prime or notdef isGoodrPrime(n): # Declaring variables as global global next_prime, prev_prime # Smallest good prime is 5 # So the number less than 5 # can not be a good prime if(n < 5): return False # Initialize previous_prime to n - 1 # and next_prime to n + 1 prev_prime = n - 1 next_prime = n + 1 while(prev_prime >= 2): # Calculate first prime number < n while (not isPrime(prev_prime)): prev_prime -= 1 # Calculate first prime number > n while(not isPrime(next_prime)): next_prime += 1 # Check if product of next_prime # and prev_prime # is less than n^2 if((prev_prime * next_prime) >= n * n): return False prev_prime -= 1 next_prime += 1 return True # Driver codeif __name__ == '__main__': n = 11 if(isGoodrPrime(n)): print("Yes") else: print("No") # This code is contributed by Shivam Singh
// C# program to check if a number is// good prime or not using System;class GFG { // Function to check if a // number is prime or not static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } // Function to check // if the given number is good prime or not static bool isGoodrprime(int n) { // Smallest good prime is 5 // So the number less than 5 // can not be a good prime if (n < 5) return false; int prev_prime = n - 1; int next_prime = n + 1; while (prev_prime >= 2) { // Calculate first prime number < n while (!isPrime(prev_prime)) { prev_prime--; } // Calculate first prime number > n while (!isPrime(next_prime)) { next_prime++; } // check if product of next_prime // and prev_prime // is less than n^2 if ((prev_prime * next_prime) >= n * n) return false; prev_prime -= 1; next_prime += 1; } return true; } public static void Main() { int n = 11; if (isGoodrprime(n)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }}
<script> // Javascript program to check if a number// is good prime or not // Function to check if a// number is Prime or notfunction isPrime (n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can // skip middle five numbers in loop if (n % 2 == 0 || n % 3 == 0) return false; for(let i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true;} // Function to check if the// given number is Good prime function isGoodprime (n){ // Smallest good prime is 5 // So the number less than 5 // can not be a Good prime if (n < 5) return false; let prev_prime = n - 1; let next_prime = n + 1; while (prev_prime >= 2) { // Calculate first prime number < n while (!isPrime(prev_prime)) { prev_prime--; } // Calculate first prime number > n while (!isPrime(next_prime)) { next_prime++; } // Check if product of next_prime // and prev_prime is less than n^2 if ((prev_prime * next_prime) >= n * n) return false; prev_prime -= 1; next_prime += 1; } return true;} // Driver code let n = 11; if (isGoodprime(n)) document.write("YES"); else document.write("NO"); // This code is contributed by Mayank Tyagi </script>
YES
Time Complexity: O(n3/2)
Auxiliary Space: O(1)
SHIVAMSINGH67
Amal Kumar Choubey
himanshu77
subhammahato348
mayanktyagi1709
arorakashish0911
Prime Number
Mathematical
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 219,
"s": 54,
"text": "Given a positive integer N, the task is to check whether the given number is good prime or not. If the given number is good prime print ‘YES’ Otherwise Print ‘NO’. "
},
{
"code": null,
"e": 495,
"s": 219,
"text": "Good Prime: In Mathematics, a good prime is a prime number whose square is greater than the product of any two primes at the same number of positions before and after it in the sequence of primes. In other word, A prime Pn is said to be good prime if it for every 1 <= i < n."
},
{
"code": null,
"e": 604,
"s": 495,
"text": "The first few good primes are: 5, 11, 17, 29, 37, 41, 53, 59, 67, 71, 97, 101, 127, 149, 179, 191, 223, ...."
},
{
"code": null,
"e": 614,
"s": 604,
"text": "Examples:"
},
{
"code": null,
"e": 734,
"s": 614,
"text": "Input: N = 5 Output: YES Explanation: 5 is a good prime number since 5^2 = 25 is greater than 3.7 = 21 and 2.11 = 22. "
},
{
"code": null,
"e": 761,
"s": 734,
"text": "Input: N = 20 Output: NO "
},
{
"code": null,
"e": 771,
"s": 761,
"text": "Approach:"
},
{
"code": null,
"e": 792,
"s": 771,
"text": "1. Get the number N."
},
{
"code": null,
"e": 844,
"s": 792,
"text": "2. Initialise prev_prime = N-1 and next_prime = N+1"
},
{
"code": null,
"e": 994,
"s": 844,
"text": "3. Iterate the loop while prev_prime is greater than or equal to 2. And check for both next_prime and prev_prime are prime of not using prime number."
},
{
"code": null,
"e": 1046,
"s": 994,
"text": "4. If both are not prime, then repeat step 2 and 3."
},
{
"code": null,
"e": 1143,
"s": 1046,
"text": "5. If both next_prime and prev_prime are prime, then check N^2 > next_prime . prev_prime or not."
},
{
"code": null,
"e": 1218,
"s": 1143,
"text": "If Not then number is not good prime and stop the execution and return NO."
},
{
"code": null,
"e": 1261,
"s": 1218,
"text": "If Yes then repeat the step 2, 3, 4 and 5."
},
{
"code": null,
"e": 1312,
"s": 1261,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1316,
"s": 1312,
"text": "C++"
},
{
"code": null,
"e": 1321,
"s": 1316,
"text": "Java"
},
{
"code": null,
"e": 1329,
"s": 1321,
"text": "Python3"
},
{
"code": null,
"e": 1332,
"s": 1329,
"text": "C#"
},
{
"code": null,
"e": 1343,
"s": 1332,
"text": "Javascript"
},
{
"code": "// C++ program to check if a number// is good prime or not#include<bits/stdc++.h>using namespace std; // Function to check if a// number is Prime or notbool isPrime (int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can // skip middle five numbers in loop if (n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true;} // Function to check if the// given number is Good primebool isGoodprime (int n){ // Smallest good prime is 5 // So the number less than 5 // can not be a Good prime if (n < 5) return false; int prev_prime = n - 1; int next_prime = n + 1; while (prev_prime >= 2) { // Calculate first prime number < n while (!isPrime(prev_prime)) { prev_prime--; } // Calculate first prime number > n while (!isPrime(next_prime)) { next_prime++; } // Check if product of next_prime // and prev_prime is less than n^2 if ((prev_prime * next_prime) >= n * n) return false; prev_prime -= 1; next_prime += 1; } return true;} // Driver codeint main(){ int n = 11; if (isGoodprime(n)) cout << \"YES\"; else cout << \"NO\"; return 0;} // This code is contributed by himanshu77",
"e": 2825,
"s": 1343,
"text": null
},
{
"code": "// Java program to check if a number is// good prime or notclass GFG{ // Function to check if a// number is prime or notstatic boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true;} // Function to check if the given// number is good prime or notstatic boolean isGoodrprime(int n){ // Smallest good prime is 5 // So the number less than 5 // can not be a good prime if (n < 5) return false; int prev_prime = n - 1; int next_prime = n + 1; while (prev_prime >= 2) { // Calculate first prime number < n while (!isPrime(prev_prime)) { prev_prime--; } // Calculate first prime number > n while (!isPrime(next_prime)) { next_prime++; } // Check if product of next_prime // and prev_prime // is less than n^2 if ((prev_prime * next_prime) >= n * n) return false; prev_prime -= 1; next_prime += 1; } return true;} // Driver codepublic static void main(String []args){ int n = 11; if (isGoodrprime(n)) System.out.println(\"YES\"); else System.out.println(\"NO\");}} // This code is contributed by amal kumar choubey",
"e": 4392,
"s": 2825,
"text": null
},
{
"code": "# Python3 program to check if a number is# good prime or not # Utility function to check# if a number is prime or notdef isPrime(n): # Corner cases if (n <= 1): return False if (n <= 3): return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0): return False i = 5 while (i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return False i = i + 6 return True # Function to check if the given number# is good prime or notdef isGoodrPrime(n): # Declaring variables as global global next_prime, prev_prime # Smallest good prime is 5 # So the number less than 5 # can not be a good prime if(n < 5): return False # Initialize previous_prime to n - 1 # and next_prime to n + 1 prev_prime = n - 1 next_prime = n + 1 while(prev_prime >= 2): # Calculate first prime number < n while (not isPrime(prev_prime)): prev_prime -= 1 # Calculate first prime number > n while(not isPrime(next_prime)): next_prime += 1 # Check if product of next_prime # and prev_prime # is less than n^2 if((prev_prime * next_prime) >= n * n): return False prev_prime -= 1 next_prime += 1 return True # Driver codeif __name__ == '__main__': n = 11 if(isGoodrPrime(n)): print(\"Yes\") else: print(\"No\") # This code is contributed by Shivam Singh",
"e": 5916,
"s": 4392,
"text": null
},
{
"code": "// C# program to check if a number is// good prime or not using System;class GFG { // Function to check if a // number is prime or not static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } // Function to check // if the given number is good prime or not static bool isGoodrprime(int n) { // Smallest good prime is 5 // So the number less than 5 // can not be a good prime if (n < 5) return false; int prev_prime = n - 1; int next_prime = n + 1; while (prev_prime >= 2) { // Calculate first prime number < n while (!isPrime(prev_prime)) { prev_prime--; } // Calculate first prime number > n while (!isPrime(next_prime)) { next_prime++; } // check if product of next_prime // and prev_prime // is less than n^2 if ((prev_prime * next_prime) >= n * n) return false; prev_prime -= 1; next_prime += 1; } return true; } public static void Main() { int n = 11; if (isGoodrprime(n)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }}",
"e": 7620,
"s": 5916,
"text": null
},
{
"code": "<script> // Javascript program to check if a number// is good prime or not // Function to check if a// number is Prime or notfunction isPrime (n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can // skip middle five numbers in loop if (n % 2 == 0 || n % 3 == 0) return false; for(let i = 5; i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true;} // Function to check if the// given number is Good prime function isGoodprime (n){ // Smallest good prime is 5 // So the number less than 5 // can not be a Good prime if (n < 5) return false; let prev_prime = n - 1; let next_prime = n + 1; while (prev_prime >= 2) { // Calculate first prime number < n while (!isPrime(prev_prime)) { prev_prime--; } // Calculate first prime number > n while (!isPrime(next_prime)) { next_prime++; } // Check if product of next_prime // and prev_prime is less than n^2 if ((prev_prime * next_prime) >= n * n) return false; prev_prime -= 1; next_prime += 1; } return true;} // Driver code let n = 11; if (isGoodprime(n)) document.write(\"YES\"); else document.write(\"NO\"); // This code is contributed by Mayank Tyagi </script>",
"e": 9074,
"s": 7620,
"text": null
},
{
"code": null,
"e": 9078,
"s": 9074,
"text": "YES"
},
{
"code": null,
"e": 9105,
"s": 9080,
"text": "Time Complexity: O(n3/2)"
},
{
"code": null,
"e": 9127,
"s": 9105,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9141,
"s": 9127,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 9160,
"s": 9141,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 9171,
"s": 9160,
"text": "himanshu77"
},
{
"code": null,
"e": 9187,
"s": 9171,
"text": "subhammahato348"
},
{
"code": null,
"e": 9203,
"s": 9187,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 9220,
"s": 9203,
"text": "arorakashish0911"
},
{
"code": null,
"e": 9233,
"s": 9220,
"text": "Prime Number"
},
{
"code": null,
"e": 9246,
"s": 9233,
"text": "Mathematical"
},
{
"code": null,
"e": 9259,
"s": 9246,
"text": "Mathematical"
},
{
"code": null,
"e": 9272,
"s": 9259,
"text": "Prime Number"
}
] |
Merge two DataFrames in PySpark | 04 May, 2022
In this article, we will learn how to merge multiple data frames row-wise in PySpark. Outside chaining unions this is the only way to do it for DataFrames. The module used is pyspark :
Spark (open-source Big-Data processing engine by Apache) is a cluster computing system. It is faster as compared to other cluster computing systems (such as Hadoop). It provides high-level APIs in Python, Scala, and Java. Parallel jobs are easy to write in Spark. We will cover PySpark (Python + Apache Spark) because this will make the learning curve flatter. To install Spark on a linux system, follow this. To run Spark in a multi–cluster system, follow this.
To do our task we are defining a function called recursively for all the input dataframes and union this one by one. To union, we use pyspark module:
Dataframe union() – union() method of the DataFrame is employed to mix two DataFrame’s of an equivalent structure/schema. If schemas aren’t equivalent it returns a mistake.
DataFrame unionAll() – unionAll() is deprecated since Spark “2.0.0” version and replaced with union().
Note: In other SQL’s, Union eliminates the duplicates but UnionAll combines two datasets including duplicate records. But, in spark both behave an equivalent and use DataFrame duplicate function to get rid of duplicate rows.
At the last call, it returns the required resultant dataframe. The following code represents the logic behind our solution to the given problem.
Python3
from functools import reduce # For Python 3.xfrom pyspark.sql import DataFrame def unionAll(*dfs): return reduce(DataFrame.unionAll, dfs) unionAll(td2, td3, td4, td5, td6, td7, td8, td9, td10)
What takes place is that it takes all the objects that you handed as parameters and reduces them the usage of unionAll (this limit is from Python, no longer the Spark minimize even though they work similarly) which sooner or later reduces it to one DataFrame.
If rather of DataFrames are ordinary RDDs you can bypass a listing of them to the union feature of your SparkContext
Sometimes, when the dataframes to combine do not have the same order of columns, it is better to df2.select(df1.columns) in order to ensure both df have the same column order before the union.
Python3
import functools def unionAll(dfs): return functools.reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs)
The reduce(fun,seq) function is used to apply a particular function passed in its argument to all the list elements mentioned in the sequence passed along. This function is defined in functools module.
Now, let’s understand the whole process with the help of some examples.
Example 1:
In this example, we create dataframes with columns ‘a’ and ‘b’ of some random values and pass all these three dataframe to our above-created method unionAll() and get the resultant dataframe as output and show the result.
Python3
# import modulesfrom pyspark.sql import SparkSessionimport functools # explicit functiondef unionAll(dfs): return functools.reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs) spark = SparkSession.builder.getOrCreate()df1 = spark.createDataFrame([[1, 1], [2, 2]], ['a', 'b']) # different column order.df2 = spark.createDataFrame([[3, 333], [4, 444]], ['b', 'a'])df3 = spark.createDataFrame([[555, 5], [666, 6]], ['b', 'a']) unioned_df = unionAll([df1, df2, df3])unioned_df.show()
Output:
Example 2:
In this example, we create dataframes with columns ‘a’ and ‘b’ of some random values and pass all these three dataframe to our newly created method unionAll() in which we are not focusing on the names of the columns. We are just doing union the input dataframe to the next dataframe and get the resultant dataframe as output and show the result.
Python3
# import modulesfrom functools import reduce from pyspark.sql import DataFramefrom pyspark.sql import SparkSession # explicit functionsdef unionAll(*dfs): return reduce(DataFrame.unionAll, dfs) spark = SparkSession.builder.getOrCreate() df1 = spark.createDataFrame([[1, 1], [2, 2]], ['a', 'b']) # different column order.df2 = spark.createDataFrame([[3, 333], [4, 444]], ['b', 'a'])df3 = spark.createDataFrame([[555, 5], [666, 6]], ['b', 'a']) unionAll(*[df1, df2, df3]).show()
Output:
Important:
Notice how values for columns a, b are mixed up in here – that’s because when performing a union the order the columns isn’t matching.
since both columns are of type string we get no error.
In order to perform a valid union order should match across all DataFrames.another option is using UnionByName
vladislavgrischinsky
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 May, 2022"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "In this article, we will learn how to merge multiple data frames row-wise in PySpark. Outside chaining unions this is the only way to do it for DataFrames. The module used is pyspark :"
},
{
"code": null,
"e": 676,
"s": 213,
"text": "Spark (open-source Big-Data processing engine by Apache) is a cluster computing system. It is faster as compared to other cluster computing systems (such as Hadoop). It provides high-level APIs in Python, Scala, and Java. Parallel jobs are easy to write in Spark. We will cover PySpark (Python + Apache Spark) because this will make the learning curve flatter. To install Spark on a linux system, follow this. To run Spark in a multi–cluster system, follow this."
},
{
"code": null,
"e": 826,
"s": 676,
"text": "To do our task we are defining a function called recursively for all the input dataframes and union this one by one. To union, we use pyspark module:"
},
{
"code": null,
"e": 999,
"s": 826,
"text": "Dataframe union() – union() method of the DataFrame is employed to mix two DataFrame’s of an equivalent structure/schema. If schemas aren’t equivalent it returns a mistake."
},
{
"code": null,
"e": 1102,
"s": 999,
"text": "DataFrame unionAll() – unionAll() is deprecated since Spark “2.0.0” version and replaced with union()."
},
{
"code": null,
"e": 1327,
"s": 1102,
"text": "Note: In other SQL’s, Union eliminates the duplicates but UnionAll combines two datasets including duplicate records. But, in spark both behave an equivalent and use DataFrame duplicate function to get rid of duplicate rows."
},
{
"code": null,
"e": 1473,
"s": 1327,
"text": " At the last call, it returns the required resultant dataframe. The following code represents the logic behind our solution to the given problem."
},
{
"code": null,
"e": 1481,
"s": 1473,
"text": "Python3"
},
{
"code": "from functools import reduce # For Python 3.xfrom pyspark.sql import DataFrame def unionAll(*dfs): return reduce(DataFrame.unionAll, dfs) unionAll(td2, td3, td4, td5, td6, td7, td8, td9, td10)",
"e": 1678,
"s": 1481,
"text": null
},
{
"code": null,
"e": 1938,
"s": 1678,
"text": "What takes place is that it takes all the objects that you handed as parameters and reduces them the usage of unionAll (this limit is from Python, no longer the Spark minimize even though they work similarly) which sooner or later reduces it to one DataFrame."
},
{
"code": null,
"e": 2055,
"s": 1938,
"text": "If rather of DataFrames are ordinary RDDs you can bypass a listing of them to the union feature of your SparkContext"
},
{
"code": null,
"e": 2248,
"s": 2055,
"text": "Sometimes, when the dataframes to combine do not have the same order of columns, it is better to df2.select(df1.columns) in order to ensure both df have the same column order before the union."
},
{
"code": null,
"e": 2256,
"s": 2248,
"text": "Python3"
},
{
"code": "import functools def unionAll(dfs): return functools.reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs)",
"e": 2377,
"s": 2256,
"text": null
},
{
"code": null,
"e": 2579,
"s": 2377,
"text": "The reduce(fun,seq) function is used to apply a particular function passed in its argument to all the list elements mentioned in the sequence passed along. This function is defined in functools module."
},
{
"code": null,
"e": 2651,
"s": 2579,
"text": "Now, let’s understand the whole process with the help of some examples."
},
{
"code": null,
"e": 2663,
"s": 2651,
"text": "Example 1: "
},
{
"code": null,
"e": 2885,
"s": 2663,
"text": "In this example, we create dataframes with columns ‘a’ and ‘b’ of some random values and pass all these three dataframe to our above-created method unionAll() and get the resultant dataframe as output and show the result."
},
{
"code": null,
"e": 2893,
"s": 2885,
"text": "Python3"
},
{
"code": "# import modulesfrom pyspark.sql import SparkSessionimport functools # explicit functiondef unionAll(dfs): return functools.reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs) spark = SparkSession.builder.getOrCreate()df1 = spark.createDataFrame([[1, 1], [2, 2]], ['a', 'b']) # different column order.df2 = spark.createDataFrame([[3, 333], [4, 444]], ['b', 'a'])df3 = spark.createDataFrame([[555, 5], [666, 6]], ['b', 'a']) unioned_df = unionAll([df1, df2, df3])unioned_df.show()",
"e": 3390,
"s": 2893,
"text": null
},
{
"code": null,
"e": 3398,
"s": 3390,
"text": "Output:"
},
{
"code": null,
"e": 3410,
"s": 3398,
"text": "Example 2: "
},
{
"code": null,
"e": 3756,
"s": 3410,
"text": "In this example, we create dataframes with columns ‘a’ and ‘b’ of some random values and pass all these three dataframe to our newly created method unionAll() in which we are not focusing on the names of the columns. We are just doing union the input dataframe to the next dataframe and get the resultant dataframe as output and show the result."
},
{
"code": null,
"e": 3764,
"s": 3756,
"text": "Python3"
},
{
"code": "# import modulesfrom functools import reduce from pyspark.sql import DataFramefrom pyspark.sql import SparkSession # explicit functionsdef unionAll(*dfs): return reduce(DataFrame.unionAll, dfs) spark = SparkSession.builder.getOrCreate() df1 = spark.createDataFrame([[1, 1], [2, 2]], ['a', 'b']) # different column order.df2 = spark.createDataFrame([[3, 333], [4, 444]], ['b', 'a'])df3 = spark.createDataFrame([[555, 5], [666, 6]], ['b', 'a']) unionAll(*[df1, df2, df3]).show()",
"e": 4245,
"s": 3764,
"text": null
},
{
"code": null,
"e": 4253,
"s": 4245,
"text": "Output:"
},
{
"code": null,
"e": 4264,
"s": 4253,
"text": "Important:"
},
{
"code": null,
"e": 4399,
"s": 4264,
"text": "Notice how values for columns a, b are mixed up in here – that’s because when performing a union the order the columns isn’t matching."
},
{
"code": null,
"e": 4454,
"s": 4399,
"text": "since both columns are of type string we get no error."
},
{
"code": null,
"e": 4565,
"s": 4454,
"text": "In order to perform a valid union order should match across all DataFrames.another option is using UnionByName"
},
{
"code": null,
"e": 4586,
"s": 4565,
"text": "vladislavgrischinsky"
},
{
"code": null,
"e": 4593,
"s": 4586,
"text": "Picked"
},
{
"code": null,
"e": 4600,
"s": 4593,
"text": "Python"
}
] |
Comparison Networks - GeeksforGeeks | 20 Feb, 2020
Comparison Networks are a type of sorting networks which always sort their inputs. Wires and comparator comprise comparison network. A Comparator is a device which has two inputs (x, y) and outputs (x’, y’). It performs the following function:
x' = min(x, y),
y' = max(x, y)
Comparators are conventionally drawn as single vertical lines where input is on the left and output on right. Smaller input values are put on top output while larger input values are put on bottom output. thus comparator can be thought of as sorting its two inputs. It is assumed that each comparator operates in O(1) time i.e time between appearance of input values and production of output is constant.
The second component of comparison networks i.e. wires performs the function of transmitting a value from one place to another. These are either network input wires or network output wires. Wires are capable of connecting input of a comparator to output of other.
Output is produced by comparator only when it has both of its input values available. Now, assuming that each comparator takes unit time “running time” can be defined. Running time is time taken by output wires to receive values after input wires have received their values. Formally is defined as follows. An input wire of comparison network has depth 0. Now, if d1 and d2 are depths of two input wires, then the depth of output wires is max(d1, d2) + 1. Depth of a comparator is defined to be the depth of its output wires.
Properties:
Graph is required to be acyclic.
Output is produced only when input is available.
Comparators process in parallel if input is available.
Sorting network is a comparison network where the output is sorted.
Not all comparison networks are sorting networks.
A comparison network is like a procedure which specifies how comparisons are to occur.
Theorems:
If a comparison network with n inputs sorts all 2n possible sequences of 0’s and 1’s correctly, then it sorts all sequences of arbitrary numbers correctly.If a comparison network transforms the input a = ha1, a2, . . ., ani into the output b = hb1, b2, . . ., bni, then for any monotonically increasing function f, the network transformsf(a) = hf(a1), f(a2), . . ., f(an)i
into
f(b) = hf(b1), f(b2), . . ., f(bn)i
If a comparison network with n inputs sorts all 2n possible sequences of 0’s and 1’s correctly, then it sorts all sequences of arbitrary numbers correctly.
If a comparison network transforms the input a = ha1, a2, . . ., ani into the output b = hb1, b2, . . ., bni, then for any monotonically increasing function f, the network transformsf(a) = hf(a1), f(a2), . . ., f(an)i
into
f(b) = hf(b1), f(b2), . . ., f(bn)i
f(a) = hf(a1), f(a2), . . ., f(an)i
into
f(b) = hf(b1), f(b2), . . ., f(bn)i
Computer Networks
Misc
Misc
Misc
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
GSM in Wireless Communication
Multiple Access Protocols in Computer Network
Stop and Wait ARQ
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
fgets() and gets() in C language | [
{
"code": null,
"e": 24510,
"s": 24482,
"text": "\n20 Feb, 2020"
},
{
"code": null,
"e": 24754,
"s": 24510,
"text": "Comparison Networks are a type of sorting networks which always sort their inputs. Wires and comparator comprise comparison network. A Comparator is a device which has two inputs (x, y) and outputs (x’, y’). It performs the following function:"
},
{
"code": null,
"e": 24786,
"s": 24754,
"text": "x' = min(x, y),\ny' = max(x, y) "
},
{
"code": null,
"e": 25191,
"s": 24786,
"text": "Comparators are conventionally drawn as single vertical lines where input is on the left and output on right. Smaller input values are put on top output while larger input values are put on bottom output. thus comparator can be thought of as sorting its two inputs. It is assumed that each comparator operates in O(1) time i.e time between appearance of input values and production of output is constant."
},
{
"code": null,
"e": 25455,
"s": 25191,
"text": "The second component of comparison networks i.e. wires performs the function of transmitting a value from one place to another. These are either network input wires or network output wires. Wires are capable of connecting input of a comparator to output of other."
},
{
"code": null,
"e": 25981,
"s": 25455,
"text": "Output is produced by comparator only when it has both of its input values available. Now, assuming that each comparator takes unit time “running time” can be defined. Running time is time taken by output wires to receive values after input wires have received their values. Formally is defined as follows. An input wire of comparison network has depth 0. Now, if d1 and d2 are depths of two input wires, then the depth of output wires is max(d1, d2) + 1. Depth of a comparator is defined to be the depth of its output wires."
},
{
"code": null,
"e": 25993,
"s": 25981,
"text": "Properties:"
},
{
"code": null,
"e": 26026,
"s": 25993,
"text": "Graph is required to be acyclic."
},
{
"code": null,
"e": 26075,
"s": 26026,
"text": "Output is produced only when input is available."
},
{
"code": null,
"e": 26130,
"s": 26075,
"text": "Comparators process in parallel if input is available."
},
{
"code": null,
"e": 26198,
"s": 26130,
"text": "Sorting network is a comparison network where the output is sorted."
},
{
"code": null,
"e": 26248,
"s": 26198,
"text": "Not all comparison networks are sorting networks."
},
{
"code": null,
"e": 26335,
"s": 26248,
"text": "A comparison network is like a procedure which specifies how comparisons are to occur."
},
{
"code": null,
"e": 26345,
"s": 26335,
"text": "Theorems:"
},
{
"code": null,
"e": 26762,
"s": 26345,
"text": "If a comparison network with n inputs sorts all 2n possible sequences of 0’s and 1’s correctly, then it sorts all sequences of arbitrary numbers correctly.If a comparison network transforms the input a = ha1, a2, . . ., ani into the output b = hb1, b2, . . ., bni, then for any monotonically increasing function f, the network transformsf(a) = hf(a1), f(a2), . . ., f(an)i \ninto \nf(b) = hf(b1), f(b2), . . ., f(bn)i "
},
{
"code": null,
"e": 26918,
"s": 26762,
"text": "If a comparison network with n inputs sorts all 2n possible sequences of 0’s and 1’s correctly, then it sorts all sequences of arbitrary numbers correctly."
},
{
"code": null,
"e": 27180,
"s": 26918,
"text": "If a comparison network transforms the input a = ha1, a2, . . ., ani into the output b = hb1, b2, . . ., bni, then for any monotonically increasing function f, the network transformsf(a) = hf(a1), f(a2), . . ., f(an)i \ninto \nf(b) = hf(b1), f(b2), . . ., f(bn)i "
},
{
"code": null,
"e": 27260,
"s": 27180,
"text": "f(a) = hf(a1), f(a2), . . ., f(an)i \ninto \nf(b) = hf(b1), f(b2), . . ., f(bn)i "
},
{
"code": null,
"e": 27278,
"s": 27260,
"text": "Computer Networks"
},
{
"code": null,
"e": 27283,
"s": 27278,
"text": "Misc"
},
{
"code": null,
"e": 27288,
"s": 27283,
"text": "Misc"
},
{
"code": null,
"e": 27293,
"s": 27288,
"text": "Misc"
},
{
"code": null,
"e": 27311,
"s": 27293,
"text": "Computer Networks"
},
{
"code": null,
"e": 27409,
"s": 27311,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27418,
"s": 27409,
"text": "Comments"
},
{
"code": null,
"e": 27431,
"s": 27418,
"text": "Old Comments"
},
{
"code": null,
"e": 27466,
"s": 27431,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 27499,
"s": 27466,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 27529,
"s": 27499,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 27575,
"s": 27529,
"text": "Multiple Access Protocols in Computer Network"
},
{
"code": null,
"e": 27593,
"s": 27575,
"text": "Stop and Wait ARQ"
},
{
"code": null,
"e": 27634,
"s": 27593,
"text": "Top 10 algorithms in Interview Questions"
},
{
"code": null,
"e": 27688,
"s": 27634,
"text": "vector::push_back() and vector::pop_back() in C++ STL"
},
{
"code": null,
"e": 27749,
"s": 27688,
"text": "Overview of Data Structures | Set 1 (Linear Data Structures)"
},
{
"code": null,
"e": 27783,
"s": 27749,
"text": "How to write Regular Expressions?"
}
] |
new and delete operators in C++ for dynamic memory - GeeksforGeeks | 22 Oct, 2021
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack (Refer Memory Layout C Programs for details).What are applications?
One use of dynamically allocated memory is to allocate memory of variable size which is not possible with compiler allocated memory except variable length arrays.
The most important use is flexibility provided to programmers. We are free to allocate and deallocate memory whenever we need and whenever we don’t need anymore. There are many cases where this flexibility helps. Examples of such cases are Linked List, Tree, etc.
How is it different from memory allocated to normal variables? For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and deallocated. For dynamically allocated memory like “int *p = new int[10]”, it is programmers responsibility to deallocate memory when no longer needed. If programmer doesn’t deallocate memory, it causes memory leak (memory is not deallocated until program terminates). How is memory allocated/deallocated in C++? C uses malloc() and calloc() function to allocate memory dynamically at run time and uses free() function to free dynamically allocated memory. C++ supports these functions and also has two operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.This article is all about new and delete operators.
new operator
The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
Syntax to use new operator: To allocate memory of any data type, the syntax is:
pointer-variable = new data-type;
Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including array or any user defined data types including structure and class. Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
// Combine declaration of pointer
// and their assignment
int *p = new int;
Initialize memory: We can also initialize the memory for built-in data types using new operator. For custom data types a constructor is required (with the data-type as input) for initializing the value. Here’s an example for the initialization of both data types :
pointer-variable = new data-type(value);
Example:
int *p = new int(25);
float *q = new float(75.25);
// Custom data type
struct cust
{
int p;
cust(int q) : p(q) {}
};
cust* var1 = new cust; // Works fine, doesn't require constructor
OR
cust* var1 = new cust(); // Works fine, doesn't require constructor
cust* var = new cust(25) // Notice error if you comment this line
Allocate block of memory: new operator is also used to allocate a block(an array) of memory of type data-type.
pointer-variable = new data-type[size];
where size(a variable) specifies the number of elements in an array.
Example:
int *p = new int[10]
Dynamically allocates memory for 10 integers continuously of type int and returns pointer to the first element of the sequence, which is assigned to p(a pointer). p[0] refers to first element, p[1] refers to second element and so on.
Normal Array Declaration vs Using new There is a difference between declaring a normal array and allocating a block of memory using new. The most important difference is, normal arrays are deallocated by compiler (If array is local, then deallocated when function returns or completes). However, dynamically allocated arrays always remain there until either they are deallocated by programmer or program terminates.What if enough memory is not available during runtime? If enough memory is not available in the heap to allocate, the new request indicates failure by throwing an exception of type std::bad_alloc, unless “nothrow” is used with the new operator, in which case it returns a NULL pointer (scroll to section “Exception handling of new operator” in this article). Therefore, it may be good idea to check for the pointer variable produced by new before using it program.
int *p = new(nothrow) int;
if (!p)
{
cout << "Memory allocation failed\n";
}
delete operator
Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator by C++ language. Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;
Here, pointer-variable is the pointer that points to the data object created by new. Examples:
delete p;
delete q;
To free the dynamically allocated array pointed by pointer-variable, use following form of delete:
// Release block of memory
// pointed by pointer-variable
delete[] pointer-variable;
Example:
// It will free the entire array
// pointed by p.
delete[] p;
CPP
// C++ program to illustrate dynamic allocation// and deallocation of memory using new and delete#include <iostream>using namespace std; int main (){ // Pointer initialization to null int* p = NULL; // Request memory for the variable // using new operator p = new(nothrow) int; if (!p) cout << "allocation of memory failed\n"; else { // Store value at allocated address *p = 29; cout << "Value of p: " << *p << endl; } // Request block of memory // using new operator float *r = new float(75.25); cout << "Value of r: " << *r << endl; // Request block of memory of size n int n = 5; int *q = new(nothrow) int[n]; if (!q) cout << "allocation of memory failed\n"; else { for (int i = 0; i < n; i++) q[i] = i+1; cout << "Value store in block of memory: "; for (int i = 0; i < n; i++) cout << q[i] << " "; } // freed the allocated memory delete p; delete r; // freed the block of allocated memory delete[] q; return 0;}
Output:
Value of p: 29
Value of r: 75.25
Value store in block of memory: 1 2 3 4 5
Related Articles:
Quiz on new and delete
delete vs free
This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Abhi1909
BabisSarantoglou
jeetundaviya20017
dvsingla28
cpp-pointer
C++
School Programming
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Virtual Function in C++
Bitwise Operators in C/C++
Python Dictionary
Reverse a string in Java
Interfaces in Java
Friend class and function in C++
Types of Operating Systems | [
{
"code": null,
"e": 27058,
"s": 27030,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 27341,
"s": 27058,
"text": "Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack (Refer Memory Layout C Programs for details).What are applications? "
},
{
"code": null,
"e": 27504,
"s": 27341,
"text": "One use of dynamically allocated memory is to allocate memory of variable size which is not possible with compiler allocated memory except variable length arrays."
},
{
"code": null,
"e": 27768,
"s": 27504,
"text": "The most important use is flexibility provided to programmers. We are free to allocate and deallocate memory whenever we need and whenever we don’t need anymore. There are many cases where this flexibility helps. Examples of such cases are Linked List, Tree, etc."
},
{
"code": null,
"e": 28593,
"s": 27768,
"text": "How is it different from memory allocated to normal variables? For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and deallocated. For dynamically allocated memory like “int *p = new int[10]”, it is programmers responsibility to deallocate memory when no longer needed. If programmer doesn’t deallocate memory, it causes memory leak (memory is not deallocated until program terminates). How is memory allocated/deallocated in C++? C uses malloc() and calloc() function to allocate memory dynamically at run time and uses free() function to free dynamically allocated memory. C++ supports these functions and also has two operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.This article is all about new and delete operators. "
},
{
"code": null,
"e": 28608,
"s": 28595,
"text": "new operator"
},
{
"code": null,
"e": 28852,
"s": 28608,
"text": "The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. "
},
{
"code": null,
"e": 28934,
"s": 28852,
"text": "Syntax to use new operator: To allocate memory of any data type, the syntax is: "
},
{
"code": null,
"e": 28968,
"s": 28934,
"text": "pointer-variable = new data-type;"
},
{
"code": null,
"e": 29156,
"s": 28968,
"text": "Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including array or any user defined data types including structure and class. Example: "
},
{
"code": null,
"e": 29356,
"s": 29156,
"text": "// Pointer initialized with NULL\n// Then request memory for the variable\nint *p = NULL; \np = new int; \n\n OR\n\n// Combine declaration of pointer \n// and their assignment\nint *p = new int; "
},
{
"code": null,
"e": 29623,
"s": 29356,
"text": "Initialize memory: We can also initialize the memory for built-in data types using new operator. For custom data types a constructor is required (with the data-type as input) for initializing the value. Here’s an example for the initialization of both data types : "
},
{
"code": null,
"e": 30032,
"s": 29623,
"text": "pointer-variable = new data-type(value);\nExample:\nint *p = new int(25);\nfloat *q = new float(75.25);\n\n// Custom data type\nstruct cust\n{\n int p;\n cust(int q) : p(q) {}\n};\n\ncust* var1 = new cust; // Works fine, doesn't require constructor\n\n OR\n\ncust* var1 = new cust(); // Works fine, doesn't require constructor\n\n\ncust* var = new cust(25) // Notice error if you comment this line"
},
{
"code": null,
"e": 30145,
"s": 30032,
"text": "Allocate block of memory: new operator is also used to allocate a block(an array) of memory of type data-type. "
},
{
"code": null,
"e": 30185,
"s": 30145,
"text": "pointer-variable = new data-type[size];"
},
{
"code": null,
"e": 30256,
"s": 30185,
"text": "where size(a variable) specifies the number of elements in an array. "
},
{
"code": null,
"e": 30294,
"s": 30256,
"text": "Example:\n int *p = new int[10]"
},
{
"code": null,
"e": 30530,
"s": 30294,
"text": "Dynamically allocates memory for 10 integers continuously of type int and returns pointer to the first element of the sequence, which is assigned to p(a pointer). p[0] refers to first element, p[1] refers to second element and so on. "
},
{
"code": null,
"e": 31414,
"s": 30532,
"text": "Normal Array Declaration vs Using new There is a difference between declaring a normal array and allocating a block of memory using new. The most important difference is, normal arrays are deallocated by compiler (If array is local, then deallocated when function returns or completes). However, dynamically allocated arrays always remain there until either they are deallocated by programmer or program terminates.What if enough memory is not available during runtime? If enough memory is not available in the heap to allocate, the new request indicates failure by throwing an exception of type std::bad_alloc, unless “nothrow” is used with the new operator, in which case it returns a NULL pointer (scroll to section “Exception handling of new operator” in this article). Therefore, it may be good idea to check for the pointer variable produced by new before using it program. "
},
{
"code": null,
"e": 31494,
"s": 31414,
"text": "int *p = new(nothrow) int;\nif (!p)\n{\n cout << \"Memory allocation failed\\n\";\n}"
},
{
"code": null,
"e": 31512,
"s": 31496,
"text": "delete operator"
},
{
"code": null,
"e": 31664,
"s": 31512,
"text": "Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator by C++ language. Syntax: "
},
{
"code": null,
"e": 31737,
"s": 31664,
"text": "// Release memory pointed by pointer-variable\ndelete pointer-variable; "
},
{
"code": null,
"e": 31834,
"s": 31737,
"text": "Here, pointer-variable is the pointer that points to the data object created by new. Examples: "
},
{
"code": null,
"e": 31858,
"s": 31834,
"text": " delete p;\n delete q;"
},
{
"code": null,
"e": 31959,
"s": 31858,
"text": "To free the dynamically allocated array pointed by pointer-variable, use following form of delete: "
},
{
"code": null,
"e": 32128,
"s": 31959,
"text": "// Release block of memory \n// pointed by pointer-variable\ndelete[] pointer-variable; \n\nExample:\n // It will free the entire array\n // pointed by p.\n delete[] p;"
},
{
"code": null,
"e": 32134,
"s": 32130,
"text": "CPP"
},
{
"code": "// C++ program to illustrate dynamic allocation// and deallocation of memory using new and delete#include <iostream>using namespace std; int main (){ // Pointer initialization to null int* p = NULL; // Request memory for the variable // using new operator p = new(nothrow) int; if (!p) cout << \"allocation of memory failed\\n\"; else { // Store value at allocated address *p = 29; cout << \"Value of p: \" << *p << endl; } // Request block of memory // using new operator float *r = new float(75.25); cout << \"Value of r: \" << *r << endl; // Request block of memory of size n int n = 5; int *q = new(nothrow) int[n]; if (!q) cout << \"allocation of memory failed\\n\"; else { for (int i = 0; i < n; i++) q[i] = i+1; cout << \"Value store in block of memory: \"; for (int i = 0; i < n; i++) cout << q[i] << \" \"; } // freed the allocated memory delete p; delete r; // freed the block of allocated memory delete[] q; return 0;}",
"e": 33215,
"s": 32134,
"text": null
},
{
"code": null,
"e": 33225,
"s": 33215,
"text": "Output: "
},
{
"code": null,
"e": 33301,
"s": 33225,
"text": "Value of p: 29\nValue of r: 75.25\nValue store in block of memory: 1 2 3 4 5 "
},
{
"code": null,
"e": 33319,
"s": 33301,
"text": "Related Articles:"
},
{
"code": null,
"e": 33342,
"s": 33319,
"text": "Quiz on new and delete"
},
{
"code": null,
"e": 33357,
"s": 33342,
"text": "delete vs free"
},
{
"code": null,
"e": 33777,
"s": 33357,
"text": "This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33786,
"s": 33777,
"text": "Abhi1909"
},
{
"code": null,
"e": 33803,
"s": 33786,
"text": "BabisSarantoglou"
},
{
"code": null,
"e": 33821,
"s": 33803,
"text": "jeetundaviya20017"
},
{
"code": null,
"e": 33832,
"s": 33821,
"text": "dvsingla28"
},
{
"code": null,
"e": 33844,
"s": 33832,
"text": "cpp-pointer"
},
{
"code": null,
"e": 33848,
"s": 33844,
"text": "C++"
},
{
"code": null,
"e": 33867,
"s": 33848,
"text": "School Programming"
},
{
"code": null,
"e": 33871,
"s": 33867,
"text": "CPP"
},
{
"code": null,
"e": 33969,
"s": 33871,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33987,
"s": 33969,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 34033,
"s": 33987,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 34056,
"s": 34033,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 34080,
"s": 34056,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 34107,
"s": 34080,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 34125,
"s": 34107,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34150,
"s": 34125,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34169,
"s": 34150,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 34202,
"s": 34169,
"text": "Friend class and function in C++"
}
] |
Python - Find dictionary keys present in a Strings List - GeeksforGeeks | 08 May, 2020
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionThis is brute force way in which this task can be performed. In this, we use conditional statements to find the strings matching keys in each string and extract keys from string list.
# Python3 code to demonstrate working of # Extract dictionary keys in Strings List# Using list comprehension # initializing listtest_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing dictionarytest_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10} # Extract dictionary keys in Strings List# Using list comprehensionres = [ele if len(ele) > 0 else [None] for ele in [[key for key in test_dict if key in sub] for sub in test_list]] # printing result print("The matching keys list : " + str(res))
The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks']
The matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]
Method #2 : Using filter() + lambda + list comprehensionThe combination of above functions can also be used to solve this problem. In this, we perform the task of filtering using filter() and lambda and list comprehension help to reduce one level of nesting.
# Python3 code to demonstrate working of # Extract dictionary keys in Strings List# Using filter() + lambda + list comprehension # initializing listtest_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing dictionarytest_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10} # Extract dictionary keys in Strings List# Using filter() + lambda + list comprehensionres = [list(filter(lambda ele: ele in sub, test_dict)) for sub in test_list] # printing result print("The matching keys list : " + str(res))
The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks']
The matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]
Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n08 May, 2020"
},
{
"code": null,
"e": 25843,
"s": 25555,
"text": "Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26063,
"s": 25843,
"text": "Method #1 : Using list comprehensionThis is brute force way in which this task can be performed. In this, we use conditional statements to find the strings matching keys in each string and extract keys from string list."
},
{
"code": "# Python3 code to demonstrate working of # Extract dictionary keys in Strings List# Using list comprehension # initializing listtest_list = [\"GeeksforGeeks is best for geeks\", \"I love GeeksforGeeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing dictionarytest_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10} # Extract dictionary keys in Strings List# Using list comprehensionres = [ele if len(ele) > 0 else [None] for ele in [[key for key in test_dict if key in sub] for sub in test_list]] # printing result print(\"The matching keys list : \" + str(res)) ",
"e": 26752,
"s": 26063,
"text": null
},
{
"code": null,
"e": 26900,
"s": 26752,
"text": "The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks']\nThe matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]\n"
},
{
"code": null,
"e": 27161,
"s": 26902,
"text": "Method #2 : Using filter() + lambda + list comprehensionThe combination of above functions can also be used to solve this problem. In this, we perform the task of filtering using filter() and lambda and list comprehension help to reduce one level of nesting."
},
{
"code": "# Python3 code to demonstrate working of # Extract dictionary keys in Strings List# Using filter() + lambda + list comprehension # initializing listtest_list = [\"GeeksforGeeks is best for geeks\", \"I love GeeksforGeeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing dictionarytest_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10} # Extract dictionary keys in Strings List# Using filter() + lambda + list comprehensionres = [list(filter(lambda ele: ele in sub, test_dict)) for sub in test_list] # printing result print(\"The matching keys list : \" + str(res)) ",
"e": 27814,
"s": 27161,
"text": null
},
{
"code": null,
"e": 27962,
"s": 27814,
"text": "The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks']\nThe matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]\n"
},
{
"code": null,
"e": 27983,
"s": 27962,
"text": "Python list-programs"
},
{
"code": null,
"e": 27990,
"s": 27983,
"text": "Python"
},
{
"code": null,
"e": 28088,
"s": 27990,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28120,
"s": 28088,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28162,
"s": 28120,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28204,
"s": 28162,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28260,
"s": 28204,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28287,
"s": 28260,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28318,
"s": 28287,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28357,
"s": 28318,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28386,
"s": 28357,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28408,
"s": 28386,
"text": "Defaultdict in Python"
}
] |
D3.js symbol.size() Method - GeeksforGeeks | 14 Sep, 2020
The symbol.size() method can be used to change the size of the symbol.
Syntax:
symbol.size([size])
Parameters: This function accepts a single parameter as mentioned above and described below:
size: This is the size in square pixels or the area to be set.
Return Value: This method has no return value.
Example 1:
HTML
<!DOCTYPE html><html><head> <meta charset="utf-8"> <script src= "https://d3js.org/d3.v5.min.js"> </script></head> <body> <h1 style="text-align: center; color: green;"> GeeksforGeeks </h1> <h3 style="text-align: center;"> D3.js | symbol.size() Method </h3> <center> <svg id="gfg" width="100" height="100"></svg> </center> <script> var sym = d3.symbol().size(300); d3.select("#gfg") .append("path") .attr("d", sym) .attr("fill", "green") .attr("transform", "translate(50,50)"); </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html><head> <meta charset="utf-8"> <script src= "https://d3js.org/d3.v5.min.js"> </script></head> <body> <h1 style="text-align: center; color: green;"> GeeksforGeeks </h1> <h3 style="text-align: center;"> D3.js | symbol.size() Method </h3> <center> <svg id="gfg" width="100" height="100"></svg> </center> <script> var sym = d3.symbol().size(500); d3.select("#gfg") .append("path") .attr("d", sym) .attr("fill", "none") .attr("stroke", "green") .attr("stroke-width", "5px") .attr("transform", "translate(50,50)"); </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 25371,
"s": 25300,
"text": "The symbol.size() method can be used to change the size of the symbol."
},
{
"code": null,
"e": 25379,
"s": 25371,
"text": "Syntax:"
},
{
"code": null,
"e": 25400,
"s": 25379,
"text": "symbol.size([size])\n"
},
{
"code": null,
"e": 25493,
"s": 25400,
"text": "Parameters: This function accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25556,
"s": 25493,
"text": "size: This is the size in square pixels or the area to be set."
},
{
"code": null,
"e": 25603,
"s": 25556,
"text": "Return Value: This method has no return value."
},
{
"code": null,
"e": 25614,
"s": 25603,
"text": "Example 1:"
},
{
"code": null,
"e": 25619,
"s": 25614,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <script src= \"https://d3js.org/d3.v5.min.js\"> </script></head> <body> <h1 style=\"text-align: center; color: green;\"> GeeksforGeeks </h1> <h3 style=\"text-align: center;\"> D3.js | symbol.size() Method </h3> <center> <svg id=\"gfg\" width=\"100\" height=\"100\"></svg> </center> <script> var sym = d3.symbol().size(300); d3.select(\"#gfg\") .append(\"path\") .attr(\"d\", sym) .attr(\"fill\", \"green\") .attr(\"transform\", \"translate(50,50)\"); </script></body> </html>",
"e": 26241,
"s": 25619,
"text": null
},
{
"code": null,
"e": 26249,
"s": 26241,
"text": "Output:"
},
{
"code": null,
"e": 26260,
"s": 26249,
"text": "Example 2:"
},
{
"code": null,
"e": 26265,
"s": 26260,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <script src= \"https://d3js.org/d3.v5.min.js\"> </script></head> <body> <h1 style=\"text-align: center; color: green;\"> GeeksforGeeks </h1> <h3 style=\"text-align: center;\"> D3.js | symbol.size() Method </h3> <center> <svg id=\"gfg\" width=\"100\" height=\"100\"></svg> </center> <script> var sym = d3.symbol().size(500); d3.select(\"#gfg\") .append(\"path\") .attr(\"d\", sym) .attr(\"fill\", \"none\") .attr(\"stroke\", \"green\") .attr(\"stroke-width\", \"5px\") .attr(\"transform\", \"translate(50,50)\"); </script></body> </html>",
"e": 26962,
"s": 26265,
"text": null
},
{
"code": null,
"e": 26970,
"s": 26962,
"text": "Output:"
},
{
"code": null,
"e": 26976,
"s": 26970,
"text": "D3.js"
},
{
"code": null,
"e": 26987,
"s": 26976,
"text": "JavaScript"
},
{
"code": null,
"e": 27004,
"s": 26987,
"text": "Web Technologies"
},
{
"code": null,
"e": 27102,
"s": 27004,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27111,
"s": 27102,
"text": "Comments"
},
{
"code": null,
"e": 27124,
"s": 27111,
"text": "Old Comments"
},
{
"code": null,
"e": 27185,
"s": 27124,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27226,
"s": 27185,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27280,
"s": 27226,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27333,
"s": 27280,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 27395,
"s": 27333,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27437,
"s": 27395,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27470,
"s": 27437,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27532,
"s": 27470,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27575,
"s": 27532,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
LISP - Variables | In LISP, each variable is represented by a symbol. The variable's name is the name of the symbol and it is stored in the storage cell of the symbol.
Global variables have permanent values throughout the LISP system and remain in effect until a new value is specified.
Global variables are generally declared using the defvar construct.
(defvar x 234)
(write x)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is
234
Since there is no type declaration for variables in LISP, you directly specify a value for a symbol with the setq construct.
->(setq x 10)
The above expression assigns the value 10 to the variable x. You can refer to the variable using the symbol itself as an expression.
The symbol-value function allows you to extract the value stored at the symbol storage place.
Create new source code file named main.lisp and type the following code in it.
(setq x 10)
(setq y 20)
(format t "x = ~2d y = ~2d ~%" x y)
(setq x 100)
(setq y 200)
(format t "x = ~2d y = ~2d" x y)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is.
x = 10 y = 20
x = 100 y = 200
Local variables are defined within a given procedure. The parameters named as arguments within a function definition are also local variables. Local variables are accessible only within the respective function.
Like the global variables, local variables can also be created using the setq construct.
There are two other constructs - let and prog for creating local variables.
The let construct has the following syntax.
(let ((var1 val1) (var2 val2).. (varn valn))<s-expressions>)
Where var1, var2, ..varn are variable names and val1, val2, .. valn are the initial values assigned to the respective variables.
When let is executed, each variable is assigned the respective value and lastly the s-expression is evaluated. The value of the last expression evaluated is returned.
If you don't include an initial value for a variable, it is assigned to nil.
Create new source code file named main.lisp and type the following code in it.
(let ((x 'a) (y 'b)(z 'c))
(format t "x = ~a y = ~a z = ~a" x y z))
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is.
x = A y = B z = C
The prog construct also has the list of local variables as its first argument, which is followed by the body of the prog, and any number of s-expressions.
The prog function executes the list of s-expressions in sequence and returns nil unless it encounters a function call named return. Then the argument of the return function is evaluated and returned.
Create new source code file named main.lisp and type the following code in it.
(prog ((x '(a b c))(y '(1 2 3))(z '(p q 10)))
(format t "x = ~a y = ~a z = ~a" x y z))
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is.
x = (A B C) y = (1 2 3) z = (P Q 10)
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2209,
"s": 2060,
"text": "In LISP, each variable is represented by a symbol. The variable's name is the name of the symbol and it is stored in the storage cell of the symbol."
},
{
"code": null,
"e": 2328,
"s": 2209,
"text": "Global variables have permanent values throughout the LISP system and remain in effect until a new value is specified."
},
{
"code": null,
"e": 2396,
"s": 2328,
"text": "Global variables are generally declared using the defvar construct."
},
{
"code": null,
"e": 2421,
"s": 2396,
"text": "(defvar x 234)\n(write x)"
},
{
"code": null,
"e": 2528,
"s": 2421,
"text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is"
},
{
"code": null,
"e": 2533,
"s": 2528,
"text": "234\n"
},
{
"code": null,
"e": 2658,
"s": 2533,
"text": "Since there is no type declaration for variables in LISP, you directly specify a value for a symbol with the setq construct."
},
{
"code": null,
"e": 2672,
"s": 2658,
"text": "->(setq x 10)"
},
{
"code": null,
"e": 2805,
"s": 2672,
"text": "The above expression assigns the value 10 to the variable x. You can refer to the variable using the symbol itself as an expression."
},
{
"code": null,
"e": 2899,
"s": 2805,
"text": "The symbol-value function allows you to extract the value stored at the symbol storage place."
},
{
"code": null,
"e": 2978,
"s": 2899,
"text": "Create new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 3098,
"s": 2978,
"text": "(setq x 10)\n(setq y 20)\n(format t \"x = ~2d y = ~2d ~%\" x y)\n\n(setq x 100)\n(setq y 200)\n(format t \"x = ~2d y = ~2d\" x y)"
},
{
"code": null,
"e": 3206,
"s": 3098,
"text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is."
},
{
"code": null,
"e": 3238,
"s": 3206,
"text": "x = 10 y = 20 \nx = 100 y = 200\n"
},
{
"code": null,
"e": 3449,
"s": 3238,
"text": "Local variables are defined within a given procedure. The parameters named as arguments within a function definition are also local variables. Local variables are accessible only within the respective function."
},
{
"code": null,
"e": 3538,
"s": 3449,
"text": "Like the global variables, local variables can also be created using the setq construct."
},
{
"code": null,
"e": 3614,
"s": 3538,
"text": "There are two other constructs - let and prog for creating local variables."
},
{
"code": null,
"e": 3658,
"s": 3614,
"text": "The let construct has the following syntax."
},
{
"code": null,
"e": 3722,
"s": 3658,
"text": "(let ((var1 val1) (var2 val2).. (varn valn))<s-expressions>)"
},
{
"code": null,
"e": 3851,
"s": 3722,
"text": "Where var1, var2, ..varn are variable names and val1, val2, .. valn are the initial values assigned to the respective variables."
},
{
"code": null,
"e": 4018,
"s": 3851,
"text": "When let is executed, each variable is assigned the respective value and lastly the s-expression is evaluated. The value of the last expression evaluated is returned."
},
{
"code": null,
"e": 4095,
"s": 4018,
"text": "If you don't include an initial value for a variable, it is assigned to nil."
},
{
"code": null,
"e": 4174,
"s": 4095,
"text": "Create new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 4242,
"s": 4174,
"text": "(let ((x 'a) (y 'b)(z 'c))\n(format t \"x = ~a y = ~a z = ~a\" x y z))"
},
{
"code": null,
"e": 4350,
"s": 4242,
"text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is."
},
{
"code": null,
"e": 4369,
"s": 4350,
"text": "x = A y = B z = C\n"
},
{
"code": null,
"e": 4524,
"s": 4369,
"text": "The prog construct also has the list of local variables as its first argument, which is followed by the body of the prog, and any number of s-expressions."
},
{
"code": null,
"e": 4724,
"s": 4524,
"text": "The prog function executes the list of s-expressions in sequence and returns nil unless it encounters a function call named return. Then the argument of the return function is evaluated and returned."
},
{
"code": null,
"e": 4803,
"s": 4724,
"text": "Create new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 4890,
"s": 4803,
"text": "(prog ((x '(a b c))(y '(1 2 3))(z '(p q 10)))\n(format t \"x = ~a y = ~a z = ~a\" x y z))"
},
{
"code": null,
"e": 4998,
"s": 4890,
"text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is."
},
{
"code": null,
"e": 5036,
"s": 4998,
"text": "x = (A B C) y = (1 2 3) z = (P Q 10)\n"
},
{
"code": null,
"e": 5069,
"s": 5036,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5084,
"s": 5069,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 5091,
"s": 5084,
"text": " Print"
},
{
"code": null,
"e": 5102,
"s": 5091,
"text": " Add Notes"
}
] |
Beginner’s Guide to Jupyter Notebook | by Shinichi Okada | Towards Data Science | Table of ContentsIntroduction1. Installing Anaconda2. Jupyter Notebook help and shortcuts3. Python libraries4. Finding data5. Importing data6. Data attributes7. Missing Value8. Dealing with NaN values9. How to deal categorical data10. Descriptive statistics11. Basic plotting12. Matplotlib13. Seaborn14. What’s next?
In this beginner’s guide to Jupyter Notebook, we go through how to get started with basic descriptive statistics. This article is intended for high-school students (or above) with little experience with coding.
If you want to read about Jupyter Notebook tips please read this article.
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. (description from Project Jupyter)
The Jupyter system supports over 100 programming languages including Python. Currently, Python is the most popular language for Data Science.
You can see the original chart here.
I created a Jupyer slideshow and you can download it here. You need to install RISE to use this slideshow.
We are going to use Python libraries, Numpy, Pandas, Matplotlib and Seaborn. Python library is a collection of functions and methods that allows you to perform many actions without writing your code.
We are going to install Anaconda. Anaconda is the standard platform for Python data science. Anaconda will install all necessary packages for our purpose.
From https://www.anaconda.com/distribution/, download a 3.7 version and install it.
After installing the Anaconda, start Anaconda-Navigator.
Press Launch Jupyter Notebook. It will start a terminal and open a browser.
To create a folder, click the New button on the top right. Then click Folder.
You need to rename the folder to Statistics.
Create a folder called Data and we are going to store all our data in this folder.
In the Data folder, create a text file called mydata1.csv.
Open http://bit.ly/2M1yrW7 in a browser. Command(or ctrl in windows) + A to select all and Command + C to copy. Command + V to paste it to the mydata1.csv and Command + S to save the file.
In the Statistics folder, create a file called Test by New > Python 3.
That’s all for setup. Let’s start writing some codes.
towardsdatascience.com
Pressing h toggles the keyboards shortcuts screen. You can see all commands by pressing ⌘⇧f. I use the following shortcuts often and it will be useful if you can memorize them.
Numpy and Pandas are two of the most used libraries in scientific computing, Data science, and machine learning. Pandas is built on top of Numpy. Both offer similar functions. Numpy provides objects for multi-dimensional array and Pandas provides an in-memory 2D table object called DataFrame.
Python offers a variety of packages for plotting data. Seaborn and Matplotlib are two of Python’s most powerful visualization libraries.
Use import ... as ... to import a library. We use %matplotlib inline to show graphs inline. In our Test file please write/copy the following.
import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline
After typing the above, press SHIFT + RETURN. This will run the code you wrote. If you have written correctly, nothing is going to happen. But if you have misspelled then it will return an error. Please read the last line of error and fix the problem.
There are many resources you can find online. This is a collection of data sources. CSV file is a comma-separated values file and is the easiest file to work on. Most of the data sources provided a CSV file. Find a couple of data you are interested in from the list. Download them to your hard drive.
We are going to read the CSV file and store the data in a variable called df. In the next cell please write the following.
df = pd.read_csv('data/mydata1.csv')
Please do not forget to press SHIFT + RETURN.
We are going to see the overview of our data using shape, info(), head(), tail(), describe().
We use shape to print the dimension of our data. info() prints a concise summary of our data. Press SHIFT + RETURN to run the program.
df.shape
It prints out (569, 33).
df.info()
head() prints the first 5 rows of data as the default. If you want to return the first 10 rows, use head(10).
df.head()
tail() prints the last 5 rows of data as the default. You can use any number as tail(10).
df.tail()
For the Statistical overview, describe() prints the mean, standard deviation, min, etc.
df.describe()
First, we import sample data which has ?, na, NA, N/A, and no data. We check if the data frame has any null values using `isnull()`. `any()` outputs by columns if there are any null values.
Please note that NaN will replace data items where there is no data.Comparing the first two tables, ? and na are not recognized as null. So we need to use `na_values` to recognize them as null values. This will change to NAN.
towardsdatascience.com
One way to deal with null values is to drop rows or columns. dropna() has the default value of axis=0. So dropna() and dropna(axis=0) outputs the same table. This will drop all rows where there is a null value.
`axis=1` will drop columns where there is NaN in the column.
We can fill up NaN value with the column mean. The following fill NaN in each column with its column mean.
You can fill up with the median.
Or any value you think it is appropriate.
Our data have a cat, dog, and fox under the col3. We use `get_dummies()` to convert categorical variable to dummy/indicator variables. This will create columns with all categories and add either 0 or 1.
We concatenate these dummies to our data.
We don’t need col3 anymore, so let’s drop it.
towardsdatascience.com
Unless you specify the column, mean, max, min, etc. returns the result of all columns. Here we are going to print only all_mean.
df=pd.read_csv('http://bit.ly/2vmLyvU')all_mean = df.mean()all_max = df.max()all_min = df.min()all_median = df.median()all_std = df.std()all_25_quantile = df.quantile(0.25)print('The means of all data.')print(all_mean)
As an exercise, can you print all_median, all_max?
Let’s focus on radius_mean in our data. We set a variable called target.
df=pd.read_csv('http://bit.ly/2vmLyvU')target = 'radius_mean'
We find the max, min, and range of radius_mean.
max = df[target].max()min = df[target].min()range = max - minprint('The max is %.1f, the min is %.1f and the range is %.1f' % (max, min, range))
The print command prints out within the bracket. Three %.1 print with one decimal place and will be replaced with max, min, and range. You can find out more details in this article.
Let’s find out the mean, median, and mode.
mean = df[target].mean()median = df[target].median()mode = df[target].mode()print('The mean is %.1f, the median is %.1f and the mode is %.1f.' % (mean, median, mode))
The default value ofquartile is 0.5 which is the same as the median or 50%-tile. You can specify the percentile, quantile(0.25).
q1 = df[target].quantile(0.25)q3 = df[target].quantile(0.75)iqr = q3-q1print('The lower quartile is %.1f, the upper quartile is %.1f and the interquartile range is %.1f' % (q1, q3, iqr))
Panda’s plot() draws a line graph as the default. You can set the kind parameter with bar, hist, box, pie, etc.
df[target].plot()
The above diagram is the line graph of radius_mean.
By adding kind='hist' to plot(), you can plot a histogram.
df[target].plot(kind='hist')
By adding hist() after plot also prints a histogram.
df[target].plot.hist()
You can add bins=100 to use 100 histogram bins.
df[target].plot.hist(bins=100)
plot(kind='box') or plot.box() shows a box-whisker plot.
df[target].plot(kind='box')
Matplotlib has a lot of flexibility. Here you change the outlier's color and symbol and showing three box plots together.
data =[df['radius_mean'],df['texture_mean'],df['texture_worst']]green_diamond = dict(markerfacecolor='g', marker='D')fig7, ax7 = plt.subplots()ax7.set_title('Multiple Samples with Different sizes')ax7.boxplot(data,flierprops=green_diamond)plt.show()
Matplotlib’s histogram has a lot of flexibility. You can add different parameters.
plt.hist([df['radius_mean'], df['texture_mean']], histtype='barstacked', orientation='horizontal',bins=20)plt.show()
Seaborn builds on top of Matplotlib and introduces additional plot types. It also makes your traditional Matplotlib plots look a bit prettier. (from Quora)
sns.boxplot(x='diagnosis', y='perimeter_mean', data=df)
Get full access to every story on Medium by becoming a member. | [
{
"code": null,
"e": 489,
"s": 172,
"text": "Table of ContentsIntroduction1. Installing Anaconda2. Jupyter Notebook help and shortcuts3. Python libraries4. Finding data5. Importing data6. Data attributes7. Missing Value8. Dealing with NaN values9. How to deal categorical data10. Descriptive statistics11. Basic plotting12. Matplotlib13. Seaborn14. What’s next?"
},
{
"code": null,
"e": 700,
"s": 489,
"text": "In this beginner’s guide to Jupyter Notebook, we go through how to get started with basic descriptive statistics. This article is intended for high-school students (or above) with little experience with coding."
},
{
"code": null,
"e": 774,
"s": 700,
"text": "If you want to read about Jupyter Notebook tips please read this article."
},
{
"code": null,
"e": 981,
"s": 774,
"text": "The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. (description from Project Jupyter)"
},
{
"code": null,
"e": 1123,
"s": 981,
"text": "The Jupyter system supports over 100 programming languages including Python. Currently, Python is the most popular language for Data Science."
},
{
"code": null,
"e": 1160,
"s": 1123,
"text": "You can see the original chart here."
},
{
"code": null,
"e": 1267,
"s": 1160,
"text": "I created a Jupyer slideshow and you can download it here. You need to install RISE to use this slideshow."
},
{
"code": null,
"e": 1467,
"s": 1267,
"text": "We are going to use Python libraries, Numpy, Pandas, Matplotlib and Seaborn. Python library is a collection of functions and methods that allows you to perform many actions without writing your code."
},
{
"code": null,
"e": 1622,
"s": 1467,
"text": "We are going to install Anaconda. Anaconda is the standard platform for Python data science. Anaconda will install all necessary packages for our purpose."
},
{
"code": null,
"e": 1706,
"s": 1622,
"text": "From https://www.anaconda.com/distribution/, download a 3.7 version and install it."
},
{
"code": null,
"e": 1763,
"s": 1706,
"text": "After installing the Anaconda, start Anaconda-Navigator."
},
{
"code": null,
"e": 1839,
"s": 1763,
"text": "Press Launch Jupyter Notebook. It will start a terminal and open a browser."
},
{
"code": null,
"e": 1917,
"s": 1839,
"text": "To create a folder, click the New button on the top right. Then click Folder."
},
{
"code": null,
"e": 1962,
"s": 1917,
"text": "You need to rename the folder to Statistics."
},
{
"code": null,
"e": 2045,
"s": 1962,
"text": "Create a folder called Data and we are going to store all our data in this folder."
},
{
"code": null,
"e": 2104,
"s": 2045,
"text": "In the Data folder, create a text file called mydata1.csv."
},
{
"code": null,
"e": 2293,
"s": 2104,
"text": "Open http://bit.ly/2M1yrW7 in a browser. Command(or ctrl in windows) + A to select all and Command + C to copy. Command + V to paste it to the mydata1.csv and Command + S to save the file."
},
{
"code": null,
"e": 2364,
"s": 2293,
"text": "In the Statistics folder, create a file called Test by New > Python 3."
},
{
"code": null,
"e": 2418,
"s": 2364,
"text": "That’s all for setup. Let’s start writing some codes."
},
{
"code": null,
"e": 2441,
"s": 2418,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2618,
"s": 2441,
"text": "Pressing h toggles the keyboards shortcuts screen. You can see all commands by pressing ⌘⇧f. I use the following shortcuts often and it will be useful if you can memorize them."
},
{
"code": null,
"e": 2912,
"s": 2618,
"text": "Numpy and Pandas are two of the most used libraries in scientific computing, Data science, and machine learning. Pandas is built on top of Numpy. Both offer similar functions. Numpy provides objects for multi-dimensional array and Pandas provides an in-memory 2D table object called DataFrame."
},
{
"code": null,
"e": 3049,
"s": 2912,
"text": "Python offers a variety of packages for plotting data. Seaborn and Matplotlib are two of Python’s most powerful visualization libraries."
},
{
"code": null,
"e": 3191,
"s": 3049,
"text": "Use import ... as ... to import a library. We use %matplotlib inline to show graphs inline. In our Test file please write/copy the following."
},
{
"code": null,
"e": 3299,
"s": 3191,
"text": "import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline"
},
{
"code": null,
"e": 3551,
"s": 3299,
"text": "After typing the above, press SHIFT + RETURN. This will run the code you wrote. If you have written correctly, nothing is going to happen. But if you have misspelled then it will return an error. Please read the last line of error and fix the problem."
},
{
"code": null,
"e": 3852,
"s": 3551,
"text": "There are many resources you can find online. This is a collection of data sources. CSV file is a comma-separated values file and is the easiest file to work on. Most of the data sources provided a CSV file. Find a couple of data you are interested in from the list. Download them to your hard drive."
},
{
"code": null,
"e": 3975,
"s": 3852,
"text": "We are going to read the CSV file and store the data in a variable called df. In the next cell please write the following."
},
{
"code": null,
"e": 4012,
"s": 3975,
"text": "df = pd.read_csv('data/mydata1.csv')"
},
{
"code": null,
"e": 4058,
"s": 4012,
"text": "Please do not forget to press SHIFT + RETURN."
},
{
"code": null,
"e": 4152,
"s": 4058,
"text": "We are going to see the overview of our data using shape, info(), head(), tail(), describe()."
},
{
"code": null,
"e": 4287,
"s": 4152,
"text": "We use shape to print the dimension of our data. info() prints a concise summary of our data. Press SHIFT + RETURN to run the program."
},
{
"code": null,
"e": 4296,
"s": 4287,
"text": "df.shape"
},
{
"code": null,
"e": 4321,
"s": 4296,
"text": "It prints out (569, 33)."
},
{
"code": null,
"e": 4331,
"s": 4321,
"text": "df.info()"
},
{
"code": null,
"e": 4441,
"s": 4331,
"text": "head() prints the first 5 rows of data as the default. If you want to return the first 10 rows, use head(10)."
},
{
"code": null,
"e": 4451,
"s": 4441,
"text": "df.head()"
},
{
"code": null,
"e": 4541,
"s": 4451,
"text": "tail() prints the last 5 rows of data as the default. You can use any number as tail(10)."
},
{
"code": null,
"e": 4551,
"s": 4541,
"text": "df.tail()"
},
{
"code": null,
"e": 4639,
"s": 4551,
"text": "For the Statistical overview, describe() prints the mean, standard deviation, min, etc."
},
{
"code": null,
"e": 4653,
"s": 4639,
"text": "df.describe()"
},
{
"code": null,
"e": 4843,
"s": 4653,
"text": "First, we import sample data which has ?, na, NA, N/A, and no data. We check if the data frame has any null values using `isnull()`. `any()` outputs by columns if there are any null values."
},
{
"code": null,
"e": 5069,
"s": 4843,
"text": "Please note that NaN will replace data items where there is no data.Comparing the first two tables, ? and na are not recognized as null. So we need to use `na_values` to recognize them as null values. This will change to NAN."
},
{
"code": null,
"e": 5092,
"s": 5069,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5303,
"s": 5092,
"text": "One way to deal with null values is to drop rows or columns. dropna() has the default value of axis=0. So dropna() and dropna(axis=0) outputs the same table. This will drop all rows where there is a null value."
},
{
"code": null,
"e": 5364,
"s": 5303,
"text": "`axis=1` will drop columns where there is NaN in the column."
},
{
"code": null,
"e": 5471,
"s": 5364,
"text": "We can fill up NaN value with the column mean. The following fill NaN in each column with its column mean."
},
{
"code": null,
"e": 5504,
"s": 5471,
"text": "You can fill up with the median."
},
{
"code": null,
"e": 5546,
"s": 5504,
"text": "Or any value you think it is appropriate."
},
{
"code": null,
"e": 5749,
"s": 5546,
"text": "Our data have a cat, dog, and fox under the col3. We use `get_dummies()` to convert categorical variable to dummy/indicator variables. This will create columns with all categories and add either 0 or 1."
},
{
"code": null,
"e": 5791,
"s": 5749,
"text": "We concatenate these dummies to our data."
},
{
"code": null,
"e": 5837,
"s": 5791,
"text": "We don’t need col3 anymore, so let’s drop it."
},
{
"code": null,
"e": 5860,
"s": 5837,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5989,
"s": 5860,
"text": "Unless you specify the column, mean, max, min, etc. returns the result of all columns. Here we are going to print only all_mean."
},
{
"code": null,
"e": 6208,
"s": 5989,
"text": "df=pd.read_csv('http://bit.ly/2vmLyvU')all_mean = df.mean()all_max = df.max()all_min = df.min()all_median = df.median()all_std = df.std()all_25_quantile = df.quantile(0.25)print('The means of all data.')print(all_mean)"
},
{
"code": null,
"e": 6259,
"s": 6208,
"text": "As an exercise, can you print all_median, all_max?"
},
{
"code": null,
"e": 6332,
"s": 6259,
"text": "Let’s focus on radius_mean in our data. We set a variable called target."
},
{
"code": null,
"e": 6394,
"s": 6332,
"text": "df=pd.read_csv('http://bit.ly/2vmLyvU')target = 'radius_mean'"
},
{
"code": null,
"e": 6442,
"s": 6394,
"text": "We find the max, min, and range of radius_mean."
},
{
"code": null,
"e": 6588,
"s": 6442,
"text": "max = df[target].max()min = df[target].min()range = max - minprint('The max is %.1f, the min is %.1f and the range is %.1f' % (max, min, range))"
},
{
"code": null,
"e": 6770,
"s": 6588,
"text": "The print command prints out within the bracket. Three %.1 print with one decimal place and will be replaced with max, min, and range. You can find out more details in this article."
},
{
"code": null,
"e": 6813,
"s": 6770,
"text": "Let’s find out the mean, median, and mode."
},
{
"code": null,
"e": 6980,
"s": 6813,
"text": "mean = df[target].mean()median = df[target].median()mode = df[target].mode()print('The mean is %.1f, the median is %.1f and the mode is %.1f.' % (mean, median, mode))"
},
{
"code": null,
"e": 7109,
"s": 6980,
"text": "The default value ofquartile is 0.5 which is the same as the median or 50%-tile. You can specify the percentile, quantile(0.25)."
},
{
"code": null,
"e": 7296,
"s": 7109,
"text": "q1 = df[target].quantile(0.25)q3 = df[target].quantile(0.75)iqr = q3-q1print('The lower quartile is %.1f, the upper quartile is %.1f and the interquartile range is %.1f' % (q1, q3, iqr))"
},
{
"code": null,
"e": 7408,
"s": 7296,
"text": "Panda’s plot() draws a line graph as the default. You can set the kind parameter with bar, hist, box, pie, etc."
},
{
"code": null,
"e": 7426,
"s": 7408,
"text": "df[target].plot()"
},
{
"code": null,
"e": 7478,
"s": 7426,
"text": "The above diagram is the line graph of radius_mean."
},
{
"code": null,
"e": 7537,
"s": 7478,
"text": "By adding kind='hist' to plot(), you can plot a histogram."
},
{
"code": null,
"e": 7566,
"s": 7537,
"text": "df[target].plot(kind='hist')"
},
{
"code": null,
"e": 7619,
"s": 7566,
"text": "By adding hist() after plot also prints a histogram."
},
{
"code": null,
"e": 7642,
"s": 7619,
"text": "df[target].plot.hist()"
},
{
"code": null,
"e": 7690,
"s": 7642,
"text": "You can add bins=100 to use 100 histogram bins."
},
{
"code": null,
"e": 7721,
"s": 7690,
"text": "df[target].plot.hist(bins=100)"
},
{
"code": null,
"e": 7778,
"s": 7721,
"text": "plot(kind='box') or plot.box() shows a box-whisker plot."
},
{
"code": null,
"e": 7806,
"s": 7778,
"text": "df[target].plot(kind='box')"
},
{
"code": null,
"e": 7928,
"s": 7806,
"text": "Matplotlib has a lot of flexibility. Here you change the outlier's color and symbol and showing three box plots together."
},
{
"code": null,
"e": 8178,
"s": 7928,
"text": "data =[df['radius_mean'],df['texture_mean'],df['texture_worst']]green_diamond = dict(markerfacecolor='g', marker='D')fig7, ax7 = plt.subplots()ax7.set_title('Multiple Samples with Different sizes')ax7.boxplot(data,flierprops=green_diamond)plt.show()"
},
{
"code": null,
"e": 8261,
"s": 8178,
"text": "Matplotlib’s histogram has a lot of flexibility. You can add different parameters."
},
{
"code": null,
"e": 8405,
"s": 8261,
"text": "plt.hist([df['radius_mean'], df['texture_mean']], histtype='barstacked', orientation='horizontal',bins=20)plt.show()"
},
{
"code": null,
"e": 8561,
"s": 8405,
"text": "Seaborn builds on top of Matplotlib and introduces additional plot types. It also makes your traditional Matplotlib plots look a bit prettier. (from Quora)"
},
{
"code": null,
"e": 8617,
"s": 8561,
"text": "sns.boxplot(x='diagnosis', y='perimeter_mean', data=df)"
}
] |
Python matplotlib multiple bars | We can use a user-defined method, autolabel, to annotate the axis value. Before that, we can initialize the fig and ax using plt.subplots() method.
Create lists, labels, men_means, and women_means with different data elements.
Create lists, labels, men_means, and women_means with different data elements.
Return evenly spaced values within a given interval, using numpy.arrange() method.
Return evenly spaced values within a given interval, using numpy.arrange() method.
Set the width variable i.e., width=0.35.
Set the width variable i.e., width=0.35.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method.
The bars are positioned at *x* with the given *align*\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method.
Set the Y-axis label using plt.ylabel() method.
Set the Y-axis label using plt.ylabel() method.
Set a title for the axes using set_title() method.
Set a title for the axes using set_title() method.
Get or set the current tick locations and labels of the X-axis, using set_xticks() method.
Get or set the current tick locations and labels of the X-axis, using set_xticks() method.
Set x axis tick labels of the grid using set_xticklabels() method.
Set x axis tick labels of the grid using set_xticklabels() method.
Place a legend on the figure using legend() method.
Place a legend on the figure using legend() method.
Annotate created bars(rect1 and rect2) with some label using autolabel() method, that is user-defined method.
Annotate created bars(rect1 and rect2) with some label using autolabel() method, that is user-defined method.
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
import matplotlib.pyplot as plt
import numpy as np
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
x = np.arange(len(labels))
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(x - width / 2, men_means, width, label='Men')
rects2 = ax.bar(x + width / 2, women_means, width, label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.show() | [
{
"code": null,
"e": 1210,
"s": 1062,
"text": "We can use a user-defined method, autolabel, to annotate the axis value. Before that, we can initialize the fig and ax using plt.subplots() method."
},
{
"code": null,
"e": 1289,
"s": 1210,
"text": "Create lists, labels, men_means, and women_means with different data elements."
},
{
"code": null,
"e": 1368,
"s": 1289,
"text": "Create lists, labels, men_means, and women_means with different data elements."
},
{
"code": null,
"e": 1451,
"s": 1368,
"text": "Return evenly spaced values within a given interval, using numpy.arrange() method."
},
{
"code": null,
"e": 1534,
"s": 1451,
"text": "Return evenly spaced values within a given interval, using numpy.arrange() method."
},
{
"code": null,
"e": 1575,
"s": 1534,
"text": "Set the width variable i.e., width=0.35."
},
{
"code": null,
"e": 1616,
"s": 1575,
"text": "Set the width variable i.e., width=0.35."
},
{
"code": null,
"e": 1704,
"s": 1616,
"text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1."
},
{
"code": null,
"e": 1792,
"s": 1704,
"text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1."
},
{
"code": null,
"e": 2001,
"s": 1792,
"text": "The bars are positioned at *x* with the given *align*\\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method."
},
{
"code": null,
"e": 2210,
"s": 2001,
"text": "The bars are positioned at *x* with the given *align*\\ment. Their dimensions are given by *height* and *width*. The vertical baseline is *bottom* (default 0), so create rect1 and rect2 using plt.bar() method."
},
{
"code": null,
"e": 2258,
"s": 2210,
"text": "Set the Y-axis label using plt.ylabel() method."
},
{
"code": null,
"e": 2306,
"s": 2258,
"text": "Set the Y-axis label using plt.ylabel() method."
},
{
"code": null,
"e": 2357,
"s": 2306,
"text": "Set a title for the axes using set_title() method."
},
{
"code": null,
"e": 2408,
"s": 2357,
"text": "Set a title for the axes using set_title() method."
},
{
"code": null,
"e": 2499,
"s": 2408,
"text": "Get or set the current tick locations and labels of the X-axis, using set_xticks() method."
},
{
"code": null,
"e": 2590,
"s": 2499,
"text": "Get or set the current tick locations and labels of the X-axis, using set_xticks() method."
},
{
"code": null,
"e": 2657,
"s": 2590,
"text": "Set x axis tick labels of the grid using set_xticklabels() method."
},
{
"code": null,
"e": 2724,
"s": 2657,
"text": "Set x axis tick labels of the grid using set_xticklabels() method."
},
{
"code": null,
"e": 2776,
"s": 2724,
"text": "Place a legend on the figure using legend() method."
},
{
"code": null,
"e": 2828,
"s": 2776,
"text": "Place a legend on the figure using legend() method."
},
{
"code": null,
"e": 2938,
"s": 2828,
"text": "Annotate created bars(rect1 and rect2) with some label using autolabel() method, that is user-defined method."
},
{
"code": null,
"e": 3048,
"s": 2938,
"text": "Annotate created bars(rect1 and rect2) with some label using autolabel() method, that is user-defined method."
},
{
"code": null,
"e": 3095,
"s": 3048,
"text": "To show the figure, use the plt.show() method."
},
{
"code": null,
"e": 3142,
"s": 3095,
"text": "To show the figure, use the plt.show() method."
},
{
"code": null,
"e": 3969,
"s": 3142,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nlabels = ['G1', 'G2', 'G3', 'G4', 'G5']\nmen_means = [20, 34, 30, 35, 27]\nwomen_means = [25, 32, 34, 20, 25]\n\nx = np.arange(len(labels))\nwidth = 0.35\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(x - width / 2, men_means, width, label='Men')\nrects2 = ax.bar(x + width / 2, women_means, width, label='Women')\n\nax.set_ylabel('Scores')\nax.set_title('Scores by group and gender')\nax.set_xticks(x)\nax.set_xticklabels(labels)\nax.legend()\n\ndef autolabel(rects):\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\nautolabel(rects1)\nautolabel(rects2)\n\nplt.show()"
}
] |
Longest Consecutive Sequence in Python | Suppose we have an array of integers. We have to find the length of the longest consecutive elements sequence. So if the input is like [100, 4, 250, 1, 3, 2], answer will be 4, as the longest consecutive sequence is [1,2,3,4].
To solve this, we will follow these steps −
make the array set, longest := 0
make the array set, longest := 0
for i in range array −if i – 1 is not in a −current := i, streak := 0while i in a −increase i by 1, increase streak by 1longest := max of longest and streak
for i in range array −
if i – 1 is not in a −current := i, streak := 0while i in a −increase i by 1, increase streak by 1longest := max of longest and streak
if i – 1 is not in a −
current := i, streak := 0
current := i, streak := 0
while i in a −increase i by 1, increase streak by 1longest := max of longest and streak
while i in a −
increase i by 1, increase streak by 1
increase i by 1, increase streak by 1
longest := max of longest and streak
longest := max of longest and streak
return longest
return longest
Let us see the following implementation to get a better understanding −
Live Demo
class Solution(object):
def longestConsecutive(self, a):
a = set(a)
longest = 0
for i in a:
if i-1 not in a:
current = i
streak = 0
while i in a:
i+=1
streak+=1
longest = max(longest,streak)
return longest
ob = Solution()
print(ob.longestConsecutive([100,4,250,1,3,2]))
[100,4,250,1,3,2]
4 | [
{
"code": null,
"e": 1289,
"s": 1062,
"text": "Suppose we have an array of integers. We have to find the length of the longest consecutive elements sequence. So if the input is like [100, 4, 250, 1, 3, 2], answer will be 4, as the longest consecutive sequence is [1,2,3,4]."
},
{
"code": null,
"e": 1333,
"s": 1289,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1366,
"s": 1333,
"text": "make the array set, longest := 0"
},
{
"code": null,
"e": 1399,
"s": 1366,
"text": "make the array set, longest := 0"
},
{
"code": null,
"e": 1556,
"s": 1399,
"text": "for i in range array −if i – 1 is not in a −current := i, streak := 0while i in a −increase i by 1, increase streak by 1longest := max of longest and streak"
},
{
"code": null,
"e": 1579,
"s": 1556,
"text": "for i in range array −"
},
{
"code": null,
"e": 1714,
"s": 1579,
"text": "if i – 1 is not in a −current := i, streak := 0while i in a −increase i by 1, increase streak by 1longest := max of longest and streak"
},
{
"code": null,
"e": 1737,
"s": 1714,
"text": "if i – 1 is not in a −"
},
{
"code": null,
"e": 1763,
"s": 1737,
"text": "current := i, streak := 0"
},
{
"code": null,
"e": 1789,
"s": 1763,
"text": "current := i, streak := 0"
},
{
"code": null,
"e": 1877,
"s": 1789,
"text": "while i in a −increase i by 1, increase streak by 1longest := max of longest and streak"
},
{
"code": null,
"e": 1892,
"s": 1877,
"text": "while i in a −"
},
{
"code": null,
"e": 1930,
"s": 1892,
"text": "increase i by 1, increase streak by 1"
},
{
"code": null,
"e": 1968,
"s": 1930,
"text": "increase i by 1, increase streak by 1"
},
{
"code": null,
"e": 2005,
"s": 1968,
"text": "longest := max of longest and streak"
},
{
"code": null,
"e": 2042,
"s": 2005,
"text": "longest := max of longest and streak"
},
{
"code": null,
"e": 2057,
"s": 2042,
"text": "return longest"
},
{
"code": null,
"e": 2072,
"s": 2057,
"text": "return longest"
},
{
"code": null,
"e": 2144,
"s": 2072,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 2155,
"s": 2144,
"text": " Live Demo"
},
{
"code": null,
"e": 2543,
"s": 2155,
"text": "class Solution(object):\n def longestConsecutive(self, a):\n a = set(a)\n longest = 0\n for i in a:\n if i-1 not in a:\n current = i\n streak = 0\n while i in a:\n i+=1\n streak+=1\n longest = max(longest,streak)\n return longest\n\nob = Solution()\nprint(ob.longestConsecutive([100,4,250,1,3,2]))"
},
{
"code": null,
"e": 2561,
"s": 2543,
"text": "[100,4,250,1,3,2]"
},
{
"code": null,
"e": 2563,
"s": 2561,
"text": "4"
}
] |
Frequent pattern mining, Association, and Correlations | by Prathibha Perera | Towards Data Science | In Data Mining, Frequent Pattern Mining is a major concern because it is playing a major role in Associations and Correlations. First of all, we should know what is a Frequent Pattern?
Frequent Pattern is a pattern which appears frequently in a data set. By identifying frequent patterns we can observe strongly correlated items together and easily identify similar characteristics, associations among them. By doing frequent pattern mining, it leads to further analysis like clustering, classification and other data mining tasks.
Before moving to mine frequent patterns, we should focus on two terms which “support” and “confidence” because they can provide a measure if the Association rule is qualified or not for a particular data set.
Support: how often a given rule appears in the database being mined
Confidence: the number of times a given rule turns out to be true in practice
Let’s practice it through a sample data set;
Example: One of possible Association Rule is A => D
Total no of Transactions(N) = 5
Frequency(A, D) = > Total no of instances together A with D is 3
Frequency(A) => Total no of occurrence in A
Support = 3 / 5
Confidence = 3 / 4
After getting a clear idea about the two terms Support and Confidence, we can move to frequent pattern mining. Frequent pattern mining, there are 2 categories to be considered,
Mining frequent pattern with candidate generationMining frequent pattern without candidate generation
Mining frequent pattern with candidate generation
Mining frequent pattern without candidate generation
In this article, we are focusing on Mining frequent patterns with candidate generation with Apriori Algorithm which is popularly used for Association mining. Let’s understand Apriori Algorithm with an example and it will help you to understand the concept behind it in a clear manner. Let’s consider the sample data set mentioned above and assume that the minimum support=2.
Generate Candidate set 1, do the first scan and generate One item set
Generate Candidate set 1, do the first scan and generate One item set
In this stage, we get the sample data set and take each individual’s count and make frequent item set 1(K = 1).
“Candidate set 1” figure shows you the individual item Support count. Hence the minimum support is 2 and based on that, item E will remove from the Candidate set 1 as an infrequent item (disqualified).
Frequent itemset based on the minimum support value will be shown under the figure “Frequent item set from the first scan” as the “One item set”.
2. Generate Candidate set 2, do the second scan and generate Second item set
Through this step, you create frequent set 2 (K =2) and takes each of their Support counts.
“Candidate set 2” figure generates through joining Candidate set 1 and takes the frequency of related occurrences. Hence the minimum support is 2, Itemset B, D will be removed from Candidate set 2 as an infrequent item set.
“Frequent item set from the second scan” is the frequent itemset based on the minimum support value and it will generate the “Second item set”.
3. Generate Candidate set 3, do the third scan and generate Third item set
In this iteration create frequent set 3 (K = 3) and take count of Support. Then compare with the minimum support value from the Candidate set 3.
As you can see here we compare Candidate set 3 with the minimum support value, generated Third item set. The frequent set from the third scan is the same as above.
4. Generate Candidate set 4, do the fourth scan and generate Fourth item set
By considering the Frequent set, we can generate Candidate set 4, by joining Candidate set 3. Then possible Candidate set 4 is; [A, B, C, D] which has minimum support less than 2. Therefore we have to stop the calculation from here because we can not go no any more iterations. Therefore for the above data set frequent patterns are [A, B, C] and [A, C, D].
By considering one of the frequent set as{A, B, C} and the possible Association rules as follows;
A => B, CA, B => CA, C => BB => A, CB, C => AC => A, B
A => B, C
A, B => C
A, C => B
B => A, C
B, C => A
C => A, B
Then we assume that the minimum confidence = 50% and calculate each possible Association rules’ Confidence then we can identify disqualified ones with respect to minimum confidence is less than 50%. Then rest of the Association rules which have the Confidence greater or equal to 50% percent those are qualified rules.
As you can see in the Apriori Algorithm, for each step it is generating candidates and it is taking much time when the list of candidates becomes larger.
Now let’s focus on how to do Association using Weka. You can follow the below steps.
Open Weka software and click the “Explore” button.
Open Weka software and click the “Explore” button.
After clicking the “Explorer” button you will get a new window named “Weka Explorer”.
2. Open a preferred data set
Weka Explorer > Preprocess > Open File
By following the above order you can load a data set by selecting an in-built data set or any data set that you want to apply to the Apriori Algorithm.
After opening the selected file you can see the attributes and other statistics under the Preprocess tab. Then you can click the “Edit” button to open the current data set in a Viewer for editing.
♦♦♦♦♦♦♦♦♦ It is important to notice that, your data set includes numerical data you can discretize them using a filter called “Discretize” under the Preprocess tab♦♦♦♦♦♦♦♦♦
3. Go to the Associate tab and choose Apriori, using the choose button.
4. Left click on Apriori and select “Show properties..”
5. Customise the algorithm properties and then click on “Save”
As an example, we can change the number of rules which you obtained from the data set after the Association is done.
6. Click on the “Start” button
♦♦♦♦It is important to notice that you will not enable the “Start” button if it does not have discrete data which is chosen to do Association♦♦♦♦♦♦♦
7. Observe the results
Associator output is as follows and in this case, Algorithm has found the 10 best rules for the provided data set.
This article provides you with some facts that you may know about Frequent pattern mining, Apriori Algorithm, Support, Confidence, and how to proceed with Association through Weka software. Hope this article will help you to enhance your knowledge about the above-mentioned points.
Thank you for reading 🤗 !!!!!
Reference
[1] Ion Lungu, Alexandru Pirjan, Research issues concerning algorithms used for optimizing the data mining process (2010) | [
{
"code": null,
"e": 356,
"s": 171,
"text": "In Data Mining, Frequent Pattern Mining is a major concern because it is playing a major role in Associations and Correlations. First of all, we should know what is a Frequent Pattern?"
},
{
"code": null,
"e": 703,
"s": 356,
"text": "Frequent Pattern is a pattern which appears frequently in a data set. By identifying frequent patterns we can observe strongly correlated items together and easily identify similar characteristics, associations among them. By doing frequent pattern mining, it leads to further analysis like clustering, classification and other data mining tasks."
},
{
"code": null,
"e": 912,
"s": 703,
"text": "Before moving to mine frequent patterns, we should focus on two terms which “support” and “confidence” because they can provide a measure if the Association rule is qualified or not for a particular data set."
},
{
"code": null,
"e": 980,
"s": 912,
"text": "Support: how often a given rule appears in the database being mined"
},
{
"code": null,
"e": 1058,
"s": 980,
"text": "Confidence: the number of times a given rule turns out to be true in practice"
},
{
"code": null,
"e": 1103,
"s": 1058,
"text": "Let’s practice it through a sample data set;"
},
{
"code": null,
"e": 1155,
"s": 1103,
"text": "Example: One of possible Association Rule is A => D"
},
{
"code": null,
"e": 1187,
"s": 1155,
"text": "Total no of Transactions(N) = 5"
},
{
"code": null,
"e": 1252,
"s": 1187,
"text": "Frequency(A, D) = > Total no of instances together A with D is 3"
},
{
"code": null,
"e": 1296,
"s": 1252,
"text": "Frequency(A) => Total no of occurrence in A"
},
{
"code": null,
"e": 1312,
"s": 1296,
"text": "Support = 3 / 5"
},
{
"code": null,
"e": 1331,
"s": 1312,
"text": "Confidence = 3 / 4"
},
{
"code": null,
"e": 1508,
"s": 1331,
"text": "After getting a clear idea about the two terms Support and Confidence, we can move to frequent pattern mining. Frequent pattern mining, there are 2 categories to be considered,"
},
{
"code": null,
"e": 1610,
"s": 1508,
"text": "Mining frequent pattern with candidate generationMining frequent pattern without candidate generation"
},
{
"code": null,
"e": 1660,
"s": 1610,
"text": "Mining frequent pattern with candidate generation"
},
{
"code": null,
"e": 1713,
"s": 1660,
"text": "Mining frequent pattern without candidate generation"
},
{
"code": null,
"e": 2088,
"s": 1713,
"text": "In this article, we are focusing on Mining frequent patterns with candidate generation with Apriori Algorithm which is popularly used for Association mining. Let’s understand Apriori Algorithm with an example and it will help you to understand the concept behind it in a clear manner. Let’s consider the sample data set mentioned above and assume that the minimum support=2."
},
{
"code": null,
"e": 2158,
"s": 2088,
"text": "Generate Candidate set 1, do the first scan and generate One item set"
},
{
"code": null,
"e": 2228,
"s": 2158,
"text": "Generate Candidate set 1, do the first scan and generate One item set"
},
{
"code": null,
"e": 2340,
"s": 2228,
"text": "In this stage, we get the sample data set and take each individual’s count and make frequent item set 1(K = 1)."
},
{
"code": null,
"e": 2542,
"s": 2340,
"text": "“Candidate set 1” figure shows you the individual item Support count. Hence the minimum support is 2 and based on that, item E will remove from the Candidate set 1 as an infrequent item (disqualified)."
},
{
"code": null,
"e": 2688,
"s": 2542,
"text": "Frequent itemset based on the minimum support value will be shown under the figure “Frequent item set from the first scan” as the “One item set”."
},
{
"code": null,
"e": 2765,
"s": 2688,
"text": "2. Generate Candidate set 2, do the second scan and generate Second item set"
},
{
"code": null,
"e": 2857,
"s": 2765,
"text": "Through this step, you create frequent set 2 (K =2) and takes each of their Support counts."
},
{
"code": null,
"e": 3081,
"s": 2857,
"text": "“Candidate set 2” figure generates through joining Candidate set 1 and takes the frequency of related occurrences. Hence the minimum support is 2, Itemset B, D will be removed from Candidate set 2 as an infrequent item set."
},
{
"code": null,
"e": 3225,
"s": 3081,
"text": "“Frequent item set from the second scan” is the frequent itemset based on the minimum support value and it will generate the “Second item set”."
},
{
"code": null,
"e": 3300,
"s": 3225,
"text": "3. Generate Candidate set 3, do the third scan and generate Third item set"
},
{
"code": null,
"e": 3445,
"s": 3300,
"text": "In this iteration create frequent set 3 (K = 3) and take count of Support. Then compare with the minimum support value from the Candidate set 3."
},
{
"code": null,
"e": 3609,
"s": 3445,
"text": "As you can see here we compare Candidate set 3 with the minimum support value, generated Third item set. The frequent set from the third scan is the same as above."
},
{
"code": null,
"e": 3686,
"s": 3609,
"text": "4. Generate Candidate set 4, do the fourth scan and generate Fourth item set"
},
{
"code": null,
"e": 4044,
"s": 3686,
"text": "By considering the Frequent set, we can generate Candidate set 4, by joining Candidate set 3. Then possible Candidate set 4 is; [A, B, C, D] which has minimum support less than 2. Therefore we have to stop the calculation from here because we can not go no any more iterations. Therefore for the above data set frequent patterns are [A, B, C] and [A, C, D]."
},
{
"code": null,
"e": 4142,
"s": 4044,
"text": "By considering one of the frequent set as{A, B, C} and the possible Association rules as follows;"
},
{
"code": null,
"e": 4197,
"s": 4142,
"text": "A => B, CA, B => CA, C => BB => A, CB, C => AC => A, B"
},
{
"code": null,
"e": 4207,
"s": 4197,
"text": "A => B, C"
},
{
"code": null,
"e": 4217,
"s": 4207,
"text": "A, B => C"
},
{
"code": null,
"e": 4227,
"s": 4217,
"text": "A, C => B"
},
{
"code": null,
"e": 4237,
"s": 4227,
"text": "B => A, C"
},
{
"code": null,
"e": 4247,
"s": 4237,
"text": "B, C => A"
},
{
"code": null,
"e": 4257,
"s": 4247,
"text": "C => A, B"
},
{
"code": null,
"e": 4576,
"s": 4257,
"text": "Then we assume that the minimum confidence = 50% and calculate each possible Association rules’ Confidence then we can identify disqualified ones with respect to minimum confidence is less than 50%. Then rest of the Association rules which have the Confidence greater or equal to 50% percent those are qualified rules."
},
{
"code": null,
"e": 4730,
"s": 4576,
"text": "As you can see in the Apriori Algorithm, for each step it is generating candidates and it is taking much time when the list of candidates becomes larger."
},
{
"code": null,
"e": 4815,
"s": 4730,
"text": "Now let’s focus on how to do Association using Weka. You can follow the below steps."
},
{
"code": null,
"e": 4866,
"s": 4815,
"text": "Open Weka software and click the “Explore” button."
},
{
"code": null,
"e": 4917,
"s": 4866,
"text": "Open Weka software and click the “Explore” button."
},
{
"code": null,
"e": 5003,
"s": 4917,
"text": "After clicking the “Explorer” button you will get a new window named “Weka Explorer”."
},
{
"code": null,
"e": 5032,
"s": 5003,
"text": "2. Open a preferred data set"
},
{
"code": null,
"e": 5071,
"s": 5032,
"text": "Weka Explorer > Preprocess > Open File"
},
{
"code": null,
"e": 5223,
"s": 5071,
"text": "By following the above order you can load a data set by selecting an in-built data set or any data set that you want to apply to the Apriori Algorithm."
},
{
"code": null,
"e": 5420,
"s": 5223,
"text": "After opening the selected file you can see the attributes and other statistics under the Preprocess tab. Then you can click the “Edit” button to open the current data set in a Viewer for editing."
},
{
"code": null,
"e": 5593,
"s": 5420,
"text": "♦♦♦♦♦♦♦♦♦ It is important to notice that, your data set includes numerical data you can discretize them using a filter called “Discretize” under the Preprocess tab♦♦♦♦♦♦♦♦♦"
},
{
"code": null,
"e": 5665,
"s": 5593,
"text": "3. Go to the Associate tab and choose Apriori, using the choose button."
},
{
"code": null,
"e": 5721,
"s": 5665,
"text": "4. Left click on Apriori and select “Show properties..”"
},
{
"code": null,
"e": 5784,
"s": 5721,
"text": "5. Customise the algorithm properties and then click on “Save”"
},
{
"code": null,
"e": 5901,
"s": 5784,
"text": "As an example, we can change the number of rules which you obtained from the data set after the Association is done."
},
{
"code": null,
"e": 5932,
"s": 5901,
"text": "6. Click on the “Start” button"
},
{
"code": null,
"e": 6081,
"s": 5932,
"text": "♦♦♦♦It is important to notice that you will not enable the “Start” button if it does not have discrete data which is chosen to do Association♦♦♦♦♦♦♦"
},
{
"code": null,
"e": 6104,
"s": 6081,
"text": "7. Observe the results"
},
{
"code": null,
"e": 6219,
"s": 6104,
"text": "Associator output is as follows and in this case, Algorithm has found the 10 best rules for the provided data set."
},
{
"code": null,
"e": 6501,
"s": 6219,
"text": "This article provides you with some facts that you may know about Frequent pattern mining, Apriori Algorithm, Support, Confidence, and how to proceed with Association through Weka software. Hope this article will help you to enhance your knowledge about the above-mentioned points."
},
{
"code": null,
"e": 6531,
"s": 6501,
"text": "Thank you for reading 🤗 !!!!!"
},
{
"code": null,
"e": 6541,
"s": 6531,
"text": "Reference"
}
] |
Simple Transformers — Introducing The Easiest Way To Use BERT, RoBERTa, XLNet, and XLM | by Thilina Rajapakse | Towards Data Science | The Simple Transformers library is built as a wrapper around the excellent Transformers library by Hugging Face. I am eternally grateful for the hard work done by the folks at Hugging Face to enable the public to easily access and use Transformer models. I don’t know what I’d have done without you guys!
I believe it’s fair to say that the success of Transformer models have been nothing short of phenomenal in advancing the field of Natural Language Processing. Not only have they shown staggering leaps in performance on many NLP tasks they were designed to solve, pre-trained Transformers are also almost uncannily good at Transfer Learning. This means that anyone can take advantage of the long hours and the mind-boggling computational power that has gone into training these models to perform a countless variety of NLP tasks. You don’t need the deep pockets of Google or Facebook to build a state-of-the-art model to solve your NLP problem anymore!
Or so one might hope. The truth is that getting these models to work still requires substantial technical know-how. Unless you have expertise or at least experience in deep learning, it can seem a daunting challenge. I am happy to say that my previous articles on Transformers (here and here) seem to have helped a lot of people get a start on using Transformers. Interestingly, I noticed that people of various backgrounds (linguistics, medicine, and business to name but a few) were attempting to use these models to solve problems in their own domain. However, the technical barriers that need to be overcome in order to adapt Transformers to specific tasks are non-trivial and may even be rather discouraging.
This conundrum was the main motivation behind my decision to develop a simple library to perform (binary and multiclass) text classification (the most common NLP task that I’ve seen) using Transformers. The idea was to make it as simple as possible, which means abstracting away a lot of the implementational and technical details. The implementation of the library can be found on Github. I highly encourage you to look at it to get a better idea of how everything works, although it is not necessary to know the inner details to use the library.
To that end, the Simple Transformers library was written so that a Transformer model can be initialized, trained on a given dataset, and evaluated on a given dataset, in just 3 lines of code! Let’s see how it’s done, shall we?
Install Anaconda or Miniconda Package Manager from hereCreate a new virtual environment and install the required packages.conda create -n transformers python pandas tqdmconda activate transformersIf using cuda: conda install pytorch cudatoolkit=10.0 -c pytorchelse: conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install tensorboardxInstall simpletransformers.pip install simpletransformers
Install Anaconda or Miniconda Package Manager from here
Create a new virtual environment and install the required packages.conda create -n transformers python pandas tqdmconda activate transformersIf using cuda: conda install pytorch cudatoolkit=10.0 -c pytorchelse: conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install tensorboardx
Install simpletransformers.pip install simpletransformers
A quick look at how to use this library on the Yelp Reviews dataset.
Download Yelp Reviews Dataset.Extract train.csv and test.csv and place them in the directory data/.
Download Yelp Reviews Dataset.
Extract train.csv and test.csv and place them in the directory data/.
(Bash users can use this script to download the dataset)
Nothing fancy here, we are just getting the data in the correct form. This is all you have to do for any dataset.
Create two pandas DataFrame objects for the train and eval portions.
Each DataFrame should have two columns. The first column contains the text that you want to train or evaluate and has the datatype str. The second column has the corresponding label and has the datatype int.Update: It is now recommended to name the columns as labels and text rather than relying on the order of the columns.
With the data in order, it’s time to train and evaluate the model.
That’s it!
For making predictions on other text, TransformerModel comes with a predict(to_predict) method which given a list of text, returns the model predictions and the raw model outputs.
For more details on all available methods, please see the Github repo. The repo also contains a minimal example of using the library.
The default args used are given below. Any of these can be overridden by passing a dict containing the corresponding key/value pairs to the init method of TransformerModel. (See example below)
self.args = { 'model_type': 'roberta', 'model_name': 'roberta-base', 'output_dir': 'outputs/', 'cache_dir': 'cache/', 'fp16': True, 'fp16_opt_level': 'O1', 'max_seq_length': 128, 'train_batch_size': 8, 'eval_batch_size': 8, 'gradient_accumulation_steps': 1, 'num_train_epochs': 1, 'weight_decay': 0, 'learning_rate': 4e-5, 'adam_epsilon': 1e-8, 'warmup_ratio': 0.06, 'warmup_steps': 0, 'max_grad_norm': 1.0, 'logging_steps': 50, 'evaluate_during_training': False, 'save_steps': 2000, 'eval_all_checkpoints': True, 'use_tensorboard': True, 'overwrite_output_dir': False, 'reprocess_input_data': False,}
To override any of these, simply pass in a dictionary with the appropriate key/value pair to the TransformerModel.
For an explanation of what each argument does, please refer to the Github repo.
Update: See docs for current args.
That’s all folks! The easiest way to use Transformer models that I know of. | [
{
"code": null,
"e": 476,
"s": 171,
"text": "The Simple Transformers library is built as a wrapper around the excellent Transformers library by Hugging Face. I am eternally grateful for the hard work done by the folks at Hugging Face to enable the public to easily access and use Transformer models. I don’t know what I’d have done without you guys!"
},
{
"code": null,
"e": 1128,
"s": 476,
"text": "I believe it’s fair to say that the success of Transformer models have been nothing short of phenomenal in advancing the field of Natural Language Processing. Not only have they shown staggering leaps in performance on many NLP tasks they were designed to solve, pre-trained Transformers are also almost uncannily good at Transfer Learning. This means that anyone can take advantage of the long hours and the mind-boggling computational power that has gone into training these models to perform a countless variety of NLP tasks. You don’t need the deep pockets of Google or Facebook to build a state-of-the-art model to solve your NLP problem anymore!"
},
{
"code": null,
"e": 1842,
"s": 1128,
"text": "Or so one might hope. The truth is that getting these models to work still requires substantial technical know-how. Unless you have expertise or at least experience in deep learning, it can seem a daunting challenge. I am happy to say that my previous articles on Transformers (here and here) seem to have helped a lot of people get a start on using Transformers. Interestingly, I noticed that people of various backgrounds (linguistics, medicine, and business to name but a few) were attempting to use these models to solve problems in their own domain. However, the technical barriers that need to be overcome in order to adapt Transformers to specific tasks are non-trivial and may even be rather discouraging."
},
{
"code": null,
"e": 2390,
"s": 1842,
"text": "This conundrum was the main motivation behind my decision to develop a simple library to perform (binary and multiclass) text classification (the most common NLP task that I’ve seen) using Transformers. The idea was to make it as simple as possible, which means abstracting away a lot of the implementational and technical details. The implementation of the library can be found on Github. I highly encourage you to look at it to get a better idea of how everything works, although it is not necessary to know the inner details to use the library."
},
{
"code": null,
"e": 2617,
"s": 2390,
"text": "To that end, the Simple Transformers library was written so that a Transformer model can be initialized, trained on a given dataset, and evaluated on a given dataset, in just 3 lines of code! Let’s see how it’s done, shall we?"
},
{
"code": null,
"e": 3098,
"s": 2617,
"text": "Install Anaconda or Miniconda Package Manager from hereCreate a new virtual environment and install the required packages.conda create -n transformers python pandas tqdmconda activate transformersIf using cuda: conda install pytorch cudatoolkit=10.0 -c pytorchelse: conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install tensorboardxInstall simpletransformers.pip install simpletransformers"
},
{
"code": null,
"e": 3154,
"s": 3098,
"text": "Install Anaconda or Miniconda Package Manager from here"
},
{
"code": null,
"e": 3523,
"s": 3154,
"text": "Create a new virtual environment and install the required packages.conda create -n transformers python pandas tqdmconda activate transformersIf using cuda: conda install pytorch cudatoolkit=10.0 -c pytorchelse: conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install tensorboardx"
},
{
"code": null,
"e": 3581,
"s": 3523,
"text": "Install simpletransformers.pip install simpletransformers"
},
{
"code": null,
"e": 3650,
"s": 3581,
"text": "A quick look at how to use this library on the Yelp Reviews dataset."
},
{
"code": null,
"e": 3750,
"s": 3650,
"text": "Download Yelp Reviews Dataset.Extract train.csv and test.csv and place them in the directory data/."
},
{
"code": null,
"e": 3781,
"s": 3750,
"text": "Download Yelp Reviews Dataset."
},
{
"code": null,
"e": 3851,
"s": 3781,
"text": "Extract train.csv and test.csv and place them in the directory data/."
},
{
"code": null,
"e": 3908,
"s": 3851,
"text": "(Bash users can use this script to download the dataset)"
},
{
"code": null,
"e": 4022,
"s": 3908,
"text": "Nothing fancy here, we are just getting the data in the correct form. This is all you have to do for any dataset."
},
{
"code": null,
"e": 4091,
"s": 4022,
"text": "Create two pandas DataFrame objects for the train and eval portions."
},
{
"code": null,
"e": 4416,
"s": 4091,
"text": "Each DataFrame should have two columns. The first column contains the text that you want to train or evaluate and has the datatype str. The second column has the corresponding label and has the datatype int.Update: It is now recommended to name the columns as labels and text rather than relying on the order of the columns."
},
{
"code": null,
"e": 4483,
"s": 4416,
"text": "With the data in order, it’s time to train and evaluate the model."
},
{
"code": null,
"e": 4494,
"s": 4483,
"text": "That’s it!"
},
{
"code": null,
"e": 4674,
"s": 4494,
"text": "For making predictions on other text, TransformerModel comes with a predict(to_predict) method which given a list of text, returns the model predictions and the raw model outputs."
},
{
"code": null,
"e": 4808,
"s": 4674,
"text": "For more details on all available methods, please see the Github repo. The repo also contains a minimal example of using the library."
},
{
"code": null,
"e": 5001,
"s": 4808,
"text": "The default args used are given below. Any of these can be overridden by passing a dict containing the corresponding key/value pairs to the init method of TransformerModel. (See example below)"
},
{
"code": null,
"e": 5652,
"s": 5001,
"text": "self.args = { 'model_type': 'roberta', 'model_name': 'roberta-base', 'output_dir': 'outputs/', 'cache_dir': 'cache/', 'fp16': True, 'fp16_opt_level': 'O1', 'max_seq_length': 128, 'train_batch_size': 8, 'eval_batch_size': 8, 'gradient_accumulation_steps': 1, 'num_train_epochs': 1, 'weight_decay': 0, 'learning_rate': 4e-5, 'adam_epsilon': 1e-8, 'warmup_ratio': 0.06, 'warmup_steps': 0, 'max_grad_norm': 1.0, 'logging_steps': 50, 'evaluate_during_training': False, 'save_steps': 2000, 'eval_all_checkpoints': True, 'use_tensorboard': True, 'overwrite_output_dir': False, 'reprocess_input_data': False,}"
},
{
"code": null,
"e": 5767,
"s": 5652,
"text": "To override any of these, simply pass in a dictionary with the appropriate key/value pair to the TransformerModel."
},
{
"code": null,
"e": 5847,
"s": 5767,
"text": "For an explanation of what each argument does, please refer to the Github repo."
},
{
"code": null,
"e": 5882,
"s": 5847,
"text": "Update: See docs for current args."
}
] |
EDA: Variable Relationships and Filling Missing Values | by Wesley Neill | Towards Data Science | As part of my journey as a data scientist, end-to-end data exploration and model development has been a key to my learning success. This series will provide an end to end look at predicting home sale prices in Ames Iowa. The series will be broken down into four parts for readability:
EDA Part 1: Plotting Warmup and Filling in Missing Values
EDA Part 2: Feature Engineering and Variable Encoding
EDA Part 3: Statistical Tests
Predictive Modeling: Training and Tuning XGBoost
Stacking Models: Combining XGBoost with Enet, Ridge, and Lasso
Open up a Jupyter Notebook, download the data, and follow along by implementing the following strategies yourself. I’ve included a few ‘exercises’ to get you going. I’m hiding the full code to force you to focus on the thought process. Additionally, by typing the code out yourself, you will gain experience that will eventually lead to fluency. However, if you need help along the way, you can find my full notebook here.
If you already read my article “A Beginner’s Look at Kaggle”, you know what’s coming: Let’s get our hands dirty with EDA. It’s going to be the sole focus of this part of the series.
This first section will focus primarily on basic plotting and missing value imputation. My goal is to outline a process for building an intuition as to what variables are at play, and which have the greatest impact on sale price. I also want to evaluate relationships between variables because it will give insight on how we might intelligently fill missing data.
The focus of our data exploration throughout the 4 part series is as follows:
Visually Representing Data — Graphing and plotting our data can provide human insight into the real-world implications of our data. We have 79 variables at play, so it’s a great way to get a feel for what’s going on. All visualizations should be taken with a grain of salt, however. They don’t tell the whole story.
Finding and Dealing with Missing Data — In this phase, we will analyze what variables have missing values, why they are missing, and how we might deal with the missing data.
Feature Engineering — Can we find and define underlying patterns in the data that help us better describe and solve our problem?
Strength of association. Provided that a variable is related to Sale Price at all, how strong is that relationship?
ANOVA F-Test of categorical variables against sale price. Unlike continuous variables, we can not necessarily determine the traditional correlation metric between categories and continuous data. Through analysis of variance or ANOVA, we can gain some insight into whether there is a significant impact of a categorical variable such as neighborhood on the continuous variable sale price.
*****************************************************************Exercise 1: Sign up for a Kaggle account and download the data we will be using! I keep my data in a folder called data located in the same directory as my notebook.*****************************************************************
import pandas as pdtrain_df = pd.read_csv('data/train.csv', index_col='Id')test_df = pd.read_csv('data/test.csv', index_col='Id')train_df.describe().T.head(10)
To begin getting a feel for our data, we will plot our target variable distribution along with a couple of different transformations. We’ll do this for a couple of reasons:
We want to understand our data, and looking at it visually helps us build intuition of the underlying factors that affect an outcome. It gets the wheels turning in our mind, and hopefully spurs questions that might lead to valuable insights.Transforming the distributions of our variables is common industry practice. Transformation is not always necessary or helpful. The mathematical theory behind the effectiveness of data transformation goes deep and is often debated (especially in the realm of deep learning). It suffices to say “it depends” and then experiment!
We want to understand our data, and looking at it visually helps us build intuition of the underlying factors that affect an outcome. It gets the wheels turning in our mind, and hopefully spurs questions that might lead to valuable insights.
Transforming the distributions of our variables is common industry practice. Transformation is not always necessary or helpful. The mathematical theory behind the effectiveness of data transformation goes deep and is often debated (especially in the realm of deep learning). It suffices to say “it depends” and then experiment!
Before transformation, our sale price data is right-skewed, meaning that the mean is biased towards a higher price than the median. Applying a Yeo Johnson transformation via sklearn.preprocessing.PowerTransformer() we get a pretty good approximation of the standard normal distribution:
import sklearn.preprocessing as preimport seaborn as snsimport matplotlib.pyplot as pltpt = pre.PowerTransformer()ptd = pt.fit_transform(train_df.SalePrice.to_numpy().reshape(-1,1))plt.title(f'Yeo Johnson, Skew: {stats.skew(ptd.squeeze()):.3f}')sns.distplot(ptd, kde=True)
I also checked out using a log transformation, but we don’t get quite as close to a normal distribution:
These transformations alter the meaning of the data (notice the lack of the ‘SalePrice’ label on the horizontal axis). The main purpose of transforming the target variable is in hopes of assisting the training of a machine learning algorithm. Again, this requires experimentation and won’t be covered until Part 3 of this series.
As our second warm-up exercise, let’s check our intuition that it’s not just quantity but the quality that counts toward the final sale price:
fig, axes = plt.subplots(2,2, figsize=(12,12))sns.scatterplot( x='GrLivArea', y='SalePrice', hue='OverallQual', data=train_df, ax=axes[0,0])...plt.tight_layout()# Try reproducing the plot below using the above code as a hint.
In the first column, we compare the sale price to the above-ground living (aka GrLivArea) area and the overall quality of home build materials. What we see is that the sale price is graduated well by both living-area and by quality. This is evident in the strong linear trend in the scatterplot, the even graduation of hue, as well as the boxplot of overall quality.
Somewhat surprisingly, we see that the variable describing the overall condition, OverallCond, seems to have little effect on sale price. The hue of the data points in the second scatterplot is random, and the boxplot is unordered. This is counter-intuitive, and we can dig into whether or not what we are seeing makes sense a little later.
Also, notice the two outliers in the data. There are two homes seen in the scatterplots that have quite large living areas, yet somehow sold for very low prices relative to others of the same size.
*****************************************************************Exercise 2: Investigate your intuitions about other variables and their relation to the sale price and one another by plotting them. Check out Seaborn’s great utility for plotting relationships.*****************************************************************
Our next round of analysis will focus on our missing data. We want to know why the data is missing, and how we might be able to fill in the blanks. Lost data is lost information that might otherwise be useful to us. It is often worth attempting to fill in those blanks for better predictions.
First, we will address the gaps in our missing training data. I wrote a little function to visualize missing data in a data set. Look in my full notebook for a method called viz_missing(df):
The barplot shows a lot of missing data. This data shouldn’t be ignored if we wish to get really good results. This part of the process is tedious but necessary. I encourage you to focus on the following thought process:
Choose a variable with missing data you wish to fill.See if there is another variable, related to the one you are investigating.Determine if the missing data can be accounted for by the related variable.If you cannot determine the missing information by using steps 2 & 3, consider using mean, median, or mode. Be aware that this can be dangerous for small datasets.
Choose a variable with missing data you wish to fill.
See if there is another variable, related to the one you are investigating.
Determine if the missing data can be accounted for by the related variable.
If you cannot determine the missing information by using steps 2 & 3, consider using mean, median, or mode. Be aware that this can be dangerous for small datasets.
The variable with the greatest amount of missing data in the chart above is PoolQC which stands for ‘Pool Quality and Condition’.
After looking at our data dictionary, we should notice that there is only one other variable that describes a home’s pool. That variable is PoolArea. Take note that there is no missing data associated with that variable.
My intuition is that all of the homes that have PoolArea = 0 may be associated with homes that are missing PoolQC information. In other words, those homes don’t have pools, and that is why they are missing the pool quality variable. We can check that intuition with just a couple lines of code:
# Get number of homes with missing PoolQC that also have 0 PoolArea.np = train_df[train_df.PoolQc.isna() & (train_df.PoolArea == 0)]count = np.shape[0]# Get total number of missing PoolQC entriesmissing = train_df.PoolQC.isna().sum()count, missing>>> (1452, 1452)
So we see that for all 1452 homes missing PoolQC entries, the PoolArea of that home is 0. This proves our intuition correct. We can fill in the blanks with one more line of code:
train_df.PoolQC.fillna("NA", inplace=True)
LotFrontage, according to the data dictionary, is the measure of the number of feet of road that is connected to the property. This time we don’t have any additional variables that will tell us why LotFrontage is missing. This means we will have to approach filling the blanks differently.
We may reasonably assume that almost every piece of property touches at least a small part of some road or alley. This may not be universally true, but is probably the rule rather than the exception. We will use this intuition to fill any missing LotFrontage with the mean or median of all homes for which we do have this data:
train_df.LotFrontage.fillna(train_df.LotFrontage.median(), inplace=True)
I chose to fill the missing entries with the median, as it will be more robust against outliers.
*****************************************************************Exercise 3: Perform this same investigation on all the missing data in both the test and training sets. It should take you a while. A lot is missing!*****************************************************************
I’m going to leave off here until part 2 of the series. Completing exercises 1–3 should take you quite some time and are encouraged to code up these exercises before moving on.
If you have any questions, comments, or critiques, please feel to reach out to me in the comment section! | [
{
"code": null,
"e": 457,
"s": 172,
"text": "As part of my journey as a data scientist, end-to-end data exploration and model development has been a key to my learning success. This series will provide an end to end look at predicting home sale prices in Ames Iowa. The series will be broken down into four parts for readability:"
},
{
"code": null,
"e": 515,
"s": 457,
"text": "EDA Part 1: Plotting Warmup and Filling in Missing Values"
},
{
"code": null,
"e": 569,
"s": 515,
"text": "EDA Part 2: Feature Engineering and Variable Encoding"
},
{
"code": null,
"e": 599,
"s": 569,
"text": "EDA Part 3: Statistical Tests"
},
{
"code": null,
"e": 648,
"s": 599,
"text": "Predictive Modeling: Training and Tuning XGBoost"
},
{
"code": null,
"e": 711,
"s": 648,
"text": "Stacking Models: Combining XGBoost with Enet, Ridge, and Lasso"
},
{
"code": null,
"e": 1134,
"s": 711,
"text": "Open up a Jupyter Notebook, download the data, and follow along by implementing the following strategies yourself. I’ve included a few ‘exercises’ to get you going. I’m hiding the full code to force you to focus on the thought process. Additionally, by typing the code out yourself, you will gain experience that will eventually lead to fluency. However, if you need help along the way, you can find my full notebook here."
},
{
"code": null,
"e": 1316,
"s": 1134,
"text": "If you already read my article “A Beginner’s Look at Kaggle”, you know what’s coming: Let’s get our hands dirty with EDA. It’s going to be the sole focus of this part of the series."
},
{
"code": null,
"e": 1680,
"s": 1316,
"text": "This first section will focus primarily on basic plotting and missing value imputation. My goal is to outline a process for building an intuition as to what variables are at play, and which have the greatest impact on sale price. I also want to evaluate relationships between variables because it will give insight on how we might intelligently fill missing data."
},
{
"code": null,
"e": 1758,
"s": 1680,
"text": "The focus of our data exploration throughout the 4 part series is as follows:"
},
{
"code": null,
"e": 2074,
"s": 1758,
"text": "Visually Representing Data — Graphing and plotting our data can provide human insight into the real-world implications of our data. We have 79 variables at play, so it’s a great way to get a feel for what’s going on. All visualizations should be taken with a grain of salt, however. They don’t tell the whole story."
},
{
"code": null,
"e": 2248,
"s": 2074,
"text": "Finding and Dealing with Missing Data — In this phase, we will analyze what variables have missing values, why they are missing, and how we might deal with the missing data."
},
{
"code": null,
"e": 2377,
"s": 2248,
"text": "Feature Engineering — Can we find and define underlying patterns in the data that help us better describe and solve our problem?"
},
{
"code": null,
"e": 2493,
"s": 2377,
"text": "Strength of association. Provided that a variable is related to Sale Price at all, how strong is that relationship?"
},
{
"code": null,
"e": 2881,
"s": 2493,
"text": "ANOVA F-Test of categorical variables against sale price. Unlike continuous variables, we can not necessarily determine the traditional correlation metric between categories and continuous data. Through analysis of variance or ANOVA, we can gain some insight into whether there is a significant impact of a categorical variable such as neighborhood on the continuous variable sale price."
},
{
"code": null,
"e": 3177,
"s": 2881,
"text": "*****************************************************************Exercise 1: Sign up for a Kaggle account and download the data we will be using! I keep my data in a folder called data located in the same directory as my notebook.*****************************************************************"
},
{
"code": null,
"e": 3337,
"s": 3177,
"text": "import pandas as pdtrain_df = pd.read_csv('data/train.csv', index_col='Id')test_df = pd.read_csv('data/test.csv', index_col='Id')train_df.describe().T.head(10)"
},
{
"code": null,
"e": 3510,
"s": 3337,
"text": "To begin getting a feel for our data, we will plot our target variable distribution along with a couple of different transformations. We’ll do this for a couple of reasons:"
},
{
"code": null,
"e": 4079,
"s": 3510,
"text": "We want to understand our data, and looking at it visually helps us build intuition of the underlying factors that affect an outcome. It gets the wheels turning in our mind, and hopefully spurs questions that might lead to valuable insights.Transforming the distributions of our variables is common industry practice. Transformation is not always necessary or helpful. The mathematical theory behind the effectiveness of data transformation goes deep and is often debated (especially in the realm of deep learning). It suffices to say “it depends” and then experiment!"
},
{
"code": null,
"e": 4321,
"s": 4079,
"text": "We want to understand our data, and looking at it visually helps us build intuition of the underlying factors that affect an outcome. It gets the wheels turning in our mind, and hopefully spurs questions that might lead to valuable insights."
},
{
"code": null,
"e": 4649,
"s": 4321,
"text": "Transforming the distributions of our variables is common industry practice. Transformation is not always necessary or helpful. The mathematical theory behind the effectiveness of data transformation goes deep and is often debated (especially in the realm of deep learning). It suffices to say “it depends” and then experiment!"
},
{
"code": null,
"e": 4936,
"s": 4649,
"text": "Before transformation, our sale price data is right-skewed, meaning that the mean is biased towards a higher price than the median. Applying a Yeo Johnson transformation via sklearn.preprocessing.PowerTransformer() we get a pretty good approximation of the standard normal distribution:"
},
{
"code": null,
"e": 5209,
"s": 4936,
"text": "import sklearn.preprocessing as preimport seaborn as snsimport matplotlib.pyplot as pltpt = pre.PowerTransformer()ptd = pt.fit_transform(train_df.SalePrice.to_numpy().reshape(-1,1))plt.title(f'Yeo Johnson, Skew: {stats.skew(ptd.squeeze()):.3f}')sns.distplot(ptd, kde=True)"
},
{
"code": null,
"e": 5314,
"s": 5209,
"text": "I also checked out using a log transformation, but we don’t get quite as close to a normal distribution:"
},
{
"code": null,
"e": 5644,
"s": 5314,
"text": "These transformations alter the meaning of the data (notice the lack of the ‘SalePrice’ label on the horizontal axis). The main purpose of transforming the target variable is in hopes of assisting the training of a machine learning algorithm. Again, this requires experimentation and won’t be covered until Part 3 of this series."
},
{
"code": null,
"e": 5787,
"s": 5644,
"text": "As our second warm-up exercise, let’s check our intuition that it’s not just quantity but the quality that counts toward the final sale price:"
},
{
"code": null,
"e": 6028,
"s": 5787,
"text": "fig, axes = plt.subplots(2,2, figsize=(12,12))sns.scatterplot( x='GrLivArea', y='SalePrice', hue='OverallQual', data=train_df, ax=axes[0,0])...plt.tight_layout()# Try reproducing the plot below using the above code as a hint."
},
{
"code": null,
"e": 6395,
"s": 6028,
"text": "In the first column, we compare the sale price to the above-ground living (aka GrLivArea) area and the overall quality of home build materials. What we see is that the sale price is graduated well by both living-area and by quality. This is evident in the strong linear trend in the scatterplot, the even graduation of hue, as well as the boxplot of overall quality."
},
{
"code": null,
"e": 6736,
"s": 6395,
"text": "Somewhat surprisingly, we see that the variable describing the overall condition, OverallCond, seems to have little effect on sale price. The hue of the data points in the second scatterplot is random, and the boxplot is unordered. This is counter-intuitive, and we can dig into whether or not what we are seeing makes sense a little later."
},
{
"code": null,
"e": 6934,
"s": 6736,
"text": "Also, notice the two outliers in the data. There are two homes seen in the scatterplots that have quite large living areas, yet somehow sold for very low prices relative to others of the same size."
},
{
"code": null,
"e": 7259,
"s": 6934,
"text": "*****************************************************************Exercise 2: Investigate your intuitions about other variables and their relation to the sale price and one another by plotting them. Check out Seaborn’s great utility for plotting relationships.*****************************************************************"
},
{
"code": null,
"e": 7552,
"s": 7259,
"text": "Our next round of analysis will focus on our missing data. We want to know why the data is missing, and how we might be able to fill in the blanks. Lost data is lost information that might otherwise be useful to us. It is often worth attempting to fill in those blanks for better predictions."
},
{
"code": null,
"e": 7743,
"s": 7552,
"text": "First, we will address the gaps in our missing training data. I wrote a little function to visualize missing data in a data set. Look in my full notebook for a method called viz_missing(df):"
},
{
"code": null,
"e": 7964,
"s": 7743,
"text": "The barplot shows a lot of missing data. This data shouldn’t be ignored if we wish to get really good results. This part of the process is tedious but necessary. I encourage you to focus on the following thought process:"
},
{
"code": null,
"e": 8331,
"s": 7964,
"text": "Choose a variable with missing data you wish to fill.See if there is another variable, related to the one you are investigating.Determine if the missing data can be accounted for by the related variable.If you cannot determine the missing information by using steps 2 & 3, consider using mean, median, or mode. Be aware that this can be dangerous for small datasets."
},
{
"code": null,
"e": 8385,
"s": 8331,
"text": "Choose a variable with missing data you wish to fill."
},
{
"code": null,
"e": 8461,
"s": 8385,
"text": "See if there is another variable, related to the one you are investigating."
},
{
"code": null,
"e": 8537,
"s": 8461,
"text": "Determine if the missing data can be accounted for by the related variable."
},
{
"code": null,
"e": 8701,
"s": 8537,
"text": "If you cannot determine the missing information by using steps 2 & 3, consider using mean, median, or mode. Be aware that this can be dangerous for small datasets."
},
{
"code": null,
"e": 8831,
"s": 8701,
"text": "The variable with the greatest amount of missing data in the chart above is PoolQC which stands for ‘Pool Quality and Condition’."
},
{
"code": null,
"e": 9052,
"s": 8831,
"text": "After looking at our data dictionary, we should notice that there is only one other variable that describes a home’s pool. That variable is PoolArea. Take note that there is no missing data associated with that variable."
},
{
"code": null,
"e": 9347,
"s": 9052,
"text": "My intuition is that all of the homes that have PoolArea = 0 may be associated with homes that are missing PoolQC information. In other words, those homes don’t have pools, and that is why they are missing the pool quality variable. We can check that intuition with just a couple lines of code:"
},
{
"code": null,
"e": 9611,
"s": 9347,
"text": "# Get number of homes with missing PoolQC that also have 0 PoolArea.np = train_df[train_df.PoolQc.isna() & (train_df.PoolArea == 0)]count = np.shape[0]# Get total number of missing PoolQC entriesmissing = train_df.PoolQC.isna().sum()count, missing>>> (1452, 1452)"
},
{
"code": null,
"e": 9790,
"s": 9611,
"text": "So we see that for all 1452 homes missing PoolQC entries, the PoolArea of that home is 0. This proves our intuition correct. We can fill in the blanks with one more line of code:"
},
{
"code": null,
"e": 9833,
"s": 9790,
"text": "train_df.PoolQC.fillna(\"NA\", inplace=True)"
},
{
"code": null,
"e": 10123,
"s": 9833,
"text": "LotFrontage, according to the data dictionary, is the measure of the number of feet of road that is connected to the property. This time we don’t have any additional variables that will tell us why LotFrontage is missing. This means we will have to approach filling the blanks differently."
},
{
"code": null,
"e": 10451,
"s": 10123,
"text": "We may reasonably assume that almost every piece of property touches at least a small part of some road or alley. This may not be universally true, but is probably the rule rather than the exception. We will use this intuition to fill any missing LotFrontage with the mean or median of all homes for which we do have this data:"
},
{
"code": null,
"e": 10524,
"s": 10451,
"text": "train_df.LotFrontage.fillna(train_df.LotFrontage.median(), inplace=True)"
},
{
"code": null,
"e": 10621,
"s": 10524,
"text": "I chose to fill the missing entries with the median, as it will be more robust against outliers."
},
{
"code": null,
"e": 10901,
"s": 10621,
"text": "*****************************************************************Exercise 3: Perform this same investigation on all the missing data in both the test and training sets. It should take you a while. A lot is missing!*****************************************************************"
},
{
"code": null,
"e": 11078,
"s": 10901,
"text": "I’m going to leave off here until part 2 of the series. Completing exercises 1–3 should take you quite some time and are encouraged to code up these exercises before moving on."
}
] |
Bash Script - Write Hello World Program - GeeksforGeeks | 08 Dec, 2021
In this article, we are going to see how to write “hello world” program in Bash script.
The bash script is a text file that contains a set of instructions ( i.e. codes or commands ) that can be executed in the terminal. In any programming language, the first program that we learn to write is ” Hello World “.
We can create an empty file using the following commands:
$ touch HelloWorld.sh
Where:
touch : It is used to create an empty file.
HelloWorld.sh : HelloWorld is file with .sh extension of unix shell executable file.
Here we will open our created file, using the following commands:
$ nano HelloWorld.sh
Where:
nano : It is used to open files in a text editor ( i.e. GNU nano )
The editor is open, write the following code in a text editor:
#!/bin/sh
# This is bash program to display Hello World
echo " Hello World "
Where:
#! : It is known as shebang.
/bin/sh: It is the executable path of the system shell.
# : It is used to write comments.
echo : It is used to display text on the screen.
$ chmod +x HelloWorld.sh
Where:
chmod +x : It is used to make file executable.
$ ./Helloworld.sh
Output:
Hello World
Bash-Script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples | [
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 24103,
"s": 24015,
"text": "In this article, we are going to see how to write “hello world” program in Bash script."
},
{
"code": null,
"e": 24327,
"s": 24103,
"text": "The bash script is a text file that contains a set of instructions ( i.e. codes or commands ) that can be executed in the terminal. In any programming language, the first program that we learn to write is ” Hello World “. "
},
{
"code": null,
"e": 24385,
"s": 24327,
"text": "We can create an empty file using the following commands:"
},
{
"code": null,
"e": 24407,
"s": 24385,
"text": "$ touch HelloWorld.sh"
},
{
"code": null,
"e": 24414,
"s": 24407,
"text": "Where:"
},
{
"code": null,
"e": 24458,
"s": 24414,
"text": "touch : It is used to create an empty file."
},
{
"code": null,
"e": 24543,
"s": 24458,
"text": "HelloWorld.sh : HelloWorld is file with .sh extension of unix shell executable file."
},
{
"code": null,
"e": 24610,
"s": 24543,
"text": "Here we will open our created file, using the following commands: "
},
{
"code": null,
"e": 24631,
"s": 24610,
"text": "$ nano HelloWorld.sh"
},
{
"code": null,
"e": 24638,
"s": 24631,
"text": "Where:"
},
{
"code": null,
"e": 24705,
"s": 24638,
"text": "nano : It is used to open files in a text editor ( i.e. GNU nano )"
},
{
"code": null,
"e": 24768,
"s": 24705,
"text": "The editor is open, write the following code in a text editor:"
},
{
"code": null,
"e": 24845,
"s": 24768,
"text": "#!/bin/sh\n# This is bash program to display Hello World\necho \" Hello World \""
},
{
"code": null,
"e": 24852,
"s": 24845,
"text": "Where:"
},
{
"code": null,
"e": 24881,
"s": 24852,
"text": "#! : It is known as shebang."
},
{
"code": null,
"e": 24937,
"s": 24881,
"text": "/bin/sh: It is the executable path of the system shell."
},
{
"code": null,
"e": 24971,
"s": 24937,
"text": "# : It is used to write comments."
},
{
"code": null,
"e": 25020,
"s": 24971,
"text": "echo : It is used to display text on the screen."
},
{
"code": null,
"e": 25045,
"s": 25020,
"text": "$ chmod +x HelloWorld.sh"
},
{
"code": null,
"e": 25052,
"s": 25045,
"text": "Where:"
},
{
"code": null,
"e": 25099,
"s": 25052,
"text": "chmod +x : It is used to make file executable."
},
{
"code": null,
"e": 25119,
"s": 25099,
"text": "$ ./Helloworld.sh "
},
{
"code": null,
"e": 25127,
"s": 25119,
"text": "Output:"
},
{
"code": null,
"e": 25139,
"s": 25127,
"text": "Hello World"
},
{
"code": null,
"e": 25151,
"s": 25139,
"text": "Bash-Script"
},
{
"code": null,
"e": 25158,
"s": 25151,
"text": "Picked"
},
{
"code": null,
"e": 25169,
"s": 25158,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25267,
"s": 25169,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25276,
"s": 25267,
"text": "Comments"
},
{
"code": null,
"e": 25289,
"s": 25276,
"text": "Old Comments"
},
{
"code": null,
"e": 25324,
"s": 25289,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 25361,
"s": 25324,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 25395,
"s": 25361,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 25421,
"s": 25395,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 25447,
"s": 25421,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 25484,
"s": 25447,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 25524,
"s": 25484,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 25553,
"s": 25524,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 25595,
"s": 25553,
"text": "Named Pipe or FIFO with example C program"
}
] |
Jackson Annotations - @JsonEnumDefaultValue | @JsonEnumDefaultValue is used to deserialize an unknown enum value using a default value.
import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]) throws ParseException{
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
String jsonString = "\"abc\"";
try {
LETTERS value = mapper.readValue(jsonString, LETTERS.class);
System.out.println(value);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
enum LETTERS {
A, B, @JsonEnumDefaultValue UNKNOWN
}
UNKNOWN
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2565,
"s": 2475,
"text": "@JsonEnumDefaultValue is used to deserialize an unknown enum value using a default value."
},
{
"code": null,
"e": 3347,
"s": 2565,
"text": "import java.io.IOException; \nimport java.text.ParseException; \n\nimport com.fasterxml.jackson.annotation.JsonEnumDefaultValue; \nimport com.fasterxml.jackson.databind.DeserializationFeature; \nimport com.fasterxml.jackson.databind.ObjectMapper; \n\npublic class JacksonTester {\n public static void main(String args[]) throws ParseException{\n ObjectMapper mapper = new ObjectMapper();\n mapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);\n String jsonString = \"\\\"abc\\\"\"; \n try {\n LETTERS value = mapper.readValue(jsonString, LETTERS.class); \n System.out.println(value); \n }\n catch (IOException e) { \n e.printStackTrace(); \n } \n } \n}\nenum LETTERS {\n A, B, @JsonEnumDefaultValue UNKNOWN \n} "
},
{
"code": null,
"e": 3357,
"s": 3347,
"text": "UNKNOWN \n"
},
{
"code": null,
"e": 3364,
"s": 3357,
"text": " Print"
},
{
"code": null,
"e": 3375,
"s": 3364,
"text": " Add Notes"
}
] |
Android - UI Design | In this chapter we will look at the different UI components of android screen. This chapter also covers the tips to make a better UI design and also explains how to design a UI.
A typical user interface of an android application consists of action bar and the application content area.
Main Action Bar
View Control
Content Area
Split Action Bar
These components have also been shown in the image below −
The basic unit of android application is the activity. A UI is defined in an xml file. During compilation, each element in the XML is compiled into equivalent Android GUI class with attributes represented by methods.
An activity is consist of views. A view is just a widget that appears on the screen. It could be button e.t.c. One or more views can be grouped together into one GroupView. Example of ViewGroup includes layouts.
There are many types of layout. Some of which are listed below −
Linear Layout
Absolute Layout
Table Layout
Frame Layout
Relative Layout
Linear layout is further divided into horizontal and vertical layout. It means it can arrange views in a single column or in a single row. Here is the code of linear layout(vertical) that includes a text view.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>
The AbsoluteLayout enables you to specify the exact location of its children. It can be declared like this.
<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
</AbsoluteLayout>
The TableLayout groups views into rows and columns. It can be declared like this.
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >
<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>
<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>
</TableLayout>
The RelativeLayout enables you to specify how child views are positioned relative to each other.It can be declared like this.
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>
The FrameLayout is a placeholder on screen that you can use to display a single view. It can be declared like this.
<?xml version=”1.0” encoding=”utf-8”?>
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >
<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</FrameLayout>
Apart form these attributes, there are other attributes that are common in all views and ViewGroups. They are listed below −
layout_width
Specifies the width of the View or ViewGroup
layout_height
Specifies the height of the View or ViewGroup
layout_marginTop
Specifies extra space on the top side of the View or ViewGroup
layout_marginBottom
Specifies extra space on the bottom side of the View or ViewGroup
layout_marginLeft
Specifies extra space on the left side of the View or ViewGroup
layout_marginRight
Specifies extra space on the right side of the View or ViewGroup
layout_gravity
Specifies how child Views are positioned
layout_weight
Specifies how much of the extra space in the layout should be allocated to the View
When you are specifying the size of an element on an Android UI, you should remember the following units of measurement.
dp
Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen.
sp
Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes
pt
Point. A point is defined to be 1/72 of an inch, based on the physical screen size.
px
Pixel. Corresponds to actual pixels on the screen
Low density (ldpi)
120 dpi
Medium density (mdpi)
160 dpi
High density (hdpi)
240 dpi
Extra High density (xhdpi)
320 dpi
Here are some of the guidelines for creating efficient layouts.
Avoid unnecessary nesting
Avoid using too many Views
Avoid deep nesting
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
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
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3785,
"s": 3607,
"text": "In this chapter we will look at the different UI components of android screen. This chapter also covers the tips to make a better UI design and also explains how to design a UI."
},
{
"code": null,
"e": 3894,
"s": 3785,
"text": "A typical user interface of an android application consists of action bar and the application content area. "
},
{
"code": null,
"e": 3910,
"s": 3894,
"text": "Main Action Bar"
},
{
"code": null,
"e": 3923,
"s": 3910,
"text": "View Control"
},
{
"code": null,
"e": 3936,
"s": 3923,
"text": "Content Area"
},
{
"code": null,
"e": 3953,
"s": 3936,
"text": "Split Action Bar"
},
{
"code": null,
"e": 4012,
"s": 3953,
"text": "These components have also been shown in the image below −"
},
{
"code": null,
"e": 4229,
"s": 4012,
"text": "The basic unit of android application is the activity. A UI is defined in an xml file. During compilation, each element in the XML is compiled into equivalent Android GUI class with attributes represented by methods."
},
{
"code": null,
"e": 4441,
"s": 4229,
"text": "An activity is consist of views. A view is just a widget that appears on the screen. It could be button e.t.c. One or more views can be grouped together into one GroupView. Example of ViewGroup includes layouts."
},
{
"code": null,
"e": 4506,
"s": 4441,
"text": "There are many types of layout. Some of which are listed below −"
},
{
"code": null,
"e": 4520,
"s": 4506,
"text": "Linear Layout"
},
{
"code": null,
"e": 4536,
"s": 4520,
"text": "Absolute Layout"
},
{
"code": null,
"e": 4549,
"s": 4536,
"text": "Table Layout"
},
{
"code": null,
"e": 4562,
"s": 4549,
"text": "Frame Layout"
},
{
"code": null,
"e": 4578,
"s": 4562,
"text": "Relative Layout"
},
{
"code": null,
"e": 4788,
"s": 4578,
"text": "Linear layout is further divided into horizontal and vertical layout. It means it can arrange views in a single column or in a single row. Here is the code of linear layout(vertical) that includes a text view."
},
{
"code": null,
"e": 5168,
"s": 4788,
"text": "<?xml version=”1.0” encoding=”utf-8”?>\n<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”\n android:layout_width=”fill_parent”\n android:layout_height=”fill_parent”\n android:orientation=”vertical” >\n \n <TextView\n android:layout_width=”fill_parent”\n android:layout_height=”wrap_content”\n android:text=”@string/hello” />\n</LinearLayout>"
},
{
"code": null,
"e": 5276,
"s": 5168,
"text": "The AbsoluteLayout enables you to specify the exact location of its children. It can be declared like this."
},
{
"code": null,
"e": 5637,
"s": 5276,
"text": "<AbsoluteLayout\n android:layout_width=”fill_parent”\n android:layout_height=”fill_parent”\n xmlns:android=”http://schemas.android.com/apk/res/android” >\n \n <Button\n android:layout_width=”188dp”\n android:layout_height=”wrap_content”\n android:text=”Button”\n android:layout_x=”126px”\n android:layout_y=”361px” />\n</AbsoluteLayout>"
},
{
"code": null,
"e": 5719,
"s": 5637,
"text": "The TableLayout groups views into rows and columns. It can be declared like this."
},
{
"code": null,
"e": 6116,
"s": 5719,
"text": "<TableLayout\n xmlns:android=”http://schemas.android.com/apk/res/android”\n android:layout_height=”fill_parent”\n android:layout_width=”fill_parent” >\n \n <TableRow>\n <TextView\n android:text=”User Name:”\n android:width =”120dp”\n />\n \n <EditText\n android:id=”@+id/txtUserName”\n android:width=”200dp” />\n </TableRow>\n \n</TableLayout>"
},
{
"code": null,
"e": 6242,
"s": 6116,
"text": "The RelativeLayout enables you to specify how child views are positioned relative to each other.It can be declared like this."
},
{
"code": null,
"e": 6446,
"s": 6242,
"text": "<RelativeLayout\n android:id=”@+id/RLayout”\n android:layout_width=”fill_parent”\n android:layout_height=”fill_parent”\n xmlns:android=”http://schemas.android.com/apk/res/android” >\n</RelativeLayout>"
},
{
"code": null,
"e": 6562,
"s": 6446,
"text": "The FrameLayout is a placeholder on screen that you can use to display a single view. It can be declared like this."
},
{
"code": null,
"e": 6986,
"s": 6562,
"text": "<?xml version=”1.0” encoding=”utf-8”?>\n<FrameLayout\n android:layout_width=”wrap_content”\n android:layout_height=”wrap_content”\n android:layout_alignLeft=”@+id/lblComments”\n android:layout_below=”@+id/lblComments”\n android:layout_centerHorizontal=”true” >\n \n <ImageView\n android:src = “@drawable/droid”\n android:layout_width=”wrap_content”\n android:layout_height=”wrap_content” />\n</FrameLayout>"
},
{
"code": null,
"e": 7111,
"s": 6986,
"text": "Apart form these attributes, there are other attributes that are common in all views and ViewGroups. They are listed below −"
},
{
"code": null,
"e": 7124,
"s": 7111,
"text": "layout_width"
},
{
"code": null,
"e": 7169,
"s": 7124,
"text": "Specifies the width of the View or ViewGroup"
},
{
"code": null,
"e": 7183,
"s": 7169,
"text": "layout_height"
},
{
"code": null,
"e": 7229,
"s": 7183,
"text": "Specifies the height of the View or ViewGroup"
},
{
"code": null,
"e": 7246,
"s": 7229,
"text": "layout_marginTop"
},
{
"code": null,
"e": 7309,
"s": 7246,
"text": "Specifies extra space on the top side of the View or ViewGroup"
},
{
"code": null,
"e": 7329,
"s": 7309,
"text": "layout_marginBottom"
},
{
"code": null,
"e": 7395,
"s": 7329,
"text": "Specifies extra space on the bottom side of the View or ViewGroup"
},
{
"code": null,
"e": 7413,
"s": 7395,
"text": "layout_marginLeft"
},
{
"code": null,
"e": 7477,
"s": 7413,
"text": "Specifies extra space on the left side of the View or ViewGroup"
},
{
"code": null,
"e": 7496,
"s": 7477,
"text": "layout_marginRight"
},
{
"code": null,
"e": 7561,
"s": 7496,
"text": "Specifies extra space on the right side of the View or ViewGroup"
},
{
"code": null,
"e": 7576,
"s": 7561,
"text": "layout_gravity"
},
{
"code": null,
"e": 7617,
"s": 7576,
"text": "Specifies how child Views are positioned"
},
{
"code": null,
"e": 7631,
"s": 7617,
"text": "layout_weight"
},
{
"code": null,
"e": 7715,
"s": 7631,
"text": "Specifies how much of the extra space in the layout should be allocated to the View"
},
{
"code": null,
"e": 7836,
"s": 7715,
"text": "When you are specifying the size of an element on an Android UI, you should remember the following units of measurement."
},
{
"code": null,
"e": 7839,
"s": 7836,
"text": "dp"
},
{
"code": null,
"e": 7919,
"s": 7839,
"text": "Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen."
},
{
"code": null,
"e": 7922,
"s": 7919,
"text": "sp"
},
{
"code": null,
"e": 8014,
"s": 7922,
"text": "Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes"
},
{
"code": null,
"e": 8017,
"s": 8014,
"text": "pt"
},
{
"code": null,
"e": 8101,
"s": 8017,
"text": "Point. A point is defined to be 1/72 of an inch, based on the physical screen size."
},
{
"code": null,
"e": 8104,
"s": 8101,
"text": "px"
},
{
"code": null,
"e": 8154,
"s": 8104,
"text": "Pixel. Corresponds to actual pixels on the screen"
},
{
"code": null,
"e": 8173,
"s": 8154,
"text": "Low density (ldpi)"
},
{
"code": null,
"e": 8181,
"s": 8173,
"text": "120 dpi"
},
{
"code": null,
"e": 8203,
"s": 8181,
"text": "Medium density (mdpi)"
},
{
"code": null,
"e": 8211,
"s": 8203,
"text": "160 dpi"
},
{
"code": null,
"e": 8231,
"s": 8211,
"text": "High density (hdpi)"
},
{
"code": null,
"e": 8239,
"s": 8231,
"text": "240 dpi"
},
{
"code": null,
"e": 8266,
"s": 8239,
"text": "Extra High density (xhdpi)"
},
{
"code": null,
"e": 8274,
"s": 8266,
"text": "320 dpi"
},
{
"code": null,
"e": 8338,
"s": 8274,
"text": "Here are some of the guidelines for creating efficient layouts."
},
{
"code": null,
"e": 8364,
"s": 8338,
"text": "Avoid unnecessary nesting"
},
{
"code": null,
"e": 8391,
"s": 8364,
"text": "Avoid using too many Views"
},
{
"code": null,
"e": 8410,
"s": 8391,
"text": "Avoid deep nesting"
},
{
"code": null,
"e": 8445,
"s": 8410,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8457,
"s": 8445,
"text": " Aditya Dua"
},
{
"code": null,
"e": 8492,
"s": 8457,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8506,
"s": 8492,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 8538,
"s": 8506,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8555,
"s": 8538,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8590,
"s": 8555,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8607,
"s": 8590,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8642,
"s": 8607,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8659,
"s": 8642,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8692,
"s": 8659,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8709,
"s": 8692,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8716,
"s": 8709,
"text": " Print"
},
{
"code": null,
"e": 8727,
"s": 8716,
"text": " Add Notes"
}
] |
Palindrome numbers in JavaScript | We are required to write a JavaScript function that takes in a number and determines whether or not it is a palindrome number.
Palindrome numbers − A palindrome number is that number which reads the same from both left and right sides.
For example −
343 is a palindrome number
343 is a palindrome number
6789876 is a palindrome number
6789876 is a palindrome number
456764 is not a palindrome number
456764 is not a palindrome number
The code for this will be −
const num1 = 343;
const num2 = 6789876;
const num3 = 456764;
const isPalindrome = num => {
let length = Math.floor(Math.log(num) / Math.log(10) +1);
while(length > 0) {
let last = Math.abs(num − Math.floor(num/10)*10);
let first = Math.floor(num / Math.pow(10, length −1));
if(first != last){
return false;
};
num −= Math.pow(10, length−1) * first ;
num = Math.floor(num/10);
length −= 2;
};
return true;
};
console.log(isPalindrome(num1));
console.log(isPalindrome(num2));
console.log(isPalindrome(num3));
And the output in the console will be −
true
true
false | [
{
"code": null,
"e": 1189,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a number and determines whether or not it is a palindrome number."
},
{
"code": null,
"e": 1298,
"s": 1189,
"text": "Palindrome numbers − A palindrome number is that number which reads the same from both left and right sides."
},
{
"code": null,
"e": 1312,
"s": 1298,
"text": "For example −"
},
{
"code": null,
"e": 1339,
"s": 1312,
"text": "343 is a palindrome number"
},
{
"code": null,
"e": 1366,
"s": 1339,
"text": "343 is a palindrome number"
},
{
"code": null,
"e": 1397,
"s": 1366,
"text": "6789876 is a palindrome number"
},
{
"code": null,
"e": 1428,
"s": 1397,
"text": "6789876 is a palindrome number"
},
{
"code": null,
"e": 1462,
"s": 1428,
"text": "456764 is not a palindrome number"
},
{
"code": null,
"e": 1496,
"s": 1462,
"text": "456764 is not a palindrome number"
},
{
"code": null,
"e": 1524,
"s": 1496,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2094,
"s": 1524,
"text": "const num1 = 343;\nconst num2 = 6789876;\nconst num3 = 456764;\nconst isPalindrome = num => {\n let length = Math.floor(Math.log(num) / Math.log(10) +1);\n while(length > 0) {\n let last = Math.abs(num − Math.floor(num/10)*10);\n let first = Math.floor(num / Math.pow(10, length −1));\n if(first != last){\n return false;\n };\n num −= Math.pow(10, length−1) * first ;\n num = Math.floor(num/10);\n length −= 2;\n };\n return true;\n};\nconsole.log(isPalindrome(num1));\nconsole.log(isPalindrome(num2));\nconsole.log(isPalindrome(num3));"
},
{
"code": null,
"e": 2134,
"s": 2094,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2150,
"s": 2134,
"text": "true\ntrue\nfalse"
}
] |
Count of substrings containing exactly K distinct vowels - GeeksforGeeks | 29 Dec, 2021
Given string str of size N containing both uppercase and lowercase letters, and an integer K. The task is to find the count of substrings containing exactly K distinct vowels.
Examples:
Input: str = “aeiou”, K = 2Output: 4Explanation: The substrings having two distinct vowels are “ae”, “ei”, “io” and “ou”.
Input: str = “TrueGoik”, K = 3Output: 5Explanation: The substrings are “TrueGo”, “rueGo”, “ueGo”, “eGoi” and “eGoik”.
Approach: The problem can be solved by generating all the substrings. From the generated substrings count the ones having K distinct vowels. Follow the steps mentioned below to implement the approach:
First generate all substrings starting from each index i in range [0, N]
Then for each substring, follow the steps:Keep a hash array to store the occurrences of unique vowels.Check if a new character in the substring is a vowel or not.If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels foundNow for each substring, if the distinct count of vowels is K, increment the final count.
Keep a hash array to store the occurrences of unique vowels.
Check if a new character in the substring is a vowel or not.
If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels found
Now for each substring, if the distinct count of vowels is K, increment the final count.
If for any loop to find substrings starting from i, the count of distinct vowels exceeds K, or, the substring length has reached string length, break the loop and look for substrings starting from i+1.
When all the substrings have been considered, print the final count.
Below is implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to count number of substrings// with exactly k distinct vowels#include <bits/stdc++.h>using namespace std; #define MAX 128 // Function to check whether// a character is vowel or notbool isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} int getIndex(char ch){ return (ch - 'A' > 26 ? ch - 'a' : ch - 'A');} // Function to count number of substrings// with exactly k unique vowelsint countkDist(string str, int k){ int n = str.length(); // Initialize result int res = 0; // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' vector<int> cnt(26, 0); // Consider all substrings // between str[i..j] for (int j = i; j < n; j++) { // If this is a new vowels // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) dist_count++; // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k then increment result if (dist_count == k) res++; if (dist_count > k) break; } } return res;} // Driver codeint main(){ string str = "TrueGoik"; int K = 3; cout << countkDist(str, K) << endl; return 0;}
// Java program to count number of substrings// with exactly k distinct vowelsimport java.util.*;public class GFG{ // Function to check whether// a character is vowel or notstatic boolean isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} static int getIndex(char ch){ return (ch - 'A' > 26 ? ch - 'a' : ch - 'A');} // Function to count number of substrings// with exactly k unique vowelsstatic int countkDist(String str, int k){ int n = str.length(); // Initialize result int res = 0; // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' int cnt[] = new int[26]; for(int t = 0; t < 26; t++) { cnt[t] = 0; } // Consider all substrings // between str[i..j] for (int j = i; j < n; j++) { // If this is a new vowels // for this substring, // increment dist_count. if (isVowel(str.charAt(j)) && cnt[getIndex(str.charAt(j))] == 0) dist_count++; // Increment count of // current character cnt[getIndex(str.charAt(j))]++; // If distinct vowels count // becomes k then increment result if (dist_count == k) res++; if (dist_count > k) break; } } return res;} // Driver codepublic static void main(String args[]){ String str = "TrueGoik"; int K = 3; System.out.println(countkDist(str, K));}} // This code is contributed by Samim Hossain Mondal.
# Python code for the above approach # Function to check whether# a character is vowel or notdef isVowel(x): return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U') def getIndex(ch): return (ord(ch) - ord('a')) if (ord(ch) - ord('A')) > 26 else (ord(ch) - ord('A')) # Function to count number of substrings# with exactly k unique vowelsdef countkDist(str, k): n = len(str) # Initialize result res = 0 # Consider all substrings # beginning with str[i] for i in range(n): dist_count = 0 # To store count of characters # from 'a' to 'z' cnt = [0] * 26 # Consider all substrings # between str[i..j] for j in range(i, n): # If this is a new vowels # for this substring, # increment dist_count. if (isVowel(str[j]) and cnt[getIndex(str[j])] == 0): dist_count += 1 # Increment count of # current character cnt[getIndex(str[j])] += 1 # If distinct vowels count # becomes k then increment result if (dist_count == k): res += 1 if (dist_count > k): break return res # Driver codes = "TrueGoik"K = 3 print(countkDist(s, K)) # This code is contributed by Saurabh Jaiswal
// C# program to count number of substrings// with exactly k distinct vowelsusing System;class GFG{ // Function to check whether // a character is vowel or not static bool isVowel(char x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } static int getIndex(char ch) { return (ch - 'A' > 26 ? ch - 'a' : ch - 'A'); } // Function to count number of substrings // with exactly k unique vowels static int countkDist(string str, int k) { int n = str.Length; // Initialize result int res = 0; // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' int []cnt = new int[26]; for(int t = 0; t < 26; t++) { cnt[t] = 0; } // Consider all substrings // between str[i..j] for (int j = i; j < n; j++) { // If this is a new vowels // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) dist_count++; // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k then increment result if (dist_count == k) res++; if (dist_count > k) break; } } return res; } // Driver code public static void Main() { string str = "TrueGoik"; int K = 3; Console.Write(countkDist(str, K)); }} // This code is contributed by Samim Hossain Mondal.
<script> // JavaScript code for the above approach // Function to check whether // a character is vowel or not function isVowel(x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } function getIndex(ch) { return ((ch.charCodeAt(0) - 'A'.charCodeAt(0)) > 26 ? (ch.charCodeAt(0) - 'a'.charCodeAt(0)) : (ch.charCodeAt(0) - 'A'.charCodeAt(0))); } // Function to count number of substrings // with exactly k unique vowels function countkDist(str, k) { let n = str.length; // Initialize result let res = 0; // Consider all substrings // beginning with str[i] for (let i = 0; i < n; i++) { let dist_count = 0; // To store count of characters // from 'a' to 'z' let cnt = new Array(26).fill(0) // Consider all substrings // between str[i..j] for (let j = i; j < n; j++) { // If this is a new vowels // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) dist_count++; // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k then increment result if (dist_count == k) res++; if (dist_count > k) break; } } return res; } // Driver code let s = "TrueGoik"; let K = 3 document.write(countkDist(s, K)); // This code is contributed by Potta Lokesh </script>
5
Time Complexity: O(N2)Auxiliary Space: O(N2)
lokeshpotta20
samim2000
_saurabh_jaiswal
Algo-Geek 2021
substring
Algo Geek
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Maximize groups to be formed such that product of size of group with its minimum element is at least K
Maximize partitions that if sorted individually makes the whole Array sorted
Generate string after adding spaces at specific positions in a given String
Count Subarrays with strictly decreasing consecutive elements
Sort given Array in descending order according to highest power of prime factors
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 25374,
"s": 25346,
"text": "\n29 Dec, 2021"
},
{
"code": null,
"e": 25550,
"s": 25374,
"text": "Given string str of size N containing both uppercase and lowercase letters, and an integer K. The task is to find the count of substrings containing exactly K distinct vowels."
},
{
"code": null,
"e": 25560,
"s": 25550,
"text": "Examples:"
},
{
"code": null,
"e": 25682,
"s": 25560,
"text": "Input: str = “aeiou”, K = 2Output: 4Explanation: The substrings having two distinct vowels are “ae”, “ei”, “io” and “ou”."
},
{
"code": null,
"e": 25800,
"s": 25682,
"text": "Input: str = “TrueGoik”, K = 3Output: 5Explanation: The substrings are “TrueGo”, “rueGo”, “ueGo”, “eGoi” and “eGoik”."
},
{
"code": null,
"e": 26001,
"s": 25800,
"text": "Approach: The problem can be solved by generating all the substrings. From the generated substrings count the ones having K distinct vowels. Follow the steps mentioned below to implement the approach:"
},
{
"code": null,
"e": 26074,
"s": 26001,
"text": "First generate all substrings starting from each index i in range [0, N]"
},
{
"code": null,
"e": 26421,
"s": 26074,
"text": "Then for each substring, follow the steps:Keep a hash array to store the occurrences of unique vowels.Check if a new character in the substring is a vowel or not.If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels foundNow for each substring, if the distinct count of vowels is K, increment the final count."
},
{
"code": null,
"e": 26482,
"s": 26421,
"text": "Keep a hash array to store the occurrences of unique vowels."
},
{
"code": null,
"e": 26543,
"s": 26482,
"text": "Check if a new character in the substring is a vowel or not."
},
{
"code": null,
"e": 26640,
"s": 26543,
"text": "If it is a vowel, increment its occurrence in the hash and keep a count of distinct vowels found"
},
{
"code": null,
"e": 26729,
"s": 26640,
"text": "Now for each substring, if the distinct count of vowels is K, increment the final count."
},
{
"code": null,
"e": 26931,
"s": 26729,
"text": "If for any loop to find substrings starting from i, the count of distinct vowels exceeds K, or, the substring length has reached string length, break the loop and look for substrings starting from i+1."
},
{
"code": null,
"e": 27000,
"s": 26931,
"text": "When all the substrings have been considered, print the final count."
},
{
"code": null,
"e": 27047,
"s": 27000,
"text": "Below is implementation of the above approach."
},
{
"code": null,
"e": 27051,
"s": 27047,
"text": "C++"
},
{
"code": null,
"e": 27056,
"s": 27051,
"text": "Java"
},
{
"code": null,
"e": 27064,
"s": 27056,
"text": "Python3"
},
{
"code": null,
"e": 27067,
"s": 27064,
"text": "C#"
},
{
"code": null,
"e": 27078,
"s": 27067,
"text": "Javascript"
},
{
"code": "// C++ program to count number of substrings// with exactly k distinct vowels#include <bits/stdc++.h>using namespace std; #define MAX 128 // Function to check whether// a character is vowel or notbool isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} int getIndex(char ch){ return (ch - 'A' > 26 ? ch - 'a' : ch - 'A');} // Function to count number of substrings// with exactly k unique vowelsint countkDist(string str, int k){ int n = str.length(); // Initialize result int res = 0; // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' vector<int> cnt(26, 0); // Consider all substrings // between str[i..j] for (int j = i; j < n; j++) { // If this is a new vowels // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) dist_count++; // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k then increment result if (dist_count == k) res++; if (dist_count > k) break; } } return res;} // Driver codeint main(){ string str = \"TrueGoik\"; int K = 3; cout << countkDist(str, K) << endl; return 0;}",
"e": 28733,
"s": 27078,
"text": null
},
{
"code": "// Java program to count number of substrings// with exactly k distinct vowelsimport java.util.*;public class GFG{ // Function to check whether// a character is vowel or notstatic boolean isVowel(char x){ return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U');} static int getIndex(char ch){ return (ch - 'A' > 26 ? ch - 'a' : ch - 'A');} // Function to count number of substrings// with exactly k unique vowelsstatic int countkDist(String str, int k){ int n = str.length(); // Initialize result int res = 0; // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' int cnt[] = new int[26]; for(int t = 0; t < 26; t++) { cnt[t] = 0; } // Consider all substrings // between str[i..j] for (int j = i; j < n; j++) { // If this is a new vowels // for this substring, // increment dist_count. if (isVowel(str.charAt(j)) && cnt[getIndex(str.charAt(j))] == 0) dist_count++; // Increment count of // current character cnt[getIndex(str.charAt(j))]++; // If distinct vowels count // becomes k then increment result if (dist_count == k) res++; if (dist_count > k) break; } } return res;} // Driver codepublic static void main(String args[]){ String str = \"TrueGoik\"; int K = 3; System.out.println(countkDist(str, K));}} // This code is contributed by Samim Hossain Mondal.",
"e": 30563,
"s": 28733,
"text": null
},
{
"code": "# Python code for the above approach # Function to check whether# a character is vowel or notdef isVowel(x): return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U') def getIndex(ch): return (ord(ch) - ord('a')) if (ord(ch) - ord('A')) > 26 else (ord(ch) - ord('A')) # Function to count number of substrings# with exactly k unique vowelsdef countkDist(str, k): n = len(str) # Initialize result res = 0 # Consider all substrings # beginning with str[i] for i in range(n): dist_count = 0 # To store count of characters # from 'a' to 'z' cnt = [0] * 26 # Consider all substrings # between str[i..j] for j in range(i, n): # If this is a new vowels # for this substring, # increment dist_count. if (isVowel(str[j]) and cnt[getIndex(str[j])] == 0): dist_count += 1 # Increment count of # current character cnt[getIndex(str[j])] += 1 # If distinct vowels count # becomes k then increment result if (dist_count == k): res += 1 if (dist_count > k): break return res # Driver codes = \"TrueGoik\"K = 3 print(countkDist(s, K)) # This code is contributed by Saurabh Jaiswal",
"e": 31980,
"s": 30563,
"text": null
},
{
"code": "// C# program to count number of substrings// with exactly k distinct vowelsusing System;class GFG{ // Function to check whether // a character is vowel or not static bool isVowel(char x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } static int getIndex(char ch) { return (ch - 'A' > 26 ? ch - 'a' : ch - 'A'); } // Function to count number of substrings // with exactly k unique vowels static int countkDist(string str, int k) { int n = str.Length; // Initialize result int res = 0; // Consider all substrings // beginning with str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // To store count of characters // from 'a' to 'z' int []cnt = new int[26]; for(int t = 0; t < 26; t++) { cnt[t] = 0; } // Consider all substrings // between str[i..j] for (int j = i; j < n; j++) { // If this is a new vowels // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) dist_count++; // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k then increment result if (dist_count == k) res++; if (dist_count > k) break; } } return res; } // Driver code public static void Main() { string str = \"TrueGoik\"; int K = 3; Console.Write(countkDist(str, K)); }} // This code is contributed by Samim Hossain Mondal.",
"e": 33681,
"s": 31980,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to check whether // a character is vowel or not function isVowel(x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U'); } function getIndex(ch) { return ((ch.charCodeAt(0) - 'A'.charCodeAt(0)) > 26 ? (ch.charCodeAt(0) - 'a'.charCodeAt(0)) : (ch.charCodeAt(0) - 'A'.charCodeAt(0))); } // Function to count number of substrings // with exactly k unique vowels function countkDist(str, k) { let n = str.length; // Initialize result let res = 0; // Consider all substrings // beginning with str[i] for (let i = 0; i < n; i++) { let dist_count = 0; // To store count of characters // from 'a' to 'z' let cnt = new Array(26).fill(0) // Consider all substrings // between str[i..j] for (let j = i; j < n; j++) { // If this is a new vowels // for this substring, // increment dist_count. if (isVowel(str[j]) && cnt[getIndex(str[j])] == 0) dist_count++; // Increment count of // current character cnt[getIndex(str[j])]++; // If distinct vowels count // becomes k then increment result if (dist_count == k) res++; if (dist_count > k) break; } } return res; } // Driver code let s = \"TrueGoik\"; let K = 3 document.write(countkDist(s, K)); // This code is contributed by Potta Lokesh </script>",
"e": 35751,
"s": 33681,
"text": null
},
{
"code": null,
"e": 35756,
"s": 35754,
"text": "5"
},
{
"code": null,
"e": 35803,
"s": 35758,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 35819,
"s": 35805,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 35829,
"s": 35819,
"text": "samim2000"
},
{
"code": null,
"e": 35846,
"s": 35829,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 35861,
"s": 35846,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 35871,
"s": 35861,
"text": "substring"
},
{
"code": null,
"e": 35881,
"s": 35871,
"text": "Algo Geek"
},
{
"code": null,
"e": 35894,
"s": 35881,
"text": "Mathematical"
},
{
"code": null,
"e": 35902,
"s": 35894,
"text": "Strings"
},
{
"code": null,
"e": 35910,
"s": 35902,
"text": "Strings"
},
{
"code": null,
"e": 35923,
"s": 35910,
"text": "Mathematical"
},
{
"code": null,
"e": 36021,
"s": 35923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36030,
"s": 36021,
"text": "Comments"
},
{
"code": null,
"e": 36043,
"s": 36030,
"text": "Old Comments"
},
{
"code": null,
"e": 36146,
"s": 36043,
"text": "Maximize groups to be formed such that product of size of group with its minimum element is at least K"
},
{
"code": null,
"e": 36223,
"s": 36146,
"text": "Maximize partitions that if sorted individually makes the whole Array sorted"
},
{
"code": null,
"e": 36299,
"s": 36223,
"text": "Generate string after adding spaces at specific positions in a given String"
},
{
"code": null,
"e": 36361,
"s": 36299,
"text": "Count Subarrays with strictly decreasing consecutive elements"
},
{
"code": null,
"e": 36442,
"s": 36361,
"text": "Sort given Array in descending order according to highest power of prime factors"
},
{
"code": null,
"e": 36472,
"s": 36442,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36487,
"s": 36472,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36547,
"s": 36487,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36590,
"s": 36547,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Develop glue jobs locally using Docker containers | by Shubham Jain | Towards Data Science | With the increasing amount of data in the current world, the need for services handling big data is very demanding. When we think about big data, there are very few frameworks which are used by most of the data engineers. Apache Spark is one of them.
Apache Spark is a distributed processing engine which requires a large cluster to execute any kind of analytics or simply perform ETL on the dataset. To use Apache Spark, we need to set up large clusters of our own which are very expensive or we can leverage them on the cloud. Here, we will be discussing the services provided by AWS. So to process large dataset and to perform analytics on them using spark, AWS provides two major services
AWS EMR (Elastic Map Reduce)AWS Glue
AWS EMR (Elastic Map Reduce)
AWS Glue
AWS EMR provides us cluster to perform our processing and are very expensive, so we need to be careful to identify for how long we require clusters and how to optimize our jobs properly. We will not be covering EMR in this post as it is itself a very large topic to discuss.
AWS Glue is a fully managed ETL service provided by amazon web services for handling large amount of data. The best part of AWS Glue is it comes under the AWS serverless umbrella where we need not worry about managing all those clusters and the cost associated with it. In serverless paradigm, we pay for what we use, so if our job is using only 25 DPU for processing our data and it runs for 20 minutes then we end up paying only the cost for leveraging 25 DPU’s for 20 minutes and not a single penny extra.
AWS Glue is in utmost demand nowadays for creating python or scala based spark processing jobs. To develop jobs on AWS glue, we have three options. Let’s discuss them one by one.
Create Job Directly in glue editor and run the job:
Create Job Directly in glue editor and run the job:
If you are a spark developer and not so familiar with glue libraries and its diagram generation, avoid using this editor at all cost. This is for those who are very sure what they are writing and knew from their heart that their job will run in the first run itself. This is not at all recommended and can only be considered when we need to make a few changes in the existing job. Using the job editor directly is good when you are using glue libraries in your code as it generates the lineage diagram as you write the code. Before opting for this option I would recommend going through the glue libraries here.
2. Create a Glue Dev endpoint:
You can set up a glue dev endpoint and link it to either zeppelin notebooks or to your pycharm IDE or you can even connect local jupyter notebooks. This is a better option if you want to test your jobs while you are developing them. To setup Glue Dev endpoint you can follow official AWS documentation here. The only problem with this glue dev endpoint is its cost. You will be charged for the time it is running, so it basically spins up a EMR cluster with your desired capacity and glue libraries installed on the cluster. This is one of the best option if cost is not a problem with your development and can be considered.
3. Use AWS Glue libraries and run them on Docker container locally
This is by far the best option considering the development of the jobs and testing the jobs on relatively small datasets and once the job is ready running them using the glue job console itself. With this option, you get the flexibility of using glue libraries either on your machine or you can spin up EC2 instances according to your dataset size and launch the docker container on these EC2, as this will be a relatively cheaper option and the most suitable one to run your jobs.
To set up AWS glue locally, you can follow AWS documentation here. But this seems to be not working and we will be discussing it in detail. So I have created a Docker image and will explain what we are doing.
I am taking centos as base image then setting these env variables we will require this to download the libraries later on
ENV MAVEN=https://aws-glue-etl-artifacts.s3.amazonaws.com/glue-common/apache-maven-3.6.0-bin.tar.gzENV SPARK=https://aws-glue-etl-artifacts.s3.amazonaws.com/glue-1.0/spark-2.4.3-bin-hadoop2.8.tgzENV GLUE=https://github.com/awslabs/aws-glue-libs.git
Then we will create a directory glue and install required libraries like Java, Python, wget, tar and python packages and set our working directory to glue
RUN mkdir glueRUN yum install -y python3 java-1.8.0-openjdk java-1.8.0-openjdk-devel tar git wget zipRUN ln -s /usr/bin/python3 /usr/bin/pythonRUN ln -s /usr/bin/pip3 /usr/bin/pipRUN pip install pandasRUN pip install boto3RUN pip install pyntWORKDIR ./glue
Now in this directory will download maven, spark and glue libs and unzip them. Then we will be updating the path variable and adding SPARK_HOME, JAVA_HOME, MAVEN_HOME and GLUE_HOME variables to it.
#To get the latest aws librariesRUN git clone -b glue-1.0 $GLUE#To get latest spark versionRUN wget $SPARK#To install Maven for dependenciesRUN wget $MAVENRUN tar zxfv apache-maven-3.6.0-bin.tar.gzRUN tar zxfv spark-2.4.3-bin-hadoop2.8.tgz#Removing zip files inorder to reduce the final docker image sizeRUN rm spark-2.4.3-bin-hadoop2.8.tgzRUN rm apache-maven-3.6.0-bin.tar.gz#Setting up env variablesRUN mv $(rpm -q -l java-1.8.0-openjdk-devel | grep "/bin$" | rev | cut -d"/" -f2- |rev) /usr/lib/jvm/jdkENV SPARK_HOME /glue/spark-2.4.3-bin-spark-2.4.3-bin-hadoop2.8ENV MAVEN_HOME /glue/apache-maven-3.6.0ENV JAVA_HOME /usr/lib/jvm/jdkENV GLUE_HOME /glue/aws-glue-libsENV PATH $PATH:$MAVEN_HOME/bin:$SPARK_HOME/bin:$JAVA_HOME/bin:$GLUE_HOME/bin
Here is an important known issue where will be removing some of the libraries https://github.com/awslabs/aws-glue-libs/issues/25.
RUN sed -i '/mvn -f/a rm /glue/aws-glue-libs/jarsv1/netty-*' /glue/aws-glue-libs/bin/glue-setup.shRUN sed -i '/mvn -f/a rm /glue/aws-glue-libs/jarsv1/javax.servlet-3.*' /glue/aws-glue-libs/bin/glue-setup.sh
Now we will compile all the dependencies using maven. This shell script run the maven build command and gets all the required dependencies.
We are running this once so that our docker image will contain the libraries beforehand and will save time to run spark jobs later.
RUN sh /glue/aws-glue-libs/bin/glue-setup.sh
At last we will be cleaning all the tmp directories and using bash as our entrypoint to our container.
RUN yum clean allRUN rm -rf /var/cache/yumCMD ["bash"]
Now to use the docker file and create your container in order to start developing your glue spark jobs follow along.
To build the image out of this Dockerfile run the following command:
docker build -t jnshubham/glue_etl_local .
To use the existing image for starting your container, just pull the image from docker hub and run the commands provided to submit jobs
To pull the image run the following command:
docker pull jnshubham/glue_etl_local:latest
Check downloaded image by running
docker images
To run the container and get into repl shell:
docker run jnshubham/glue_etl_local "gluepyspark"
To get into the terminal and submit a spark job run
docker run -it jnshubham/glue_etl_localgluesparksubmit script.py --JOB_NAME script
This way you will be able to test your job on your local machine or you can also use this on any EC2 instance based on your data size.
For more information, visit my GitHub or dockerhub. | [
{
"code": null,
"e": 423,
"s": 172,
"text": "With the increasing amount of data in the current world, the need for services handling big data is very demanding. When we think about big data, there are very few frameworks which are used by most of the data engineers. Apache Spark is one of them."
},
{
"code": null,
"e": 865,
"s": 423,
"text": "Apache Spark is a distributed processing engine which requires a large cluster to execute any kind of analytics or simply perform ETL on the dataset. To use Apache Spark, we need to set up large clusters of our own which are very expensive or we can leverage them on the cloud. Here, we will be discussing the services provided by AWS. So to process large dataset and to perform analytics on them using spark, AWS provides two major services"
},
{
"code": null,
"e": 902,
"s": 865,
"text": "AWS EMR (Elastic Map Reduce)AWS Glue"
},
{
"code": null,
"e": 931,
"s": 902,
"text": "AWS EMR (Elastic Map Reduce)"
},
{
"code": null,
"e": 940,
"s": 931,
"text": "AWS Glue"
},
{
"code": null,
"e": 1215,
"s": 940,
"text": "AWS EMR provides us cluster to perform our processing and are very expensive, so we need to be careful to identify for how long we require clusters and how to optimize our jobs properly. We will not be covering EMR in this post as it is itself a very large topic to discuss."
},
{
"code": null,
"e": 1724,
"s": 1215,
"text": "AWS Glue is a fully managed ETL service provided by amazon web services for handling large amount of data. The best part of AWS Glue is it comes under the AWS serverless umbrella where we need not worry about managing all those clusters and the cost associated with it. In serverless paradigm, we pay for what we use, so if our job is using only 25 DPU for processing our data and it runs for 20 minutes then we end up paying only the cost for leveraging 25 DPU’s for 20 minutes and not a single penny extra."
},
{
"code": null,
"e": 1903,
"s": 1724,
"text": "AWS Glue is in utmost demand nowadays for creating python or scala based spark processing jobs. To develop jobs on AWS glue, we have three options. Let’s discuss them one by one."
},
{
"code": null,
"e": 1955,
"s": 1903,
"text": "Create Job Directly in glue editor and run the job:"
},
{
"code": null,
"e": 2007,
"s": 1955,
"text": "Create Job Directly in glue editor and run the job:"
},
{
"code": null,
"e": 2619,
"s": 2007,
"text": "If you are a spark developer and not so familiar with glue libraries and its diagram generation, avoid using this editor at all cost. This is for those who are very sure what they are writing and knew from their heart that their job will run in the first run itself. This is not at all recommended and can only be considered when we need to make a few changes in the existing job. Using the job editor directly is good when you are using glue libraries in your code as it generates the lineage diagram as you write the code. Before opting for this option I would recommend going through the glue libraries here."
},
{
"code": null,
"e": 2650,
"s": 2619,
"text": "2. Create a Glue Dev endpoint:"
},
{
"code": null,
"e": 3276,
"s": 2650,
"text": "You can set up a glue dev endpoint and link it to either zeppelin notebooks or to your pycharm IDE or you can even connect local jupyter notebooks. This is a better option if you want to test your jobs while you are developing them. To setup Glue Dev endpoint you can follow official AWS documentation here. The only problem with this glue dev endpoint is its cost. You will be charged for the time it is running, so it basically spins up a EMR cluster with your desired capacity and glue libraries installed on the cluster. This is one of the best option if cost is not a problem with your development and can be considered."
},
{
"code": null,
"e": 3343,
"s": 3276,
"text": "3. Use AWS Glue libraries and run them on Docker container locally"
},
{
"code": null,
"e": 3825,
"s": 3343,
"text": "This is by far the best option considering the development of the jobs and testing the jobs on relatively small datasets and once the job is ready running them using the glue job console itself. With this option, you get the flexibility of using glue libraries either on your machine or you can spin up EC2 instances according to your dataset size and launch the docker container on these EC2, as this will be a relatively cheaper option and the most suitable one to run your jobs."
},
{
"code": null,
"e": 4034,
"s": 3825,
"text": "To set up AWS glue locally, you can follow AWS documentation here. But this seems to be not working and we will be discussing it in detail. So I have created a Docker image and will explain what we are doing."
},
{
"code": null,
"e": 4156,
"s": 4034,
"text": "I am taking centos as base image then setting these env variables we will require this to download the libraries later on"
},
{
"code": null,
"e": 4405,
"s": 4156,
"text": "ENV MAVEN=https://aws-glue-etl-artifacts.s3.amazonaws.com/glue-common/apache-maven-3.6.0-bin.tar.gzENV SPARK=https://aws-glue-etl-artifacts.s3.amazonaws.com/glue-1.0/spark-2.4.3-bin-hadoop2.8.tgzENV GLUE=https://github.com/awslabs/aws-glue-libs.git"
},
{
"code": null,
"e": 4560,
"s": 4405,
"text": "Then we will create a directory glue and install required libraries like Java, Python, wget, tar and python packages and set our working directory to glue"
},
{
"code": null,
"e": 4817,
"s": 4560,
"text": "RUN mkdir glueRUN yum install -y python3 java-1.8.0-openjdk java-1.8.0-openjdk-devel tar git wget zipRUN ln -s /usr/bin/python3 /usr/bin/pythonRUN ln -s /usr/bin/pip3 /usr/bin/pipRUN pip install pandasRUN pip install boto3RUN pip install pyntWORKDIR ./glue"
},
{
"code": null,
"e": 5015,
"s": 4817,
"text": "Now in this directory will download maven, spark and glue libs and unzip them. Then we will be updating the path variable and adding SPARK_HOME, JAVA_HOME, MAVEN_HOME and GLUE_HOME variables to it."
},
{
"code": null,
"e": 5761,
"s": 5015,
"text": "#To get the latest aws librariesRUN git clone -b glue-1.0 $GLUE#To get latest spark versionRUN wget $SPARK#To install Maven for dependenciesRUN wget $MAVENRUN tar zxfv apache-maven-3.6.0-bin.tar.gzRUN tar zxfv spark-2.4.3-bin-hadoop2.8.tgz#Removing zip files inorder to reduce the final docker image sizeRUN rm spark-2.4.3-bin-hadoop2.8.tgzRUN rm apache-maven-3.6.0-bin.tar.gz#Setting up env variablesRUN mv $(rpm -q -l java-1.8.0-openjdk-devel | grep \"/bin$\" | rev | cut -d\"/\" -f2- |rev) /usr/lib/jvm/jdkENV SPARK_HOME /glue/spark-2.4.3-bin-spark-2.4.3-bin-hadoop2.8ENV MAVEN_HOME /glue/apache-maven-3.6.0ENV JAVA_HOME /usr/lib/jvm/jdkENV GLUE_HOME /glue/aws-glue-libsENV PATH $PATH:$MAVEN_HOME/bin:$SPARK_HOME/bin:$JAVA_HOME/bin:$GLUE_HOME/bin"
},
{
"code": null,
"e": 5891,
"s": 5761,
"text": "Here is an important known issue where will be removing some of the libraries https://github.com/awslabs/aws-glue-libs/issues/25."
},
{
"code": null,
"e": 6098,
"s": 5891,
"text": "RUN sed -i '/mvn -f/a rm /glue/aws-glue-libs/jarsv1/netty-*' /glue/aws-glue-libs/bin/glue-setup.shRUN sed -i '/mvn -f/a rm /glue/aws-glue-libs/jarsv1/javax.servlet-3.*' /glue/aws-glue-libs/bin/glue-setup.sh"
},
{
"code": null,
"e": 6238,
"s": 6098,
"text": "Now we will compile all the dependencies using maven. This shell script run the maven build command and gets all the required dependencies."
},
{
"code": null,
"e": 6370,
"s": 6238,
"text": "We are running this once so that our docker image will contain the libraries beforehand and will save time to run spark jobs later."
},
{
"code": null,
"e": 6415,
"s": 6370,
"text": "RUN sh /glue/aws-glue-libs/bin/glue-setup.sh"
},
{
"code": null,
"e": 6518,
"s": 6415,
"text": "At last we will be cleaning all the tmp directories and using bash as our entrypoint to our container."
},
{
"code": null,
"e": 6573,
"s": 6518,
"text": "RUN yum clean allRUN rm -rf /var/cache/yumCMD [\"bash\"]"
},
{
"code": null,
"e": 6690,
"s": 6573,
"text": "Now to use the docker file and create your container in order to start developing your glue spark jobs follow along."
},
{
"code": null,
"e": 6759,
"s": 6690,
"text": "To build the image out of this Dockerfile run the following command:"
},
{
"code": null,
"e": 6802,
"s": 6759,
"text": "docker build -t jnshubham/glue_etl_local ."
},
{
"code": null,
"e": 6938,
"s": 6802,
"text": "To use the existing image for starting your container, just pull the image from docker hub and run the commands provided to submit jobs"
},
{
"code": null,
"e": 6983,
"s": 6938,
"text": "To pull the image run the following command:"
},
{
"code": null,
"e": 7027,
"s": 6983,
"text": "docker pull jnshubham/glue_etl_local:latest"
},
{
"code": null,
"e": 7061,
"s": 7027,
"text": "Check downloaded image by running"
},
{
"code": null,
"e": 7075,
"s": 7061,
"text": "docker images"
},
{
"code": null,
"e": 7121,
"s": 7075,
"text": "To run the container and get into repl shell:"
},
{
"code": null,
"e": 7171,
"s": 7121,
"text": "docker run jnshubham/glue_etl_local \"gluepyspark\""
},
{
"code": null,
"e": 7223,
"s": 7171,
"text": "To get into the terminal and submit a spark job run"
},
{
"code": null,
"e": 7306,
"s": 7223,
"text": "docker run -it jnshubham/glue_etl_localgluesparksubmit script.py --JOB_NAME script"
},
{
"code": null,
"e": 7441,
"s": 7306,
"text": "This way you will be able to test your job on your local machine or you can also use this on any EC2 instance based on your data size."
}
] |
Find the Kth smallest element in the sorted generated array - GeeksforGeeks | 21 Jan, 2022
Given an array arr[] of N elements and an integer K, the task is to generate an B[] with the following rules:
Copy elements arr[1...N], N times to array B[].Copy elements arr[1...N/2], 2*N times to array B[].Copy elements arr[1...N/4], 3*N times to array B[].Similarly, until only no element is left to be copied to array B[].
Copy elements arr[1...N], N times to array B[].
Copy elements arr[1...N/2], 2*N times to array B[].
Copy elements arr[1...N/4], 3*N times to array B[].
Similarly, until only no element is left to be copied to array B[].
Finally print the Kth smallest element from the array B[]. If K is out of bounds of B[] then return -1.Examples:
Input: arr[] = {1, 2, 3}, K = 4 Output: 1 {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 1, 1, 1, 1, 1} is the required array B[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3} in the sorted form where 1 is the 4th smallest element.Input: arr[] = {2, 4, 5, 1}, K = 13 Output: 2
Approach:
Maintain a Count_Array where we must store the count of times every element occurs in array B[]. It can be done for range of elements by adding the count at start index and subtracting the same count at end index + 1 location.Take cumulative sum of count array.Maintain all elements of arr[] with their count in Array B[] along with their counts and sort them based on element value.Traverse through vector and see which element has Kth position in B[] as per their individual counts.If K is out of bounds of B[] then return -1.
Maintain a Count_Array where we must store the count of times every element occurs in array B[]. It can be done for range of elements by adding the count at start index and subtracting the same count at end index + 1 location.
Take cumulative sum of count array.
Maintain all elements of arr[] with their count in Array B[] along with their counts and sort them based on element value.
Traverse through vector and see which element has Kth position in B[] as per their individual counts.
If K is out of bounds of B[] then return -1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the Kth element in B[]int solve(int Array[], int N, int K){ // Initialize the count Array int count_Arr[N + 1] = { 0 }; int factor = 1; int size = N; // Reduce N repeatedly to half its value while (size) { int start = 1; int end = size; // Add count to start count_Arr[1] += factor * N; // Subtract same count after end index count_Arr[end + 1] -= factor * N; factor++; size /= 2; } for (int i = 2; i <= N; i++) count_Arr[i] += count_Arr[i - 1]; // Store each element of Array[] with their count vector<pair<int, int> > element; for (int i = 0; i < N; i++) { element.push_back({ Array[i], count_Arr[i + 1] }); } // Sort the elements wrt value sort(element.begin(), element.end()); int start = 1; for (int i = 0; i < N; i++) { int end = start + element[i].second - 1; // If Kth element is in range of element[i] // return element[i] if (K >= start && K <= end) { return element[i].first; } start += element[i].second; } // If K is out of bound return -1;} // Driver codeint main(){ int arr[] = { 2, 4, 5, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 13; cout << solve(arr, N, K); return 0;}
// Java implementation of the approachimport java.util.Vector; class GFG{ // Pair class implementation to use Pair static class Pair { private int first; private int second; Pair(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; } } // Function to return the Kth element in B[] static int solve(int[] Array, int N, int K) { // Initialize the count Array int[] count_Arr = new int[N + 2]; int factor = 1; int size = N; // Reduce N repeatedly to half its value while (size > 0) { int start = 1; int end = size; // Add count to start count_Arr[1] += factor * N; // Subtract same count after end index count_Arr[end + 1] -= factor * N; factor++; size /= 2; } for (int i = 2; i <= N; i++) count_Arr[i] += count_Arr[i - 1]; // Store each element of Array[] // with their count Vector<Pair> element = new Vector<>(); for (int i = 0; i < N; i++) { Pair x = new Pair(Array[i], count_Arr[i + 1]); element.add(x); } int start = 1; for (int i = 0; i < N; i++) { int end = start + element.elementAt(0).getSecond() - 1; // If Kth element is in range of element[i] // return element[i] if (K >= start && K <= end) return element.elementAt(i).getFirst(); start += element.elementAt(i).getSecond(); } // If K is out of bound return -1; } // Driver code public static void main(String[] args) { int[] arr = { 2, 4, 5, 1 }; int N = arr.length; int K = 13; System.out.println(solve(arr, N, K)); }} // This code is contributed by// sanjeev2552
# Python3 implementation of the approach # Function to return the Kth element in B[]def solve(Array, N, K) : # Initialize the count Array count_Arr = [0]*(N + 2) ; factor = 1; size = N; # Reduce N repeatedly to half its value while (size) : start = 1; end = size; # Add count to start count_Arr[1] += factor * N; # Subtract same count after end index count_Arr[end + 1] -= factor * N; factor += 1; size //= 2; for i in range(2, N + 1) : count_Arr[i] += count_Arr[i - 1]; # Store each element of Array[] with their count element = []; for i in range(N) : element.append(( Array[i], count_Arr[i + 1] )); # Sort the elements wrt value element.sort(); start = 1; for i in range(N) : end = start + element[i][1] - 1; # If Kth element is in range of element[i] # return element[i] if (K >= start and K <= end) : return element[i][0]; start += element[i][1]; # If K is out of bound return -1; # Driver codeif __name__ == "__main__" : arr = [ 2, 4, 5, 1 ]; N = len(arr); K = 13; print(solve(arr, N, K)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Pair class implementation to use Pair public class Pair { public int first; public int second; public Pair(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; } } // Function to return the Kth element in B[] static int solve(int[] Array, int N, int K) { // Initialize the count Array int[] count_Arr = new int[N + 2]; int factor = 1; int size = N; // Reduce N repeatedly to half its value while (size > 0) { int end = size; // Add count to start count_Arr[1] += factor * N; // Subtract same count after end index count_Arr[end + 1] -= factor * N; factor++; size /= 2; } for (int i = 2; i <= N; i++) count_Arr[i] += count_Arr[i - 1]; // Store each element of Array[] // with their count List<Pair> element = new List<Pair>(); for (int i = 0; i < N; i++) { Pair x = new Pair(Array[i], count_Arr[i + 1]); element.Add(x); } int start = 1; for (int i = 0; i < N; i++) { int end = start + element[0].getSecond() - 1; // If Kth element is in range of element[i] // return element[i] if (K >= start && K <= end) return element[i].getFirst(); start += element[i].getSecond(); } // If K is out of bound return -1; } // Driver code public static void Main(String[] args) { int[] arr = { 2, 4, 5, 1 }; int N = arr.Length; int K = 13; Console.WriteLine(solve(arr, N, K)); }} // This code is contributed by Rajput-Ji
<script> // JavaScript implementation of the approach // Function to return the Kth element in B[]function solve(arr, N, K) { // Initialize the count Array let count_Arr = new Array(N + 1).fill(0); let factor = 1; let size = N; // Reduce N repeatedly to half its value while (size) { let start = 1; let end = size; // Add count to start count_Arr[1] += factor * N; // Subtract same count after end index count_Arr[end + 1] -= factor * N; factor++; size = Math.floor(size / 2); } for (let i = 2; i <= N; i++) count_Arr[i] += count_Arr[i - 1]; // Store each element of Array[] with their count let element = []; for (let i = 0; i < N; i++) { element.push([arr[i], count_Arr[i + 1]]); } // Sort the elements wrt value element.sort((a, b) => a - b); let start = 1; for (let i = 0; i < N; i++) { let end = start + element[i][1] - 1; // If Kth element is in range of element[i] // return element[i] if (K >= start && K <= end) { return element[i][0]; } start += element[i][1]; } // If K is out of bound return -1;} // Driver code let arr = [2, 4, 5, 1];let N = arr.length;let K = 13; document.write(solve(arr, N, K)); // This code is contributed by gfgking </script>
2
ankthon
sanjeev2552
Rajput-Ji
gfgking
simmytarika5
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Linked List vs Array
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 25432,
"s": 25404,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 25544,
"s": 25432,
"text": "Given an array arr[] of N elements and an integer K, the task is to generate an B[] with the following rules: "
},
{
"code": null,
"e": 25761,
"s": 25544,
"text": "Copy elements arr[1...N], N times to array B[].Copy elements arr[1...N/2], 2*N times to array B[].Copy elements arr[1...N/4], 3*N times to array B[].Similarly, until only no element is left to be copied to array B[]."
},
{
"code": null,
"e": 25809,
"s": 25761,
"text": "Copy elements arr[1...N], N times to array B[]."
},
{
"code": null,
"e": 25861,
"s": 25809,
"text": "Copy elements arr[1...N/2], 2*N times to array B[]."
},
{
"code": null,
"e": 25913,
"s": 25861,
"text": "Copy elements arr[1...N/4], 3*N times to array B[]."
},
{
"code": null,
"e": 25981,
"s": 25913,
"text": "Similarly, until only no element is left to be copied to array B[]."
},
{
"code": null,
"e": 26096,
"s": 25981,
"text": "Finally print the Kth smallest element from the array B[]. If K is out of bounds of B[] then return -1.Examples: "
},
{
"code": null,
"e": 26359,
"s": 26096,
"text": "Input: arr[] = {1, 2, 3}, K = 4 Output: 1 {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 1, 1, 1, 1, 1} is the required array B[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3} in the sorted form where 1 is the 4th smallest element.Input: arr[] = {2, 4, 5, 1}, K = 13 Output: 2 "
},
{
"code": null,
"e": 26373,
"s": 26361,
"text": "Approach: "
},
{
"code": null,
"e": 26902,
"s": 26373,
"text": "Maintain a Count_Array where we must store the count of times every element occurs in array B[]. It can be done for range of elements by adding the count at start index and subtracting the same count at end index + 1 location.Take cumulative sum of count array.Maintain all elements of arr[] with their count in Array B[] along with their counts and sort them based on element value.Traverse through vector and see which element has Kth position in B[] as per their individual counts.If K is out of bounds of B[] then return -1."
},
{
"code": null,
"e": 27129,
"s": 26902,
"text": "Maintain a Count_Array where we must store the count of times every element occurs in array B[]. It can be done for range of elements by adding the count at start index and subtracting the same count at end index + 1 location."
},
{
"code": null,
"e": 27165,
"s": 27129,
"text": "Take cumulative sum of count array."
},
{
"code": null,
"e": 27288,
"s": 27165,
"text": "Maintain all elements of arr[] with their count in Array B[] along with their counts and sort them based on element value."
},
{
"code": null,
"e": 27390,
"s": 27288,
"text": "Traverse through vector and see which element has Kth position in B[] as per their individual counts."
},
{
"code": null,
"e": 27435,
"s": 27390,
"text": "If K is out of bounds of B[] then return -1."
},
{
"code": null,
"e": 27488,
"s": 27435,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27492,
"s": 27488,
"text": "C++"
},
{
"code": null,
"e": 27497,
"s": 27492,
"text": "Java"
},
{
"code": null,
"e": 27505,
"s": 27497,
"text": "Python3"
},
{
"code": null,
"e": 27508,
"s": 27505,
"text": "C#"
},
{
"code": null,
"e": 27519,
"s": 27508,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the Kth element in B[]int solve(int Array[], int N, int K){ // Initialize the count Array int count_Arr[N + 1] = { 0 }; int factor = 1; int size = N; // Reduce N repeatedly to half its value while (size) { int start = 1; int end = size; // Add count to start count_Arr[1] += factor * N; // Subtract same count after end index count_Arr[end + 1] -= factor * N; factor++; size /= 2; } for (int i = 2; i <= N; i++) count_Arr[i] += count_Arr[i - 1]; // Store each element of Array[] with their count vector<pair<int, int> > element; for (int i = 0; i < N; i++) { element.push_back({ Array[i], count_Arr[i + 1] }); } // Sort the elements wrt value sort(element.begin(), element.end()); int start = 1; for (int i = 0; i < N; i++) { int end = start + element[i].second - 1; // If Kth element is in range of element[i] // return element[i] if (K >= start && K <= end) { return element[i].first; } start += element[i].second; } // If K is out of bound return -1;} // Driver codeint main(){ int arr[] = { 2, 4, 5, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 13; cout << solve(arr, N, K); return 0;}",
"e": 28927,
"s": 27519,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.Vector; class GFG{ // Pair class implementation to use Pair static class Pair { private int first; private int second; Pair(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; } } // Function to return the Kth element in B[] static int solve(int[] Array, int N, int K) { // Initialize the count Array int[] count_Arr = new int[N + 2]; int factor = 1; int size = N; // Reduce N repeatedly to half its value while (size > 0) { int start = 1; int end = size; // Add count to start count_Arr[1] += factor * N; // Subtract same count after end index count_Arr[end + 1] -= factor * N; factor++; size /= 2; } for (int i = 2; i <= N; i++) count_Arr[i] += count_Arr[i - 1]; // Store each element of Array[] // with their count Vector<Pair> element = new Vector<>(); for (int i = 0; i < N; i++) { Pair x = new Pair(Array[i], count_Arr[i + 1]); element.add(x); } int start = 1; for (int i = 0; i < N; i++) { int end = start + element.elementAt(0).getSecond() - 1; // If Kth element is in range of element[i] // return element[i] if (K >= start && K <= end) return element.elementAt(i).getFirst(); start += element.elementAt(i).getSecond(); } // If K is out of bound return -1; } // Driver code public static void main(String[] args) { int[] arr = { 2, 4, 5, 1 }; int N = arr.length; int K = 13; System.out.println(solve(arr, N, K)); }} // This code is contributed by// sanjeev2552",
"e": 31020,
"s": 28927,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the Kth element in B[]def solve(Array, N, K) : # Initialize the count Array count_Arr = [0]*(N + 2) ; factor = 1; size = N; # Reduce N repeatedly to half its value while (size) : start = 1; end = size; # Add count to start count_Arr[1] += factor * N; # Subtract same count after end index count_Arr[end + 1] -= factor * N; factor += 1; size //= 2; for i in range(2, N + 1) : count_Arr[i] += count_Arr[i - 1]; # Store each element of Array[] with their count element = []; for i in range(N) : element.append(( Array[i], count_Arr[i + 1] )); # Sort the elements wrt value element.sort(); start = 1; for i in range(N) : end = start + element[i][1] - 1; # If Kth element is in range of element[i] # return element[i] if (K >= start and K <= end) : return element[i][0]; start += element[i][1]; # If K is out of bound return -1; # Driver codeif __name__ == \"__main__\" : arr = [ 2, 4, 5, 1 ]; N = len(arr); K = 13; print(solve(arr, N, K)); # This code is contributed by AnkitRai01",
"e": 32256,
"s": 31020,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Pair class implementation to use Pair public class Pair { public int first; public int second; public Pair(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; } } // Function to return the Kth element in B[] static int solve(int[] Array, int N, int K) { // Initialize the count Array int[] count_Arr = new int[N + 2]; int factor = 1; int size = N; // Reduce N repeatedly to half its value while (size > 0) { int end = size; // Add count to start count_Arr[1] += factor * N; // Subtract same count after end index count_Arr[end + 1] -= factor * N; factor++; size /= 2; } for (int i = 2; i <= N; i++) count_Arr[i] += count_Arr[i - 1]; // Store each element of Array[] // with their count List<Pair> element = new List<Pair>(); for (int i = 0; i < N; i++) { Pair x = new Pair(Array[i], count_Arr[i + 1]); element.Add(x); } int start = 1; for (int i = 0; i < N; i++) { int end = start + element[0].getSecond() - 1; // If Kth element is in range of element[i] // return element[i] if (K >= start && K <= end) return element[i].getFirst(); start += element[i].getSecond(); } // If K is out of bound return -1; } // Driver code public static void Main(String[] args) { int[] arr = { 2, 4, 5, 1 }; int N = arr.Length; int K = 13; Console.WriteLine(solve(arr, N, K)); }} // This code is contributed by Rajput-Ji",
"e": 34314,
"s": 32256,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the Kth element in B[]function solve(arr, N, K) { // Initialize the count Array let count_Arr = new Array(N + 1).fill(0); let factor = 1; let size = N; // Reduce N repeatedly to half its value while (size) { let start = 1; let end = size; // Add count to start count_Arr[1] += factor * N; // Subtract same count after end index count_Arr[end + 1] -= factor * N; factor++; size = Math.floor(size / 2); } for (let i = 2; i <= N; i++) count_Arr[i] += count_Arr[i - 1]; // Store each element of Array[] with their count let element = []; for (let i = 0; i < N; i++) { element.push([arr[i], count_Arr[i + 1]]); } // Sort the elements wrt value element.sort((a, b) => a - b); let start = 1; for (let i = 0; i < N; i++) { let end = start + element[i][1] - 1; // If Kth element is in range of element[i] // return element[i] if (K >= start && K <= end) { return element[i][0]; } start += element[i][1]; } // If K is out of bound return -1;} // Driver code let arr = [2, 4, 5, 1];let N = arr.length;let K = 13; document.write(solve(arr, N, K)); // This code is contributed by gfgking </script>",
"e": 35667,
"s": 34314,
"text": null
},
{
"code": null,
"e": 35669,
"s": 35667,
"text": "2"
},
{
"code": null,
"e": 35679,
"s": 35671,
"text": "ankthon"
},
{
"code": null,
"e": 35691,
"s": 35679,
"text": "sanjeev2552"
},
{
"code": null,
"e": 35701,
"s": 35691,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 35709,
"s": 35701,
"text": "gfgking"
},
{
"code": null,
"e": 35722,
"s": 35709,
"text": "simmytarika5"
},
{
"code": null,
"e": 35729,
"s": 35722,
"text": "Arrays"
},
{
"code": null,
"e": 35736,
"s": 35729,
"text": "Greedy"
},
{
"code": null,
"e": 35749,
"s": 35736,
"text": "Mathematical"
},
{
"code": null,
"e": 35756,
"s": 35749,
"text": "Arrays"
},
{
"code": null,
"e": 35763,
"s": 35756,
"text": "Greedy"
},
{
"code": null,
"e": 35776,
"s": 35763,
"text": "Mathematical"
},
{
"code": null,
"e": 35874,
"s": 35776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35942,
"s": 35874,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 35974,
"s": 35942,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 35997,
"s": 35974,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36042,
"s": 35997,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 36063,
"s": 36042,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 36114,
"s": 36063,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 36172,
"s": 36114,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 36223,
"s": 36172,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 36254,
"s": 36223,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
Anonymous Structure and Field in Golang - GeeksforGeeks | 12 Aug, 2019
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct.
In Go language, you are allowed to create an anonymous structure. An anonymous structure is a structure which does not contain a name. It useful when you want to create a one-time usable structure. You can create an anonymous structure using the following syntax:
variable_name := struct{
// fields
}{// Field_values}
Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate the// concept of anonymous structurepackage main import "fmt" // Main functionfunc main() { // Creating and initializing // the anonymous structure Element := struct { name string branch string language string Particles int }{ name: "Pikachu", branch: "ECE", language: "C++", Particles: 498, } // Display the anonymous structure fmt.Println(Element)}
Output:
{Pikachu ECE C++ 498}
In a Go structure, you are allowed to create anonymous fields. Anonymous fields are those fields which do not contain any name you just simply mention the type of the fields and Go will automatically use the type as the name of the field. You can create anonymous fields of the structure using the following syntax:
type struct_name struct{
int
bool
float64
}
Important Points:
In a structure, you are not allowed to create two or more fields of the same type as shown below:type student struct{
int
int
}
If you try to do so, then the compiler will give an error.
type student struct{
int
int
}
If you try to do so, then the compiler will give an error.
You are allowed to combine the anonymous fields with the named fields as shown below:type student struct{
name int
price int
string
}
Let us discuss the anonymous field concept with the help of an example:Example:// Go program to illustrate the// concept of anonymous structurepackage main import "fmt" // Creating a structure// with anonymous fieldstype student struct { int string float64} // Main functionfunc main() { // Assigning values to the anonymous // fields of the student structure value := student{123, "Bud", 8900.23} // Display the values of the fields fmt.Println("Enrollment number : ", value.int) fmt.Println("Student name : ", value.string) fmt.Println("Package price : ", value.float64)}Output:Enrollment number : 123
Student name : Bud
Package price : 8900.23
My Personal Notes
arrow_drop_upSave
type student struct{
name int
price int
string
}
Let us discuss the anonymous field concept with the help of an example:
Example:
// Go program to illustrate the// concept of anonymous structurepackage main import "fmt" // Creating a structure// with anonymous fieldstype student struct { int string float64} // Main functionfunc main() { // Assigning values to the anonymous // fields of the student structure value := student{123, "Bud", 8900.23} // Display the values of the fields fmt.Println("Enrollment number : ", value.int) fmt.Println("Student name : ", value.string) fmt.Println("Package price : ", value.float64)}
Output:
Enrollment number : 123
Student name : Bud
Package price : 8900.23
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
Time Formatting in Golang
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
How to convert a string in lower case in Golang?
How to compare times in Golang?
Inheritance in GoLang | [
{
"code": null,
"e": 24906,
"s": 24878,
"text": "\n12 Aug, 2019"
},
{
"code": null,
"e": 25144,
"s": 24906,
"text": "A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct."
},
{
"code": null,
"e": 25408,
"s": 25144,
"text": "In Go language, you are allowed to create an anonymous structure. An anonymous structure is a structure which does not contain a name. It useful when you want to create a one-time usable structure. You can create an anonymous structure using the following syntax:"
},
{
"code": null,
"e": 25463,
"s": 25408,
"text": "variable_name := struct{\n// fields\n}{// Field_values}\n"
},
{
"code": null,
"e": 25520,
"s": 25463,
"text": "Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 25529,
"s": 25520,
"text": "Example:"
},
{
"code": "// Go program to illustrate the// concept of anonymous structurepackage main import \"fmt\" // Main functionfunc main() { // Creating and initializing // the anonymous structure Element := struct { name string branch string language string Particles int }{ name: \"Pikachu\", branch: \"ECE\", language: \"C++\", Particles: 498, } // Display the anonymous structure fmt.Println(Element)}",
"e": 26009,
"s": 25529,
"text": null
},
{
"code": null,
"e": 26017,
"s": 26009,
"text": "Output:"
},
{
"code": null,
"e": 26039,
"s": 26017,
"text": "{Pikachu ECE C++ 498}"
},
{
"code": null,
"e": 26355,
"s": 26039,
"text": "In a Go structure, you are allowed to create anonymous fields. Anonymous fields are those fields which do not contain any name you just simply mention the type of the fields and Go will automatically use the type as the name of the field. You can create anonymous fields of the structure using the following syntax:"
},
{
"code": null,
"e": 26412,
"s": 26355,
"text": "type struct_name struct{\n int\n bool\n float64\n}\n"
},
{
"code": null,
"e": 26430,
"s": 26412,
"text": "Important Points:"
},
{
"code": null,
"e": 26617,
"s": 26430,
"text": "In a structure, you are not allowed to create two or more fields of the same type as shown below:type student struct{\nint\nint\n}\nIf you try to do so, then the compiler will give an error."
},
{
"code": null,
"e": 26649,
"s": 26617,
"text": "type student struct{\nint\nint\n}\n"
},
{
"code": null,
"e": 26708,
"s": 26649,
"text": "If you try to do so, then the compiler will give an error."
},
{
"code": null,
"e": 27568,
"s": 26708,
"text": "You are allowed to combine the anonymous fields with the named fields as shown below:type student struct{\n name int\n price int\n string\n}\nLet us discuss the anonymous field concept with the help of an example:Example:// Go program to illustrate the// concept of anonymous structurepackage main import \"fmt\" // Creating a structure// with anonymous fieldstype student struct { int string float64} // Main functionfunc main() { // Assigning values to the anonymous // fields of the student structure value := student{123, \"Bud\", 8900.23} // Display the values of the fields fmt.Println(\"Enrollment number : \", value.int) fmt.Println(\"Student name : \", value.string) fmt.Println(\"Package price : \", value.float64)}Output:Enrollment number : 123\nStudent name : Bud\nPackage price : 8900.23\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 27621,
"s": 27568,
"text": "type student struct{\n name int\n price int\n string\n}\n"
},
{
"code": null,
"e": 27693,
"s": 27621,
"text": "Let us discuss the anonymous field concept with the help of an example:"
},
{
"code": null,
"e": 27702,
"s": 27693,
"text": "Example:"
},
{
"code": "// Go program to illustrate the// concept of anonymous structurepackage main import \"fmt\" // Creating a structure// with anonymous fieldstype student struct { int string float64} // Main functionfunc main() { // Assigning values to the anonymous // fields of the student structure value := student{123, \"Bud\", 8900.23} // Display the values of the fields fmt.Println(\"Enrollment number : \", value.int) fmt.Println(\"Student name : \", value.string) fmt.Println(\"Package price : \", value.float64)}",
"e": 28234,
"s": 27702,
"text": null
},
{
"code": null,
"e": 28242,
"s": 28234,
"text": "Output:"
},
{
"code": null,
"e": 28313,
"s": 28242,
"text": "Enrollment number : 123\nStudent name : Bud\nPackage price : 8900.23\n"
},
{
"code": null,
"e": 28320,
"s": 28313,
"text": "Golang"
},
{
"code": null,
"e": 28332,
"s": 28320,
"text": "Go Language"
},
{
"code": null,
"e": 28430,
"s": 28332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28482,
"s": 28430,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 28528,
"s": 28482,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 28554,
"s": 28528,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 28604,
"s": 28554,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 28655,
"s": 28604,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 28702,
"s": 28655,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 28714,
"s": 28702,
"text": "Golang Maps"
},
{
"code": null,
"e": 28763,
"s": 28714,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 28795,
"s": 28763,
"text": "How to compare times in Golang?"
}
] |
Is BIGINT(8) the largest integer MySQL can store? | In BIGINT(8), the number 8 represents how the data will be displayed. It does not affect the storage. The number is used to display width.
BIGINT takes 8 bytes i.e. 64 bits. The signed range is -9223372036854775808 to 9223372036854775807 and unsigned range takes positive value. The range of unsigned is 0 to 18446744073709551615.
To understand bigint(8), let us create a table with BIGINT(8) and zerofill column −
mysql> create table BigIntDemo8
-> (
-> Number1 BIGINT(8) not null,
-> Number2 BIGINT(8) unsigned zerofill not null
-> );
Query OK, 0 rows affected (0.59 sec)
Insert some records for both the columns. The query to insert record is as follows −
mysql> insert into BigIntDemo8 values(1,1);
Query OK, 1 row affected (0.14 sec)
mysql> insert into BigIntDemo8 values(11,11);
Query OK, 1 row affected (0.24 sec)
mysql> insert into BigIntDemo8 values(111,111);
Query OK, 1 row affected (0.14 sec)
mysql> insert into BigIntDemo8 values(1111,1111);
Query OK, 1 row affected (0.18 sec)
mysql> insert into BigIntDemo8 values(11111,11111);
Query OK, 1 row affected (0.10 sec)
mysql> insert into BigIntDemo8 values(111111,111111);
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from BigIntDemo8;
The following is the output −
+---------+----------+
| Number1 | Number2 |
+---------+----------+
| 1 | 00000001 |
| 11 | 00000011 |
| 111 | 00000111 |
| 1111 | 00001111 |
| 11111 | 00011111 |
| 111111 | 00111111 |
+---------+----------+
6 rows in set (0.00 sec) | [
{
"code": null,
"e": 1201,
"s": 1062,
"text": "In BIGINT(8), the number 8 represents how the data will be displayed. It does not affect the storage. The number is used to display width."
},
{
"code": null,
"e": 1393,
"s": 1201,
"text": "BIGINT takes 8 bytes i.e. 64 bits. The signed range is -9223372036854775808 to 9223372036854775807 and unsigned range takes positive value. The range of unsigned is 0 to 18446744073709551615."
},
{
"code": null,
"e": 1477,
"s": 1393,
"text": "To understand bigint(8), let us create a table with BIGINT(8) and zerofill column −"
},
{
"code": null,
"e": 1648,
"s": 1477,
"text": "mysql> create table BigIntDemo8\n -> (\n -> Number1 BIGINT(8) not null,\n -> Number2 BIGINT(8) unsigned zerofill not null\n -> );\nQuery OK, 0 rows affected (0.59 sec)"
},
{
"code": null,
"e": 1733,
"s": 1648,
"text": "Insert some records for both the columns. The query to insert record is as follows −"
},
{
"code": null,
"e": 2248,
"s": 1733,
"text": "mysql> insert into BigIntDemo8 values(1,1);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into BigIntDemo8 values(11,11);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into BigIntDemo8 values(111,111);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into BigIntDemo8 values(1111,1111);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into BigIntDemo8 values(11111,11111);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into BigIntDemo8 values(111111,111111);\nQuery OK, 1 row affected (0.21 sec)"
},
{
"code": null,
"e": 2333,
"s": 2248,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2366,
"s": 2333,
"text": "mysql> select *from BigIntDemo8;"
},
{
"code": null,
"e": 2396,
"s": 2366,
"text": "The following is the output −"
},
{
"code": null,
"e": 2651,
"s": 2396,
"text": "+---------+----------+\n| Number1 | Number2 |\n+---------+----------+\n| 1 | 00000001 |\n| 11 | 00000011 |\n| 111 | 00000111 |\n| 1111 | 00001111 |\n| 11111 | 00011111 |\n| 111111 | 00111111 |\n+---------+----------+\n6 rows in set (0.00 sec)"
}
] |
PHP - imap_headerinfo() Function | PHP−IMAP functions helps you to access email accounts, IMAP stands for Internet Mail Access Protocol using these functions you can also work with NNTP, POP3 protocols and local mailbox access methods.
The imap_headerinfo() function accepts a resource value representing an IMAP stream, an integer value representing a particular message as parameters and, reads the header of the specified message.
imap_headerinfo($imap_stream ,$msg [,fromlength, $subjectlength, $defaulthost]);
imap_stream (Mandatory)
This is a string value representing an IMAP stream, return value of the imap_open() function.
msg (Mandatory)
This is an integer value representing the message/mail number.
fromlength (Optional)
This is an integer value representing the length of the fetchfrom property.
subjectlength (Optional)
This is an integer value representing the length of the fetchsubject property.
This function returns an object representing the headers of the specified message in case of success and a Boolean value which is FALSE in case of failure.
This function was first introduced in PHP Version 4 and works in all the later versions.
Following example demonstrates the usage of the imap_headerinfo() function −
<html>
<body>
<?php
//Establishing connection
$url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
$id = "tutorialspoint.test@gmail.com";
$pwd = "cohondob_123";
$imap = imap_open($url, $id, $pwd);
print("Connection established...."."<br>");
//Fetching the headers of all messages
print("Headers of all messages: "."<br>");
$res = imap_headerinfo($imap, 2);
print_r($res);
//Closing the connection
imap_close($imap);
?>
</body>
</html>
This will generate the following output −
Connection established....
Headers of all messages:
stdClass Object ( [date] => Thu, 22 Oct 2020 20:10:52 +0530 [Date] => Thu,
22 Oct 2020 20:10:52 +0530 [message_id] => [toaddress] =>
tutorialspoint.test@gmail.com [to] => Array ( [0] => stdClass Object (
[mailbox] => tutorialspoint.test [host] => gmail.com ) ) [fromaddress] =>
Sender [from] => Array ( [0] => stdClass Object ( [personal] => Sender
[mailbox] => sample.test[host] => gmail.com ) ) [reply_toaddress] =>
Sender [reply_to] => Array ( [0] => stdClass Object ( [personal] =>
Sender [mailbox] => sample.test[host] => gmail.com ) ) [senderaddress] =>
Sender [sender] => Array ( [0] => stdClass Object ( [personal] => Sender
[mailbox] => sample.test[host] => gmail.com ) ) [Recent] => [Unseen] =
> U [Flagged] => [Answered] => [Deleted] => [Draft] => [Msgno] =
> 2 [MailDate] => 22-Oct-2020 14:41:31 +0000 [Size] => 4858 [udate] =>
1603377691 )
Following is another example of the above function −
<html>
<body>
<?php
//Establishing connection
$url = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
$id = "tutorialspoint.test@gmail.com";
$pwd = "cohondob_123";
$imap = imap_open($url, $id, $pwd);
print("Connection established...."."<br>");
//Fetching the headers of all messages
print("Headers of all messages: "."<br>");
for($i=1; $i<=imap_num_msg($imap); $i++) {
$res = imap_headerinfo($imap, $i);
print($res->toaddress);
print("<br>");
print($res->fromaddress);
print("<br>");
print($res->date);
print("<br>");
print($res->Size);
print("<br>");
print("<br>");
}
//Closing the connection
imap_close($imap);
?>
</body>
</html>
This will generate the following output −
Connection established....
Headers of all messages:
tutorialspoint.test@gmail.com
Sender
Thu, 22 Oct 2020 20:10:17 +0530
4857
tutorialspoint.test@gmail.com
Sender
Thu, 22 Oct 2020 20:10:52 +0530
4858
tutorialspoint.test@gmail.com
Sender
Sun, 25 Oct 2020 16:11:22 +0530
4880
tutorialspoint.test@gmail.com
Sender
Sun, 25 Oct 2020 17:22:41 +0530
4882
tutorialspoint.test@gmail.com
Sender
Sun, 25 Oct 2020 17:23:10 +0530
4884
tutorialspoint.test@gmail.com
Sender
Sun, 25 Oct 2020 17:24:25 +0530
4883
tutorialspoint.test@gmail.com
Sender
Mon, 26 Oct 2020 12:31:14 +0530
4888
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2958,
"s": 2757,
"text": "PHP−IMAP functions helps you to access email accounts, IMAP stands for Internet Mail Access Protocol using these functions you can also work with NNTP, POP3 protocols and local mailbox access methods."
},
{
"code": null,
"e": 3156,
"s": 2958,
"text": "The imap_headerinfo() function accepts a resource value representing an IMAP stream, an integer value representing a particular message as parameters and, reads the header of the specified message."
},
{
"code": null,
"e": 3238,
"s": 3156,
"text": "imap_headerinfo($imap_stream ,$msg [,fromlength, $subjectlength, $defaulthost]);\n"
},
{
"code": null,
"e": 3262,
"s": 3238,
"text": "imap_stream (Mandatory)"
},
{
"code": null,
"e": 3356,
"s": 3262,
"text": "This is a string value representing an IMAP stream, return value of the imap_open() function."
},
{
"code": null,
"e": 3372,
"s": 3356,
"text": "msg (Mandatory)"
},
{
"code": null,
"e": 3435,
"s": 3372,
"text": "This is an integer value representing the message/mail number."
},
{
"code": null,
"e": 3457,
"s": 3435,
"text": "fromlength (Optional)"
},
{
"code": null,
"e": 3533,
"s": 3457,
"text": "This is an integer value representing the length of the fetchfrom property."
},
{
"code": null,
"e": 3558,
"s": 3533,
"text": "subjectlength (Optional)"
},
{
"code": null,
"e": 3637,
"s": 3558,
"text": "This is an integer value representing the length of the fetchsubject property."
},
{
"code": null,
"e": 3793,
"s": 3637,
"text": "This function returns an object representing the headers of the specified message in case of success and a Boolean value which is FALSE in case of failure."
},
{
"code": null,
"e": 3882,
"s": 3793,
"text": "This function was first introduced in PHP Version 4 and works in all the later versions."
},
{
"code": null,
"e": 3959,
"s": 3882,
"text": "Following example demonstrates the usage of the imap_headerinfo() function −"
},
{
"code": null,
"e": 4546,
"s": 3959,
"text": "<html>\n <body>\n <?php\n //Establishing connection\n $url = \"{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX\";\n $id = \"tutorialspoint.test@gmail.com\";\n $pwd = \"cohondob_123\";\n $imap = imap_open($url, $id, $pwd);\n print(\"Connection established....\".\"<br>\");\n\t\t \n //Fetching the headers of all messages\t\t \n print(\"Headers of all messages: \".\"<br>\");\n $res = imap_headerinfo($imap, 2);\t\n print_r($res);\t\t \n //Closing the connection\n imap_close($imap); \n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 4588,
"s": 4546,
"text": "This will generate the following output −"
},
{
"code": null,
"e": 5501,
"s": 4588,
"text": "Connection established....\nHeaders of all messages:\nstdClass Object ( [date] => Thu, 22 Oct 2020 20:10:52 +0530 [Date] => Thu, \n22 Oct 2020 20:10:52 +0530 [message_id] => [toaddress] => \ntutorialspoint.test@gmail.com [to] => Array ( [0] => stdClass Object ( \n[mailbox] => tutorialspoint.test [host] => gmail.com ) ) [fromaddress] =>\nSender [from] => Array ( [0] => stdClass Object ( [personal] => Sender \n[mailbox] => sample.test[host] => gmail.com ) ) [reply_toaddress] => \nSender [reply_to] => Array ( [0] => stdClass Object ( [personal] => \nSender [mailbox] => sample.test[host] => gmail.com ) ) [senderaddress] =>\nSender [sender] => Array ( [0] => stdClass Object ( [personal] => Sender \n[mailbox] => sample.test[host] => gmail.com ) ) [Recent] => [Unseen] =\n> U [Flagged] => [Answered] => [Deleted] => [Draft] => [Msgno] =\n> 2 [MailDate] => 22-Oct-2020 14:41:31 +0000 [Size] => 4858 [udate] =>\n1603377691 )\n"
},
{
"code": null,
"e": 5554,
"s": 5501,
"text": "Following is another example of the above function −"
},
{
"code": null,
"e": 6465,
"s": 5554,
"text": "<html>\n <body>\n <?php\n //Establishing connection\n $url = \"{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX\";\n $id = \"tutorialspoint.test@gmail.com\";\n $pwd = \"cohondob_123\";\n $imap = imap_open($url, $id, $pwd);\n print(\"Connection established....\".\"<br>\");\n\t\t \n //Fetching the headers of all messages\t\t \n print(\"Headers of all messages: \".\"<br>\");\n \n for($i=1; $i<=imap_num_msg($imap); $i++) {\n $res = imap_headerinfo($imap, $i);\n print($res->toaddress);\n print(\"<br>\");\n print($res->fromaddress);\n print(\"<br>\");\n print($res->date);\n print(\"<br>\");\n print($res->Size);\t\n print(\"<br>\");\t\n print(\"<br>\");\t\t \n }\n //Closing the connection\n imap_close($imap); \n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 6507,
"s": 6465,
"text": "This will generate the following output −"
},
{
"code": null,
"e": 7084,
"s": 6507,
"text": "Connection established....\nHeaders of all messages:\ntutorialspoint.test@gmail.com\nSender\nThu, 22 Oct 2020 20:10:17 +0530\n4857\n\ntutorialspoint.test@gmail.com\nSender\nThu, 22 Oct 2020 20:10:52 +0530\n4858\n\ntutorialspoint.test@gmail.com\nSender\nSun, 25 Oct 2020 16:11:22 +0530\n4880\n\ntutorialspoint.test@gmail.com\nSender\nSun, 25 Oct 2020 17:22:41 +0530\n4882\n\ntutorialspoint.test@gmail.com\nSender\nSun, 25 Oct 2020 17:23:10 +0530\n4884\n\ntutorialspoint.test@gmail.com\nSender\nSun, 25 Oct 2020 17:24:25 +0530\n4883\n\ntutorialspoint.test@gmail.com\nSender\nMon, 26 Oct 2020 12:31:14 +0530\n4888\n"
},
{
"code": null,
"e": 7117,
"s": 7084,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 7133,
"s": 7117,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7166,
"s": 7133,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7177,
"s": 7166,
"text": " Syed Raza"
},
{
"code": null,
"e": 7212,
"s": 7177,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7229,
"s": 7212,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7262,
"s": 7229,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7277,
"s": 7262,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 7312,
"s": 7277,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 7324,
"s": 7312,
"text": " Azaz Patel"
},
{
"code": null,
"e": 7359,
"s": 7324,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7387,
"s": 7359,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 7394,
"s": 7387,
"text": " Print"
},
{
"code": null,
"e": 7405,
"s": 7394,
"text": " Add Notes"
}
] |
Computer Concepts - Programming Languages | A program is a set of instructions that help computer to perform tasks. This set of instructions is also called as scripts. Programs are executed by processor whereas scripts are interpreted. The languages that are used to write a program or set of instructions are called "Programming languages". Programming languages are broadly categorized into three types −
Machine level language
Assembly level language
High-level language
Machine language is lowest level of programming language. It handles binary data i.e. 0’s and 1’s. It directly interacts with system. Machine language is difficult for human beings to understand as it comprises combination of 0’s and 1’s. There is software which translate programs into machine level language. Examples include operating systems like Linux, UNIX, Windows, etc. In this language, there is no need of compilers and interpreters for conversion and hence the time consumption is less. However, it is not portable and non-readable to humans.
Assembly language is a middle-level language. It consists of a set of instructions in a specific format called commands. It uses symbols to represent field of instructions. It is very close to machine level language. The computer should have assembler to translate assembly level program to machine level program. Examples include ADA, PASCAL, etc. It is in human-readable format and takes lesser time to write a program and debug it. However, it is a machine dependent language.
High-level language uses format or language that is most familiar to users. The instructions in this language are called codes or scripts. The computer needs a compiler and interpreter to convert high-level language program to machine level language. Examples include C++, Python, Java, etc. It is easy to write a program using high level language and is less time-consuming. Debugging is also easy and is a human-readable language. Main disadvantages of this are that it takes lot of time for execution and occupies more space when compared to Assembly- or Machine-level languages. Following is a simple example for a high level language −
if age < 18 {
printf("You are not eligible to vote");
} else{
printf("You are eligible to vote");
}
107 Lectures
13.5 hours
Arnab Chakraborty
106 Lectures
8 hours
Arnab Chakraborty
99 Lectures
6 hours
Arnab Chakraborty
46 Lectures
2.5 hours
Shweta
70 Lectures
9 hours
Abhilash Nelson
52 Lectures
7 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2233,
"s": 1870,
"text": "A program is a set of instructions that help computer to perform tasks. This set of instructions is also called as scripts. Programs are executed by processor whereas scripts are interpreted. The languages that are used to write a program or set of instructions are called \"Programming languages\". Programming languages are broadly categorized into three types −"
},
{
"code": null,
"e": 2256,
"s": 2233,
"text": "Machine level language"
},
{
"code": null,
"e": 2280,
"s": 2256,
"text": "Assembly level language"
},
{
"code": null,
"e": 2300,
"s": 2280,
"text": "High-level language"
},
{
"code": null,
"e": 2854,
"s": 2300,
"text": "Machine language is lowest level of programming language. It handles binary data i.e. 0’s and 1’s. It directly interacts with system. Machine language is difficult for human beings to understand as it comprises combination of 0’s and 1’s. There is software which translate programs into machine level language. Examples include operating systems like Linux, UNIX, Windows, etc. In this language, there is no need of compilers and interpreters for conversion and hence the time consumption is less. However, it is not portable and non-readable to humans."
},
{
"code": null,
"e": 3334,
"s": 2854,
"text": "Assembly language is a middle-level language. It consists of a set of instructions in a specific format called commands. It uses symbols to represent field of instructions. It is very close to machine level language. The computer should have assembler to translate assembly level program to machine level program. Examples include ADA, PASCAL, etc. It is in human-readable format and takes lesser time to write a program and debug it. However, it is a machine dependent language."
},
{
"code": null,
"e": 3975,
"s": 3334,
"text": "High-level language uses format or language that is most familiar to users. The instructions in this language are called codes or scripts. The computer needs a compiler and interpreter to convert high-level language program to machine level language. Examples include C++, Python, Java, etc. It is easy to write a program using high level language and is less time-consuming. Debugging is also easy and is a human-readable language. Main disadvantages of this are that it takes lot of time for execution and occupies more space when compared to Assembly- or Machine-level languages. Following is a simple example for a high level language −"
},
{
"code": null,
"e": 4081,
"s": 3975,
"text": "if age < 18 {\n printf(\"You are not eligible to vote\");\n} else{\n printf(\"You are eligible to vote\");\n}"
},
{
"code": null,
"e": 4118,
"s": 4081,
"text": "\n 107 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 4137,
"s": 4118,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4171,
"s": 4137,
"text": "\n 106 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4190,
"s": 4171,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4223,
"s": 4190,
"text": "\n 99 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4242,
"s": 4223,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4277,
"s": 4242,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4285,
"s": 4277,
"text": " Shweta"
},
{
"code": null,
"e": 4318,
"s": 4285,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4335,
"s": 4318,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4368,
"s": 4335,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4390,
"s": 4368,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4397,
"s": 4390,
"text": " Print"
},
{
"code": null,
"e": 4408,
"s": 4397,
"text": " Add Notes"
}
] |
ReactJS UI Ant Design Table Component - GeeksforGeeks | 30 Jun, 2021
Ant Design Library has this component pre-built, and it is very easy to integrate as well. ReactJS UI Ant Design Table Component is used to display rows of data. It is used to display data in the form of table format. We can use the following approach in ReactJS to use the Ant Design Table Component.
Table Props:
bordered: It is used to indicate whether to show all table borders or not.
columns: It is used to denote the columns of the table.
components: It is used to override default table elements,
dataSource: It is used to denote the data record array to be displayed.
expandable: It is used to configure expandable content.
footer: It is used to denote the Table footer renderer.
getPopupContainer: It is the rendering container of dropdowns in the table.
loading: It is used to denote the loading status of the table.
locale: It is the i18n text including filter, sort, empty text, etc.
pagination: It is used for the configuration of pagination.
rowClassName: It is used to denote the row’s className.
rowKey: It is used to denote the row’s unique key.
rowSelection: It is used to denote the row selection config.
scroll: It is used to indicate whether the table can be scrollable or not.
showHeader: It is used to indicate whether to show table header or not.
showSorterTooltip: It is used for the header show next sorter direction tooltip.
size: It is used to denote the size of the table.
sortDirections: It is used to denote the sort directions.
sticky: It is used to set a sticky header and scroll bar.
summary: It is used to denote the summary content.
tableLayout: It is used to denote the table-layout attribute of the table element.
title: It is used to denote the table title renderer.
onChange: It is a callback function that is executed when pagination, filters, or sorter is changed.
onHeaderRow: It is used to set props on per header row.
onRow: It is used to set props per row.
Column Props:
align: It is used to specify which way that column is aligned.
className: It is used to denote the className of this column.
colSpan: It is used to denote the span of this column’s title.
dataIndex: It is used to display the field of the data record.
defaultFilteredValue: It is used to denote the default filtered values.
defaultSortOrder: It is used to denote the default order of sorted values.
editable: It is used to indicate whether a column can be edited.
ellipsis: It is used to denote the ellipsis cell content.
filterDropdown: It is used to customized filter overlay.
filterDropdownVisible: It is used to indicate whether filterDropdown is visible or not.
filtered: It is used to indicate whether the dataSource is filtered or not.
filteredValue: It is used to denote the controlled filtered value, filter icon will highlight.
filterIcon: It is used for the customized filter icon.
filterMultiple: It is used to indicate whether multiple filters can be selected or not.
filters: It is used to denote the filter menu config.
fixed: It is used to set columns to be fixed.
key: It is used to denote the unique key of this column.
render: It is the renderer of the table cell.
responsive: It is used to denote the list of breakpoints at which to display this column.
shouldCellUpdate: It is used to denote the control cell render logic.
showSorterTooltip: Used to override showSorterTooltip in table if header show next sorter direction tooltip.
sortDirections: It is used to sort directions in a Table and values could be ascend or descend.
sorter: It is a sort function for local sort.
sortOrder: It is used to denote the order of sorted values.
title: It is used to denote the title of this column.
width: It is used to width of this column.
onCell: It is used to set props on per cell.
onFilter: It is a callback function that determines if the row is displayed when filtered.
onFilterDropdownVisibleChange: Callback function that is triggered when filterDropdownVisible is changed
onHeaderCell: It is used to set props on per header cell.
ColumnGroup Props:
title: It is used to denote the title for the column group.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import "antd/dist/antd.css";import { Table } from 'antd'; export default function App() { // Sample Data for the table const dataSource = [ { key: '1', username: 'Gourav', age: 10 }, { key: '2', username: 'Kartik', age: 20 }, { key: '3', username: 'Madhu', age: 30 }, { key: '4', username: 'Karu', age: 40 }, { key: '5', username: 'Dinesh', age: 50 }, ]; // Sample Columns data const columns = [ { title: 'Username', dataIndex: 'username', key: 'username', }, { title: 'Age', dataIndex: 'age', key: 'age', }, ]; return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Table Component</h4> <Table dataSource={dataSource} columns={columns} /> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://ant.design/components/table/
ReactJS-Ant Design
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ? | [
{
"code": null,
"e": 33847,
"s": 33819,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 34149,
"s": 33847,
"text": "Ant Design Library has this component pre-built, and it is very easy to integrate as well. ReactJS UI Ant Design Table Component is used to display rows of data. It is used to display data in the form of table format. We can use the following approach in ReactJS to use the Ant Design Table Component."
},
{
"code": null,
"e": 34162,
"s": 34149,
"text": "Table Props:"
},
{
"code": null,
"e": 34237,
"s": 34162,
"text": "bordered: It is used to indicate whether to show all table borders or not."
},
{
"code": null,
"e": 34295,
"s": 34237,
"text": "columns: It is used to denote the columns of the table. "
},
{
"code": null,
"e": 34356,
"s": 34295,
"text": "components: It is used to override default table elements, "
},
{
"code": null,
"e": 34428,
"s": 34356,
"text": "dataSource: It is used to denote the data record array to be displayed."
},
{
"code": null,
"e": 34486,
"s": 34428,
"text": "expandable: It is used to configure expandable content. "
},
{
"code": null,
"e": 34544,
"s": 34486,
"text": "footer: It is used to denote the Table footer renderer. "
},
{
"code": null,
"e": 34622,
"s": 34544,
"text": "getPopupContainer: It is the rendering container of dropdowns in the table. "
},
{
"code": null,
"e": 34686,
"s": 34622,
"text": "loading: It is used to denote the loading status of the table. "
},
{
"code": null,
"e": 34755,
"s": 34686,
"text": "locale: It is the i18n text including filter, sort, empty text, etc."
},
{
"code": null,
"e": 34817,
"s": 34755,
"text": "pagination: It is used for the configuration of pagination. "
},
{
"code": null,
"e": 34873,
"s": 34817,
"text": "rowClassName: It is used to denote the row’s className."
},
{
"code": null,
"e": 34924,
"s": 34873,
"text": "rowKey: It is used to denote the row’s unique key."
},
{
"code": null,
"e": 34987,
"s": 34924,
"text": "rowSelection: It is used to denote the row selection config. "
},
{
"code": null,
"e": 35062,
"s": 34987,
"text": "scroll: It is used to indicate whether the table can be scrollable or not."
},
{
"code": null,
"e": 35134,
"s": 35062,
"text": "showHeader: It is used to indicate whether to show table header or not."
},
{
"code": null,
"e": 35217,
"s": 35134,
"text": "showSorterTooltip: It is used for the header show next sorter direction tooltip. "
},
{
"code": null,
"e": 35267,
"s": 35217,
"text": "size: It is used to denote the size of the table."
},
{
"code": null,
"e": 35325,
"s": 35267,
"text": "sortDirections: It is used to denote the sort directions."
},
{
"code": null,
"e": 35385,
"s": 35325,
"text": "sticky: It is used to set a sticky header and scroll bar. "
},
{
"code": null,
"e": 35438,
"s": 35385,
"text": "summary: It is used to denote the summary content. "
},
{
"code": null,
"e": 35523,
"s": 35438,
"text": "tableLayout: It is used to denote the table-layout attribute of the table element. "
},
{
"code": null,
"e": 35579,
"s": 35523,
"text": "title: It is used to denote the table title renderer. "
},
{
"code": null,
"e": 35681,
"s": 35579,
"text": "onChange: It is a callback function that is executed when pagination, filters, or sorter is changed. "
},
{
"code": null,
"e": 35739,
"s": 35681,
"text": "onHeaderRow: It is used to set props on per header row. "
},
{
"code": null,
"e": 35780,
"s": 35739,
"text": "onRow: It is used to set props per row. "
},
{
"code": null,
"e": 35794,
"s": 35780,
"text": "Column Props:"
},
{
"code": null,
"e": 35857,
"s": 35794,
"text": "align: It is used to specify which way that column is aligned."
},
{
"code": null,
"e": 35921,
"s": 35857,
"text": "className: It is used to denote the className of this column. "
},
{
"code": null,
"e": 35986,
"s": 35921,
"text": "colSpan: It is used to denote the span of this column’s title. "
},
{
"code": null,
"e": 36049,
"s": 35986,
"text": "dataIndex: It is used to display the field of the data record."
},
{
"code": null,
"e": 36121,
"s": 36049,
"text": "defaultFilteredValue: It is used to denote the default filtered values."
},
{
"code": null,
"e": 36198,
"s": 36121,
"text": "defaultSortOrder: It is used to denote the default order of sorted values. "
},
{
"code": null,
"e": 36265,
"s": 36198,
"text": "editable: It is used to indicate whether a column can be edited. "
},
{
"code": null,
"e": 36323,
"s": 36265,
"text": "ellipsis: It is used to denote the ellipsis cell content."
},
{
"code": null,
"e": 36382,
"s": 36323,
"text": "filterDropdown: It is used to customized filter overlay. "
},
{
"code": null,
"e": 36470,
"s": 36382,
"text": "filterDropdownVisible: It is used to indicate whether filterDropdown is visible or not."
},
{
"code": null,
"e": 36546,
"s": 36470,
"text": "filtered: It is used to indicate whether the dataSource is filtered or not."
},
{
"code": null,
"e": 36641,
"s": 36546,
"text": "filteredValue: It is used to denote the controlled filtered value, filter icon will highlight."
},
{
"code": null,
"e": 36696,
"s": 36641,
"text": "filterIcon: It is used for the customized filter icon."
},
{
"code": null,
"e": 36784,
"s": 36696,
"text": "filterMultiple: It is used to indicate whether multiple filters can be selected or not."
},
{
"code": null,
"e": 36840,
"s": 36784,
"text": "filters: It is used to denote the filter menu config. "
},
{
"code": null,
"e": 36886,
"s": 36840,
"text": "fixed: It is used to set columns to be fixed."
},
{
"code": null,
"e": 36943,
"s": 36886,
"text": "key: It is used to denote the unique key of this column."
},
{
"code": null,
"e": 36991,
"s": 36943,
"text": "render: It is the renderer of the table cell. "
},
{
"code": null,
"e": 37083,
"s": 36991,
"text": "responsive: It is used to denote the list of breakpoints at which to display this column. "
},
{
"code": null,
"e": 37153,
"s": 37083,
"text": "shouldCellUpdate: It is used to denote the control cell render logic."
},
{
"code": null,
"e": 37263,
"s": 37153,
"text": "showSorterTooltip: Used to override showSorterTooltip in table if header show next sorter direction tooltip. "
},
{
"code": null,
"e": 37359,
"s": 37263,
"text": "sortDirections: It is used to sort directions in a Table and values could be ascend or descend."
},
{
"code": null,
"e": 37405,
"s": 37359,
"text": "sorter: It is a sort function for local sort."
},
{
"code": null,
"e": 37465,
"s": 37405,
"text": "sortOrder: It is used to denote the order of sorted values."
},
{
"code": null,
"e": 37521,
"s": 37465,
"text": "title: It is used to denote the title of this column. "
},
{
"code": null,
"e": 37566,
"s": 37521,
"text": "width: It is used to width of this column. "
},
{
"code": null,
"e": 37613,
"s": 37566,
"text": "onCell: It is used to set props on per cell. "
},
{
"code": null,
"e": 37706,
"s": 37613,
"text": "onFilter: It is a callback function that determines if the row is displayed when filtered. "
},
{
"code": null,
"e": 37811,
"s": 37706,
"text": "onFilterDropdownVisibleChange: Callback function that is triggered when filterDropdownVisible is changed"
},
{
"code": null,
"e": 37870,
"s": 37811,
"text": "onHeaderCell: It is used to set props on per header cell. "
},
{
"code": null,
"e": 37889,
"s": 37870,
"text": "ColumnGroup Props:"
},
{
"code": null,
"e": 37949,
"s": 37889,
"text": "title: It is used to denote the title for the column group."
},
{
"code": null,
"e": 38001,
"s": 37951,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 38096,
"s": 38001,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 38160,
"s": 38096,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 38192,
"s": 38160,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 38305,
"s": 38192,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 38405,
"s": 38305,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 38419,
"s": 38405,
"text": "cd foldername"
},
{
"code": null,
"e": 38540,
"s": 38419,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install antd"
},
{
"code": null,
"e": 38645,
"s": 38540,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 38662,
"s": 38645,
"text": "npm install antd"
},
{
"code": null,
"e": 38714,
"s": 38662,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 38732,
"s": 38714,
"text": "Project Structure"
},
{
"code": null,
"e": 38862,
"s": 38732,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 38869,
"s": 38862,
"text": "App.js"
},
{
"code": "import React from 'react'import \"antd/dist/antd.css\";import { Table } from 'antd'; export default function App() { // Sample Data for the table const dataSource = [ { key: '1', username: 'Gourav', age: 10 }, { key: '2', username: 'Kartik', age: 20 }, { key: '3', username: 'Madhu', age: 30 }, { key: '4', username: 'Karu', age: 40 }, { key: '5', username: 'Dinesh', age: 50 }, ]; // Sample Columns data const columns = [ { title: 'Username', dataIndex: 'username', key: 'username', }, { title: 'Age', dataIndex: 'age', key: 'age', }, ]; return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Table Component</h4> <Table dataSource={dataSource} columns={columns} /> </div> );}",
"e": 39796,
"s": 38869,
"text": null
},
{
"code": null,
"e": 39909,
"s": 39796,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 39919,
"s": 39909,
"text": "npm start"
},
{
"code": null,
"e": 40018,
"s": 39919,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 40066,
"s": 40018,
"text": "Reference: https://ant.design/components/table/"
},
{
"code": null,
"e": 40085,
"s": 40066,
"text": "ReactJS-Ant Design"
},
{
"code": null,
"e": 40096,
"s": 40085,
"text": "JavaScript"
},
{
"code": null,
"e": 40104,
"s": 40096,
"text": "ReactJS"
},
{
"code": null,
"e": 40121,
"s": 40104,
"text": "Web Technologies"
},
{
"code": null,
"e": 40219,
"s": 40121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40228,
"s": 40219,
"text": "Comments"
},
{
"code": null,
"e": 40241,
"s": 40228,
"text": "Old Comments"
},
{
"code": null,
"e": 40302,
"s": 40241,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 40347,
"s": 40302,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40419,
"s": 40347,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 40488,
"s": 40419,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 40515,
"s": 40488,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 40558,
"s": 40515,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 40603,
"s": 40558,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 40668,
"s": 40603,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 40709,
"s": 40668,
"text": "Create a Responsive Navbar using ReactJS"
}
] |
Sum of similarities of string with all of its suffixes - GeeksforGeeks | 11 Aug, 2021
Given a string str, the task is to find the sum of the similarities of str with each of its suffixes. The similarity of strings A and B is the length of the longest prefix common to both the strings i.e. the similarity of “aabc” and “aab” is 3 and that of “qwer” and “abc” is 0.Examples:
Input: str = “ababa” Output: 9 The suffixes of str are “ababa”, “baba”, “aba”, “ba” and “a”. The similarities of these strings with the original string “ababa” are 5, 0, 3, 0 & 1 respectively. Thus, the answer is 5 + 0 + 3 + 0 + 1 = 9.Input: str = “aaabaab” Output: 13
Approach: Compute Z-array using Z-algorithm – For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is the length of the string. Now, sum all the elements of the Z-array to get the required sum of the similarities.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>#include <string>#include <vector>using namespace std; // Function to calculate the Z-array for the given stringvoid getZarr(string str, int n, int Z[]){ int L, R, k; // [L, R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } else { // k = i-L so k corresponds to number which // matches in [L, R] interval. k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", i = 3, R = 5 // and L = 2 if (Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = "aaaaaa" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } }} // Function to return the similarity sumint sumSimilarities(string s, int n){ int Z[n] = { 0 }; // Compute the Z-array for the given string getZarr(s, n, Z); int total = n; // Summation of the Z-values for (int i = 1; i < n; i++) total += Z[i]; return total;} // Driver codeint main(){ string s = "ababa"; int n = s.length(); cout << sumSimilarities(s, n); return 0;}
// Java implementation of the above approach public class GFG{ // Function to calculate the Z-array for the given stringstatic void getZarr(String str, int n, int Z[]){ int L, R, k; // [L, R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while (R < n && str.charAt(R - L) == str.charAt(R)) R++; Z[i] = R - L; R--; } else { // k = i-L so k corresponds to number which // matches in [L, R] interval. k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", i = 3, R = 5 // and L = 2 if (Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = "aaaaaa" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R < n && str.charAt(R - L) == str.charAt(R)) R++; Z[i] = R - L; R--; } } }} // Function to return the similarity sumstatic int sumSimilarities(String s, int n){ int Z[] = new int[n] ; // Compute the Z-array for the given string getZarr(s, n, Z); int total = n; // Summation of the Z-values for (int i = 1; i < n; i++) total += Z[i]; return total;} // Driver codepublic static void main(String []args){ String s = "ababa"; int n = s.length(); System.out.println(sumSimilarities(s, n));}// This code is contributed by Ryuga}
# Python3 implementation of the approachdef getZarr(s, n, Z): L, R, k = 0, 0, 0 # [L, R] make a window which matches # with prefix of s for i in range(n): # if i>R nothing matches so we will # calculate Z[i] using naive way. if i > R: L, R = i, i ''' R-L = 0 in starting, so it will start checking from 0'th index. For example, for "ababab" and i = 1, the value of R remains 0 and Z[i] becomes 0. For string "aaaaaa" and i = 1, Z[i] and R become 5 ''' while R < n and s[R - L] == s[R]: R += 1 Z[i] = R - L R -= 1 else: # k = i-L so k corresponds to number # which matches in [L, R] interval. k = i - L # if Z[k] is less than remaining interval # then Z[i] will be equal to Z[k]. # For example, str = "ababab", i = 3, R = 5 # and L = 2 if Z[k] < R - i + 1: Z[i] = Z[k] else: L = i while R < n and s[R - L] == s[R]: R += 1 Z[i] = R - L R -= 1 def sumSimilarities(s, n): Z = [0 for i in range(n)] # Compute the Z-array for the # given string getZarr(s, n, Z) total = n # summation of the Z-values for i in range(n): total += Z[i] return total # Driver Codes = "ababa" n = len(s) print(sumSimilarities(s, n)) # This code is contributed# by Mohit kumar 29
//C# implementation of the above approachusing System; public class GFG{ // Function to calculate the Z-array for the given stringstatic void getZarr(string str, int n, int []Z){ int L, R, k; // [L, R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } else { // k = i-L so k corresponds to number which // matches in [L, R] interval. k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", i = 3, R = 5 // and L = 2 if (Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = "aaaaaa" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } }} // Function to return the similarity sumstatic int sumSimilarities(string s, int n){ int []Z = new int[n] ; // Compute the Z-array for the given string getZarr(s, n, Z); int total = n; // Summation of the Z-values for (int i = 1; i < n; i++) total += Z[i]; return total;} // Driver code static public void Main (){ string s = "ababa"; int n = s.Length; Console.WriteLine(sumSimilarities(s, n));}// This code is contributed by ajit.}
<script> // Javascript implementation of // the above approach // Function to calculate the Z-array // for the given string function getZarr(str, n, Z) { let L, R, k; // [L, R] make a window which matches // with prefix of s L = R = 0; for (let i = 1; i < n; ++i) { // if i>R nothing matches so // we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } else { // k = i-L so k corresponds // to number which // matches in [L, R] interval. k = i - L; // if Z[k] is less than // remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", // i = 3, R = 5 // and L = 2 if (Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = "aaaaaa" // and i = 2, R is 5, // L is 0 else { // else start from R and // check manually L = i; while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } } } // Function to return the similarity sum function sumSimilarities(s, n) { let Z = new Array(n); Z.fill(0); // Compute the Z-array for the given string getZarr(s, n, Z); let total = n; // Summation of the Z-values for (let i = 1; i < n; i++) total += Z[i]; return total; } let s = "ababa"; let n = s.length; document.write(sumSimilarities(s, n)); </script>
9
Time Complexity: ON) Auxiliary Space: O(N)
ankthon
jit_t
mohit kumar 29
nidhi_biet
divyeshrabadiya07
pankajsharmagfg
C-String-Question
Technical Scripter 2018
Algorithms
Competitive Programming
Pattern Searching
Strings
Strings
Pattern Searching
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
Arrow operator -> in C/C++ with Examples
Practice for cracking any coding interview
Competitive Programming - A Complete Guide
Bits manipulation (Important tactics)
String hashing using Polynomial rolling hash function | [
{
"code": null,
"e": 24619,
"s": 24591,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 24909,
"s": 24619,
"text": "Given a string str, the task is to find the sum of the similarities of str with each of its suffixes. The similarity of strings A and B is the length of the longest prefix common to both the strings i.e. the similarity of “aabc” and “aab” is 3 and that of “qwer” and “abc” is 0.Examples: "
},
{
"code": null,
"e": 25180,
"s": 24909,
"text": "Input: str = “ababa” Output: 9 The suffixes of str are “ababa”, “baba”, “aba”, “ba” and “a”. The similarities of these strings with the original string “ababa” are 5, 0, 3, 0 & 1 respectively. Thus, the answer is 5 + 0 + 3 + 0 + 1 = 9.Input: str = “aaabaab” Output: 13 "
},
{
"code": null,
"e": 25611,
"s": 25182,
"text": "Approach: Compute Z-array using Z-algorithm – For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is the length of the string. Now, sum all the elements of the Z-array to get the required sum of the similarities.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25615,
"s": 25611,
"text": "C++"
},
{
"code": null,
"e": 25620,
"s": 25615,
"text": "Java"
},
{
"code": null,
"e": 25628,
"s": 25620,
"text": "Python3"
},
{
"code": null,
"e": 25631,
"s": 25628,
"text": "C#"
},
{
"code": null,
"e": 25642,
"s": 25631,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>#include <string>#include <vector>using namespace std; // Function to calculate the Z-array for the given stringvoid getZarr(string str, int n, int Z[]){ int L, R, k; // [L, R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for \"ababab\" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // \"aaaaaa\" and i = 1, Z[i] and R become 5 while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } else { // k = i-L so k corresponds to number which // matches in [L, R] interval. k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = \"ababab\", i = 3, R = 5 // and L = 2 if (Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = \"aaaaaa\" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } }} // Function to return the similarity sumint sumSimilarities(string s, int n){ int Z[n] = { 0 }; // Compute the Z-array for the given string getZarr(s, n, Z); int total = n; // Summation of the Z-values for (int i = 1; i < n; i++) total += Z[i]; return total;} // Driver codeint main(){ string s = \"ababa\"; int n = s.length(); cout << sumSimilarities(s, n); return 0;}",
"e": 27612,
"s": 25642,
"text": null
},
{
"code": "// Java implementation of the above approach public class GFG{ // Function to calculate the Z-array for the given stringstatic void getZarr(String str, int n, int Z[]){ int L, R, k; // [L, R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for \"ababab\" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // \"aaaaaa\" and i = 1, Z[i] and R become 5 while (R < n && str.charAt(R - L) == str.charAt(R)) R++; Z[i] = R - L; R--; } else { // k = i-L so k corresponds to number which // matches in [L, R] interval. k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = \"ababab\", i = 3, R = 5 // and L = 2 if (Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = \"aaaaaa\" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R < n && str.charAt(R - L) == str.charAt(R)) R++; Z[i] = R - L; R--; } } }} // Function to return the similarity sumstatic int sumSimilarities(String s, int n){ int Z[] = new int[n] ; // Compute the Z-array for the given string getZarr(s, n, Z); int total = n; // Summation of the Z-values for (int i = 1; i < n; i++) total += Z[i]; return total;} // Driver codepublic static void main(String []args){ String s = \"ababa\"; int n = s.length(); System.out.println(sumSimilarities(s, n));}// This code is contributed by Ryuga}",
"e": 29645,
"s": 27612,
"text": null
},
{
"code": "# Python3 implementation of the approachdef getZarr(s, n, Z): L, R, k = 0, 0, 0 # [L, R] make a window which matches # with prefix of s for i in range(n): # if i>R nothing matches so we will # calculate Z[i] using naive way. if i > R: L, R = i, i ''' R-L = 0 in starting, so it will start checking from 0'th index. For example, for \"ababab\" and i = 1, the value of R remains 0 and Z[i] becomes 0. For string \"aaaaaa\" and i = 1, Z[i] and R become 5 ''' while R < n and s[R - L] == s[R]: R += 1 Z[i] = R - L R -= 1 else: # k = i-L so k corresponds to number # which matches in [L, R] interval. k = i - L # if Z[k] is less than remaining interval # then Z[i] will be equal to Z[k]. # For example, str = \"ababab\", i = 3, R = 5 # and L = 2 if Z[k] < R - i + 1: Z[i] = Z[k] else: L = i while R < n and s[R - L] == s[R]: R += 1 Z[i] = R - L R -= 1 def sumSimilarities(s, n): Z = [0 for i in range(n)] # Compute the Z-array for the # given string getZarr(s, n, Z) total = n # summation of the Z-values for i in range(n): total += Z[i] return total # Driver Codes = \"ababa\" n = len(s) print(sumSimilarities(s, n)) # This code is contributed# by Mohit kumar 29",
"e": 31275,
"s": 29645,
"text": null
},
{
"code": "//C# implementation of the above approachusing System; public class GFG{ // Function to calculate the Z-array for the given stringstatic void getZarr(string str, int n, int []Z){ int L, R, k; // [L, R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for \"ababab\" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // \"aaaaaa\" and i = 1, Z[i] and R become 5 while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } else { // k = i-L so k corresponds to number which // matches in [L, R] interval. k = i - L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = \"ababab\", i = 3, R = 5 // and L = 2 if (Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = \"aaaaaa\" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } }} // Function to return the similarity sumstatic int sumSimilarities(string s, int n){ int []Z = new int[n] ; // Compute the Z-array for the given string getZarr(s, n, Z); int total = n; // Summation of the Z-values for (int i = 1; i < n; i++) total += Z[i]; return total;} // Driver code static public void Main (){ string s = \"ababa\"; int n = s.Length; Console.WriteLine(sumSimilarities(s, n));}// This code is contributed by ajit.}",
"e": 33291,
"s": 31275,
"text": null
},
{
"code": "<script> // Javascript implementation of // the above approach // Function to calculate the Z-array // for the given string function getZarr(str, n, Z) { let L, R, k; // [L, R] make a window which matches // with prefix of s L = R = 0; for (let i = 1; i < n; ++i) { // if i>R nothing matches so // we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for \"ababab\" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // \"aaaaaa\" and i = 1, Z[i] and R become 5 while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } else { // k = i-L so k corresponds // to number which // matches in [L, R] interval. k = i - L; // if Z[k] is less than // remaining interval // then Z[i] will be equal to Z[k]. // For example, str = \"ababab\", // i = 3, R = 5 // and L = 2 if (Z[k] < R - i + 1) Z[i] = Z[k]; // For example str = \"aaaaaa\" // and i = 2, R is 5, // L is 0 else { // else start from R and // check manually L = i; while (R < n && str[R - L] == str[R]) R++; Z[i] = R - L; R--; } } } } // Function to return the similarity sum function sumSimilarities(s, n) { let Z = new Array(n); Z.fill(0); // Compute the Z-array for the given string getZarr(s, n, Z); let total = n; // Summation of the Z-values for (let i = 1; i < n; i++) total += Z[i]; return total; } let s = \"ababa\"; let n = s.length; document.write(sumSimilarities(s, n)); </script>",
"e": 35559,
"s": 33291,
"text": null
},
{
"code": null,
"e": 35561,
"s": 35559,
"text": "9"
},
{
"code": null,
"e": 35607,
"s": 35563,
"text": "Time Complexity: ON) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 35615,
"s": 35607,
"text": "ankthon"
},
{
"code": null,
"e": 35621,
"s": 35615,
"text": "jit_t"
},
{
"code": null,
"e": 35636,
"s": 35621,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35647,
"s": 35636,
"text": "nidhi_biet"
},
{
"code": null,
"e": 35665,
"s": 35647,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 35681,
"s": 35665,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 35699,
"s": 35681,
"text": "C-String-Question"
},
{
"code": null,
"e": 35723,
"s": 35699,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 35734,
"s": 35723,
"text": "Algorithms"
},
{
"code": null,
"e": 35758,
"s": 35734,
"text": "Competitive Programming"
},
{
"code": null,
"e": 35776,
"s": 35758,
"text": "Pattern Searching"
},
{
"code": null,
"e": 35784,
"s": 35776,
"text": "Strings"
},
{
"code": null,
"e": 35792,
"s": 35784,
"text": "Strings"
},
{
"code": null,
"e": 35810,
"s": 35792,
"text": "Pattern Searching"
},
{
"code": null,
"e": 35821,
"s": 35810,
"text": "Algorithms"
},
{
"code": null,
"e": 35919,
"s": 35821,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35928,
"s": 35919,
"text": "Comments"
},
{
"code": null,
"e": 35941,
"s": 35928,
"text": "Old Comments"
},
{
"code": null,
"e": 35990,
"s": 35941,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 36019,
"s": 35990,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 36046,
"s": 36019,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 36094,
"s": 36046,
"text": "Uniform-Cost Search (Dijkstra for large Graphs)"
},
{
"code": null,
"e": 36119,
"s": 36094,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36160,
"s": 36119,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 36203,
"s": 36160,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 36246,
"s": 36203,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 36284,
"s": 36246,
"text": "Bits manipulation (Important tactics)"
}
] |
How Important is the K in KNN Algorithm | by Soner Yıldırım | Towards Data Science | K-nearest neighbors (KNN) is a supervised machine learning algorithm that can be used to solve both classification and regression tasks.
It is based on a very simple idea. The value of a data point is determined by the data points around it.
The value of a data point is determined by the data points around it.
The number of data points that are taken into consideration is determined by the k value. Thus, the k value is the core of the algorithm.
KNN classifier determines the class of a data point by the majority voting principle. If k is set to 5, the classes of 5 closest points are checked. Prediction is done according to the majority class. Similarly, KNN regression takes the mean value of 5 closest points.
In this article, we will examine the importance of the k value for a classification task.
Let’s create a sample classification dataset by using the make_classification function of Scikit-learn.
import numpy as npimport pandas as pdfrom sklearn.datasets import make_classificationX, y = make_classification( n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_classes=2, class_sep=0.8)
The dataset contains 1000 samples that belong to 2 classes. Let’s also create a scatter plot of the data points (i.e. samples).
import matplotlib.pyplot as pltplt.figure(figsize=(12,8))plt.scatter(X[:,0], X[:,1], c=y)
Selecting the optimal k value is the essential requirement to create a decent and accurate knn model.
If k is selected to be too low, the model becomes too specific and fails to generalize well. It also tends to be sensitive to noise. The model accomplishes a high accuracy on train set but will be a poor predictor on new, previously unseen data points. Therefore, we are likely to end up with an overfit model.
If k is selected to be too large, the model becomes too generalized and fails to accurately predict the data points in both train and test sets. This situation is known as underfitting.
We can now create two different knn models with k values 1 and 50. We will then create scatter plots of the predictions to see the difference.
The first step is to split the dataset into train and test subsets.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
The first model is knn with k equals 1.
from sklearn.neighbors import KNeighborsClassifierknn1 = KNeighborsClassifier(n_neighbors=1)knn1.fit(X_train, y_train)predict1 = knn1.predict(X_test)plt.figure(figsize=(12,8))plt.title("KNN with k=1", fontsize=16)plt.scatter(X_test[:,0], X_test[:,1], c=predict1)
We can create the next model just by changing the n_neighbors parameter to 50. Here are the predictions of this model on the test set.
You can see how the generalization changes when k is increased.
What we need is not a too generalized or a too specific model. The goal is to create a robust and accurate model.
An overfit model (too specific) is sensitive to slight changes in the values of data points. Thus, the predictions can change dramatically after very small changes in the data points.
An underfit model (too general) is likely to have poor performance on both train and test subsets.
Unfortunately, there is not a go-to solution to find the optimal k value. It depends on the underlying structure of the dataset. However, there are tools that can help us in finding the optimal k value.
The GridSearchCV function can be used to create, train, and evaluate models with different hyperparameter values. The k is the most important hyperparameter of the knn algorithm.
We will create a GridSearchCV object to evaluate the performance of 20 different knn models with k values changing from 1 to 20. The parameter values are passed to param_grid parameter as a dictionary.
from sklearn.model_selection import GridSearchCVknn = GridSearchCV( estimator = KNeighborsClassifier(), param_grid = {'n_neighbors': np.arange(1,21)}, scoring='neg_log_loss', cv = 5)
You can use any scoring metric of scikit-learn. I have used the log loss which is a commonly used metric for classification tasks.
We can now fit the dataset to the GridSearchCV object. We do not need to split train and test subsets because a 5-fold cross validation is applied.
knn.fit(X, y)
We can access the mean test score of cross validation for each k values.
scores = pd.Series(abs(knn.cv_results_['mean_test_score']))scores.index = np.arange(1,21)
I prefer to save the results in a pandas series to be able to easily plot them. Let’s plot the scores v
scores.plot(figsize=(12,8))plt.title("Log loss of knn with k vales from 1 to 20", fontsize=16)
The loss on the test set does not seem to improve by much after the k value of 10. A good practice is to select the value that the steepness of curve changes.
This plot does not directly tells the optimal k value but it sure narrows down the choices.
The knn algorithm is a widely-used algorithm. It is simple and easy to interpret. Since it does not make any assumption, it can be used to solve non-linear tasks as well.
On the negative side, we can say that the knn algorithm becomes very slow as the number of data points increases because the model needs to store all data points. Due to this reason, it is also not memory efficient.
Finally, it is sensitive to outliers because outliers also have a vote in decisions.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 309,
"s": 172,
"text": "K-nearest neighbors (KNN) is a supervised machine learning algorithm that can be used to solve both classification and regression tasks."
},
{
"code": null,
"e": 414,
"s": 309,
"text": "It is based on a very simple idea. The value of a data point is determined by the data points around it."
},
{
"code": null,
"e": 484,
"s": 414,
"text": "The value of a data point is determined by the data points around it."
},
{
"code": null,
"e": 622,
"s": 484,
"text": "The number of data points that are taken into consideration is determined by the k value. Thus, the k value is the core of the algorithm."
},
{
"code": null,
"e": 891,
"s": 622,
"text": "KNN classifier determines the class of a data point by the majority voting principle. If k is set to 5, the classes of 5 closest points are checked. Prediction is done according to the majority class. Similarly, KNN regression takes the mean value of 5 closest points."
},
{
"code": null,
"e": 981,
"s": 891,
"text": "In this article, we will examine the importance of the k value for a classification task."
},
{
"code": null,
"e": 1085,
"s": 981,
"text": "Let’s create a sample classification dataset by using the make_classification function of Scikit-learn."
},
{
"code": null,
"e": 1300,
"s": 1085,
"text": "import numpy as npimport pandas as pdfrom sklearn.datasets import make_classificationX, y = make_classification( n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_classes=2, class_sep=0.8)"
},
{
"code": null,
"e": 1428,
"s": 1300,
"text": "The dataset contains 1000 samples that belong to 2 classes. Let’s also create a scatter plot of the data points (i.e. samples)."
},
{
"code": null,
"e": 1518,
"s": 1428,
"text": "import matplotlib.pyplot as pltplt.figure(figsize=(12,8))plt.scatter(X[:,0], X[:,1], c=y)"
},
{
"code": null,
"e": 1620,
"s": 1518,
"text": "Selecting the optimal k value is the essential requirement to create a decent and accurate knn model."
},
{
"code": null,
"e": 1931,
"s": 1620,
"text": "If k is selected to be too low, the model becomes too specific and fails to generalize well. It also tends to be sensitive to noise. The model accomplishes a high accuracy on train set but will be a poor predictor on new, previously unseen data points. Therefore, we are likely to end up with an overfit model."
},
{
"code": null,
"e": 2117,
"s": 1931,
"text": "If k is selected to be too large, the model becomes too generalized and fails to accurately predict the data points in both train and test sets. This situation is known as underfitting."
},
{
"code": null,
"e": 2260,
"s": 2117,
"text": "We can now create two different knn models with k values 1 and 50. We will then create scatter plots of the predictions to see the difference."
},
{
"code": null,
"e": 2328,
"s": 2260,
"text": "The first step is to split the dataset into train and test subsets."
},
{
"code": null,
"e": 2453,
"s": 2328,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)"
},
{
"code": null,
"e": 2493,
"s": 2453,
"text": "The first model is knn with k equals 1."
},
{
"code": null,
"e": 2756,
"s": 2493,
"text": "from sklearn.neighbors import KNeighborsClassifierknn1 = KNeighborsClassifier(n_neighbors=1)knn1.fit(X_train, y_train)predict1 = knn1.predict(X_test)plt.figure(figsize=(12,8))plt.title(\"KNN with k=1\", fontsize=16)plt.scatter(X_test[:,0], X_test[:,1], c=predict1)"
},
{
"code": null,
"e": 2891,
"s": 2756,
"text": "We can create the next model just by changing the n_neighbors parameter to 50. Here are the predictions of this model on the test set."
},
{
"code": null,
"e": 2955,
"s": 2891,
"text": "You can see how the generalization changes when k is increased."
},
{
"code": null,
"e": 3069,
"s": 2955,
"text": "What we need is not a too generalized or a too specific model. The goal is to create a robust and accurate model."
},
{
"code": null,
"e": 3253,
"s": 3069,
"text": "An overfit model (too specific) is sensitive to slight changes in the values of data points. Thus, the predictions can change dramatically after very small changes in the data points."
},
{
"code": null,
"e": 3352,
"s": 3253,
"text": "An underfit model (too general) is likely to have poor performance on both train and test subsets."
},
{
"code": null,
"e": 3555,
"s": 3352,
"text": "Unfortunately, there is not a go-to solution to find the optimal k value. It depends on the underlying structure of the dataset. However, there are tools that can help us in finding the optimal k value."
},
{
"code": null,
"e": 3734,
"s": 3555,
"text": "The GridSearchCV function can be used to create, train, and evaluate models with different hyperparameter values. The k is the most important hyperparameter of the knn algorithm."
},
{
"code": null,
"e": 3936,
"s": 3734,
"text": "We will create a GridSearchCV object to evaluate the performance of 20 different knn models with k values changing from 1 to 20. The parameter values are passed to param_grid parameter as a dictionary."
},
{
"code": null,
"e": 4135,
"s": 3936,
"text": "from sklearn.model_selection import GridSearchCVknn = GridSearchCV( estimator = KNeighborsClassifier(), param_grid = {'n_neighbors': np.arange(1,21)}, scoring='neg_log_loss', cv = 5)"
},
{
"code": null,
"e": 4266,
"s": 4135,
"text": "You can use any scoring metric of scikit-learn. I have used the log loss which is a commonly used metric for classification tasks."
},
{
"code": null,
"e": 4414,
"s": 4266,
"text": "We can now fit the dataset to the GridSearchCV object. We do not need to split train and test subsets because a 5-fold cross validation is applied."
},
{
"code": null,
"e": 4428,
"s": 4414,
"text": "knn.fit(X, y)"
},
{
"code": null,
"e": 4501,
"s": 4428,
"text": "We can access the mean test score of cross validation for each k values."
},
{
"code": null,
"e": 4591,
"s": 4501,
"text": "scores = pd.Series(abs(knn.cv_results_['mean_test_score']))scores.index = np.arange(1,21)"
},
{
"code": null,
"e": 4695,
"s": 4591,
"text": "I prefer to save the results in a pandas series to be able to easily plot them. Let’s plot the scores v"
},
{
"code": null,
"e": 4790,
"s": 4695,
"text": "scores.plot(figsize=(12,8))plt.title(\"Log loss of knn with k vales from 1 to 20\", fontsize=16)"
},
{
"code": null,
"e": 4949,
"s": 4790,
"text": "The loss on the test set does not seem to improve by much after the k value of 10. A good practice is to select the value that the steepness of curve changes."
},
{
"code": null,
"e": 5041,
"s": 4949,
"text": "This plot does not directly tells the optimal k value but it sure narrows down the choices."
},
{
"code": null,
"e": 5212,
"s": 5041,
"text": "The knn algorithm is a widely-used algorithm. It is simple and easy to interpret. Since it does not make any assumption, it can be used to solve non-linear tasks as well."
},
{
"code": null,
"e": 5428,
"s": 5212,
"text": "On the negative side, we can say that the knn algorithm becomes very slow as the number of data points increases because the model needs to store all data points. Due to this reason, it is also not memory efficient."
},
{
"code": null,
"e": 5513,
"s": 5428,
"text": "Finally, it is sensitive to outliers because outliers also have a vote in decisions."
}
] |
How to Use Neumorphic Theme in Android? - GeeksforGeeks | 21 Apr, 2021
Neumorphic theme is one of the beautiful which is seen used in many of the apps. It is a beautiful theme in which we can add a little elevation to the views of our layout components to make it look beautiful. Below is the screenshot in which you can get to see the sample layout which is made with the help of Neumorphic Theme.
Attributes
Usage
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add dependency and JitPack Repository
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
implementation ‘com.github.Borutsky:neumorphism-android:1.0.0-alpha01’
Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.
allprojects {
repositories {
...
maven { url “https://jitpack.io” }
}
}
After adding this dependency sync your project and now we will move towards its implementation.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/purple_200" android:clipChildren="false" tools:context=".MainActivity"> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:id="@+id/firstBlock" android:layout_width="100dp" android:layout_height="100dp" android:layout_centerHorizontal="true" android:layout_marginTop="100dp" android:layout_marginBottom="30dp" app:background_color="@color/purple_200" app:corner_radius="20dp" app:shape="rectangle"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Press Me" android:textColor="@color/white" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> <LinearLayout android:id="@+id/idLLTwo" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/firstBlock" android:layout_marginTop="30dp" android:clipChildren="false" android:gravity="center" android:orientation="horizontal" android:weightSum="4"> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:layout_width="0dp" android:layout_height="80dp" android:layout_margin="10dp" android:layout_weight="1" app:background_color="@color/purple_200" app:corner_radius="20dp" app:shape="rectangle" app:state="flat"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Flat" android:textColor="@color/white" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle in this we are using state as concave--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:layout_width="0dp" android:layout_height="80dp" android:layout_margin="10dp" android:layout_weight="1" app:background_color="@color/purple_200" app:corner_radius="20dp" app:shape="rectangle" app:state="concave"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Concave" android:textColor="@color/white" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle in this we are using state as convex--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:layout_width="0dp" android:layout_height="80dp" android:layout_margin="10dp" android:layout_weight="1" app:background_color="@color/purple_200" app:corner_radius="20dp" app:shape="rectangle" app:state="convex"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Convex" android:textColor="@color/white" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle in this we are using state as pressed--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:layout_width="0dp" android:layout_height="80dp" android:layout_margin="10dp" android:layout_weight="1" app:background_color="@color/purple_200" app:corner_radius="20dp" app:shape="rectangle" app:state="pressed"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Pressed" android:textColor="@color/white" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> </LinearLayout> </RelativeLayout>
As we are working with the layout file only so we don’t have to add any code in our MainActivity.java file. Now run your app and see the output of the app.
Output:
Android-Animation
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Android Listview in Java with Example
How to Save Data to the Firebase Realtime Database in Android?
Flexbox-Layout in Android
How to Change the Background Color After Clicking the Button in Android? | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 26710,
"s": 26381,
"text": "Neumorphic theme is one of the beautiful which is seen used in many of the apps. It is a beautiful theme in which we can add a little elevation to the views of our layout components to make it look beautiful. Below is the screenshot in which you can get to see the sample layout which is made with the help of Neumorphic Theme. "
},
{
"code": null,
"e": 26721,
"s": 26710,
"text": "Attributes"
},
{
"code": null,
"e": 26727,
"s": 26721,
"text": "Usage"
},
{
"code": null,
"e": 26756,
"s": 26727,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26918,
"s": 26756,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26964,
"s": 26918,
"text": "Step 2: Add dependency and JitPack Repository"
},
{
"code": null,
"e": 27083,
"s": 26964,
"text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 27154,
"s": 27083,
"text": "implementation ‘com.github.Borutsky:neumorphism-android:1.0.0-alpha01’"
},
{
"code": null,
"e": 27296,
"s": 27154,
"text": "Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section."
},
{
"code": null,
"e": 27310,
"s": 27296,
"text": "allprojects {"
},
{
"code": null,
"e": 27326,
"s": 27310,
"text": " repositories {"
},
{
"code": null,
"e": 27333,
"s": 27326,
"text": " ..."
},
{
"code": null,
"e": 27371,
"s": 27333,
"text": " maven { url “https://jitpack.io” }"
},
{
"code": null,
"e": 27378,
"s": 27371,
"text": " }"
},
{
"code": null,
"e": 27380,
"s": 27378,
"text": "}"
},
{
"code": null,
"e": 27478,
"s": 27380,
"text": "After adding this dependency sync your project and now we will move towards its implementation. "
},
{
"code": null,
"e": 27526,
"s": 27478,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27669,
"s": 27526,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 27673,
"s": 27669,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@color/purple_200\" android:clipChildren=\"false\" tools:context=\".MainActivity\"> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:id=\"@+id/firstBlock\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"100dp\" android:layout_marginBottom=\"30dp\" app:background_color=\"@color/purple_200\" app:corner_radius=\"20dp\" app:shape=\"rectangle\"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:text=\"Press Me\" android:textColor=\"@color/white\" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> <LinearLayout android:id=\"@+id/idLLTwo\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/firstBlock\" android:layout_marginTop=\"30dp\" android:clipChildren=\"false\" android:gravity=\"center\" android:orientation=\"horizontal\" android:weightSum=\"4\"> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:layout_width=\"0dp\" android:layout_height=\"80dp\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" app:background_color=\"@color/purple_200\" app:corner_radius=\"20dp\" app:shape=\"rectangle\" app:state=\"flat\"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:text=\"Flat\" android:textColor=\"@color/white\" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle in this we are using state as concave--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:layout_width=\"0dp\" android:layout_height=\"80dp\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" app:background_color=\"@color/purple_200\" app:corner_radius=\"20dp\" app:shape=\"rectangle\" app:state=\"concave\"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:text=\"Concave\" android:textColor=\"@color/white\" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle in this we are using state as convex--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:layout_width=\"0dp\" android:layout_height=\"80dp\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" app:background_color=\"@color/purple_200\" app:corner_radius=\"20dp\" app:shape=\"rectangle\" app:state=\"convex\"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:text=\"Convex\" android:textColor=\"@color/white\" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> <!--on below line we are creating a new neumorphic frame layout--> <!--we are adding radius as 20 and shape as rectangle in this we are using state as pressed--> <com.borutsky.neumorphism.NeumorphicFrameLayout android:layout_width=\"0dp\" android:layout_height=\"80dp\" android:layout_margin=\"10dp\" android:layout_weight=\"1\" app:background_color=\"@color/purple_200\" app:corner_radius=\"20dp\" app:shape=\"rectangle\" app:state=\"pressed\"> <!--inside this frame layout we are creating a simple text view--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:text=\"Pressed\" android:textColor=\"@color/white\" /> </com.borutsky.neumorphism.NeumorphicFrameLayout> </LinearLayout> </RelativeLayout>",
"e": 33119,
"s": 27673,
"text": null
},
{
"code": null,
"e": 33276,
"s": 33119,
"text": "As we are working with the layout file only so we don’t have to add any code in our MainActivity.java file. Now run your app and see the output of the app. "
},
{
"code": null,
"e": 33284,
"s": 33276,
"text": "Output:"
},
{
"code": null,
"e": 33302,
"s": 33284,
"text": "Android-Animation"
},
{
"code": null,
"e": 33310,
"s": 33302,
"text": "Android"
},
{
"code": null,
"e": 33318,
"s": 33310,
"text": "Android"
},
{
"code": null,
"e": 33416,
"s": 33318,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33454,
"s": 33416,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 33493,
"s": 33454,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 33543,
"s": 33493,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 33594,
"s": 33543,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 33636,
"s": 33594,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 33676,
"s": 33636,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 33714,
"s": 33676,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 33777,
"s": 33714,
"text": "How to Save Data to the Firebase Realtime Database in Android?"
},
{
"code": null,
"e": 33803,
"s": 33777,
"text": "Flexbox-Layout in Android"
}
] |
Python - Concatenate Tuple elements by delimiter - GeeksforGeeks | 02 Sep, 2020
Given a tuple, concatenate each element of tuple by delimiter.
Input : test_tup = (“Gfg”, “is”, 4, “Best”), delim = “, ”Output : Gfg, is, 4, BestExplanation : Elements joined by “, “.
Input : test_tup = (“Gfg”, “is”, 4), delim = “, ”Output : Gfg, is, 4Explanation : Elements joined by “, “.
Method #1 : Using list comprehension
In this, we iterate for each element in tuple using loop in list comprehension and concatenate using + operator.
Python3
# Python3 code to demonstrate working of # Concatenate Tuple elements by delimiter# Using list comprehension # initializing tupletest_tup = ("Gfg", "is", 4, "Best") # printing original tupleprint("The original tuple is : " + str(test_tup)) # initializing delim delim = "-" # using str() to convert elements to string # join to convert to stringres = ''.join([str(ele) + delim for ele in test_tup]) # striping stray char res = res[ : len(res) - len(delim)] # printing result print("Concatenated Tuple : " + str(res))
The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best
Method #2 : Using join() + map()
In this, we convert all chars to string using str() and map to perform str() to all elements, then concatenation using join().
Python3
# Python3 code to demonstrate working of # Concatenate Tuple elements by delimiter# Using join() + map() # initializing tupletest_tup = ("Gfg", "is", 4, "Best") # printing original tupleprint("The original tuple is : " + str(test_tup)) # initializing delim delim = "-" # for joining, delim is used res = delim.join(map(str, test_tup)) # printing result print("Concatenated Tuple : " + str(res))
The original tuple is : ('Gfg', 'is', 4, 'Best')
Concatenated Tuple : Gfg-is-4-Best
Python tuple-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 ?
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 25600,
"s": 25537,
"text": "Given a tuple, concatenate each element of tuple by delimiter."
},
{
"code": null,
"e": 25721,
"s": 25600,
"text": "Input : test_tup = (“Gfg”, “is”, 4, “Best”), delim = “, ”Output : Gfg, is, 4, BestExplanation : Elements joined by “, “."
},
{
"code": null,
"e": 25828,
"s": 25721,
"text": "Input : test_tup = (“Gfg”, “is”, 4), delim = “, ”Output : Gfg, is, 4Explanation : Elements joined by “, “."
},
{
"code": null,
"e": 25865,
"s": 25828,
"text": "Method #1 : Using list comprehension"
},
{
"code": null,
"e": 25978,
"s": 25865,
"text": "In this, we iterate for each element in tuple using loop in list comprehension and concatenate using + operator."
},
{
"code": null,
"e": 25986,
"s": 25978,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Concatenate Tuple elements by delimiter# Using list comprehension # initializing tupletest_tup = (\"Gfg\", \"is\", 4, \"Best\") # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) # initializing delim delim = \"-\" # using str() to convert elements to string # join to convert to stringres = ''.join([str(ele) + delim for ele in test_tup]) # striping stray char res = res[ : len(res) - len(delim)] # printing result print(\"Concatenated Tuple : \" + str(res)) ",
"e": 26509,
"s": 25986,
"text": null
},
{
"code": null,
"e": 26594,
"s": 26509,
"text": "The original tuple is : ('Gfg', 'is', 4, 'Best')\nConcatenated Tuple : Gfg-is-4-Best\n"
},
{
"code": null,
"e": 26627,
"s": 26594,
"text": "Method #2 : Using join() + map()"
},
{
"code": null,
"e": 26754,
"s": 26627,
"text": "In this, we convert all chars to string using str() and map to perform str() to all elements, then concatenation using join()."
},
{
"code": null,
"e": 26762,
"s": 26754,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Concatenate Tuple elements by delimiter# Using join() + map() # initializing tupletest_tup = (\"Gfg\", \"is\", 4, \"Best\") # printing original tupleprint(\"The original tuple is : \" + str(test_tup)) # initializing delim delim = \"-\" # for joining, delim is used res = delim.join(map(str, test_tup)) # printing result print(\"Concatenated Tuple : \" + str(res)) ",
"e": 27163,
"s": 26762,
"text": null
},
{
"code": null,
"e": 27248,
"s": 27163,
"text": "The original tuple is : ('Gfg', 'is', 4, 'Best')\nConcatenated Tuple : Gfg-is-4-Best\n"
},
{
"code": null,
"e": 27270,
"s": 27248,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 27277,
"s": 27270,
"text": "Python"
},
{
"code": null,
"e": 27293,
"s": 27277,
"text": "Python Programs"
},
{
"code": null,
"e": 27391,
"s": 27293,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27423,
"s": 27391,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27465,
"s": 27423,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27507,
"s": 27465,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27534,
"s": 27507,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27590,
"s": 27534,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27612,
"s": 27590,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27651,
"s": 27612,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27697,
"s": 27651,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27735,
"s": 27697,
"text": "Python | Convert a list to dictionary"
}
] |
Minimize cost of operation to equalize tower heights - GeeksforGeeks | 14 Mar, 2022
Given heights of n (n <=10000) towers as an array h[]; we need to bring every tower to same height by either adding or removing blocks in a tower. Every addition or removal operation costs a different value in a different tower. The objective is to minimize this cost.Examples:
Input : Tower heights h[] = {1, 2, 3}
Costs of operations cost[] = {10, 100, 1000}
Output : 120
The heights can be equalized by either "Removing
one block from 3 and adding one in 1" or "Adding
two blocks in 1 and adding one in 2". Since the
cost of operation in tower 3 is 1000, the first
process would yield 1010 while the second one
yields 120. Since the second process yields the
lowest cost of operation, it is the required
output.
Input : h[] = {7,1,5 };
cost[] = { 1, 1, 1 };
Output : 6
abs(7-5) + abs(1-5) + abs(5-5) = 6 (taking 5
as final height)
Input : h[] = {2, 4, 8}
cost[] = {10, 100, 1000}
Output : 460
Naive Approach : A naive approach would be to find the cost of each and every possible operation set, and then find the minimum cost of operation. This would give O(n2) in the worst case.Best Approach : The best approach here seems to be Binary search. We store the minimum height & alter our resultant height by a factor of 2 in each step.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to minimize the cost of operation// to bring all towers to same height.#include <bits/stdc++.h>using namespace std; // Returns the cost of entire operation in bringing// the height of all towers to equal height eq_hlong int costOfOperation(int n, int h[], int cost[], int eq_h){ // Initialize initial cost to 0 long int c = 0; // Adding cost for each tower for (int i = 0; i < n; i++) c += abs(h[i] - eq_h) * cost[i]; return c;} // Return the minimum possible cost of operation// to bring all the towers of different height// in height[0..n-1] to same height.long long int Bsearch(int n, int h[], int cost[]){ long int max_h = *max_element(h, h + n); long int ans = LONG_MAX; // Do binary search for minimum cost long int high = 1 + max_h; long int low = 0; while (high > low) { int mid = (low + high) >> 1; // Cost below mid long int bm = (mid > 0) ? costOfOperation(n, h, cost, mid - 1) : LONG_MAX; // Cost at mid long int m = costOfOperation(n, h, cost, mid); // Cost above mid long int am = costOfOperation(n, h, cost, mid + 1); // ans should hold the minimum cost of operation ans = min(ans, m); // Search lower cost if (bm <= m) high = mid; // Search higher cost else if (am <= m) low = mid + 1; // If am > m and bm > m // then ans is m else return m; } return ans;} // Driver codeint main(){ int h[] = { 1, 2, 3 }; int cost[] = { 10, 100, 1000 }; int n = sizeof(h)/sizeof(h[0]); cout << Bsearch(n, h, cost); return 0;}
// Java program to minimize the cost of operation// to bring all towers to same height.import java.util.Arrays;public class MinCostOp_Mintowerheight { // Returns the cost of entire operation in bringing // the height of all towers to equal height eq_h static long costOfOperation(int n, int h[], int cost[], int eq_h) { // Initialize initial cost to 0 long c = 0; // Adding cost for each tower for (int i = 0; i < n; i++) c += Math.abs(h[i] - eq_h) * cost[i]; return c; } // Return the minimum possible cost of operation // to bring all the towers of different height // in height[0..n-1] to same height. static long Bsearch(int n, int h[], int cost[]) { int max_h = Arrays.stream(h).max().getAsInt(); long ans = Long.MAX_VALUE; // Do binary search for minimum cost long high = 1 + max_h; long low = 0; while (high > low) { int mid = (int) ((low + high) >> 1); // Cost below mid long bm = (mid > 0) ? costOfOperation(n, h, cost, mid - 1) : Long.MAX_VALUE; // Cost at mid long m = costOfOperation(n, h, cost, mid); // Cost above mid long am = costOfOperation(n, h, cost, mid + 1); // Break if the answer becomes equal to // minimum cost m if (ans == m) break; // ans should hold the minimum cost of operation ans = Long.min(ans, m); // Search lower cost if (bm <= m) high = mid; // Search higher cost else if (am <= m) low = mid + 1; // If am > m and bm > m // then ans is m else return m; } return ans; } // Driver code public static void main(String args[]) { int h[] = { 1, 2, 3 }; int cost[] = { 10, 100, 1000 }; int n = h.length; System.out.println(Bsearch(n, h, cost)); }}// This code is contributed by Sumit Ghosh
# Python 3 program to minimize the cost of# operation to bring all towers to same height.import sys # Returns the cost of entire operation in# bringing the height of all towers to# equal height eq_hdef costOfOperation(n, h,cost, eq_h): # Initialize initial cost to 0 c = 0 # Adding cost for each tower for i in range(0, n, 1): c += abs(h[i] - eq_h) * cost[i] return c # Return the minimum possible cost of# operation to bring all the towers of# different height in height[0..n-1]# to same height.def Bsearch(n, h, cost): max_h = h[0] for i in range(len(h)): if(h[i] > max_h): max_h = h[i] ans = sys.maxsize # Do binary search for minimum cost high = 1 + max_h low = 0 while (high > low): mid = (low + high) >> 1 # Cost below mid if(mid > 0): bm = costOfOperation(n, h, cost, mid - 1) else: bm = sys.maxsize # Cost at mid m = costOfOperation(n, h, cost, mid) # Cost above mid am = costOfOperation(n, h, cost, mid + 1) # Break if the answer becomes equal # to minimum cost m if (ans == m): break # ans should hold the minimum cost # of operation ans = min(ans, m) # Search lower cost if (bm <= m): high = mid # Search higher cost else if(am <= m): low = mid + 1 # If am > m and bm > m # then ans is m else : return m; return ans # Driver codeif __name__ == '__main__': h = [1, 2, 3] cost = [10, 100, 1000] n = len(h) print(Bsearch(n, h, cost)) # This code is contributed by# Sahil_shelangia
// C# program to minimize the// cost of operation to bring// all towers to same height.using System;using System.Linq; public class MinCostOp_Mintowerheight{ // Returns the cost of entire // operation in bringing the height // of all towers to equal height eq_h static long costOfOperation(int n, int []h, int []cost, int eq_h) { // Initialize initial cost to 0 long c = 0; // Adding cost for each tower for (int i = 0; i < n; i++) c += Math.Abs(h[i] - eq_h) * cost[i]; return c; } // Return the minimum possible // cost of operation to bring // all the towers of different height // in height[0..n-1] to same height. static long Bsearch(int n, int []h, int []cost) { int max_h = h.Max(); long ans = long.MaxValue; // Do binary search for minimum cost long high = 1 + max_h; long low = 0; while (high > low) { int mid = (int) ((low + high) >> 1); // Cost below mid long bm = (mid > 0) ? costOfOperation(n, h, cost, mid - 1) : long.MaxValue; // Cost at mid long m = costOfOperation(n, h, cost, mid); // Cost above mid long am = costOfOperation(n, h, cost, mid + 1); // Break if the answer becomes // equal to minimum cost m if (ans == m) break; // ans should hold the minimum // cost of operation ans = Math.Min(ans, m); // Search lower cost if (bm <= m) high = mid; // Search higher cost else if (am <= m) low = mid + 1; // If am > m and bm > m // then ans is m else return m; } return ans; } // Driver code public static void Main(String []args) { int []h = { 1, 2, 3 }; int []cost = { 10, 100, 1000 }; int n = h.Length; Console.WriteLine(Bsearch(n, h, cost)); }} // This code contributed by Rajput-Ji
<?php// PHP program to minimize the cost// of operation to bring all towers// to same height. // Returns the cost of entire operation// in bringing the height of all towers// to equal height eq_hfunction costOfOperation($n, $h, $cost, $eq_h){ // Initialize initial cost to 0 $c = 0; // Adding cost for each tower for ($i = 0; $i < $n; $i++) $c += abs($h[$i] - $eq_h) * $cost[$i]; return $c;} // Return the minimum possible cost of operation// to bring all the towers of different height// in height[0..n-1] to same height.function Bsearch($n, $h, $cost){ $max_h = max($h); $ans = PHP_INT_MAX; // Do binary search for minimum cost $high = 1 + $max_h; $low = 0; while ($high > $low) { $mid = ($low + $high) >> 1; // Cost below mid $bm = ($mid > 0) ? costOfOperation($n, $h, $cost, $mid - 1) : PHP_INT_MAX; // Cost at mid $m = costOfOperation($n, $h, $cost, $mid); // Cost above mid $am = costOfOperation($n, $h, $cost, $mid + 1); // Break if the answer becomes equal to // minimum cost m if ($ans == $m) break; // ans should hold the minimum // cost of operation $ans = min($ans, $m); // Search lower cost if ($bm <= $m) $high = $mid; // Search higher cost else if ($am <= $m) $low = $mid + 1; // If am > m and bm > m // then ans is m else return $m; } return $ans;} // Driver code$h = array( 1, 2, 3 );$cost = array( 10, 100, 1000 );$n = count($h);echo Bsearch($n, $h, $cost); // This code is contributed by mits?>
<script> // JavaScript program to minimize the cost// of operation to bring all towers// to same height. // Returns the cost of entire operation// in bringing the height of all towers// to equal height eq_hfunction costOfOperation(n, h, cost, eq_h){ // Initialize initial cost to 0 let c = 0; // Adding cost for each tower for (let i = 0; i < n; i++) c += Math.abs(h[i] - eq_h) * cost[i]; return c;} // Return the minimum possible cost of operation// to bring all the towers of different height// in height[0..n-1] to same height.function Bsearch(n, h, cost){ let max_h = [...h].sort((a, b) => a - b)[h.length - 1]; let ans = Number.MAX_SAFE_INTEGER; // Do binary search for minimum cost let high = 1 + max_h; let low = 0; while (high > low) { let mid = (low + high) >> 1; // Cost below mid let bm = (mid > 0) ? costOfOperation(n, h, cost, mid - 1) : PHP_INT_MAX; // Cost at mid let m = costOfOperation(n, h, cost, mid); // Cost above mid let am = costOfOperation(n, h, cost, mid + 1); // Break if the answer becomes equal to // minimum cost m if (ans == m) break; // ans should hold the minimum // cost of operation ans = Math.min(ans, m); // Search lower cost if (bm <= m) high = mid; // Search higher cost else if (am <= m) low = mid + 1; // If am > m and bm > m // then ans is m else return m; } return ans;} // Driver codelet h = new Array( 1, 2, 3 );let cost = new Array( 10, 100, 1000 );let n = h.length;document.write(Bsearch(n, h, cost)); // This code is contributed by gfgking </script>
120
This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sahilshelangia
Rajput-Ji
Mithun Kumar
Avnishkumar1
gfgking
surinderdawra388
Binary Search
Arrays
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Bridge and Torch problem
Window Sliding Technique
Binary Tree (Array implementation)
Segment Tree | Set 1 (Sum of given range)
MSD( Most Significant Digit ) Radix Sort
Building Heap from Array
Maximum Subarray Sum using Divide and Conquer algorithm
Product of Array except itself
Find duplicates in O(n) time and O(1) extra space | Set 1 | [
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 26345,
"s": 26065,
"text": "Given heights of n (n <=10000) towers as an array h[]; we need to bring every tower to same height by either adding or removing blocks in a tower. Every addition or removal operation costs a different value in a different tower. The objective is to minimize this cost.Examples: "
},
{
"code": null,
"e": 26987,
"s": 26345,
"text": "Input : Tower heights h[] = {1, 2, 3}\nCosts of operations cost[] = {10, 100, 1000}\nOutput : 120\nThe heights can be equalized by either \"Removing \none block from 3 and adding one in 1\" or \"Adding\ntwo blocks in 1 and adding one in 2\". Since the \ncost of operation in tower 3 is 1000, the first\nprocess would yield 1010 while the second one \nyields 120. Since the second process yields the\nlowest cost of operation, it is the required \noutput.\n\nInput : h[] = {7,1,5 }; \n cost[] = { 1, 1, 1 }; \nOutput : 6\nabs(7-5) + abs(1-5) + abs(5-5) = 6 (taking 5\nas final height)\n\nInput : h[] = {2, 4, 8}\n cost[] = {10, 100, 1000}\nOutput : 460"
},
{
"code": null,
"e": 27332,
"s": 26989,
"text": "Naive Approach : A naive approach would be to find the cost of each and every possible operation set, and then find the minimum cost of operation. This would give O(n2) in the worst case.Best Approach : The best approach here seems to be Binary search. We store the minimum height & alter our resultant height by a factor of 2 in each step. "
},
{
"code": null,
"e": 27336,
"s": 27332,
"text": "C++"
},
{
"code": null,
"e": 27341,
"s": 27336,
"text": "Java"
},
{
"code": null,
"e": 27349,
"s": 27341,
"text": "Python3"
},
{
"code": null,
"e": 27352,
"s": 27349,
"text": "C#"
},
{
"code": null,
"e": 27356,
"s": 27352,
"text": "PHP"
},
{
"code": null,
"e": 27367,
"s": 27356,
"text": "Javascript"
},
{
"code": "// C++ program to minimize the cost of operation// to bring all towers to same height.#include <bits/stdc++.h>using namespace std; // Returns the cost of entire operation in bringing// the height of all towers to equal height eq_hlong int costOfOperation(int n, int h[], int cost[], int eq_h){ // Initialize initial cost to 0 long int c = 0; // Adding cost for each tower for (int i = 0; i < n; i++) c += abs(h[i] - eq_h) * cost[i]; return c;} // Return the minimum possible cost of operation// to bring all the towers of different height// in height[0..n-1] to same height.long long int Bsearch(int n, int h[], int cost[]){ long int max_h = *max_element(h, h + n); long int ans = LONG_MAX; // Do binary search for minimum cost long int high = 1 + max_h; long int low = 0; while (high > low) { int mid = (low + high) >> 1; // Cost below mid long int bm = (mid > 0) ? costOfOperation(n, h, cost, mid - 1) : LONG_MAX; // Cost at mid long int m = costOfOperation(n, h, cost, mid); // Cost above mid long int am = costOfOperation(n, h, cost, mid + 1); // ans should hold the minimum cost of operation ans = min(ans, m); // Search lower cost if (bm <= m) high = mid; // Search higher cost else if (am <= m) low = mid + 1; // If am > m and bm > m // then ans is m else return m; } return ans;} // Driver codeint main(){ int h[] = { 1, 2, 3 }; int cost[] = { 10, 100, 1000 }; int n = sizeof(h)/sizeof(h[0]); cout << Bsearch(n, h, cost); return 0;}",
"e": 29080,
"s": 27367,
"text": null
},
{
"code": "// Java program to minimize the cost of operation// to bring all towers to same height.import java.util.Arrays;public class MinCostOp_Mintowerheight { // Returns the cost of entire operation in bringing // the height of all towers to equal height eq_h static long costOfOperation(int n, int h[], int cost[], int eq_h) { // Initialize initial cost to 0 long c = 0; // Adding cost for each tower for (int i = 0; i < n; i++) c += Math.abs(h[i] - eq_h) * cost[i]; return c; } // Return the minimum possible cost of operation // to bring all the towers of different height // in height[0..n-1] to same height. static long Bsearch(int n, int h[], int cost[]) { int max_h = Arrays.stream(h).max().getAsInt(); long ans = Long.MAX_VALUE; // Do binary search for minimum cost long high = 1 + max_h; long low = 0; while (high > low) { int mid = (int) ((low + high) >> 1); // Cost below mid long bm = (mid > 0) ? costOfOperation(n, h, cost, mid - 1) : Long.MAX_VALUE; // Cost at mid long m = costOfOperation(n, h, cost, mid); // Cost above mid long am = costOfOperation(n, h, cost, mid + 1); // Break if the answer becomes equal to // minimum cost m if (ans == m) break; // ans should hold the minimum cost of operation ans = Long.min(ans, m); // Search lower cost if (bm <= m) high = mid; // Search higher cost else if (am <= m) low = mid + 1; // If am > m and bm > m // then ans is m else return m; } return ans; } // Driver code public static void main(String args[]) { int h[] = { 1, 2, 3 }; int cost[] = { 10, 100, 1000 }; int n = h.length; System.out.println(Bsearch(n, h, cost)); }}// This code is contributed by Sumit Ghosh",
"e": 31307,
"s": 29080,
"text": null
},
{
"code": "# Python 3 program to minimize the cost of# operation to bring all towers to same height.import sys # Returns the cost of entire operation in# bringing the height of all towers to# equal height eq_hdef costOfOperation(n, h,cost, eq_h): # Initialize initial cost to 0 c = 0 # Adding cost for each tower for i in range(0, n, 1): c += abs(h[i] - eq_h) * cost[i] return c # Return the minimum possible cost of# operation to bring all the towers of# different height in height[0..n-1]# to same height.def Bsearch(n, h, cost): max_h = h[0] for i in range(len(h)): if(h[i] > max_h): max_h = h[i] ans = sys.maxsize # Do binary search for minimum cost high = 1 + max_h low = 0 while (high > low): mid = (low + high) >> 1 # Cost below mid if(mid > 0): bm = costOfOperation(n, h, cost, mid - 1) else: bm = sys.maxsize # Cost at mid m = costOfOperation(n, h, cost, mid) # Cost above mid am = costOfOperation(n, h, cost, mid + 1) # Break if the answer becomes equal # to minimum cost m if (ans == m): break # ans should hold the minimum cost # of operation ans = min(ans, m) # Search lower cost if (bm <= m): high = mid # Search higher cost else if(am <= m): low = mid + 1 # If am > m and bm > m # then ans is m else : return m; return ans # Driver codeif __name__ == '__main__': h = [1, 2, 3] cost = [10, 100, 1000] n = len(h) print(Bsearch(n, h, cost)) # This code is contributed by# Sahil_shelangia",
"e": 33007,
"s": 31307,
"text": null
},
{
"code": "// C# program to minimize the// cost of operation to bring// all towers to same height.using System;using System.Linq; public class MinCostOp_Mintowerheight{ // Returns the cost of entire // operation in bringing the height // of all towers to equal height eq_h static long costOfOperation(int n, int []h, int []cost, int eq_h) { // Initialize initial cost to 0 long c = 0; // Adding cost for each tower for (int i = 0; i < n; i++) c += Math.Abs(h[i] - eq_h) * cost[i]; return c; } // Return the minimum possible // cost of operation to bring // all the towers of different height // in height[0..n-1] to same height. static long Bsearch(int n, int []h, int []cost) { int max_h = h.Max(); long ans = long.MaxValue; // Do binary search for minimum cost long high = 1 + max_h; long low = 0; while (high > low) { int mid = (int) ((low + high) >> 1); // Cost below mid long bm = (mid > 0) ? costOfOperation(n, h, cost, mid - 1) : long.MaxValue; // Cost at mid long m = costOfOperation(n, h, cost, mid); // Cost above mid long am = costOfOperation(n, h, cost, mid + 1); // Break if the answer becomes // equal to minimum cost m if (ans == m) break; // ans should hold the minimum // cost of operation ans = Math.Min(ans, m); // Search lower cost if (bm <= m) high = mid; // Search higher cost else if (am <= m) low = mid + 1; // If am > m and bm > m // then ans is m else return m; } return ans; } // Driver code public static void Main(String []args) { int []h = { 1, 2, 3 }; int []cost = { 10, 100, 1000 }; int n = h.Length; Console.WriteLine(Bsearch(n, h, cost)); }} // This code contributed by Rajput-Ji",
"e": 35216,
"s": 33007,
"text": null
},
{
"code": "<?php// PHP program to minimize the cost// of operation to bring all towers// to same height. // Returns the cost of entire operation// in bringing the height of all towers// to equal height eq_hfunction costOfOperation($n, $h, $cost, $eq_h){ // Initialize initial cost to 0 $c = 0; // Adding cost for each tower for ($i = 0; $i < $n; $i++) $c += abs($h[$i] - $eq_h) * $cost[$i]; return $c;} // Return the minimum possible cost of operation// to bring all the towers of different height// in height[0..n-1] to same height.function Bsearch($n, $h, $cost){ $max_h = max($h); $ans = PHP_INT_MAX; // Do binary search for minimum cost $high = 1 + $max_h; $low = 0; while ($high > $low) { $mid = ($low + $high) >> 1; // Cost below mid $bm = ($mid > 0) ? costOfOperation($n, $h, $cost, $mid - 1) : PHP_INT_MAX; // Cost at mid $m = costOfOperation($n, $h, $cost, $mid); // Cost above mid $am = costOfOperation($n, $h, $cost, $mid + 1); // Break if the answer becomes equal to // minimum cost m if ($ans == $m) break; // ans should hold the minimum // cost of operation $ans = min($ans, $m); // Search lower cost if ($bm <= $m) $high = $mid; // Search higher cost else if ($am <= $m) $low = $mid + 1; // If am > m and bm > m // then ans is m else return $m; } return $ans;} // Driver code$h = array( 1, 2, 3 );$cost = array( 10, 100, 1000 );$n = count($h);echo Bsearch($n, $h, $cost); // This code is contributed by mits?>",
"e": 36932,
"s": 35216,
"text": null
},
{
"code": "<script> // JavaScript program to minimize the cost// of operation to bring all towers// to same height. // Returns the cost of entire operation// in bringing the height of all towers// to equal height eq_hfunction costOfOperation(n, h, cost, eq_h){ // Initialize initial cost to 0 let c = 0; // Adding cost for each tower for (let i = 0; i < n; i++) c += Math.abs(h[i] - eq_h) * cost[i]; return c;} // Return the minimum possible cost of operation// to bring all the towers of different height// in height[0..n-1] to same height.function Bsearch(n, h, cost){ let max_h = [...h].sort((a, b) => a - b)[h.length - 1]; let ans = Number.MAX_SAFE_INTEGER; // Do binary search for minimum cost let high = 1 + max_h; let low = 0; while (high > low) { let mid = (low + high) >> 1; // Cost below mid let bm = (mid > 0) ? costOfOperation(n, h, cost, mid - 1) : PHP_INT_MAX; // Cost at mid let m = costOfOperation(n, h, cost, mid); // Cost above mid let am = costOfOperation(n, h, cost, mid + 1); // Break if the answer becomes equal to // minimum cost m if (ans == m) break; // ans should hold the minimum // cost of operation ans = Math.min(ans, m); // Search lower cost if (bm <= m) high = mid; // Search higher cost else if (am <= m) low = mid + 1; // If am > m and bm > m // then ans is m else return m; } return ans;} // Driver codelet h = new Array( 1, 2, 3 );let cost = new Array( 10, 100, 1000 );let n = h.length;document.write(Bsearch(n, h, cost)); // This code is contributed by gfgking </script>",
"e": 38725,
"s": 36932,
"text": null
},
{
"code": null,
"e": 38729,
"s": 38725,
"text": "120"
},
{
"code": null,
"e": 39154,
"s": 38731,
"text": "This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39169,
"s": 39154,
"text": "sahilshelangia"
},
{
"code": null,
"e": 39179,
"s": 39169,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39192,
"s": 39179,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 39205,
"s": 39192,
"text": "Avnishkumar1"
},
{
"code": null,
"e": 39213,
"s": 39205,
"text": "gfgking"
},
{
"code": null,
"e": 39230,
"s": 39213,
"text": "surinderdawra388"
},
{
"code": null,
"e": 39244,
"s": 39230,
"text": "Binary Search"
},
{
"code": null,
"e": 39251,
"s": 39244,
"text": "Arrays"
},
{
"code": null,
"e": 39258,
"s": 39251,
"text": "Arrays"
},
{
"code": null,
"e": 39272,
"s": 39258,
"text": "Binary Search"
},
{
"code": null,
"e": 39370,
"s": 39272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39407,
"s": 39370,
"text": "Program for Bridge and Torch problem"
},
{
"code": null,
"e": 39432,
"s": 39407,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 39467,
"s": 39432,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 39509,
"s": 39467,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 39550,
"s": 39509,
"text": "MSD( Most Significant Digit ) Radix Sort"
},
{
"code": null,
"e": 39575,
"s": 39550,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 39631,
"s": 39575,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 39662,
"s": 39631,
"text": "Product of Array except itself"
}
] |
Python | Numpy np.unique() method - GeeksforGeeks | 21 Nov, 2019
With the help of np.unique() method, we can get the unique values from an array given as parameter in np.unique() method.
Syntax : np.unique(Array)Return : Return the unique of an array.
Example #1 :In this example we can see that by using np.unique() method, we are able to get the unique values from an array by using this method.
# import numpyimport numpy as np a = [1, 2, 2, 4, 3, 6, 4, 8] # using np.unique() methodgfg = np.unique(a) print(gfg)
Output :
[1 2 3 4 6 8]
Example #2 :
# import numpyimport numpy as np a = [[10.2, 21.4, 3.6, 14.8], [1.0, 5.0, 10.0, 15.0]] # using np.unique() methodgfg = np.unique(a) print(gfg)
Output :
[1. 3.6 5. 10. 10.2 14.8 15. 21.4]
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 25683,
"s": 25561,
"text": "With the help of np.unique() method, we can get the unique values from an array given as parameter in np.unique() method."
},
{
"code": null,
"e": 25748,
"s": 25683,
"text": "Syntax : np.unique(Array)Return : Return the unique of an array."
},
{
"code": null,
"e": 25894,
"s": 25748,
"text": "Example #1 :In this example we can see that by using np.unique() method, we are able to get the unique values from an array by using this method."
},
{
"code": "# import numpyimport numpy as np a = [1, 2, 2, 4, 3, 6, 4, 8] # using np.unique() methodgfg = np.unique(a) print(gfg)",
"e": 26015,
"s": 25894,
"text": null
},
{
"code": null,
"e": 26024,
"s": 26015,
"text": "Output :"
},
{
"code": null,
"e": 26038,
"s": 26024,
"text": "[1 2 3 4 6 8]"
},
{
"code": null,
"e": 26051,
"s": 26038,
"text": "Example #2 :"
},
{
"code": "# import numpyimport numpy as np a = [[10.2, 21.4, 3.6, 14.8], [1.0, 5.0, 10.0, 15.0]] # using np.unique() methodgfg = np.unique(a) print(gfg)",
"e": 26197,
"s": 26051,
"text": null
},
{
"code": null,
"e": 26206,
"s": 26197,
"text": "Output :"
},
{
"code": null,
"e": 26241,
"s": 26206,
"text": "[1. 3.6 5. 10. 10.2 14.8 15. 21.4]"
},
{
"code": null,
"e": 26270,
"s": 26241,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 26283,
"s": 26270,
"text": "Python-numpy"
},
{
"code": null,
"e": 26290,
"s": 26283,
"text": "Python"
},
{
"code": null,
"e": 26388,
"s": 26290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26423,
"s": 26388,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26455,
"s": 26423,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26477,
"s": 26455,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26519,
"s": 26477,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26549,
"s": 26519,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26575,
"s": 26549,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26604,
"s": 26575,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26648,
"s": 26604,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26685,
"s": 26648,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to create To-Do List using jQuery? - GeeksforGeeks | 23 Jan, 2020
This article focuses on developing a To-do List with some basic features like:
Add TaskDelete TaskCross the completed tasks
Add Task
Delete Task
Cross the completed tasks
Prerequisites:Basic knowledge of Front-end development using HTML, CSS, JS, jQuery & Bootstrap-3.Steps:
Initialize the layout:– Add a input text-box with a button to add the tasks to the main list.– We will set the container containing the above as fixed at the button using some CSS position fixed property.– Now we will add the container where the tasks will be added.Below is the code along-with explanation for the above:<!-- Initialize the layout --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity= "sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"> </script> <style> .container { width: 90%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class="foot"> <div class="row"> <div class="col-sm-1"> </div> <div class="col-sm-10"> <!-- Input for tasks --> <div class="input-group"> <input type="text" class="form-control" placeholder="Add Task" id="text"> <div class="input-group-btn"> <button class="btn btn-success"> <i class="glyphicon glyphicon-plus"> </i></button> </div> </div> <br> <br> </div> </div> </div> <!-- Rest of the screen used for Adding Tasks --> <br> <h2 class="text text-success">My Tasks:</h2> <br> <div class="container"> <!-- For adding tasks to the list --> </div> </center></body> </html>jQuery script to add tasks:Now we will add the jQuery code so that we can add tasks in our to-do list. Here we have used Bootstrap alert class to add task containers.Clicking on the cross-button on the right of the task will remove the task permanently.( alert has attribute for that otherwise we would have to implement script for delete as well ).Below is the code along-with explanation for the above:<!-- Adding tasks in the list --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <style> .container { width: 80%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class="foot"> <div class="row"> <div class="col-sm-1"> </div> <div class="col-sm-10"> <!-- Input for tasks --> <div class="input-group"> <input type="text" class="form-control" placeholder="Add Task" id="text"> <div class="input-group-btn"> <button class="btn btn-success"> <i class="glyphicon glyphicon-plus"> </i></button> </div> </div> <br> <br> </div> </div> </div> <br> <h2 class="text text-success">My Tasks:</h2> <br> <div class="container"> </div> </center> <script> $(document).ready(function() { $('.btn-success').click(function() { // If something is written if ($('#text').val().length != 0) { //Store previous data var x = $('.container').html(); // Add typed text in alert container var y = `<div class="alert alert-success alert-dismissible fade in"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> ` + $('#text').val() + `</div>`; //Update $('.container').html(y + x); //Clear after addition $('#text').val(""); } else alert("Enter some Text!"); }); }); </script></body> </html>Script to indicate completed Tasks:Finally, we will be adding the script to implement the feature that whenever we will click on the task, it will be crossed and if done already, will be restored back.For crossing the task, we will use text-decoration-line : line-through property in CSS.
Initialize the layout:– Add a input text-box with a button to add the tasks to the main list.– We will set the container containing the above as fixed at the button using some CSS position fixed property.– Now we will add the container where the tasks will be added.Below is the code along-with explanation for the above:<!-- Initialize the layout --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity= "sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"> </script> <style> .container { width: 90%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class="foot"> <div class="row"> <div class="col-sm-1"> </div> <div class="col-sm-10"> <!-- Input for tasks --> <div class="input-group"> <input type="text" class="form-control" placeholder="Add Task" id="text"> <div class="input-group-btn"> <button class="btn btn-success"> <i class="glyphicon glyphicon-plus"> </i></button> </div> </div> <br> <br> </div> </div> </div> <!-- Rest of the screen used for Adding Tasks --> <br> <h2 class="text text-success">My Tasks:</h2> <br> <div class="container"> <!-- For adding tasks to the list --> </div> </center></body> </html>
Below is the code along-with explanation for the above:
<!-- Initialize the layout --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <!-- Required CDN's --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity= "sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"> </script> <style> .container { width: 90%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class="foot"> <div class="row"> <div class="col-sm-1"> </div> <div class="col-sm-10"> <!-- Input for tasks --> <div class="input-group"> <input type="text" class="form-control" placeholder="Add Task" id="text"> <div class="input-group-btn"> <button class="btn btn-success"> <i class="glyphicon glyphicon-plus"> </i></button> </div> </div> <br> <br> </div> </div> </div> <!-- Rest of the screen used for Adding Tasks --> <br> <h2 class="text text-success">My Tasks:</h2> <br> <div class="container"> <!-- For adding tasks to the list --> </div> </center></body> </html>
jQuery script to add tasks:Now we will add the jQuery code so that we can add tasks in our to-do list. Here we have used Bootstrap alert class to add task containers.Clicking on the cross-button on the right of the task will remove the task permanently.( alert has attribute for that otherwise we would have to implement script for delete as well ).Below is the code along-with explanation for the above:<!-- Adding tasks in the list --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <style> .container { width: 80%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class="foot"> <div class="row"> <div class="col-sm-1"> </div> <div class="col-sm-10"> <!-- Input for tasks --> <div class="input-group"> <input type="text" class="form-control" placeholder="Add Task" id="text"> <div class="input-group-btn"> <button class="btn btn-success"> <i class="glyphicon glyphicon-plus"> </i></button> </div> </div> <br> <br> </div> </div> </div> <br> <h2 class="text text-success">My Tasks:</h2> <br> <div class="container"> </div> </center> <script> $(document).ready(function() { $('.btn-success').click(function() { // If something is written if ($('#text').val().length != 0) { //Store previous data var x = $('.container').html(); // Add typed text in alert container var y = `<div class="alert alert-success alert-dismissible fade in"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> ` + $('#text').val() + `</div>`; //Update $('.container').html(y + x); //Clear after addition $('#text').val(""); } else alert("Enter some Text!"); }); }); </script></body> </html>
Clicking on the cross-button on the right of the task will remove the task permanently.( alert has attribute for that otherwise we would have to implement script for delete as well ).
Below is the code along-with explanation for the above:
<!-- Adding tasks in the list --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <style> .container { width: 80%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class="foot"> <div class="row"> <div class="col-sm-1"> </div> <div class="col-sm-10"> <!-- Input for tasks --> <div class="input-group"> <input type="text" class="form-control" placeholder="Add Task" id="text"> <div class="input-group-btn"> <button class="btn btn-success"> <i class="glyphicon glyphicon-plus"> </i></button> </div> </div> <br> <br> </div> </div> </div> <br> <h2 class="text text-success">My Tasks:</h2> <br> <div class="container"> </div> </center> <script> $(document).ready(function() { $('.btn-success').click(function() { // If something is written if ($('#text').val().length != 0) { //Store previous data var x = $('.container').html(); // Add typed text in alert container var y = `<div class="alert alert-success alert-dismissible fade in"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> ` + $('#text').val() + `</div>`; //Update $('.container').html(y + x); //Clear after addition $('#text').val(""); } else alert("Enter some Text!"); }); }); </script></body> </html>
Script to indicate completed Tasks:Finally, we will be adding the script to implement the feature that whenever we will click on the task, it will be crossed and if done already, will be restored back.For crossing the task, we will use text-decoration-line : line-through property in CSS.
Final Solution:
<!-- To-Do List implemented using jQuery --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity= "sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <style> .container { width: 80%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class="foot"> <div class="row"> <div class="col-sm-1"> </div> <div class="col-sm-10"> <!-- Input for tasks --> <div class="input-group"> <input type="text" class="form-control" placeholder="Add Task" id="text"> <div class="input-group-btn"> <button class="btn btn-success"> <i class="glyphicon glyphicon-plus"> </i></button> </div> </div> <br> <br> </div> </div> </div> <br> <h2 class="text text-success">My Tasks:</h2> <br> <div class="container"> </div> </center> <script> $(document).ready(function() { $('.btn-success').click(function() { if ($('#text').val().length != 0) { var x = $('.container').html(); var y = `<div class="alert alert-success alert-dismissible fade in"> <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a> ` + $('#text').val() + `</div>`; $('.container').html(y + x); $('#text').val(""); } else alert("Enter some Text!"); }); // When Task is clicked $(document).on('click', '.alert', function() { if ($(this).css('text-decoration-line') == "none") $(this).css('text-decoration-line', 'line-through'); else $(this).css('text-decoration-line', 'none'); }); }); </script></body> </html>
Output:Before adding the tasks:After adding the tasks:
jQuery-Misc
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to Show and Hide div elements using radio buttons?
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": 26033,
"s": 26005,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 26112,
"s": 26033,
"text": "This article focuses on developing a To-do List with some basic features like:"
},
{
"code": null,
"e": 26157,
"s": 26112,
"text": "Add TaskDelete TaskCross the completed tasks"
},
{
"code": null,
"e": 26166,
"s": 26157,
"text": "Add Task"
},
{
"code": null,
"e": 26178,
"s": 26166,
"text": "Delete Task"
},
{
"code": null,
"e": 26204,
"s": 26178,
"text": "Cross the completed tasks"
},
{
"code": null,
"e": 26308,
"s": 26204,
"text": "Prerequisites:Basic knowledge of Front-end development using HTML, CSS, JS, jQuery & Bootstrap-3.Steps:"
},
{
"code": null,
"e": 31935,
"s": 26308,
"text": "Initialize the layout:– Add a input text-box with a button to add the tasks to the main list.– We will set the container containing the above as fixed at the button using some CSS position fixed property.– Now we will add the container where the tasks will be added.Below is the code along-with explanation for the above:<!-- Initialize the layout --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity= \"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"> </script> <style> .container { width: 90%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class=\"foot\"> <div class=\"row\"> <div class=\"col-sm-1\"> </div> <div class=\"col-sm-10\"> <!-- Input for tasks --> <div class=\"input-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"Add Task\" id=\"text\"> <div class=\"input-group-btn\"> <button class=\"btn btn-success\"> <i class=\"glyphicon glyphicon-plus\"> </i></button> </div> </div> <br> <br> </div> </div> </div> <!-- Rest of the screen used for Adding Tasks --> <br> <h2 class=\"text text-success\">My Tasks:</h2> <br> <div class=\"container\"> <!-- For adding tasks to the list --> </div> </center></body> </html>jQuery script to add tasks:Now we will add the jQuery code so that we can add tasks in our to-do list. Here we have used Bootstrap alert class to add task containers.Clicking on the cross-button on the right of the task will remove the task permanently.( alert has attribute for that otherwise we would have to implement script for delete as well ).Below is the code along-with explanation for the above:<!-- Adding tasks in the list --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity=\"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"></script> <style> .container { width: 80%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class=\"foot\"> <div class=\"row\"> <div class=\"col-sm-1\"> </div> <div class=\"col-sm-10\"> <!-- Input for tasks --> <div class=\"input-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"Add Task\" id=\"text\"> <div class=\"input-group-btn\"> <button class=\"btn btn-success\"> <i class=\"glyphicon glyphicon-plus\"> </i></button> </div> </div> <br> <br> </div> </div> </div> <br> <h2 class=\"text text-success\">My Tasks:</h2> <br> <div class=\"container\"> </div> </center> <script> $(document).ready(function() { $('.btn-success').click(function() { // If something is written if ($('#text').val().length != 0) { //Store previous data var x = $('.container').html(); // Add typed text in alert container var y = `<div class=\"alert alert-success alert-dismissible fade in\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a> ` + $('#text').val() + `</div>`; //Update $('.container').html(y + x); //Clear after addition $('#text').val(\"\"); } else alert(\"Enter some Text!\"); }); }); </script></body> </html>Script to indicate completed Tasks:Finally, we will be adding the script to implement the feature that whenever we will click on the task, it will be crossed and if done already, will be restored back.For crossing the task, we will use text-decoration-line : line-through property in CSS."
},
{
"code": null,
"e": 34232,
"s": 31935,
"text": "Initialize the layout:– Add a input text-box with a button to add the tasks to the main list.– We will set the container containing the above as fixed at the button using some CSS position fixed property.– Now we will add the container where the tasks will be added.Below is the code along-with explanation for the above:<!-- Initialize the layout --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity= \"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"> </script> <style> .container { width: 90%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class=\"foot\"> <div class=\"row\"> <div class=\"col-sm-1\"> </div> <div class=\"col-sm-10\"> <!-- Input for tasks --> <div class=\"input-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"Add Task\" id=\"text\"> <div class=\"input-group-btn\"> <button class=\"btn btn-success\"> <i class=\"glyphicon glyphicon-plus\"> </i></button> </div> </div> <br> <br> </div> </div> </div> <!-- Rest of the screen used for Adding Tasks --> <br> <h2 class=\"text text-success\">My Tasks:</h2> <br> <div class=\"container\"> <!-- For adding tasks to the list --> </div> </center></body> </html>"
},
{
"code": null,
"e": 34288,
"s": 34232,
"text": "Below is the code along-with explanation for the above:"
},
{
"code": "<!-- Initialize the layout --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <!-- Required CDN's --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity= \"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"> </script> <style> .container { width: 90%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class=\"foot\"> <div class=\"row\"> <div class=\"col-sm-1\"> </div> <div class=\"col-sm-10\"> <!-- Input for tasks --> <div class=\"input-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"Add Task\" id=\"text\"> <div class=\"input-group-btn\"> <button class=\"btn btn-success\"> <i class=\"glyphicon glyphicon-plus\"> </i></button> </div> </div> <br> <br> </div> </div> </div> <!-- Rest of the screen used for Adding Tasks --> <br> <h2 class=\"text text-success\">My Tasks:</h2> <br> <div class=\"container\"> <!-- For adding tasks to the list --> </div> </center></body> </html>",
"e": 36264,
"s": 34288,
"text": null
},
{
"code": null,
"e": 39307,
"s": 36264,
"text": "jQuery script to add tasks:Now we will add the jQuery code so that we can add tasks in our to-do list. Here we have used Bootstrap alert class to add task containers.Clicking on the cross-button on the right of the task will remove the task permanently.( alert has attribute for that otherwise we would have to implement script for delete as well ).Below is the code along-with explanation for the above:<!-- Adding tasks in the list --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity=\"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"></script> <style> .container { width: 80%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class=\"foot\"> <div class=\"row\"> <div class=\"col-sm-1\"> </div> <div class=\"col-sm-10\"> <!-- Input for tasks --> <div class=\"input-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"Add Task\" id=\"text\"> <div class=\"input-group-btn\"> <button class=\"btn btn-success\"> <i class=\"glyphicon glyphicon-plus\"> </i></button> </div> </div> <br> <br> </div> </div> </div> <br> <h2 class=\"text text-success\">My Tasks:</h2> <br> <div class=\"container\"> </div> </center> <script> $(document).ready(function() { $('.btn-success').click(function() { // If something is written if ($('#text').val().length != 0) { //Store previous data var x = $('.container').html(); // Add typed text in alert container var y = `<div class=\"alert alert-success alert-dismissible fade in\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a> ` + $('#text').val() + `</div>`; //Update $('.container').html(y + x); //Clear after addition $('#text').val(\"\"); } else alert(\"Enter some Text!\"); }); }); </script></body> </html>"
},
{
"code": null,
"e": 39491,
"s": 39307,
"text": "Clicking on the cross-button on the right of the task will remove the task permanently.( alert has attribute for that otherwise we would have to implement script for delete as well )."
},
{
"code": null,
"e": 39547,
"s": 39491,
"text": "Below is the code along-with explanation for the above:"
},
{
"code": "<!-- Adding tasks in the list --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity=\"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"></script> <style> .container { width: 80%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class=\"foot\"> <div class=\"row\"> <div class=\"col-sm-1\"> </div> <div class=\"col-sm-10\"> <!-- Input for tasks --> <div class=\"input-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"Add Task\" id=\"text\"> <div class=\"input-group-btn\"> <button class=\"btn btn-success\"> <i class=\"glyphicon glyphicon-plus\"> </i></button> </div> </div> <br> <br> </div> </div> </div> <br> <h2 class=\"text text-success\">My Tasks:</h2> <br> <div class=\"container\"> </div> </center> <script> $(document).ready(function() { $('.btn-success').click(function() { // If something is written if ($('#text').val().length != 0) { //Store previous data var x = $('.container').html(); // Add typed text in alert container var y = `<div class=\"alert alert-success alert-dismissible fade in\"><a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a> ` + $('#text').val() + `</div>`; //Update $('.container').html(y + x); //Clear after addition $('#text').val(\"\"); } else alert(\"Enter some Text!\"); }); }); </script></body> </html>",
"e": 42186,
"s": 39547,
"text": null
},
{
"code": null,
"e": 42475,
"s": 42186,
"text": "Script to indicate completed Tasks:Finally, we will be adding the script to implement the feature that whenever we will click on the task, it will be crossed and if done already, will be restored back.For crossing the task, we will use text-decoration-line : line-through property in CSS."
},
{
"code": null,
"e": 42491,
"s": 42475,
"text": "Final Solution:"
},
{
"code": "<!-- To-Do List implemented using jQuery --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.4.1.js\" integrity= \"sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=\" crossorigin=\"anonymous\"></script> <style> .container { width: 80%; height: auto; } .foot { position: fixed; left: 10%; bottom: 0; width: 80%; text-align: center; } </style> </head> <body> <center> <div class=\"foot\"> <div class=\"row\"> <div class=\"col-sm-1\"> </div> <div class=\"col-sm-10\"> <!-- Input for tasks --> <div class=\"input-group\"> <input type=\"text\" class=\"form-control\" placeholder=\"Add Task\" id=\"text\"> <div class=\"input-group-btn\"> <button class=\"btn btn-success\"> <i class=\"glyphicon glyphicon-plus\"> </i></button> </div> </div> <br> <br> </div> </div> </div> <br> <h2 class=\"text text-success\">My Tasks:</h2> <br> <div class=\"container\"> </div> </center> <script> $(document).ready(function() { $('.btn-success').click(function() { if ($('#text').val().length != 0) { var x = $('.container').html(); var y = `<div class=\"alert alert-success alert-dismissible fade in\"> <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a> ` + $('#text').val() + `</div>`; $('.container').html(y + x); $('#text').val(\"\"); } else alert(\"Enter some Text!\"); }); // When Task is clicked $(document).on('click', '.alert', function() { if ($(this).css('text-decoration-line') == \"none\") $(this).css('text-decoration-line', 'line-through'); else $(this).css('text-decoration-line', 'none'); }); }); </script></body> </html>",
"e": 45284,
"s": 42491,
"text": null
},
{
"code": null,
"e": 45339,
"s": 45284,
"text": "Output:Before adding the tasks:After adding the tasks:"
},
{
"code": null,
"e": 45351,
"s": 45339,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 45358,
"s": 45351,
"text": "JQuery"
},
{
"code": null,
"e": 45375,
"s": 45358,
"text": "Web Technologies"
},
{
"code": null,
"e": 45402,
"s": 45375,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 45500,
"s": 45402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45529,
"s": 45500,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 45585,
"s": 45529,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 45639,
"s": 45585,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 45673,
"s": 45639,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 45728,
"s": 45673,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 45768,
"s": 45728,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 45801,
"s": 45768,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 45846,
"s": 45801,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 45889,
"s": 45846,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Print all subsequences of a string using ArrayList - GeeksforGeeks | 07 Mar, 2022
Given a string str, the task is to print all the sub-sequences of str. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.Examples:
Input: str = “abc” Output: a b ab c ac bc abcInput: str = “geek” Output: g e ge e ge ee gee k gk ek gek ek gek eek geek
Approach: Write a recursive function that prints every sub-sequence of the sub-string starting from the second character str[1, n – 1] after appending the first character of the string str[0] in the beginning of every sub-sequence. Terminating condition will be when the passed string is empty, in that case the function will return an empty arraylist.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the contents// of the Listvoid printList(vector<string> arrL){ arrL.erase(find(arrL.begin(), arrL.end(), "")); for (int i = 0; i < arrL.size(); i++) cout << arrL[i] << " ";} // Function to returns the arraylist which contains// all the sub-sequences of strvector<string> getSequence(string str){ // If string is empty if (str.length() == 0) { // Return an empty arraylist vector<string> empty; empty.push_back(""); return empty; } // Take first character of str char ch = str[0]; // Take sub-string starting from the // second character string subStr = str.substr(1); // Recursive call for all the sub-sequences // starting from the second character vector<string> subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist vector<string> res; for(string val : subSequences) { res.push_back(val); res.push_back(ch + val); } // Return the resultant arraylist return res;} int main(){ string str = "geek"; printList(getSequence(str)); return 0;} // This code is contributed by rameshtravel07.
// Java implementation of the approachimport java.util.ArrayList; public class GFG { // Utility function to print the contents // of the ArrayList static void printArrayList(ArrayList<String> arrL) { arrL.remove(""); for (int i = 0; i < arrL.size(); i++) System.out.print(arrL.get(i) + " "); } // Function to returns the arraylist which contains // all the sub-sequences of str public static ArrayList<String> getSequence(String str) { // If string is empty if (str.length() == 0) { // Return an empty arraylist ArrayList<String> empty = new ArrayList<>(); empty.add(""); return empty; } // Take first character of str char ch = str.charAt(0); // Take sub-string starting from the // second character String subStr = str.substring(1); // Recursive call for all the sub-sequences // starting from the second character ArrayList<String> subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist ArrayList<String> res = new ArrayList<>(); for (String val : subSequences) { res.add(val); res.add(ch + val); } // Return the resultant arraylist return res; } // Driver code public static void main(String[] args) { String str = "geek"; printArrayList(getSequence(str)); // System.out.print(getSequence(str)); }}
# Python implementation of the approach # Utility function to print the contents# of the ArrayListdef printArrayList(arrL): arrL.remove("") print(*arrL, sep = " ") # Function to returns the arraylist which contains# all the sub-sequences of strdef getSequence(Str): # If string is empty if(len(Str) == 0): # Return an empty arraylist empty = [] empty.append("") return empty # Take first character of str ch = Str[0] # Take sub-string starting from the # second character subStr = Str[1:] # Recursive call for all the sub-sequences # starting from the second character subSequences = getSequence(subStr) # Add first character from str in the beginning # of every character from the sub-sequences # and then store it into the resultant arraylist res = [] for val in subSequences: res.append(val) res.append(ch + val) # Return the resultant arraylist return res # Driver codeStr = "geek"printArrayList(getSequence(Str)) # This code is contributed by avanitrachhadiya2155
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Utility function to print the contents // of the List static void printList(List<String> arrL) { arrL.Remove(""); for (int i = 0; i < arrL.Count; i++) Console.Write(arrL[i] + " "); } // Function to returns the arraylist which contains // all the sub-sequences of str public static List<String> getSequence(String str) { // If string is empty if (str.Length == 0) { // Return an empty arraylist List<String> empty = new List<String>(); empty.Add(""); return empty; } // Take first character of str char ch = str[0]; // Take sub-string starting from the // second character String subStr = str.Substring(1); // Recursive call for all the sub-sequences // starting from the second character List<String> subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist List<String> res = new List<String>(); foreach (String val in subSequences) { res.Add(val); res.Add(ch + val); } // Return the resultant arraylist return res; } // Driver code public static void Main(String[] args) { String str = "geek"; printList(getSequence(str)); // Console.Write(getSequence(str)); }} // This code is contributed by Rohit_ranjan
<script> // JavaScript implementation of the approach // Utility function to print the contents // of the ArrayList function printArrayList(arrL) { arrL.splice(arrL.indexOf(""), 1); for (let i = 0; i < arrL.length; i++) document.write(arrL[i] + " "); } // Function to returns the arraylist which contains // all the sub-sequences of str function getSequence(str) { // If string is empty if (str.length == 0) { // Return an empty arraylist let empty = []; empty.push(""); return empty; } // Take first character of str let ch = str[0]; // Take sub-string starting from the // second character let subStr = str.substring(1); // Recursive call for all the sub-sequences // starting from the second character let subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist let res = []; for (let val = 0; val < subSequences.length; val++) { res.push(subSequences[val]); res.push(ch + subSequences[val]); } // Return the resultant arraylist return res; } let str = "geek"; printArrayList(getSequence(str)); </script>
g e ge e ge ee gee k gk ek gek ek gek eek geek
Alternate Solution: One by one fix characters and recursively generate all subsets starting from them.
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print all the sub-sequences// of a stringvoid printSubSeq(string sub, string ans){ if (sub.length() == 0) { cout << "" << ans << " "; return; } // First character of sub char ch = sub[0]; // Sub-string starting from second // character of sub string ros = sub.substr(1); // Excluding first character printSubSeq(ros, ans); // Including first character printSubSeq(ros, ans + ch);} // Driver codeint main(){ string str = "abc"; printSubSeq(str, ""); return 0;} // This code is contributed by divyesh072019
// Java implementation of the approachpublic class sub_sequence { // Function to print all the sub-sequences // of a string public static void printSubSeq(String sub, String ans) { if (sub.length() == 0) { System.out.print("" + ans + " "); return; } // First character of sub char ch = sub.charAt(0); // Sub-string starting from second // character of sub String ros = sub.substring(1); // Excluding first character printSubSeq(ros, ans); // Including first character printSubSeq(ros, ans + ch); } // Driver code public static void main(String[] args) { String str = "abc"; printSubSeq(str, ""); }}
# Python3 implementation of the approach # Function to print all the sub-sequences# of a stringdef printSubSeq(sub, ans) : if (len(sub) == 0) : print(ans , end = " ") return # First character of sub ch = sub[0] # Sub-string starting from second # character of sub ros = sub[1 : ] # Excluding first character printSubSeq(ros, ans) # Including first character printSubSeq(ros, ans + ch) Str = "abc"printSubSeq(Str, "") # This code iscontributed by divyeshrabadiya07
// C# implementation of the approachusing System; class GFG{ // Function to print all the // sub-sequences of a stringpublic static void printSubSeq(string sub, string ans){ if (sub.Length == 0) { Console.Write("" + ans + " "); return; } // First character of sub char ch = sub[0]; // Sub-string starting from second // character of sub string ros = sub.Substring(1); // Excluding first character printSubSeq(ros, ans); // Including first character printSubSeq(ros, ans + ch);} // Driver codepublic static void Main(){ string str = "abc"; printSubSeq(str, "") ;}} // This code is contributed by Ryuga
<script> // Javascript implementation of the approach // Function to print all the // sub-sequences of a string function printSubSeq(sub, ans) { if (sub.length == 0) { document.write("" + ans + " "); return; } // First character of sub let ch = sub[0]; // Sub-string starting from second // character of sub let ros = sub.substring(1); // Excluding first character printSubSeq(ros, ans); // Including first character printSubSeq(ros, ans + ch); } let str = "abc"; printSubSeq(str, "") ; // This code is contributed by decode2207.</script>
c b bc a ac ab abc
ankthon
Rohit_ranjan
divyesh072019
divyeshrabadiya07
avanitrachhadiya2155
decode2207
suresh07
rameshtravel07
nikhatkhan11
Java-ArrayList
subsequence
Articles
Competitive Programming
Recursion
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Service-Oriented Architecture
Const keyword in C++
Amazon’s most frequently asked interview questions | Set 2
What's the difference between Scripting and Programming Languages?
Must Do Questions for Companies like TCS, CTS, HCL, IBM ...
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming | [
{
"code": null,
"e": 26689,
"s": 26661,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 26927,
"s": 26689,
"text": "Given a string str, the task is to print all the sub-sequences of str. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.Examples: "
},
{
"code": null,
"e": 27049,
"s": 26927,
"text": "Input: str = “abc” Output: a b ab c ac bc abcInput: str = “geek” Output: g e ge e ge ee gee k gk ek gek ek gek eek geek "
},
{
"code": null,
"e": 27455,
"s": 27051,
"text": "Approach: Write a recursive function that prints every sub-sequence of the sub-string starting from the second character str[1, n – 1] after appending the first character of the string str[0] in the beginning of every sub-sequence. Terminating condition will be when the passed string is empty, in that case the function will return an empty arraylist.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27459,
"s": 27455,
"text": "C++"
},
{
"code": null,
"e": 27464,
"s": 27459,
"text": "Java"
},
{
"code": null,
"e": 27472,
"s": 27464,
"text": "Python3"
},
{
"code": null,
"e": 27475,
"s": 27472,
"text": "C#"
},
{
"code": null,
"e": 27486,
"s": 27475,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print the contents// of the Listvoid printList(vector<string> arrL){ arrL.erase(find(arrL.begin(), arrL.end(), \"\")); for (int i = 0; i < arrL.size(); i++) cout << arrL[i] << \" \";} // Function to returns the arraylist which contains// all the sub-sequences of strvector<string> getSequence(string str){ // If string is empty if (str.length() == 0) { // Return an empty arraylist vector<string> empty; empty.push_back(\"\"); return empty; } // Take first character of str char ch = str[0]; // Take sub-string starting from the // second character string subStr = str.substr(1); // Recursive call for all the sub-sequences // starting from the second character vector<string> subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist vector<string> res; for(string val : subSequences) { res.push_back(val); res.push_back(ch + val); } // Return the resultant arraylist return res;} int main(){ string str = \"geek\"; printList(getSequence(str)); return 0;} // This code is contributed by rameshtravel07.",
"e": 28847,
"s": 27486,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.ArrayList; public class GFG { // Utility function to print the contents // of the ArrayList static void printArrayList(ArrayList<String> arrL) { arrL.remove(\"\"); for (int i = 0; i < arrL.size(); i++) System.out.print(arrL.get(i) + \" \"); } // Function to returns the arraylist which contains // all the sub-sequences of str public static ArrayList<String> getSequence(String str) { // If string is empty if (str.length() == 0) { // Return an empty arraylist ArrayList<String> empty = new ArrayList<>(); empty.add(\"\"); return empty; } // Take first character of str char ch = str.charAt(0); // Take sub-string starting from the // second character String subStr = str.substring(1); // Recursive call for all the sub-sequences // starting from the second character ArrayList<String> subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist ArrayList<String> res = new ArrayList<>(); for (String val : subSequences) { res.add(val); res.add(ch + val); } // Return the resultant arraylist return res; } // Driver code public static void main(String[] args) { String str = \"geek\"; printArrayList(getSequence(str)); // System.out.print(getSequence(str)); }}",
"e": 30501,
"s": 28847,
"text": null
},
{
"code": "# Python implementation of the approach # Utility function to print the contents# of the ArrayListdef printArrayList(arrL): arrL.remove(\"\") print(*arrL, sep = \" \") # Function to returns the arraylist which contains# all the sub-sequences of strdef getSequence(Str): # If string is empty if(len(Str) == 0): # Return an empty arraylist empty = [] empty.append(\"\") return empty # Take first character of str ch = Str[0] # Take sub-string starting from the # second character subStr = Str[1:] # Recursive call for all the sub-sequences # starting from the second character subSequences = getSequence(subStr) # Add first character from str in the beginning # of every character from the sub-sequences # and then store it into the resultant arraylist res = [] for val in subSequences: res.append(val) res.append(ch + val) # Return the resultant arraylist return res # Driver codeStr = \"geek\"printArrayList(getSequence(Str)) # This code is contributed by avanitrachhadiya2155",
"e": 31577,
"s": 30501,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Utility function to print the contents // of the List static void printList(List<String> arrL) { arrL.Remove(\"\"); for (int i = 0; i < arrL.Count; i++) Console.Write(arrL[i] + \" \"); } // Function to returns the arraylist which contains // all the sub-sequences of str public static List<String> getSequence(String str) { // If string is empty if (str.Length == 0) { // Return an empty arraylist List<String> empty = new List<String>(); empty.Add(\"\"); return empty; } // Take first character of str char ch = str[0]; // Take sub-string starting from the // second character String subStr = str.Substring(1); // Recursive call for all the sub-sequences // starting from the second character List<String> subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist List<String> res = new List<String>(); foreach (String val in subSequences) { res.Add(val); res.Add(ch + val); } // Return the resultant arraylist return res; } // Driver code public static void Main(String[] args) { String str = \"geek\"; printList(getSequence(str)); // Console.Write(getSequence(str)); }} // This code is contributed by Rohit_ranjan",
"e": 33216,
"s": 31577,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Utility function to print the contents // of the ArrayList function printArrayList(arrL) { arrL.splice(arrL.indexOf(\"\"), 1); for (let i = 0; i < arrL.length; i++) document.write(arrL[i] + \" \"); } // Function to returns the arraylist which contains // all the sub-sequences of str function getSequence(str) { // If string is empty if (str.length == 0) { // Return an empty arraylist let empty = []; empty.push(\"\"); return empty; } // Take first character of str let ch = str[0]; // Take sub-string starting from the // second character let subStr = str.substring(1); // Recursive call for all the sub-sequences // starting from the second character let subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist let res = []; for (let val = 0; val < subSequences.length; val++) { res.push(subSequences[val]); res.push(ch + subSequences[val]); } // Return the resultant arraylist return res; } let str = \"geek\"; printArrayList(getSequence(str)); </script>",
"e": 34640,
"s": 33216,
"text": null
},
{
"code": null,
"e": 34687,
"s": 34640,
"text": "g e ge e ge ee gee k gk ek gek ek gek eek geek"
},
{
"code": null,
"e": 34794,
"s": 34689,
"text": "Alternate Solution: One by one fix characters and recursively generate all subsets starting from them. "
},
{
"code": null,
"e": 34798,
"s": 34794,
"text": "C++"
},
{
"code": null,
"e": 34803,
"s": 34798,
"text": "Java"
},
{
"code": null,
"e": 34811,
"s": 34803,
"text": "Python3"
},
{
"code": null,
"e": 34814,
"s": 34811,
"text": "C#"
},
{
"code": null,
"e": 34825,
"s": 34814,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print all the sub-sequences// of a stringvoid printSubSeq(string sub, string ans){ if (sub.length() == 0) { cout << \"\" << ans << \" \"; return; } // First character of sub char ch = sub[0]; // Sub-string starting from second // character of sub string ros = sub.substr(1); // Excluding first character printSubSeq(ros, ans); // Including first character printSubSeq(ros, ans + ch);} // Driver codeint main(){ string str = \"abc\"; printSubSeq(str, \"\"); return 0;} // This code is contributed by divyesh072019",
"e": 35489,
"s": 34825,
"text": null
},
{
"code": "// Java implementation of the approachpublic class sub_sequence { // Function to print all the sub-sequences // of a string public static void printSubSeq(String sub, String ans) { if (sub.length() == 0) { System.out.print(\"\" + ans + \" \"); return; } // First character of sub char ch = sub.charAt(0); // Sub-string starting from second // character of sub String ros = sub.substring(1); // Excluding first character printSubSeq(ros, ans); // Including first character printSubSeq(ros, ans + ch); } // Driver code public static void main(String[] args) { String str = \"abc\"; printSubSeq(str, \"\"); }}",
"e": 36268,
"s": 35489,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to print all the sub-sequences# of a stringdef printSubSeq(sub, ans) : if (len(sub) == 0) : print(ans , end = \" \") return # First character of sub ch = sub[0] # Sub-string starting from second # character of sub ros = sub[1 : ] # Excluding first character printSubSeq(ros, ans) # Including first character printSubSeq(ros, ans + ch) Str = \"abc\"printSubSeq(Str, \"\") # This code iscontributed by divyeshrabadiya07",
"e": 36781,
"s": 36268,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to print all the // sub-sequences of a stringpublic static void printSubSeq(string sub, string ans){ if (sub.Length == 0) { Console.Write(\"\" + ans + \" \"); return; } // First character of sub char ch = sub[0]; // Sub-string starting from second // character of sub string ros = sub.Substring(1); // Excluding first character printSubSeq(ros, ans); // Including first character printSubSeq(ros, ans + ch);} // Driver codepublic static void Main(){ string str = \"abc\"; printSubSeq(str, \"\") ;}} // This code is contributed by Ryuga",
"e": 37472,
"s": 36781,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to print all the // sub-sequences of a string function printSubSeq(sub, ans) { if (sub.length == 0) { document.write(\"\" + ans + \" \"); return; } // First character of sub let ch = sub[0]; // Sub-string starting from second // character of sub let ros = sub.substring(1); // Excluding first character printSubSeq(ros, ans); // Including first character printSubSeq(ros, ans + ch); } let str = \"abc\"; printSubSeq(str, \"\") ; // This code is contributed by decode2207.</script>",
"e": 38155,
"s": 37472,
"text": null
},
{
"code": null,
"e": 38174,
"s": 38155,
"text": "c b bc a ac ab abc"
},
{
"code": null,
"e": 38184,
"s": 38176,
"text": "ankthon"
},
{
"code": null,
"e": 38197,
"s": 38184,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 38211,
"s": 38197,
"text": "divyesh072019"
},
{
"code": null,
"e": 38229,
"s": 38211,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 38250,
"s": 38229,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 38261,
"s": 38250,
"text": "decode2207"
},
{
"code": null,
"e": 38270,
"s": 38261,
"text": "suresh07"
},
{
"code": null,
"e": 38285,
"s": 38270,
"text": "rameshtravel07"
},
{
"code": null,
"e": 38298,
"s": 38285,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 38313,
"s": 38298,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 38325,
"s": 38313,
"text": "subsequence"
},
{
"code": null,
"e": 38334,
"s": 38325,
"text": "Articles"
},
{
"code": null,
"e": 38358,
"s": 38334,
"text": "Competitive Programming"
},
{
"code": null,
"e": 38368,
"s": 38358,
"text": "Recursion"
},
{
"code": null,
"e": 38378,
"s": 38368,
"text": "Recursion"
},
{
"code": null,
"e": 38476,
"s": 38378,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38506,
"s": 38476,
"text": "Service-Oriented Architecture"
},
{
"code": null,
"e": 38527,
"s": 38506,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 38586,
"s": 38527,
"text": "Amazon’s most frequently asked interview questions | Set 2"
},
{
"code": null,
"e": 38653,
"s": 38586,
"text": "What's the difference between Scripting and Programming Languages?"
},
{
"code": null,
"e": 38713,
"s": 38653,
"text": "Must Do Questions for Companies like TCS, CTS, HCL, IBM ..."
},
{
"code": null,
"e": 38756,
"s": 38713,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 38799,
"s": 38756,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 38840,
"s": 38799,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 38918,
"s": 38840,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Program to draw a Hut in using OpenGL in C++ - GeeksforGeeks | 10 Oct, 2021
In this article, we will discuss how to create a front-facing view of a hut in OpenGL using two basic shapes i.e. triangle and rectangle.
Approach: Follow the steps below to solve the problem:
Initialize the toolkit using the function glutInit (&argc, argv).
Set the display mode and specify the color scheme using the function glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB).
Specify the window size using the function glutInitWindowSize(1200, 740).
Set the starting position for the window using the function glutInitWindowPosition (0, 0).
Initialize the window and set the title using the function glutCreateWindow(“Basic hut like structure”).
Initialize the myInit() function and perform the following steps:Set the background color to orange using the function glClearColor(1.0, 0.5, 0.0, 1.0).Specify the display area using the function gluOrtho2D(0.0, 400.0, 0.0, 400.0).
Set the background color to orange using the function glClearColor(1.0, 0.5, 0.0, 1.0).
Specify the display area using the function gluOrtho2D(0.0, 400.0, 0.0, 400.0).
Initialize the myDisplay() function and perform the following steps:Clear the screen using the function glClear(GL_COLOR_BUFFER_BIT).The rectangular part of the hut can be drawn using the function glPointSize(4.0).Set the drawing color to glColor3f(0.5f, 0.5f, 0.5f).Create the 2 windows, the door, the top triangle, and the main rectangle of the house using the polygon command and setting their vertices by using the functions:glBegin(GL_POLYGON);glVertex2i ( x, y );Color the polygons in the above steps using the function glColor3f(R, G, B).
Clear the screen using the function glClear(GL_COLOR_BUFFER_BIT).
The rectangular part of the hut can be drawn using the function glPointSize(4.0).
Set the drawing color to glColor3f(0.5f, 0.5f, 0.5f).
Create the 2 windows, the door, the top triangle, and the main rectangle of the house using the polygon command and setting their vertices by using the functions:glBegin(GL_POLYGON);glVertex2i ( x, y );
glBegin(GL_POLYGON);
glVertex2i ( x, y );
Color the polygons in the above steps using the function glColor3f(R, G, B).
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <GL\glut.h>#include <iostream>#include <windows.h>using namespace std; // Function to initialize the driversvoid myInit(void){ // Clear all the screen color glClearColor(1.0, 0.5, 0.0, 1.0); // Sets background color to orang glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Specify the display area gluOrtho2D(0.0, 400.0, 0.0, 400.0);} // Function to display the Hut like// structure on the consolevoid myDisplay(void){ // Clear the screen buffer glClear(GL_COLOR_BUFFER_BIT); glPointSize(4.0); // Rectangular part of hut glColor3f(0.5f, 0.5f, 0.5f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(40, 40); glVertex2i(320, 40); glVertex2i(40, 200); glVertex2i(320, 200); glVertex2i(40, 200); glVertex2i(40, 40); glVertex2i(320, 200); glVertex2i(320, 40); glEnd(); // Right Window Update glColor3f(1.0f, 0.0f, 0.0f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(220, 60); glVertex2i(300, 60); glVertex2i(220, 150); glVertex2i(300, 150); glVertex2i(220, 60); glVertex2i(220, 150); glVertex2i(300, 150); glVertex2i(300, 60); glEnd(); // Right Window Update part 2 glColor3f(1.0f, 0.0f, 0.0f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(220, 170); glVertex2i(300, 170); glVertex2i(220, 190); glVertex2i(300, 190); glVertex2i(220, 170); glVertex2i(220, 190); glVertex2i(300, 190); glVertex2i(300, 170); glEnd(); // Door glColor3f(0.60f, 0.42f, 0.16f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(130, 40); glVertex2i(130, 160); glVertex2i(130, 160); glVertex2i(180, 160); glVertex2i(180, 100); glVertex2i(180, 40); glVertex2i(120, 40); glVertex2i(170, 40); glEnd(); // Create Door Part 2 glColor3f(0.60f, 0.42f, 0.16f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(130, 170); glVertex2i(130, 180); glVertex2i(130, 180); glVertex2i(180, 180); glVertex2i(180, 170); glVertex2i(180, 180); glVertex2i(130, 170); glVertex2i(180, 170); glEnd(); // Hut's top triangle part glColor3f(1.0f, 0.0f, 1.0f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(10, 200); glVertex2i(340, 200); glVertex2i(200, 390); glVertex2i(10, 200); glVertex2i(200, 390); glEnd(); // Sends all output to display glFlush();} // Driver Codeint main(int argc, char** argv){ // Initialize the init function glutInit(&argc, argv); // Initialize the toolkit; glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB); // Sets the display mode and // specify the colour scheme glutInitWindowSize(1200, 740); // Specify the window size glutInitWindowPosition(0, 0); // Sets the starting position // for the window glutCreateWindow("Basic hut like" " structure"); // Creates the window and // sets the title glutDisplayFunc(myDisplay); myInit(); // Additional initializations glutMainLoop(); // Go into a loop until event // occurs return 0;}
Output:
surindertarika1234
surinderdawra388
c-graphics
computer-graphics
OpenGL
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL | [
{
"code": null,
"e": 25763,
"s": 25735,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 25901,
"s": 25763,
"text": "In this article, we will discuss how to create a front-facing view of a hut in OpenGL using two basic shapes i.e. triangle and rectangle."
},
{
"code": null,
"e": 25956,
"s": 25901,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26022,
"s": 25956,
"text": "Initialize the toolkit using the function glutInit (&argc, argv)."
},
{
"code": null,
"e": 26136,
"s": 26022,
"text": "Set the display mode and specify the color scheme using the function glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)."
},
{
"code": null,
"e": 26210,
"s": 26136,
"text": "Specify the window size using the function glutInitWindowSize(1200, 740)."
},
{
"code": null,
"e": 26301,
"s": 26210,
"text": "Set the starting position for the window using the function glutInitWindowPosition (0, 0)."
},
{
"code": null,
"e": 26406,
"s": 26301,
"text": "Initialize the window and set the title using the function glutCreateWindow(“Basic hut like structure”)."
},
{
"code": null,
"e": 26638,
"s": 26406,
"text": "Initialize the myInit() function and perform the following steps:Set the background color to orange using the function glClearColor(1.0, 0.5, 0.0, 1.0).Specify the display area using the function gluOrtho2D(0.0, 400.0, 0.0, 400.0)."
},
{
"code": null,
"e": 26726,
"s": 26638,
"text": "Set the background color to orange using the function glClearColor(1.0, 0.5, 0.0, 1.0)."
},
{
"code": null,
"e": 26806,
"s": 26726,
"text": "Specify the display area using the function gluOrtho2D(0.0, 400.0, 0.0, 400.0)."
},
{
"code": null,
"e": 27352,
"s": 26806,
"text": "Initialize the myDisplay() function and perform the following steps:Clear the screen using the function glClear(GL_COLOR_BUFFER_BIT).The rectangular part of the hut can be drawn using the function glPointSize(4.0).Set the drawing color to glColor3f(0.5f, 0.5f, 0.5f).Create the 2 windows, the door, the top triangle, and the main rectangle of the house using the polygon command and setting their vertices by using the functions:glBegin(GL_POLYGON);glVertex2i ( x, y );Color the polygons in the above steps using the function glColor3f(R, G, B)."
},
{
"code": null,
"e": 27418,
"s": 27352,
"text": "Clear the screen using the function glClear(GL_COLOR_BUFFER_BIT)."
},
{
"code": null,
"e": 27500,
"s": 27418,
"text": "The rectangular part of the hut can be drawn using the function glPointSize(4.0)."
},
{
"code": null,
"e": 27554,
"s": 27500,
"text": "Set the drawing color to glColor3f(0.5f, 0.5f, 0.5f)."
},
{
"code": null,
"e": 27757,
"s": 27554,
"text": "Create the 2 windows, the door, the top triangle, and the main rectangle of the house using the polygon command and setting their vertices by using the functions:glBegin(GL_POLYGON);glVertex2i ( x, y );"
},
{
"code": null,
"e": 27778,
"s": 27757,
"text": "glBegin(GL_POLYGON);"
},
{
"code": null,
"e": 27799,
"s": 27778,
"text": "glVertex2i ( x, y );"
},
{
"code": null,
"e": 27876,
"s": 27799,
"text": "Color the polygons in the above steps using the function glColor3f(R, G, B)."
},
{
"code": null,
"e": 27927,
"s": 27876,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27931,
"s": 27927,
"text": "C++"
},
{
"code": "// C++ program for the above approach #include <GL\\glut.h>#include <iostream>#include <windows.h>using namespace std; // Function to initialize the driversvoid myInit(void){ // Clear all the screen color glClearColor(1.0, 0.5, 0.0, 1.0); // Sets background color to orang glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Specify the display area gluOrtho2D(0.0, 400.0, 0.0, 400.0);} // Function to display the Hut like// structure on the consolevoid myDisplay(void){ // Clear the screen buffer glClear(GL_COLOR_BUFFER_BIT); glPointSize(4.0); // Rectangular part of hut glColor3f(0.5f, 0.5f, 0.5f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(40, 40); glVertex2i(320, 40); glVertex2i(40, 200); glVertex2i(320, 200); glVertex2i(40, 200); glVertex2i(40, 40); glVertex2i(320, 200); glVertex2i(320, 40); glEnd(); // Right Window Update glColor3f(1.0f, 0.0f, 0.0f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(220, 60); glVertex2i(300, 60); glVertex2i(220, 150); glVertex2i(300, 150); glVertex2i(220, 60); glVertex2i(220, 150); glVertex2i(300, 150); glVertex2i(300, 60); glEnd(); // Right Window Update part 2 glColor3f(1.0f, 0.0f, 0.0f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(220, 170); glVertex2i(300, 170); glVertex2i(220, 190); glVertex2i(300, 190); glVertex2i(220, 170); glVertex2i(220, 190); glVertex2i(300, 190); glVertex2i(300, 170); glEnd(); // Door glColor3f(0.60f, 0.42f, 0.16f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(130, 40); glVertex2i(130, 160); glVertex2i(130, 160); glVertex2i(180, 160); glVertex2i(180, 100); glVertex2i(180, 40); glVertex2i(120, 40); glVertex2i(170, 40); glEnd(); // Create Door Part 2 glColor3f(0.60f, 0.42f, 0.16f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(130, 170); glVertex2i(130, 180); glVertex2i(130, 180); glVertex2i(180, 180); glVertex2i(180, 170); glVertex2i(180, 180); glVertex2i(130, 170); glVertex2i(180, 170); glEnd(); // Hut's top triangle part glColor3f(1.0f, 0.0f, 1.0f); // Begin the polygon glBegin(GL_POLYGON); // Create the polygon glVertex2i(10, 200); glVertex2i(340, 200); glVertex2i(200, 390); glVertex2i(10, 200); glVertex2i(200, 390); glEnd(); // Sends all output to display glFlush();} // Driver Codeint main(int argc, char** argv){ // Initialize the init function glutInit(&argc, argv); // Initialize the toolkit; glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB); // Sets the display mode and // specify the colour scheme glutInitWindowSize(1200, 740); // Specify the window size glutInitWindowPosition(0, 0); // Sets the starting position // for the window glutCreateWindow(\"Basic hut like\" \" structure\"); // Creates the window and // sets the title glutDisplayFunc(myDisplay); myInit(); // Additional initializations glutMainLoop(); // Go into a loop until event // occurs return 0;}",
"e": 31263,
"s": 27931,
"text": null
},
{
"code": null,
"e": 31271,
"s": 31263,
"text": "Output:"
},
{
"code": null,
"e": 31290,
"s": 31271,
"text": "surindertarika1234"
},
{
"code": null,
"e": 31307,
"s": 31290,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31318,
"s": 31307,
"text": "c-graphics"
},
{
"code": null,
"e": 31336,
"s": 31318,
"text": "computer-graphics"
},
{
"code": null,
"e": 31343,
"s": 31336,
"text": "OpenGL"
},
{
"code": null,
"e": 31347,
"s": 31343,
"text": "C++"
},
{
"code": null,
"e": 31360,
"s": 31347,
"text": "C++ Programs"
},
{
"code": null,
"e": 31364,
"s": 31360,
"text": "CPP"
},
{
"code": null,
"e": 31462,
"s": 31364,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31481,
"s": 31462,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 31524,
"s": 31481,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 31548,
"s": 31524,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 31575,
"s": 31548,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 31599,
"s": 31575,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 31634,
"s": 31599,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 31678,
"s": 31634,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 31704,
"s": 31678,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 31763,
"s": 31704,
"text": "How to return multiple values from a function in C or C++?"
}
] |
How to compare two objects to determine the first object contains equivalent property values to the second object in JavaScript ? - GeeksforGeeks | 23 Apr, 2021
Given two objects obj1 and obj2 and the task is to check the obj1 contains all the property values of obj2 in JavaScript.
Input: obj1: { name: "John", age: 23; degree: "CS" }
obj2: {age: 23, degree: "CS"}
Output: true
Input: obj1: { name: "John", degree: "CS" }
obj2: {name: "Max", age: 23, degree: "CS"}
Output: false
To solve this problem we follow the following approaches.
Approach 1: It is a naive approach to solve this problem. In this approach, we iterate the obj2 using the for..in loop and at every iteration, we check the current key of both objects are not equal we return false otherwise after completion the loop we return true.
Example:
Javascript
<script> // Define the first object let obj1 = { name: "John", age: 23, degree: "CS" } // Define the second object let obj2 = { age: 23, degree: "CS" } // Define the function check function check(obj1, obj2) { // Iterate the obj2 using for..in for (key in obj2) { // Check if both objects do // not have the equal values // of same key if (obj1[key] !== obj2[key]) { return false; } } return true } // Call the function console.log(check(obj1, obj2))</script>
Output:
true
Approach 2: In this approach, we create an array of all the keys of obj2 by using the Object.keys() method and then using the Array.every() method we check if all the properties of obj2 are equal to obj1 or not.
Example:
Javascript
<script> // Define the first object let obj1 = { name: "John", age: 23, degree: "CS" } // Define the Second object let obj2 = { age: 23, degree: "CS" } // Define the function check function check(obj1, obj2) { return Object // Get all the keys in array .keys(obj2) .every(val => obj1.hasOwnProperty(val) && obj1[val] === obj2[val]) } // Call the function console.log(check(obj1, obj2))</script>
Output:
true
JavaScript-Methods
javascript-object
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 26667,
"s": 26545,
"text": "Given two objects obj1 and obj2 and the task is to check the obj1 contains all the property values of obj2 in JavaScript."
},
{
"code": null,
"e": 26895,
"s": 26667,
"text": "Input: obj1: { name: \"John\", age: 23; degree: \"CS\" }\n obj2: {age: 23, degree: \"CS\"}\n \nOutput: true\n\nInput: obj1: { name: \"John\", degree: \"CS\" }\n obj2: {name: \"Max\", age: 23, degree: \"CS\"}\n \nOutput: false"
},
{
"code": null,
"e": 26953,
"s": 26895,
"text": "To solve this problem we follow the following approaches."
},
{
"code": null,
"e": 27219,
"s": 26953,
"text": "Approach 1: It is a naive approach to solve this problem. In this approach, we iterate the obj2 using the for..in loop and at every iteration, we check the current key of both objects are not equal we return false otherwise after completion the loop we return true."
},
{
"code": null,
"e": 27228,
"s": 27219,
"text": "Example:"
},
{
"code": null,
"e": 27239,
"s": 27228,
"text": "Javascript"
},
{
"code": "<script> // Define the first object let obj1 = { name: \"John\", age: 23, degree: \"CS\" } // Define the second object let obj2 = { age: 23, degree: \"CS\" } // Define the function check function check(obj1, obj2) { // Iterate the obj2 using for..in for (key in obj2) { // Check if both objects do // not have the equal values // of same key if (obj1[key] !== obj2[key]) { return false; } } return true } // Call the function console.log(check(obj1, obj2))</script>",
"e": 27890,
"s": 27239,
"text": null
},
{
"code": null,
"e": 27898,
"s": 27890,
"text": "Output:"
},
{
"code": null,
"e": 27903,
"s": 27898,
"text": "true"
},
{
"code": null,
"e": 28115,
"s": 27903,
"text": "Approach 2: In this approach, we create an array of all the keys of obj2 by using the Object.keys() method and then using the Array.every() method we check if all the properties of obj2 are equal to obj1 or not."
},
{
"code": null,
"e": 28124,
"s": 28115,
"text": "Example:"
},
{
"code": null,
"e": 28135,
"s": 28124,
"text": "Javascript"
},
{
"code": "<script> // Define the first object let obj1 = { name: \"John\", age: 23, degree: \"CS\" } // Define the Second object let obj2 = { age: 23, degree: \"CS\" } // Define the function check function check(obj1, obj2) { return Object // Get all the keys in array .keys(obj2) .every(val => obj1.hasOwnProperty(val) && obj1[val] === obj2[val]) } // Call the function console.log(check(obj1, obj2))</script>",
"e": 28664,
"s": 28135,
"text": null
},
{
"code": null,
"e": 28672,
"s": 28664,
"text": "Output:"
},
{
"code": null,
"e": 28677,
"s": 28672,
"text": "true"
},
{
"code": null,
"e": 28696,
"s": 28677,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 28714,
"s": 28696,
"text": "javascript-object"
},
{
"code": null,
"e": 28735,
"s": 28714,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28742,
"s": 28735,
"text": "Picked"
},
{
"code": null,
"e": 28753,
"s": 28742,
"text": "JavaScript"
},
{
"code": null,
"e": 28770,
"s": 28753,
"text": "Web Technologies"
},
{
"code": null,
"e": 28868,
"s": 28770,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28908,
"s": 28868,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28969,
"s": 28908,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29010,
"s": 28969,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29032,
"s": 29010,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 29086,
"s": 29032,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29126,
"s": 29086,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29159,
"s": 29126,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29202,
"s": 29159,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29252,
"s": 29202,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |