title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
mysqlcheck - Unix, Linux Command | The
mysqlcheck
client performs table maintenance: It checks, repairs, optimizes, or analyzes tables.
Each table is locked and therefore unavailable to other sessions while it is being processed, although for check operations, the table is locked with a
READ
lock only (see
Section 12.3.5, \(lqLOCK TABLES and UNLOCK TABLES Syntax\(rq, for more information about
READ
and
WRITE
locks). Table maintenance operations can be time-consuming, particularly for large tables. If you use the
--databases
or
--all-databases
option to process all tables in one or more databases, an invocation of
mysqlcheck
might take a long time. (This is also true for
mysql_upgrade
because that program invokes
mysqlcheck
to check all tables and repair them if necessary.)
mysqlcheck
is similar in function to
myisamchk, but works differently. The main operational difference is that
mysqlcheck
must be used when the
mysqld
server is running, whereas
myisamchk
should be used when it is not. The benefit of using
mysqlcheck
is that you do not have to stop the server to perform table maintenance.
mysqlcheck
uses the SQL statements
CHECK TABLE,
REPAIR TABLE,
ANALYZE TABLE, and
OPTIMIZE TABLE
in a convenient way for the user. It determines which statements to use for the operation you want to perform, and then sends the statements to the server to be executed. For details about which storage engines each statement works with, see the descriptions for those statements in
Section 12.4.2, \(lqTable Maintenance Statements\(rq.
The
MyISAM
storage engine supports all four maintenance operations, so
mysqlcheck
can be used to perform any of them on
MyISAM
tables. Other storage engines do not necessarily support all operations. In such cases, an error message is displayed. For example, if
test.t
is a
MEMORY
table, an attempt to check it produces this result:
shell> mysqlcheck test t
test.t
note : The storage engine for the table doesn't support check
If
mysqlcheck
is unable to repair a table, see
Section 2.13.4, \(lqRebuilding or Repairing Tables or Indexes\(rq
for manual table repair strategies. This will be the case, for example, for
InnoDB
tables, which can be checked with
CHECK TABLE, but not repaired with
REPAIR TABLE.
The use of
mysqlcheck
with partitioned tables is not supported before MySQL 5.1.27.
Caution
It is best to make a backup of a table before performing a table repair operation; under some circumstances the operation might cause data loss. Possible causes include but are not limited to file system errors.
There are three general ways to invoke
mysqlcheck:
shell> mysqlcheck [options] db_name [tbl_name ...]
shell> mysqlcheck [options] --databases db_name ...
shell> mysqlcheck [options] --all-databases
If you do not name any tables following
db_name
or if you use the
--databases
or
--all-databases
option, entire databases are checked.
mysqlcheck
has a special feature compared to other client programs. The default behavior of checking tables (--check) can be changed by renaming the binary. If you want to have a tool that repairs tables by default, you should just make a copy of
mysqlcheck
named
mysqlrepair, or make a symbolic link to
mysqlcheck
named
mysqlrepair. If you invoke
mysqlrepair, it repairs tables.
The names shown in the following table can be used to change
mysqlcheck
default behavior.
mysqlcheck
supports the following options, which can be specified on the command line or in the
[mysqlcheck]
and
[client]
option file groups.
mysqlcheck
also supports the options for processing option files described at
Section 4.2.3.3.1, \(lqCommand-Line Options that Affect Option-File Handling\(rq.
o
Display a help message and exit.
o
Check all tables in all databases. This is the same as using the
--databases
option and naming all the databases on the command line.
o
Instead of issuing a statement for each table, execute a single statement for each database that names all the tables from that database to be processed.
o
Analyze the tables.
o
If a checked table is corrupted, automatically fix it. Any necessary repairs are done after all tables have been checked.
o
On a computer having multiple network interfaces, this option can be used to select which interface is employed when connecting to the MySQL server.
This option is supported only in the version of
mysqlcheck
that is supplied with MySQL Cluster, beginning with MySQL Cluster NDB 6.3.4. It is not available in standard MySQL 5.1 releases.
o
The directory where character sets are installed. See
Section 9.5, \(lqCharacter Set Configuration\(rq.
o
Check the tables for errors. This is the default operation.
o
Check only tables that have changed since the last check or that have not been closed properly.
o
Invoke
CHECK TABLE
with the
FOR UPGRADE
option to check tables for incompatibilities with the current version of the server. This option automatically enables the
--fix-db-names
and
--fix-table-names
options.
--check-upgrade
was added in MySQL 5.1.7.
o
Compress all information sent between the client and the server if both support compression.
o
Process all tables in the named databases. Normally,
mysqlcheck
treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names.
o
Write a debugging log. A typical
debug_options
string is
'd:t:o,file_name'. The default is
'd:t:o'.
o
Print some debugging information when the program exits. This option was added in MySQL 5.1.21.
o
Print debugging information and memory and CPU usage statistics when the program exits. This option was added in MySQL 5.1.14.
o
Use
charset_name
as the default character set. See
Section 9.5, \(lqCharacter Set Configuration\(rq.
o
If you are using this option to check tables, it ensures that they are 100% consistent but takes a long time.
If you are using this option to repair tables, it runs an extended repair that may not only take a long time to execute, but may produce a lot of garbage rows also!
o
Check only tables that have not been closed properly.
o
Convert database names to 5.1 format. Only database names that contain special characters are affected. This option was added in MySQL 5.1.7.
o
Convert table names to 5.1 format. Only table names that contain special characters are affected. This option was added in MySQL 5.1.7. As of MySQL 5.1.23, this option also applies to views.
o
Continue even if an SQL error occurs.
o
Connect to the MySQL server on the given host.
o
Do a check that is faster than an
--extended
operation. This finds only 99.99% of all errors, which should be good enough in most cases.
o
Optimize the tables.
o
The password to use when connecting to the server. If you use the short option form (-p), you
cannot
have a space between the option and the password. If you omit the
password
value following the
--password
or
-p
option on the command line,
mysqlcheck
prompts for one.
Specifying a password on the command line should be considered insecure. See
Section 5.3.2.2, \(lqEnd-User Guidelines for Password Security\(rq. You can use an option file to avoid giving the password on the command line.
o
On Windows, connect to the server using a named pipe. This option applies only if the server supports named-pipe connections.
o
The TCP/IP port number to use for the connection.
o
The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For details on the permissible values, see
Section 4.2.2, \(lqConnecting to the MySQL Server\(rq.
o
If you are using this option to check tables, it prevents the check from scanning the rows to check for incorrect links. This is the fastest check method.
If you are using this option to repair tables, it tries to repair only the index tree. This is the fastest repair method.
o
Perform a repair that can fix almost anything except unique keys that are not unique.
o
Silent mode. Print only error messages.
o
For connections to
localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.
o
Options that begin with
--ssl
specify whether to connect to the server using SSL and indicate where to find SSL keys and certificates. See
Section 5.5.6.3, \(lqSSL Command Options\(rq.
o
Override the
--databases
or
-B
option. All name arguments following the option are regarded as table names.
o
For repair operations on
MyISAM
tables, get the table structure from the
.frm
file so that the table can be repaired even if the
.MYI
header is corrupted.
o
The MySQL user name to use when connecting to the server.
o
Verbose mode. Print information about the various stages of program operation.
o
Display version information and exit.
o
This option is enabled by default, so that
ANALYZE TABLE,
OPTIMIZE TABLE, and
REPAIR TABLE
statements generated by
mysqlcheck
are written to the binary log. Use
--skip-write-binlog
to cause
NO_WRITE_TO_BINLOG
to be added to the statements so that they are not logged. Use the
--skip-write-binlog
when these statements should not be sent to replication slaves or run when using the binary logs for recovery from backup. This option was added in MySQL 5.1.18.
Copyright © 1997, 2011, Oracle and/or its affiliates. All rights reserved.
This documentation is free software; you can redistribute it and/or modify it only under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License.
This documentation is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with the program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or see http://www.gnu.org/licenses/.
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10680,
"s": 10577,
"text": "\nThe\nmysqlcheck\nclient performs table maintenance: It checks, repairs, optimizes, or analyzes tables.\n"
},
{
"code": null,
"e": 11330,
"s": 10680,
"text": "\nEach table is locked and therefore unavailable to other sessions while it is being processed, although for check operations, the table is locked with a\nREAD\nlock only (see\nSection 12.3.5, \\(lqLOCK TABLES and UNLOCK TABLES Syntax\\(rq, for more information about\nREAD\nand\nWRITE\nlocks). Table maintenance operations can be time-consuming, particularly for large tables. If you use the\n--databases\nor\n--all-databases\noption to process all tables in one or more databases, an invocation of\nmysqlcheck\nmight take a long time. (This is also true for\nmysql_upgrade\nbecause that program invokes\nmysqlcheck\nto check all tables and repair them if necessary.)\n"
},
{
"code": null,
"e": 11656,
"s": 11330,
"text": "\nmysqlcheck\nis similar in function to\nmyisamchk, but works differently. The main operational difference is that\nmysqlcheck\nmust be used when the\nmysqld\nserver is running, whereas\nmyisamchk\nshould be used when it is not. The benefit of using\nmysqlcheck\nis that you do not have to stop the server to perform table maintenance.\n"
},
{
"code": null,
"e": 12091,
"s": 11656,
"text": "\nmysqlcheck\nuses the SQL statements\nCHECK TABLE,\nREPAIR TABLE,\nANALYZE TABLE, and\nOPTIMIZE TABLE\nin a convenient way for the user. It determines which statements to use for the operation you want to perform, and then sends the statements to the server to be executed. For details about which storage engines each statement works with, see the descriptions for those statements in\nSection 12.4.2, \\(lqTable Maintenance Statements\\(rq.\n"
},
{
"code": null,
"e": 12426,
"s": 12091,
"text": "\nThe\nMyISAM\nstorage engine supports all four maintenance operations, so\nmysqlcheck\ncan be used to perform any of them on\nMyISAM\ntables. Other storage engines do not necessarily support all operations. In such cases, an error message is displayed. For example, if\ntest.t\nis a\nMEMORY\ntable, an attempt to check it produces this result:\n"
},
{
"code": null,
"e": 12529,
"s": 12430,
"text": "shell> mysqlcheck test t\ntest.t\nnote : The storage engine for the table doesn't support check\n"
},
{
"code": null,
"e": 12810,
"s": 12529,
"text": "\nIf\nmysqlcheck\nis unable to repair a table, see\nSection 2.13.4, \\(lqRebuilding or Repairing Tables or Indexes\\(rq\nfor manual table repair strategies. This will be the case, for example, for\nInnoDB\ntables, which can be checked with\nCHECK TABLE, but not repaired with\nREPAIR TABLE.\n"
},
{
"code": null,
"e": 12897,
"s": 12810,
"text": "\nThe use of\nmysqlcheck\nwith partitioned tables is not supported before MySQL 5.1.27.\n\n"
},
{
"code": null,
"e": 12909,
"s": 12897,
"text": "\n\n\nCaution\n"
},
{
"code": null,
"e": 13123,
"s": 12909,
"text": "\nIt is best to make a backup of a table before performing a table repair operation; under some circumstances the operation might cause data loss. Possible causes include but are not limited to file system errors.\n"
},
{
"code": null,
"e": 13178,
"s": 13125,
"text": "\nThere are three general ways to invoke\nmysqlcheck:\n"
},
{
"code": null,
"e": 13330,
"s": 13182,
"text": "shell> mysqlcheck [options] db_name [tbl_name ...]\nshell> mysqlcheck [options] --databases db_name ...\nshell> mysqlcheck [options] --all-databases\n"
},
{
"code": null,
"e": 13467,
"s": 13330,
"text": "\nIf you do not name any tables following\ndb_name\nor if you use the\n--databases\nor\n--all-databases\noption, entire databases are checked.\n"
},
{
"code": null,
"e": 13849,
"s": 13467,
"text": "\nmysqlcheck\nhas a special feature compared to other client programs. The default behavior of checking tables (--check) can be changed by renaming the binary. If you want to have a tool that repairs tables by default, you should just make a copy of\nmysqlcheck\nnamed\nmysqlrepair, or make a symbolic link to\nmysqlcheck\nnamed\nmysqlrepair. If you invoke\nmysqlrepair, it repairs tables.\n"
},
{
"code": null,
"e": 13941,
"s": 13849,
"text": "\nThe names shown in the following table can be used to change\nmysqlcheck\ndefault behavior.\n"
},
{
"code": null,
"e": 14247,
"s": 13943,
"text": "\nmysqlcheck\nsupports the following options, which can be specified on the command line or in the\n[mysqlcheck]\nand\n[client]\noption file groups.\nmysqlcheck\nalso supports the options for processing option files described at\nSection 4.2.3.3.1, \\(lqCommand-Line Options that Affect Option-File Handling\\(rq.\n"
},
{
"code": null,
"e": 14253,
"s": 14247,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 14290,
"s": 14255,
"text": "\nDisplay a help message and exit.\n"
},
{
"code": null,
"e": 14296,
"s": 14290,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 14434,
"s": 14298,
"text": "\nCheck all tables in all databases. This is the same as using the\n--databases\noption and naming all the databases on the command line.\n"
},
{
"code": null,
"e": 14440,
"s": 14434,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 14598,
"s": 14442,
"text": "\nInstead of issuing a statement for each table, execute a single statement for each database that names all the tables from that database to be processed.\n"
},
{
"code": null,
"e": 14604,
"s": 14598,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 14628,
"s": 14606,
"text": "\nAnalyze the tables.\n"
},
{
"code": null,
"e": 14634,
"s": 14628,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 14760,
"s": 14636,
"text": "\nIf a checked table is corrupted, automatically fix it. Any necessary repairs are done after all tables have been checked.\n"
},
{
"code": null,
"e": 14766,
"s": 14760,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 14919,
"s": 14768,
"text": "\nOn a computer having multiple network interfaces, this option can be used to select which interface is employed when connecting to the MySQL server.\n"
},
{
"code": null,
"e": 15109,
"s": 14919,
"text": "\nThis option is supported only in the version of\nmysqlcheck\nthat is supplied with MySQL Cluster, beginning with MySQL Cluster NDB 6.3.4. It is not available in standard MySQL 5.1 releases.\n"
},
{
"code": null,
"e": 15115,
"s": 15109,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 15223,
"s": 15117,
"text": "\nThe directory where character sets are installed. See\nSection 9.5, \\(lqCharacter Set Configuration\\(rq.\n"
},
{
"code": null,
"e": 15229,
"s": 15223,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 15293,
"s": 15231,
"text": "\nCheck the tables for errors. This is the default operation.\n"
},
{
"code": null,
"e": 15299,
"s": 15293,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 15399,
"s": 15301,
"text": "\nCheck only tables that have changed since the last check or that have not been closed properly.\n"
},
{
"code": null,
"e": 15405,
"s": 15399,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 15660,
"s": 15407,
"text": "\nInvoke\nCHECK TABLE\nwith the\nFOR UPGRADE\noption to check tables for incompatibilities with the current version of the server. This option automatically enables the\n--fix-db-names\nand\n--fix-table-names\noptions.\n--check-upgrade\nwas added in MySQL 5.1.7.\n"
},
{
"code": null,
"e": 15666,
"s": 15660,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 15763,
"s": 15668,
"text": "\nCompress all information sent between the client and the server if both support compression.\n"
},
{
"code": null,
"e": 15769,
"s": 15763,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 16009,
"s": 15771,
"text": "\nProcess all tables in the named databases. Normally,\nmysqlcheck\ntreats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names.\n"
},
{
"code": null,
"e": 16015,
"s": 16009,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 16119,
"s": 16017,
"text": "\nWrite a debugging log. A typical\ndebug_options\nstring is\n'd:t:o,file_name'. The default is\n'd:t:o'.\n"
},
{
"code": null,
"e": 16125,
"s": 16119,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 16225,
"s": 16127,
"text": "\nPrint some debugging information when the program exits. This option was added in MySQL 5.1.21.\n"
},
{
"code": null,
"e": 16231,
"s": 16225,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 16362,
"s": 16233,
"text": "\nPrint debugging information and memory and CPU usage statistics when the program exits. This option was added in MySQL 5.1.14.\n"
},
{
"code": null,
"e": 16368,
"s": 16362,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 16473,
"s": 16370,
"text": "\nUse\ncharset_name\nas the default character set. See\nSection 9.5, \\(lqCharacter Set Configuration\\(rq.\n"
},
{
"code": null,
"e": 16479,
"s": 16473,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 16593,
"s": 16481,
"text": "\nIf you are using this option to check tables, it ensures that they are 100% consistent but takes a long time.\n"
},
{
"code": null,
"e": 16760,
"s": 16593,
"text": "\nIf you are using this option to repair tables, it runs an extended repair that may not only take a long time to execute, but may produce a lot of garbage rows also!\n"
},
{
"code": null,
"e": 16766,
"s": 16760,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 16824,
"s": 16768,
"text": "\nCheck only tables that have not been closed properly.\n"
},
{
"code": null,
"e": 16830,
"s": 16824,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 16976,
"s": 16832,
"text": "\nConvert database names to 5.1 format. Only database names that contain special characters are affected. This option was added in MySQL 5.1.7.\n"
},
{
"code": null,
"e": 16982,
"s": 16976,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 17177,
"s": 16984,
"text": "\nConvert table names to 5.1 format. Only table names that contain special characters are affected. This option was added in MySQL 5.1.7. As of MySQL 5.1.23, this option also applies to views.\n"
},
{
"code": null,
"e": 17183,
"s": 17177,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 17225,
"s": 17185,
"text": "\nContinue even if an SQL error occurs.\n"
},
{
"code": null,
"e": 17231,
"s": 17225,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 17282,
"s": 17233,
"text": "\nConnect to the MySQL server on the given host.\n"
},
{
"code": null,
"e": 17288,
"s": 17282,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 17429,
"s": 17290,
"text": "\nDo a check that is faster than an\n--extended\noperation. This finds only 99.99% of all errors, which should be good enough in most cases.\n"
},
{
"code": null,
"e": 17435,
"s": 17429,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 17460,
"s": 17437,
"text": "\nOptimize the tables.\n"
},
{
"code": null,
"e": 17466,
"s": 17460,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 17739,
"s": 17468,
"text": "\nThe password to use when connecting to the server. If you use the short option form (-p), you\ncannot\nhave a space between the option and the password. If you omit the\npassword\nvalue following the\n--password\nor\n-p\noption on the command line,\nmysqlcheck\nprompts for one.\n"
},
{
"code": null,
"e": 17963,
"s": 17739,
"text": "\nSpecifying a password on the command line should be considered insecure. See\nSection 5.3.2.2, \\(lqEnd-User Guidelines for Password Security\\(rq. You can use an option file to avoid giving the password on the command line.\n"
},
{
"code": null,
"e": 17969,
"s": 17963,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 18099,
"s": 17971,
"text": "\nOn Windows, connect to the server using a named pipe. This option applies only if the server supports named-pipe connections.\n"
},
{
"code": null,
"e": 18105,
"s": 18099,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 18159,
"s": 18107,
"text": "\nThe TCP/IP port number to use for the connection.\n"
},
{
"code": null,
"e": 18165,
"s": 18159,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 18450,
"s": 18167,
"text": "\nThe connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. For details on the permissible values, see\nSection 4.2.2, \\(lqConnecting to the MySQL Server\\(rq.\n"
},
{
"code": null,
"e": 18456,
"s": 18450,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 18615,
"s": 18458,
"text": "\nIf you are using this option to check tables, it prevents the check from scanning the rows to check for incorrect links. This is the fastest check method.\n"
},
{
"code": null,
"e": 18739,
"s": 18615,
"text": "\nIf you are using this option to repair tables, it tries to repair only the index tree. This is the fastest repair method.\n"
},
{
"code": null,
"e": 18745,
"s": 18739,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 18835,
"s": 18747,
"text": "\nPerform a repair that can fix almost anything except unique keys that are not unique.\n"
},
{
"code": null,
"e": 18841,
"s": 18835,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 18885,
"s": 18843,
"text": "\nSilent mode. Print only error messages.\n"
},
{
"code": null,
"e": 18891,
"s": 18885,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 19005,
"s": 18893,
"text": "\nFor connections to\nlocalhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.\n"
},
{
"code": null,
"e": 19011,
"s": 19005,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 19200,
"s": 19013,
"text": "\nOptions that begin with\n--ssl\nspecify whether to connect to the server using SSL and indicate where to find SSL keys and certificates. See\nSection 5.5.6.3, \\(lqSSL Command Options\\(rq.\n"
},
{
"code": null,
"e": 19206,
"s": 19200,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 19318,
"s": 19208,
"text": "\nOverride the\n--databases\nor\n-B\noption. All name arguments following the option are regarded as table names.\n"
},
{
"code": null,
"e": 19324,
"s": 19318,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 19483,
"s": 19326,
"text": "\nFor repair operations on\nMyISAM\ntables, get the table structure from the\n.frm\nfile so that the table can be repaired even if the\n.MYI\nheader is corrupted.\n"
},
{
"code": null,
"e": 19489,
"s": 19483,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 19551,
"s": 19491,
"text": "\nThe MySQL user name to use when connecting to the server.\n"
},
{
"code": null,
"e": 19557,
"s": 19551,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 19640,
"s": 19559,
"text": "\nVerbose mode. Print information about the various stages of program operation.\n"
},
{
"code": null,
"e": 19646,
"s": 19640,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 19688,
"s": 19648,
"text": "\nDisplay version information and exit.\n"
},
{
"code": null,
"e": 19694,
"s": 19688,
"text": "\n\no\n\n"
},
{
"code": null,
"e": 20156,
"s": 19696,
"text": "\nThis option is enabled by default, so that\nANALYZE TABLE,\nOPTIMIZE TABLE, and\nREPAIR TABLE\nstatements generated by\nmysqlcheck\nare written to the binary log. Use\n--skip-write-binlog\nto cause\nNO_WRITE_TO_BINLOG\nto be added to the statements so that they are not logged. Use the\n--skip-write-binlog\nwhen these statements should not be sent to replication slaves or run when using the binary logs for recovery from backup. This option was added in MySQL 5.1.18.\n"
},
{
"code": null,
"e": 20233,
"s": 20156,
"text": "\nCopyright © 1997, 2011, Oracle and/or its affiliates. All rights reserved.\n"
},
{
"code": null,
"e": 20440,
"s": 20233,
"text": "\nThis documentation is free software; you can redistribute it and/or modify it only under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License.\n"
},
{
"code": null,
"e": 20681,
"s": 20440,
"text": "\nThis documentation is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n"
},
{
"code": null,
"e": 20922,
"s": 20681,
"text": "\nYou should have received a copy of the GNU General Public License along with the program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or see http://www.gnu.org/licenses/.\n"
},
{
"code": null,
"e": 20941,
"s": 20924,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 20976,
"s": 20941,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 21004,
"s": 20976,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 21038,
"s": 21004,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 21055,
"s": 21038,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 21088,
"s": 21055,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 21099,
"s": 21088,
"text": " Pradeep D"
},
{
"code": null,
"e": 21134,
"s": 21099,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 21150,
"s": 21134,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 21183,
"s": 21150,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 21195,
"s": 21183,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 21227,
"s": 21195,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 21235,
"s": 21227,
"text": " Uplatz"
},
{
"code": null,
"e": 21242,
"s": 21235,
"text": " Print"
},
{
"code": null,
"e": 21253,
"s": 21242,
"text": " Add Notes"
}
]
|
How to align two elements left and right using tailwind CSS ? - GeeksforGeeks | 21 May, 2021
In this article, we will learn how to align two HTML elements on the left and right sides of a document using Tailwind CSS.
You can easily float the elements to left and right using Tailwind CSS. This can be done using either tailwind flex or flow-root classes.
Classes used:
flow-root: This class quickly clears floated content within a container by adding a flow-root utility.
position: This is used for controlling the placement of positioned elements.
Method 1: Using flow-root utility
Note: The class flow-root is added in the upgraded version i.e. v2.0 or greater in Tailwind. If you have not upgraded then simply replace flow-root with clearfix in the codes. The clearfix class has been removed since flow-root is a simpler solution to the same problem in modern browsers.
Syntax:
<div class="flow-root">
<p class="float-left">Welcome to GeeksforGeeks</p>
<p class="float-right">A complete portal for geeks</p>
</div>
Example 1: Add flow-root class to the parent ( div) of the element that you have to align left or right.
HTML
<!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> <style> body, h2 { text-align: center; } </style></head> <body> <h2 style="color:green"> GeeksforGeeks </h2> <b>Positions using class flow-root</b> <br /><br /> <div class="flow-root "> <p class="float-left text-green-600"> Welcome to GeeksforGeeks </p> <p class="float-right text-green-800"> A complete portal for geeks </p> </div></body> </html>
Output:
Method 2: Tailwind CSS Position class
Syntax:
<div class="relative">
<p class="absolute left-0">
Welcome to GeeksforGeeks
</p>
<p class="absolute right-0">
A complete portal for geeks
</p>
</div>
Note: You can use the {top|right|bottom|left|inset}-0 utilities to anchor absolutely positioned elements against any of the edges of the nearest positioned parent. You can also use the top and bottom parameters to position the element in the way that you want.
Parameters:
relative: This class is used to set the position of an element relative to the normal flow of the document.
absolute: This class is used to set the position of an element outside the normal flow of the document, causing neighboring elements to act as if the element does not exist.
left-0 : It positions the element in the left of the screen.
right-0 : It positions the element in the right side of the screen.
top-0: It positions the element in the top side of the screen.
bottom-0 : It positions the element on the bottom side of the screen.
Example 2:
HTML
<!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> <style> body, h2 { text-align: center; } </style></head> <body> <h2 style="color:green"> GeeksforGeeks </h2> <b> Position left and right using relative class </b> <br /><br /> <div class="relative"> <p class="absolute left-0 text-green-600"> <b>Welcome to GeeksforGeeks </b> </p> <p class="absolute right-0 text-green-800"> <b>A complete portal for geeks </b> </p> </div></body> </html>
Output:
CSS-Questions
Tailwind CSS
Tailwind CSS-Questions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24370,
"s": 24342,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 24494,
"s": 24370,
"text": "In this article, we will learn how to align two HTML elements on the left and right sides of a document using Tailwind CSS."
},
{
"code": null,
"e": 24632,
"s": 24494,
"text": "You can easily float the elements to left and right using Tailwind CSS. This can be done using either tailwind flex or flow-root classes."
},
{
"code": null,
"e": 24646,
"s": 24632,
"text": "Classes used:"
},
{
"code": null,
"e": 24749,
"s": 24646,
"text": "flow-root: This class quickly clears floated content within a container by adding a flow-root utility."
},
{
"code": null,
"e": 24826,
"s": 24749,
"text": "position: This is used for controlling the placement of positioned elements."
},
{
"code": null,
"e": 24860,
"s": 24826,
"text": "Method 1: Using flow-root utility"
},
{
"code": null,
"e": 25150,
"s": 24860,
"text": "Note: The class flow-root is added in the upgraded version i.e. v2.0 or greater in Tailwind. If you have not upgraded then simply replace flow-root with clearfix in the codes. The clearfix class has been removed since flow-root is a simpler solution to the same problem in modern browsers."
},
{
"code": null,
"e": 25158,
"s": 25150,
"text": "Syntax:"
},
{
"code": null,
"e": 25306,
"s": 25158,
"text": "<div class=\"flow-root\"> \n <p class=\"float-left\">Welcome to GeeksforGeeks</p> \n <p class=\"float-right\">A complete portal for geeks</p>\n</div>"
},
{
"code": null,
"e": 25412,
"s": 25306,
"text": "Example 1: Add flow-root class to the parent ( div) of the element that you have to align left or right."
},
{
"code": null,
"e": 25417,
"s": 25412,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> <style> body, h2 { text-align: center; } </style></head> <body> <h2 style=\"color:green\"> GeeksforGeeks </h2> <b>Positions using class flow-root</b> <br /><br /> <div class=\"flow-root \"> <p class=\"float-left text-green-600\"> Welcome to GeeksforGeeks </p> <p class=\"float-right text-green-800\"> A complete portal for geeks </p> </div></body> </html>",
"e": 26021,
"s": 25417,
"text": null
},
{
"code": null,
"e": 26029,
"s": 26021,
"text": "Output:"
},
{
"code": null,
"e": 26067,
"s": 26029,
"text": "Method 2: Tailwind CSS Position class"
},
{
"code": null,
"e": 26075,
"s": 26067,
"text": "Syntax:"
},
{
"code": null,
"e": 26259,
"s": 26075,
"text": "<div class=\"relative\">\n <p class=\"absolute left-0\">\n Welcome to GeeksforGeeks\n </p> \n <p class=\"absolute right-0\">\n A complete portal for geeks \n </p>\n</div>"
},
{
"code": null,
"e": 26521,
"s": 26259,
"text": "Note: You can use the {top|right|bottom|left|inset}-0 utilities to anchor absolutely positioned elements against any of the edges of the nearest positioned parent. You can also use the top and bottom parameters to position the element in the way that you want. "
},
{
"code": null,
"e": 26533,
"s": 26521,
"text": "Parameters:"
},
{
"code": null,
"e": 26641,
"s": 26533,
"text": "relative: This class is used to set the position of an element relative to the normal flow of the document."
},
{
"code": null,
"e": 26815,
"s": 26641,
"text": "absolute: This class is used to set the position of an element outside the normal flow of the document, causing neighboring elements to act as if the element does not exist."
},
{
"code": null,
"e": 26876,
"s": 26815,
"text": "left-0 : It positions the element in the left of the screen."
},
{
"code": null,
"e": 26944,
"s": 26876,
"text": "right-0 : It positions the element in the right side of the screen."
},
{
"code": null,
"e": 27007,
"s": 26944,
"text": "top-0: It positions the element in the top side of the screen."
},
{
"code": null,
"e": 27077,
"s": 27007,
"text": "bottom-0 : It positions the element on the bottom side of the screen."
},
{
"code": null,
"e": 27088,
"s": 27077,
"text": "Example 2:"
},
{
"code": null,
"e": 27093,
"s": 27088,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> <style> body, h2 { text-align: center; } </style></head> <body> <h2 style=\"color:green\"> GeeksforGeeks </h2> <b> Position left and right using relative class </b> <br /><br /> <div class=\"relative\"> <p class=\"absolute left-0 text-green-600\"> <b>Welcome to GeeksforGeeks </b> </p> <p class=\"absolute right-0 text-green-800\"> <b>A complete portal for geeks </b> </p> </div></body> </html>",
"e": 27751,
"s": 27093,
"text": null
},
{
"code": null,
"e": 27759,
"s": 27751,
"text": "Output:"
},
{
"code": null,
"e": 27773,
"s": 27759,
"text": "CSS-Questions"
},
{
"code": null,
"e": 27786,
"s": 27773,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 27809,
"s": 27786,
"text": "Tailwind CSS-Questions"
},
{
"code": null,
"e": 27813,
"s": 27809,
"text": "CSS"
},
{
"code": null,
"e": 27830,
"s": 27813,
"text": "Web Technologies"
},
{
"code": null,
"e": 27928,
"s": 27830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27986,
"s": 27928,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28023,
"s": 27986,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 28087,
"s": 28023,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 28128,
"s": 28087,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 28165,
"s": 28128,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28207,
"s": 28165,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28240,
"s": 28207,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28283,
"s": 28240,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28328,
"s": 28283,
"text": "Convert a string to an integer in JavaScript"
}
]
|
Print all the palindromic permutations of given string in alphabetic order in C++ | In this problem, we are given a string of size n. And we have to print all possible palindromic permutation that can be generated using the characters of the string in alphabetical order. If palindrome is not created using the
string print ‘-1’.
Let’s take an example to understand the topic better −
Input:
string = “abcba”
Output :
abcba
bacba
Now, to solve this we need to find all the palindromes possible and then arrange them in alphabetical order(lexicographical order). Or another way could be finding the lexicographically first palindrome that is made from the string. Then find the sequentially next palindrome of the sequence.
For this, we will do the following steps −
Step 1 − store the frequency of occurrence of all characters of the string.
Step 2 − Now check if the string can form a palindrome. If no PRINT “No palindrome can be formed ” and exit. Otherwise do −
Step 3 − Create a string based on the logic that all characters with even occurrence form a string and odd occurrence from others. And we will sandwich the odd string between even string (i.e. in the form even_string + odd_string + even_string).
Using this we can find lexicographically first palindrome. Then find the next by check concurrent lexicographical combinations.
PROGRAM to illustrate the concept −
#include <iostream>
#include <string.h>
using namespace std;
const char MAX_CHAR = 26;
void countFreq(char str[], int freq[], int n){
for (int i = 0; i < n; i++)
freq[str[i] - 'a']++;
}
bool canMakePalindrome(int freq[], int n){
int count_odd = 0;
for (int i = 0; i < 26; i++)
if (freq[i] % 2 != 0)
count_odd++;
if (n % 2 == 0) {
if (count_odd > 0)
return false;
else
return true;
}
if (count_odd != 1)
return false;
return true;
}
bool isPalimdrome(char str[], int n){
int freq[26] = { 0 };
countFreq(str, freq, n);
if (!canMakePalindrome(freq, n))
return false;
char odd_char;
for (int i = 0; i < 26; i++) {
if (freq[i] % 2 != 0) {
freq[i]--;
odd_char = (char)(i + 'a');
break;
}
}
int front_index = 0, rear_index = n - 1;
for (int i = 0; i < 26; i++) {
if (freq[i] != 0) {
char ch = (char)(i + 'a');
for (int j = 1; j <= freq[i] / 2; j++) {
str[front_index++] = ch;
str[rear_index--] = ch;
}
}
}
if (front_index == rear_index)
str[front_index] = odd_char;
return true;
}
void reverse(char str[], int i, int j){
while (i < j) {
swap(str[i], str[j]);
i++;
j--;
}
}
bool nextPalindrome(char str[], int n){
if (n <= 3)
return false;
int mid = n / 2 - 1;
int i, j;
for (i = mid - 1; i >= 0; i--)
if (str[i] < str[i + 1])
break;
if (i < 0)
return false;
int smallest = i + 1;
for (j = i + 2; j <= mid; j++)
if (str[j] > str[i] && str[j] < str[smallest])
smallest = j;
swap(str[i], str[smallest]);
swap(str[n - i - 1], str[n - smallest - 1]);
reverse(str, i + 1, mid);
if (n % 2 == 0)
reverse(str, mid + 1, n - i - 2);
else
reverse(str, mid + 2, n - i - 2);
return true;
}
void printAllPalindromes(char str[], int n){
if (!(isPalimdrome(str, n))) {
cout<<"-1";
return;
}
do {
cout<<str<<endl;
} while (nextPalindrome(str, n));
}
int main(){
char str[] = "abccba";
int n = strlen(str);
cout<<”The list of palindromes possible is :\n”;
printAllPalindromes(str, n);
return 0;
}
The list of palindromes possible is −
abccba
acbbca
baccab
bcaacb
cabbac
cbaabc | [
{
"code": null,
"e": 1308,
"s": 1062,
"text": "In this problem, we are given a string of size n. And we have to print all possible palindromic permutation that can be generated using the characters of the string in alphabetical order. If palindrome is not created using the\nstring print ‘-1’."
},
{
"code": null,
"e": 1363,
"s": 1308,
"text": "Let’s take an example to understand the topic better −"
},
{
"code": null,
"e": 1408,
"s": 1363,
"text": "Input:\nstring = “abcba”\nOutput :\nabcba\nbacba"
},
{
"code": null,
"e": 1701,
"s": 1408,
"text": "Now, to solve this we need to find all the palindromes possible and then arrange them in alphabetical order(lexicographical order). Or another way could be finding the lexicographically first palindrome that is made from the string. Then find the sequentially next palindrome of the sequence."
},
{
"code": null,
"e": 1744,
"s": 1701,
"text": "For this, we will do the following steps −"
},
{
"code": null,
"e": 1820,
"s": 1744,
"text": "Step 1 − store the frequency of occurrence of all characters of the string."
},
{
"code": null,
"e": 1944,
"s": 1820,
"text": "Step 2 − Now check if the string can form a palindrome. If no PRINT “No palindrome can be formed ” and exit. Otherwise do −"
},
{
"code": null,
"e": 2190,
"s": 1944,
"text": "Step 3 − Create a string based on the logic that all characters with even occurrence form a string and odd occurrence from others. And we will sandwich the odd string between even string (i.e. in the form even_string + odd_string + even_string)."
},
{
"code": null,
"e": 2318,
"s": 2190,
"text": "Using this we can find lexicographically first palindrome. Then find the next by check concurrent lexicographical combinations."
},
{
"code": null,
"e": 2354,
"s": 2318,
"text": "PROGRAM to illustrate the concept −"
},
{
"code": null,
"e": 4642,
"s": 2354,
"text": "#include <iostream>\n#include <string.h>\nusing namespace std;\nconst char MAX_CHAR = 26;\nvoid countFreq(char str[], int freq[], int n){\n for (int i = 0; i < n; i++)\n freq[str[i] - 'a']++;\n}\nbool canMakePalindrome(int freq[], int n){\n int count_odd = 0;\n for (int i = 0; i < 26; i++)\n if (freq[i] % 2 != 0)\n count_odd++;\n if (n % 2 == 0) {\n if (count_odd > 0)\n return false;\n else\n return true;\n }\n if (count_odd != 1)\n return false;\n return true;\n}\nbool isPalimdrome(char str[], int n){\n int freq[26] = { 0 };\n countFreq(str, freq, n);\n if (!canMakePalindrome(freq, n))\n return false;\n char odd_char;\n for (int i = 0; i < 26; i++) {\n if (freq[i] % 2 != 0) {\n freq[i]--;\n odd_char = (char)(i + 'a');\n break;\n }\n }\n int front_index = 0, rear_index = n - 1;\n for (int i = 0; i < 26; i++) {\n if (freq[i] != 0) {\n char ch = (char)(i + 'a');\n for (int j = 1; j <= freq[i] / 2; j++) {\n str[front_index++] = ch;\n str[rear_index--] = ch;\n }\n }\n }\n if (front_index == rear_index)\n str[front_index] = odd_char;\n return true;\n}\nvoid reverse(char str[], int i, int j){\n while (i < j) {\n swap(str[i], str[j]);\n i++;\n j--;\n }\n}\nbool nextPalindrome(char str[], int n){\n if (n <= 3)\n return false;\n int mid = n / 2 - 1;\n int i, j;\n for (i = mid - 1; i >= 0; i--)\n if (str[i] < str[i + 1])\n break;\n if (i < 0)\n return false;\n int smallest = i + 1;\n for (j = i + 2; j <= mid; j++)\n if (str[j] > str[i] && str[j] < str[smallest])\n smallest = j;\n swap(str[i], str[smallest]);\n swap(str[n - i - 1], str[n - smallest - 1]);\n reverse(str, i + 1, mid);\n if (n % 2 == 0)\n reverse(str, mid + 1, n - i - 2);\n else\n reverse(str, mid + 2, n - i - 2);\n return true;\n}\nvoid printAllPalindromes(char str[], int n){\n if (!(isPalimdrome(str, n))) {\n cout<<\"-1\";\n return;\n }\n do {\n cout<<str<<endl;\n } while (nextPalindrome(str, n));\n}\nint main(){\n char str[] = \"abccba\";\n int n = strlen(str);\n cout<<”The list of palindromes possible is :\\n”;\n printAllPalindromes(str, n);\n return 0;\n}"
},
{
"code": null,
"e": 4680,
"s": 4642,
"text": "The list of palindromes possible is −"
},
{
"code": null,
"e": 4722,
"s": 4680,
"text": "abccba\nacbbca\nbaccab\nbcaacb\ncabbac\ncbaabc"
}
]
|
Pandas – DataFrame to CSV file using tab separator | 27 Aug, 2021
Let’s see how to convert a DataFrame to a CSV file using the tab separator. We will be using the to_csv() method to save a DataFrame as a csv file. To save the DataFrame with tab separators, we have to pass “\t” as the sep parameter in the to_csv() method.
Approach :
Import the Pandas and Numpy modules.Create a DataFrame using the DataFrame() method.Save the DataFrame as a csv file using the to_csv() method with the parameter sep as “\t”.Load the newly created CSV file using the read_csv() method as a DataFrame.Display the new DataFrame.
Import the Pandas and Numpy modules.
Create a DataFrame using the DataFrame() method.
Save the DataFrame as a csv file using the to_csv() method with the parameter sep as “\t”.
Load the newly created CSV file using the read_csv() method as a DataFrame.
Display the new DataFrame.
Python3
# importing the modulesimport pandas as pdimport numpy as np # creating a DataFramestudents = {'Student': ['Amit', 'Cody', 'Darren', 'Drew'], 'RollNumber': [1, 5, 10, 15], 'Grade': ['A', 'C', 'F', 'B']}df = pd.DataFrame(students, columns =['Student', 'RollNumber', 'Grade'])# displaying the original DataFrameprint("Original DataFrame")print(df) # saving as a CSV filedf.to_csv('Students.csv', sep ='\t') # loading the CSV filenew_df = pd.read_csv('Students.csv') # displaying the new DataFrameprint('Data from Students.csv:')print(new_df)
Output :
The contents of the Students.csv file are :
sooda367
anikakapoor
sagartomar9927
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "Let’s see how to convert a DataFrame to a CSV file using the tab separator. We will be using the to_csv() method to save a DataFrame as a csv file. To save the DataFrame with tab separators, we have to pass “\\t” as the sep parameter in the to_csv() method."
},
{
"code": null,
"e": 297,
"s": 285,
"text": "Approach : "
},
{
"code": null,
"e": 573,
"s": 297,
"text": "Import the Pandas and Numpy modules.Create a DataFrame using the DataFrame() method.Save the DataFrame as a csv file using the to_csv() method with the parameter sep as “\\t”.Load the newly created CSV file using the read_csv() method as a DataFrame.Display the new DataFrame."
},
{
"code": null,
"e": 610,
"s": 573,
"text": "Import the Pandas and Numpy modules."
},
{
"code": null,
"e": 659,
"s": 610,
"text": "Create a DataFrame using the DataFrame() method."
},
{
"code": null,
"e": 750,
"s": 659,
"text": "Save the DataFrame as a csv file using the to_csv() method with the parameter sep as “\\t”."
},
{
"code": null,
"e": 826,
"s": 750,
"text": "Load the newly created CSV file using the read_csv() method as a DataFrame."
},
{
"code": null,
"e": 853,
"s": 826,
"text": "Display the new DataFrame."
},
{
"code": null,
"e": 861,
"s": 853,
"text": "Python3"
},
{
"code": "# importing the modulesimport pandas as pdimport numpy as np # creating a DataFramestudents = {'Student': ['Amit', 'Cody', 'Darren', 'Drew'], 'RollNumber': [1, 5, 10, 15], 'Grade': ['A', 'C', 'F', 'B']}df = pd.DataFrame(students, columns =['Student', 'RollNumber', 'Grade'])# displaying the original DataFrameprint(\"Original DataFrame\")print(df) # saving as a CSV filedf.to_csv('Students.csv', sep ='\\t') # loading the CSV filenew_df = pd.read_csv('Students.csv') # displaying the new DataFrameprint('Data from Students.csv:')print(new_df)",
"e": 1490,
"s": 861,
"text": null
},
{
"code": null,
"e": 1500,
"s": 1490,
"text": "Output : "
},
{
"code": null,
"e": 1547,
"s": 1502,
"text": "The contents of the Students.csv file are : "
},
{
"code": null,
"e": 1558,
"s": 1549,
"text": "sooda367"
},
{
"code": null,
"e": 1570,
"s": 1558,
"text": "anikakapoor"
},
{
"code": null,
"e": 1585,
"s": 1570,
"text": "sagartomar9927"
},
{
"code": null,
"e": 1610,
"s": 1585,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 1634,
"s": 1610,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1648,
"s": 1634,
"text": "Python-pandas"
},
{
"code": null,
"e": 1655,
"s": 1648,
"text": "Python"
}
]
|
Sorted merge of two sorted doubly circular linked lists | 22 Mar, 2022
Given two sorted Doubly circular Linked List containing n1 and n2 nodes respectively. The problem is to merge the two lists such that resultant list is also in sorted order.Example: List 1:
List 2:
Final list:
Approach: Following are the steps:
If head1 == NULL, return head2.If head2 == NULL, return head1.Let last1 and last2 be the last nodes of the two lists respectively. They can be obtained with the help of the previous links of the first nodes.Get pointer to the node which will be the last node of the final list. If last1.data < last2.data, then last_node = last2, Else last_node = last1.Update last1.next = last2.next = NULL.Now merge the two lists as two sorted doubly linked list are being merged. Refer merge procedure of this post. Let the first node of the final list be finalHead.Update finalHead.prev = last_node and last_node.next = finalHead.Return finalHead.
If head1 == NULL, return head2.
If head2 == NULL, return head1.
Let last1 and last2 be the last nodes of the two lists respectively. They can be obtained with the help of the previous links of the first nodes.
Get pointer to the node which will be the last node of the final list. If last1.data < last2.data, then last_node = last2, Else last_node = last1.
Update last1.next = last2.next = NULL.
Now merge the two lists as two sorted doubly linked list are being merged. Refer merge procedure of this post. Let the first node of the final list be finalHead.
Update finalHead.prev = last_node and last_node.next = finalHead.
Return finalHead.
C++
Java
Python3
C#
Javascript
// C++ implementation for Sorted merge of two// sorted doubly circular linked list#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *next, *prev;}; // A utility function to insert a new node at the// beginning of doubly circular linked listvoid insert(Node** head_ref, int data){ // allocate space Node* new_node = new Node; // put in the data new_node->data = data; // if list is empty if (*head_ref == NULL) { new_node->next = new_node; new_node->prev = new_node; } else { // pointer points to last Node Node* last = (*head_ref)->prev; // setting up previous and next of new node new_node->next = *head_ref; new_node->prev = last; // update next and previous pointers of head_ref // and last. last->next = (*head_ref)->prev = new_node; } // update head_ref pointer *head_ref = new_node;} // function for Sorted merge of two// sorted doubly linked listNode* merge(Node* first, Node* second){ // If first list is empty if (!first) return second; // If second list is empty if (!second) return first; // Pick the smaller value and adjust // the links if (first->data < second->data) { first->next = merge(first->next, second); first->next->prev = first; first->prev = NULL; return first; } else { second->next = merge(first, second->next); second->next->prev = second; second->prev = NULL; return second; }} // function for Sorted merge of two sorted// doubly circular linked listNode* mergeUtil(Node* head1, Node* head2){ // if 1st list is empty if (!head1) return head2; // if 2nd list is empty if (!head2) return head1; // get pointer to the node which will be the // last node of the final list Node* last_node; if (head1->prev->data < head2->prev->data) last_node = head2->prev; else last_node = head1->prev; // store NULL to the 'next' link of the last nodes // of the two lists head1->prev->next = head2->prev->next = NULL; // sorted merge of head1 and head2 Node* finalHead = merge(head1, head2); // 'prev' of 1st node pointing the last node // 'next' of last node pointing to 1st node finalHead->prev = last_node; last_node->next = finalHead; return finalHead;} // function to print the listvoid printList(Node* head){ Node* temp = head; while (temp->next != head) { cout << temp->data << " "; temp = temp->next; } cout << temp->data << " ";} // Driver program to test aboveint main(){ Node *head1 = NULL, *head2 = NULL; // list 1: insert(&head1, 8); insert(&head1, 5); insert(&head1, 3); insert(&head1, 1); // list 2: insert(&head2, 11); insert(&head2, 9); insert(&head2, 7); insert(&head2, 2); Node* newHead = mergeUtil(head1, head2); cout << "Final Sorted List: "; printList(newHead); return 0;}
// Java implementation for Sorted merge of two// sorted doubly circular linked listclass GFG{ static class Node{ int data; Node next, prev;}; // A utility function to insert a new node at the// beginning of doubly circular linked liststatic Node insert(Node head_ref, int data){ // allocate space Node new_node = new Node(); // put in the data new_node.data = data; // if list is empty if (head_ref == null) { new_node.next = new_node; new_node.prev = new_node; } else { // pointer points to last Node Node last = (head_ref).prev; // setting up previous and next of new node new_node.next = head_ref; new_node.prev = last; // update next and previous pointers of head_ref // and last. last.next = (head_ref).prev = new_node; } // update head_ref pointer head_ref = new_node; return head_ref;} // function for Sorted merge of two// sorted doubly linked liststatic Node merge(Node first, Node second){ // If first list is empty if (first == null) return second; // If second list is empty if (second == null) return first; // Pick the smaller value and adjust // the links if (first.data < second.data) { first.next = merge(first.next, second); first.next.prev = first; first.prev = null; return first; } else { second.next = merge(first, second.next); second.next.prev = second; second.prev = null; return second; }} // function for Sorted merge of two sorted// doubly circular linked liststatic Node mergeUtil(Node head1, Node head2){ // if 1st list is empty if (head1 == null) return head2; // if 2nd list is empty if (head2 == null) return head1; // get pointer to the node which will be the // last node of the final list Node last_node; if (head1.prev.data < head2.prev.data) last_node = head2.prev; else last_node = head1.prev; // store null to the 'next' link of the last nodes // of the two lists head1.prev.next = head2.prev.next = null; // sorted merge of head1 and head2 Node finalHead = merge(head1, head2); // 'prev' of 1st node pointing the last node // 'next' of last node pointing to 1st node finalHead.prev = last_node; last_node.next = finalHead; return finalHead;} // function to print the liststatic void printList(Node head){ Node temp = head; while (temp.next != head) { System.out.print ( temp.data+ " "); temp = temp.next; } System.out.print ( temp.data + " ");} // Driver codepublic static void main(String args[]){ Node head1 = null, head2 = null; // list 1: head1 = insert(head1, 8); head1 = insert(head1, 5); head1 = insert(head1, 3); head1 = insert(head1, 1); // list 2: head2 = insert(head2, 11); head2 = insert(head2, 9); head2 = insert(head2, 7); head2 = insert(head2, 2); Node newHead = mergeUtil(head1, head2); System.out.print( "Final Sorted List: "); printList(newHead);}} // This code is contributed by Arnab Kundu
# Python3 implementation for Sorted merge# of two sorted doubly circular linked listimport math class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # A utility function to insert# a new node at the beginning# of doubly circular linked listdef insert(head_ref, data): # allocate space new_node = Node(data) # put in the data new_node.data = data # if list is empty if (head_ref == None): new_node.next = new_node new_node.prev = new_node else : # pointer points to last Node last = head_ref.prev # setting up previous and # next of new node new_node.next = head_ref new_node.prev = last # update next and previous pointers # of head_ref and last. last.next = new_node head_ref.prev = new_node # update head_ref pointer head_ref = new_node return head_ref # function for Sorted merge of two# sorted doubly linked listdef merge(first, second): # If first list is empty if (first == None): return second # If second list is empty if (second == None): return first # Pick the smaller value and # adjust the links if (first.data < second.data) : first.next = merge(first.next, second) first.next.prev = first first.prev = None return first else : second.next = merge(first, second.next) second.next.prev = second second.prev = None return second # function for Sorted merge of two sorted# doubly circular linked listdef mergeUtil(head1, head2): # if 1st list is empty if (head1 == None): return head2 # if 2nd list is empty if (head2 == None): return head1 # get pointer to the node # which will be the last node # of the final list last_node if (head1.prev.data < head2.prev.data): last_node = head2.prev else: last_node = head1.prev # store None to the 'next' link of # the last nodes of the two lists head1.prev.next = None head2.prev.next = None # sorted merge of head1 and head2 finalHead = merge(head1, head2) # 'prev' of 1st node pointing the last node # 'next' of last node pointing to 1st node finalHead.prev = last_node last_node.next = finalHead return finalHead # function to print the listdef printList(head): temp = head while (temp.next != head): print(temp.data, end = " ") temp = temp.next print(temp.data, end = " ") # Driver Codeif __name__=='__main__': head1 = None head2 = None # list 1: head1 = insert(head1, 8) head1 = insert(head1, 5) head1 = insert(head1, 3) head1 = insert(head1, 1) # list 2: head2 = insert(head2, 11) head2 = insert(head2, 9) head2 = insert(head2, 7) head2 = insert(head2, 2) newHead = mergeUtil(head1, head2) print("Final Sorted List: ", end = "") printList(newHead) # This code is contributed by Srathore
// C# implementation for Sorted merge of two// sorted doubly circular linked listusing System; class GFG{ public class Node{ public int data; public Node next, prev;}; // A utility function to insert a new node at the// beginning of doubly circular linked liststatic Node insert(Node head_ref, int data){ // allocate space Node new_node = new Node(); // put in the data new_node.data = data; // if list is empty if (head_ref == null) { new_node.next = new_node; new_node.prev = new_node; } else { // pointer points to last Node Node last = (head_ref).prev; // setting up previous and next of new node new_node.next = head_ref; new_node.prev = last; // update next and previous pointers of head_ref // and last. last.next = (head_ref).prev = new_node; } // update head_ref pointer head_ref = new_node; return head_ref;} // function for Sorted merge of two// sorted doubly linked liststatic Node merge(Node first, Node second){ // If first list is empty if (first == null) return second; // If second list is empty if (second == null) return first; // Pick the smaller value and adjust // the links if (first.data < second.data) { first.next = merge(first.next, second); first.next.prev = first; first.prev = null; return first; } else { second.next = merge(first, second.next); second.next.prev = second; second.prev = null; return second; }} // function for Sorted merge of two sorted// doubly circular linked liststatic Node mergeUtil(Node head1, Node head2){ // if 1st list is empty if (head1 == null) return head2; // if 2nd list is empty if (head2 == null) return head1; // get pointer to the node which will be the // last node of the final list Node last_node; if (head1.prev.data < head2.prev.data) last_node = head2.prev; else last_node = head1.prev; // store null to the 'next' link of the last nodes // of the two lists head1.prev.next = head2.prev.next = null; // sorted merge of head1 and head2 Node finalHead = merge(head1, head2); // 'prev' of 1st node pointing the last node // 'next' of last node pointing to 1st node finalHead.prev = last_node; last_node.next = finalHead; return finalHead;} // function to print the liststatic void printList(Node head){ Node temp = head; while (temp.next != head) { Console.Write(temp.data + " "); temp = temp.next; } Console.Write(temp.data + " ");} // Driver codepublic static void Main(){ Node head1 = null, head2 = null; // list 1: head1 = insert(head1, 8); head1 = insert(head1, 5); head1 = insert(head1, 3); head1 = insert(head1, 1); // list 2: head2 = insert(head2, 11); head2 = insert(head2, 9); head2 = insert(head2, 7); head2 = insert(head2, 2); Node newHead = mergeUtil(head1, head2); Console.Write( "Final Sorted List: "); printList(newHead);}} // This code is contributed by Princi Singh
<script>// javascript implementation for Sorted merge of two// sorted doubly circular linked list class Node{constructor(){ this.data = 0; this.next= this.prev = null;}} // A utility function to insert a new node at the // beginning of doubly circular linked list function insert( head_ref, data) { // allocate space new_node = new Node(); // put in the data new_node.data = data; // if list is empty if (head_ref == null) { new_node.next = new_node; new_node.prev = new_node; } else { // pointer points to last Node last = (head_ref).prev; // setting up previous and next of new node new_node.next = head_ref; new_node.prev = last; // update next and previous pointers of head_ref // and last. last.next = (head_ref).prev = new_node; } // update head_ref pointer head_ref = new_node; return head_ref; } // function for Sorted merge of two // sorted doubly linked list function merge( first, second) { // If first list is empty if (first == null) return second; // If second list is empty if (second == null) return first; // Pick the smaller value and adjust // the links if (first.data < second.data) { first.next = merge(first.next, second); first.next.prev = first; first.prev = null; return first; } else { second.next = merge(first, second.next); second.next.prev = second; second.prev = null; return second; } } // function for Sorted merge of two sorted // doubly circular linked list function mergeUtil( head1, head2) { // if 1st list is empty if (head1 == null) return head2; // if 2nd list is empty if (head2 == null) return head1; // get pointer to the node which will be the // last node of the final list last_node = null; if (head1.prev.data < head2.prev.data) last_node = head2.prev; else last_node = head1.prev; // store null to the 'next' link of the last nodes // of the two lists head1.prev.next = head2.prev.next = null; // sorted merge of head1 and head2 finalHead = merge(head1, head2); // 'prev' of 1st node pointing the last node // 'next' of last node pointing to 1st node finalHead.prev = last_node; last_node.next = finalHead; return finalHead; } // function to print the list function printList( head) { temp = head; while (temp.next != head) { document.write(temp.data + " "); temp = temp.next; } document.write(temp.data + " "); } // Driver code head1 = null, head2 = null; // list 1: head1 = insert(head1, 8); head1 = insert(head1, 5); head1 = insert(head1, 3); head1 = insert(head1, 1); // list 2: head2 = insert(head2, 11); head2 = insert(head2, 9); head2 = insert(head2, 7); head2 = insert(head2, 2); newHead = mergeUtil(head1, head2); document.write("Final Sorted List: "); printList(newHead); // This code is contributed by umadevi9616</script>
Output:
Final Sorted List: 1 2 3 5 7 8 9 11
Time Complexity: O(n1 + n2). Auxiliary Space: O(n1+n2)
andrew1234
princi singh
sapnasingh4991
umadevi9616
ankita_saini
rohitsingh07052
doubly linked list
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Mar, 2022"
},
{
"code": null,
"e": 244,
"s": 52,
"text": "Given two sorted Doubly circular Linked List containing n1 and n2 nodes respectively. The problem is to merge the two lists such that resultant list is also in sorted order.Example: List 1: "
},
{
"code": null,
"e": 254,
"s": 244,
"text": "List 2: "
},
{
"code": null,
"e": 268,
"s": 254,
"text": "Final list: "
},
{
"code": null,
"e": 306,
"s": 270,
"text": "Approach: Following are the steps: "
},
{
"code": null,
"e": 941,
"s": 306,
"text": "If head1 == NULL, return head2.If head2 == NULL, return head1.Let last1 and last2 be the last nodes of the two lists respectively. They can be obtained with the help of the previous links of the first nodes.Get pointer to the node which will be the last node of the final list. If last1.data < last2.data, then last_node = last2, Else last_node = last1.Update last1.next = last2.next = NULL.Now merge the two lists as two sorted doubly linked list are being merged. Refer merge procedure of this post. Let the first node of the final list be finalHead.Update finalHead.prev = last_node and last_node.next = finalHead.Return finalHead."
},
{
"code": null,
"e": 973,
"s": 941,
"text": "If head1 == NULL, return head2."
},
{
"code": null,
"e": 1005,
"s": 973,
"text": "If head2 == NULL, return head1."
},
{
"code": null,
"e": 1151,
"s": 1005,
"text": "Let last1 and last2 be the last nodes of the two lists respectively. They can be obtained with the help of the previous links of the first nodes."
},
{
"code": null,
"e": 1298,
"s": 1151,
"text": "Get pointer to the node which will be the last node of the final list. If last1.data < last2.data, then last_node = last2, Else last_node = last1."
},
{
"code": null,
"e": 1337,
"s": 1298,
"text": "Update last1.next = last2.next = NULL."
},
{
"code": null,
"e": 1499,
"s": 1337,
"text": "Now merge the two lists as two sorted doubly linked list are being merged. Refer merge procedure of this post. Let the first node of the final list be finalHead."
},
{
"code": null,
"e": 1565,
"s": 1499,
"text": "Update finalHead.prev = last_node and last_node.next = finalHead."
},
{
"code": null,
"e": 1583,
"s": 1565,
"text": "Return finalHead."
},
{
"code": null,
"e": 1589,
"s": 1585,
"text": "C++"
},
{
"code": null,
"e": 1594,
"s": 1589,
"text": "Java"
},
{
"code": null,
"e": 1602,
"s": 1594,
"text": "Python3"
},
{
"code": null,
"e": 1605,
"s": 1602,
"text": "C#"
},
{
"code": null,
"e": 1616,
"s": 1605,
"text": "Javascript"
},
{
"code": "// C++ implementation for Sorted merge of two// sorted doubly circular linked list#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *next, *prev;}; // A utility function to insert a new node at the// beginning of doubly circular linked listvoid insert(Node** head_ref, int data){ // allocate space Node* new_node = new Node; // put in the data new_node->data = data; // if list is empty if (*head_ref == NULL) { new_node->next = new_node; new_node->prev = new_node; } else { // pointer points to last Node Node* last = (*head_ref)->prev; // setting up previous and next of new node new_node->next = *head_ref; new_node->prev = last; // update next and previous pointers of head_ref // and last. last->next = (*head_ref)->prev = new_node; } // update head_ref pointer *head_ref = new_node;} // function for Sorted merge of two// sorted doubly linked listNode* merge(Node* first, Node* second){ // If first list is empty if (!first) return second; // If second list is empty if (!second) return first; // Pick the smaller value and adjust // the links if (first->data < second->data) { first->next = merge(first->next, second); first->next->prev = first; first->prev = NULL; return first; } else { second->next = merge(first, second->next); second->next->prev = second; second->prev = NULL; return second; }} // function for Sorted merge of two sorted// doubly circular linked listNode* mergeUtil(Node* head1, Node* head2){ // if 1st list is empty if (!head1) return head2; // if 2nd list is empty if (!head2) return head1; // get pointer to the node which will be the // last node of the final list Node* last_node; if (head1->prev->data < head2->prev->data) last_node = head2->prev; else last_node = head1->prev; // store NULL to the 'next' link of the last nodes // of the two lists head1->prev->next = head2->prev->next = NULL; // sorted merge of head1 and head2 Node* finalHead = merge(head1, head2); // 'prev' of 1st node pointing the last node // 'next' of last node pointing to 1st node finalHead->prev = last_node; last_node->next = finalHead; return finalHead;} // function to print the listvoid printList(Node* head){ Node* temp = head; while (temp->next != head) { cout << temp->data << \" \"; temp = temp->next; } cout << temp->data << \" \";} // Driver program to test aboveint main(){ Node *head1 = NULL, *head2 = NULL; // list 1: insert(&head1, 8); insert(&head1, 5); insert(&head1, 3); insert(&head1, 1); // list 2: insert(&head2, 11); insert(&head2, 9); insert(&head2, 7); insert(&head2, 2); Node* newHead = mergeUtil(head1, head2); cout << \"Final Sorted List: \"; printList(newHead); return 0;}",
"e": 4633,
"s": 1616,
"text": null
},
{
"code": "// Java implementation for Sorted merge of two// sorted doubly circular linked listclass GFG{ static class Node{ int data; Node next, prev;}; // A utility function to insert a new node at the// beginning of doubly circular linked liststatic Node insert(Node head_ref, int data){ // allocate space Node new_node = new Node(); // put in the data new_node.data = data; // if list is empty if (head_ref == null) { new_node.next = new_node; new_node.prev = new_node; } else { // pointer points to last Node Node last = (head_ref).prev; // setting up previous and next of new node new_node.next = head_ref; new_node.prev = last; // update next and previous pointers of head_ref // and last. last.next = (head_ref).prev = new_node; } // update head_ref pointer head_ref = new_node; return head_ref;} // function for Sorted merge of two// sorted doubly linked liststatic Node merge(Node first, Node second){ // If first list is empty if (first == null) return second; // If second list is empty if (second == null) return first; // Pick the smaller value and adjust // the links if (first.data < second.data) { first.next = merge(first.next, second); first.next.prev = first; first.prev = null; return first; } else { second.next = merge(first, second.next); second.next.prev = second; second.prev = null; return second; }} // function for Sorted merge of two sorted// doubly circular linked liststatic Node mergeUtil(Node head1, Node head2){ // if 1st list is empty if (head1 == null) return head2; // if 2nd list is empty if (head2 == null) return head1; // get pointer to the node which will be the // last node of the final list Node last_node; if (head1.prev.data < head2.prev.data) last_node = head2.prev; else last_node = head1.prev; // store null to the 'next' link of the last nodes // of the two lists head1.prev.next = head2.prev.next = null; // sorted merge of head1 and head2 Node finalHead = merge(head1, head2); // 'prev' of 1st node pointing the last node // 'next' of last node pointing to 1st node finalHead.prev = last_node; last_node.next = finalHead; return finalHead;} // function to print the liststatic void printList(Node head){ Node temp = head; while (temp.next != head) { System.out.print ( temp.data+ \" \"); temp = temp.next; } System.out.print ( temp.data + \" \");} // Driver codepublic static void main(String args[]){ Node head1 = null, head2 = null; // list 1: head1 = insert(head1, 8); head1 = insert(head1, 5); head1 = insert(head1, 3); head1 = insert(head1, 1); // list 2: head2 = insert(head2, 11); head2 = insert(head2, 9); head2 = insert(head2, 7); head2 = insert(head2, 2); Node newHead = mergeUtil(head1, head2); System.out.print( \"Final Sorted List: \"); printList(newHead);}} // This code is contributed by Arnab Kundu",
"e": 7788,
"s": 4633,
"text": null
},
{
"code": " # Python3 implementation for Sorted merge# of two sorted doubly circular linked listimport math class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # A utility function to insert# a new node at the beginning# of doubly circular linked listdef insert(head_ref, data): # allocate space new_node = Node(data) # put in the data new_node.data = data # if list is empty if (head_ref == None): new_node.next = new_node new_node.prev = new_node else : # pointer points to last Node last = head_ref.prev # setting up previous and # next of new node new_node.next = head_ref new_node.prev = last # update next and previous pointers # of head_ref and last. last.next = new_node head_ref.prev = new_node # update head_ref pointer head_ref = new_node return head_ref # function for Sorted merge of two# sorted doubly linked listdef merge(first, second): # If first list is empty if (first == None): return second # If second list is empty if (second == None): return first # Pick the smaller value and # adjust the links if (first.data < second.data) : first.next = merge(first.next, second) first.next.prev = first first.prev = None return first else : second.next = merge(first, second.next) second.next.prev = second second.prev = None return second # function for Sorted merge of two sorted# doubly circular linked listdef mergeUtil(head1, head2): # if 1st list is empty if (head1 == None): return head2 # if 2nd list is empty if (head2 == None): return head1 # get pointer to the node # which will be the last node # of the final list last_node if (head1.prev.data < head2.prev.data): last_node = head2.prev else: last_node = head1.prev # store None to the 'next' link of # the last nodes of the two lists head1.prev.next = None head2.prev.next = None # sorted merge of head1 and head2 finalHead = merge(head1, head2) # 'prev' of 1st node pointing the last node # 'next' of last node pointing to 1st node finalHead.prev = last_node last_node.next = finalHead return finalHead # function to print the listdef printList(head): temp = head while (temp.next != head): print(temp.data, end = \" \") temp = temp.next print(temp.data, end = \" \") # Driver Codeif __name__=='__main__': head1 = None head2 = None # list 1: head1 = insert(head1, 8) head1 = insert(head1, 5) head1 = insert(head1, 3) head1 = insert(head1, 1) # list 2: head2 = insert(head2, 11) head2 = insert(head2, 9) head2 = insert(head2, 7) head2 = insert(head2, 2) newHead = mergeUtil(head1, head2) print(\"Final Sorted List: \", end = \"\") printList(newHead) # This code is contributed by Srathore",
"e": 10872,
"s": 7788,
"text": null
},
{
"code": "// C# implementation for Sorted merge of two// sorted doubly circular linked listusing System; class GFG{ public class Node{ public int data; public Node next, prev;}; // A utility function to insert a new node at the// beginning of doubly circular linked liststatic Node insert(Node head_ref, int data){ // allocate space Node new_node = new Node(); // put in the data new_node.data = data; // if list is empty if (head_ref == null) { new_node.next = new_node; new_node.prev = new_node; } else { // pointer points to last Node Node last = (head_ref).prev; // setting up previous and next of new node new_node.next = head_ref; new_node.prev = last; // update next and previous pointers of head_ref // and last. last.next = (head_ref).prev = new_node; } // update head_ref pointer head_ref = new_node; return head_ref;} // function for Sorted merge of two// sorted doubly linked liststatic Node merge(Node first, Node second){ // If first list is empty if (first == null) return second; // If second list is empty if (second == null) return first; // Pick the smaller value and adjust // the links if (first.data < second.data) { first.next = merge(first.next, second); first.next.prev = first; first.prev = null; return first; } else { second.next = merge(first, second.next); second.next.prev = second; second.prev = null; return second; }} // function for Sorted merge of two sorted// doubly circular linked liststatic Node mergeUtil(Node head1, Node head2){ // if 1st list is empty if (head1 == null) return head2; // if 2nd list is empty if (head2 == null) return head1; // get pointer to the node which will be the // last node of the final list Node last_node; if (head1.prev.data < head2.prev.data) last_node = head2.prev; else last_node = head1.prev; // store null to the 'next' link of the last nodes // of the two lists head1.prev.next = head2.prev.next = null; // sorted merge of head1 and head2 Node finalHead = merge(head1, head2); // 'prev' of 1st node pointing the last node // 'next' of last node pointing to 1st node finalHead.prev = last_node; last_node.next = finalHead; return finalHead;} // function to print the liststatic void printList(Node head){ Node temp = head; while (temp.next != head) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.Write(temp.data + \" \");} // Driver codepublic static void Main(){ Node head1 = null, head2 = null; // list 1: head1 = insert(head1, 8); head1 = insert(head1, 5); head1 = insert(head1, 3); head1 = insert(head1, 1); // list 2: head2 = insert(head2, 11); head2 = insert(head2, 9); head2 = insert(head2, 7); head2 = insert(head2, 2); Node newHead = mergeUtil(head1, head2); Console.Write( \"Final Sorted List: \"); printList(newHead);}} // This code is contributed by Princi Singh",
"e": 14029,
"s": 10872,
"text": null
},
{
"code": "<script>// javascript implementation for Sorted merge of two// sorted doubly circular linked list class Node{constructor(){ this.data = 0; this.next= this.prev = null;}} // A utility function to insert a new node at the // beginning of doubly circular linked list function insert( head_ref, data) { // allocate space new_node = new Node(); // put in the data new_node.data = data; // if list is empty if (head_ref == null) { new_node.next = new_node; new_node.prev = new_node; } else { // pointer points to last Node last = (head_ref).prev; // setting up previous and next of new node new_node.next = head_ref; new_node.prev = last; // update next and previous pointers of head_ref // and last. last.next = (head_ref).prev = new_node; } // update head_ref pointer head_ref = new_node; return head_ref; } // function for Sorted merge of two // sorted doubly linked list function merge( first, second) { // If first list is empty if (first == null) return second; // If second list is empty if (second == null) return first; // Pick the smaller value and adjust // the links if (first.data < second.data) { first.next = merge(first.next, second); first.next.prev = first; first.prev = null; return first; } else { second.next = merge(first, second.next); second.next.prev = second; second.prev = null; return second; } } // function for Sorted merge of two sorted // doubly circular linked list function mergeUtil( head1, head2) { // if 1st list is empty if (head1 == null) return head2; // if 2nd list is empty if (head2 == null) return head1; // get pointer to the node which will be the // last node of the final list last_node = null; if (head1.prev.data < head2.prev.data) last_node = head2.prev; else last_node = head1.prev; // store null to the 'next' link of the last nodes // of the two lists head1.prev.next = head2.prev.next = null; // sorted merge of head1 and head2 finalHead = merge(head1, head2); // 'prev' of 1st node pointing the last node // 'next' of last node pointing to 1st node finalHead.prev = last_node; last_node.next = finalHead; return finalHead; } // function to print the list function printList( head) { temp = head; while (temp.next != head) { document.write(temp.data + \" \"); temp = temp.next; } document.write(temp.data + \" \"); } // Driver code head1 = null, head2 = null; // list 1: head1 = insert(head1, 8); head1 = insert(head1, 5); head1 = insert(head1, 3); head1 = insert(head1, 1); // list 2: head2 = insert(head2, 11); head2 = insert(head2, 9); head2 = insert(head2, 7); head2 = insert(head2, 2); newHead = mergeUtil(head1, head2); document.write(\"Final Sorted List: \"); printList(newHead); // This code is contributed by umadevi9616</script>",
"e": 17547,
"s": 14029,
"text": null
},
{
"code": null,
"e": 17557,
"s": 17547,
"text": "Output: "
},
{
"code": null,
"e": 17593,
"s": 17557,
"text": "Final Sorted List: 1 2 3 5 7 8 9 11"
},
{
"code": null,
"e": 17648,
"s": 17593,
"text": "Time Complexity: O(n1 + n2). Auxiliary Space: O(n1+n2)"
},
{
"code": null,
"e": 17659,
"s": 17648,
"text": "andrew1234"
},
{
"code": null,
"e": 17672,
"s": 17659,
"text": "princi singh"
},
{
"code": null,
"e": 17687,
"s": 17672,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 17699,
"s": 17687,
"text": "umadevi9616"
},
{
"code": null,
"e": 17712,
"s": 17699,
"text": "ankita_saini"
},
{
"code": null,
"e": 17728,
"s": 17712,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 17747,
"s": 17728,
"text": "doubly linked list"
},
{
"code": null,
"e": 17759,
"s": 17747,
"text": "Linked List"
},
{
"code": null,
"e": 17771,
"s": 17759,
"text": "Linked List"
}
]
|
Event Handling in Java | 18 Feb, 2022
An event can be defined as changing the state of an object or behavior by performing actions. Actions can be a button click, cursor movement, keypress through keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Foreground Events
Background Events
Types of Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are generated due to interaction by the user on components in Graphic User Interface (GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
Events that don’t require interactions of users to generate are known as background events. Examples of these events are operating system failures/interrupts, operation completion, etc.
It is a mechanism to control the events and to decide what should happen after an event occur. To handle the events, Java follows the Delegation Event model.
It has Sources and Listeners.
Delegation Event Model
Source: Events are generated from the source. There are various sources like buttons, checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source. Each of these listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
Event Class
Listener Interface
Description
ActionEvent
ActionListener
An event that indicates that a component-defined action occurred like a button click or selecting an item from the menu-item list.
AdjustmentEvent
AdjustmentListener
The adjustment event is emitted by an Adjustable object like Scrollbar.
ComponentEvent
ComponentListener
An event that indicates that a component moved, the size changed or changed its visibility.
ContainerEvent
ContainerListener
When a component is added to a container (or) removed from it, then this event is generated by a container object.
FocusEvent
FocusListener
These are focus-related events, which include focus, focusin, focusout, and blur.
ItemEvent
ItemListener
An event that indicates whether an item was selected or not.
KeyEvent
KeyListener
An event that occurs due to a sequence of keypresses on the keyboard.
MouseEvent
MouseListener & MouseMotionListener
The events that occur due to the user interaction with the mouse (Pointing Device).
MouseWheelEvent
MouseWheelListener
An event that specifies that the mouse wheel was rotated in a component.
TextEvent
TextListener
An event that occurs when an object’s text changes.
WindowEvent
WindowListener
An event which indicates whether a window has changed its status or not.
Note: As Interfaces contains abstract methods which need to implemented by the registered class to handle events.
Different interfaces consists of different methods which are specified below.
Listener Interface
Methods
ActionListener
actionPerformed()
AdjustmentListener
adjustmentValueChanged()
ComponentListener
componentResized()
componentShown()
componentMoved()
componentHidden()
ContainerListener
componentAdded()
componentRemoved()
FocusListener
focusGained()
focusLost()
ItemListener
itemStateChanged()
KeyListener
keyTyped()
keyPressed()
keyReleased()
MouseListener
mousePressed()
mouseClicked()
mouseEntered()
mouseExited()
mouseReleased()
MouseMotionListener
mouseMoved()
mouseDragged()
MouseWheelListener
mouseWheelMoved()
TextListener
textChanged()
WindowListener
windowActivated()
windowDeactivated()
windowOpened()
windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
User Interaction with a component is required to generate an event.The object of the respective event class is created automatically after event generation, and it holds all information of the event source.The newly created object is passed to the methods of the registered listener.The method executes and returns the result.
User Interaction with a component is required to generate an event.
The object of the respective event class is created automatically after event generation, and it holds all information of the event source.
The newly created object is passed to the methods of the registered listener.
The method executes and returns the result.
The three approaches for performing event handling are by placing the event handling code in one of the below-specified places.
Within ClassOther ClassAnonymous Class
Within Class
Other Class
Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler may throw errors due to the unavailability of some packages.
Java
// Java program to demonstrate the// event handling within the class import java.awt.*;import java.awt.event.*; class GFG extends Frame implements ActionListener { TextField textField; GFGTop() { // Component Creation textField = new TextField(); // setBounds method is used to provide // position and size of the component textField.setBounds(60, 50, 180, 25); Button button = new Button("click Here"); button.setBounds(100, 120, 80, 30); // Registering component with listener // this refers to current instance button.addActionListener(this); // add Components add(textField); add(button); // set visibility setVisible(true); } // implementing method of actionListener public void actionPerformed(ActionEvent e) { // Setting text to field textField.setText("GFG!"); } public static void main(String[] args) { new GFGTop(); }}
After Clicking, the text field value is set to GFG!
Firstly extend the class with the applet and implement the respective listener.Create Text-Field and Button components.Registered the button component with respective event. i.e. ActionEvent by addActionListener().In the end, implement the abstract method.
Firstly extend the class with the applet and implement the respective listener.
Create Text-Field and Button components.
Registered the button component with respective event. i.e. ActionEvent by addActionListener().
In the end, implement the abstract method.
Java
// Java program to demonstrate the// event handling by the other class import java.awt.*;import java.awt.event.*; class GFG1 extends Frame { TextField textField; GFG2() { // Component Creation textField = new TextField(); // setBounds method is used to provide // position and size of component textField.setBounds(60, 50, 180, 25); Button button = new Button("click Here"); button.setBounds(100, 120, 80, 30); Other other = new Other(this); // Registering component with listener // Passing other class as reference button.addActionListener(other); // add Components add(textField); add(button); // set visibility setVisible(true); } public static void main(String[] args) { new GFG2(); }}
Java
/// import necessary packagesimport java.awt.event.*; // implements the listener interfaceclass Other implements ActionListener { GFG2 gfgObj; Other(GFG1 gfgObj) { this.gfgObj = gfgObj; } public void actionPerformed(ActionEvent e) { // setting text from different class gfgObj.textField.setText("Using Different Classes"); }}
Handling event from different class
Java
// Java program to demonstrate the// event handling by the anonymous class import java.awt.*;import java.awt.event.*; class GFG3 extends Frame { TextField textField; GFG3() { // Component Creation textField = new TextField(); // setBounds method is used to provide // position and size of component textField.setBounds(60, 50, 180, 25); Button button = new Button("click Here"); button.setBounds(100, 120, 80, 30); // Registering component with listener anonymously button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Setting text to field textField.setText("Anonymous"); } }); // add Components add(textField); add(button); // set visibility setVisible(true); } public static void main(String[] args) { new GFG3(); }}
Handling anonymously
kk773572498
Java-AWT
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 247,
"s": 54,
"text": "An event can be defined as changing the state of an object or behavior by performing actions. Actions can be a button click, cursor movement, keypress through keyboard or page scrolling, etc. "
},
{
"code": null,
"e": 321,
"s": 247,
"text": "The java.awt.event package can be used to provide various event classes. "
},
{
"code": null,
"e": 339,
"s": 321,
"text": "Foreground Events"
},
{
"code": null,
"e": 357,
"s": 339,
"text": "Background Events"
},
{
"code": null,
"e": 373,
"s": 357,
"text": "Types of Events"
},
{
"code": null,
"e": 663,
"s": 373,
"text": "Foreground events are the events that require user interaction to generate, i.e., foreground events are generated due to interaction by the user on components in Graphic User Interface (GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc."
},
{
"code": null,
"e": 849,
"s": 663,
"text": "Events that don’t require interactions of users to generate are known as background events. Examples of these events are operating system failures/interrupts, operation completion, etc."
},
{
"code": null,
"e": 1007,
"s": 849,
"text": "It is a mechanism to control the events and to decide what should happen after an event occur. To handle the events, Java follows the Delegation Event model."
},
{
"code": null,
"e": 1037,
"s": 1007,
"text": "It has Sources and Listeners."
},
{
"code": null,
"e": 1060,
"s": 1037,
"text": "Delegation Event Model"
},
{
"code": null,
"e": 1246,
"s": 1060,
"text": "Source: Events are generated from the source. There are various sources like buttons, checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate events."
},
{
"code": null,
"e": 1415,
"s": 1246,
"text": "Listeners: Listeners are used for handling the events generated from the source. Each of these listeners represents interfaces that are responsible for handling events."
},
{
"code": null,
"e": 1492,
"s": 1415,
"text": "To perform Event Handling, we need to register the source with the listener."
},
{
"code": null,
"e": 1550,
"s": 1492,
"text": "Different Classes provide different registration methods."
},
{
"code": null,
"e": 1558,
"s": 1550,
"text": "Syntax:"
},
{
"code": null,
"e": 1576,
"s": 1558,
"text": "addTypeListener()"
},
{
"code": null,
"e": 1617,
"s": 1576,
"text": "where Type represents the type of event."
},
{
"code": null,
"e": 1678,
"s": 1617,
"text": "Example 1: For KeyEvent we use addKeyListener() to register."
},
{
"code": null,
"e": 1749,
"s": 1678,
"text": "Example 2:that For ActionEvent we use addActionListener() to register."
},
{
"code": null,
"e": 1761,
"s": 1749,
"text": "Event Class"
},
{
"code": null,
"e": 1780,
"s": 1761,
"text": "Listener Interface"
},
{
"code": null,
"e": 1792,
"s": 1780,
"text": "Description"
},
{
"code": null,
"e": 1804,
"s": 1792,
"text": "ActionEvent"
},
{
"code": null,
"e": 1819,
"s": 1804,
"text": "ActionListener"
},
{
"code": null,
"e": 1950,
"s": 1819,
"text": "An event that indicates that a component-defined action occurred like a button click or selecting an item from the menu-item list."
},
{
"code": null,
"e": 1966,
"s": 1950,
"text": "AdjustmentEvent"
},
{
"code": null,
"e": 1985,
"s": 1966,
"text": "AdjustmentListener"
},
{
"code": null,
"e": 2057,
"s": 1985,
"text": "The adjustment event is emitted by an Adjustable object like Scrollbar."
},
{
"code": null,
"e": 2072,
"s": 2057,
"text": "ComponentEvent"
},
{
"code": null,
"e": 2090,
"s": 2072,
"text": "ComponentListener"
},
{
"code": null,
"e": 2182,
"s": 2090,
"text": "An event that indicates that a component moved, the size changed or changed its visibility."
},
{
"code": null,
"e": 2197,
"s": 2182,
"text": "ContainerEvent"
},
{
"code": null,
"e": 2215,
"s": 2197,
"text": "ContainerListener"
},
{
"code": null,
"e": 2330,
"s": 2215,
"text": "When a component is added to a container (or) removed from it, then this event is generated by a container object."
},
{
"code": null,
"e": 2341,
"s": 2330,
"text": "FocusEvent"
},
{
"code": null,
"e": 2355,
"s": 2341,
"text": "FocusListener"
},
{
"code": null,
"e": 2437,
"s": 2355,
"text": "These are focus-related events, which include focus, focusin, focusout, and blur."
},
{
"code": null,
"e": 2447,
"s": 2437,
"text": "ItemEvent"
},
{
"code": null,
"e": 2460,
"s": 2447,
"text": "ItemListener"
},
{
"code": null,
"e": 2521,
"s": 2460,
"text": "An event that indicates whether an item was selected or not."
},
{
"code": null,
"e": 2530,
"s": 2521,
"text": "KeyEvent"
},
{
"code": null,
"e": 2542,
"s": 2530,
"text": "KeyListener"
},
{
"code": null,
"e": 2612,
"s": 2542,
"text": "An event that occurs due to a sequence of keypresses on the keyboard."
},
{
"code": null,
"e": 2623,
"s": 2612,
"text": "MouseEvent"
},
{
"code": null,
"e": 2659,
"s": 2623,
"text": "MouseListener & MouseMotionListener"
},
{
"code": null,
"e": 2743,
"s": 2659,
"text": "The events that occur due to the user interaction with the mouse (Pointing Device)."
},
{
"code": null,
"e": 2759,
"s": 2743,
"text": "MouseWheelEvent"
},
{
"code": null,
"e": 2778,
"s": 2759,
"text": "MouseWheelListener"
},
{
"code": null,
"e": 2852,
"s": 2778,
"text": "An event that specifies that the mouse wheel was rotated in a component. "
},
{
"code": null,
"e": 2862,
"s": 2852,
"text": "TextEvent"
},
{
"code": null,
"e": 2875,
"s": 2862,
"text": "TextListener"
},
{
"code": null,
"e": 2927,
"s": 2875,
"text": "An event that occurs when an object’s text changes."
},
{
"code": null,
"e": 2939,
"s": 2927,
"text": "WindowEvent"
},
{
"code": null,
"e": 2954,
"s": 2939,
"text": "WindowListener"
},
{
"code": null,
"e": 3027,
"s": 2954,
"text": "An event which indicates whether a window has changed its status or not."
},
{
"code": null,
"e": 3141,
"s": 3027,
"text": "Note: As Interfaces contains abstract methods which need to implemented by the registered class to handle events."
},
{
"code": null,
"e": 3219,
"s": 3141,
"text": "Different interfaces consists of different methods which are specified below."
},
{
"code": null,
"e": 3238,
"s": 3219,
"text": "Listener Interface"
},
{
"code": null,
"e": 3246,
"s": 3238,
"text": "Methods"
},
{
"code": null,
"e": 3261,
"s": 3246,
"text": "ActionListener"
},
{
"code": null,
"e": 3279,
"s": 3261,
"text": "actionPerformed()"
},
{
"code": null,
"e": 3298,
"s": 3279,
"text": "AdjustmentListener"
},
{
"code": null,
"e": 3323,
"s": 3298,
"text": "adjustmentValueChanged()"
},
{
"code": null,
"e": 3341,
"s": 3323,
"text": "ComponentListener"
},
{
"code": null,
"e": 3360,
"s": 3341,
"text": "componentResized()"
},
{
"code": null,
"e": 3377,
"s": 3360,
"text": "componentShown()"
},
{
"code": null,
"e": 3394,
"s": 3377,
"text": "componentMoved()"
},
{
"code": null,
"e": 3412,
"s": 3394,
"text": "componentHidden()"
},
{
"code": null,
"e": 3430,
"s": 3412,
"text": "ContainerListener"
},
{
"code": null,
"e": 3447,
"s": 3430,
"text": "componentAdded()"
},
{
"code": null,
"e": 3466,
"s": 3447,
"text": "componentRemoved()"
},
{
"code": null,
"e": 3480,
"s": 3466,
"text": "FocusListener"
},
{
"code": null,
"e": 3494,
"s": 3480,
"text": "focusGained()"
},
{
"code": null,
"e": 3506,
"s": 3494,
"text": "focusLost()"
},
{
"code": null,
"e": 3519,
"s": 3506,
"text": "ItemListener"
},
{
"code": null,
"e": 3538,
"s": 3519,
"text": "itemStateChanged()"
},
{
"code": null,
"e": 3550,
"s": 3538,
"text": "KeyListener"
},
{
"code": null,
"e": 3561,
"s": 3550,
"text": "keyTyped()"
},
{
"code": null,
"e": 3574,
"s": 3561,
"text": "keyPressed()"
},
{
"code": null,
"e": 3588,
"s": 3574,
"text": "keyReleased()"
},
{
"code": null,
"e": 3602,
"s": 3588,
"text": "MouseListener"
},
{
"code": null,
"e": 3617,
"s": 3602,
"text": "mousePressed()"
},
{
"code": null,
"e": 3632,
"s": 3617,
"text": "mouseClicked()"
},
{
"code": null,
"e": 3647,
"s": 3632,
"text": "mouseEntered()"
},
{
"code": null,
"e": 3661,
"s": 3647,
"text": "mouseExited()"
},
{
"code": null,
"e": 3677,
"s": 3661,
"text": "mouseReleased()"
},
{
"code": null,
"e": 3697,
"s": 3677,
"text": "MouseMotionListener"
},
{
"code": null,
"e": 3710,
"s": 3697,
"text": "mouseMoved()"
},
{
"code": null,
"e": 3725,
"s": 3710,
"text": "mouseDragged()"
},
{
"code": null,
"e": 3744,
"s": 3725,
"text": "MouseWheelListener"
},
{
"code": null,
"e": 3762,
"s": 3744,
"text": "mouseWheelMoved()"
},
{
"code": null,
"e": 3775,
"s": 3762,
"text": "TextListener"
},
{
"code": null,
"e": 3789,
"s": 3775,
"text": "textChanged()"
},
{
"code": null,
"e": 3804,
"s": 3789,
"text": "WindowListener"
},
{
"code": null,
"e": 3822,
"s": 3804,
"text": "windowActivated()"
},
{
"code": null,
"e": 3842,
"s": 3822,
"text": "windowDeactivated()"
},
{
"code": null,
"e": 3857,
"s": 3842,
"text": "windowOpened()"
},
{
"code": null,
"e": 3872,
"s": 3857,
"text": "windowClosed()"
},
{
"code": null,
"e": 3888,
"s": 3872,
"text": "windowClosing()"
},
{
"code": null,
"e": 3906,
"s": 3888,
"text": "windowIconified()"
},
{
"code": null,
"e": 3926,
"s": 3906,
"text": "windowDeiconified()"
},
{
"code": null,
"e": 4253,
"s": 3926,
"text": "User Interaction with a component is required to generate an event.The object of the respective event class is created automatically after event generation, and it holds all information of the event source.The newly created object is passed to the methods of the registered listener.The method executes and returns the result."
},
{
"code": null,
"e": 4321,
"s": 4253,
"text": "User Interaction with a component is required to generate an event."
},
{
"code": null,
"e": 4461,
"s": 4321,
"text": "The object of the respective event class is created automatically after event generation, and it holds all information of the event source."
},
{
"code": null,
"e": 4539,
"s": 4461,
"text": "The newly created object is passed to the methods of the registered listener."
},
{
"code": null,
"e": 4583,
"s": 4539,
"text": "The method executes and returns the result."
},
{
"code": null,
"e": 4711,
"s": 4583,
"text": "The three approaches for performing event handling are by placing the event handling code in one of the below-specified places."
},
{
"code": null,
"e": 4750,
"s": 4711,
"text": "Within ClassOther ClassAnonymous Class"
},
{
"code": null,
"e": 4763,
"s": 4750,
"text": "Within Class"
},
{
"code": null,
"e": 4775,
"s": 4763,
"text": "Other Class"
},
{
"code": null,
"e": 4791,
"s": 4775,
"text": "Anonymous Class"
},
{
"code": null,
"e": 4918,
"s": 4791,
"text": "Note: Use any IDE or install JDK to run the code, Online compiler may throw errors due to the unavailability of some packages."
},
{
"code": null,
"e": 4923,
"s": 4918,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// event handling within the class import java.awt.*;import java.awt.event.*; class GFG extends Frame implements ActionListener { TextField textField; GFGTop() { // Component Creation textField = new TextField(); // setBounds method is used to provide // position and size of the component textField.setBounds(60, 50, 180, 25); Button button = new Button(\"click Here\"); button.setBounds(100, 120, 80, 30); // Registering component with listener // this refers to current instance button.addActionListener(this); // add Components add(textField); add(button); // set visibility setVisible(true); } // implementing method of actionListener public void actionPerformed(ActionEvent e) { // Setting text to field textField.setText(\"GFG!\"); } public static void main(String[] args) { new GFGTop(); }}",
"e": 5921,
"s": 4923,
"text": null
},
{
"code": null,
"e": 5976,
"s": 5924,
"text": "After Clicking, the text field value is set to GFG!"
},
{
"code": null,
"e": 6233,
"s": 5976,
"text": "Firstly extend the class with the applet and implement the respective listener.Create Text-Field and Button components.Registered the button component with respective event. i.e. ActionEvent by addActionListener().In the end, implement the abstract method."
},
{
"code": null,
"e": 6313,
"s": 6233,
"text": "Firstly extend the class with the applet and implement the respective listener."
},
{
"code": null,
"e": 6354,
"s": 6313,
"text": "Create Text-Field and Button components."
},
{
"code": null,
"e": 6450,
"s": 6354,
"text": "Registered the button component with respective event. i.e. ActionEvent by addActionListener()."
},
{
"code": null,
"e": 6493,
"s": 6450,
"text": "In the end, implement the abstract method."
},
{
"code": null,
"e": 6500,
"s": 6495,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// event handling by the other class import java.awt.*;import java.awt.event.*; class GFG1 extends Frame { TextField textField; GFG2() { // Component Creation textField = new TextField(); // setBounds method is used to provide // position and size of component textField.setBounds(60, 50, 180, 25); Button button = new Button(\"click Here\"); button.setBounds(100, 120, 80, 30); Other other = new Other(this); // Registering component with listener // Passing other class as reference button.addActionListener(other); // add Components add(textField); add(button); // set visibility setVisible(true); } public static void main(String[] args) { new GFG2(); }}",
"e": 7373,
"s": 6500,
"text": null
},
{
"code": null,
"e": 7382,
"s": 7377,
"text": "Java"
},
{
"code": "/// import necessary packagesimport java.awt.event.*; // implements the listener interfaceclass Other implements ActionListener { GFG2 gfgObj; Other(GFG1 gfgObj) { this.gfgObj = gfgObj; } public void actionPerformed(ActionEvent e) { // setting text from different class gfgObj.textField.setText(\"Using Different Classes\"); }}",
"e": 7780,
"s": 7382,
"text": null
},
{
"code": null,
"e": 7819,
"s": 7783,
"text": "Handling event from different class"
},
{
"code": null,
"e": 7826,
"s": 7821,
"text": "Java"
},
{
"code": "// Java program to demonstrate the// event handling by the anonymous class import java.awt.*;import java.awt.event.*; class GFG3 extends Frame { TextField textField; GFG3() { // Component Creation textField = new TextField(); // setBounds method is used to provide // position and size of component textField.setBounds(60, 50, 180, 25); Button button = new Button(\"click Here\"); button.setBounds(100, 120, 80, 30); // Registering component with listener anonymously button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Setting text to field textField.setText(\"Anonymous\"); } }); // add Components add(textField); add(button); // set visibility setVisible(true); } public static void main(String[] args) { new GFG3(); }}",
"e": 8822,
"s": 7826,
"text": null
},
{
"code": null,
"e": 8846,
"s": 8825,
"text": "Handling anonymously"
},
{
"code": null,
"e": 8860,
"s": 8848,
"text": "kk773572498"
},
{
"code": null,
"e": 8869,
"s": 8860,
"text": "Java-AWT"
},
{
"code": null,
"e": 8876,
"s": 8869,
"text": "Picked"
},
{
"code": null,
"e": 8881,
"s": 8876,
"text": "Java"
},
{
"code": null,
"e": 8886,
"s": 8881,
"text": "Java"
}
]
|
How to create a moving div using JavaScript ? | 25 May, 2021
In this article, we will learn to create a moving HTML div using JavaScript. The div will move left to right using HTML, CSS, and JavaScript.
Approach:
We have to create an HTML div and add some CSS to the div using a class ball. In CSS, we add some background-color to the body and give some height, width, and color to the div.Now we will add margin-left to the div using JavaScript. So it will move left to right.In JavaScript, we grab the div using the id name. And after some interval of time, we will add margin-left to the div.
We have to create an HTML div and add some CSS to the div using a class ball.
In CSS, we add some background-color to the body and give some height, width, and color to the div.
Now we will add margin-left to the div using JavaScript. So it will move left to right.
In JavaScript, we grab the div using the id name. And after some interval of time, we will add margin-left to the div.
HTML code:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> body { background-color: aqua; display: flex; align-items: center; } .ball { height: 12rem; width: 12rem; background-color: white; border-radius: 50%; margin-top: 20rem; } </style> </head> <body> <div class="container"> <div class="ball" id="ballID"></div> </div> <script> let ball = document.getElementById("ballID"); var myVar = setInterval(spostaDiv, 90); var margin = 0; let l = window.screen.width; let w = 1300; function spostaDiv() { console.log(w); if (margin == w) { margin = 0 + "px"; } else { ball.style.marginLeft = margin + "px"; } margin += 10; } </script> </body></html>
Output:
CSS-Properties
CSS-Questions
HTML-Attributes
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "In this article, we will learn to create a moving HTML div using JavaScript. The div will move left to right using HTML, CSS, and JavaScript. "
},
{
"code": null,
"e": 181,
"s": 171,
"text": "Approach:"
},
{
"code": null,
"e": 564,
"s": 181,
"text": "We have to create an HTML div and add some CSS to the div using a class ball. In CSS, we add some background-color to the body and give some height, width, and color to the div.Now we will add margin-left to the div using JavaScript. So it will move left to right.In JavaScript, we grab the div using the id name. And after some interval of time, we will add margin-left to the div."
},
{
"code": null,
"e": 642,
"s": 564,
"text": "We have to create an HTML div and add some CSS to the div using a class ball."
},
{
"code": null,
"e": 743,
"s": 642,
"text": " In CSS, we add some background-color to the body and give some height, width, and color to the div."
},
{
"code": null,
"e": 831,
"s": 743,
"text": "Now we will add margin-left to the div using JavaScript. So it will move left to right."
},
{
"code": null,
"e": 950,
"s": 831,
"text": "In JavaScript, we grab the div using the id name. And after some interval of time, we will add margin-left to the div."
},
{
"code": null,
"e": 961,
"s": 950,
"text": "HTML code:"
},
{
"code": null,
"e": 966,
"s": 961,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <style> body { background-color: aqua; display: flex; align-items: center; } .ball { height: 12rem; width: 12rem; background-color: white; border-radius: 50%; margin-top: 20rem; } </style> </head> <body> <div class=\"container\"> <div class=\"ball\" id=\"ballID\"></div> </div> <script> let ball = document.getElementById(\"ballID\"); var myVar = setInterval(spostaDiv, 90); var margin = 0; let l = window.screen.width; let w = 1300; function spostaDiv() { console.log(w); if (margin == w) { margin = 0 + \"px\"; } else { ball.style.marginLeft = margin + \"px\"; } margin += 10; } </script> </body></html>",
"e": 1983,
"s": 966,
"text": null
},
{
"code": null,
"e": 1991,
"s": 1983,
"text": "Output:"
},
{
"code": null,
"e": 2006,
"s": 1991,
"text": "CSS-Properties"
},
{
"code": null,
"e": 2020,
"s": 2006,
"text": "CSS-Questions"
},
{
"code": null,
"e": 2036,
"s": 2020,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 2043,
"s": 2036,
"text": "Picked"
},
{
"code": null,
"e": 2054,
"s": 2043,
"text": "JavaScript"
},
{
"code": null,
"e": 2071,
"s": 2054,
"text": "Web Technologies"
}
]
|
How to copy folder recursively in Node.js ? | 12 Jun, 2020
Node.js is an enhancement to the already existing javaScript. It is used for server-side scripting. It is mostly used to develop dynamic web applications. Node.js developers prefer the use of asynchronous functions over synchronous functions as the former does not block program execution under any circumstances. Copying files or folders with multiple subfolders can be tedious using conventional Node.js file copying methods. However, the use of additional modules makes the task easier.
The two modules in the discussion are the NCP module and the fs-extra module. Both the modules support asynchronous functions to aid the process of copying the folders recursively.
The examples below demonstrate the use of these modules for copying folders recursively.
Create a folder structure as follows
in the working directory:
mkdir f1\f2\f3\f4\f5
notepad f1\f2\f3\f4\f5\new.txt
// Write some text and save the .txt file
Syntax:
ncp(source, destination, options, callback)
Parameter:
source: File path of the source folder.
destination: File path of destination folder.
optionsoptions.filter: A RegExp that can be used to specify if a folder/file must be copied or skipped.options.transform: A function that can be used to apply streaming transforms while copying.options.clobber: Can be set to true or false. If set to false, ncp does not overwrite files that already exist in the destination.options.stopOnErr: Can be set to true or false. By default, it is set to false i.e. ncp continues to copy, log all errors and returns an array. If set to true, ncp stops on the first error it encounters.
options.filter: A RegExp that can be used to specify if a folder/file must be copied or skipped.
options.transform: A function that can be used to apply streaming transforms while copying.
options.clobber: Can be set to true or false. If set to false, ncp does not overwrite files that already exist in the destination.
options.stopOnErr: Can be set to true or false. By default, it is set to false i.e. ncp continues to copy, log all errors and returns an array. If set to true, ncp stops on the first error it encounters.
callback: A function called at the completion of a given task and takes error as the first parameter. If an error occurs the callback function handles it without blocking the program execution.
Example 1: Using ncp moduleInstall ncp module using the following command:
npm install ncp
Filename: recursiveCopy.js file
var ncp = require('ncp').ncp; // Represents the number of pending// file system requests at a time.ncp.limit = 16; // ncp(source, destination, callback) ncp('D:\\HTML\\f1', 'D:\\HTML\\recursive', function (err) { if (err) { return console.error(err); } console.log('Folders copied recursively');});
Output:
Syntax:
fs.copy(source, destination, callback)
Parameter:
source: File path of the source folder.
destination: File path of destination folder.
callback: A function called at the completion of a given task and takes error as the first parameter. If an error occurs the callback function handles it without blocking the program execution. If callback is not passed, it returns promises.
Example 2: Using fs-extra moduleInstall fs-extra module using the following command:
npm install fs-extra
Filename: fsrecur.js
const fs = require('fs-extra'); // Async with promises:fs.copy('D:\\HTML\\f1', 'D:\\HTML\\fsextra').then(() => console.log('Files copied successfully!')).catch(err => console.error(err));
Output:
Explanation: All the folders within f1 starting from f2 upto f5 are copied recursively into the ‘recursive’ folder. Any file or folder within these folders gets copied to the new folder.
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 518,
"s": 28,
"text": "Node.js is an enhancement to the already existing javaScript. It is used for server-side scripting. It is mostly used to develop dynamic web applications. Node.js developers prefer the use of asynchronous functions over synchronous functions as the former does not block program execution under any circumstances. Copying files or folders with multiple subfolders can be tedious using conventional Node.js file copying methods. However, the use of additional modules makes the task easier."
},
{
"code": null,
"e": 699,
"s": 518,
"text": "The two modules in the discussion are the NCP module and the fs-extra module. Both the modules support asynchronous functions to aid the process of copying the folders recursively."
},
{
"code": null,
"e": 788,
"s": 699,
"text": "The examples below demonstrate the use of these modules for copying folders recursively."
},
{
"code": null,
"e": 946,
"s": 788,
"text": "Create a folder structure as follows \nin the working directory:\nmkdir f1\\f2\\f3\\f4\\f5\nnotepad f1\\f2\\f3\\f4\\f5\\new.txt\n// Write some text and save the .txt file"
},
{
"code": null,
"e": 954,
"s": 946,
"text": "Syntax:"
},
{
"code": null,
"e": 998,
"s": 954,
"text": "ncp(source, destination, options, callback)"
},
{
"code": null,
"e": 1009,
"s": 998,
"text": "Parameter:"
},
{
"code": null,
"e": 1049,
"s": 1009,
"text": "source: File path of the source folder."
},
{
"code": null,
"e": 1095,
"s": 1049,
"text": "destination: File path of destination folder."
},
{
"code": null,
"e": 1623,
"s": 1095,
"text": "optionsoptions.filter: A RegExp that can be used to specify if a folder/file must be copied or skipped.options.transform: A function that can be used to apply streaming transforms while copying.options.clobber: Can be set to true or false. If set to false, ncp does not overwrite files that already exist in the destination.options.stopOnErr: Can be set to true or false. By default, it is set to false i.e. ncp continues to copy, log all errors and returns an array. If set to true, ncp stops on the first error it encounters."
},
{
"code": null,
"e": 1720,
"s": 1623,
"text": "options.filter: A RegExp that can be used to specify if a folder/file must be copied or skipped."
},
{
"code": null,
"e": 1812,
"s": 1720,
"text": "options.transform: A function that can be used to apply streaming transforms while copying."
},
{
"code": null,
"e": 1943,
"s": 1812,
"text": "options.clobber: Can be set to true or false. If set to false, ncp does not overwrite files that already exist in the destination."
},
{
"code": null,
"e": 2147,
"s": 1943,
"text": "options.stopOnErr: Can be set to true or false. By default, it is set to false i.e. ncp continues to copy, log all errors and returns an array. If set to true, ncp stops on the first error it encounters."
},
{
"code": null,
"e": 2341,
"s": 2147,
"text": "callback: A function called at the completion of a given task and takes error as the first parameter. If an error occurs the callback function handles it without blocking the program execution."
},
{
"code": null,
"e": 2416,
"s": 2341,
"text": "Example 1: Using ncp moduleInstall ncp module using the following command:"
},
{
"code": null,
"e": 2432,
"s": 2416,
"text": "npm install ncp"
},
{
"code": null,
"e": 2464,
"s": 2432,
"text": "Filename: recursiveCopy.js file"
},
{
"code": "var ncp = require('ncp').ncp; // Represents the number of pending// file system requests at a time.ncp.limit = 16; // ncp(source, destination, callback) ncp('D:\\\\HTML\\\\f1', 'D:\\\\HTML\\\\recursive', function (err) { if (err) { return console.error(err); } console.log('Folders copied recursively');});",
"e": 2791,
"s": 2464,
"text": null
},
{
"code": null,
"e": 2799,
"s": 2791,
"text": "Output:"
},
{
"code": null,
"e": 2807,
"s": 2799,
"text": "Syntax:"
},
{
"code": null,
"e": 2846,
"s": 2807,
"text": "fs.copy(source, destination, callback)"
},
{
"code": null,
"e": 2857,
"s": 2846,
"text": "Parameter:"
},
{
"code": null,
"e": 2897,
"s": 2857,
"text": "source: File path of the source folder."
},
{
"code": null,
"e": 2943,
"s": 2897,
"text": "destination: File path of destination folder."
},
{
"code": null,
"e": 3185,
"s": 2943,
"text": "callback: A function called at the completion of a given task and takes error as the first parameter. If an error occurs the callback function handles it without blocking the program execution. If callback is not passed, it returns promises."
},
{
"code": null,
"e": 3270,
"s": 3185,
"text": "Example 2: Using fs-extra moduleInstall fs-extra module using the following command:"
},
{
"code": null,
"e": 3291,
"s": 3270,
"text": "npm install fs-extra"
},
{
"code": null,
"e": 3312,
"s": 3291,
"text": "Filename: fsrecur.js"
},
{
"code": "const fs = require('fs-extra'); // Async with promises:fs.copy('D:\\\\HTML\\\\f1', 'D:\\\\HTML\\\\fsextra').then(() => console.log('Files copied successfully!')).catch(err => console.error(err));",
"e": 3501,
"s": 3312,
"text": null
},
{
"code": null,
"e": 3509,
"s": 3501,
"text": "Output:"
},
{
"code": null,
"e": 3696,
"s": 3509,
"text": "Explanation: All the folders within f1 starting from f2 upto f5 are copied recursively into the ‘recursive’ folder. Any file or folder within these folders gets copied to the new folder."
},
{
"code": null,
"e": 3714,
"s": 3696,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 3721,
"s": 3714,
"text": "Picked"
},
{
"code": null,
"e": 3729,
"s": 3721,
"text": "Node.js"
},
{
"code": null,
"e": 3746,
"s": 3729,
"text": "Web Technologies"
}
]
|
Find column with maximum sum in a Matrix | 14 Jun, 2022
Given a N*N matrix. The task is to find the index of column with maximum sum. That is the column whose sum of elements are maximum.Examples:
Input : mat[][] = {
{ 1, 2, 3, 4, 5 },
{ 5, 3, 1, 4, 2 },
{ 5, 6, 7, 8, 9 },
{ 0, 6, 3, 4, 12 },
{ 9, 7, 12, 4, 3 },
};
Output : Column 5 has max sum 31
Input : mat[][] = {
{ 1, 2, 3 },
{ 4, 2, 1 },
{ 5, 6, 7 },
};
Output : Column 3 has max sum 11
The idea is to traverse the matrix column-wise and find the sum of elements in each column and check for every column if current sum is greater than the maximum sum obtained till the current column and update the maximum_sum accordingly. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find column with// max sum in a matrix#include <bits/stdc++.h>using namespace std; #define N 5 // No of rows and column // Function to find the column with max sumpair<int, int> colMaxSum(int mat[N][N]){ // Variable to store index of column // with maximum int idx = -1; // Variable to store max sum int maxSum = INT_MIN; // Traverse matrix column wise for (int i = 0; i < N; i++) { int sum = 0; // calculate sum of column for (int j = 0; j < N; j++) { sum += mat[j][i]; } // Update maxSum if it is less than // current sum if (sum > maxSum) { maxSum = sum; // store index idx = i; } } pair<int, int> res; res = make_pair(idx, maxSum); // return result return res;} // driver codeint main(){ int mat[N][N] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; pair<int, int> ans = colMaxSum(mat); cout << "Column " << ans.first + 1 << " has max sum " << ans.second; return 0;}
// Java program to find column// with max sum in a matriximport java.util.*; class GFG{// No of rows and columnstatic final int N = 5; // structure for pairstatic class Pair{ int first , second; Pair(int f, int s) { first = f; second = s; }} // Function to find the column// with max sumstatic Pair colMaxSum(int mat[][]){ // Variable to store index of // column with maximum int idx = -1; // Variable to store max sum int maxSum = Integer.MIN_VALUE; // Traverse matrix column wise for (int i = 0; i < N; i++) { int sum = 0; // calculate sum of column for (int j = 0; j < N; j++) { sum += mat[j][i]; } // Update maxSum if it is // less than current sum if (sum > maxSum) { maxSum = sum; // store index idx = i; } } Pair res; res = new Pair(idx, maxSum); // return result return res;} // Driver codepublic static void main(String args[]){ int mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }}; Pair ans = colMaxSum(mat); System.out.println("Column " + (int)(ans.first + 1) + " has max sum " + ans.second);}} // This code is contributed// by Arnab Kundu
# Python3 program to find column with# max Sum in a matrix N = 5 # Function to find the column with max Sumdef colMaxSum(mat): # Variable to store index of column # with maximum idx = -1 # Variable to store max Sum maxSum = -10**9 # Traverse matrix column wise for i in range(N): Sum = 0 # calculate Sum of column for j in range(N): Sum += mat[j][i] # Update maxSum if it is less # than current Sum if (Sum > maxSum): maxSum = Sum # store index idx = i # return result return idx, maxSum # Driver Code mat = [[ 1, 2, 3, 4, 5 ], [ 5, 3, 1, 4, 2 ], [ 5, 6, 7, 8, 9 ], [ 0, 6, 3, 4, 12 ], [ 9, 7, 12, 4, 3 ]] ans, ans0 = colMaxSum(mat) print("Column", ans + 1, "has max Sum", ans0) # This code is contributed by# Mohit kumar 29
// C# program to find column// with max sum in a matrixusing System; class GFG{ // No of rows and columnstatic readonly int N = 5; // structure for pairpublic class Pair{ public int first , second; public Pair(int f, int s) { first = f; second = s; }} // Function to find the column// with max sumstatic Pair colMaxSum(int [,]mat){ // Variable to store index of // column with maximum int idx = -1; // Variable to store max sum int maxSum = int.MinValue; // Traverse matrix column wise for (int i = 0; i < N; i++) { int sum = 0; // calculate sum of column for (int j = 0; j < N; j++) { sum += mat[j, i]; } // Update maxSum if it is // less than current sum if (sum > maxSum) { maxSum = sum; // store index idx = i; } } Pair res; res = new Pair(idx, maxSum); // return result return res;} // Driver codepublic static void Main(String []args){ int [,]mat = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }}; Pair ans = colMaxSum(mat); Console.WriteLine("Column " + (int)(ans.first + 1) + " has max sum " + ans.second);}} // This code has been contributed by 29AjayKumar
<script>// Javascript program to find column// with max sum in a matrix // No of rows and columnlet N = 5; // Function to find the column// with max sumfunction colMaxSum(mat){ // Variable to store index of // column with maximum let idx = -1; // Variable to store max sum let maxSum = Number.MIN_VALUE; // Traverse matrix column wise for (let i = 0; i < N; i++) { let sum = 0; // calculate sum of column for (let j = 0; j < N; j++) { sum += mat[j][i]; } // Update maxSum if it is // less than current sum if (sum > maxSum) { maxSum = sum; // store index idx = i; } } let res; res = [idx, maxSum]; // return result return res;} // Driver codelet mat = [[ 1, 2, 3, 4, 5 ], [ 5, 3, 1, 4, 2 ], [ 5, 6, 7, 8, 9 ], [ 0, 6, 3, 4, 12 ], [ 9, 7, 12, 4, 3 ]]; let ans = colMaxSum(mat);document.write("Column " + (ans[0] + 1) + " has max sum " + ans[1]); // This code is contributed by unknown2108</script>
Column 5 has max sum 31
Time Complexity : O(N*N) where N is size of each row or column in matrix.
Auxiliary Space : O(1)
andrew1234
mohit kumar 29
29AjayKumar
unknown2108
aditya942003patil
Traversal
Matrix
Matrix
Traversal
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Unique paths in a Grid with Obstacles
Traverse a given Matrix using Recursion
Count all possible paths from top left to bottom right of a mXn matrix
Inplace rotate square matrix by 90 degrees | Set 1
Printing all solutions in N-Queen Problem
Maximum size rectangle binary sub-matrix with all 1s
Python program to multiply two matrices
Real-time application of Data Structures | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 197,
"s": 54,
"text": "Given a N*N matrix. The task is to find the index of column with maximum sum. That is the column whose sum of elements are maximum.Examples: "
},
{
"code": null,
"e": 518,
"s": 197,
"text": "Input : mat[][] = {\n { 1, 2, 3, 4, 5 },\n { 5, 3, 1, 4, 2 },\n { 5, 6, 7, 8, 9 },\n { 0, 6, 3, 4, 12 },\n { 9, 7, 12, 4, 3 },\n };\nOutput : Column 5 has max sum 31\n\nInput : mat[][] = {\n { 1, 2, 3 },\n { 4, 2, 1 },\n { 5, 6, 7 },\n };\nOutput : Column 3 has max sum 11"
},
{
"code": null,
"e": 811,
"s": 520,
"text": "The idea is to traverse the matrix column-wise and find the sum of elements in each column and check for every column if current sum is greater than the maximum sum obtained till the current column and update the maximum_sum accordingly. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 815,
"s": 811,
"text": "C++"
},
{
"code": null,
"e": 820,
"s": 815,
"text": "Java"
},
{
"code": null,
"e": 828,
"s": 820,
"text": "Python3"
},
{
"code": null,
"e": 831,
"s": 828,
"text": "C#"
},
{
"code": null,
"e": 842,
"s": 831,
"text": "Javascript"
},
{
"code": "// C++ program to find column with// max sum in a matrix#include <bits/stdc++.h>using namespace std; #define N 5 // No of rows and column // Function to find the column with max sumpair<int, int> colMaxSum(int mat[N][N]){ // Variable to store index of column // with maximum int idx = -1; // Variable to store max sum int maxSum = INT_MIN; // Traverse matrix column wise for (int i = 0; i < N; i++) { int sum = 0; // calculate sum of column for (int j = 0; j < N; j++) { sum += mat[j][i]; } // Update maxSum if it is less than // current sum if (sum > maxSum) { maxSum = sum; // store index idx = i; } } pair<int, int> res; res = make_pair(idx, maxSum); // return result return res;} // driver codeint main(){ int mat[N][N] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; pair<int, int> ans = colMaxSum(mat); cout << \"Column \" << ans.first + 1 << \" has max sum \" << ans.second; return 0;}",
"e": 1993,
"s": 842,
"text": null
},
{
"code": "// Java program to find column// with max sum in a matriximport java.util.*; class GFG{// No of rows and columnstatic final int N = 5; // structure for pairstatic class Pair{ int first , second; Pair(int f, int s) { first = f; second = s; }} // Function to find the column// with max sumstatic Pair colMaxSum(int mat[][]){ // Variable to store index of // column with maximum int idx = -1; // Variable to store max sum int maxSum = Integer.MIN_VALUE; // Traverse matrix column wise for (int i = 0; i < N; i++) { int sum = 0; // calculate sum of column for (int j = 0; j < N; j++) { sum += mat[j][i]; } // Update maxSum if it is // less than current sum if (sum > maxSum) { maxSum = sum; // store index idx = i; } } Pair res; res = new Pair(idx, maxSum); // return result return res;} // Driver codepublic static void main(String args[]){ int mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }}; Pair ans = colMaxSum(mat); System.out.println(\"Column \" + (int)(ans.first + 1) + \" has max sum \" + ans.second);}} // This code is contributed// by Arnab Kundu",
"e": 3409,
"s": 1993,
"text": null
},
{
"code": "# Python3 program to find column with# max Sum in a matrix N = 5 # Function to find the column with max Sumdef colMaxSum(mat): # Variable to store index of column # with maximum idx = -1 # Variable to store max Sum maxSum = -10**9 # Traverse matrix column wise for i in range(N): Sum = 0 # calculate Sum of column for j in range(N): Sum += mat[j][i] # Update maxSum if it is less # than current Sum if (Sum > maxSum): maxSum = Sum # store index idx = i # return result return idx, maxSum # Driver Code mat = [[ 1, 2, 3, 4, 5 ], [ 5, 3, 1, 4, 2 ], [ 5, 6, 7, 8, 9 ], [ 0, 6, 3, 4, 12 ], [ 9, 7, 12, 4, 3 ]] ans, ans0 = colMaxSum(mat) print(\"Column\", ans + 1, \"has max Sum\", ans0) # This code is contributed by# Mohit kumar 29",
"e": 4299,
"s": 3409,
"text": null
},
{
"code": "// C# program to find column// with max sum in a matrixusing System; class GFG{ // No of rows and columnstatic readonly int N = 5; // structure for pairpublic class Pair{ public int first , second; public Pair(int f, int s) { first = f; second = s; }} // Function to find the column// with max sumstatic Pair colMaxSum(int [,]mat){ // Variable to store index of // column with maximum int idx = -1; // Variable to store max sum int maxSum = int.MinValue; // Traverse matrix column wise for (int i = 0; i < N; i++) { int sum = 0; // calculate sum of column for (int j = 0; j < N; j++) { sum += mat[j, i]; } // Update maxSum if it is // less than current sum if (sum > maxSum) { maxSum = sum; // store index idx = i; } } Pair res; res = new Pair(idx, maxSum); // return result return res;} // Driver codepublic static void Main(String []args){ int [,]mat = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }}; Pair ans = colMaxSum(mat); Console.WriteLine(\"Column \" + (int)(ans.first + 1) + \" has max sum \" + ans.second);}} // This code has been contributed by 29AjayKumar",
"e": 5722,
"s": 4299,
"text": null
},
{
"code": "<script>// Javascript program to find column// with max sum in a matrix // No of rows and columnlet N = 5; // Function to find the column// with max sumfunction colMaxSum(mat){ // Variable to store index of // column with maximum let idx = -1; // Variable to store max sum let maxSum = Number.MIN_VALUE; // Traverse matrix column wise for (let i = 0; i < N; i++) { let sum = 0; // calculate sum of column for (let j = 0; j < N; j++) { sum += mat[j][i]; } // Update maxSum if it is // less than current sum if (sum > maxSum) { maxSum = sum; // store index idx = i; } } let res; res = [idx, maxSum]; // return result return res;} // Driver codelet mat = [[ 1, 2, 3, 4, 5 ], [ 5, 3, 1, 4, 2 ], [ 5, 6, 7, 8, 9 ], [ 0, 6, 3, 4, 12 ], [ 9, 7, 12, 4, 3 ]]; let ans = colMaxSum(mat);document.write(\"Column \" + (ans[0] + 1) + \" has max sum \" + ans[1]); // This code is contributed by unknown2108</script>",
"e": 6854,
"s": 5722,
"text": null
},
{
"code": null,
"e": 6878,
"s": 6854,
"text": "Column 5 has max sum 31"
},
{
"code": null,
"e": 6954,
"s": 6880,
"text": "Time Complexity : O(N*N) where N is size of each row or column in matrix."
},
{
"code": null,
"e": 6977,
"s": 6954,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 6988,
"s": 6977,
"text": "andrew1234"
},
{
"code": null,
"e": 7003,
"s": 6988,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7015,
"s": 7003,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7027,
"s": 7015,
"text": "unknown2108"
},
{
"code": null,
"e": 7045,
"s": 7027,
"text": "aditya942003patil"
},
{
"code": null,
"e": 7055,
"s": 7045,
"text": "Traversal"
},
{
"code": null,
"e": 7062,
"s": 7055,
"text": "Matrix"
},
{
"code": null,
"e": 7069,
"s": 7062,
"text": "Matrix"
},
{
"code": null,
"e": 7079,
"s": 7069,
"text": "Traversal"
},
{
"code": null,
"e": 7177,
"s": 7079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7259,
"s": 7177,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 7281,
"s": 7259,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 7319,
"s": 7281,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 7359,
"s": 7319,
"text": "Traverse a given Matrix using Recursion"
},
{
"code": null,
"e": 7430,
"s": 7359,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 7481,
"s": 7430,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 7523,
"s": 7481,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 7576,
"s": 7523,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
},
{
"code": null,
"e": 7616,
"s": 7576,
"text": "Python program to multiply two matrices"
}
]
|
Flutter - Gestures - GeeksforGeeks | 14 Sep, 2020
Gestures are used to interact with an application. It is generally used in touch-based devices to physically interact with the application. It can be as simple as a single tap on the screen to a more complex physical interaction like swiping in a specific direction to scrolling down an application. It is heavily used in gaming and more or less every application requires it to function as devices turn more touch-based than ever. In this article, we will discuss them in detail.
Some widely used gestures are mentioned here :
Tap: Touching the surface of the device with the fingertip for a small duration of time period and finally releasing the fingertip.
Double Tap: Tapping twice in a short time.
Drag: Touching the surface of the device with the fingertip and then moving the fingertip in a steadily and finally releasing the fingertip.
Flick: Similar to dragging, but doing it in a speedier way.
Pinch: Pinching the surface of the device using two fingers.
Zoom: Opposite of pinching.
Panning: Touching the device surface with the fingertip and moving it in the desired direction without releasing the fingertip.
The GestureDetector widget in flutter is used to detect physical interaction with the application on the UI. If a widget is supposed to experience a gesture, it is kept inside the GestureDetector widget. The same widget catches the gesture and returns the appropriate action or response.
Below is the list of gestures and their corresponding events :
onTapDown
onTapUp
onTap
onTapCancel
onDoubleTap
onLongPress
onVerticalDragStart
onVerticalDragUpdate
onVerticalDragEnd
onHorizontalDragStart
onHorizontalDragUpdate
onHorizontalDragEnd
onPanStart
onPanUpdate
onPanEnd
Example:
Dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'Gestures'; return MaterialApp( title: title, home: MyHomePage(title: title), ); }} class MyHomePage extends StatelessWidget { final String title; MyHomePage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center(child: MyButton()), ); }} class MyButton extends StatelessWidget { @override Widget build(BuildContext context) { // The GestureDetector wraps the button. return GestureDetector( // show snackbar on tap of child onTap: () { final snackBar = SnackBar(content: Text(" You just Tapped on the Button")); Scaffold.of(context).showSnackBar(snackBar); }, // The tap button child: Container( padding: EdgeInsets.all(12.0), decoration: BoxDecoration( color: Theme.of(context).buttonColor, borderRadius: BorderRadius.circular(8.0), ), child: Text('Tap Button'), ), ); }}
Output:
Flutter supports Listener widgets that are low-level gesture detection mechanism. It detects user interaction and dispatches one of the below mentioned corresponding events:
PointerDownEvent
PointerMoveEvent
PointerUpEvent
PointerCancelEvent
Flutter also has widgets to do specific as well as advanced gestures. These widgets are as below :
Dismissible: Supports flick gesture to terminate the widget.
Draggable: Supports drag gesture to make the widget mobile.
LongPressDraggable: If the parent widgets are draggable, it supports the drag gesture to move the children widget.
DragTarget: Accepts any Draggable widget
IgnorePointer: When used it hides the widget and its corresponding children from the gesture detection process.
AbsorbPointer: Stops the gesture detection process itself to avoid action dispatch on overlapping widgets.
Scrollable: Makes content available inside the widget scrollable.
android
Flutter
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Getter and Setter Methods in Dart
Flutter - Flexible Widget
Flutter - BoxShadow Widget | [
{
"code": null,
"e": 27159,
"s": 27131,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 27640,
"s": 27159,
"text": "Gestures are used to interact with an application. It is generally used in touch-based devices to physically interact with the application. It can be as simple as a single tap on the screen to a more complex physical interaction like swiping in a specific direction to scrolling down an application. It is heavily used in gaming and more or less every application requires it to function as devices turn more touch-based than ever. In this article, we will discuss them in detail."
},
{
"code": null,
"e": 27687,
"s": 27640,
"text": "Some widely used gestures are mentioned here :"
},
{
"code": null,
"e": 27819,
"s": 27687,
"text": "Tap: Touching the surface of the device with the fingertip for a small duration of time period and finally releasing the fingertip."
},
{
"code": null,
"e": 27862,
"s": 27819,
"text": "Double Tap: Tapping twice in a short time."
},
{
"code": null,
"e": 28003,
"s": 27862,
"text": "Drag: Touching the surface of the device with the fingertip and then moving the fingertip in a steadily and finally releasing the fingertip."
},
{
"code": null,
"e": 28063,
"s": 28003,
"text": "Flick: Similar to dragging, but doing it in a speedier way."
},
{
"code": null,
"e": 28124,
"s": 28063,
"text": "Pinch: Pinching the surface of the device using two fingers."
},
{
"code": null,
"e": 28152,
"s": 28124,
"text": "Zoom: Opposite of pinching."
},
{
"code": null,
"e": 28280,
"s": 28152,
"text": "Panning: Touching the device surface with the fingertip and moving it in the desired direction without releasing the fingertip."
},
{
"code": null,
"e": 28568,
"s": 28280,
"text": "The GestureDetector widget in flutter is used to detect physical interaction with the application on the UI. If a widget is supposed to experience a gesture, it is kept inside the GestureDetector widget. The same widget catches the gesture and returns the appropriate action or response."
},
{
"code": null,
"e": 28631,
"s": 28568,
"text": "Below is the list of gestures and their corresponding events :"
},
{
"code": null,
"e": 28641,
"s": 28631,
"text": "onTapDown"
},
{
"code": null,
"e": 28649,
"s": 28641,
"text": "onTapUp"
},
{
"code": null,
"e": 28655,
"s": 28649,
"text": "onTap"
},
{
"code": null,
"e": 28667,
"s": 28655,
"text": "onTapCancel"
},
{
"code": null,
"e": 28679,
"s": 28667,
"text": "onDoubleTap"
},
{
"code": null,
"e": 28691,
"s": 28679,
"text": "onLongPress"
},
{
"code": null,
"e": 28711,
"s": 28691,
"text": "onVerticalDragStart"
},
{
"code": null,
"e": 28732,
"s": 28711,
"text": "onVerticalDragUpdate"
},
{
"code": null,
"e": 28750,
"s": 28732,
"text": "onVerticalDragEnd"
},
{
"code": null,
"e": 28772,
"s": 28750,
"text": "onHorizontalDragStart"
},
{
"code": null,
"e": 28795,
"s": 28772,
"text": "onHorizontalDragUpdate"
},
{
"code": null,
"e": 28815,
"s": 28795,
"text": "onHorizontalDragEnd"
},
{
"code": null,
"e": 28826,
"s": 28815,
"text": "onPanStart"
},
{
"code": null,
"e": 28838,
"s": 28826,
"text": "onPanUpdate"
},
{
"code": null,
"e": 28847,
"s": 28838,
"text": "onPanEnd"
},
{
"code": null,
"e": 28856,
"s": 28847,
"text": "Example:"
},
{
"code": null,
"e": 28861,
"s": 28856,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = 'Gestures'; return MaterialApp( title: title, home: MyHomePage(title: title), ); }} class MyHomePage extends StatelessWidget { final String title; MyHomePage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksForGeeks'), backgroundColor: Colors.green, ), body: Center(child: MyButton()), ); }} class MyButton extends StatelessWidget { @override Widget build(BuildContext context) { // The GestureDetector wraps the button. return GestureDetector( // show snackbar on tap of child onTap: () { final snackBar = SnackBar(content: Text(\" You just Tapped on the Button\")); Scaffold.of(context).showSnackBar(snackBar); }, // The tap button child: Container( padding: EdgeInsets.all(12.0), decoration: BoxDecoration( color: Theme.of(context).buttonColor, borderRadius: BorderRadius.circular(8.0), ), child: Text('Tap Button'), ), ); }}",
"e": 30126,
"s": 28861,
"text": null
},
{
"code": null,
"e": 30134,
"s": 30126,
"text": "Output:"
},
{
"code": null,
"e": 30309,
"s": 30134,
"text": "Flutter supports Listener widgets that are low-level gesture detection mechanism. It detects user interaction and dispatches one of the below mentioned corresponding events:"
},
{
"code": null,
"e": 30326,
"s": 30309,
"text": "PointerDownEvent"
},
{
"code": null,
"e": 30343,
"s": 30326,
"text": "PointerMoveEvent"
},
{
"code": null,
"e": 30358,
"s": 30343,
"text": "PointerUpEvent"
},
{
"code": null,
"e": 30377,
"s": 30358,
"text": "PointerCancelEvent"
},
{
"code": null,
"e": 30476,
"s": 30377,
"text": "Flutter also has widgets to do specific as well as advanced gestures. These widgets are as below :"
},
{
"code": null,
"e": 30537,
"s": 30476,
"text": "Dismissible: Supports flick gesture to terminate the widget."
},
{
"code": null,
"e": 30597,
"s": 30537,
"text": "Draggable: Supports drag gesture to make the widget mobile."
},
{
"code": null,
"e": 30712,
"s": 30597,
"text": "LongPressDraggable: If the parent widgets are draggable, it supports the drag gesture to move the children widget."
},
{
"code": null,
"e": 30753,
"s": 30712,
"text": "DragTarget: Accepts any Draggable widget"
},
{
"code": null,
"e": 30865,
"s": 30753,
"text": "IgnorePointer: When used it hides the widget and its corresponding children from the gesture detection process."
},
{
"code": null,
"e": 30972,
"s": 30865,
"text": "AbsorbPointer: Stops the gesture detection process itself to avoid action dispatch on overlapping widgets."
},
{
"code": null,
"e": 31038,
"s": 30972,
"text": "Scrollable: Makes content available inside the widget scrollable."
},
{
"code": null,
"e": 31046,
"s": 31038,
"text": "android"
},
{
"code": null,
"e": 31054,
"s": 31046,
"text": "Flutter"
},
{
"code": null,
"e": 31059,
"s": 31054,
"text": "Dart"
},
{
"code": null,
"e": 31157,
"s": 31059,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31189,
"s": 31157,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 31217,
"s": 31189,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 31239,
"s": 31217,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 31264,
"s": 31239,
"text": "Splash Screen in Flutter"
},
{
"code": null,
"e": 31303,
"s": 31264,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31329,
"s": 31303,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 31355,
"s": 31329,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 31389,
"s": 31355,
"text": "Getter and Setter Methods in Dart"
},
{
"code": null,
"e": 31415,
"s": 31389,
"text": "Flutter - Flexible Widget"
}
]
|
Longest Possible Chunked Palindrome - GeeksforGeeks | 19 Apr, 2022
Given a string, the task is to return the length of its longest possible chunked palindrome. It means a palindrome formed by substring in the case when it is not formed by characters of the string. For a better understanding look at the example Examples:
Input : ghiabcdefhelloadamhelloabcdefghi
Output : 7
(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)
Input : merchant
Output : 1
(merchant)
Input : antaprezatepzapreanta
Output : 11
(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)
Input : geeksforgeeks
Output : 3
(geeks)(for)(geeks)
The entire idea is to create chunks from left and right and recursively. As you can see, we can match substring from the left side chunk and match it with the exact right side chunk. Once we get a match, we recursively count the length of the longest possible chunked palindrome in the remaining string. We end the recursion once no string is left or when no more valid chunked parts can be found.
Java
Python3
C#
Javascript
/* Java program to find the length of longest palindromic chunk */import java.util.*;import java.lang.*;import java.io.*; class LongestPalindromicChunk{ // Here s is the string whose LCP is needed // ln is length of string evaluated till now // and str is original string private static int LPCRec(String curr_str, int count, int len, String str) { // if there is noting at all!! if (curr_str == null || curr_str.isEmpty()) return (0); // if a single letter is left out if (curr_str.length() <= 1) { if (count != 0 && str.length() - len <= 1) return (count + 1); else return (1); } // for each length of substring chunk in string int n = curr_str.length(); for (int i = 0; i < n/2; i++) { // if left side chunk and right side chunk // are same if (curr_str.substring(0, i + 1). equals(curr_str.substring(n-1-i, n))) { // Call LCP for the part between the // chunks and add 2 to the result. // Length of string evaluated till // now is increased by (i+1)*2 return LPCRec(curr_str.substring(i+1, n-1-i), count + 2, len + (i+1)*2, str); } } return count + 1; } // Wrapper over LPCRec() public static int LPC(String str) { return LPCRec(str, 0, 0, str); } // driver function public static void main(String[] args) { System.out.println("V : " + LPC("V")); System.out.println("VOLVO : " + LPC("VOLVO")); System.out.println("VOLVOV : " + LPC("VOLVOV")); System.out.println("ghiabcdefhelloadamhelloabcdefghi : " + LPC("ghiabcdefhelloadamhelloabcdefghi")); System.out.println("ghiabcdefhelloadamhelloabcdefghik : " + LPC("ghiabcdefhelloadamhelloabcdefghik")); System.out.println("antaprezatepzapreanta : " + LPC("antaprezatepzapreanta")); }}
# Python3 program to find length of# longest palindromic chunk # Here curr_str is the string whose# LCP is needed leng is length of# string evaluated till now and s # is original stringdef LPCRec(curr_str, count, leng, s): # If there is nothing at all!! if not curr_str: return 0 # If a single letter is left out if len(curr_str) <= 1: if count != 0 and len(s) - leng <= 1: return (count + 1) else: return 1 # For each length of substring # chunk in string n = len(curr_str) for i in range(n // 2): # If left side chunk and right # side chunk are same if (curr_str[0 : i + 1] == curr_str[n - 1 - i : n]): # Call LCP for the part between the # chunks and add 2 to the result. # Length of string evaluated till # now is increased by (i+1)*2 return LPCRec(curr_str[i + 1 : n - 1 - i], count + 2, leng + (i + 1) * 2, s) return count + 1 # Wrapper over LPCRec()def LPC(s): return LPCRec(s, 0, 0, s) # Driver codeprint("V :", LPC("V"))print("VOLVO :", LPC("VOLVO"))print("VOLVOV :", LPC("VOLVOV"))print("ghiabcdefhelloadamhelloabcdefghi :", LPC("ghiabcdefhelloadamhelloabcdefghi")) print("ghiabcdefhelloadamhelloabcdefghik :", LPC("ghiabcdefhelloadamhelloabcdefghik")) print("antaprezatepzapreanta :", LPC("antaprezatepzapreanta")) # This code is contributed by Prateek Gupta
// C# program to find length of// longest palindromic chunkusing System; class GFG{// Here s is the string whose LCP// is needed ln is length of string// evaluated till now and str is// original stringprivate static int LPCRec(string curr_str, int count, int len, string str){ // if there is noting at all!! if (string.ReferenceEquals(curr_str, null) || curr_str.Length == 0) { return (0); } // if a single letter is left out if (curr_str.Length <= 1) { if (count != 0 && str.Length - len <= 1) { return (count + 1); } else { return (1); } } // for each length of substring // chunk in string int n = curr_str.Length; for (int i = 0; i < n / 2; i++) { // if left side chunk and right side chunk // are same if (curr_str.Substring(0, i + 1).Equals( curr_str.Substring(n - 1 - i, n - (n - 1 - i)))) { // Call LCP for the part between the // chunks and add 2 to the result. // Length of string evaluated till // now is increased by (i+1)*2 return LPCRec(curr_str.Substring(i + 1, (n - 1 - i) - (i + 1)), count + 2, len + (i + 1) * 2, str); } } return count + 1;} // Wrapper over LPCRec()public static int LPC(string str){ return LPCRec(str, 0, 0, str);} // Driver Codepublic static void Main(string[] args){ Console.WriteLine("V : " + LPC("V")); Console.WriteLine("VOLVO : " + LPC("VOLVO")); Console.WriteLine("VOLVOV : " + LPC("VOLVOV")); Console.WriteLine("ghiabcdefhelloadamhelloabcdefghi : " + LPC("ghiabcdefhelloadamhelloabcdefghi")); Console.WriteLine("ghiabcdefhelloadamhelloabcdefghik : " + LPC("ghiabcdefhelloadamhelloabcdefghik")); Console.WriteLine("antaprezatepzapreanta : " + LPC("antaprezatepzapreanta"));}} // This code is contributed by Shrikant13
<script> // JavaScript program to find length of// longest palindromic chunk // Here curr_str is the string whose// LCP is needed leng is length of// string evaluated till now and s // is original stringfunction LPCRec(curr_str, count, leng, s){ // If there is nothing at all!! if(!curr_str) return 0 // If a single letter is left out if(curr_str.length <= 1){ if (count != 0 && s.length - leng <= 1) return (count + 1) else return 1 } // For each length of substring // chunk in string let n = curr_str.length for(let i=0;i<Math.floor(n/2);i++){ // If left side chunk and right // side chunk are same if (curr_str.substring(0,i+1) == curr_str.substring(n-1-i,n)) // Call LCP for the part between the // chunks and add 2 to the result. // Length of string evaluated till // now is increased by (i+1)*2 return LPCRec(curr_str.substring(i + 1,n - 1 - i), count + 2, leng + (i + 1) * 2, s) } return count + 1} // Wrapper over LPCRec()function LPC(s){ return LPCRec(s, 0, 0, s)} // Driver codedocument.write("V :", LPC("V"),"</br>")document.write("VOLVO :", LPC("VOLVO"),"</br>")document.write("VOLVOV :", LPC("VOLVOV"),"</br>")document.write("ghiabcdefhelloadamhelloabcdefghi :", LPC("ghiabcdefhelloadamhelloabcdefghi"),"</br>") document.write("ghiabcdefhelloadamhelloabcdefghik :", LPC("ghiabcdefhelloadamhelloabcdefghik"),"</br>") document.write("antaprezatepzapreanta :", LPC("antaprezatepzapreanta"),"</br>") // This code is contributed by shinjanpatra </script>
Output:
V : 1
VOLVO : 3
VOLVOV : 5
ghiabcdefhelloadamhelloabcdefghi : 7
ghiabcdefhelloadamhelloabcdefghik : 1
antaprezatepzapreanta : 11
Following is the C++ implementation with memoization for above problem.
CPP
Python3
#include <iostream>#include <climits>#include <unordered_map>using namespace std; unordered_map<string, int> mem; int process(string& s, int l, int r) { int ans = 1; if (l > r) return 0; // check if we've already solved this if (mem.find(s.substr(l, r-l+1)) != mem.end()) return mem[s.substr(l, r-l+1)]; for (int len = 1; len <= (r-l+1)/2; len++) { if (s.substr(l, len) == s.substr(r-len+1, len)) ans = max(ans, 2 + process(s, l+len, r-len)); } // remember result for future mem[s.substr(l, r-l+1)] = ans; return ans;} int LPC(string s) { return process(s, 0, s.length()-1);} int main() { cout << LPC("aaaaabaababbaabaaababababababababbbbaaaaa") << endl; return 0;}
# Python code for the approach mem = {} def process(s,l,r): global mem ans = 1 if (l > r): return 0 # check if we've already solved this if (s[l: r+1] in mem): return mem[s[l: r+1]] for Len in range(1,(r-l+1)//2 + 1,1): if (s[l: Len+l] == s[r-Len+1:r+1]): ans = max(ans, 2 + process(s, l+Len, r-Len)) # remember result for future mem[s[l: r+1]] = ans return ans def LPC(s): return process(s, 0, len(s)-1) # driver code print(LPC("aaaaabaababbaabaaababababababababbbbaaaaa")) # This code is contributed by shinjanpatra.
Source: CareerCup This article is contributed by Aditya Nihal Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
babaduredi
PrateekGupta10
shinjanpatra
Google
palindrome
Strings
Google
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Check whether two strings are anagram of each other
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews | [
{
"code": null,
"e": 26543,
"s": 26515,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 26798,
"s": 26543,
"text": "Given a string, the task is to return the length of its longest possible chunked palindrome. It means a palindrome formed by substring in the case when it is not formed by characters of the string. For a better understanding look at the example Examples:"
},
{
"code": null,
"e": 27079,
"s": 26798,
"text": "Input : ghiabcdefhelloadamhelloabcdefghi \nOutput : 7\n(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\n\nInput : merchant\nOutput : 1\n(merchant)\n\nInput : antaprezatepzapreanta\nOutput : 11\n(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)\n\nInput : geeksforgeeks\nOutput : 3\n(geeks)(for)(geeks)"
},
{
"code": null,
"e": 27479,
"s": 27079,
"text": "The entire idea is to create chunks from left and right and recursively. As you can see, we can match substring from the left side chunk and match it with the exact right side chunk. Once we get a match, we recursively count the length of the longest possible chunked palindrome in the remaining string. We end the recursion once no string is left or when no more valid chunked parts can be found. "
},
{
"code": null,
"e": 27484,
"s": 27479,
"text": "Java"
},
{
"code": null,
"e": 27492,
"s": 27484,
"text": "Python3"
},
{
"code": null,
"e": 27495,
"s": 27492,
"text": "C#"
},
{
"code": null,
"e": 27506,
"s": 27495,
"text": "Javascript"
},
{
"code": "/* Java program to find the length of longest palindromic chunk */import java.util.*;import java.lang.*;import java.io.*; class LongestPalindromicChunk{ // Here s is the string whose LCP is needed // ln is length of string evaluated till now // and str is original string private static int LPCRec(String curr_str, int count, int len, String str) { // if there is noting at all!! if (curr_str == null || curr_str.isEmpty()) return (0); // if a single letter is left out if (curr_str.length() <= 1) { if (count != 0 && str.length() - len <= 1) return (count + 1); else return (1); } // for each length of substring chunk in string int n = curr_str.length(); for (int i = 0; i < n/2; i++) { // if left side chunk and right side chunk // are same if (curr_str.substring(0, i + 1). equals(curr_str.substring(n-1-i, n))) { // Call LCP for the part between the // chunks and add 2 to the result. // Length of string evaluated till // now is increased by (i+1)*2 return LPCRec(curr_str.substring(i+1, n-1-i), count + 2, len + (i+1)*2, str); } } return count + 1; } // Wrapper over LPCRec() public static int LPC(String str) { return LPCRec(str, 0, 0, str); } // driver function public static void main(String[] args) { System.out.println(\"V : \" + LPC(\"V\")); System.out.println(\"VOLVO : \" + LPC(\"VOLVO\")); System.out.println(\"VOLVOV : \" + LPC(\"VOLVOV\")); System.out.println(\"ghiabcdefhelloadamhelloabcdefghi : \" + LPC(\"ghiabcdefhelloadamhelloabcdefghi\")); System.out.println(\"ghiabcdefhelloadamhelloabcdefghik : \" + LPC(\"ghiabcdefhelloadamhelloabcdefghik\")); System.out.println(\"antaprezatepzapreanta : \" + LPC(\"antaprezatepzapreanta\")); }}",
"e": 29680,
"s": 27506,
"text": null
},
{
"code": "# Python3 program to find length of# longest palindromic chunk # Here curr_str is the string whose# LCP is needed leng is length of# string evaluated till now and s # is original stringdef LPCRec(curr_str, count, leng, s): # If there is nothing at all!! if not curr_str: return 0 # If a single letter is left out if len(curr_str) <= 1: if count != 0 and len(s) - leng <= 1: return (count + 1) else: return 1 # For each length of substring # chunk in string n = len(curr_str) for i in range(n // 2): # If left side chunk and right # side chunk are same if (curr_str[0 : i + 1] == curr_str[n - 1 - i : n]): # Call LCP for the part between the # chunks and add 2 to the result. # Length of string evaluated till # now is increased by (i+1)*2 return LPCRec(curr_str[i + 1 : n - 1 - i], count + 2, leng + (i + 1) * 2, s) return count + 1 # Wrapper over LPCRec()def LPC(s): return LPCRec(s, 0, 0, s) # Driver codeprint(\"V :\", LPC(\"V\"))print(\"VOLVO :\", LPC(\"VOLVO\"))print(\"VOLVOV :\", LPC(\"VOLVOV\"))print(\"ghiabcdefhelloadamhelloabcdefghi :\", LPC(\"ghiabcdefhelloadamhelloabcdefghi\")) print(\"ghiabcdefhelloadamhelloabcdefghik :\", LPC(\"ghiabcdefhelloadamhelloabcdefghik\")) print(\"antaprezatepzapreanta :\", LPC(\"antaprezatepzapreanta\")) # This code is contributed by Prateek Gupta",
"e": 31199,
"s": 29680,
"text": null
},
{
"code": "// C# program to find length of// longest palindromic chunkusing System; class GFG{// Here s is the string whose LCP// is needed ln is length of string// evaluated till now and str is// original stringprivate static int LPCRec(string curr_str, int count, int len, string str){ // if there is noting at all!! if (string.ReferenceEquals(curr_str, null) || curr_str.Length == 0) { return (0); } // if a single letter is left out if (curr_str.Length <= 1) { if (count != 0 && str.Length - len <= 1) { return (count + 1); } else { return (1); } } // for each length of substring // chunk in string int n = curr_str.Length; for (int i = 0; i < n / 2; i++) { // if left side chunk and right side chunk // are same if (curr_str.Substring(0, i + 1).Equals( curr_str.Substring(n - 1 - i, n - (n - 1 - i)))) { // Call LCP for the part between the // chunks and add 2 to the result. // Length of string evaluated till // now is increased by (i+1)*2 return LPCRec(curr_str.Substring(i + 1, (n - 1 - i) - (i + 1)), count + 2, len + (i + 1) * 2, str); } } return count + 1;} // Wrapper over LPCRec()public static int LPC(string str){ return LPCRec(str, 0, 0, str);} // Driver Codepublic static void Main(string[] args){ Console.WriteLine(\"V : \" + LPC(\"V\")); Console.WriteLine(\"VOLVO : \" + LPC(\"VOLVO\")); Console.WriteLine(\"VOLVOV : \" + LPC(\"VOLVOV\")); Console.WriteLine(\"ghiabcdefhelloadamhelloabcdefghi : \" + LPC(\"ghiabcdefhelloadamhelloabcdefghi\")); Console.WriteLine(\"ghiabcdefhelloadamhelloabcdefghik : \" + LPC(\"ghiabcdefhelloadamhelloabcdefghik\")); Console.WriteLine(\"antaprezatepzapreanta : \" + LPC(\"antaprezatepzapreanta\"));}} // This code is contributed by Shrikant13",
"e": 33239,
"s": 31199,
"text": null
},
{
"code": "<script> // JavaScript program to find length of// longest palindromic chunk // Here curr_str is the string whose// LCP is needed leng is length of// string evaluated till now and s // is original stringfunction LPCRec(curr_str, count, leng, s){ // If there is nothing at all!! if(!curr_str) return 0 // If a single letter is left out if(curr_str.length <= 1){ if (count != 0 && s.length - leng <= 1) return (count + 1) else return 1 } // For each length of substring // chunk in string let n = curr_str.length for(let i=0;i<Math.floor(n/2);i++){ // If left side chunk and right // side chunk are same if (curr_str.substring(0,i+1) == curr_str.substring(n-1-i,n)) // Call LCP for the part between the // chunks and add 2 to the result. // Length of string evaluated till // now is increased by (i+1)*2 return LPCRec(curr_str.substring(i + 1,n - 1 - i), count + 2, leng + (i + 1) * 2, s) } return count + 1} // Wrapper over LPCRec()function LPC(s){ return LPCRec(s, 0, 0, s)} // Driver codedocument.write(\"V :\", LPC(\"V\"),\"</br>\")document.write(\"VOLVO :\", LPC(\"VOLVO\"),\"</br>\")document.write(\"VOLVOV :\", LPC(\"VOLVOV\"),\"</br>\")document.write(\"ghiabcdefhelloadamhelloabcdefghi :\", LPC(\"ghiabcdefhelloadamhelloabcdefghi\"),\"</br>\") document.write(\"ghiabcdefhelloadamhelloabcdefghik :\", LPC(\"ghiabcdefhelloadamhelloabcdefghik\"),\"</br>\") document.write(\"antaprezatepzapreanta :\", LPC(\"antaprezatepzapreanta\"),\"</br>\") // This code is contributed by shinjanpatra </script>",
"e": 34922,
"s": 33239,
"text": null
},
{
"code": null,
"e": 34930,
"s": 34922,
"text": "Output:"
},
{
"code": null,
"e": 35059,
"s": 34930,
"text": "V : 1\nVOLVO : 3\nVOLVOV : 5\nghiabcdefhelloadamhelloabcdefghi : 7\nghiabcdefhelloadamhelloabcdefghik : 1\nantaprezatepzapreanta : 11"
},
{
"code": null,
"e": 35132,
"s": 35059,
"text": "Following is the C++ implementation with memoization for above problem. "
},
{
"code": null,
"e": 35136,
"s": 35132,
"text": "CPP"
},
{
"code": null,
"e": 35144,
"s": 35136,
"text": "Python3"
},
{
"code": "#include <iostream>#include <climits>#include <unordered_map>using namespace std; unordered_map<string, int> mem; int process(string& s, int l, int r) { int ans = 1; if (l > r) return 0; // check if we've already solved this if (mem.find(s.substr(l, r-l+1)) != mem.end()) return mem[s.substr(l, r-l+1)]; for (int len = 1; len <= (r-l+1)/2; len++) { if (s.substr(l, len) == s.substr(r-len+1, len)) ans = max(ans, 2 + process(s, l+len, r-len)); } // remember result for future mem[s.substr(l, r-l+1)] = ans; return ans;} int LPC(string s) { return process(s, 0, s.length()-1);} int main() { cout << LPC(\"aaaaabaababbaabaaababababababababbbbaaaaa\") << endl; return 0;}",
"e": 35878,
"s": 35144,
"text": null
},
{
"code": "# Python code for the approach mem = {} def process(s,l,r): global mem ans = 1 if (l > r): return 0 # check if we've already solved this if (s[l: r+1] in mem): return mem[s[l: r+1]] for Len in range(1,(r-l+1)//2 + 1,1): if (s[l: Len+l] == s[r-Len+1:r+1]): ans = max(ans, 2 + process(s, l+Len, r-Len)) # remember result for future mem[s[l: r+1]] = ans return ans def LPC(s): return process(s, 0, len(s)-1) # driver code print(LPC(\"aaaaabaababbaabaaababababababababbbbaaaaa\")) # This code is contributed by shinjanpatra.",
"e": 36459,
"s": 35878,
"text": null
},
{
"code": null,
"e": 36910,
"s": 36459,
"text": "Source: CareerCup This article is contributed by Aditya Nihal Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 36922,
"s": 36910,
"text": "shrikanth13"
},
{
"code": null,
"e": 36933,
"s": 36922,
"text": "babaduredi"
},
{
"code": null,
"e": 36948,
"s": 36933,
"text": "PrateekGupta10"
},
{
"code": null,
"e": 36961,
"s": 36948,
"text": "shinjanpatra"
},
{
"code": null,
"e": 36968,
"s": 36961,
"text": "Google"
},
{
"code": null,
"e": 36979,
"s": 36968,
"text": "palindrome"
},
{
"code": null,
"e": 36987,
"s": 36979,
"text": "Strings"
},
{
"code": null,
"e": 36994,
"s": 36987,
"text": "Google"
},
{
"code": null,
"e": 37002,
"s": 36994,
"text": "Strings"
},
{
"code": null,
"e": 37013,
"s": 37002,
"text": "palindrome"
},
{
"code": null,
"e": 37111,
"s": 37013,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37186,
"s": 37111,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 37243,
"s": 37186,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 37279,
"s": 37243,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 37326,
"s": 37279,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 37379,
"s": 37326,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 37415,
"s": 37379,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 37467,
"s": 37415,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 37505,
"s": 37467,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 37535,
"s": 37505,
"text": "Caesar Cipher in Cryptography"
}
]
|
Python Program for Largest Sum Contiguous Subarray - GeeksforGeeks | 06 Jan, 2022
Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum.
Kadane’s Algorithm:
Initialize:
max_so_far = INT_MIN
max_ending_here = 0
Loop for each element of the array
(a) max_ending_here = max_ending_here + a[i]
(b) if(max_so_far < max_ending_here)
max_so_far = max_ending_here
(c) if(max_ending_here < 0)
max_ending_here = 0
return max_so_far
Explanation: The simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far
Lets take the example:
{-2, -3, 4, -1, -2, 1, 5, -3}
max_so_far = max_ending_here = 0
for i=0, a[0] = -2
max_ending_here = max_ending_here + (-2)
Set max_ending_here = 0 because max_ending_here < 0
for i=1, a[1] = -3
max_ending_here = max_ending_here + (-3)
Set max_ending_here = 0 because max_ending_here < 0
for i=2, a[2] = 4
max_ending_here = max_ending_here + (4)
max_ending_here = 4
max_so_far is updated to 4 because max_ending_here greater
than max_so_far which was 0 till now
for i=3, a[3] = -1
max_ending_here = max_ending_here + (-1)
max_ending_here = 3
for i=4, a[4] = -2
max_ending_here = max_ending_here + (-2)
max_ending_here = 1
for i=5, a[5] = 1
max_ending_here = max_ending_here + (1)
max_ending_here = 2
for i=6, a[6] = 5
max_ending_here = max_ending_here + (5)
max_ending_here = 7
max_so_far is updated to 7 because max_ending_here is
greater than max_so_far
for i=7, a[7] = -3
max_ending_here = max_ending_here + (-3)
max_ending_here = 4
Program:
Python3
# Python program to find maximum contiguous subarray # Function to find the maximum contiguous subarrayfrom math import infmaxint=infdef maxSubArraySum(a,size): max_so_far = -maxint - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far # Driver function to check the above functiona = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]print ("Maximum contiguous sum is", maxSubArraySum(a,len(a))) #This code is contributed by _Devesh Agrawal_
Output:
Maximum contiguous sum is 7
Another approach:
Python3
def maxSubArraySum(a,size): max_so_far = a[0] max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_ending_here < 0: max_ending_here = 0 # Do not compare for all elements. Compare only # when max_ending_here > 0 elif (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far
Time Complexity: O(n)
Algorithmic Paradigm: Dynamic ProgrammingFollowing is another simple implementation suggested by Mohit Kumar. The implementation handles the case when all numbers in the array are negative.
Python3
# Python program to find maximum contiguous subarray def maxSubArraySum(a,size): max_so_far =a[0] curr_max = a[0] for i in range(1,size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far,curr_max) return max_so_far # Driver function to check the above functiona = [-2, -3, 4, -1, -2, 1, 5, -3]print("Maximum contiguous sum is" , maxSubArraySum(a,len(a))) #This code is contributed by _Devesh Agrawal_
Output:
Maximum contiguous sum is 7
To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum.
Python3
# Python program to print largest contiguous array sum from sys import maxsize # Function to find the maximum contiguous subarray# and print its starting and end indexdef maxSubArraySum(a,size): max_so_far = -maxsize - 1 max_ending_here = 0 start = 0 end = 0 s = 0 for i in range(0,size): max_ending_here += a[i] if max_so_far < max_ending_here: max_so_far = max_ending_here start = s end = i if max_ending_here < 0: max_ending_here = 0 s = i+1 print ("Maximum contiguous sum is %d"%(max_so_far)) print ("Starting Index %d"%(start)) print ("Ending Index %d"%(end)) # Driver program to test maxSubArraySuma = [-2, -3, 4, -1, -2, 1, 5, -3]maxSubArraySum(a,len(a))
Output:
Maximum contiguous sum is 7
Starting index 2
Ending index 6
Kadane’s Algorithm can be viewed both as a greedy and DP. As we can see that we are keeping a running sum of integers and when it becomes less than 0, we reset it to 0 (Greedy Part). This is because continuing with a negative sum is way more worse than restarting with a new range. Now it can also be viewed as a DP, at each stage we have 2 choices: Either take the current element and continue with previous sum OR restart a new range. These both choices are being taken care of in the implementation.
Time Complexity: O(n)
Auxiliary Space: O(1)
Now try the below question Given an array of integers (possibly some elements negative), write a C program to find out the *maximum product* possible by multiplying ‘n’ consecutive integers in the array where n ≤ ARRAY_SIZE. Also, print the starting point of the maximum product subarray.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
amartyaghoshgfg
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python program to check whether a number is Prime or not
Python Program for Binary Search (Recursive and Iterative)
Python Program for Fibonacci numbers
Iterate over characters of a string in Python
Python Program for factorial of a number
Python | Convert set into a list
Python | Check if a variable is string
Python | Convert a list into a tuple | [
{
"code": null,
"e": 26607,
"s": 26579,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 26742,
"s": 26607,
"text": "Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers that has the largest sum. "
},
{
"code": null,
"e": 26764,
"s": 26744,
"text": "Kadane’s Algorithm:"
},
{
"code": null,
"e": 27068,
"s": 26764,
"text": "Initialize:\n max_so_far = INT_MIN\n max_ending_here = 0\n\nLoop for each element of the array\n (a) max_ending_here = max_ending_here + a[i]\n (b) if(max_so_far < max_ending_here)\n max_so_far = max_ending_here\n (c) if(max_ending_here < 0)\n max_ending_here = 0\nreturn max_so_far"
},
{
"code": null,
"e": 27439,
"s": 27068,
"text": "Explanation: The simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far "
},
{
"code": null,
"e": 28548,
"s": 27439,
"text": " Lets take the example:\n {-2, -3, 4, -1, -2, 1, 5, -3}\n\n max_so_far = max_ending_here = 0\n\n for i=0, a[0] = -2\n max_ending_here = max_ending_here + (-2)\n Set max_ending_here = 0 because max_ending_here < 0\n\n for i=1, a[1] = -3\n max_ending_here = max_ending_here + (-3)\n Set max_ending_here = 0 because max_ending_here < 0\n\n for i=2, a[2] = 4\n max_ending_here = max_ending_here + (4)\n max_ending_here = 4\n max_so_far is updated to 4 because max_ending_here greater \n than max_so_far which was 0 till now\n\n for i=3, a[3] = -1\n max_ending_here = max_ending_here + (-1)\n max_ending_here = 3\n\n for i=4, a[4] = -2\n max_ending_here = max_ending_here + (-2)\n max_ending_here = 1\n\n for i=5, a[5] = 1\n max_ending_here = max_ending_here + (1)\n max_ending_here = 2\n\n for i=6, a[6] = 5\n max_ending_here = max_ending_here + (5)\n max_ending_here = 7\n max_so_far is updated to 7 because max_ending_here is \n greater than max_so_far\n\n for i=7, a[7] = -3\n max_ending_here = max_ending_here + (-3)\n max_ending_here = 4"
},
{
"code": null,
"e": 28558,
"s": 28548,
"text": "Program: "
},
{
"code": null,
"e": 28566,
"s": 28558,
"text": "Python3"
},
{
"code": "# Python program to find maximum contiguous subarray # Function to find the maximum contiguous subarrayfrom math import infmaxint=infdef maxSubArraySum(a,size): max_so_far = -maxint - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far # Driver function to check the above functiona = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]print (\"Maximum contiguous sum is\", maxSubArraySum(a,len(a))) #This code is contributed by _Devesh Agrawal_",
"e": 29254,
"s": 28566,
"text": null
},
{
"code": null,
"e": 29262,
"s": 29254,
"text": "Output:"
},
{
"code": null,
"e": 29290,
"s": 29262,
"text": "Maximum contiguous sum is 7"
},
{
"code": null,
"e": 29308,
"s": 29290,
"text": "Another approach:"
},
{
"code": null,
"e": 29316,
"s": 29308,
"text": "Python3"
},
{
"code": "def maxSubArraySum(a,size): max_so_far = a[0] max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_ending_here < 0: max_ending_here = 0 # Do not compare for all elements. Compare only # when max_ending_here > 0 elif (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far",
"e": 29755,
"s": 29316,
"text": null
},
{
"code": null,
"e": 29778,
"s": 29755,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 29969,
"s": 29778,
"text": "Algorithmic Paradigm: Dynamic ProgrammingFollowing is another simple implementation suggested by Mohit Kumar. The implementation handles the case when all numbers in the array are negative. "
},
{
"code": null,
"e": 29977,
"s": 29969,
"text": "Python3"
},
{
"code": "# Python program to find maximum contiguous subarray def maxSubArraySum(a,size): max_so_far =a[0] curr_max = a[0] for i in range(1,size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far,curr_max) return max_so_far # Driver function to check the above functiona = [-2, -3, 4, -1, -2, 1, 5, -3]print(\"Maximum contiguous sum is\" , maxSubArraySum(a,len(a))) #This code is contributed by _Devesh Agrawal_",
"e": 30440,
"s": 29977,
"text": null
},
{
"code": null,
"e": 30449,
"s": 30440,
"text": "Output: "
},
{
"code": null,
"e": 30477,
"s": 30449,
"text": "Maximum contiguous sum is 7"
},
{
"code": null,
"e": 30576,
"s": 30477,
"text": "To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum. "
},
{
"code": null,
"e": 30584,
"s": 30576,
"text": "Python3"
},
{
"code": "# Python program to print largest contiguous array sum from sys import maxsize # Function to find the maximum contiguous subarray# and print its starting and end indexdef maxSubArraySum(a,size): max_so_far = -maxsize - 1 max_ending_here = 0 start = 0 end = 0 s = 0 for i in range(0,size): max_ending_here += a[i] if max_so_far < max_ending_here: max_so_far = max_ending_here start = s end = i if max_ending_here < 0: max_ending_here = 0 s = i+1 print (\"Maximum contiguous sum is %d\"%(max_so_far)) print (\"Starting Index %d\"%(start)) print (\"Ending Index %d\"%(end)) # Driver program to test maxSubArraySuma = [-2, -3, 4, -1, -2, 1, 5, -3]maxSubArraySum(a,len(a))",
"e": 31355,
"s": 30584,
"text": null
},
{
"code": null,
"e": 31364,
"s": 31355,
"text": "Output: "
},
{
"code": null,
"e": 31424,
"s": 31364,
"text": "Maximum contiguous sum is 7\nStarting index 2\nEnding index 6"
},
{
"code": null,
"e": 31928,
"s": 31424,
"text": "Kadane’s Algorithm can be viewed both as a greedy and DP. As we can see that we are keeping a running sum of integers and when it becomes less than 0, we reset it to 0 (Greedy Part). This is because continuing with a negative sum is way more worse than restarting with a new range. Now it can also be viewed as a DP, at each stage we have 2 choices: Either take the current element and continue with previous sum OR restart a new range. These both choices are being taken care of in the implementation. "
},
{
"code": null,
"e": 31950,
"s": 31928,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 31972,
"s": 31950,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32261,
"s": 31972,
"text": "Now try the below question Given an array of integers (possibly some elements negative), write a C program to find out the *maximum product* possible by multiplying ‘n’ consecutive integers in the array where n ≤ ARRAY_SIZE. Also, print the starting point of the maximum product subarray."
},
{
"code": null,
"e": 32386,
"s": 32261,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32402,
"s": 32386,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 32418,
"s": 32402,
"text": "Python Programs"
},
{
"code": null,
"e": 32516,
"s": 32418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32554,
"s": 32516,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 32603,
"s": 32554,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 32660,
"s": 32603,
"text": "Python program to check whether a number is Prime or not"
},
{
"code": null,
"e": 32719,
"s": 32660,
"text": "Python Program for Binary Search (Recursive and Iterative)"
},
{
"code": null,
"e": 32756,
"s": 32719,
"text": "Python Program for Fibonacci numbers"
},
{
"code": null,
"e": 32802,
"s": 32756,
"text": "Iterate over characters of a string in Python"
},
{
"code": null,
"e": 32843,
"s": 32802,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 32876,
"s": 32843,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 32915,
"s": 32876,
"text": "Python | Check if a variable is string"
}
]
|
How to get the last character of a string in PHP ? - GeeksforGeeks | 21 May, 2021
In this article, we will find the last character of a string in PHP. The last character can be found using the following methods.
Using array() method
Using substr() method
Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is “Akshit” Its length is 6, in zero-indexing, the value of (length-1) is 5 which is the character “t” The length can be found using the PHP strlen() method.
The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.
Syntax:
strlen($string)
Example:
PHP
<?php $txt = "Geeksforgeeks"; echo "Last Character of string is : " .$txt[strlen($txt)-1];?>
Output:
Last Character of string is : s
Using substr() Method: The substr() is a built-in function in PHP that is used to extract a part of string.
Syntax:
substr(string_name, start_position, string_length_to_cut)
Example: For example, if the string is “Akshit loves GeeksForGeeks”. The last character of the string is “s”. There are 2 ways to reach “s”. From the beginning “s” is at the 25th position. We can find the length of the string, then display “length-1”. This means we want to display part of the string using substr() method where the starting point is “length-1”.
PHP
<?php$txt = "Akshit Loves GeeksForGeeks";echo "Last character of String is : " .substr($txt, strlen($txt)-1);?>
Output: From the end, “s” is at 1st position. We can display string from (-1)
Last character of String is : s
From end: “s” is at 1st position
We can display string from “-1”
PHP
<?php$txt = "Akshit Loves GeeksForGeeks";echo "Last character of String is: ".substr($txt, -1);?>
Last character of String is: s
NOTE: If you’re using multibyte character encodings like UTF-8, use mb_substr() instead of substr .
PHP-function
PHP-Questions
PHP-string
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 32651,
"s": 32623,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 32781,
"s": 32651,
"text": "In this article, we will find the last character of a string in PHP. The last character can be found using the following methods."
},
{
"code": null,
"e": 32802,
"s": 32781,
"text": "Using array() method"
},
{
"code": null,
"e": 32824,
"s": 32802,
"text": "Using substr() method"
},
{
"code": null,
"e": 33122,
"s": 32824,
"text": "Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is “Akshit” Its length is 6, in zero-indexing, the value of (length-1) is 5 which is the character “t” The length can be found using the PHP strlen() method."
},
{
"code": null,
"e": 33359,
"s": 33122,
"text": "The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters."
},
{
"code": null,
"e": 33367,
"s": 33359,
"text": "Syntax:"
},
{
"code": null,
"e": 33383,
"s": 33367,
"text": "strlen($string)"
},
{
"code": null,
"e": 33392,
"s": 33383,
"text": "Example:"
},
{
"code": null,
"e": 33396,
"s": 33392,
"text": "PHP"
},
{
"code": "<?php $txt = \"Geeksforgeeks\"; echo \"Last Character of string is : \" .$txt[strlen($txt)-1];?>",
"e": 33492,
"s": 33396,
"text": null
},
{
"code": null,
"e": 33500,
"s": 33492,
"text": "Output:"
},
{
"code": null,
"e": 33532,
"s": 33500,
"text": "Last Character of string is : s"
},
{
"code": null,
"e": 33640,
"s": 33532,
"text": "Using substr() Method: The substr() is a built-in function in PHP that is used to extract a part of string."
},
{
"code": null,
"e": 33648,
"s": 33640,
"text": "Syntax:"
},
{
"code": null,
"e": 33706,
"s": 33648,
"text": "substr(string_name, start_position, string_length_to_cut)"
},
{
"code": null,
"e": 34069,
"s": 33706,
"text": "Example: For example, if the string is “Akshit loves GeeksForGeeks”. The last character of the string is “s”. There are 2 ways to reach “s”. From the beginning “s” is at the 25th position. We can find the length of the string, then display “length-1”. This means we want to display part of the string using substr() method where the starting point is “length-1”."
},
{
"code": null,
"e": 34073,
"s": 34069,
"text": "PHP"
},
{
"code": "<?php$txt = \"Akshit Loves GeeksForGeeks\";echo \"Last character of String is : \" .substr($txt, strlen($txt)-1);?>",
"e": 34186,
"s": 34073,
"text": null
},
{
"code": null,
"e": 34264,
"s": 34186,
"text": "Output: From the end, “s” is at 1st position. We can display string from (-1)"
},
{
"code": null,
"e": 34296,
"s": 34264,
"text": "Last character of String is : s"
},
{
"code": null,
"e": 34329,
"s": 34296,
"text": "From end: “s” is at 1st position"
},
{
"code": null,
"e": 34361,
"s": 34329,
"text": "We can display string from “-1”"
},
{
"code": null,
"e": 34365,
"s": 34361,
"text": "PHP"
},
{
"code": "<?php$txt = \"Akshit Loves GeeksForGeeks\";echo \"Last character of String is: \".substr($txt, -1);?>",
"e": 34463,
"s": 34365,
"text": null
},
{
"code": null,
"e": 34494,
"s": 34463,
"text": "Last character of String is: s"
},
{
"code": null,
"e": 34594,
"s": 34494,
"text": "NOTE: If you’re using multibyte character encodings like UTF-8, use mb_substr() instead of substr ."
},
{
"code": null,
"e": 34607,
"s": 34594,
"text": "PHP-function"
},
{
"code": null,
"e": 34621,
"s": 34607,
"text": "PHP-Questions"
},
{
"code": null,
"e": 34632,
"s": 34621,
"text": "PHP-string"
},
{
"code": null,
"e": 34639,
"s": 34632,
"text": "Picked"
},
{
"code": null,
"e": 34643,
"s": 34639,
"text": "PHP"
},
{
"code": null,
"e": 34660,
"s": 34643,
"text": "Web Technologies"
},
{
"code": null,
"e": 34664,
"s": 34660,
"text": "PHP"
},
{
"code": null,
"e": 34762,
"s": 34664,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34807,
"s": 34762,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 34857,
"s": 34807,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 34897,
"s": 34857,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 34921,
"s": 34897,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 34965,
"s": 34921,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 35005,
"s": 34965,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35038,
"s": 35005,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35083,
"s": 35038,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35126,
"s": 35083,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Program to add two integers of given base - GeeksforGeeks | 25 Nov, 2021
Given three integers X, Y and B, where X and Y are Base-B integers. The task is to find the sum of integers X and Y.
Examples:
Input: X = 123, Y = 234, B = 6
Output: 401
Explanation:
Sum of two integers in base 6 -
1 1
1 2 3
+ 2 3 4
-------------
4 0 1
Input: X = 546, Y = 248 B = 9
Output: 805
Explanation:
Sum of two integers in base 9 -
1 1
5 4 6
+ 2 4 8
-------------
8 0 5
Approach: The idea is to use the fact that whenever two digits of the numbers are added, then the place value will be the modulo of the sum of digits by the base whereas carry will be the integer division of the sum of digits by base. i.e.
Let two digits of the number be D1 and D2 -
Place Value = (D1 + D2) % B
Carry = (D1 + D2) / B
Similarly, Add every digit from the last to get the desired result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// sum of two integers of base B #include <bits/stdc++.h> using namespace std; // Function to find the sum of// two integers of base Bstring sumBaseB(string a, string b, int base){ int len_a, len_b; len_a = a.size(); len_b = b.size(); string sum, s; s = ""; sum = ""; int diff; diff = abs(len_a - len_b); // Padding 0 in front of the // number to make both numbers equal for (int i = 1; i <= diff; i++) s += "0"; // Condition to check if the strings // have lengths mis-match if (len_a < len_b) a = s + a; else b = s + b; int curr, carry = 0; // Loop to find the find the sum // of two integers of base B for (int i = max(len_a, len_b) - 1; i > -1; i--) { // Current Place value for // the resultant sum curr = carry + (a[i] - '0') + (b[i] - '0'); // Update carry carry = curr / base; // Find current digit curr = curr % base; // Update sum result sum = (char)(curr + '0') + sum; } if (carry > 0) sum = (char)(carry + '0') + sum; return sum;} // Driver Codeint main(){ string a, b, sum; int base; a = "123"; b = "234"; base = 6; // Function Call sum = sumBaseB(a, b, base); cout << sum << endl; return 0;}
// Java implementation to find the// sum of two integers of base Bclass GFG { // Function to find the sum of // two integers of base B static String sumBaseB(String a, String b, int base) { int len_a, len_b; len_a = a.length(); len_b = b.length(); String sum, s; s = ""; sum = ""; int diff; diff = Math.abs(len_a - len_b); // Padding 0 in front of the // number to make both numbers equal for (int i = 1; i <= diff; i++) s += "0"; // Condition to check if the strings // have lengths mis-match if (len_a < len_b) a = s + a; else b = s + b; int curr, carry = 0; // Loop to find the find the sum // of two integers of base B for (int i = Math.max(len_a, len_b) - 1; i > -1; i--) { // Current Place value for // the resultant sum curr = carry + (a.charAt(i) - '0') + (b.charAt(i) - '0'); // Update carry carry = curr / base; // Find current digit curr = curr % base; // Update sum result sum = (char)(curr + '0') + sum; } if (carry > 0) sum = (char)(carry + '0') + sum; return sum; } // Driver Code public static void main (String[] args) { String a, b, sum; int base; a = "123"; b = "234"; base = 6; // Function Call sum = sumBaseB(a, b, base); System.out.println(sum); }} // This code is contributed by AnkitRai01
# Python 3 implementation to find the# sum of two integers of base B # Function to find the sum of# two integers of base Bdef sumBaseB(a,b,base): len_a = len(a) len_b = len(b) s = ""; sum = ""; diff = abs(len_a - len_b); # Padding 0 in front of the # number to make both numbers equal for i in range(1,diff+1): s += "0" # Condition to check if the strings # have lengths mis-match if (len_a < len_b): a = s + a else: b = s + b; carry = 0; # Loop to find the find the sum # of two integers of base B for i in range(max(len_a, len_b) - 1,-1,-1): # Current Place value for # the resultant sum curr = carry + (ord(a[i]) -ord('0')) +( ord(b[i]) - ord('0')); # Update carry carry = curr // base # Find current digit curr = curr % base; # Update sum result sum = chr(curr + ord('0')) + sum if (carry > 0): sum = chr(carry + ord('0')) + sum; return sum # Driver Code a = "123"b = "234"base = 6 # Function Callsum = sumBaseB(a, b, base);print(sum) # This code is contributed by atul_kumar_shrivastava
// C# implementation to find the// sum of two integers of base Busing System; class GFG { // Function to find the sum of // two integers of base B static string sumBaseB(string a, string b, int base_var) { int len_a, len_b; len_a = a.Length; len_b = b.Length; string sum, s; s = ""; sum = ""; int diff; diff = Math.Abs(len_a - len_b); // Padding 0 in front of the // number to make both numbers equal for (int i = 1; i <= diff; i++) s += "0"; // Condition to check if the strings // have lengths mis-match if (len_a < len_b) a = s + a; else b = s + b; int curr, carry = 0; // Loop to find the find the sum // of two integers of base B for (int i = Math.Max(len_a, len_b) - 1; i > -1; i--) { // Current Place value for // the resultant sum curr = carry + (a[i] - '0') + (b[i] - '0'); // Update carry carry = curr / base_var; // Find current digit curr = curr % base_var; // Update sum result sum = (char)(curr + '0') + sum; } if (carry > 0) sum = (char)(carry + '0') + sum; return sum; } // Driver Code public static void Main (string[] args) { string a, b, sum; int base_var; a = "123"; b = "234"; base_var = 6; // Function Call sum = sumBaseB(a, b, base_var); Console.WriteLine(sum); }} // This code is contributed by AnkitRai01
<script> // Javascript implementation to find the// sum of two integers of base B // Function to find the sum of// two integers of base Bfunction sumBaseB(a, b, base_var){ let len_a, len_b; len_a = a.length; len_b = b.length; let sum, s; s = ""; sum = ""; let diff; diff = Math.abs(len_a - len_b); // Padding 0 in front of the // number to make both numbers equal for(let i = 1; i <= diff; i++) s += "0"; // Condition to check if the strings // have lengths mis-match if (len_a < len_b) a = s + a; else b = s + b; let curr, carry = 0; // Loop to find the find the sum // of two integers of base B for(let i = Math.max(len_a, len_b) - 1; i > -1; i--) { // Current Place value for // the resultant sum curr = carry + (a[i].charCodeAt() - '0'.charCodeAt()) + (b[i].charCodeAt() - '0'.charCodeAt()); // Update carry carry = parseInt(curr / base_var, 10); // Find current digit curr = curr % base_var; // Update sum result sum = String.fromCharCode( curr + '0'.charCodeAt()) + sum; } if (carry > 0) sum = String.fromCharCode( carry + '0'.charCodeAt()) + sum; return sum;} // Driver codelet a, b, sum;let base_var;a = "123";b = "234";base_var = 6; // Function Callsum = sumBaseB(a, b, base_var);document.write(sum + "</br>"); // This code is contributed by divyesh072019 </script>
401
Time Complexity: O(len_a – len_b)
Auxiliary Space: O(1)
Atul_kumar_Shrivastava
ankthon
divyesh072019
souravmahato348
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair | [
{
"code": null,
"e": 25963,
"s": 25935,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 26080,
"s": 25963,
"text": "Given three integers X, Y and B, where X and Y are Base-B integers. The task is to find the sum of integers X and Y."
},
{
"code": null,
"e": 26091,
"s": 26080,
"text": "Examples: "
},
{
"code": null,
"e": 26387,
"s": 26091,
"text": "Input: X = 123, Y = 234, B = 6\nOutput: 401\nExplanation:\nSum of two integers in base 6 - \n 1 1 \n 1 2 3\n+ 2 3 4\n-------------\n 4 0 1\n\nInput: X = 546, Y = 248 B = 9\nOutput: 805\nExplanation:\nSum of two integers in base 9 - \n 1 1\n 5 4 6\n+ 2 4 8\n-------------\n 8 0 5 "
},
{
"code": null,
"e": 26629,
"s": 26387,
"text": "Approach: The idea is to use the fact that whenever two digits of the numbers are added, then the place value will be the modulo of the sum of digits by the base whereas carry will be the integer division of the sum of digits by base. i.e. "
},
{
"code": null,
"e": 26724,
"s": 26629,
"text": "Let two digits of the number be D1 and D2 -\nPlace Value = (D1 + D2) % B\n\nCarry = (D1 + D2) / B"
},
{
"code": null,
"e": 26792,
"s": 26724,
"text": "Similarly, Add every digit from the last to get the desired result."
},
{
"code": null,
"e": 26844,
"s": 26792,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26848,
"s": 26844,
"text": "C++"
},
{
"code": null,
"e": 26853,
"s": 26848,
"text": "Java"
},
{
"code": null,
"e": 26861,
"s": 26853,
"text": "Python3"
},
{
"code": null,
"e": 26864,
"s": 26861,
"text": "C#"
},
{
"code": null,
"e": 26875,
"s": 26864,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// sum of two integers of base B #include <bits/stdc++.h> using namespace std; // Function to find the sum of// two integers of base Bstring sumBaseB(string a, string b, int base){ int len_a, len_b; len_a = a.size(); len_b = b.size(); string sum, s; s = \"\"; sum = \"\"; int diff; diff = abs(len_a - len_b); // Padding 0 in front of the // number to make both numbers equal for (int i = 1; i <= diff; i++) s += \"0\"; // Condition to check if the strings // have lengths mis-match if (len_a < len_b) a = s + a; else b = s + b; int curr, carry = 0; // Loop to find the find the sum // of two integers of base B for (int i = max(len_a, len_b) - 1; i > -1; i--) { // Current Place value for // the resultant sum curr = carry + (a[i] - '0') + (b[i] - '0'); // Update carry carry = curr / base; // Find current digit curr = curr % base; // Update sum result sum = (char)(curr + '0') + sum; } if (carry > 0) sum = (char)(carry + '0') + sum; return sum;} // Driver Codeint main(){ string a, b, sum; int base; a = \"123\"; b = \"234\"; base = 6; // Function Call sum = sumBaseB(a, b, base); cout << sum << endl; return 0;}",
"e": 28287,
"s": 26875,
"text": null
},
{
"code": "// Java implementation to find the// sum of two integers of base Bclass GFG { // Function to find the sum of // two integers of base B static String sumBaseB(String a, String b, int base) { int len_a, len_b; len_a = a.length(); len_b = b.length(); String sum, s; s = \"\"; sum = \"\"; int diff; diff = Math.abs(len_a - len_b); // Padding 0 in front of the // number to make both numbers equal for (int i = 1; i <= diff; i++) s += \"0\"; // Condition to check if the strings // have lengths mis-match if (len_a < len_b) a = s + a; else b = s + b; int curr, carry = 0; // Loop to find the find the sum // of two integers of base B for (int i = Math.max(len_a, len_b) - 1; i > -1; i--) { // Current Place value for // the resultant sum curr = carry + (a.charAt(i) - '0') + (b.charAt(i) - '0'); // Update carry carry = curr / base; // Find current digit curr = curr % base; // Update sum result sum = (char)(curr + '0') + sum; } if (carry > 0) sum = (char)(carry + '0') + sum; return sum; } // Driver Code public static void main (String[] args) { String a, b, sum; int base; a = \"123\"; b = \"234\"; base = 6; // Function Call sum = sumBaseB(a, b, base); System.out.println(sum); }} // This code is contributed by AnkitRai01",
"e": 30020,
"s": 28287,
"text": null
},
{
"code": "# Python 3 implementation to find the# sum of two integers of base B # Function to find the sum of# two integers of base Bdef sumBaseB(a,b,base): len_a = len(a) len_b = len(b) s = \"\"; sum = \"\"; diff = abs(len_a - len_b); # Padding 0 in front of the # number to make both numbers equal for i in range(1,diff+1): s += \"0\" # Condition to check if the strings # have lengths mis-match if (len_a < len_b): a = s + a else: b = s + b; carry = 0; # Loop to find the find the sum # of two integers of base B for i in range(max(len_a, len_b) - 1,-1,-1): # Current Place value for # the resultant sum curr = carry + (ord(a[i]) -ord('0')) +( ord(b[i]) - ord('0')); # Update carry carry = curr // base # Find current digit curr = curr % base; # Update sum result sum = chr(curr + ord('0')) + sum if (carry > 0): sum = chr(carry + ord('0')) + sum; return sum # Driver Code a = \"123\"b = \"234\"base = 6 # Function Callsum = sumBaseB(a, b, base);print(sum) # This code is contributed by atul_kumar_shrivastava",
"e": 31214,
"s": 30020,
"text": null
},
{
"code": "// C# implementation to find the// sum of two integers of base Busing System; class GFG { // Function to find the sum of // two integers of base B static string sumBaseB(string a, string b, int base_var) { int len_a, len_b; len_a = a.Length; len_b = b.Length; string sum, s; s = \"\"; sum = \"\"; int diff; diff = Math.Abs(len_a - len_b); // Padding 0 in front of the // number to make both numbers equal for (int i = 1; i <= diff; i++) s += \"0\"; // Condition to check if the strings // have lengths mis-match if (len_a < len_b) a = s + a; else b = s + b; int curr, carry = 0; // Loop to find the find the sum // of two integers of base B for (int i = Math.Max(len_a, len_b) - 1; i > -1; i--) { // Current Place value for // the resultant sum curr = carry + (a[i] - '0') + (b[i] - '0'); // Update carry carry = curr / base_var; // Find current digit curr = curr % base_var; // Update sum result sum = (char)(curr + '0') + sum; } if (carry > 0) sum = (char)(carry + '0') + sum; return sum; } // Driver Code public static void Main (string[] args) { string a, b, sum; int base_var; a = \"123\"; b = \"234\"; base_var = 6; // Function Call sum = sumBaseB(a, b, base_var); Console.WriteLine(sum); }} // This code is contributed by AnkitRai01",
"e": 32964,
"s": 31214,
"text": null
},
{
"code": "<script> // Javascript implementation to find the// sum of two integers of base B // Function to find the sum of// two integers of base Bfunction sumBaseB(a, b, base_var){ let len_a, len_b; len_a = a.length; len_b = b.length; let sum, s; s = \"\"; sum = \"\"; let diff; diff = Math.abs(len_a - len_b); // Padding 0 in front of the // number to make both numbers equal for(let i = 1; i <= diff; i++) s += \"0\"; // Condition to check if the strings // have lengths mis-match if (len_a < len_b) a = s + a; else b = s + b; let curr, carry = 0; // Loop to find the find the sum // of two integers of base B for(let i = Math.max(len_a, len_b) - 1; i > -1; i--) { // Current Place value for // the resultant sum curr = carry + (a[i].charCodeAt() - '0'.charCodeAt()) + (b[i].charCodeAt() - '0'.charCodeAt()); // Update carry carry = parseInt(curr / base_var, 10); // Find current digit curr = curr % base_var; // Update sum result sum = String.fromCharCode( curr + '0'.charCodeAt()) + sum; } if (carry > 0) sum = String.fromCharCode( carry + '0'.charCodeAt()) + sum; return sum;} // Driver codelet a, b, sum;let base_var;a = \"123\";b = \"234\";base_var = 6; // Function Callsum = sumBaseB(a, b, base_var);document.write(sum + \"</br>\"); // This code is contributed by divyesh072019 </script>",
"e": 34568,
"s": 32964,
"text": null
},
{
"code": null,
"e": 34572,
"s": 34568,
"text": "401"
},
{
"code": null,
"e": 34608,
"s": 34574,
"text": "Time Complexity: O(len_a – len_b)"
},
{
"code": null,
"e": 34630,
"s": 34608,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34653,
"s": 34630,
"text": "Atul_kumar_Shrivastava"
},
{
"code": null,
"e": 34661,
"s": 34653,
"text": "ankthon"
},
{
"code": null,
"e": 34675,
"s": 34661,
"text": "divyesh072019"
},
{
"code": null,
"e": 34691,
"s": 34675,
"text": "souravmahato348"
},
{
"code": null,
"e": 34704,
"s": 34691,
"text": "Mathematical"
},
{
"code": null,
"e": 34717,
"s": 34704,
"text": "Mathematical"
},
{
"code": null,
"e": 34815,
"s": 34717,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34859,
"s": 34815,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 34901,
"s": 34859,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 34932,
"s": 34901,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 35003,
"s": 34932,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 35028,
"s": 35003,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 35060,
"s": 35028,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 35093,
"s": 35060,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 35139,
"s": 35093,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 35183,
"s": 35139,
"text": "Generate all permutation of a set in Python"
}
]
|
numpy.fromiter() function – Python - GeeksforGeeks | 18 Aug, 2020
numpy.fromiter() function create a new one-dimensional array from an iterable object.
Syntax : numpy.fromiter(iterable, dtype, count = -1)
Parameters :
iterable : [iterable object] An iterable object providing data for the array.
dtype : [data-type] Data-type of the returned array.
count : [int, optional] Number of items to read.
Returns : [ndarray] The output array.
Code #1 :
Python3
# Python program explaining# numpy.fromiter() function # importing numpy as geek import numpy as geek iterable = (x * x*x for x in range(4)) gfg = geek.fromiter(iterable, int) print (gfg)
Output :
[ 0 1 8 27]
Code #2 :
Python3
# Python program explaining# numpy.fromiter() function # importing numpy as geek import numpy as geek iterable = (x * x for x in range(6)) gfg = geek.fromiter(iterable, float) print (gfg)
Output :
[ 0. 1. 4. 9. 16. 25.]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 25623,
"s": 25537,
"text": "numpy.fromiter() function create a new one-dimensional array from an iterable object."
},
{
"code": null,
"e": 25676,
"s": 25623,
"text": "Syntax : numpy.fromiter(iterable, dtype, count = -1)"
},
{
"code": null,
"e": 25689,
"s": 25676,
"text": "Parameters :"
},
{
"code": null,
"e": 25767,
"s": 25689,
"text": "iterable : [iterable object] An iterable object providing data for the array."
},
{
"code": null,
"e": 25820,
"s": 25767,
"text": "dtype : [data-type] Data-type of the returned array."
},
{
"code": null,
"e": 25869,
"s": 25820,
"text": "count : [int, optional] Number of items to read."
},
{
"code": null,
"e": 25907,
"s": 25869,
"text": "Returns : [ndarray] The output array."
},
{
"code": null,
"e": 25917,
"s": 25907,
"text": "Code #1 :"
},
{
"code": null,
"e": 25925,
"s": 25917,
"text": "Python3"
},
{
"code": "# Python program explaining# numpy.fromiter() function # importing numpy as geek import numpy as geek iterable = (x * x*x for x in range(4)) gfg = geek.fromiter(iterable, int) print (gfg)",
"e": 26129,
"s": 25925,
"text": null
},
{
"code": null,
"e": 26138,
"s": 26129,
"text": "Output :"
},
{
"code": null,
"e": 26152,
"s": 26138,
"text": "[ 0 1 8 27]"
},
{
"code": null,
"e": 26162,
"s": 26152,
"text": "Code #2 :"
},
{
"code": null,
"e": 26170,
"s": 26162,
"text": "Python3"
},
{
"code": "# Python program explaining# numpy.fromiter() function # importing numpy as geek import numpy as geek iterable = (x * x for x in range(6)) gfg = geek.fromiter(iterable, float) print (gfg)",
"e": 26374,
"s": 26170,
"text": null
},
{
"code": null,
"e": 26383,
"s": 26374,
"text": "Output :"
},
{
"code": null,
"e": 26409,
"s": 26383,
"text": "[ 0. 1. 4. 9. 16. 25.]"
},
{
"code": null,
"e": 26422,
"s": 26409,
"text": "Python-numpy"
},
{
"code": null,
"e": 26429,
"s": 26422,
"text": "Python"
},
{
"code": null,
"e": 26527,
"s": 26429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26559,
"s": 26527,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26601,
"s": 26559,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26643,
"s": 26601,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26670,
"s": 26643,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26726,
"s": 26670,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26765,
"s": 26726,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26787,
"s": 26765,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26818,
"s": 26787,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26847,
"s": 26818,
"text": "Create a directory in Python"
}
]
|
How to get relative click coordinates on the target element using JQuery? - GeeksforGeeks | 06 Sep, 2019
Here is the code to get the coordinates of the element, Here 2 methods are discussed one is calculating the relative position to its parent while another is calculating the relative position to the document.
Approach 1:
Attach the click event to the element.
Call an anonymous function when an event occurs.
Calculate the X relative to the parent element by subtracting the Offset().left property from the pageX property.
Similarly, calculate the Y relative to parent element by subtracting the Offset().top property from the pageY property.
Example 1: This example follows the approach discussed above to calculate the location’s relative position to its parent element.
<!DOCTYPE HTML><html> <head> <title> How to get relative click coordinates on the target element using JQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> h1 { border: 1px solid green; } #GFG_UP { border: 1px solid green; } button { border: 1px solid green; } </style></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var x, y; el_up.innerHTML = "Click inside any bordered element to get the"+ "click coordinates of that particular location with respect"+ "to its parent element "; $('h1').click(function(e) { // element that has been clicked. var elm = $(this); // getting the respective x = e.pageX - elm.offset().left; // coordinates of location. y = e.pageY - elm.offset().top; gfg_Run(); }); $('#GFG_UP').click(function(e) { var elm = $(this); // getting the respective x = e.pageX - elm.offset().left; // coordinates of location. y = e.pageY - elm.offset().top; gfg_Run(); }); function gfg_Run() { el_down.innerHTML = "X- " + x + "<br>Y- " + y; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Attach the click event to the element.
Call an anonymous function when event occurs.
Calculate the X relative to document by pageX property.
Similarly, calculate the Y relative to document by pageY property.
Example 2: This example follows the approach discussed above to calculate the location’s relative position to the document.
<!DOCTYPE HTML><html> <head> <title> How to get relative click coordinates on the target element using JQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> h1 { border: 1px solid green; } #GFG_UP { border: 1px solid green; } button { border: 1px solid green; } </style></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var x, y; el_up.innerHTML = "Click inside any bordered element "+ "to get the click coordinates of that particular "+ "location with respect to document"; $('h1').click(function(e) { // element that has been clicked. var elm = $(this); // getting the respective x = e.pageX; // coordinates of location. y = e.pageY; gfg_Run(); }); $('#GFG_UP').click(function(e) { // element that has been clicked. var elm = $(this); // getting the respective x = e.pageX; // coordinates of location. y = e.pageY; gfg_Run(); }); function gfg_Run() { el_down.innerHTML = "X- " + x + "<br>Y- " + y; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 26964,
"s": 26936,
"text": "\n06 Sep, 2019"
},
{
"code": null,
"e": 27172,
"s": 26964,
"text": "Here is the code to get the coordinates of the element, Here 2 methods are discussed one is calculating the relative position to its parent while another is calculating the relative position to the document."
},
{
"code": null,
"e": 27184,
"s": 27172,
"text": "Approach 1:"
},
{
"code": null,
"e": 27223,
"s": 27184,
"text": "Attach the click event to the element."
},
{
"code": null,
"e": 27272,
"s": 27223,
"text": "Call an anonymous function when an event occurs."
},
{
"code": null,
"e": 27386,
"s": 27272,
"text": "Calculate the X relative to the parent element by subtracting the Offset().left property from the pageX property."
},
{
"code": null,
"e": 27506,
"s": 27386,
"text": "Similarly, calculate the Y relative to parent element by subtracting the Offset().top property from the pageY property."
},
{
"code": null,
"e": 27636,
"s": 27506,
"text": "Example 1: This example follows the approach discussed above to calculate the location’s relative position to its parent element."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to get relative click coordinates on the target element using JQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> h1 { border: 1px solid green; } #GFG_UP { border: 1px solid green; } button { border: 1px solid green; } </style></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var x, y; el_up.innerHTML = \"Click inside any bordered element to get the\"+ \"click coordinates of that particular location with respect\"+ \"to its parent element \"; $('h1').click(function(e) { // element that has been clicked. var elm = $(this); // getting the respective x = e.pageX - elm.offset().left; // coordinates of location. y = e.pageY - elm.offset().top; gfg_Run(); }); $('#GFG_UP').click(function(e) { var elm = $(this); // getting the respective x = e.pageX - elm.offset().left; // coordinates of location. y = e.pageY - elm.offset().top; gfg_Run(); }); function gfg_Run() { el_down.innerHTML = \"X- \" + x + \"<br>Y- \" + y; } </script></body> </html>",
"e": 29435,
"s": 27636,
"text": null
},
{
"code": null,
"e": 29443,
"s": 29435,
"text": "Output:"
},
{
"code": null,
"e": 29474,
"s": 29443,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29504,
"s": 29474,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 29516,
"s": 29504,
"text": "Approach 2:"
},
{
"code": null,
"e": 29555,
"s": 29516,
"text": "Attach the click event to the element."
},
{
"code": null,
"e": 29601,
"s": 29555,
"text": "Call an anonymous function when event occurs."
},
{
"code": null,
"e": 29657,
"s": 29601,
"text": "Calculate the X relative to document by pageX property."
},
{
"code": null,
"e": 29724,
"s": 29657,
"text": "Similarly, calculate the Y relative to document by pageY property."
},
{
"code": null,
"e": 29848,
"s": 29724,
"text": "Example 2: This example follows the approach discussed above to calculate the location’s relative position to the document."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to get relative click coordinates on the target element using JQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> h1 { border: 1px solid green; } #GFG_UP { border: 1px solid green; } button { border: 1px solid green; } </style></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var x, y; el_up.innerHTML = \"Click inside any bordered element \"+ \"to get the click coordinates of that particular \"+ \"location with respect to document\"; $('h1').click(function(e) { // element that has been clicked. var elm = $(this); // getting the respective x = e.pageX; // coordinates of location. y = e.pageY; gfg_Run(); }); $('#GFG_UP').click(function(e) { // element that has been clicked. var elm = $(this); // getting the respective x = e.pageX; // coordinates of location. y = e.pageY; gfg_Run(); }); function gfg_Run() { el_down.innerHTML = \"X- \" + x + \"<br>Y- \" + y; } </script></body> </html>",
"e": 31651,
"s": 29848,
"text": null
},
{
"code": null,
"e": 31659,
"s": 31651,
"text": "Output:"
},
{
"code": null,
"e": 31690,
"s": 31659,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 31720,
"s": 31690,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 31732,
"s": 31720,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 31739,
"s": 31732,
"text": "JQuery"
},
{
"code": null,
"e": 31756,
"s": 31739,
"text": "Web Technologies"
},
{
"code": null,
"e": 31783,
"s": 31756,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31881,
"s": 31783,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31910,
"s": 31881,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31966,
"s": 31910,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 32020,
"s": 31966,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 32054,
"s": 32020,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 32109,
"s": 32054,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 32149,
"s": 32109,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32182,
"s": 32149,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32227,
"s": 32182,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32270,
"s": 32227,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Program to convert Primitive Array to Stream in Java - GeeksforGeeks | 11 Dec, 2018
An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap segment.
A Primitive array is an array which is defined with the help of the primitive wrapper classes, instead of objects.Example: Integer a = new Integer(4);
When a Primitive Array is converted into a Stream, primitive Streams will be obtained like IntStream, DoubleStream and LongStream.
Examples:
Input: Double Array: [1.2, 2.4, 3.6, 4.8, 5.0]Output: DoubleStream: [1.2, 2.4, 3.6, 4.8, 5.0]
Input: Integer Array: [1, 2, 3, 4, 5]Output: IntStream: [1, 2, 3, 4, 5]
Below are methods to convert Primitive Array to Stream in Java:
Using Arrays.stream():Algorithm:Get the Array to be converted.Convert the array into Stream using Arrays.stream() method by passing the array as the parameter.Return the formed StreamProgram:// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return Arrays.stream(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Array: [3, 2, 5, 4, 1]
Stream: [3, 2, 5, 4, 1]
Using IntStream.of(): The IntStream.of() method creates a Stream directly with the primitive values or collection passed as the parameter.Algorithm:Get the Array to be converted.Convert the array into Stream using IntStream.of() method by passing the array as the parameter.Return the formed StreamProgram:// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return IntStream.of(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Array: [3, 2, 5, 4, 1]
Stream: [3, 2, 5, 4, 1]
Using Arrays.stream():Algorithm:Get the Array to be converted.Convert the array into Stream using Arrays.stream() method by passing the array as the parameter.Return the formed StreamProgram:// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return Arrays.stream(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Array: [3, 2, 5, 4, 1]
Stream: [3, 2, 5, 4, 1]
Algorithm:
Get the Array to be converted.Convert the array into Stream using Arrays.stream() method by passing the array as the parameter.Return the formed Stream
Get the Array to be converted.
Convert the array into Stream using Arrays.stream() method by passing the array as the parameter.
Return the formed Stream
Program:
// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return Arrays.stream(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}
Array: [3, 2, 5, 4, 1]
Stream: [3, 2, 5, 4, 1]
Using IntStream.of(): The IntStream.of() method creates a Stream directly with the primitive values or collection passed as the parameter.Algorithm:Get the Array to be converted.Convert the array into Stream using IntStream.of() method by passing the array as the parameter.Return the formed StreamProgram:// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return IntStream.of(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Array: [3, 2, 5, 4, 1]
Stream: [3, 2, 5, 4, 1]
Algorithm:
Get the Array to be converted.Convert the array into Stream using IntStream.of() method by passing the array as the parameter.Return the formed Stream
Get the Array to be converted.
Convert the array into Stream using IntStream.of() method by passing the array as the parameter.
Return the formed Stream
Program:
// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return IntStream.of(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}
Array: [3, 2, 5, 4, 1]
Stream: [3, 2, 5, 4, 1]
Java - util package
Java-Array-Programs
Java-Arrays
java-intstream
java-stream
Java-Stream-programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 25681,
"s": 25653,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 26052,
"s": 25681,
"text": "An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap segment."
},
{
"code": null,
"e": 26203,
"s": 26052,
"text": "A Primitive array is an array which is defined with the help of the primitive wrapper classes, instead of objects.Example: Integer a = new Integer(4);"
},
{
"code": null,
"e": 26334,
"s": 26203,
"text": "When a Primitive Array is converted into a Stream, primitive Streams will be obtained like IntStream, DoubleStream and LongStream."
},
{
"code": null,
"e": 26344,
"s": 26334,
"text": "Examples:"
},
{
"code": null,
"e": 26438,
"s": 26344,
"text": "Input: Double Array: [1.2, 2.4, 3.6, 4.8, 5.0]Output: DoubleStream: [1.2, 2.4, 3.6, 4.8, 5.0]"
},
{
"code": null,
"e": 26510,
"s": 26438,
"text": "Input: Integer Array: [1, 2, 3, 4, 5]Output: IntStream: [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 26574,
"s": 26510,
"text": "Below are methods to convert Primitive Array to Stream in Java:"
},
{
"code": null,
"e": 28762,
"s": 26574,
"text": "Using Arrays.stream():Algorithm:Get the Array to be converted.Convert the array into Stream using Arrays.stream() method by passing the array as the parameter.Return the formed StreamProgram:// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return Arrays.stream(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Array: [3, 2, 5, 4, 1]\nStream: [3, 2, 5, 4, 1]\nUsing IntStream.of(): The IntStream.of() method creates a Stream directly with the primitive values or collection passed as the parameter.Algorithm:Get the Array to be converted.Convert the array into Stream using IntStream.of() method by passing the array as the parameter.Return the formed StreamProgram:// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return IntStream.of(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Array: [3, 2, 5, 4, 1]\nStream: [3, 2, 5, 4, 1]\n"
},
{
"code": null,
"e": 29798,
"s": 28762,
"text": "Using Arrays.stream():Algorithm:Get the Array to be converted.Convert the array into Stream using Arrays.stream() method by passing the array as the parameter.Return the formed StreamProgram:// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return Arrays.stream(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Array: [3, 2, 5, 4, 1]\nStream: [3, 2, 5, 4, 1]\n"
},
{
"code": null,
"e": 29809,
"s": 29798,
"text": "Algorithm:"
},
{
"code": null,
"e": 29961,
"s": 29809,
"text": "Get the Array to be converted.Convert the array into Stream using Arrays.stream() method by passing the array as the parameter.Return the formed Stream"
},
{
"code": null,
"e": 29992,
"s": 29961,
"text": "Get the Array to be converted."
},
{
"code": null,
"e": 30090,
"s": 29992,
"text": "Convert the array into Stream using Arrays.stream() method by passing the array as the parameter."
},
{
"code": null,
"e": 30115,
"s": 30090,
"text": "Return the formed Stream"
},
{
"code": null,
"e": 30124,
"s": 30115,
"text": "Program:"
},
{
"code": "// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return Arrays.stream(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}",
"e": 30915,
"s": 30124,
"text": null
},
{
"code": null,
"e": 30963,
"s": 30915,
"text": "Array: [3, 2, 5, 4, 1]\nStream: [3, 2, 5, 4, 1]\n"
},
{
"code": null,
"e": 32116,
"s": 30963,
"text": "Using IntStream.of(): The IntStream.of() method creates a Stream directly with the primitive values or collection passed as the parameter.Algorithm:Get the Array to be converted.Convert the array into Stream using IntStream.of() method by passing the array as the parameter.Return the formed StreamProgram:// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return IntStream.of(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Array: [3, 2, 5, 4, 1]\nStream: [3, 2, 5, 4, 1]\n"
},
{
"code": null,
"e": 32127,
"s": 32116,
"text": "Algorithm:"
},
{
"code": null,
"e": 32278,
"s": 32127,
"text": "Get the Array to be converted.Convert the array into Stream using IntStream.of() method by passing the array as the parameter.Return the formed Stream"
},
{
"code": null,
"e": 32309,
"s": 32278,
"text": "Get the Array to be converted."
},
{
"code": null,
"e": 32406,
"s": 32309,
"text": "Convert the array into Stream using IntStream.of() method by passing the array as the parameter."
},
{
"code": null,
"e": 32431,
"s": 32406,
"text": "Return the formed Stream"
},
{
"code": null,
"e": 32440,
"s": 32431,
"text": "Program:"
},
{
"code": "// Java Program to convert// Array to Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert // an Array to Stream public static IntStream convertArrayToStream(int array[]) { // Return the converted Stream return IntStream.of(array); } public static void main(String args[]) { // Create an Array int[] array = new int[] { 3, 2, 5, 4, 1 }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to Stream IntStream stream = convertArrayToStream(array); // Print the Stream System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}",
"e": 33233,
"s": 32440,
"text": null
},
{
"code": null,
"e": 33281,
"s": 33233,
"text": "Array: [3, 2, 5, 4, 1]\nStream: [3, 2, 5, 4, 1]\n"
},
{
"code": null,
"e": 33301,
"s": 33281,
"text": "Java - util package"
},
{
"code": null,
"e": 33321,
"s": 33301,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 33333,
"s": 33321,
"text": "Java-Arrays"
},
{
"code": null,
"e": 33348,
"s": 33333,
"text": "java-intstream"
},
{
"code": null,
"e": 33360,
"s": 33348,
"text": "java-stream"
},
{
"code": null,
"e": 33381,
"s": 33360,
"text": "Java-Stream-programs"
},
{
"code": null,
"e": 33386,
"s": 33381,
"text": "Java"
},
{
"code": null,
"e": 33400,
"s": 33386,
"text": "Java Programs"
},
{
"code": null,
"e": 33405,
"s": 33400,
"text": "Java"
},
{
"code": null,
"e": 33503,
"s": 33405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33554,
"s": 33503,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 33584,
"s": 33554,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 33603,
"s": 33584,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 33618,
"s": 33603,
"text": "Stream In Java"
},
{
"code": null,
"e": 33649,
"s": 33618,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 33677,
"s": 33649,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 33721,
"s": 33677,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 33747,
"s": 33721,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 33781,
"s": 33747,
"text": "Convert Double to Integer in Java"
}
]
|
this pointer in C++ - GeeksQuiz | 10 Jul, 2018
/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
#include
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
// Chained function calls. All calls modify the same object
// as the same object is returned by reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Best Time to Buy and Sell Stock
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial | [
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n10 Jul, 2018"
},
{
"code": null,
"e": 29153,
"s": 28855,
"text": "/* local variable is same as a member's name */\nclass Test\n{\nprivate:\n int x;\npublic:\n void setX (int x)\n {\n // The 'this' pointer is used to retrieve the object's x\n // hidden by the local variable 'x'\n this->x = x;\n }\n void print() { cout << \"x = \" << x << endl; }\n};"
},
{
"code": null,
"e": 29656,
"s": 29153,
"text": "#include\nusing namespace std;\n \nclass Test\n{\nprivate:\n int x;\n int y;\npublic:\n Test(int x = 0, int y = 0) { this->x = x; this->y = y; }\n Test &setX(int a) { x = a; return *this; }\n Test &setY(int b) { y = b; return *this; }\n void print() { cout << \"x = \" << x << \" y = \" << y << endl; }\n};\n \nint main()\n{\n Test obj1(5, 5);\n \n // Chained function calls. All calls modify the same object\n // as the same object is returned by reference\n obj1.setX(10).setY(20);\n \n obj1.print();\n return 0;\n}\n"
},
{
"code": null,
"e": 29754,
"s": 29656,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29786,
"s": 29754,
"text": "Best Time to Buy and Sell Stock"
},
{
"code": null,
"e": 29839,
"s": 29786,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29901,
"s": 29839,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29942,
"s": 29901,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29977,
"s": 29942,
"text": "Insert Image in a Jupyter Notebook"
},
{
"code": null,
"e": 30020,
"s": 29977,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 30056,
"s": 30020,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 30094,
"s": 30056,
"text": "How to Compare Two Columns in Pandas?"
},
{
"code": null,
"e": 30132,
"s": 30094,
"text": "Python Data Structures and Algorithms"
}
]
|
File Handling in Python - GeeksforGeeks | 24 Dec, 2021
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but like other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.
Before performing any operation on the file like read or write, first we have to open that file. For this, we should use Python’s inbuilt function open()
But at the time of opening, we have to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
r: open an existing file for a read operation.w: open an existing file for a write operation. If the file already contains some data then it will be overridden.a: open an existing file for append operation. It won’t override existing data. r+: To read and write data into the file. The previous data in the file will not be deleted.w+: To write and read data. It will override existing data.a+: To append and read data from the file. It won’t override existing data.
r: open an existing file for a read operation.
w: open an existing file for a write operation. If the file already contains some data then it will be overridden.
a: open an existing file for append operation. It won’t override existing data.
r+: To read and write data into the file. The previous data in the file will not be deleted.
w+: To write and read data. It will override existing data.
a+: To append and read data from the file. It won’t override existing data.
Take a look at the below example:
Python3
# a file named "geek", will be opened with the reading mode.file = open('geek.txt', 'r')# This will print every line one by one in the filefor each in file: print (each)
The open command will open the file in the read mode and the for loop will print each line present in the file.
There is more than one way to read a file in Python. If you need to extract a string that contains all characters in the file then we can use file.read(). The full code would work like this:
Python3
# Python code to illustrate read() modefile = open("file.txt", "r")print (file.read())
Another way to read a file is to call a certain number of characters like in the following code the interpreter will read the first five characters of stored data and return it as a string:
Python3
# Python code to illustrate read() mode character wisefile = open("file.txt", "r")print (file.read(5))
Let’s see how to create a file and how write mode works: To manipulate the file, write the following in your Python environment:
Python3
# Python code to create a filefile = open('geek.txt','w')file.write("This is the write command")file.write("It allows us to write in a particular file")file.close()
The close() command terminates all the resources in use and frees the system of this particular program.
Let’s see how the append mode works:
Python3
# Python code to illustrate append() modefile = open('geek.txt','a')file.write("This will add this line")file.close()
There are also various other commands in file handling that is used to handle various tasks like:
rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are working with code. That explains why it’s good practice to use them with a statement where applicable. This is helpful because using this method any files opened will be closed automatically after one is done, so auto-cleanup. Example:
Python3
# Python code to illustrate with()with open("file.txt") as file: data = file.read()# do something with data
We can also use the write function along with the with() function:
Python3
# Python code to illustrate with() alongwith write()with open("file.txt", "w") as f: f.write("Hello World!!!")
We can also split lines using file handling in Python. This splits the variable when space is encountered. You can also split using any characters as we wish. Here is the code:
Python3
# Python code to illustrate split() functionwith open("file.text", "r") as file: data = file.readlines() for line in data: word = line.split() print (word)
There are also various other functions that help to manipulate the files and their contents. One can explore various other functions in Python Docs.
This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Shivaansh Agarwal
samadhan2601
icecrac34r
python-io
Python
python-io
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
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() | [
{
"code": null,
"e": 42713,
"s": 42685,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 43489,
"s": 42713,
"text": "Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but like other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files. "
},
{
"code": null,
"e": 43643,
"s": 43489,
"text": "Before performing any operation on the file like read or write, first we have to open that file. For this, we should use Python’s inbuilt function open()"
},
{
"code": null,
"e": 43750,
"s": 43643,
"text": "But at the time of opening, we have to specify the mode, which represents the purpose of the opening file."
},
{
"code": null,
"e": 43775,
"s": 43750,
"text": "f = open(filename, mode)"
},
{
"code": null,
"e": 43814,
"s": 43775,
"text": "Where the following mode is supported:"
},
{
"code": null,
"e": 44283,
"s": 43814,
"text": "r: open an existing file for a read operation.w: open an existing file for a write operation. If the file already contains some data then it will be overridden.a: open an existing file for append operation. It won’t override existing data. r+: To read and write data into the file. The previous data in the file will not be deleted.w+: To write and read data. It will override existing data.a+: To append and read data from the file. It won’t override existing data."
},
{
"code": null,
"e": 44330,
"s": 44283,
"text": "r: open an existing file for a read operation."
},
{
"code": null,
"e": 44445,
"s": 44330,
"text": "w: open an existing file for a write operation. If the file already contains some data then it will be overridden."
},
{
"code": null,
"e": 44526,
"s": 44445,
"text": "a: open an existing file for append operation. It won’t override existing data."
},
{
"code": null,
"e": 44621,
"s": 44526,
"text": " r+: To read and write data into the file. The previous data in the file will not be deleted."
},
{
"code": null,
"e": 44681,
"s": 44621,
"text": "w+: To write and read data. It will override existing data."
},
{
"code": null,
"e": 44757,
"s": 44681,
"text": "a+: To append and read data from the file. It won’t override existing data."
},
{
"code": null,
"e": 44791,
"s": 44757,
"text": "Take a look at the below example:"
},
{
"code": null,
"e": 44799,
"s": 44791,
"text": "Python3"
},
{
"code": "# a file named \"geek\", will be opened with the reading mode.file = open('geek.txt', 'r')# This will print every line one by one in the filefor each in file: print (each)",
"e": 44972,
"s": 44799,
"text": null
},
{
"code": null,
"e": 45086,
"s": 44972,
"text": "The open command will open the file in the read mode and the for loop will print each line present in the file. "
},
{
"code": null,
"e": 45278,
"s": 45086,
"text": "There is more than one way to read a file in Python. If you need to extract a string that contains all characters in the file then we can use file.read(). The full code would work like this: "
},
{
"code": null,
"e": 45286,
"s": 45278,
"text": "Python3"
},
{
"code": "# Python code to illustrate read() modefile = open(\"file.txt\", \"r\")print (file.read())",
"e": 45373,
"s": 45286,
"text": null
},
{
"code": null,
"e": 45564,
"s": 45373,
"text": "Another way to read a file is to call a certain number of characters like in the following code the interpreter will read the first five characters of stored data and return it as a string: "
},
{
"code": null,
"e": 45572,
"s": 45564,
"text": "Python3"
},
{
"code": "# Python code to illustrate read() mode character wisefile = open(\"file.txt\", \"r\")print (file.read(5))",
"e": 45675,
"s": 45572,
"text": null
},
{
"code": null,
"e": 45805,
"s": 45675,
"text": "Let’s see how to create a file and how write mode works: To manipulate the file, write the following in your Python environment: "
},
{
"code": null,
"e": 45813,
"s": 45805,
"text": "Python3"
},
{
"code": "# Python code to create a filefile = open('geek.txt','w')file.write(\"This is the write command\")file.write(\"It allows us to write in a particular file\")file.close()",
"e": 45978,
"s": 45813,
"text": null
},
{
"code": null,
"e": 46085,
"s": 45978,
"text": "The close() command terminates all the resources in use and frees the system of this particular program. "
},
{
"code": null,
"e": 46123,
"s": 46085,
"text": "Let’s see how the append mode works: "
},
{
"code": null,
"e": 46131,
"s": 46123,
"text": "Python3"
},
{
"code": "# Python code to illustrate append() modefile = open('geek.txt','a')file.write(\"This will add this line\")file.close()",
"e": 46249,
"s": 46131,
"text": null
},
{
"code": null,
"e": 46348,
"s": 46249,
"text": "There are also various other commands in file handling that is used to handle various tasks like: "
},
{
"code": null,
"e": 46523,
"s": 46348,
"text": "rstrip(): This function strips each line of a file off spaces from the right-hand side.\nlstrip(): This function strips each line of a file off spaces from the left-hand side."
},
{
"code": null,
"e": 46842,
"s": 46523,
"text": "It is designed to provide much cleaner syntax and exception handling when you are working with code. That explains why it’s good practice to use them with a statement where applicable. This is helpful because using this method any files opened will be closed automatically after one is done, so auto-cleanup. Example: "
},
{
"code": null,
"e": 46850,
"s": 46842,
"text": "Python3"
},
{
"code": "# Python code to illustrate with()with open(\"file.txt\") as file: data = file.read()# do something with data",
"e": 46962,
"s": 46850,
"text": null
},
{
"code": null,
"e": 47031,
"s": 46962,
"text": "We can also use the write function along with the with() function: "
},
{
"code": null,
"e": 47039,
"s": 47031,
"text": "Python3"
},
{
"code": "# Python code to illustrate with() alongwith write()with open(\"file.txt\", \"w\") as f: f.write(\"Hello World!!!\")",
"e": 47153,
"s": 47039,
"text": null
},
{
"code": null,
"e": 47330,
"s": 47153,
"text": "We can also split lines using file handling in Python. This splits the variable when space is encountered. You can also split using any characters as we wish. Here is the code:"
},
{
"code": null,
"e": 47338,
"s": 47330,
"text": "Python3"
},
{
"code": "# Python code to illustrate split() functionwith open(\"file.text\", \"r\") as file: data = file.readlines() for line in data: word = line.split() print (word)",
"e": 47514,
"s": 47338,
"text": null
},
{
"code": null,
"e": 47664,
"s": 47514,
"text": "There are also various other functions that help to manipulate the files and their contents. One can explore various other functions in Python Docs. "
},
{
"code": null,
"e": 48085,
"s": 47664,
"text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 48103,
"s": 48085,
"text": "Shivaansh Agarwal"
},
{
"code": null,
"e": 48116,
"s": 48103,
"text": "samadhan2601"
},
{
"code": null,
"e": 48127,
"s": 48116,
"text": "icecrac34r"
},
{
"code": null,
"e": 48137,
"s": 48127,
"text": "python-io"
},
{
"code": null,
"e": 48144,
"s": 48137,
"text": "Python"
},
{
"code": null,
"e": 48154,
"s": 48144,
"text": "python-io"
},
{
"code": null,
"e": 48252,
"s": 48154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48280,
"s": 48252,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 48330,
"s": 48280,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 48352,
"s": 48330,
"text": "Python map() function"
},
{
"code": null,
"e": 48396,
"s": 48352,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 48431,
"s": 48396,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 48463,
"s": 48431,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 48485,
"s": 48463,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 48527,
"s": 48485,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 48557,
"s": 48527,
"text": "Iterate over a list in Python"
}
]
|
How to Install Kali Docker Image to the Linux ? - GeeksforGeeks | 29 Jun, 2021
In the cybersecurity sector, Kali is a prominent security distribution. Penetration testers, in particular, adore it. Kali has a number of security exploitation tools that may be used to test various systems, such as servers, networks, application servers, databases, VoIP, and so on. Kali is available in a variety of formats, including a virtual machine, an ISO file, a USB image, and a container.
To install docker, run the following command:
$ sudo apt-get install docker.io
Installing Docker
Docker is a daemon service that runs in the background. This service must be started before we can use Docker. There are a variety of service and daemon management tools available, but they all support sytemctl.
$ sudo systemctl start docker
Starting Docker
The status option can be used to examine the status of a Docker service.
$ sudo systemctl status docker
Checking docker service status
We can now use the docker command to locate the Kali Docker image. To identify accessible Kali container images in the Docker Hub, we’ll use the search subcommand with the kali keyword.
$ sudo docker search kali
Searching kali image
Now choose the most popular one, which is offered by kali developers.
We’ll use the pull subcommand to get a Kali container image from the Docker Repository, as seen below. Container pictures are downloaded in many parts and employ a layered file structure. This has the advantage of allowing you to make several containers from a single image because just the altered parts of the image will be copied, while the rest of the image will be used by numerous containers without issue.
$ sudo docker pull kalilinux/kali-rolling
Installing container image
Now choose the most popular one, which is offered by kali developers.
The run subcommand will be used to start the container. However, there are a few options that we should present. How can we connect to Kali after the container has started? We’ll use the -t and -i options to indicate that we’d like to connect to the terminal interactively.
$ sudo docker run -t -i kalilinux/kali-rolling
Running the container
We should update the Kali container’s package metadata because it contains outdated utilities. Another reason is that apt does not have up-to-date and complete package information. The following command will be used to update package information.
$ apt-get update
Updating packages
The Kali container comes with relatively few tools by default. Using apt package management, we should install the essential tools. In the following example, we will install nmap.
$ apt install nmap -y
Installing nmap
Dockers are the most efficient way to distribute and deploy your packages. The Kali Linux docker image is quite useful; it doesn’t take up a lot of disc space, and it’s now very simple to test this amazing distro on any docker-enabled operating system.
Kali-Linux
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 26051,
"s": 25651,
"text": "In the cybersecurity sector, Kali is a prominent security distribution. Penetration testers, in particular, adore it. Kali has a number of security exploitation tools that may be used to test various systems, such as servers, networks, application servers, databases, VoIP, and so on. Kali is available in a variety of formats, including a virtual machine, an ISO file, a USB image, and a container."
},
{
"code": null,
"e": 26098,
"s": 26051,
"text": "To install docker, run the following command:"
},
{
"code": null,
"e": 26131,
"s": 26098,
"text": "$ sudo apt-get install docker.io"
},
{
"code": null,
"e": 26149,
"s": 26131,
"text": "Installing Docker"
},
{
"code": null,
"e": 26361,
"s": 26149,
"text": "Docker is a daemon service that runs in the background. This service must be started before we can use Docker. There are a variety of service and daemon management tools available, but they all support sytemctl."
},
{
"code": null,
"e": 26391,
"s": 26361,
"text": "$ sudo systemctl start docker"
},
{
"code": null,
"e": 26407,
"s": 26391,
"text": "Starting Docker"
},
{
"code": null,
"e": 26480,
"s": 26407,
"text": "The status option can be used to examine the status of a Docker service."
},
{
"code": null,
"e": 26511,
"s": 26480,
"text": "$ sudo systemctl status docker"
},
{
"code": null,
"e": 26542,
"s": 26511,
"text": "Checking docker service status"
},
{
"code": null,
"e": 26728,
"s": 26542,
"text": "We can now use the docker command to locate the Kali Docker image. To identify accessible Kali container images in the Docker Hub, we’ll use the search subcommand with the kali keyword."
},
{
"code": null,
"e": 26754,
"s": 26728,
"text": "$ sudo docker search kali"
},
{
"code": null,
"e": 26775,
"s": 26754,
"text": "Searching kali image"
},
{
"code": null,
"e": 26845,
"s": 26775,
"text": "Now choose the most popular one, which is offered by kali developers."
},
{
"code": null,
"e": 27258,
"s": 26845,
"text": "We’ll use the pull subcommand to get a Kali container image from the Docker Repository, as seen below. Container pictures are downloaded in many parts and employ a layered file structure. This has the advantage of allowing you to make several containers from a single image because just the altered parts of the image will be copied, while the rest of the image will be used by numerous containers without issue."
},
{
"code": null,
"e": 27300,
"s": 27258,
"text": "$ sudo docker pull kalilinux/kali-rolling"
},
{
"code": null,
"e": 27327,
"s": 27300,
"text": "Installing container image"
},
{
"code": null,
"e": 27397,
"s": 27327,
"text": "Now choose the most popular one, which is offered by kali developers."
},
{
"code": null,
"e": 27671,
"s": 27397,
"text": "The run subcommand will be used to start the container. However, there are a few options that we should present. How can we connect to Kali after the container has started? We’ll use the -t and -i options to indicate that we’d like to connect to the terminal interactively."
},
{
"code": null,
"e": 27718,
"s": 27671,
"text": "$ sudo docker run -t -i kalilinux/kali-rolling"
},
{
"code": null,
"e": 27740,
"s": 27718,
"text": "Running the container"
},
{
"code": null,
"e": 27987,
"s": 27740,
"text": "We should update the Kali container’s package metadata because it contains outdated utilities. Another reason is that apt does not have up-to-date and complete package information. The following command will be used to update package information."
},
{
"code": null,
"e": 28004,
"s": 27987,
"text": "$ apt-get update"
},
{
"code": null,
"e": 28022,
"s": 28004,
"text": "Updating packages"
},
{
"code": null,
"e": 28202,
"s": 28022,
"text": "The Kali container comes with relatively few tools by default. Using apt package management, we should install the essential tools. In the following example, we will install nmap."
},
{
"code": null,
"e": 28224,
"s": 28202,
"text": "$ apt install nmap -y"
},
{
"code": null,
"e": 28240,
"s": 28224,
"text": "Installing nmap"
},
{
"code": null,
"e": 28493,
"s": 28240,
"text": "Dockers are the most efficient way to distribute and deploy your packages. The Kali Linux docker image is quite useful; it doesn’t take up a lot of disc space, and it’s now very simple to test this amazing distro on any docker-enabled operating system."
},
{
"code": null,
"e": 28504,
"s": 28493,
"text": "Kali-Linux"
},
{
"code": null,
"e": 28511,
"s": 28504,
"text": "Picked"
},
{
"code": null,
"e": 28522,
"s": 28511,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28620,
"s": 28522,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28655,
"s": 28620,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28681,
"s": 28655,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28715,
"s": 28681,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28744,
"s": 28715,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 28781,
"s": 28744,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28818,
"s": 28781,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28860,
"s": 28818,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28886,
"s": 28860,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 28922,
"s": 28886,
"text": "uniq Command in LINUX with examples"
}
]
|
Read a file line by line in Python - GeeksforGeeks | 12 May, 2022
Prerequisites:
Access modes
Open a file
Close a file
Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file.
readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines. We can iterate over the list and strip the newline ‘\n’ character using strip() function.
Example:
Python3
# Python code to# demonstrate readlines() L = ["Geeks\n", "for\n", "Geeks\n"] # writing to filefile1 = open('myfile.txt', 'w')file1.writelines(L)file1.close() # Using readlines()file1 = open('myfile.txt', 'r')Lines = file1.readlines() count = 0# Strips the newline characterfor line in Lines: count += 1 print("Line{}: {}".format(count, line.strip()))
Output:
Line1: Geeks
Line2: for
Line3: Geeks
readline() function reads a line of the file and return it in the form of the string. It takes a parameter n, which specifies the maximum number of bytes that will be read. However, does not reads more than one line, even if n exceeds the length of the line. It will be efficient when reading a large file because instead of fetching all the data in one go, it fetches line by line. readline() returns the next line of the file which contains a newline character in the end. Also, if the end of the file is reached, it will return an empty string.
Example:
Python3
# Python program to# demonstrate readline() L = ["Geeks\n", "for\n", "Geeks\n"] # Writing to a filefile1 = open('myfile.txt', 'w')file1.writelines((L))file1.close() # Using readline()file1 = open('myfile.txt', 'r')count = 0 while True: count += 1 # Get next line from file line = file1.readline() # if line is empty # end of file is reached if not line: break print("Line{}: {}".format(count, line.strip())) file1.close()
Output:
Line1 Geeks
Line2 for
Line3 Geeks
An iterable object is returned by open() function while opening a file. This final way of reading in a file line-by-line includes iterating over a file object in a for loop. Doing this we are taking advantage of a built-in Python function that allows us to iterate over the file object implicitly using a for loop in a combination with using the iterable object. This approach takes fewer lines of code, which is always the best practice worthy of following.
Example:
Python3
# Python program to# demonstrate reading files# using for loop L = ["Geeks\n", "for\n", "Geeks\n"] # Writing to filefile1 = open('myfile.txt', 'w')file1.writelines(L)file1.close() # Opening filefile1 = open('myfile.txt', 'r')count = 0 # Using for loopprint("Using for loop")for line in file1: count += 1 print("Line{}: {}".format(count, line.strip())) # Closing filesfile1.close()
Output:
Using for loop
Line1: Geeks
Line2: for
Line3: Geeks
In the above approaches, every time the file is opened it is needed to be closed explicitly. If one forgets to close the file, it may introduce several bugs in the code, i.e. many changes in files do not go into effect until the file is properly closed. To prevent this with statement can be used. The With statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes the code cleaner. There is no need to call file.close() when using with the statement. The with the statement itself ensures proper acquisition and release of resources.
Example:
Python3
# Python program to# demonstrate with# statement L = ["Geeks\n", "for\n", "Geeks\n"] # Writing to filewith open("myfile.txt", "w") as fp: fp.writelines(L) # using readlines()count = 0print("Using readlines()") with open("myfile.txt") as fp: Lines = fp.readlines() for line in Lines: count += 1 print("Line{}: {}".format(count, line.strip())) # Using readline()count = 0print("\nUsing readline()") with open("myfile.txt") as fp: while True: count += 1 line = fp.readline() if not line: break print("Line{}: {}".format(count, line.strip())) # Using for loopcount = 0print("\nUsing for loop") with open("myfile.txt") as fp: for line in fp: count += 1 print("Line{}: {}".format(count, line.strip()))
Output:
Using readlines()
Line1: Geeks
Line2: for
Line3: Geeks
Using readline()
Line1: Geeks
Line2: for
Line3: Geeks
Using for loop
Line1: Geeks
Line2: for
Line3: Geeks
shubham singh 29
1912shashank
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Graph Plotting in Python | Set 1
Defaultdict in Python | [
{
"code": null,
"e": 25433,
"s": 25405,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 25449,
"s": 25433,
"text": "Prerequisites: "
},
{
"code": null,
"e": 25463,
"s": 25449,
"text": "Access modes "
},
{
"code": null,
"e": 25476,
"s": 25463,
"text": "Open a file "
},
{
"code": null,
"e": 25491,
"s": 25476,
"text": "Close a file "
},
{
"code": null,
"e": 25778,
"s": 25491,
"text": "Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. "
},
{
"code": null,
"e": 26118,
"s": 25780,
"text": "readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines. We can iterate over the list and strip the newline ‘\\n’ character using strip() function. "
},
{
"code": null,
"e": 26128,
"s": 26118,
"text": "Example: "
},
{
"code": null,
"e": 26136,
"s": 26128,
"text": "Python3"
},
{
"code": "# Python code to# demonstrate readlines() L = [\"Geeks\\n\", \"for\\n\", \"Geeks\\n\"] # writing to filefile1 = open('myfile.txt', 'w')file1.writelines(L)file1.close() # Using readlines()file1 = open('myfile.txt', 'r')Lines = file1.readlines() count = 0# Strips the newline characterfor line in Lines: count += 1 print(\"Line{}: {}\".format(count, line.strip()))",
"e": 26498,
"s": 26136,
"text": null
},
{
"code": null,
"e": 26508,
"s": 26498,
"text": "Output: "
},
{
"code": null,
"e": 26545,
"s": 26508,
"text": "Line1: Geeks\nLine2: for\nLine3: Geeks"
},
{
"code": null,
"e": 27096,
"s": 26547,
"text": "readline() function reads a line of the file and return it in the form of the string. It takes a parameter n, which specifies the maximum number of bytes that will be read. However, does not reads more than one line, even if n exceeds the length of the line. It will be efficient when reading a large file because instead of fetching all the data in one go, it fetches line by line. readline() returns the next line of the file which contains a newline character in the end. Also, if the end of the file is reached, it will return an empty string. "
},
{
"code": null,
"e": 27105,
"s": 27096,
"text": "Example:"
},
{
"code": null,
"e": 27113,
"s": 27105,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate readline() L = [\"Geeks\\n\", \"for\\n\", \"Geeks\\n\"] # Writing to a filefile1 = open('myfile.txt', 'w')file1.writelines((L))file1.close() # Using readline()file1 = open('myfile.txt', 'r')count = 0 while True: count += 1 # Get next line from file line = file1.readline() # if line is empty # end of file is reached if not line: break print(\"Line{}: {}\".format(count, line.strip())) file1.close()",
"e": 27572,
"s": 27113,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27572,
"text": "Output: "
},
{
"code": null,
"e": 27615,
"s": 27581,
"text": "Line1 Geeks\nLine2 for\nLine3 Geeks"
},
{
"code": null,
"e": 28077,
"s": 27617,
"text": "An iterable object is returned by open() function while opening a file. This final way of reading in a file line-by-line includes iterating over a file object in a for loop. Doing this we are taking advantage of a built-in Python function that allows us to iterate over the file object implicitly using a for loop in a combination with using the iterable object. This approach takes fewer lines of code, which is always the best practice worthy of following. "
},
{
"code": null,
"e": 28086,
"s": 28077,
"text": "Example:"
},
{
"code": null,
"e": 28094,
"s": 28086,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate reading files# using for loop L = [\"Geeks\\n\", \"for\\n\", \"Geeks\\n\"] # Writing to filefile1 = open('myfile.txt', 'w')file1.writelines(L)file1.close() # Opening filefile1 = open('myfile.txt', 'r')count = 0 # Using for loopprint(\"Using for loop\")for line in file1: count += 1 print(\"Line{}: {}\".format(count, line.strip())) # Closing filesfile1.close()",
"e": 28486,
"s": 28094,
"text": null
},
{
"code": null,
"e": 28496,
"s": 28486,
"text": "Output: "
},
{
"code": null,
"e": 28548,
"s": 28496,
"text": "Using for loop\nLine1: Geeks\nLine2: for\nLine3: Geeks"
},
{
"code": null,
"e": 29269,
"s": 28550,
"text": "In the above approaches, every time the file is opened it is needed to be closed explicitly. If one forgets to close the file, it may introduce several bugs in the code, i.e. many changes in files do not go into effect until the file is properly closed. To prevent this with statement can be used. The With statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes the code cleaner. There is no need to call file.close() when using with the statement. The with the statement itself ensures proper acquisition and release of resources. "
},
{
"code": null,
"e": 29278,
"s": 29269,
"text": "Example:"
},
{
"code": null,
"e": 29286,
"s": 29278,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate with# statement L = [\"Geeks\\n\", \"for\\n\", \"Geeks\\n\"] # Writing to filewith open(\"myfile.txt\", \"w\") as fp: fp.writelines(L) # using readlines()count = 0print(\"Using readlines()\") with open(\"myfile.txt\") as fp: Lines = fp.readlines() for line in Lines: count += 1 print(\"Line{}: {}\".format(count, line.strip())) # Using readline()count = 0print(\"\\nUsing readline()\") with open(\"myfile.txt\") as fp: while True: count += 1 line = fp.readline() if not line: break print(\"Line{}: {}\".format(count, line.strip())) # Using for loopcount = 0print(\"\\nUsing for loop\") with open(\"myfile.txt\") as fp: for line in fp: count += 1 print(\"Line{}: {}\".format(count, line.strip()))",
"e": 30082,
"s": 29286,
"text": null
},
{
"code": null,
"e": 30092,
"s": 30082,
"text": "Output: "
},
{
"code": null,
"e": 30255,
"s": 30092,
"text": "Using readlines()\nLine1: Geeks\nLine2: for\nLine3: Geeks\n\nUsing readline()\nLine1: Geeks\nLine2: for\nLine3: Geeks\n\nUsing for loop\nLine1: Geeks\nLine2: for\nLine3: Geeks"
},
{
"code": null,
"e": 30274,
"s": 30257,
"text": "shubham singh 29"
},
{
"code": null,
"e": 30287,
"s": 30274,
"text": "1912shashank"
},
{
"code": null,
"e": 30308,
"s": 30287,
"text": "python-file-handling"
},
{
"code": null,
"e": 30315,
"s": 30308,
"text": "Python"
},
{
"code": null,
"e": 30413,
"s": 30315,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30445,
"s": 30413,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30474,
"s": 30445,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30511,
"s": 30474,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30547,
"s": 30511,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 30589,
"s": 30547,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30631,
"s": 30589,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30658,
"s": 30631,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30714,
"s": 30658,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30747,
"s": 30714,
"text": "Graph Plotting in Python | Set 1"
}
]
|
Create an Alarm Clock using Tkinter - GeeksforGeeks | 19 Oct, 2021
Prerequisite: Python GUI – tkinter, winsound, time, and datetime.
As we all know, nowadays wake up on time is a very difficult task. The solution is the Alarm Clock. In this article, we will learn, How to create an Alarm Clock using Tkinter in Python. Without alarms, several people would oversleep and land up late for work. Alarm clocks may also be useful for keeping sleep schedules regular.
Tkinter: Python offers multiple choices for developing a GUI (Graphical User Interface). Out of all the GUI strategies, tkinter is that the most ordinarily used technique. It’s a customary Python interface to the Tk GUI toolkit shipped with Python.
Winsound: The winsound module provides access to the essential sound-playing machinery provided by Windows platforms. It includes functions and a number of other constants. Beep the PC’s speaker.
time: Time module in Python provides varied time-related functions. This module comes with Python’s normal modules.
datetime: The main focus of datetime is to form it simpler to access attributes of the thing associated with dates, times, and time zones.
Below is what GUI looks like:-
Let’s Understand step by step implementation:
Step1: Import Required Library
Python3
# Import Required Libraryfrom tkinter import *import datetimeimport timeimport winsound
Step 2: Add Button, Labels, Frame, and option menus
Syntax:
# Button
Button(Object Name, text=”Enter Text”,**attr)
# Label
Label(Object Name, text=”Enter Text”, command=”Enter Command” , **attr)
# Frame
Frame(Object Name, **attr)
# Option Menu
OptionMenu(“Object Name”, “Data Type”, “list of value in form of tuple”, **attr)
We will create a three-option menu:-
Hours (00–24)
Minutes (00–60)
Seconds (00–60)
Time is in 24-hour time format.
Step 3: Make a function named alarm(), which performs alarm clock work.
Python3
def alarm(): # Infinite Loop while True: # Set Alarm set_alarm = f"{hour.get()}:{minute.get()}:{second.get()}" # Wait for one seconds time.sleep(1) # Get current time current_time = datetime.datetime.now().strftime("%H:%M:%S") # Check whether set alarm is equal to current time or not if current_time == set_alarm: print("Time to Wake up") # Playing sound winsound.PlaySound("sound.wav",winsound.SND_ASYNC)
Below is the full implementation:
Make Infinite Loop
Get hours, minutes, seconds value from the user
Wait for one second using time module
Get Current time using datetime module
Check if the current time is equal to set time; play sound using winsound module
Python3
# Import Required Libraryfrom tkinter import *import datetimeimport timeimport winsoundfrom threading import * # Create Objectroot = Tk() # Set geometryroot.geometry("400x200") # Use Threadingdef Threading(): t1=Thread(target=alarm) t1.start() def alarm(): # Infinite Loop while True: # Set Alarm set_alarm_time = f"{hour.get()}:{minute.get()}:{second.get()}" # Wait for one seconds time.sleep(1) # Get current time current_time = datetime.datetime.now().strftime("%H:%M:%S") print(current_time,set_alarm_time) # Check whether set alarm is equal to current time or not if current_time == set_alarm_time: print("Time to Wake up") # Playing sound winsound.PlaySound("sound.wav",winsound.SND_ASYNC) # Add Labels, Frame, Button, OptionmenusLabel(root,text="Alarm Clock",font=("Helvetica 20 bold"),fg="red").pack(pady=10)Label(root,text="Set Time",font=("Helvetica 15 bold")).pack() frame = Frame(root)frame.pack() hour = StringVar(root)hours = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24' )hour.set(hours[0]) hrs = OptionMenu(frame, hour, *hours)hrs.pack(side=LEFT) minute = StringVar(root)minutes = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60')minute.set(minutes[0]) mins = OptionMenu(frame, minute, *minutes)mins.pack(side=LEFT) second = StringVar(root)seconds = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60')second.set(seconds[0]) secs = OptionMenu(frame, second, *seconds)secs.pack(side=LEFT) Button(root,text="Set Alarm",font=("Helvetica 15"),command=Threading).pack(pady=20) # Execute Tkinterroot.mainloop()
Output:
anikaseth98
adnanirshad158
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25579,
"s": 25551,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 25645,
"s": 25579,
"text": "Prerequisite: Python GUI – tkinter, winsound, time, and datetime."
},
{
"code": null,
"e": 25974,
"s": 25645,
"text": "As we all know, nowadays wake up on time is a very difficult task. The solution is the Alarm Clock. In this article, we will learn, How to create an Alarm Clock using Tkinter in Python. Without alarms, several people would oversleep and land up late for work. Alarm clocks may also be useful for keeping sleep schedules regular."
},
{
"code": null,
"e": 26223,
"s": 25974,
"text": "Tkinter: Python offers multiple choices for developing a GUI (Graphical User Interface). Out of all the GUI strategies, tkinter is that the most ordinarily used technique. It’s a customary Python interface to the Tk GUI toolkit shipped with Python."
},
{
"code": null,
"e": 26419,
"s": 26223,
"text": "Winsound: The winsound module provides access to the essential sound-playing machinery provided by Windows platforms. It includes functions and a number of other constants. Beep the PC’s speaker."
},
{
"code": null,
"e": 26535,
"s": 26419,
"text": "time: Time module in Python provides varied time-related functions. This module comes with Python’s normal modules."
},
{
"code": null,
"e": 26674,
"s": 26535,
"text": "datetime: The main focus of datetime is to form it simpler to access attributes of the thing associated with dates, times, and time zones."
},
{
"code": null,
"e": 26705,
"s": 26674,
"text": "Below is what GUI looks like:-"
},
{
"code": null,
"e": 26751,
"s": 26705,
"text": "Let’s Understand step by step implementation:"
},
{
"code": null,
"e": 26782,
"s": 26751,
"text": "Step1: Import Required Library"
},
{
"code": null,
"e": 26790,
"s": 26782,
"text": "Python3"
},
{
"code": "# Import Required Libraryfrom tkinter import *import datetimeimport timeimport winsound",
"e": 26878,
"s": 26790,
"text": null
},
{
"code": null,
"e": 26933,
"s": 26881,
"text": "Step 2: Add Button, Labels, Frame, and option menus"
},
{
"code": null,
"e": 26943,
"s": 26935,
"text": "Syntax:"
},
{
"code": null,
"e": 26954,
"s": 26945,
"text": "# Button"
},
{
"code": null,
"e": 27000,
"s": 26954,
"text": "Button(Object Name, text=”Enter Text”,**attr)"
},
{
"code": null,
"e": 27008,
"s": 27000,
"text": "# Label"
},
{
"code": null,
"e": 27080,
"s": 27008,
"text": "Label(Object Name, text=”Enter Text”, command=”Enter Command” , **attr)"
},
{
"code": null,
"e": 27088,
"s": 27080,
"text": "# Frame"
},
{
"code": null,
"e": 27115,
"s": 27088,
"text": "Frame(Object Name, **attr)"
},
{
"code": null,
"e": 27129,
"s": 27115,
"text": "# Option Menu"
},
{
"code": null,
"e": 27210,
"s": 27129,
"text": "OptionMenu(“Object Name”, “Data Type”, “list of value in form of tuple”, **attr)"
},
{
"code": null,
"e": 27249,
"s": 27212,
"text": "We will create a three-option menu:-"
},
{
"code": null,
"e": 27265,
"s": 27251,
"text": "Hours (00–24)"
},
{
"code": null,
"e": 27281,
"s": 27265,
"text": "Minutes (00–60)"
},
{
"code": null,
"e": 27297,
"s": 27281,
"text": "Seconds (00–60)"
},
{
"code": null,
"e": 27331,
"s": 27299,
"text": "Time is in 24-hour time format."
},
{
"code": null,
"e": 27405,
"s": 27333,
"text": "Step 3: Make a function named alarm(), which performs alarm clock work."
},
{
"code": null,
"e": 27415,
"s": 27407,
"text": "Python3"
},
{
"code": "def alarm(): # Infinite Loop while True: # Set Alarm set_alarm = f\"{hour.get()}:{minute.get()}:{second.get()}\" # Wait for one seconds time.sleep(1) # Get current time current_time = datetime.datetime.now().strftime(\"%H:%M:%S\") # Check whether set alarm is equal to current time or not if current_time == set_alarm: print(\"Time to Wake up\") # Playing sound winsound.PlaySound(\"sound.wav\",winsound.SND_ASYNC)",
"e": 27920,
"s": 27415,
"text": null
},
{
"code": null,
"e": 27957,
"s": 27923,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 27978,
"s": 27959,
"text": "Make Infinite Loop"
},
{
"code": null,
"e": 28026,
"s": 27978,
"text": "Get hours, minutes, seconds value from the user"
},
{
"code": null,
"e": 28064,
"s": 28026,
"text": "Wait for one second using time module"
},
{
"code": null,
"e": 28103,
"s": 28064,
"text": "Get Current time using datetime module"
},
{
"code": null,
"e": 28184,
"s": 28103,
"text": "Check if the current time is equal to set time; play sound using winsound module"
},
{
"code": null,
"e": 28194,
"s": 28186,
"text": "Python3"
},
{
"code": "# Import Required Libraryfrom tkinter import *import datetimeimport timeimport winsoundfrom threading import * # Create Objectroot = Tk() # Set geometryroot.geometry(\"400x200\") # Use Threadingdef Threading(): t1=Thread(target=alarm) t1.start() def alarm(): # Infinite Loop while True: # Set Alarm set_alarm_time = f\"{hour.get()}:{minute.get()}:{second.get()}\" # Wait for one seconds time.sleep(1) # Get current time current_time = datetime.datetime.now().strftime(\"%H:%M:%S\") print(current_time,set_alarm_time) # Check whether set alarm is equal to current time or not if current_time == set_alarm_time: print(\"Time to Wake up\") # Playing sound winsound.PlaySound(\"sound.wav\",winsound.SND_ASYNC) # Add Labels, Frame, Button, OptionmenusLabel(root,text=\"Alarm Clock\",font=(\"Helvetica 20 bold\"),fg=\"red\").pack(pady=10)Label(root,text=\"Set Time\",font=(\"Helvetica 15 bold\")).pack() frame = Frame(root)frame.pack() hour = StringVar(root)hours = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24' )hour.set(hours[0]) hrs = OptionMenu(frame, hour, *hours)hrs.pack(side=LEFT) minute = StringVar(root)minutes = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60')minute.set(minutes[0]) mins = OptionMenu(frame, minute, *minutes)mins.pack(side=LEFT) second = StringVar(root)seconds = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60')second.set(seconds[0]) secs = OptionMenu(frame, second, *seconds)secs.pack(side=LEFT) Button(root,text=\"Set Alarm\",font=(\"Helvetica 15\"),command=Threading).pack(pady=20) # Execute Tkinterroot.mainloop()",
"e": 30724,
"s": 28194,
"text": null
},
{
"code": null,
"e": 30735,
"s": 30727,
"text": "Output:"
},
{
"code": null,
"e": 30751,
"s": 30739,
"text": "anikaseth98"
},
{
"code": null,
"e": 30766,
"s": 30751,
"text": "adnanirshad158"
},
{
"code": null,
"e": 30791,
"s": 30766,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 30806,
"s": 30791,
"text": "Python-tkinter"
},
{
"code": null,
"e": 30813,
"s": 30806,
"text": "Python"
},
{
"code": null,
"e": 30911,
"s": 30813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30943,
"s": 30911,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30985,
"s": 30943,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31027,
"s": 30985,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31083,
"s": 31027,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31110,
"s": 31083,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31141,
"s": 31110,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 31180,
"s": 31141,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31209,
"s": 31180,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 31231,
"s": 31209,
"text": "Defaultdict in Python"
}
]
|
File.Copy(String, String, Boolean) Method in C# with Examples - GeeksforGeeks | 02 Mar, 2021
File.Copy(String, String, Boolean) is an inbuilt File class method that is used to copy the content of the existing source file content to another destination file if exist, else create a new destination file then copying process is done.Syntax:
public static void Copy (string sourceFileName, string destFileName, bool overwrite);
Parameter: This function accepts three parameters which are illustrated below:
sourceFileName: This is the file from where data is copied.
destFileName: This is the file where data is pasted.
overwrite: This is the boolean value. It uses true if the destination file can be overwritten otherwise it uses false.
Exceptions:
UnauthorizedAccessException: The destFileName is read-only OR Here overwrite is true if the destFileName exists and is hidden, but source filename is not hidden.
ArgumentException: The source filename or destFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. OR the sourceFileName or destFileName specifies a directory.
ArgumentNullException: The sourceFileName or destFileName is null.
PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: The path specified in source filename or destFileName is invalid (for example, it is on an unmapped drive).
FileNotFoundException: The source filename was not found.
IOException: The destFileName exists and overwrite is false OR An I/O error has occurred.
NotSupportedException: The sourceFileName or destFileName is in an invalid format.
Below are the programs to illustrate the File.Copy(String, String, Boolean) method.Program 1: Before running the below code, two files i.e, source file file.txt and destination file gfg.txt are created with some contents shown below:
C#
// C# program to illustrate the usage// of File.Copy() method // Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq; class GFG { // Main() method public static void Main() { // Specifying two files string sourceFile = @"file.txt"; string destinationFile = @"gfg.txt"; try { // Copying source file's contents to // destination file File.Copy(sourceFile, destinationFile, true); } catch (IOException iox) { Console.WriteLine(iox.Message); } Console.WriteLine("Copying process has been done."); }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
Copying process has been done.
After running the above code, above output is shown and the destination file contents become like shown below:
Program 2: Before running the below code, two files i.e, source file file.txt and destination file gfg.txt is created with some contents shown below:
C#
// C# program to illustrate the usage// of File.Copy() method // Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq; class GFG { // Main() method public static void Main() { // Specifying two files string sourceFile = @"file.txt"; string destinationFile = @"gfg.txt"; try { // Copying source file's contents to // destination file File.Copy(sourceFile, destinationFile, true); } catch (IOException iox) { Console.WriteLine(iox.Message); } Console.WriteLine("Copying process has been done."); }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
Copying process has been done.
After running the above code, above output is shown and the destination file contents get overwritten with the content of source file file.txt like shown below:
Program 3: Before running the below code, two files i.e, source file file.txt and destination file gfg.txt is created with some contents shown below:
C#
// C# program to illustrate the usage// of File.Copy() method // Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq; class GFG { // Main() method public static void Main() { // Specifying two files string sourceFile = @"file.txt"; string destinationFile = @"gfg.txt"; try { // Copying source file's contents to // destination file File.Copy(sourceFile, destinationFile, false); } catch (IOException iox) { Console.WriteLine(iox.Message); } }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
Could not create file "/home/runner/NutritiousHeavyRegression/gfg.txt". File already exists.
After running the above code, above error is thrown this is because the bool overwrite values used in the above code is false.
arorakashish0911
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Linked List Implementation in C#
Convert String to Character Array in C# | [
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n02 Mar, 2021"
},
{
"code": null,
"e": 25795,
"s": 25547,
"text": "File.Copy(String, String, Boolean) is an inbuilt File class method that is used to copy the content of the existing source file content to another destination file if exist, else create a new destination file then copying process is done.Syntax: "
},
{
"code": null,
"e": 25881,
"s": 25795,
"text": "public static void Copy (string sourceFileName, string destFileName, bool overwrite);"
},
{
"code": null,
"e": 25961,
"s": 25881,
"text": "Parameter: This function accepts three parameters which are illustrated below: "
},
{
"code": null,
"e": 26021,
"s": 25961,
"text": "sourceFileName: This is the file from where data is copied."
},
{
"code": null,
"e": 26074,
"s": 26021,
"text": "destFileName: This is the file where data is pasted."
},
{
"code": null,
"e": 26193,
"s": 26074,
"text": "overwrite: This is the boolean value. It uses true if the destination file can be overwritten otherwise it uses false."
},
{
"code": null,
"e": 26206,
"s": 26193,
"text": "Exceptions: "
},
{
"code": null,
"e": 26368,
"s": 26206,
"text": "UnauthorizedAccessException: The destFileName is read-only OR Here overwrite is true if the destFileName exists and is hidden, but source filename is not hidden."
},
{
"code": null,
"e": 26611,
"s": 26368,
"text": "ArgumentException: The source filename or destFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars. OR the sourceFileName or destFileName specifies a directory."
},
{
"code": null,
"e": 26678,
"s": 26611,
"text": "ArgumentNullException: The sourceFileName or destFileName is null."
},
{
"code": null,
"e": 26781,
"s": 26678,
"text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 26917,
"s": 26781,
"text": "DirectoryNotFoundException: The path specified in source filename or destFileName is invalid (for example, it is on an unmapped drive)."
},
{
"code": null,
"e": 26975,
"s": 26917,
"text": "FileNotFoundException: The source filename was not found."
},
{
"code": null,
"e": 27065,
"s": 26975,
"text": "IOException: The destFileName exists and overwrite is false OR An I/O error has occurred."
},
{
"code": null,
"e": 27148,
"s": 27065,
"text": "NotSupportedException: The sourceFileName or destFileName is in an invalid format."
},
{
"code": null,
"e": 27383,
"s": 27148,
"text": "Below are the programs to illustrate the File.Copy(String, String, Boolean) method.Program 1: Before running the below code, two files i.e, source file file.txt and destination file gfg.txt are created with some contents shown below: "
},
{
"code": null,
"e": 27390,
"s": 27387,
"text": "C#"
},
{
"code": "// C# program to illustrate the usage// of File.Copy() method // Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq; class GFG { // Main() method public static void Main() { // Specifying two files string sourceFile = @\"file.txt\"; string destinationFile = @\"gfg.txt\"; try { // Copying source file's contents to // destination file File.Copy(sourceFile, destinationFile, true); } catch (IOException iox) { Console.WriteLine(iox.Message); } Console.WriteLine(\"Copying process has been done.\"); }}",
"e": 28078,
"s": 27390,
"text": null
},
{
"code": null,
"e": 28091,
"s": 28078,
"text": "Executing: "
},
{
"code": null,
"e": 28162,
"s": 28091,
"text": "mcs -out:main.exe main.cs\nmono main.exe\nCopying process has been done."
},
{
"code": null,
"e": 28274,
"s": 28162,
"text": "After running the above code, above output is shown and the destination file contents become like shown below: "
},
{
"code": null,
"e": 28425,
"s": 28274,
"text": "Program 2: Before running the below code, two files i.e, source file file.txt and destination file gfg.txt is created with some contents shown below: "
},
{
"code": null,
"e": 28432,
"s": 28429,
"text": "C#"
},
{
"code": "// C# program to illustrate the usage// of File.Copy() method // Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq; class GFG { // Main() method public static void Main() { // Specifying two files string sourceFile = @\"file.txt\"; string destinationFile = @\"gfg.txt\"; try { // Copying source file's contents to // destination file File.Copy(sourceFile, destinationFile, true); } catch (IOException iox) { Console.WriteLine(iox.Message); } Console.WriteLine(\"Copying process has been done.\"); }}",
"e": 29120,
"s": 28432,
"text": null
},
{
"code": null,
"e": 29133,
"s": 29120,
"text": "Executing: "
},
{
"code": null,
"e": 29204,
"s": 29133,
"text": "mcs -out:main.exe main.cs\nmono main.exe\nCopying process has been done."
},
{
"code": null,
"e": 29366,
"s": 29204,
"text": "After running the above code, above output is shown and the destination file contents get overwritten with the content of source file file.txt like shown below: "
},
{
"code": null,
"e": 29517,
"s": 29366,
"text": "Program 3: Before running the below code, two files i.e, source file file.txt and destination file gfg.txt is created with some contents shown below: "
},
{
"code": null,
"e": 29524,
"s": 29521,
"text": "C#"
},
{
"code": "// C# program to illustrate the usage// of File.Copy() method // Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq; class GFG { // Main() method public static void Main() { // Specifying two files string sourceFile = @\"file.txt\"; string destinationFile = @\"gfg.txt\"; try { // Copying source file's contents to // destination file File.Copy(sourceFile, destinationFile, false); } catch (IOException iox) { Console.WriteLine(iox.Message); } }}",
"e": 30153,
"s": 29524,
"text": null
},
{
"code": null,
"e": 30165,
"s": 30153,
"text": "Executing: "
},
{
"code": null,
"e": 30298,
"s": 30165,
"text": "mcs -out:main.exe main.cs\nmono main.exe\nCould not create file \"/home/runner/NutritiousHeavyRegression/gfg.txt\". File already exists."
},
{
"code": null,
"e": 30426,
"s": 30298,
"text": "After running the above code, above error is thrown this is because the bool overwrite values used in the above code is false. "
},
{
"code": null,
"e": 30443,
"s": 30426,
"text": "arorakashish0911"
},
{
"code": null,
"e": 30464,
"s": 30443,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 30467,
"s": 30464,
"text": "C#"
},
{
"code": null,
"e": 30565,
"s": 30467,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30588,
"s": 30565,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 30616,
"s": 30588,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 30633,
"s": 30616,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 30655,
"s": 30633,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 30684,
"s": 30655,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 30724,
"s": 30684,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 30767,
"s": 30724,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 30790,
"s": 30767,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 30823,
"s": 30790,
"text": "Linked List Implementation in C#"
}
]
|
Concurrent Merge Sort in Shared Memory - GeeksforGeeks | 14 Jan, 2022
Given a number ‘n’ and a n numbers, sort the numbers using Concurrent Merge Sort. (Hint: Try to use shmget, shmat system calls).Part1: The algorithm (HOW?) Recursively make two child processes, one for the left half, one of the right half. If the number of elements in the array for a process is less than 5, perform a Insertion Sort. The parent of the two children then merges the result and returns back to the parent and so on. But how do you make it concurrent?Part2: The logical (WHY?) The important part of the solution to this problem is not algorithmic, but to explain concepts of Operating System and kernel. To achieve concurrent sorting, we need a way to make two processes to work on the same array at the same time. To make things easier Linux provides a lot of system calls via simple API endpoints. Two of them are, shmget() (for shared memory allocation) and shmat() (for shared memory operations). We create a shared memory space between the child process that we fork. Each segment is split into left and right child which is sorted, the interesting part being they are working concurrently! The shmget() requests the kernel to allocate a shared page for both the processes.Why traditional fork() does not work? The answer lies in what fork() actually does. From the documentation, “fork() creates a new process by duplicating the calling process”. The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the same content. Memory writes, file-descriptor(fd) changes, etc, performed by one of the processes do not affect the other. Hence we need a shared memory segment.
CPP
// C program to implement concurrent merge sort#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h> void insertionSort(int arr[], int n);void merge(int a[], int l1, int h1, int h2); void mergeSort(int a[], int l, int h){ int i, len=(h-l+1); // Using insertion sort for small sized array if (len<=5) { insertionSort(a+l, len); return; } pid_t lpid,rpid; lpid = fork(); if (lpid<0) { // Lchild proc not created perror("Left Child Proc. not created\n"); _exit(-1); } else if (lpid==0) { mergeSort(a,l,l+len/2-1); _exit(0); } else { rpid = fork(); if (rpid<0) { // Rchild proc not created perror("Right Child Proc. not created\n"); _exit(-1); } else if(rpid==0) { mergeSort(a,l+len/2,h); _exit(0); } } int status; // Wait for child processes to finish waitpid(lpid, &status, 0); waitpid(rpid, &status, 0); // Merge the sorted subarrays merge(a, l, l+len/2-1, h);} /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; }} // Method to merge sorted subarraysvoid merge(int a[], int l1, int h1, int h2){ // We can directly copy the sorted elements // in the final array, no need for a temporary // sorted array. int count=h2-l1+1; int sorted[count]; int i=l1, k=h1+1, m=0; while (i<=h1 && k<=h2) { if (a[i]<a[k]) sorted[m++]=a[i++]; else if (a[k]<a[i]) sorted[m++]=a[k++]; else if (a[i]==a[k]) { sorted[m++]=a[i++]; sorted[m++]=a[k++]; } } while (i<=h1) sorted[m++]=a[i++]; while (k<=h2) sorted[m++]=a[k++]; int arr_count = l1; for (i=0; i<count; i++,l1++) a[l1] = sorted[i];} // To check if array is actually sorted or notvoid isSorted(int arr[], int len){ if (len==1) { printf("Sorting Done Successfully\n"); return; } int i; for (i=1; i<len; i++) { if (arr[i]<arr[i-1]) { printf("Sorting Not Done\n"); return; } } printf("Sorting Done Successfully\n"); return;} // To fill random values in array for testing// purposevoid fillData(int a[], int len){ // Create random arrays int i; for (i=0; i<len; i++) a[i] = rand(); return;} // Driver codeint main(){ int shmid; key_t key = IPC_PRIVATE; int *shm_array; // Using fixed size array. We can uncomment // below lines to take size from user int length = 128; /* printf("Enter No of elements of Array:"); scanf("%d",&length); */ // Calculate segment length size_t SHM_SIZE = sizeof(int)*length; // Create the segment. if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) < 0) { perror("shmget"); _exit(1); } // Now we attach the segment to our data space. if ((shm_array = shmat(shmid, NULL, 0)) == (int *) -1) { perror("shmat"); _exit(1); } // Create a random array of given length srand(time(NULL)); fillData(shm_array, length); // Sort the created array mergeSort(shm_array, 0, length-1); // Check if array is sorted or not isSorted(shm_array, length); /* Detach from the shared memory now that we are done using it. */ if (shmdt(shm_array) == -1) { perror("shmdt"); _exit(1); } /* Delete the shared memory segment. */ if (shmctl(shmid, IPC_RMID, NULL) == -1) { perror("shmctl"); _exit(1); } return 0;}
Output:
Sorting Done Successfully
Performance improvements? Try to time the code and compare its performance with the traditional sequential code. You would be surprised to know that sequential sort performance better! When, say left child, access the left array, the array is loaded into the cache of a processor. Now when the right array is accessed (because of concurrent accesses), there is a cache miss since the cache is filled with left segment and then right segment is copied to the cache memory. This to-and-fro process continues and it degrades the performance to such a level that it performs poorer than the sequential code.There are ways to reduce the cache misses by controlling the workflow of the code. But they cannot be avoided completely!This article is contributed by Pinkesh Badjatiya .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prachisoda1234
varshagumber28
Merge Sort
system-programming
Project
Strings
Strings
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Banking Transaction System using Java
Student record management system using linked list
E-commerce Website using Django
Handling Ajax request in Django
How to write a good SRS for your Project
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4 | [
{
"code": null,
"e": 25721,
"s": 25693,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 27372,
"s": 25721,
"text": "Given a number ‘n’ and a n numbers, sort the numbers using Concurrent Merge Sort. (Hint: Try to use shmget, shmat system calls).Part1: The algorithm (HOW?) Recursively make two child processes, one for the left half, one of the right half. If the number of elements in the array for a process is less than 5, perform a Insertion Sort. The parent of the two children then merges the result and returns back to the parent and so on. But how do you make it concurrent?Part2: The logical (WHY?) The important part of the solution to this problem is not algorithmic, but to explain concepts of Operating System and kernel. To achieve concurrent sorting, we need a way to make two processes to work on the same array at the same time. To make things easier Linux provides a lot of system calls via simple API endpoints. Two of them are, shmget() (for shared memory allocation) and shmat() (for shared memory operations). We create a shared memory space between the child process that we fork. Each segment is split into left and right child which is sorted, the interesting part being they are working concurrently! The shmget() requests the kernel to allocate a shared page for both the processes.Why traditional fork() does not work? The answer lies in what fork() actually does. From the documentation, “fork() creates a new process by duplicating the calling process”. The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the same content. Memory writes, file-descriptor(fd) changes, etc, performed by one of the processes do not affect the other. Hence we need a shared memory segment. "
},
{
"code": null,
"e": 27376,
"s": 27372,
"text": "CPP"
},
{
"code": "// C program to implement concurrent merge sort#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h> void insertionSort(int arr[], int n);void merge(int a[], int l1, int h1, int h2); void mergeSort(int a[], int l, int h){ int i, len=(h-l+1); // Using insertion sort for small sized array if (len<=5) { insertionSort(a+l, len); return; } pid_t lpid,rpid; lpid = fork(); if (lpid<0) { // Lchild proc not created perror(\"Left Child Proc. not created\\n\"); _exit(-1); } else if (lpid==0) { mergeSort(a,l,l+len/2-1); _exit(0); } else { rpid = fork(); if (rpid<0) { // Rchild proc not created perror(\"Right Child Proc. not created\\n\"); _exit(-1); } else if(rpid==0) { mergeSort(a,l+len/2,h); _exit(0); } } int status; // Wait for child processes to finish waitpid(lpid, &status, 0); waitpid(rpid, &status, 0); // Merge the sorted subarrays merge(a, l, l+len/2-1, h);} /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; }} // Method to merge sorted subarraysvoid merge(int a[], int l1, int h1, int h2){ // We can directly copy the sorted elements // in the final array, no need for a temporary // sorted array. int count=h2-l1+1; int sorted[count]; int i=l1, k=h1+1, m=0; while (i<=h1 && k<=h2) { if (a[i]<a[k]) sorted[m++]=a[i++]; else if (a[k]<a[i]) sorted[m++]=a[k++]; else if (a[i]==a[k]) { sorted[m++]=a[i++]; sorted[m++]=a[k++]; } } while (i<=h1) sorted[m++]=a[i++]; while (k<=h2) sorted[m++]=a[k++]; int arr_count = l1; for (i=0; i<count; i++,l1++) a[l1] = sorted[i];} // To check if array is actually sorted or notvoid isSorted(int arr[], int len){ if (len==1) { printf(\"Sorting Done Successfully\\n\"); return; } int i; for (i=1; i<len; i++) { if (arr[i]<arr[i-1]) { printf(\"Sorting Not Done\\n\"); return; } } printf(\"Sorting Done Successfully\\n\"); return;} // To fill random values in array for testing// purposevoid fillData(int a[], int len){ // Create random arrays int i; for (i=0; i<len; i++) a[i] = rand(); return;} // Driver codeint main(){ int shmid; key_t key = IPC_PRIVATE; int *shm_array; // Using fixed size array. We can uncomment // below lines to take size from user int length = 128; /* printf(\"Enter No of elements of Array:\"); scanf(\"%d\",&length); */ // Calculate segment length size_t SHM_SIZE = sizeof(int)*length; // Create the segment. if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) < 0) { perror(\"shmget\"); _exit(1); } // Now we attach the segment to our data space. if ((shm_array = shmat(shmid, NULL, 0)) == (int *) -1) { perror(\"shmat\"); _exit(1); } // Create a random array of given length srand(time(NULL)); fillData(shm_array, length); // Sort the created array mergeSort(shm_array, 0, length-1); // Check if array is sorted or not isSorted(shm_array, length); /* Detach from the shared memory now that we are done using it. */ if (shmdt(shm_array) == -1) { perror(\"shmdt\"); _exit(1); } /* Delete the shared memory segment. */ if (shmctl(shmid, IPC_RMID, NULL) == -1) { perror(\"shmctl\"); _exit(1); } return 0;}",
"e": 31416,
"s": 27376,
"text": null
},
{
"code": null,
"e": 31426,
"s": 31416,
"text": "Output: "
},
{
"code": null,
"e": 31452,
"s": 31426,
"text": "Sorting Done Successfully"
},
{
"code": null,
"e": 32602,
"s": 31452,
"text": "Performance improvements? Try to time the code and compare its performance with the traditional sequential code. You would be surprised to know that sequential sort performance better! When, say left child, access the left array, the array is loaded into the cache of a processor. Now when the right array is accessed (because of concurrent accesses), there is a cache miss since the cache is filled with left segment and then right segment is copied to the cache memory. This to-and-fro process continues and it degrades the performance to such a level that it performs poorer than the sequential code.There are ways to reduce the cache misses by controlling the workflow of the code. But they cannot be avoided completely!This article is contributed by Pinkesh Badjatiya .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32617,
"s": 32602,
"text": "prachisoda1234"
},
{
"code": null,
"e": 32632,
"s": 32617,
"text": "varshagumber28"
},
{
"code": null,
"e": 32643,
"s": 32632,
"text": "Merge Sort"
},
{
"code": null,
"e": 32662,
"s": 32643,
"text": "system-programming"
},
{
"code": null,
"e": 32670,
"s": 32662,
"text": "Project"
},
{
"code": null,
"e": 32678,
"s": 32670,
"text": "Strings"
},
{
"code": null,
"e": 32686,
"s": 32678,
"text": "Strings"
},
{
"code": null,
"e": 32697,
"s": 32686,
"text": "Merge Sort"
},
{
"code": null,
"e": 32795,
"s": 32697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32833,
"s": 32795,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 32884,
"s": 32833,
"text": "Student record management system using linked list"
},
{
"code": null,
"e": 32916,
"s": 32884,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 32948,
"s": 32916,
"text": "Handling Ajax request in Django"
},
{
"code": null,
"e": 32989,
"s": 32948,
"text": "How to write a good SRS for your Project"
},
{
"code": null,
"e": 33035,
"s": 32989,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 33060,
"s": 33035,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33120,
"s": 33060,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33135,
"s": 33120,
"text": "C++ Data Types"
}
]
|
ReactJS useLayoutEffect Hook - GeeksforGeeks | 22 Jan, 2021
The useLayoutEffect works similarly to useEffect but rather working asynchronously like useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the page loading, we should always use useEffect hook.
The useLayoutEffect hook works in the same phase as componentDidMount and componentDidUpdate methods. We should only use useLayoutEffect if useEffect isn’t outputting the expected result.
Syntax:
useLayoutEffect()
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build a name changer application that changes the name of the state when the useLayoutEffect hook is called.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useLayoutEffect, useState } from 'react'; const App = () => { const [value, setValue] = useState('GFG'); useLayoutEffect(() => { if (value === 'GFG') { // Changing the state setValue('GeeksForGeeks'); } console.log('UseLayoutEffect is called with the value of ', value); }, [value]); return <div>{value} is the greatest portal for geeks!</div>;}; export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
React-misc
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
How to build a basic CRUD app with Node.js and ReactJS ?
How to Use Bootstrap with React?
How to check the version of ReactJS ?
Destructuring of Props in ReactJS | [
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 26412,
"s": 26071,
"text": "The useLayoutEffect works similarly to useEffect but rather working asynchronously like useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the page loading, we should always use useEffect hook."
},
{
"code": null,
"e": 26600,
"s": 26412,
"text": "The useLayoutEffect hook works in the same phase as componentDidMount and componentDidUpdate methods. We should only use useLayoutEffect if useEffect isn’t outputting the expected result."
},
{
"code": null,
"e": 26608,
"s": 26600,
"text": "Syntax:"
},
{
"code": null,
"e": 26626,
"s": 26608,
"text": "useLayoutEffect()"
},
{
"code": null,
"e": 26654,
"s": 26626,
"text": "Creating React Application:"
},
{
"code": null,
"e": 26718,
"s": 26654,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 26752,
"s": 26718,
"text": "npx create-react-app functiondemo"
},
{
"code": null,
"e": 26854,
"s": 26752,
"text": "Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:"
},
{
"code": null,
"e": 26870,
"s": 26854,
"text": "cd functiondemo"
},
{
"code": null,
"e": 26922,
"s": 26870,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 26940,
"s": 26922,
"text": "Project Structure"
},
{
"code": null,
"e": 27091,
"s": 26940,
"text": "Example: In this example, we are going to build a name changer application that changes the name of the state when the useLayoutEffect hook is called."
},
{
"code": null,
"e": 27220,
"s": 27091,
"text": "App.js: 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": 27231,
"s": 27220,
"text": "Javascript"
},
{
"code": "import React, { useLayoutEffect, useState } from 'react'; const App = () => { const [value, setValue] = useState('GFG'); useLayoutEffect(() => { if (value === 'GFG') { // Changing the state setValue('GeeksForGeeks'); } console.log('UseLayoutEffect is called with the value of ', value); }, [value]); return <div>{value} is the greatest portal for geeks!</div>;}; export default App;",
"e": 27645,
"s": 27231,
"text": null
},
{
"code": null,
"e": 27758,
"s": 27645,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 27768,
"s": 27758,
"text": "npm start"
},
{
"code": null,
"e": 27777,
"s": 27768,
"text": "Output: "
},
{
"code": null,
"e": 27788,
"s": 27777,
"text": "React-misc"
},
{
"code": null,
"e": 27796,
"s": 27788,
"text": "ReactJS"
},
{
"code": null,
"e": 27894,
"s": 27796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27921,
"s": 27894,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 27963,
"s": 27921,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 28001,
"s": 27963,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 28036,
"s": 28001,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 28094,
"s": 28036,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 28146,
"s": 28094,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 28203,
"s": 28146,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 28236,
"s": 28203,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 28274,
"s": 28236,
"text": "How to check the version of ReactJS ?"
}
]
|
Image Classification using JavaScript - GeeksforGeeks | 28 May, 2020
Image Classification is one of the most common applications of machine learning. Image classification is a computer vision technique in which we classify images according to the visual content in it. The example we can train an image classifier that can predict if a given image is a dog or not. In this article we would use ml5 js which is a machine learning library for the web.
Transfer Learning: In machine learning, it is a very popular technique. In this technique, we use a machine learning model trained for one task, used for another similar task. Here we would use Mobile Net a pre-trained machine learning model for image classification tasks.
HTML Code: Here, we have created a html file and used ml5 js cdn to use it in our file. We have created an input field to upload image files. A onchange event listener is set to loadFile() function which we will define in a separate javascript file. Also, a blank image field is added to show the uploaded image.index.html:<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Image Classifier using ML5 js</title> <script src="https://unpkg.com/[email protected]/dist/ml5.min.js"> </script> </head> <body> <center> <h1 style="color: green;">GeeksforGeeks</h1> <b> Image Classification using Javascript </b> </br> <img src="" alt="" id="image" width="315px" height="200px" /> </br></br> <input type="file" accept="image/*" onchange="loadFile(event)" name="image" id="file" /> <button onclick="predict()">Predict</button> </center> </body></html>
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Image Classifier using ML5 js</title> <script src="https://unpkg.com/[email protected]/dist/ml5.min.js"> </script> </head> <body> <center> <h1 style="color: green;">GeeksforGeeks</h1> <b> Image Classification using Javascript </b> </br> <img src="" alt="" id="image" width="315px" height="200px" /> </br></br> <input type="file" accept="image/*" onchange="loadFile(event)" name="image" id="file" /> <button onclick="predict()">Predict</button> </center> </body></html>
JS Code: Create a loadFile function in script.js file if you prefer external js file. Firstly the image is fetched from the input field from the HTML file and the image is set inside the blank image field. Now we would initiate our machine learning model. Then ml5.imageClassifier method is called an argument ‘MobileNet’ is passed so that MobileNet is loaded for transfer learning and the second parameter is a callback function which logs ‘Model Loaded !’ in the console when the model is loaded. Now create a predict function in js section and the classifier.predict method is called. The first argument is the image that has to be classified and the second argument is a callback function. Now we use the alert method to show the predicted result of the model. This function will be called when the predict button is clicked.<script> var loadFile = function (event) { var image = document.getElementById("image"); image.src = URL.createObjectURL(event.target.files[0]); }; const classifier = ml5.imageClassifier ("MobileNet", modelLoaded); // When the model is loaded function modelLoaded() { console.log("Model Loaded!"); } function predict() { classifier.predict(document.getElementById("image"), function (err, results) { alert(results[0].label); }); }</script>
<script> var loadFile = function (event) { var image = document.getElementById("image"); image.src = URL.createObjectURL(event.target.files[0]); }; const classifier = ml5.imageClassifier ("MobileNet", modelLoaded); // When the model is loaded function modelLoaded() { console.log("Model Loaded!"); } function predict() { classifier.predict(document.getElementById("image"), function (err, results) { alert(results[0].label); }); }</script>
Final Solution: In this section we will just combine the above two code section into one to achieve the the
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Image Classifier using ML5 js</title> <script src="https://unpkg.com/[email protected]/dist/ml5.min.js"> </script> <script> var loadFile = function (event) { var image = document.getElementById("image"); image.src = URL.createObjectURL(event.target.files[0]); }; const classifier = ml5.imageClassifier ("MobileNet", modelLoaded); // When the model is loaded function modelLoaded() { console.log("Model Loaded!"); } function predict() { classifier.predict(document.getElementById("image"), function (err, results) { alert(results[0].label); }); } </script> </head> <body> <center> <h1 style="color: green;">GeeksforGeeks</h1> <b> Image Classification using Javascript </b> </br> <img src="" alt="" id="image" width="315px" height="200px" /> </br></br> <input type="file" accept="image/*" onchange="loadFile(event)" name="image" id="file" /> <button onclick="predict()">Predict</button> </center> </body></html>
Output:
ml5.js
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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": 26571,
"s": 26543,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 26952,
"s": 26571,
"text": "Image Classification is one of the most common applications of machine learning. Image classification is a computer vision technique in which we classify images according to the visual content in it. The example we can train an image classifier that can predict if a given image is a dog or not. In this article we would use ml5 js which is a machine learning library for the web."
},
{
"code": null,
"e": 27226,
"s": 26952,
"text": "Transfer Learning: In machine learning, it is a very popular technique. In this technique, we use a machine learning model trained for one task, used for another similar task. Here we would use Mobile Net a pre-trained machine learning model for image classification tasks."
},
{
"code": null,
"e": 28394,
"s": 27226,
"text": "HTML Code: Here, we have created a html file and used ml5 js cdn to use it in our file. We have created an input field to upload image files. A onchange event listener is set to loadFile() function which we will define in a separate javascript file. Also, a blank image field is added to show the uploaded image.index.html:<html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Image Classifier using ML5 js</title> <script src=\"https://unpkg.com/[email protected]/dist/ml5.min.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b> Image Classification using Javascript </b> </br> <img src=\"\" alt=\"\" id=\"image\" width=\"315px\" height=\"200px\" /> </br></br> <input type=\"file\" accept=\"image/*\" onchange=\"loadFile(event)\" name=\"image\" id=\"file\" /> <button onclick=\"predict()\">Predict</button> </center> </body></html>"
},
{
"code": "<html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Image Classifier using ML5 js</title> <script src=\"https://unpkg.com/[email protected]/dist/ml5.min.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b> Image Classification using Javascript </b> </br> <img src=\"\" alt=\"\" id=\"image\" width=\"315px\" height=\"200px\" /> </br></br> <input type=\"file\" accept=\"image/*\" onchange=\"loadFile(event)\" name=\"image\" id=\"file\" /> <button onclick=\"predict()\">Predict</button> </center> </body></html>",
"e": 29239,
"s": 28394,
"text": null
},
{
"code": null,
"e": 30653,
"s": 29239,
"text": "JS Code: Create a loadFile function in script.js file if you prefer external js file. Firstly the image is fetched from the input field from the HTML file and the image is set inside the blank image field. Now we would initiate our machine learning model. Then ml5.imageClassifier method is called an argument ‘MobileNet’ is passed so that MobileNet is loaded for transfer learning and the second parameter is a callback function which logs ‘Model Loaded !’ in the console when the model is loaded. Now create a predict function in js section and the classifier.predict method is called. The first argument is the image that has to be classified and the second argument is a callback function. Now we use the alert method to show the predicted result of the model. This function will be called when the predict button is clicked.<script> var loadFile = function (event) { var image = document.getElementById(\"image\"); image.src = URL.createObjectURL(event.target.files[0]); }; const classifier = ml5.imageClassifier (\"MobileNet\", modelLoaded); // When the model is loaded function modelLoaded() { console.log(\"Model Loaded!\"); } function predict() { classifier.predict(document.getElementById(\"image\"), function (err, results) { alert(results[0].label); }); }</script>"
},
{
"code": "<script> var loadFile = function (event) { var image = document.getElementById(\"image\"); image.src = URL.createObjectURL(event.target.files[0]); }; const classifier = ml5.imageClassifier (\"MobileNet\", modelLoaded); // When the model is loaded function modelLoaded() { console.log(\"Model Loaded!\"); } function predict() { classifier.predict(document.getElementById(\"image\"), function (err, results) { alert(results[0].label); }); }</script>",
"e": 31238,
"s": 30653,
"text": null
},
{
"code": null,
"e": 31346,
"s": 31238,
"text": "Final Solution: In this section we will just combine the above two code section into one to achieve the the"
},
{
"code": "<html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Image Classifier using ML5 js</title> <script src=\"https://unpkg.com/[email protected]/dist/ml5.min.js\"> </script> <script> var loadFile = function (event) { var image = document.getElementById(\"image\"); image.src = URL.createObjectURL(event.target.files[0]); }; const classifier = ml5.imageClassifier (\"MobileNet\", modelLoaded); // When the model is loaded function modelLoaded() { console.log(\"Model Loaded!\"); } function predict() { classifier.predict(document.getElementById(\"image\"), function (err, results) { alert(results[0].label); }); } </script> </head> <body> <center> <h1 style=\"color: green;\">GeeksforGeeks</h1> <b> Image Classification using Javascript </b> </br> <img src=\"\" alt=\"\" id=\"image\" width=\"315px\" height=\"200px\" /> </br></br> <input type=\"file\" accept=\"image/*\" onchange=\"loadFile(event)\" name=\"image\" id=\"file\" /> <button onclick=\"predict()\">Predict</button> </center> </body></html>",
"e": 32773,
"s": 31346,
"text": null
},
{
"code": null,
"e": 32781,
"s": 32773,
"text": "Output:"
},
{
"code": null,
"e": 32788,
"s": 32781,
"text": "ml5.js"
},
{
"code": null,
"e": 32799,
"s": 32788,
"text": "JavaScript"
},
{
"code": null,
"e": 32816,
"s": 32799,
"text": "Web Technologies"
},
{
"code": null,
"e": 32843,
"s": 32816,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 32941,
"s": 32843,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32981,
"s": 32941,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33042,
"s": 32981,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33083,
"s": 33042,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 33105,
"s": 33083,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 33159,
"s": 33105,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 33199,
"s": 33159,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33232,
"s": 33199,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33275,
"s": 33232,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 33325,
"s": 33275,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Enum Classes in Kotlin - GeeksforGeeks | 11 Jul, 2019
In programming, sometimes there arises a need for a type to have only certain values. To accomplish this, the concept of enumeration was introduced. Enumeration is a named list of constants.In Kotlin, like many other programming languages, an enum has its own specialized type, indicating that something has a number of possible values. Unlike Java enums, Kotlin enums are classes.
Some important points about enum classes in kotlin –
Enum constants aren’t just mere collections of constants- these have properties, methods etc
Each of the enum constants acts as separate instances of the class and separated by commas.
Enums increases readability of your code by assigning pre-defined names to constants.
An instance of enum class cannot be created using constructors.
Enums are defined by using the enum keyword in front of class like this:-
enum class DAYS{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
In Kotlin also enums can have a constructor like Java enums. Since enum constants are instances of an Enum class, the constants can be initialized by passing specific values to the primary constructor.
Here is an example to specify colors to cards –
enum class Cards(val color: String) {
Diamond("black"),
Heart("red"),
}
We can easily access the color of a card using –
val color = Cards.Diamond.color
As in Java and in other programming languages, Kotlin enum classes has some inbuilt properties and functions which can be used by the programmer. Here’s a look at the major properties and methods.
Properties –
ordinal: This property stores the ordinal value of the constant, which is usually a zero-based index.name: This property stores the name of the constant.
ordinal: This property stores the ordinal value of the constant, which is usually a zero-based index.
name: This property stores the name of the constant.
Methods –
values: This method returns a list of all the constants defined within the enum class.valueOf: This methods returns the enum constant defined in enum, matching the input string. If the constant, is not present in the enum, then an IllegalArgumentException is thrown.
values: This method returns a list of all the constants defined within the enum class.
valueOf: This methods returns the enum constant defined in enum, matching the input string. If the constant, is not present in the enum, then an IllegalArgumentException is thrown.
Example to demonstrate enum class in Kotlin –
enum class DAYS { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}fun main(){ // A simple demonstration of properties and methods for (day in DAYS.values()) { println("${day.ordinal} = ${day.name}") } println("${DAYS.valueOf(" WEDNESDAY ")}")}
Output:
0 = SUNDAY
1 = MONDAY
2 = TUESDAY
3 = WEDNESDAY
4 = THURSDAY
5 = FRIDAY
6 = SATURDAY
WEDNESDAY
Since enum class in Kotlin, defines a new type. This class type can have its own properties and functions. The properties can be given a default value, however, if not provided, then each constant should define its own value for the property. In the case of functions, they are usually defined within the companion objects so that they do not depend on specific instances of the class. However, they can be defined without companion objects also.
Example to demonstrate properties and functions in Kotlin
// A property with default value providedenum class DAYS(val isWeekend: Boolean = false){ SUNDAY(true), MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, // Default value overridden SATURDAY(true); companion object{ fun today(obj: DAYS): Boolean { return obj.name.compareTo("SATURDAY") == 0 || obj.name.compareTo("SUNDAY") == 0 } }} fun main(){ // A simple demonstration of properties and methods for(day in DAYS.values()) { println("${day.ordinal} = ${day.name} and is weekend ${day.isWeekend}") } val today = DAYS.MONDAY; println("Is today a weekend ${DAYS.today(today)}")}
Output:
0 = SUNDAY and is weekend true
1 = MONDAY and is weekend false
2 = TUESDAY and is weekend false
3 = WEDNESDAY and is weekend false
4 = THURSDAY and is weekend false
5 = FRIDAY and is weekend false
6 = SATURDAY and is weekend true
Is today a weekend false
Enum constants also behaves as anonymous classes by implementing their own functions along with overriding the abstract functions of the class. The most important thing is that each enum constant must be override.
// defining enum classenum class Seasons(var weather: String) { Summer("hot"){ // compile time error if not override the function foo() override fun foo() { println("Hot days of a year") } }, Winter("cold"){ override fun foo() { println("Cold days of a year") } }, Rainy("moderate"){ override fun foo() { println("Rainy days of a year") } }; abstract fun foo()}// main functionfun main(args: Array<String>) { // calling foo() function override be Summer constant Seasons.Summer.foo() }
Output:
Hot days of a year
A great advantage of enum classes in Kotlin comes into play when they are combined with the when expression. The advantage is since enum classes restrict the value a type can take, so when used with the when expression and the definition for all the constants are provided, then the need of the else clause is completely eliminated. In fact, doing so will generate a warning from the compiler.
enum class DAYS{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;} fun main(){ when(DAYS.SUNDAY){ DAYS.SUNDAY -> println("Today is Sunday") DAYS.MONDAY -> println("Today is Monday") DAYS.TUESDAY -> println("Today is Tuesday") DAYS.WEDNESDAY -> println("Today is Wednesday") DAYS.THURSDAY -> println("Today is Thursday") DAYS.FRIDAY -> println("Today is Friday") DAYS.SATURDAY -> println("Today is Saturday") // Adding an else clause will generate a warning }}
Output:
Today is Sunday
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
How to Add and Customize Back Button of Action Bar in Android?
How to Get Current Location in Android?
Kotlin Android Tutorial
How to Change the Color of Status Bar in an Android App?
Kotlin when expression
Kotlin Higher-Order Functions | [
{
"code": null,
"e": 25147,
"s": 25119,
"text": "\n11 Jul, 2019"
},
{
"code": null,
"e": 25529,
"s": 25147,
"text": "In programming, sometimes there arises a need for a type to have only certain values. To accomplish this, the concept of enumeration was introduced. Enumeration is a named list of constants.In Kotlin, like many other programming languages, an enum has its own specialized type, indicating that something has a number of possible values. Unlike Java enums, Kotlin enums are classes."
},
{
"code": null,
"e": 25582,
"s": 25529,
"text": "Some important points about enum classes in kotlin –"
},
{
"code": null,
"e": 25675,
"s": 25582,
"text": "Enum constants aren’t just mere collections of constants- these have properties, methods etc"
},
{
"code": null,
"e": 25767,
"s": 25675,
"text": "Each of the enum constants acts as separate instances of the class and separated by commas."
},
{
"code": null,
"e": 25853,
"s": 25767,
"text": "Enums increases readability of your code by assigning pre-defined names to constants."
},
{
"code": null,
"e": 25917,
"s": 25853,
"text": "An instance of enum class cannot be created using constructors."
},
{
"code": null,
"e": 25991,
"s": 25917,
"text": "Enums are defined by using the enum keyword in front of class like this:-"
},
{
"code": null,
"e": 26088,
"s": 25991,
"text": "enum class DAYS{\n SUNDAY,\n MONDAY,\n TUESDAY,\n WEDNESDAY,\n THURSDAY,\n FRIDAY,\n SATURDAY\n}\n"
},
{
"code": null,
"e": 26290,
"s": 26088,
"text": "In Kotlin also enums can have a constructor like Java enums. Since enum constants are instances of an Enum class, the constants can be initialized by passing specific values to the primary constructor."
},
{
"code": null,
"e": 26338,
"s": 26290,
"text": "Here is an example to specify colors to cards –"
},
{
"code": null,
"e": 26419,
"s": 26338,
"text": "enum class Cards(val color: String) {\n Diamond(\"black\"),\n Heart(\"red\"),\n}\n"
},
{
"code": null,
"e": 26468,
"s": 26419,
"text": "We can easily access the color of a card using –"
},
{
"code": null,
"e": 26500,
"s": 26468,
"text": "val color = Cards.Diamond.color"
},
{
"code": null,
"e": 26697,
"s": 26500,
"text": "As in Java and in other programming languages, Kotlin enum classes has some inbuilt properties and functions which can be used by the programmer. Here’s a look at the major properties and methods."
},
{
"code": null,
"e": 26710,
"s": 26697,
"text": "Properties –"
},
{
"code": null,
"e": 26864,
"s": 26710,
"text": "ordinal: This property stores the ordinal value of the constant, which is usually a zero-based index.name: This property stores the name of the constant."
},
{
"code": null,
"e": 26966,
"s": 26864,
"text": "ordinal: This property stores the ordinal value of the constant, which is usually a zero-based index."
},
{
"code": null,
"e": 27019,
"s": 26966,
"text": "name: This property stores the name of the constant."
},
{
"code": null,
"e": 27029,
"s": 27019,
"text": "Methods –"
},
{
"code": null,
"e": 27296,
"s": 27029,
"text": "values: This method returns a list of all the constants defined within the enum class.valueOf: This methods returns the enum constant defined in enum, matching the input string. If the constant, is not present in the enum, then an IllegalArgumentException is thrown."
},
{
"code": null,
"e": 27383,
"s": 27296,
"text": "values: This method returns a list of all the constants defined within the enum class."
},
{
"code": null,
"e": 27564,
"s": 27383,
"text": "valueOf: This methods returns the enum constant defined in enum, matching the input string. If the constant, is not present in the enum, then an IllegalArgumentException is thrown."
},
{
"code": null,
"e": 27610,
"s": 27564,
"text": "Example to demonstrate enum class in Kotlin –"
},
{
"code": "enum class DAYS { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}fun main(){ // A simple demonstration of properties and methods for (day in DAYS.values()) { println(\"${day.ordinal} = ${day.name}\") } println(\"${DAYS.valueOf(\" WEDNESDAY \")}\")}",
"e": 27909,
"s": 27610,
"text": null
},
{
"code": null,
"e": 27917,
"s": 27909,
"text": "Output:"
},
{
"code": null,
"e": 28013,
"s": 27917,
"text": "0 = SUNDAY\n1 = MONDAY\n2 = TUESDAY\n3 = WEDNESDAY\n4 = THURSDAY\n5 = FRIDAY\n6 = SATURDAY\nWEDNESDAY\n"
},
{
"code": null,
"e": 28460,
"s": 28013,
"text": "Since enum class in Kotlin, defines a new type. This class type can have its own properties and functions. The properties can be given a default value, however, if not provided, then each constant should define its own value for the property. In the case of functions, they are usually defined within the companion objects so that they do not depend on specific instances of the class. However, they can be defined without companion objects also."
},
{
"code": null,
"e": 28518,
"s": 28460,
"text": "Example to demonstrate properties and functions in Kotlin"
},
{
"code": "// A property with default value providedenum class DAYS(val isWeekend: Boolean = false){ SUNDAY(true), MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, // Default value overridden SATURDAY(true); companion object{ fun today(obj: DAYS): Boolean { return obj.name.compareTo(\"SATURDAY\") == 0 || obj.name.compareTo(\"SUNDAY\") == 0 } }} fun main(){ // A simple demonstration of properties and methods for(day in DAYS.values()) { println(\"${day.ordinal} = ${day.name} and is weekend ${day.isWeekend}\") } val today = DAYS.MONDAY; println(\"Is today a weekend ${DAYS.today(today)}\")}",
"e": 29172,
"s": 28518,
"text": null
},
{
"code": null,
"e": 29180,
"s": 29172,
"text": "Output:"
},
{
"code": null,
"e": 29436,
"s": 29180,
"text": "0 = SUNDAY and is weekend true\n1 = MONDAY and is weekend false\n2 = TUESDAY and is weekend false\n3 = WEDNESDAY and is weekend false\n4 = THURSDAY and is weekend false\n5 = FRIDAY and is weekend false\n6 = SATURDAY and is weekend true\nIs today a weekend false\n"
},
{
"code": null,
"e": 29650,
"s": 29436,
"text": "Enum constants also behaves as anonymous classes by implementing their own functions along with overriding the abstract functions of the class. The most important thing is that each enum constant must be override."
},
{
"code": "// defining enum classenum class Seasons(var weather: String) { Summer(\"hot\"){ // compile time error if not override the function foo() override fun foo() { println(\"Hot days of a year\") } }, Winter(\"cold\"){ override fun foo() { println(\"Cold days of a year\") } }, Rainy(\"moderate\"){ override fun foo() { println(\"Rainy days of a year\") } }; abstract fun foo()}// main functionfun main(args: Array<String>) { // calling foo() function override be Summer constant Seasons.Summer.foo() }",
"e": 30259,
"s": 29650,
"text": null
},
{
"code": null,
"e": 30267,
"s": 30259,
"text": "Output:"
},
{
"code": null,
"e": 30286,
"s": 30267,
"text": "Hot days of a year"
},
{
"code": null,
"e": 30680,
"s": 30286,
"text": "A great advantage of enum classes in Kotlin comes into play when they are combined with the when expression. The advantage is since enum classes restrict the value a type can take, so when used with the when expression and the definition for all the constants are provided, then the need of the else clause is completely eliminated. In fact, doing so will generate a warning from the compiler."
},
{
"code": "enum class DAYS{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;} fun main(){ when(DAYS.SUNDAY){ DAYS.SUNDAY -> println(\"Today is Sunday\") DAYS.MONDAY -> println(\"Today is Monday\") DAYS.TUESDAY -> println(\"Today is Tuesday\") DAYS.WEDNESDAY -> println(\"Today is Wednesday\") DAYS.THURSDAY -> println(\"Today is Thursday\") DAYS.FRIDAY -> println(\"Today is Friday\") DAYS.SATURDAY -> println(\"Today is Saturday\") // Adding an else clause will generate a warning }}",
"e": 31240,
"s": 30680,
"text": null
},
{
"code": null,
"e": 31248,
"s": 31240,
"text": "Output:"
},
{
"code": null,
"e": 31265,
"s": 31248,
"text": "Today is Sunday\n"
},
{
"code": null,
"e": 31272,
"s": 31265,
"text": "Kotlin"
},
{
"code": null,
"e": 31370,
"s": 31272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31413,
"s": 31370,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 31444,
"s": 31413,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 31486,
"s": 31444,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 31528,
"s": 31486,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31591,
"s": 31528,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 31631,
"s": 31591,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 31655,
"s": 31631,
"text": "Kotlin Android Tutorial"
},
{
"code": null,
"e": 31712,
"s": 31655,
"text": "How to Change the Color of Status Bar in an Android App?"
},
{
"code": null,
"e": 31735,
"s": 31712,
"text": "Kotlin when expression"
}
]
|
Python - Consecutive Alphabetic Occurrence - GeeksforGeeks | 22 Apr, 2020
Sometimes, while working with Strings, we can have a problem in which we need to check whether we can find occurrence of characters consecutive and according to English alphabets. This kind of problem can occur in school programming and day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + ascii_letters + zip()The combination of above methods can be used to perform this task. In this, we extract the English alphabets using ascii_letters and check for consecution using zip().
# Python3 code to demonstrate working of # Consecutive Alphabetic Occurrence# Using loop + ascii_letters + zip()from string import ascii_letters # initializing stringtest_str = 'geeksforgeeks is best fgr geeks' # printing original stringprint("The original string is : " + str(test_str)) # Consecutive Alphabetic Occurrence# Using loop + ascii_letters + zip()res = []for i, j in zip(ascii_letters, ascii_letters[1:]) : if i + j in test_str: res.append((i, j)) # printing result print("The Consecutive matching letter pairs : " + str(res))
The original string is : geeksforgeeks is best fgr geeksThe Consecutive matching letter pairs : [(‘f’, ‘g’), (‘s’, ‘t’)]
Method #2 : Using list comprehension + ascii_letters + zip()The combination of above methods can be used to perform this task. In this, we perform similar way as above just in one-liner shortened way using list comprehension.
# Python3 code to demonstrate working of # Consecutive Alphabetic Occurrence# Using list comprehension + ascii_letters + zip()from string import ascii_letters # initializing stringtest_str = 'geeksforgeeks is best fgr geeks' # printing original stringprint("The original string is : " + str(test_str)) # Consecutive Alphabetic Occurrence# Using list comprehension + ascii_letters + zip()res = [(i, j) for i, j in zip(ascii_letters, ascii_letters[1:]) if i + j in test_str] # printing result print("The Consecutive matching letter pairs : " + str(res))
The original string is : geeksforgeeks is best fgr geeks
The Consecutive matching letter pairs : [('f', 'g'), ('s', 't')]
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
sum() function in Python
Enumerate() in Python
Defaultdict in Python
Python Dictionary
Read a file line by line in Python
Defaultdict in Python
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python Program for Binary Search (Recursive and Iterative) | [
{
"code": null,
"e": 26307,
"s": 26279,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 26628,
"s": 26307,
"text": "Sometimes, while working with Strings, we can have a problem in which we need to check whether we can find occurrence of characters consecutive and according to English alphabets. This kind of problem can occur in school programming and day-day programming. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26842,
"s": 26628,
"text": "Method #1 : Using loop + ascii_letters + zip()The combination of above methods can be used to perform this task. In this, we extract the English alphabets using ascii_letters and check for consecution using zip()."
},
{
"code": "# Python3 code to demonstrate working of # Consecutive Alphabetic Occurrence# Using loop + ascii_letters + zip()from string import ascii_letters # initializing stringtest_str = 'geeksforgeeks is best fgr geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Consecutive Alphabetic Occurrence# Using loop + ascii_letters + zip()res = []for i, j in zip(ascii_letters, ascii_letters[1:]) : if i + j in test_str: res.append((i, j)) # printing result print(\"The Consecutive matching letter pairs : \" + str(res)) ",
"e": 27396,
"s": 26842,
"text": null
},
{
"code": null,
"e": 27517,
"s": 27396,
"text": "The original string is : geeksforgeeks is best fgr geeksThe Consecutive matching letter pairs : [(‘f’, ‘g’), (‘s’, ‘t’)]"
},
{
"code": null,
"e": 27745,
"s": 27519,
"text": "Method #2 : Using list comprehension + ascii_letters + zip()The combination of above methods can be used to perform this task. In this, we perform similar way as above just in one-liner shortened way using list comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Consecutive Alphabetic Occurrence# Using list comprehension + ascii_letters + zip()from string import ascii_letters # initializing stringtest_str = 'geeksforgeeks is best fgr geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # Consecutive Alphabetic Occurrence# Using list comprehension + ascii_letters + zip()res = [(i, j) for i, j in zip(ascii_letters, ascii_letters[1:]) if i + j in test_str] # printing result print(\"The Consecutive matching letter pairs : \" + str(res)) ",
"e": 28308,
"s": 27745,
"text": null
},
{
"code": null,
"e": 28431,
"s": 28308,
"text": "The original string is : geeksforgeeks is best fgr geeks\nThe Consecutive matching letter pairs : [('f', 'g'), ('s', 't')]\n"
},
{
"code": null,
"e": 28454,
"s": 28431,
"text": "Python string-programs"
},
{
"code": null,
"e": 28461,
"s": 28454,
"text": "Python"
},
{
"code": null,
"e": 28477,
"s": 28461,
"text": "Python Programs"
},
{
"code": null,
"e": 28575,
"s": 28477,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28600,
"s": 28575,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28622,
"s": 28600,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28644,
"s": 28622,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28662,
"s": 28644,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28697,
"s": 28662,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28719,
"s": 28697,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28762,
"s": 28719,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28801,
"s": 28762,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28847,
"s": 28801,
"text": "Python | Split string into list of characters"
}
]
|
How to Get Current Location in Android? - GeeksforGeeks | 19 Sep, 2021
As a developer when you work on locations in Android then you always have some doubts about selecting the best and efficient approach for your requirement. So in this article, we are going to discuss how to get the user’s current location in Android. There are two ways to get the current location of any Android device:
Android’s Location Manager APIFused Location Provider: Google Play Services Location APIs
Android’s Location Manager API
Fused Location Provider: Google Play Services Location APIs
Question: Which one is efficient and why?
Answer: Fused Location Provider because it optimizes the device’s use of battery power.
Before moving any of the above methods we will have to take location permission.
Step 1: Define uses permissions for location access in the manifest file
<!– To request foreground location access, declare one of these permissions. –>
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />
<!– Required only when requesting background location access on Android 10 (API level 29) –>
<uses-permission android:name=”android.permission.ACCESS_BACKGROUND_LOCATION” />
Note:
In order to receive location updates from NETWORK_PROVIDER or GPS_PROVIDER, you must request the user’s permission by declaring either the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission, respectively, in your Android manifest file. Without these permissions, your application will fail at runtime when requesting location updates.
If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. Permission for ACCESS_COARSE_LOCATION allows access only to NETWORK_PROVIDER.
Step 2: Define uses permission for internet access because we are going to use Internet Provider.
<uses-permission android:name=”android.permission.INTERNET”/>
Step 3: Write a function for checking that location permission is granted or not. If permission is not granted then ask for the permissions in run time.
Kotlin
private fun isLocationPermissionGranted(): Boolean { return if (ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf( android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION ), requestcode ) false } else { true }}
Now after handling location permissions, we are going to learn how can we get the location in android.
We assume that the user has been granted Location Permission. If not then ask first.
Step 1: Creating an instance of LocationManager in the context of LOCATION_SERVICE.
Kotlin
private var currentLocation: Location? = nulllateinit var locationManager: LocationManagerlocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
Step 2: Check that if the GPS and Network are available or not and if both are available then we use one with greater accuracy.
Kotlin
val hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)//------------------------------------------------------//val hasNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
Step 3: Creating an instance of LocationListener (package: android.location) for both(GPS and Network).
Kotlin
val gpsLocationListener: LocationListener = object : LocationListener { override fun onLocationChanged(location: Location) { locationByGps= location } override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {} override fun onProviderEnabled(provider: String) {} override fun onProviderDisabled(provider: String) {}}//------------------------------------------------------//val networkLocationListener: LocationListener = object : LocationListener { override fun onLocationChanged(location: Location) { locationByNetwork= location } override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {} override fun onProviderEnabled(provider: String) {} override fun onProviderDisabled(provider: String) {}}
Step 4: If any of the GPS or Network providers is enabled then we will request a current location update from the LocationManager with LocationListener.
Kotlin
if (hasGps) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 0F, gpsLocationListener )}//------------------------------------------------------//if (hasNetwork) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 0F, networkLocationListener )}
Step 5: Now we check which provider has given us the more accurate location and then we will use that location as per our requirement.
Kotlin
val lastKnownLocationByGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)lastKnownLocationByGps?.let { locationByGps = lastKnownLocationByGps}//------------------------------------------------------//val lastKnownLocationByNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)lastKnownLocationByNetwork?.let { locationByNetwork = lastKnownLocationByNetwork}//------------------------------------------------------//if (locationByGps != null && locationByNetwork != null) { if (locationByGps.accuracy > locationByNetwork!!.accuracy) { currentLocation = locationByGps latitude = currentLocation.latitude longitude = currentLocation.longitude // use latitude and longitude as per your need } else { currentLocation = locationByNetwork latitude = currentLocation.latitude longitude = currentLocation.longitude // use latitude and longitude as per your need }}
Now after learning how can we get the location in android by Location Manager API, we are moving to the second method Fused Location Provider (Google Play Services Location APIs).
We assume that the user has been granted Location Permission. If not then ask first. Fused Location Provider is the Google Play services location APIs. It provides a simple API for getting locations with high, medium, and low accuracy. It also optimizes the device’s use of battery power. So we should prefer this method.
Step 1: Declare variables of FusedLocationProviderClient, LocationRequest, LocationCallback and Location.
Kotlin
// FusedLocationProviderClient - Main class for receiving location updates.private lateinit var fusedLocationProviderClient: FusedLocationProviderClient // LocationRequest - Requirements for the location updates, i.e.,// how often you should receive updates, the priority, etc.private lateinit var locationRequest: LocationRequest // LocationCallback - Called when FusedLocationProviderClient// has a new Locationprivate lateinit var locationCallback: LocationCallback // This will store current location infoprivate var currentLocation: Location? = null
Step 2: Initialize fusedLocationProviderClient.
Kotlin
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
Step 3: Initialize locationRequest.
Kotlin
locationRequest = LocationRequest().apply { // Sets the desired interval for // active location updates. // This interval is inexact. interval = TimeUnit.SECONDS.toMillis(60) // Sets the fastest rate for active location updates. // This interval is exact, and your application will never // receive updates more frequently than this value fastestInterval = TimeUnit.SECONDS.toMillis(30) // Sets the maximum time when batched location // updates are delivered. Updates may be // delivered sooner than this interval maxWaitTime = TimeUnit.MINUTES.toMillis(2) priority = LocationRequest.PRIORITY_HIGH_ACCURACY}
Step 4: Initialize locationCallback.
Kotlin
locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult?) { super.onLocationResult(locationResult) locationResult?.lastLocation?.let { currentLocation = locationByGps latitude = currentLocation.latitude longitude = currentLocation.longitude // use latitude and longitude as per your need } ?: { Log.d(TAG, "Location information isn't available.") } }}
Step 5: Now that you initialized everything, you need to let the FusedLocationProviderClient know that you want to receive updates. So Subscribe to location changes.
Kotlin
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
Step 6: When the app no longer needs access to location information, it’s important to unsubscribe from location updates.
Kotlin
val removeTask = fusedLocationProviderClient.removeLocationUpdates(locationCallback)removeTask.addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Location Callback removed.") } else { Log.d(TAG, "Failed to remove Location Callback.") }}
Now one more important point to give support for Android 10 and Android R. So Let’s talk about it...
Step 1: Make these changes in build.gradle file.
Set compileSdkVersion to 29.Set buildToolsVersion to “29.0.3”.Set targetSdkVersion to 29.
Set compileSdkVersion to 29.
Set buildToolsVersion to “29.0.3”.
Set targetSdkVersion to 29.
Your code should look something like this:
android {
compileSdkVersion 29
buildToolsVersion “29.0.3”
defaultConfig {
applicationId “com.example.android.location”
minSdkVersion 26
targetSdkVersion 29
versionCode 1
versionName “1.0”
}
...
}
Step 2: If you have a foreground service, declare a foregroundServiceType of location in the manifest.
android:foregroundServiceType=”location”
Your code should look something like this:
<application>
...
<!– Foreground services in Android 10+ require type. –>
<service
android:name=”com.example.android.location.ForegroundOnlyLocationService”
android:enabled=”true”
android:exported=”false”
android:foregroundServiceType=”location” />
</application>
Great news, you don’t need to make changes to any files except for the build.gradle file! Make these changes:
compileSdkVersion to “android-R”targetSdkVersion to “R”
compileSdkVersion to “android-R”
targetSdkVersion to “R”
Your code should look something like this:
android {
compileSdkVersion “android-R”
buildToolsVersion “29.0.2”
defaultConfig {
applicationId “com.example.android.location”
minSdkVersion 26
targetSdkVersion “R”
versionCode 1
versionName “1.0”
}
...
}
Blogathon-2021
Android
Blogathon
How To
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Call or Consume External API in Spring Boot?
How to Create a Table With Multiple Foreign Keys in SQL?
Re-rendering Components in ReactJS
Python NOT EQUAL operator
SQL Query to Insert Multiple Rows | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n19 Sep, 2021"
},
{
"code": null,
"e": 26702,
"s": 26381,
"text": "As a developer when you work on locations in Android then you always have some doubts about selecting the best and efficient approach for your requirement. So in this article, we are going to discuss how to get the user’s current location in Android. There are two ways to get the current location of any Android device:"
},
{
"code": null,
"e": 26792,
"s": 26702,
"text": "Android’s Location Manager APIFused Location Provider: Google Play Services Location APIs"
},
{
"code": null,
"e": 26823,
"s": 26792,
"text": "Android’s Location Manager API"
},
{
"code": null,
"e": 26883,
"s": 26823,
"text": "Fused Location Provider: Google Play Services Location APIs"
},
{
"code": null,
"e": 26925,
"s": 26883,
"text": "Question: Which one is efficient and why?"
},
{
"code": null,
"e": 27013,
"s": 26925,
"text": "Answer: Fused Location Provider because it optimizes the device’s use of battery power."
},
{
"code": null,
"e": 27094,
"s": 27013,
"text": "Before moving any of the above methods we will have to take location permission."
},
{
"code": null,
"e": 27167,
"s": 27094,
"text": "Step 1: Define uses permissions for location access in the manifest file"
},
{
"code": null,
"e": 27247,
"s": 27167,
"text": "<!– To request foreground location access, declare one of these permissions. –>"
},
{
"code": null,
"e": 27322,
"s": 27247,
"text": "<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />"
},
{
"code": null,
"e": 27399,
"s": 27322,
"text": "<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />"
},
{
"code": null,
"e": 27492,
"s": 27399,
"text": "<!– Required only when requesting background location access on Android 10 (API level 29) –>"
},
{
"code": null,
"e": 27573,
"s": 27492,
"text": "<uses-permission android:name=”android.permission.ACCESS_BACKGROUND_LOCATION” />"
},
{
"code": null,
"e": 27579,
"s": 27573,
"text": "Note:"
},
{
"code": null,
"e": 27921,
"s": 27579,
"text": "In order to receive location updates from NETWORK_PROVIDER or GPS_PROVIDER, you must request the user’s permission by declaring either the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission, respectively, in your Android manifest file. Without these permissions, your application will fail at runtime when requesting location updates."
},
{
"code": null,
"e": 28174,
"s": 27921,
"text": "If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. Permission for ACCESS_COARSE_LOCATION allows access only to NETWORK_PROVIDER."
},
{
"code": null,
"e": 28272,
"s": 28174,
"text": "Step 2: Define uses permission for internet access because we are going to use Internet Provider."
},
{
"code": null,
"e": 28334,
"s": 28272,
"text": "<uses-permission android:name=”android.permission.INTERNET”/>"
},
{
"code": null,
"e": 28487,
"s": 28334,
"text": "Step 3: Write a function for checking that location permission is granted or not. If permission is not granted then ask for the permissions in run time."
},
{
"code": null,
"e": 28494,
"s": 28487,
"text": "Kotlin"
},
{
"code": "private fun isLocationPermissionGranted(): Boolean { return if (ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf( android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION ), requestcode ) false } else { true }}",
"e": 29190,
"s": 28494,
"text": null
},
{
"code": null,
"e": 29293,
"s": 29190,
"text": "Now after handling location permissions, we are going to learn how can we get the location in android."
},
{
"code": null,
"e": 29378,
"s": 29293,
"text": "We assume that the user has been granted Location Permission. If not then ask first."
},
{
"code": null,
"e": 29462,
"s": 29378,
"text": "Step 1: Creating an instance of LocationManager in the context of LOCATION_SERVICE."
},
{
"code": null,
"e": 29469,
"s": 29462,
"text": "Kotlin"
},
{
"code": "private var currentLocation: Location? = nulllateinit var locationManager: LocationManagerlocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager",
"e": 29639,
"s": 29469,
"text": null
},
{
"code": null,
"e": 29767,
"s": 29639,
"text": "Step 2: Check that if the GPS and Network are available or not and if both are available then we use one with greater accuracy."
},
{
"code": null,
"e": 29774,
"s": 29767,
"text": "Kotlin"
},
{
"code": "val hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)//------------------------------------------------------//val hasNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)",
"e": 29993,
"s": 29774,
"text": null
},
{
"code": null,
"e": 30097,
"s": 29993,
"text": "Step 3: Creating an instance of LocationListener (package: android.location) for both(GPS and Network)."
},
{
"code": null,
"e": 30104,
"s": 30097,
"text": "Kotlin"
},
{
"code": "val gpsLocationListener: LocationListener = object : LocationListener { override fun onLocationChanged(location: Location) { locationByGps= location } override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {} override fun onProviderEnabled(provider: String) {} override fun onProviderDisabled(provider: String) {}}//------------------------------------------------------//val networkLocationListener: LocationListener = object : LocationListener { override fun onLocationChanged(location: Location) { locationByNetwork= location } override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {} override fun onProviderEnabled(provider: String) {} override fun onProviderDisabled(provider: String) {}}",
"e": 30889,
"s": 30104,
"text": null
},
{
"code": null,
"e": 31042,
"s": 30889,
"text": "Step 4: If any of the GPS or Network providers is enabled then we will request a current location update from the LocationManager with LocationListener."
},
{
"code": null,
"e": 31049,
"s": 31042,
"text": "Kotlin"
},
{
"code": "if (hasGps) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 0F, gpsLocationListener )}//------------------------------------------------------//if (hasNetwork) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 0F, networkLocationListener )}",
"e": 31420,
"s": 31049,
"text": null
},
{
"code": null,
"e": 31555,
"s": 31420,
"text": "Step 5: Now we check which provider has given us the more accurate location and then we will use that location as per our requirement."
},
{
"code": null,
"e": 31562,
"s": 31555,
"text": "Kotlin"
},
{
"code": "val lastKnownLocationByGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)lastKnownLocationByGps?.let { locationByGps = lastKnownLocationByGps}//------------------------------------------------------//val lastKnownLocationByNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)lastKnownLocationByNetwork?.let { locationByNetwork = lastKnownLocationByNetwork}//------------------------------------------------------//if (locationByGps != null && locationByNetwork != null) { if (locationByGps.accuracy > locationByNetwork!!.accuracy) { currentLocation = locationByGps latitude = currentLocation.latitude longitude = currentLocation.longitude // use latitude and longitude as per your need } else { currentLocation = locationByNetwork latitude = currentLocation.latitude longitude = currentLocation.longitude // use latitude and longitude as per your need }}",
"e": 32540,
"s": 31562,
"text": null
},
{
"code": null,
"e": 32720,
"s": 32540,
"text": "Now after learning how can we get the location in android by Location Manager API, we are moving to the second method Fused Location Provider (Google Play Services Location APIs)."
},
{
"code": null,
"e": 33042,
"s": 32720,
"text": "We assume that the user has been granted Location Permission. If not then ask first. Fused Location Provider is the Google Play services location APIs. It provides a simple API for getting locations with high, medium, and low accuracy. It also optimizes the device’s use of battery power. So we should prefer this method."
},
{
"code": null,
"e": 33148,
"s": 33042,
"text": "Step 1: Declare variables of FusedLocationProviderClient, LocationRequest, LocationCallback and Location."
},
{
"code": null,
"e": 33155,
"s": 33148,
"text": "Kotlin"
},
{
"code": "// FusedLocationProviderClient - Main class for receiving location updates.private lateinit var fusedLocationProviderClient: FusedLocationProviderClient // LocationRequest - Requirements for the location updates, i.e.,// how often you should receive updates, the priority, etc.private lateinit var locationRequest: LocationRequest // LocationCallback - Called when FusedLocationProviderClient// has a new Locationprivate lateinit var locationCallback: LocationCallback // This will store current location infoprivate var currentLocation: Location? = null",
"e": 33713,
"s": 33155,
"text": null
},
{
"code": null,
"e": 33761,
"s": 33713,
"text": "Step 2: Initialize fusedLocationProviderClient."
},
{
"code": null,
"e": 33768,
"s": 33761,
"text": "Kotlin"
},
{
"code": "fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)",
"e": 33852,
"s": 33768,
"text": null
},
{
"code": null,
"e": 33888,
"s": 33852,
"text": "Step 3: Initialize locationRequest."
},
{
"code": null,
"e": 33895,
"s": 33888,
"text": "Kotlin"
},
{
"code": "locationRequest = LocationRequest().apply { // Sets the desired interval for // active location updates. // This interval is inexact. interval = TimeUnit.SECONDS.toMillis(60) // Sets the fastest rate for active location updates. // This interval is exact, and your application will never // receive updates more frequently than this value fastestInterval = TimeUnit.SECONDS.toMillis(30) // Sets the maximum time when batched location // updates are delivered. Updates may be // delivered sooner than this interval maxWaitTime = TimeUnit.MINUTES.toMillis(2) priority = LocationRequest.PRIORITY_HIGH_ACCURACY}",
"e": 34562,
"s": 33895,
"text": null
},
{
"code": null,
"e": 34599,
"s": 34562,
"text": "Step 4: Initialize locationCallback."
},
{
"code": null,
"e": 34606,
"s": 34599,
"text": "Kotlin"
},
{
"code": "locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult?) { super.onLocationResult(locationResult) locationResult?.lastLocation?.let { currentLocation = locationByGps latitude = currentLocation.latitude longitude = currentLocation.longitude // use latitude and longitude as per your need } ?: { Log.d(TAG, \"Location information isn't available.\") } }}",
"e": 35101,
"s": 34606,
"text": null
},
{
"code": null,
"e": 35267,
"s": 35101,
"text": "Step 5: Now that you initialized everything, you need to let the FusedLocationProviderClient know that you want to receive updates. So Subscribe to location changes."
},
{
"code": null,
"e": 35274,
"s": 35267,
"text": "Kotlin"
},
{
"code": "fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())",
"e": 35379,
"s": 35274,
"text": null
},
{
"code": null,
"e": 35501,
"s": 35379,
"text": "Step 6: When the app no longer needs access to location information, it’s important to unsubscribe from location updates."
},
{
"code": null,
"e": 35508,
"s": 35501,
"text": "Kotlin"
},
{
"code": "val removeTask = fusedLocationProviderClient.removeLocationUpdates(locationCallback)removeTask.addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, \"Location Callback removed.\") } else { Log.d(TAG, \"Failed to remove Location Callback.\") }}",
"e": 35781,
"s": 35508,
"text": null
},
{
"code": null,
"e": 35882,
"s": 35781,
"text": "Now one more important point to give support for Android 10 and Android R. So Let’s talk about it..."
},
{
"code": null,
"e": 35931,
"s": 35882,
"text": "Step 1: Make these changes in build.gradle file."
},
{
"code": null,
"e": 36021,
"s": 35931,
"text": "Set compileSdkVersion to 29.Set buildToolsVersion to “29.0.3”.Set targetSdkVersion to 29."
},
{
"code": null,
"e": 36050,
"s": 36021,
"text": "Set compileSdkVersion to 29."
},
{
"code": null,
"e": 36085,
"s": 36050,
"text": "Set buildToolsVersion to “29.0.3”."
},
{
"code": null,
"e": 36113,
"s": 36085,
"text": "Set targetSdkVersion to 29."
},
{
"code": null,
"e": 36156,
"s": 36113,
"text": "Your code should look something like this:"
},
{
"code": null,
"e": 36166,
"s": 36156,
"text": "android {"
},
{
"code": null,
"e": 36189,
"s": 36166,
"text": " compileSdkVersion 29"
},
{
"code": null,
"e": 36218,
"s": 36189,
"text": " buildToolsVersion “29.0.3”"
},
{
"code": null,
"e": 36236,
"s": 36218,
"text": " defaultConfig {"
},
{
"code": null,
"e": 36287,
"s": 36236,
"text": " applicationId “com.example.android.location”"
},
{
"code": null,
"e": 36310,
"s": 36287,
"text": " minSdkVersion 26"
},
{
"code": null,
"e": 36336,
"s": 36310,
"text": " targetSdkVersion 29"
},
{
"code": null,
"e": 36356,
"s": 36336,
"text": " versionCode 1"
},
{
"code": null,
"e": 36380,
"s": 36356,
"text": " versionName “1.0”"
},
{
"code": null,
"e": 36384,
"s": 36380,
"text": " }"
},
{
"code": null,
"e": 36388,
"s": 36384,
"text": "..."
},
{
"code": null,
"e": 36390,
"s": 36388,
"text": "}"
},
{
"code": null,
"e": 36493,
"s": 36390,
"text": "Step 2: If you have a foreground service, declare a foregroundServiceType of location in the manifest."
},
{
"code": null,
"e": 36534,
"s": 36493,
"text": "android:foregroundServiceType=”location”"
},
{
"code": null,
"e": 36577,
"s": 36534,
"text": "Your code should look something like this:"
},
{
"code": null,
"e": 36591,
"s": 36577,
"text": "<application>"
},
{
"code": null,
"e": 36598,
"s": 36591,
"text": " ..."
},
{
"code": null,
"e": 36657,
"s": 36598,
"text": " <!– Foreground services in Android 10+ require type. –>"
},
{
"code": null,
"e": 36669,
"s": 36657,
"text": " <service"
},
{
"code": null,
"e": 36743,
"s": 36669,
"text": "android:name=”com.example.android.location.ForegroundOnlyLocationService”"
},
{
"code": null,
"e": 36773,
"s": 36743,
"text": " android:enabled=”true”"
},
{
"code": null,
"e": 36805,
"s": 36773,
"text": " android:exported=”false”"
},
{
"code": null,
"e": 36856,
"s": 36805,
"text": " android:foregroundServiceType=”location” />"
},
{
"code": null,
"e": 36871,
"s": 36856,
"text": "</application>"
},
{
"code": null,
"e": 36981,
"s": 36871,
"text": "Great news, you don’t need to make changes to any files except for the build.gradle file! Make these changes:"
},
{
"code": null,
"e": 37037,
"s": 36981,
"text": "compileSdkVersion to “android-R”targetSdkVersion to “R”"
},
{
"code": null,
"e": 37070,
"s": 37037,
"text": "compileSdkVersion to “android-R”"
},
{
"code": null,
"e": 37094,
"s": 37070,
"text": "targetSdkVersion to “R”"
},
{
"code": null,
"e": 37137,
"s": 37094,
"text": "Your code should look something like this:"
},
{
"code": null,
"e": 37147,
"s": 37137,
"text": "android {"
},
{
"code": null,
"e": 37179,
"s": 37147,
"text": " compileSdkVersion “android-R”"
},
{
"code": null,
"e": 37208,
"s": 37179,
"text": " buildToolsVersion “29.0.2”"
},
{
"code": null,
"e": 37226,
"s": 37208,
"text": " defaultConfig {"
},
{
"code": null,
"e": 37277,
"s": 37226,
"text": " applicationId “com.example.android.location”"
},
{
"code": null,
"e": 37300,
"s": 37277,
"text": " minSdkVersion 26"
},
{
"code": null,
"e": 37327,
"s": 37300,
"text": " targetSdkVersion “R”"
},
{
"code": null,
"e": 37347,
"s": 37327,
"text": " versionCode 1"
},
{
"code": null,
"e": 37371,
"s": 37347,
"text": " versionName “1.0”"
},
{
"code": null,
"e": 37375,
"s": 37371,
"text": " }"
},
{
"code": null,
"e": 37379,
"s": 37375,
"text": "..."
},
{
"code": null,
"e": 37381,
"s": 37379,
"text": "}"
},
{
"code": null,
"e": 37396,
"s": 37381,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 37404,
"s": 37396,
"text": "Android"
},
{
"code": null,
"e": 37414,
"s": 37404,
"text": "Blogathon"
},
{
"code": null,
"e": 37421,
"s": 37414,
"text": "How To"
},
{
"code": null,
"e": 37428,
"s": 37421,
"text": "Kotlin"
},
{
"code": null,
"e": 37436,
"s": 37428,
"text": "Android"
},
{
"code": null,
"e": 37534,
"s": 37436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37572,
"s": 37534,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 37611,
"s": 37572,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 37661,
"s": 37611,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 37712,
"s": 37661,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 37754,
"s": 37712,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 37806,
"s": 37754,
"text": "How to Call or Consume External API in Spring Boot?"
},
{
"code": null,
"e": 37863,
"s": 37806,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 37898,
"s": 37863,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 37924,
"s": 37898,
"text": "Python NOT EQUAL operator"
}
]
|
Perl unlink Function | This function deletes the files specified by LIST, or the file specified by $_ otherwise. Be careful while using this function because there is no recovering once a file gets deleted.
Following is the simple syntax for this function −
unlink LIST
unlink
This function returns the number of files deleted.
Following is the example code showing its basic usage, create two files t1.txt and t2.txt in /tmp directory and then use the following program to delete these two files −
#!/usr/bin/perl -w
unlink( "/tmp/t1.txt", "/tmp/t2.txt" );
When above code is executed, it produces the following result −
Both the files t1.txt and t2.txt will be deleted from /tmp.
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2404,
"s": 2220,
"text": "This function deletes the files specified by LIST, or the file specified by $_ otherwise. Be careful while using this function because there is no recovering once a file gets deleted."
},
{
"code": null,
"e": 2455,
"s": 2404,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 2476,
"s": 2455,
"text": "unlink LIST\n\nunlink\n"
},
{
"code": null,
"e": 2527,
"s": 2476,
"text": "This function returns the number of files deleted."
},
{
"code": null,
"e": 2698,
"s": 2527,
"text": "Following is the example code showing its basic usage, create two files t1.txt and t2.txt in /tmp directory and then use the following program to delete these two files −"
},
{
"code": null,
"e": 2758,
"s": 2698,
"text": "#!/usr/bin/perl -w\n\nunlink( \"/tmp/t1.txt\", \"/tmp/t2.txt\" );"
},
{
"code": null,
"e": 2822,
"s": 2758,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2883,
"s": 2822,
"text": "Both the files t1.txt and t2.txt will be deleted from /tmp.\n"
},
{
"code": null,
"e": 2918,
"s": 2883,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2932,
"s": 2918,
"text": " Devi Killada"
},
{
"code": null,
"e": 2967,
"s": 2932,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2987,
"s": 2967,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3020,
"s": 2987,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3036,
"s": 3020,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3069,
"s": 3036,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3086,
"s": 3069,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3119,
"s": 3086,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3142,
"s": 3119,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3177,
"s": 3142,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3200,
"s": 3177,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3207,
"s": 3200,
"text": " Print"
},
{
"code": null,
"e": 3218,
"s": 3207,
"text": " Add Notes"
}
]
|
C# | Getting the value at the specified index of a SortedList object - GeeksforGeeks | 01 Feb, 2019
SortedList.GetByIndex(Int32) Method is used to get the value at the specified index of a SortedList object.
Syntax:
public virtual object GetByIndex (int index);
Here index is the zero-based index of the value to get.
Return Value: It returns the value at the specified index of the SortedList object.
Exception: This method will throw ArgumentOutOfRangeException if the index is outside the range of valid indexes for the SortedList object.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to get the value at the specified// index of a SortedList object.using System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("1", "C++"); mylist.Add("2", "Java"); mylist.Add("3", "DSA"); mylist.Add("4", "Python"); mylist.Add("5", "C#"); // getting the indexing and // store into a variable int i = 4; // getting the value at index 4 Console.WriteLine("Value at index {0} is {1}", i, mylist.GetByIndex(i)); }}
Output:
Value at index 4 is C#
Example 2:
// C# code to get the value at the specified// index of a SortedList object.using System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("First", "Ram"); mylist.Add("Second", "Shyam"); mylist.Add("Third", "Mohit"); mylist.Add("Fourth", "Rohit"); mylist.Add("Fifth", "Manish"); // getting the indexing and // store into a variable // it will give error as // index is out of range int i = 7; // getting the value at index 7 Console.WriteLine("Value at index {0} is {1}", i, mylist.GetByIndex(i)); }}
Runtime Error:
Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.getbyindex?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-SortedList
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
C# | List Class
Partial Classes in C#
Convert String to Character Array in C#
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24410,
"s": 24302,
"text": "SortedList.GetByIndex(Int32) Method is used to get the value at the specified index of a SortedList object."
},
{
"code": null,
"e": 24418,
"s": 24410,
"text": "Syntax:"
},
{
"code": null,
"e": 24464,
"s": 24418,
"text": "public virtual object GetByIndex (int index);"
},
{
"code": null,
"e": 24520,
"s": 24464,
"text": "Here index is the zero-based index of the value to get."
},
{
"code": null,
"e": 24604,
"s": 24520,
"text": "Return Value: It returns the value at the specified index of the SortedList object."
},
{
"code": null,
"e": 24744,
"s": 24604,
"text": "Exception: This method will throw ArgumentOutOfRangeException if the index is outside the range of valid indexes for the SortedList object."
},
{
"code": null,
"e": 24805,
"s": 24744,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 24816,
"s": 24805,
"text": "Example 1:"
},
{
"code": "// C# code to get the value at the specified// index of a SortedList object.using System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"1\", \"C++\"); mylist.Add(\"2\", \"Java\"); mylist.Add(\"3\", \"DSA\"); mylist.Add(\"4\", \"Python\"); mylist.Add(\"5\", \"C#\"); // getting the indexing and // store into a variable int i = 4; // getting the value at index 4 Console.WriteLine(\"Value at index {0} is {1}\", i, mylist.GetByIndex(i)); }}",
"e": 25543,
"s": 24816,
"text": null
},
{
"code": null,
"e": 25551,
"s": 25543,
"text": "Output:"
},
{
"code": null,
"e": 25575,
"s": 25551,
"text": "Value at index 4 is C#\n"
},
{
"code": null,
"e": 25586,
"s": 25575,
"text": "Example 2:"
},
{
"code": "// C# code to get the value at the specified// index of a SortedList object.using System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"First\", \"Ram\"); mylist.Add(\"Second\", \"Shyam\"); mylist.Add(\"Third\", \"Mohit\"); mylist.Add(\"Fourth\", \"Rohit\"); mylist.Add(\"Fifth\", \"Manish\"); // getting the indexing and // store into a variable // it will give error as // index is out of range int i = 7; // getting the value at index 7 Console.WriteLine(\"Value at index {0} is {1}\", i, mylist.GetByIndex(i)); }}",
"e": 26405,
"s": 25586,
"text": null
},
{
"code": null,
"e": 26420,
"s": 26405,
"text": "Runtime Error:"
},
{
"code": null,
"e": 26584,
"s": 26420,
"text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
},
{
"code": null,
"e": 26595,
"s": 26584,
"text": "Reference:"
},
{
"code": null,
"e": 26704,
"s": 26595,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.getbyindex?view=netframework-4.7.2"
},
{
"code": null,
"e": 26733,
"s": 26704,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 26763,
"s": 26733,
"text": "CSharp-Collections-SortedList"
},
{
"code": null,
"e": 26777,
"s": 26763,
"text": "CSharp-method"
},
{
"code": null,
"e": 26780,
"s": 26777,
"text": "C#"
},
{
"code": null,
"e": 26878,
"s": 26780,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26887,
"s": 26878,
"text": "Comments"
},
{
"code": null,
"e": 26900,
"s": 26887,
"text": "Old Comments"
},
{
"code": null,
"e": 26923,
"s": 26900,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26951,
"s": 26923,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26991,
"s": 26951,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27034,
"s": 26991,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27051,
"s": 27034,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27067,
"s": 27051,
"text": "C# | List Class"
},
{
"code": null,
"e": 27089,
"s": 27067,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27129,
"s": 27089,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27154,
"s": 27129,
"text": "Lambda Expressions in C#"
}
]
|
MySQL query to select records with a particular date and time? | You can use BETWEEN clause from MySQL to select records with a particular date and time. The syntax is as follows.
select *from AllRecordsFromadate where AdmissionDate between 'yourDateTimeValue1 ' and ''yourDateTimeValue2';
To understand the above syntax, let us first create a table. The query to create a table is as follows.
mysql> create table AllRecordsFromadate
-> (
-> Id int,
-> Name varchar(100),
-> Age int,
-> AdmissionDate datetime
-> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command. The query to insert records is as follows.
mysql> insert into AllRecordsFromadate values(101,'John',23,'2018-10-13');
Query OK, 1 row affected (0.18 sec)
mysql> insert into AllRecordsFromadate values(102,'Carol',24,'2014-12-5 12:34:50');
Query OK, 1 row affected (0.18 sec)
mysql> insert into AllRecordsFromadate values(103,'Mike',25,'2014-12-5 12:30:40');
Query OK, 1 row affected (0.23 sec)
mysql> insert into AllRecordsFromadate values(104,'Bob',24,'2015-10-7 11:10:20');
Query OK, 1 row affected (0.20 sec)
mysql> insert into AllRecordsFromadate values(105,'Sam',25,'2011-6-26 10:10:20');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select command. The query is as follows.
mysql> select *from AllRecordsFromadate;
The following is the output.
+------+-------+------+---------------------+
| Id | Name | Age | AdmissionDate |
+------+-------+------+---------------------+
| 101 | John | 23 | 2018-10-13 00:00:00 |
| 102 | Carol | 24 | 2014-12-05 12:34:50 |
| 103 | Mike | 25 | 2014-12-05 12:30:40 |
| 104 | Bob | 24 | 2015-10-07 11:10:20 |
| 105 | Sam | 25 | 2011-06-26 10:10:20 |
+------+-------+------+---------------------+
5 rows in set (0.00 sec)
The following is the query can be used for specific date and time.
mysql> select *from AllRecordsFromadate where AdmissionDate between '2014-12-05 10:00:00' and '2014-12-05 12:50:58';
The following is the output.
+------+-------+------+---------------------+
| Id | Name | Age | AdmissionDate |
+------+-------+------+---------------------+
| 102 | Carol | 24 | 2014-12-05 12:34:50 |
| 103 | Mike | 25 | 2014-12-05 12:30:40 |
+------+-------+------+---------------------+
2 rows in set (0.00 sec) | [
{
"code": null,
"e": 1177,
"s": 1062,
"text": "You can use BETWEEN clause from MySQL to select records with a particular date and time. The syntax is as follows."
},
{
"code": null,
"e": 1287,
"s": 1177,
"text": "select *from AllRecordsFromadate where AdmissionDate between 'yourDateTimeValue1 ' and ''yourDateTimeValue2';"
},
{
"code": null,
"e": 1391,
"s": 1287,
"text": "To understand the above syntax, let us first create a table. The query to create a table is as follows."
},
{
"code": null,
"e": 1550,
"s": 1391,
"text": "mysql> create table AllRecordsFromadate\n-> (\n-> Id int,\n-> Name varchar(100),\n-> Age int,\n-> AdmissionDate datetime\n-> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1648,
"s": 1550,
"text": "Insert some records in the table using insert command. The query to insert records is as follows."
},
{
"code": null,
"e": 2238,
"s": 1648,
"text": "mysql> insert into AllRecordsFromadate values(101,'John',23,'2018-10-13');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into AllRecordsFromadate values(102,'Carol',24,'2014-12-5 12:34:50');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into AllRecordsFromadate values(103,'Mike',25,'2014-12-5 12:30:40');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into AllRecordsFromadate values(104,'Bob',24,'2015-10-7 11:10:20');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into AllRecordsFromadate values(105,'Sam',25,'2011-6-26 10:10:20');\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 2320,
"s": 2238,
"text": "Display all records from the table using select command. The query is as follows."
},
{
"code": null,
"e": 2361,
"s": 2320,
"text": "mysql> select *from AllRecordsFromadate;"
},
{
"code": null,
"e": 2390,
"s": 2361,
"text": "The following is the output."
},
{
"code": null,
"e": 2829,
"s": 2390,
"text": "+------+-------+------+---------------------+\n| Id | Name | Age | AdmissionDate |\n+------+-------+------+---------------------+\n| 101 | John | 23 | 2018-10-13 00:00:00 |\n| 102 | Carol | 24 | 2014-12-05 12:34:50 |\n| 103 | Mike | 25 | 2014-12-05 12:30:40 |\n| 104 | Bob | 24 | 2015-10-07 11:10:20 |\n| 105 | Sam | 25 | 2011-06-26 10:10:20 |\n+------+-------+------+---------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2896,
"s": 2829,
"text": "The following is the query can be used for specific date and time."
},
{
"code": null,
"e": 3013,
"s": 2896,
"text": "mysql> select *from AllRecordsFromadate where AdmissionDate between '2014-12-05 10:00:00' and '2014-12-05 12:50:58';"
},
{
"code": null,
"e": 3042,
"s": 3013,
"text": "The following is the output."
},
{
"code": null,
"e": 3343,
"s": 3042,
"text": "+------+-------+------+---------------------+\n| Id | Name | Age | AdmissionDate |\n+------+-------+------+---------------------+\n| 102 | Carol | 24 | 2014-12-05 12:34:50 |\n| 103 | Mike | 25 | 2014-12-05 12:30:40 |\n+------+-------+------+---------------------+\n2 rows in set (0.00 sec)"
}
]
|
How to capture index out of range exception in C#? | IndexOutOfRangeException occurs when you try to access an element with an index that is outsise the bounds of the array.
Let’s say the following is our array. It has 5 elements −
int [] n = new int[5] {66, 33, 56, 23, 81};
Now if you will try to access elements with index more than 5, then the IndexOutOfRange Exception is thrown −
for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
In the above example, we are trying to access above index 5, therefore the following error occurs −
System.IndexOutOfRangeException: Index was outside the bounds of the array.
Here is the complete code −
Live Demo
using System;
namespace Demo {
class MyArray {
static void Main(string[] args) {
try {
int [] n = new int[5] {66, 33, 56, 23, 81};
int i,j;
// error: IndexOutOfRangeException
for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
} catch (System.IndexOutOfRangeException e) {
Console.WriteLine(e);
}
}
}
}
Element[0] = 66
Element[1] = 33
Element[2] = 56
Element[3] = 23
Element[4] = 81
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Demo.MyArray.Main (System.String[] args) [0x00019] in <6ff1dbe1755b407391fe21dec35d62bd>:0
The code will generate an error −
System.IndexOutOfRangeException −Index was outside the bounds of the array. | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "IndexOutOfRangeException occurs when you try to access an element with an index that is outsise the bounds of the array."
},
{
"code": null,
"e": 1241,
"s": 1183,
"text": "Let’s say the following is our array. It has 5 elements −"
},
{
"code": null,
"e": 1285,
"s": 1241,
"text": "int [] n = new int[5] {66, 33, 56, 23, 81};"
},
{
"code": null,
"e": 1395,
"s": 1285,
"text": "Now if you will try to access elements with index more than 5, then the IndexOutOfRange Exception is thrown −"
},
{
"code": null,
"e": 1475,
"s": 1395,
"text": "for (j = 0; j < 10; j++ ) {\nConsole.WriteLine(\"Element[{0}] = {1}\", j, n[j]);\n}"
},
{
"code": null,
"e": 1575,
"s": 1475,
"text": "In the above example, we are trying to access above index 5, therefore the following error occurs −"
},
{
"code": null,
"e": 1651,
"s": 1575,
"text": "System.IndexOutOfRangeException: Index was outside the bounds of the array."
},
{
"code": null,
"e": 1679,
"s": 1651,
"text": "Here is the complete code −"
},
{
"code": null,
"e": 1690,
"s": 1679,
"text": " Live Demo"
},
{
"code": null,
"e": 2185,
"s": 1690,
"text": "using System;\n\nnamespace Demo {\n class MyArray {\n static void Main(string[] args) {\n try {\n int [] n = new int[5] {66, 33, 56, 23, 81};\n int i,j;\n // error: IndexOutOfRangeException\n for (j = 0; j < 10; j++ ) {\n Console.WriteLine(\"Element[{0}] = {1}\", j, n[j]);\n }\n Console.ReadKey();\n } catch (System.IndexOutOfRangeException e) {\n Console.WriteLine(e);\n }\n }\n }\n}"
},
{
"code": null,
"e": 2435,
"s": 2185,
"text": "Element[0] = 66\nElement[1] = 33\nElement[2] = 56\nElement[3] = 23\nElement[4] = 81\nSystem.IndexOutOfRangeException: Index was outside the bounds of the array.\nat Demo.MyArray.Main (System.String[] args) [0x00019] in <6ff1dbe1755b407391fe21dec35d62bd>:0"
},
{
"code": null,
"e": 2469,
"s": 2435,
"text": "The code will generate an error −"
},
{
"code": null,
"e": 2545,
"s": 2469,
"text": "System.IndexOutOfRangeException −Index was outside the bounds of the array."
}
]
|
QTP Working with XML | XML is a markup language designed to store data in a format that can be both readable by human and machine. Using XML, data can also be easily exchanged between computer and database systems.
Sample XML and their key elements are represented below −
Const XMLDataFile = "C:\TestData.xml"
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = False
xmlDoc.Load(XMLDataFile)
' Getting the number of Nodes (books)
Set nodes = xmlDoc.SelectNodes("/bookstore/book")
Print "Total books: " & nodes.Length ' Displays 2
' get all titles
Set nodes = xmlDoc.SelectNodes("/Booklib/book/value/text()")
' get their values
For i = 0 To (nodes.Length - 1)
Title = nodes(i).NodeValue
Print "Title is" & (i + 1) & ": " & Title
Next
We can compare two given XMLs −
Dim xmlDoc1
Dim xmlDoc2
' Load the XML Files
Set xmlDoc1 = XMLUtil.CreateXMLFromFile ("C:\File1.xml")
Set xmlDoc2 = XMLUtil.CreateXMLFromFile ("C:\File2.xml")
'Use the compare method of the XML to check if they are equivalent
Comp = xmlDoc1.Compare (xmlDoc1, xmlDoc2)
'Returns 1 if the two files are the same
If Comp = 1 Then
Msgbox "XML Files are the Same"
Else
Msgbox "XML Files are Different"
End if
108 Lectures
8 hours
Pavan Lalwani
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2314,
"s": 2122,
"text": "XML is a markup language designed to store data in a format that can be both readable by human and machine. Using XML, data can also be easily exchanged between computer and database systems."
},
{
"code": null,
"e": 2372,
"s": 2314,
"text": "Sample XML and their key elements are represented below −"
},
{
"code": null,
"e": 2855,
"s": 2372,
"text": "Const XMLDataFile = \"C:\\TestData.xml\"\nSet xmlDoc = CreateObject(\"Microsoft.XMLDOM\")\nxmlDoc.Async = False\nxmlDoc.Load(XMLDataFile)\n\n' Getting the number of Nodes (books)\nSet nodes = xmlDoc.SelectNodes(\"/bookstore/book\")\nPrint \"Total books: \" & nodes.Length ' Displays 2\n\n' get all titles\nSet nodes = xmlDoc.SelectNodes(\"/Booklib/book/value/text()\")\n\n' get their values\nFor i = 0 To (nodes.Length - 1)\n Title = nodes(i).NodeValue\n Print \"Title is\" & (i + 1) & \": \" & Title\nNext"
},
{
"code": null,
"e": 2887,
"s": 2855,
"text": "We can compare two given XMLs −"
},
{
"code": null,
"e": 3299,
"s": 2887,
"text": "Dim xmlDoc1\nDim xmlDoc2\n\n' Load the XML Files\nSet xmlDoc1 = XMLUtil.CreateXMLFromFile (\"C:\\File1.xml\")\nSet xmlDoc2 = XMLUtil.CreateXMLFromFile (\"C:\\File2.xml\")\n\n'Use the compare method of the XML to check if they are equivalent\nComp = xmlDoc1.Compare (xmlDoc1, xmlDoc2)\n\n'Returns 1 if the two files are the same\nIf Comp = 1 Then\n Msgbox \"XML Files are the Same\"\nElse\n Msgbox \"XML Files are Different\"\nEnd if"
},
{
"code": null,
"e": 3333,
"s": 3299,
"text": "\n 108 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3348,
"s": 3333,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3355,
"s": 3348,
"text": " Print"
},
{
"code": null,
"e": 3366,
"s": 3355,
"text": " Add Notes"
}
]
|
Feature importance and forward feature selection | by Vishal Singh | Towards Data Science | Processing of high dimensional data can be very challenging. By “high” it is meant thousands of dimensions, try to imagine(even though you can’t) a 70k dimensional space. Algorithms which rely on Euclidean distance as the measure of distance between 2 points start breaking down. This is referred to as the curse of dimensionality. Models such as K Nearest Neighbors and Linear Regression can easily overfit to high dimensional data and thus require careful hyperparameter tuning. Thus dimensionality reduction can be quite advantageous for any predictive model. However one cannot just throw away features randomly, after all, it is data which is the new oil. Dimensionality reduction techniques have been developed which not only facilitate extraction of discriminating features for data modeling but also help in visualizing high dimensional data in 2D, 3D or nD(if you can visualize it) space by transforming high dimensional data into low dimensional embeddings while preserving some fraction of originally available information. In case of PCA, this information is contained in the variance of extracted features whereas TSNE(T distributed stochastic neighborhood embedding) tries to preserve neighborhood information for as many points as it can, based on perplexity of the model. TSNE is state-of-the-art technique presently available.
The focus of this post is selection of the most discriminating subset of features for classification problems based on KPI of choice. Classification accuracy is chosen to be the KPI for explanation purposes. I will be using the “hello world” dataset of machine learning, you guessed it right, the very famous Iris dataset.
The dataset consists of 150 rows and 4 columns. It is a balanced dataset with 50 instances each of Iris-Setosa, Iris-Virginica, and Iris-Versicolor. If we look at the distribution of petal length and petal width for the three classes, we find something very interesting.
Clearly, these 2 are very good discriminators for separating Setosa from Versicolor and Virginica. We would like to find the most important features for accurately predicting the class of an input flower.
To solve this problem we will be employing a technique called forward feature selection. This reduction in features offers the following benefits
Reduced training times
Simplified and interpretable models
Reduced chances of overfitting i.e. lesser variance
Less impact of the curse of dimensionality
The code for forward feature selection looks somewhat like this
The code is pretty straightforward. First, we have created an empty list to which we will be appending the relevant features. We start by selecting one feature and calculating the metric value for each feature on cross-validation dataset. The feature offering best metric value is selected and appended to list of features. The process is reiterated, this time with two features, one selected from the previous iteration and the other one selected from the set of all features not present in the set of already chosen features. The metric value is computed for each set of 2 features and feature offering best metric value is appended to the list of relevant features. This process is repeated until we have the desired number of features (n in this case). Thus we can look at the feature set as a hyperparameter. Forward feature selection allows us to tune this hyperparameter for optimal performance.
Enough with the theory, let us see if this algorithm aligns with our observations about iris dataset. Just to recall, petal dimensions are good discriminators for separating Setosa from Virginica and Versicolor flowers. We arrange the four features in descending order of their importance and here are the results when f1_score is chosen as the KPI
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
x_train, x_cv, y_train, y_cv=train_test_split(df, target, test_size=0.2, stratify=target)
def evaluate_metric(model, x_cv, y_cv):
return f1_score(y_cv, model.predict(x_cv), average='micro')
def forward_feature_selection(x_train, x_cv, y_train, y_cv, n):
feature_set = []
for num_features in range(n):
metric_list = [] # Choose appropriate metric based on business problem
model = SGDClassifier() # You can choose any model you like, this technique is model agnostic
for feature in x_train.columns:
if feature not in feature_set:
f_set = feature_set.copy()
f_set.append(feature)
model.fit(x_train[f_set], y_train)
metric_list.append((evaluate_metric(model, x_cv[f_set], y_cv), feature))
metric_list.sort(key=lambda x : x[0], reverse = True) # In case metric follows "the more, the merrier"
feature_set.append(metric_list[0][1])
return feature_set
f=forward_feature_selection(x_train, x_cv, y_train, y_cv, 4)
f
['petal width (cm)',
'petal length (cm)',
'sepal width (cm)',
'sepal length (cm)']
Voila! Results are in perfect alignment with our observation. As mentioned in the code, this technique is model agnostic and can be used for evaluating feature importance for any classification/regression model.
What about the time complexity? It’s fairly obvious that it depends on the model being used. Linear models take less time to train than non-linear models. For the sake of simplicity assume that it takes linear time to train a model (linear in the number of rows). This assumption is correct in case of small m. If there are r rows in a dataset, the time taken to run above algorithm will be
which simplifies to
We can observe that although reliable, this method takes a considerable amount of time to run.
That’s all for forward feature selection. If you know better techniques to extract valuable features, do let me know in the comments section below.
Until next time, farewell... | [
{
"code": null,
"e": 1516,
"s": 172,
"text": "Processing of high dimensional data can be very challenging. By “high” it is meant thousands of dimensions, try to imagine(even though you can’t) a 70k dimensional space. Algorithms which rely on Euclidean distance as the measure of distance between 2 points start breaking down. This is referred to as the curse of dimensionality. Models such as K Nearest Neighbors and Linear Regression can easily overfit to high dimensional data and thus require careful hyperparameter tuning. Thus dimensionality reduction can be quite advantageous for any predictive model. However one cannot just throw away features randomly, after all, it is data which is the new oil. Dimensionality reduction techniques have been developed which not only facilitate extraction of discriminating features for data modeling but also help in visualizing high dimensional data in 2D, 3D or nD(if you can visualize it) space by transforming high dimensional data into low dimensional embeddings while preserving some fraction of originally available information. In case of PCA, this information is contained in the variance of extracted features whereas TSNE(T distributed stochastic neighborhood embedding) tries to preserve neighborhood information for as many points as it can, based on perplexity of the model. TSNE is state-of-the-art technique presently available."
},
{
"code": null,
"e": 1839,
"s": 1516,
"text": "The focus of this post is selection of the most discriminating subset of features for classification problems based on KPI of choice. Classification accuracy is chosen to be the KPI for explanation purposes. I will be using the “hello world” dataset of machine learning, you guessed it right, the very famous Iris dataset."
},
{
"code": null,
"e": 2110,
"s": 1839,
"text": "The dataset consists of 150 rows and 4 columns. It is a balanced dataset with 50 instances each of Iris-Setosa, Iris-Virginica, and Iris-Versicolor. If we look at the distribution of petal length and petal width for the three classes, we find something very interesting."
},
{
"code": null,
"e": 2315,
"s": 2110,
"text": "Clearly, these 2 are very good discriminators for separating Setosa from Versicolor and Virginica. We would like to find the most important features for accurately predicting the class of an input flower."
},
{
"code": null,
"e": 2461,
"s": 2315,
"text": "To solve this problem we will be employing a technique called forward feature selection. This reduction in features offers the following benefits"
},
{
"code": null,
"e": 2484,
"s": 2461,
"text": "Reduced training times"
},
{
"code": null,
"e": 2520,
"s": 2484,
"text": "Simplified and interpretable models"
},
{
"code": null,
"e": 2572,
"s": 2520,
"text": "Reduced chances of overfitting i.e. lesser variance"
},
{
"code": null,
"e": 2615,
"s": 2572,
"text": "Less impact of the curse of dimensionality"
},
{
"code": null,
"e": 2679,
"s": 2615,
"text": "The code for forward feature selection looks somewhat like this"
},
{
"code": null,
"e": 3582,
"s": 2679,
"text": "The code is pretty straightforward. First, we have created an empty list to which we will be appending the relevant features. We start by selecting one feature and calculating the metric value for each feature on cross-validation dataset. The feature offering best metric value is selected and appended to list of features. The process is reiterated, this time with two features, one selected from the previous iteration and the other one selected from the set of all features not present in the set of already chosen features. The metric value is computed for each set of 2 features and feature offering best metric value is appended to the list of relevant features. This process is repeated until we have the desired number of features (n in this case). Thus we can look at the feature set as a hyperparameter. Forward feature selection allows us to tune this hyperparameter for optimal performance."
},
{
"code": null,
"e": 3931,
"s": 3582,
"text": "Enough with the theory, let us see if this algorithm aligns with our observations about iris dataset. Just to recall, petal dimensions are good discriminators for separating Setosa from Virginica and Versicolor flowers. We arrange the four features in descending order of their importance and here are the results when f1_score is chosen as the KPI"
},
{
"code": null,
"e": 4069,
"s": 3931,
"text": "from sklearn.linear_model import SGDClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score\n"
},
{
"code": null,
"e": 4160,
"s": 4069,
"text": "x_train, x_cv, y_train, y_cv=train_test_split(df, target, test_size=0.2, stratify=target)\n"
},
{
"code": null,
"e": 4265,
"s": 4160,
"text": "def evaluate_metric(model, x_cv, y_cv):\n return f1_score(y_cv, model.predict(x_cv), average='micro')\n"
},
{
"code": null,
"e": 5051,
"s": 4265,
"text": "def forward_feature_selection(x_train, x_cv, y_train, y_cv, n):\n feature_set = []\n for num_features in range(n):\n metric_list = [] # Choose appropriate metric based on business problem\n model = SGDClassifier() # You can choose any model you like, this technique is model agnostic\n for feature in x_train.columns:\n if feature not in feature_set:\n f_set = feature_set.copy()\n f_set.append(feature)\n model.fit(x_train[f_set], y_train)\n metric_list.append((evaluate_metric(model, x_cv[f_set], y_cv), feature))\n\n metric_list.sort(key=lambda x : x[0], reverse = True) # In case metric follows \"the more, the merrier\"\n feature_set.append(metric_list[0][1])\n return feature_set\n"
},
{
"code": null,
"e": 5113,
"s": 5051,
"text": "f=forward_feature_selection(x_train, x_cv, y_train, y_cv, 4)\n"
},
{
"code": null,
"e": 5116,
"s": 5113,
"text": "f\n"
},
{
"code": null,
"e": 5202,
"s": 5116,
"text": "['petal width (cm)',\n 'petal length (cm)',\n 'sepal width (cm)',\n 'sepal length (cm)']"
},
{
"code": null,
"e": 5414,
"s": 5202,
"text": "Voila! Results are in perfect alignment with our observation. As mentioned in the code, this technique is model agnostic and can be used for evaluating feature importance for any classification/regression model."
},
{
"code": null,
"e": 5805,
"s": 5414,
"text": "What about the time complexity? It’s fairly obvious that it depends on the model being used. Linear models take less time to train than non-linear models. For the sake of simplicity assume that it takes linear time to train a model (linear in the number of rows). This assumption is correct in case of small m. If there are r rows in a dataset, the time taken to run above algorithm will be"
},
{
"code": null,
"e": 5825,
"s": 5805,
"text": "which simplifies to"
},
{
"code": null,
"e": 5920,
"s": 5825,
"text": "We can observe that although reliable, this method takes a considerable amount of time to run."
},
{
"code": null,
"e": 6068,
"s": 5920,
"text": "That’s all for forward feature selection. If you know better techniques to extract valuable features, do let me know in the comments section below."
}
]
|
Access Free Google Cloud Public Dataset with Python | by Joe T. Santhanavanich | Towards Data Science | Good news for Data Scientists! Google is making a hosted repository of public datasets, like Johns Hopkins Center for Systems Science and Engineering (JHU CSSE), the Global Health Data from the World Bank, and OpenStreetMap data, free to access and query through their COVID-19 Public Dataset Program to aid researchers, data scientists, and analysts in the effort to combat COVID-19. These datasets remove barriers and provide access to critical information quickly and easily, eliminating the need to search for and onboard large data files. Researchers can access the datasets from within the Google Cloud Console, along with a description of the data and sample queries to advance research. All data we include in the program will be public and freely available. *The program will remain in effect until September 15, 2020. [1]
Storing, managing, updating data myself with the database is sometimes boring and pricey. With Google Public Dataset, they are taking care of these boring parts for me. And for pricing, before the COVID-19 pandemic, it has a free-tier limit of 1 TB of querying per month (Well, really a lot of free data already!) To support the pandemic situation, there is no limit anymore!! So I could happily concentrate on the FUN parts: data analysis, sexy data visualization, developing web applications, etc.
This article will share with you step-by-step guides as follows:
Enable Google Cloud BigQuery API.Create Service Account for BigQuery API to grant permission to your Python script.Explore Dataset with BigQuery Web Interface.Access Dataset with Python and import it to the Pandas dataframe.
Enable Google Cloud BigQuery API.
Create Service Account for BigQuery API to grant permission to your Python script.
Explore Dataset with BigQuery Web Interface.
Access Dataset with Python and import it to the Pandas dataframe.
So, let’s get started!
To be able to access the dataset, you should register for the Google Cloud account. After you have registered or if you already have an account, please go to your Google Cloud console and then activate your Google Cloud BigQuery API (link). After you click on “Activate” the API, then you can see the confirmed “API enabled” as the figure below.
In order to give BigQuery API access to your machine with Python or other programming languages later, you need a new Google service account key by the following steps. (If you only need to access through the web interface, you may skip these steps)
Go to your Google API Credentials page to create the API key for this BigQuery API (link).
Select Service Account permission role as “BigQuery Admin”
Then, click on Create Key and select the JSON type. Please, make sure that you keep this file securely or someone might have access to your API account too. We will use this file again in the last step.
Users can retrieve or query the Google Public dataset using SQL Query syntax. At the starting point, you may try observing what dataset you have access to and test the SQL query through the Google BigQuery Web interface with three following steps:
Explore available data resources. Select one of them.Type your query syntax in the “Query Editor” window. In this step, you gonna need a basic knowledge of SQL to query (search) the dataset. If you have never used it before, please check the online document about it. Several of them are online such as W3.Explore your Query Results.
Explore available data resources. Select one of them.
Type your query syntax in the “Query Editor” window. In this step, you gonna need a basic knowledge of SQL to query (search) the dataset. If you have never used it before, please check the online document about it. Several of them are online such as W3.
Explore your Query Results.
To access the BigQuery API with Python, install the library with the following command:
pip install --upgrade google-cloud-bigquery
Create your project folder and put the service account JSON file in the folder. Then, create a Python file and edit it with the editor you like. The first thing you need is to set the OS environment of Google Application point to your JSON key directory which you can do by using os.environ["xxx"]="yyy"
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="Your json directory"
Then, you can start your BigQuery client and start a query with this command:
client = bigquery.Client() # Start the BigQuery ClientQUERY = ('SELECT ...') # Input Query Syntaxquery_job = client.query(QUERY) # Start Query API Requestquery_result = query_job.result() # Get Query Resultdf = query_result.to_dataframe() # Save the Query to Dataframe
For example, you can follow the full Python script below to query the top 20 COVID-19 confirmed and death cases in USA order by the later date and the higher confirmed cases from the New York Times COVID-19 database.
So, that’s about it! Congratulation, now you access the dataset, have fun with your new dataframe!! ✌🎉🎉
This article covers basic steps on how to use and access the dataset with Google Cloud BigQuery service with WebUI and Python. Please note that this article covers only the beginner steps and there are many more features and interfaces to access and play around with this service. You may check the full BigQuery document here.
I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments.
About me & Check out all my blog contents: Link
Be Safe and Healthy! 💪
Thank you for Reading. 📚
[1] Chad W. Jennings, COVID-19 public dataset program: Making data freely accessible for better public outcomes (Mar, 30 2020), Google Cloud Data Analytics | [
{
"code": null,
"e": 1004,
"s": 172,
"text": "Good news for Data Scientists! Google is making a hosted repository of public datasets, like Johns Hopkins Center for Systems Science and Engineering (JHU CSSE), the Global Health Data from the World Bank, and OpenStreetMap data, free to access and query through their COVID-19 Public Dataset Program to aid researchers, data scientists, and analysts in the effort to combat COVID-19. These datasets remove barriers and provide access to critical information quickly and easily, eliminating the need to search for and onboard large data files. Researchers can access the datasets from within the Google Cloud Console, along with a description of the data and sample queries to advance research. All data we include in the program will be public and freely available. *The program will remain in effect until September 15, 2020. [1]"
},
{
"code": null,
"e": 1504,
"s": 1004,
"text": "Storing, managing, updating data myself with the database is sometimes boring and pricey. With Google Public Dataset, they are taking care of these boring parts for me. And for pricing, before the COVID-19 pandemic, it has a free-tier limit of 1 TB of querying per month (Well, really a lot of free data already!) To support the pandemic situation, there is no limit anymore!! So I could happily concentrate on the FUN parts: data analysis, sexy data visualization, developing web applications, etc."
},
{
"code": null,
"e": 1569,
"s": 1504,
"text": "This article will share with you step-by-step guides as follows:"
},
{
"code": null,
"e": 1794,
"s": 1569,
"text": "Enable Google Cloud BigQuery API.Create Service Account for BigQuery API to grant permission to your Python script.Explore Dataset with BigQuery Web Interface.Access Dataset with Python and import it to the Pandas dataframe."
},
{
"code": null,
"e": 1828,
"s": 1794,
"text": "Enable Google Cloud BigQuery API."
},
{
"code": null,
"e": 1911,
"s": 1828,
"text": "Create Service Account for BigQuery API to grant permission to your Python script."
},
{
"code": null,
"e": 1956,
"s": 1911,
"text": "Explore Dataset with BigQuery Web Interface."
},
{
"code": null,
"e": 2022,
"s": 1956,
"text": "Access Dataset with Python and import it to the Pandas dataframe."
},
{
"code": null,
"e": 2045,
"s": 2022,
"text": "So, let’s get started!"
},
{
"code": null,
"e": 2391,
"s": 2045,
"text": "To be able to access the dataset, you should register for the Google Cloud account. After you have registered or if you already have an account, please go to your Google Cloud console and then activate your Google Cloud BigQuery API (link). After you click on “Activate” the API, then you can see the confirmed “API enabled” as the figure below."
},
{
"code": null,
"e": 2641,
"s": 2391,
"text": "In order to give BigQuery API access to your machine with Python or other programming languages later, you need a new Google service account key by the following steps. (If you only need to access through the web interface, you may skip these steps)"
},
{
"code": null,
"e": 2732,
"s": 2641,
"text": "Go to your Google API Credentials page to create the API key for this BigQuery API (link)."
},
{
"code": null,
"e": 2791,
"s": 2732,
"text": "Select Service Account permission role as “BigQuery Admin”"
},
{
"code": null,
"e": 2994,
"s": 2791,
"text": "Then, click on Create Key and select the JSON type. Please, make sure that you keep this file securely or someone might have access to your API account too. We will use this file again in the last step."
},
{
"code": null,
"e": 3242,
"s": 2994,
"text": "Users can retrieve or query the Google Public dataset using SQL Query syntax. At the starting point, you may try observing what dataset you have access to and test the SQL query through the Google BigQuery Web interface with three following steps:"
},
{
"code": null,
"e": 3576,
"s": 3242,
"text": "Explore available data resources. Select one of them.Type your query syntax in the “Query Editor” window. In this step, you gonna need a basic knowledge of SQL to query (search) the dataset. If you have never used it before, please check the online document about it. Several of them are online such as W3.Explore your Query Results."
},
{
"code": null,
"e": 3630,
"s": 3576,
"text": "Explore available data resources. Select one of them."
},
{
"code": null,
"e": 3884,
"s": 3630,
"text": "Type your query syntax in the “Query Editor” window. In this step, you gonna need a basic knowledge of SQL to query (search) the dataset. If you have never used it before, please check the online document about it. Several of them are online such as W3."
},
{
"code": null,
"e": 3912,
"s": 3884,
"text": "Explore your Query Results."
},
{
"code": null,
"e": 4000,
"s": 3912,
"text": "To access the BigQuery API with Python, install the library with the following command:"
},
{
"code": null,
"e": 4044,
"s": 4000,
"text": "pip install --upgrade google-cloud-bigquery"
},
{
"code": null,
"e": 4348,
"s": 4044,
"text": "Create your project folder and put the service account JSON file in the folder. Then, create a Python file and edit it with the editor you like. The first thing you need is to set the OS environment of Google Application point to your JSON key directory which you can do by using os.environ[\"xxx\"]=\"yyy\""
},
{
"code": null,
"e": 4415,
"s": 4348,
"text": "os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=\"Your json directory\""
},
{
"code": null,
"e": 4493,
"s": 4415,
"text": "Then, you can start your BigQuery client and start a query with this command:"
},
{
"code": null,
"e": 4793,
"s": 4493,
"text": "client = bigquery.Client() # Start the BigQuery ClientQUERY = ('SELECT ...') # Input Query Syntaxquery_job = client.query(QUERY) # Start Query API Requestquery_result = query_job.result() # Get Query Resultdf = query_result.to_dataframe() # Save the Query to Dataframe"
},
{
"code": null,
"e": 5010,
"s": 4793,
"text": "For example, you can follow the full Python script below to query the top 20 COVID-19 confirmed and death cases in USA order by the later date and the higher confirmed cases from the New York Times COVID-19 database."
},
{
"code": null,
"e": 5114,
"s": 5010,
"text": "So, that’s about it! Congratulation, now you access the dataset, have fun with your new dataframe!! ✌🎉🎉"
},
{
"code": null,
"e": 5442,
"s": 5114,
"text": "This article covers basic steps on how to use and access the dataset with Google Cloud BigQuery service with WebUI and Python. Please note that this article covers only the beginner steps and there are many more features and interfaces to access and play around with this service. You may check the full BigQuery document here."
},
{
"code": null,
"e": 5595,
"s": 5442,
"text": "I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments."
},
{
"code": null,
"e": 5643,
"s": 5595,
"text": "About me & Check out all my blog contents: Link"
},
{
"code": null,
"e": 5666,
"s": 5643,
"text": "Be Safe and Healthy! 💪"
},
{
"code": null,
"e": 5691,
"s": 5666,
"text": "Thank you for Reading. 📚"
}
]
|
Check if two numbers are equal without using arithmetic and comparison operators - GeeksforGeeks | 18 Jan, 2022
Following are not allowed to use 1) Arithmetic and Comparison Operators 2) String functions
Method 1 : The idea is to use XOR operator. XOR of two numbers is 0 if the numbers are same, otherwise non-zero.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if two numbers// are equal without using arithmetic// and comparison operators#include <iostream>using namespace std; // Function to check if two// numbers are equal using// XOR operatorvoid areSame(int a, int b){ if (a ^ b) cout << "Not Same"; else cout << "Same";} // Driver Codeint main(){ // Calling function areSame(10, 20);}
// Java program to check if two numbers// are equal without using arithmetic// and comparison operatorsclass GFG { // Function to check if two // numbers are equal using // XOR operator static void areSame(int a, int b) { if ((a ^ b) != 0) System.out.print("Not Same"); else System.out.print("Same"); } // Driver Code public static void main(String[] args) { // Calling function areSame(10, 20); }} // This code is contributed by Smitha
# Python3 program to check if two numbers# are equal without using arithmetic# and comparison operators def areSame(a, b): # Function to check if two# numbers are equal using# XOR operator if ((a ^ b) != 0): print("Not Same") else: print("Same") # Driver Code areSame(10, 20) # This code is contributed by Smitha
// C# program to check if two numbers// are equal without using arithmetic// and comparison operatorsusing System; class GFG { // Function to check if two // numbers are equal using // XOR operator static void areSame(int a, int b) { if ((a ^ b) != 0) Console.Write("Not Same"); else Console.Write("Same"); } // Driver Code public static void Main(String[] args) { // Calling function areSame(10, 20); }} // This code is contributed by Smitha
<?php// PHP program to check if// two numbers are equal// without using arithmetic// and comparison operators // Function to check if two// numbers are equal using// XOR operatorfunction areSame($a, $b){if ($a ^ $b)echo "Not Same";elseecho "Same";} // Driver Code // Calling functionareSame(10, 20); // This code is contributed// by nitin mittal.?>
<script> // Javascript program to check if two numbers// are equal without using arithmetic and// comparison operators // Function to check if two// numbers are equal using// XOR operatorfunction areSame(a, b){ if ((a ^ b) != 0) document.write("Not Same"); else document.write("Same");} // Driver CodeareSame(10, 20); // This code is contributed by shikhasingrajput </script>
Output :
Not Same
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 2 : Here idea is using complement ( ~ ) and bit-wise ‘&’ operator.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if two numbers// are equal without using arithmetic// and comparison operators#include <iostream>using namespace std; // Function to check if two// numbers are equal using// using ~ complement and & operator.void areSame(int a, int b){ if ((a & ~b) == 0) cout << "Same"; else cout << "Not Same";}// Driver Codeint main(){ // Calling function areSame(10, 10); // This Code is improved by Sonu Kumar Pandit}
// Java program to check if two numbers// are equal without using arithmetic// and comparison operators class GFG { // Function to check if two // numbers are equal using // using ~ complement and & operator. static void areSame(int a, int b) { if ((a & ~b) == 0 && (~a & b) == 0) System.out.print("Same"); else System.out.print("Not Same"); } // Driver Code public static void main(String args[]) { // Calling function areSame(10, 20); }} // This code is contributed// by Akanksha Rai
# Python3 program to check if two numbers# are equal without using arithmetic# and comparison operators # Function to check if two# numbers are equal using# using ~ complement and & operator. def areSame(a, b): if ((a & ~b) == 0 and (~a & b) == 0): print("Same") else: print("Not Same") # Calling functionareSame(10, 20) # This code is contributed by Rajput-Ji
// C# program to check if two numbers// are equal without using arithmetic// and comparison operatorsusing System; class GFG { // Function to check if two // numbers are equal using // using ~ complement and & operator. static void areSame(int a, int b) { if ((a & ~b) == 0 && (~a & b) == 0) Console.Write("Same"); else Console.Write("Not Same"); } // Driver Code public static void Main() { // Calling function areSame(10, 20); }} // This code is contributed// by Akanksha Rai
<?php// PHP program to check if two numbers// are equal without using arithmetic// and comparison operators // Function to check if two// numbers are equal using// using ~ complement and & operator.function areSame($a, $b){ if (($a & ~$b)==0 && (~$a & $b)==0) echo "Same"; else echo "Not Same";} // Driver Code// Calling functionareSame(1, 1); // This code is contributed by ita_c?>
<script> // Javascript program to check if two numbers// are equal without using arithmetic// and comparison operators // Function to check if two// Numbers are equal using// using ~ complement and & operator.function areSame(a, b){ if ((a & ~b) == 0 && (~a & b) == 0) document.write("Same"); else document.write("Not Same");} // Driver Code // Calling functionareSame(10, 20); // This code is contributed by gauravrajput1 </script>
Output :
Not Same
Time Complexity: O(1)
Auxiliary Space: O(1)
YouTubeGeeksforGeeks502K subscribersCheck if two numbers are equal without using comparison operators | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=if_uoOTVgXw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Source: https://www.geeksforgeeks.org/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum/Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Smitha Dinesh Semwal
nitin mittal
vivek kumar 9
Rajput-Ji
ukasp
Akanksha_Rai
competing23invain
shikhasingrajput
GauravRajput1
subham348
sonukmrpndt
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Program to find whether a given number is power of 2
Binary representation of a given number
Find the element that appears once
Add two numbers without using arithmetic operators
Bit Fields in C
Josephus problem | Set 1 (A O(n) Solution)
Set, Clear and Toggle a given bit of a number in C
C++ bitset and its application | [
{
"code": null,
"e": 25121,
"s": 25093,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 25213,
"s": 25121,
"text": "Following are not allowed to use 1) Arithmetic and Comparison Operators 2) String functions"
},
{
"code": null,
"e": 25327,
"s": 25213,
"text": "Method 1 : The idea is to use XOR operator. XOR of two numbers is 0 if the numbers are same, otherwise non-zero. "
},
{
"code": null,
"e": 25331,
"s": 25327,
"text": "C++"
},
{
"code": null,
"e": 25336,
"s": 25331,
"text": "Java"
},
{
"code": null,
"e": 25344,
"s": 25336,
"text": "Python3"
},
{
"code": null,
"e": 25347,
"s": 25344,
"text": "C#"
},
{
"code": null,
"e": 25351,
"s": 25347,
"text": "PHP"
},
{
"code": null,
"e": 25362,
"s": 25351,
"text": "Javascript"
},
{
"code": "// C++ program to check if two numbers// are equal without using arithmetic// and comparison operators#include <iostream>using namespace std; // Function to check if two// numbers are equal using// XOR operatorvoid areSame(int a, int b){ if (a ^ b) cout << \"Not Same\"; else cout << \"Same\";} // Driver Codeint main(){ // Calling function areSame(10, 20);}",
"e": 25744,
"s": 25362,
"text": null
},
{
"code": "// Java program to check if two numbers// are equal without using arithmetic// and comparison operatorsclass GFG { // Function to check if two // numbers are equal using // XOR operator static void areSame(int a, int b) { if ((a ^ b) != 0) System.out.print(\"Not Same\"); else System.out.print(\"Same\"); } // Driver Code public static void main(String[] args) { // Calling function areSame(10, 20); }} // This code is contributed by Smitha",
"e": 26264,
"s": 25744,
"text": null
},
{
"code": "# Python3 program to check if two numbers# are equal without using arithmetic# and comparison operators def areSame(a, b): # Function to check if two# numbers are equal using# XOR operator if ((a ^ b) != 0): print(\"Not Same\") else: print(\"Same\") # Driver Code areSame(10, 20) # This code is contributed by Smitha",
"e": 26583,
"s": 26264,
"text": null
},
{
"code": "// C# program to check if two numbers// are equal without using arithmetic// and comparison operatorsusing System; class GFG { // Function to check if two // numbers are equal using // XOR operator static void areSame(int a, int b) { if ((a ^ b) != 0) Console.Write(\"Not Same\"); else Console.Write(\"Same\"); } // Driver Code public static void Main(String[] args) { // Calling function areSame(10, 20); }} // This code is contributed by Smitha",
"e": 27109,
"s": 26583,
"text": null
},
{
"code": "<?php// PHP program to check if// two numbers are equal// without using arithmetic// and comparison operators // Function to check if two// numbers are equal using// XOR operatorfunction areSame($a, $b){if ($a ^ $b)echo \"Not Same\";elseecho \"Same\";} // Driver Code // Calling functionareSame(10, 20); // This code is contributed// by nitin mittal.?>",
"e": 27458,
"s": 27109,
"text": null
},
{
"code": "<script> // Javascript program to check if two numbers// are equal without using arithmetic and// comparison operators // Function to check if two// numbers are equal using// XOR operatorfunction areSame(a, b){ if ((a ^ b) != 0) document.write(\"Not Same\"); else document.write(\"Same\");} // Driver CodeareSame(10, 20); // This code is contributed by shikhasingrajput </script>",
"e": 27856,
"s": 27458,
"text": null
},
{
"code": null,
"e": 27866,
"s": 27856,
"text": "Output : "
},
{
"code": null,
"e": 27875,
"s": 27866,
"text": "Not Same"
},
{
"code": null,
"e": 27897,
"s": 27875,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 27919,
"s": 27897,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27994,
"s": 27919,
"text": "Method 2 : Here idea is using complement ( ~ ) and bit-wise ‘&’ operator. "
},
{
"code": null,
"e": 27998,
"s": 27994,
"text": "C++"
},
{
"code": null,
"e": 28003,
"s": 27998,
"text": "Java"
},
{
"code": null,
"e": 28011,
"s": 28003,
"text": "Python3"
},
{
"code": null,
"e": 28014,
"s": 28011,
"text": "C#"
},
{
"code": null,
"e": 28018,
"s": 28014,
"text": "PHP"
},
{
"code": null,
"e": 28029,
"s": 28018,
"text": "Javascript"
},
{
"code": "// C++ program to check if two numbers// are equal without using arithmetic// and comparison operators#include <iostream>using namespace std; // Function to check if two// numbers are equal using// using ~ complement and & operator.void areSame(int a, int b){ if ((a & ~b) == 0) cout << \"Same\"; else cout << \"Not Same\";}// Driver Codeint main(){ // Calling function areSame(10, 10); // This Code is improved by Sonu Kumar Pandit}",
"e": 28490,
"s": 28029,
"text": null
},
{
"code": "// Java program to check if two numbers// are equal without using arithmetic// and comparison operators class GFG { // Function to check if two // numbers are equal using // using ~ complement and & operator. static void areSame(int a, int b) { if ((a & ~b) == 0 && (~a & b) == 0) System.out.print(\"Same\"); else System.out.print(\"Not Same\"); } // Driver Code public static void main(String args[]) { // Calling function areSame(10, 20); }} // This code is contributed// by Akanksha Rai",
"e": 29057,
"s": 28490,
"text": null
},
{
"code": "# Python3 program to check if two numbers# are equal without using arithmetic# and comparison operators # Function to check if two# numbers are equal using# using ~ complement and & operator. def areSame(a, b): if ((a & ~b) == 0 and (~a & b) == 0): print(\"Same\") else: print(\"Not Same\") # Calling functionareSame(10, 20) # This code is contributed by Rajput-Ji",
"e": 29440,
"s": 29057,
"text": null
},
{
"code": "// C# program to check if two numbers// are equal without using arithmetic// and comparison operatorsusing System; class GFG { // Function to check if two // numbers are equal using // using ~ complement and & operator. static void areSame(int a, int b) { if ((a & ~b) == 0 && (~a & b) == 0) Console.Write(\"Same\"); else Console.Write(\"Not Same\"); } // Driver Code public static void Main() { // Calling function areSame(10, 20); }} // This code is contributed// by Akanksha Rai",
"e": 29999,
"s": 29440,
"text": null
},
{
"code": "<?php// PHP program to check if two numbers// are equal without using arithmetic// and comparison operators // Function to check if two// numbers are equal using// using ~ complement and & operator.function areSame($a, $b){ if (($a & ~$b)==0 && (~$a & $b)==0) echo \"Same\"; else echo \"Not Same\";} // Driver Code// Calling functionareSame(1, 1); // This code is contributed by ita_c?>",
"e": 30402,
"s": 29999,
"text": null
},
{
"code": "<script> // Javascript program to check if two numbers// are equal without using arithmetic// and comparison operators // Function to check if two// Numbers are equal using// using ~ complement and & operator.function areSame(a, b){ if ((a & ~b) == 0 && (~a & b) == 0) document.write(\"Same\"); else document.write(\"Not Same\");} // Driver Code // Calling functionareSame(10, 20); // This code is contributed by gauravrajput1 </script>",
"e": 30855,
"s": 30402,
"text": null
},
{
"code": null,
"e": 30865,
"s": 30855,
"text": "Output : "
},
{
"code": null,
"e": 30874,
"s": 30865,
"text": "Not Same"
},
{
"code": null,
"e": 30896,
"s": 30874,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 30918,
"s": 30896,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31782,
"s": 30918,
"text": "YouTubeGeeksforGeeks502K subscribersCheck if two numbers are equal without using comparison operators | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=if_uoOTVgXw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 32010,
"s": 31782,
"text": "Source: https://www.geeksforgeeks.org/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum/Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 32031,
"s": 32010,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 32044,
"s": 32031,
"text": "nitin mittal"
},
{
"code": null,
"e": 32058,
"s": 32044,
"text": "vivek kumar 9"
},
{
"code": null,
"e": 32068,
"s": 32058,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32074,
"s": 32068,
"text": "ukasp"
},
{
"code": null,
"e": 32087,
"s": 32074,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 32105,
"s": 32087,
"text": "competing23invain"
},
{
"code": null,
"e": 32122,
"s": 32105,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 32136,
"s": 32122,
"text": "GauravRajput1"
},
{
"code": null,
"e": 32146,
"s": 32136,
"text": "subham348"
},
{
"code": null,
"e": 32158,
"s": 32146,
"text": "sonukmrpndt"
},
{
"code": null,
"e": 32168,
"s": 32158,
"text": "Bit Magic"
},
{
"code": null,
"e": 32178,
"s": 32168,
"text": "Bit Magic"
},
{
"code": null,
"e": 32276,
"s": 32178,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32322,
"s": 32276,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 32352,
"s": 32322,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 32405,
"s": 32352,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 32445,
"s": 32405,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 32480,
"s": 32445,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 32531,
"s": 32480,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 32547,
"s": 32531,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 32590,
"s": 32547,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 32641,
"s": 32590,
"text": "Set, Clear and Toggle a given bit of a number in C"
}
]
|
CSS | background-color Property - GeeksforGeeks | 29 Oct, 2021
The background-color property in CSS is used to specify the background color of an element. The background covers the total size of the element with padding and border but excluding margin. It makes the text so easy to read for the user.
Syntax:
element {
background-color property
}
Default value : It has a default value i.e transparent.
Property Values:
Syntax:element {
background-color: color_name;
}
element {
background-color: color_name;
}
Example:<!DOCTYPE html><html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html>
<!DOCTYPE html><html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html>
Output:
transparent: It is the default value. It specifies the transparent background-color.
Syntax:element {
background-color:transparent;
}
element {
background-color:transparent;
}
Example:<!DOCTYPE html><html> <head> <title>background-color property</title> <style> body { background-color:transparent; text-align:center; } h1 { background-color: transparent; } h2 { background-color:transparent; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>background-color: transparent;</h2> </body> </html>
<!DOCTYPE html><html> <head> <title>background-color property</title> <style> body { background-color:transparent; text-align:center; } h1 { background-color: transparent; } h2 { background-color:transparent; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>background-color: transparent;</h2> </body> </html>
Output:
initial: It is used to set the default value. It does not set the background color.
Syntax:element {
background-color: initial;
}
element {
background-color: initial;
}
inherit: It is inherit the background-color from it’s parent.
Supported Browsers: The browser supported by css background-color Property are listed below:
Chrome 1.0
Internet Explorer 4.0
Firefox 1.0
Opera 3.5
Safari 1.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
CSS-Properties
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
CSS to put icon inside an input element in a form
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": 23758,
"s": 23730,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 23996,
"s": 23758,
"text": "The background-color property in CSS is used to specify the background color of an element. The background covers the total size of the element with padding and border but excluding margin. It makes the text so easy to read for the user."
},
{
"code": null,
"e": 24004,
"s": 23996,
"text": "Syntax:"
},
{
"code": null,
"e": 24046,
"s": 24004,
"text": "element {\n background-color property\n}"
},
{
"code": null,
"e": 24102,
"s": 24046,
"text": "Default value : It has a default value i.e transparent."
},
{
"code": null,
"e": 24119,
"s": 24102,
"text": "Property Values:"
},
{
"code": null,
"e": 24172,
"s": 24119,
"text": "Syntax:element {\n background-color: color_name;\n}"
},
{
"code": null,
"e": 24218,
"s": 24172,
"text": "element {\n background-color: color_name;\n}"
},
{
"code": null,
"e": 24792,
"s": 24218,
"text": "Example:<!DOCTYPE html><html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html> "
},
{
"code": "<!DOCTYPE html><html> <head> <title>background-color property</title> <style> body { text-align:center; background-color:green; } h1 { color:white; background-color:blue; } h2 { color:white; background-color:black; } </style> </head> <body> <h1>Geeksforgeeks </h1> <h2>background-color: color_name;</h2> </body> </html> ",
"e": 25358,
"s": 24792,
"text": null
},
{
"code": null,
"e": 25366,
"s": 25358,
"text": "Output:"
},
{
"code": null,
"e": 25451,
"s": 25366,
"text": "transparent: It is the default value. It specifies the transparent background-color."
},
{
"code": null,
"e": 25504,
"s": 25451,
"text": "Syntax:element {\n background-color:transparent;\n}"
},
{
"code": null,
"e": 25550,
"s": 25504,
"text": "element {\n background-color:transparent;\n}"
},
{
"code": null,
"e": 26077,
"s": 25550,
"text": "Example:<!DOCTYPE html><html> <head> <title>background-color property</title> <style> body { background-color:transparent; text-align:center; } h1 { background-color: transparent; } h2 { background-color:transparent; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>background-color: transparent;</h2> </body> </html> "
},
{
"code": "<!DOCTYPE html><html> <head> <title>background-color property</title> <style> body { background-color:transparent; text-align:center; } h1 { background-color: transparent; } h2 { background-color:transparent; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>background-color: transparent;</h2> </body> </html> ",
"e": 26596,
"s": 26077,
"text": null
},
{
"code": null,
"e": 26604,
"s": 26596,
"text": "Output:"
},
{
"code": null,
"e": 26688,
"s": 26604,
"text": "initial: It is used to set the default value. It does not set the background color."
},
{
"code": null,
"e": 26738,
"s": 26688,
"text": "Syntax:element {\n background-color: initial;\n}"
},
{
"code": null,
"e": 26781,
"s": 26738,
"text": "element {\n background-color: initial;\n}"
},
{
"code": null,
"e": 26843,
"s": 26781,
"text": "inherit: It is inherit the background-color from it’s parent."
},
{
"code": null,
"e": 26936,
"s": 26843,
"text": "Supported Browsers: The browser supported by css background-color Property are listed below:"
},
{
"code": null,
"e": 26947,
"s": 26936,
"text": "Chrome 1.0"
},
{
"code": null,
"e": 26969,
"s": 26947,
"text": "Internet Explorer 4.0"
},
{
"code": null,
"e": 26981,
"s": 26969,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 26991,
"s": 26981,
"text": "Opera 3.5"
},
{
"code": null,
"e": 27002,
"s": 26991,
"text": "Safari 1.0"
},
{
"code": null,
"e": 27139,
"s": 27002,
"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": 27159,
"s": 27139,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 27174,
"s": 27159,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27181,
"s": 27174,
"text": "Picked"
},
{
"code": null,
"e": 27185,
"s": 27181,
"text": "CSS"
},
{
"code": null,
"e": 27190,
"s": 27185,
"text": "HTML"
},
{
"code": null,
"e": 27207,
"s": 27190,
"text": "Web Technologies"
},
{
"code": null,
"e": 27212,
"s": 27207,
"text": "HTML"
},
{
"code": null,
"e": 27310,
"s": 27212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27372,
"s": 27310,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27422,
"s": 27372,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27480,
"s": 27422,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27528,
"s": 27480,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27578,
"s": 27528,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27640,
"s": 27578,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27690,
"s": 27640,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27750,
"s": 27690,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27798,
"s": 27750,
"text": "How to update Node.js and NPM to next version ?"
}
]
|
Blackeye Phishing Tool in Kali Linux - GeeksforGeeks | 28 Nov, 2021
Blackeye is a powerful open-source tool Phishing Tool. Blackeye is becoming very popular nowadays that is used to do phishing attacks on Target. Blackeye is an easy Social Engineering Toolkit. Blackeye contains some templates generated by another tool called Blackeye. This tool makes it easy to perform phishing attacks. There is a lot of creativity that they can put into making the email look as legitimate as possible. Blackeye offers phishing templates web pages for 33 popular sites such as Facebook, Instagram, Google, Snapchat, GitHub, Yahoo, Protonmail, Spotify, Netflix, Linkedin, WordPress, Origin, Steam, Microsoft, etc. Blackeye also provides an option to use a custom template if someone wants.
Step 1: Open your kali Linux operating system and use the following command to install the tool.
git clone https://github.com/thelinuxchoice/blackeye
Step 2: Now use the following command to move into the directory of the tool.
cd blackeye
ls
Step 3: Now use the following command to run the tool.
bash blackeye.sh
The tool has been installed successfully now if you want to perform a phishing attack on your victims choose any option from the menu list of the blackeye and blackeye will create the phishing link of the respective website which you can send to your victims. For example, if you choose Instagram choose option 1.
The tool has created some target links use these links and send them to the victim. Once the victim filled his/her id password it will reflect in the terminal.
The user has filled in the details.
You can see that the credentials are visible in the terminal.
Example: Use the blackeye tool to get credentials of google account.
Step 1: Choose option 6.
6
Step 2: Send the ngrok link to the victim. Once he/she adds his/her account details it will be reflected on the terminal.
Step 3: You can see the tool has found credentials.
Similarly, you perform experiments using the blackeye tool. The tool is free to use.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples | [
{
"code": null,
"e": 24431,
"s": 24403,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25141,
"s": 24431,
"text": "Blackeye is a powerful open-source tool Phishing Tool. Blackeye is becoming very popular nowadays that is used to do phishing attacks on Target. Blackeye is an easy Social Engineering Toolkit. Blackeye contains some templates generated by another tool called Blackeye. This tool makes it easy to perform phishing attacks. There is a lot of creativity that they can put into making the email look as legitimate as possible. Blackeye offers phishing templates web pages for 33 popular sites such as Facebook, Instagram, Google, Snapchat, GitHub, Yahoo, Protonmail, Spotify, Netflix, Linkedin, WordPress, Origin, Steam, Microsoft, etc. Blackeye also provides an option to use a custom template if someone wants."
},
{
"code": null,
"e": 25238,
"s": 25141,
"text": "Step 1: Open your kali Linux operating system and use the following command to install the tool."
},
{
"code": null,
"e": 25291,
"s": 25238,
"text": "git clone https://github.com/thelinuxchoice/blackeye"
},
{
"code": null,
"e": 25369,
"s": 25291,
"text": "Step 2: Now use the following command to move into the directory of the tool."
},
{
"code": null,
"e": 25384,
"s": 25369,
"text": "cd blackeye\nls"
},
{
"code": null,
"e": 25439,
"s": 25384,
"text": "Step 3: Now use the following command to run the tool."
},
{
"code": null,
"e": 25456,
"s": 25439,
"text": "bash blackeye.sh"
},
{
"code": null,
"e": 25770,
"s": 25456,
"text": "The tool has been installed successfully now if you want to perform a phishing attack on your victims choose any option from the menu list of the blackeye and blackeye will create the phishing link of the respective website which you can send to your victims. For example, if you choose Instagram choose option 1."
},
{
"code": null,
"e": 25930,
"s": 25770,
"text": "The tool has created some target links use these links and send them to the victim. Once the victim filled his/her id password it will reflect in the terminal."
},
{
"code": null,
"e": 25966,
"s": 25930,
"text": "The user has filled in the details."
},
{
"code": null,
"e": 26028,
"s": 25966,
"text": "You can see that the credentials are visible in the terminal."
},
{
"code": null,
"e": 26097,
"s": 26028,
"text": "Example: Use the blackeye tool to get credentials of google account."
},
{
"code": null,
"e": 26122,
"s": 26097,
"text": "Step 1: Choose option 6."
},
{
"code": null,
"e": 26124,
"s": 26122,
"text": "6"
},
{
"code": null,
"e": 26246,
"s": 26124,
"text": "Step 2: Send the ngrok link to the victim. Once he/she adds his/her account details it will be reflected on the terminal."
},
{
"code": null,
"e": 26298,
"s": 26246,
"text": "Step 3: You can see the tool has found credentials."
},
{
"code": null,
"e": 26383,
"s": 26298,
"text": "Similarly, you perform experiments using the blackeye tool. The tool is free to use."
},
{
"code": null,
"e": 26394,
"s": 26383,
"text": "Kali-Linux"
},
{
"code": null,
"e": 26406,
"s": 26394,
"text": "Linux-Tools"
},
{
"code": null,
"e": 26417,
"s": 26406,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26515,
"s": 26417,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26552,
"s": 26515,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26587,
"s": 26552,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26613,
"s": 26587,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26647,
"s": 26613,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26684,
"s": 26647,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26713,
"s": 26684,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26739,
"s": 26713,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26779,
"s": 26739,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26814,
"s": 26779,
"text": "Basic Operators in Shell Scripting"
}
]
|
Ways to Create NaN Values in Pandas DataFrame - GeeksforGeeks | 08 Dec, 2021
Let’s discuss ways of creating NaN values in the Pandas Dataframe. There are various ways to create NaN values in Pandas dataFrame. Those are:
Using NumPy
Importing csv file having blank values
Applying to_numeric function
Method 1: Using NumPy
Python3
import pandas as pdimport numpy as np num = {'number': [1,2,np.nan,6,7,np.nan,np.nan]}df = pd.DataFrame(num) df
Method 2: Importing the CSV file having blank instances
Consider the below csv file named “Book1.csv”:
Code:
Python3
# import pandasimport pandas as pd # read filedf = pd.read_csv("Book1.csv") # print valuesdf
You will get Nan values for blank instances.
Method 3: Applying to_numeric function
to_numeric function converts arguments to a numeric type.
Example:
Python3
import pandas as pd num = {'data': [1,"hjghjd",3,"jxsh"]}df = pd.DataFrame(num) # this will convert non-numeric # values into NaN valuesdf = pd.to_numeric(df["data"], errors='coerce') df
Output:
anikaseth98
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 25680,
"s": 25537,
"text": "Let’s discuss ways of creating NaN values in the Pandas Dataframe. There are various ways to create NaN values in Pandas dataFrame. Those are:"
},
{
"code": null,
"e": 25692,
"s": 25680,
"text": "Using NumPy"
},
{
"code": null,
"e": 25731,
"s": 25692,
"text": "Importing csv file having blank values"
},
{
"code": null,
"e": 25760,
"s": 25731,
"text": "Applying to_numeric function"
},
{
"code": null,
"e": 25782,
"s": 25760,
"text": "Method 1: Using NumPy"
},
{
"code": null,
"e": 25790,
"s": 25782,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np num = {'number': [1,2,np.nan,6,7,np.nan,np.nan]}df = pd.DataFrame(num) df",
"e": 25904,
"s": 25790,
"text": null
},
{
"code": null,
"e": 25960,
"s": 25904,
"text": "Method 2: Importing the CSV file having blank instances"
},
{
"code": null,
"e": 26007,
"s": 25960,
"text": "Consider the below csv file named “Book1.csv”:"
},
{
"code": null,
"e": 26013,
"s": 26007,
"text": "Code:"
},
{
"code": null,
"e": 26021,
"s": 26013,
"text": "Python3"
},
{
"code": "# import pandasimport pandas as pd # read filedf = pd.read_csv(\"Book1.csv\") # print valuesdf",
"e": 26116,
"s": 26021,
"text": null
},
{
"code": null,
"e": 26161,
"s": 26116,
"text": "You will get Nan values for blank instances."
},
{
"code": null,
"e": 26200,
"s": 26161,
"text": "Method 3: Applying to_numeric function"
},
{
"code": null,
"e": 26258,
"s": 26200,
"text": "to_numeric function converts arguments to a numeric type."
},
{
"code": null,
"e": 26267,
"s": 26258,
"text": "Example:"
},
{
"code": null,
"e": 26275,
"s": 26267,
"text": "Python3"
},
{
"code": "import pandas as pd num = {'data': [1,\"hjghjd\",3,\"jxsh\"]}df = pd.DataFrame(num) # this will convert non-numeric # values into NaN valuesdf = pd.to_numeric(df[\"data\"], errors='coerce') df",
"e": 26465,
"s": 26275,
"text": null
},
{
"code": null,
"e": 26473,
"s": 26465,
"text": "Output:"
},
{
"code": null,
"e": 26485,
"s": 26473,
"text": "anikaseth98"
},
{
"code": null,
"e": 26509,
"s": 26485,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26523,
"s": 26509,
"text": "Python-pandas"
},
{
"code": null,
"e": 26530,
"s": 26523,
"text": "Python"
},
{
"code": null,
"e": 26628,
"s": 26530,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26660,
"s": 26628,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26702,
"s": 26660,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26744,
"s": 26702,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26771,
"s": 26744,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26827,
"s": 26771,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26866,
"s": 26827,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26888,
"s": 26866,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26919,
"s": 26888,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26948,
"s": 26919,
"text": "Create a directory in Python"
}
]
|
Count of groups having largest size while grouping according to sum of its digits - GeeksforGeeks | 21 Nov, 2021
Given an integer N, the task is to find the number of groups having the largest size. Each number from 1 to N is grouped according to the sum of its digits.
Examples:
Input: N = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according to the sum of its digits of numbers from 1 to 13: [1, 10] [2, 11] [3, 12] [4, 13] [5] [6] [7] [8] [9]. Out of these, 4 groups have the largest size that is 2.
Input: n = 2 Output: 2 Explanation: There are 2 groups in total. [1] [2] and both the groups have largest size 1.
Approach: To solve the problem mentioned above we need to create a dictionary whose key represents the unique sum of digits of numbers from 1 to N. The values of those keys will keep count how many numbers have the sum equal to its key. Then we will print the highest value among all of them.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation to Count the// number of groups having the largest// size where groups are according// to the sum of its digits#include <bits/stdc++.h>using namespace std; // function to return sum of digits of iint sumDigits(int n){ int sum = 0; while(n) { sum += n%10; n /= 10; } return sum;} // Create the dictionary of unique summap<int,int> constDict(int n){ // dictionary that contain // unique sum count map<int,int> d; for(int i = 1; i < n + 1; ++i){ // calculate the sum of its digits int sum1 = sumDigits(i); if(d.find(sum1) == d.end()) d[sum1] = 1; else d[sum1] += 1; } return d;} // function to find the// largest size of groupint countLargest(int n){ map<int,int> d = constDict(n); int size = 0; // count of largest size group int count = 0; for(auto it = d.begin(); it != d.end(); ++it){ int k = it->first; int val = it->second; if(val > size){ size = val; count = 1; } else if(val == size) count += 1; } return count;} // Driver codeint main(){ int n = 13; int group = countLargest(n); cout << group << endl; return 0;}
// Java implementation to Count the // number of groups having the largest // size where groups are according // to the sum of its digitsimport java.util.HashMap;import java.util.Map; class GFG{ // Function to return sum of digits of ipublic static int sumDigits(int n){ int sum = 0; while(n != 0) { sum += n % 10; n /= 10; } return sum;} // Create the dictionary of unique sum public static HashMap<Integer, Integer> constDict(int n){ // dictionary that contain // unique sum count HashMap<Integer, Integer> d = new HashMap<>(); for(int i = 1; i < n + 1; ++i) { // Calculate the sum of its digits int sum1 = sumDigits(i); if (!d.containsKey(sum1)) d.put(sum1, 1); else d.put(sum1, d.get(sum1) + 1); } return d;} // Function to find the // largest size of group public static int countLargest(int n){ HashMap<Integer, Integer> d = constDict(n); int size = 0; // Count of largest size group int count = 0; for(Map.Entry<Integer, Integer> it : d.entrySet()) { int k = it.getKey(); int val = it.getValue(); if (val > size) { size = val; count = 1; } else if (val == size) count += 1; } return count;} // Driver codepublic static void main(String[] args){ int n = 13; int group = countLargest(n); System.out.println(group);}} // This code is contributed by divyeshrabadiya07
# Python3 implementation to Count the# number of groups having the largest# size where groups are according# to the sum of its digits # Create the dictionary of unique sumdef constDict(n): # dictionary that contain # unique sum count d ={} for i in range(1, n + 1): # convert each number to string s = str(i) # make list of number digits l = list(s) # calculate the sum of its digits sum1 = sum(map(int, l)) if sum1 not in d: d[sum1] = 1 else: d[sum1] += 1 return d # function to find the# largest size of groupdef countLargest(n): d = constDict(n) size = 0 # count of largest size group count = 0 for k, val in d.items(): if val > size: size = val count = 1 elif val == size: count += 1 return count # Driver Coden = 13group = countLargest(n)print(group) # This code is contributed by Sanjit_Prasad
// C# implementation to Count the // number of groups having the largest // size where groups are according // to the sum of its digitsusing System;using System.Collections.Generic;class GFG { // Function to return sum of digits of i static int sumDigits(int n) { int sum = 0; while(n != 0) { sum += n % 10; n /= 10; } return sum; } // Create the dictionary of unique sum static Dictionary<int, int> constDict(int n) { // dictionary that contain // unique sum count Dictionary<int, int> d = new Dictionary<int, int>(); for(int i = 1; i < n + 1; ++i) { // Calculate the sum of its digits int sum1 = sumDigits(i); if (!d.ContainsKey(sum1)) d.Add(sum1, 1); else d[sum1] += 1; } return d; } // Function to find the // largest size of group static int countLargest(int n) { Dictionary<int, int> d = constDict(n); int size = 0; // Count of largest size group int count = 0; foreach(KeyValuePair<int, int> it in d) { int k = it.Key; int val = it.Value; if (val > size) { size = val; count = 1; } else if (val == size) count += 1; } return count; } // Driver code static void Main() { int n = 13; int group = countLargest(n); Console.WriteLine(group); }} // This code is contributed by divyesh072019
4
Time Complexity: O(N)
Auxiliary Space: O(N)
Sanjit_Prasad
divyeshrabadiya07
divyesh072019
rishavmahato348
number-digits
Python dictionary-programs
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Check if a number is Palindrome
Generate all permutation of a set in Python
Program to multiply two matrices
Segment Tree | Set 1 (Sum of given range)
Merge two sorted arrays with O(1) extra space
Count ways to reach the n'th stair
How to check if a given point lies inside or outside a polygon? | [
{
"code": null,
"e": 25961,
"s": 25933,
"text": "\n21 Nov, 2021"
},
{
"code": null,
"e": 26118,
"s": 25961,
"text": "Given an integer N, the task is to find the number of groups having the largest size. Each number from 1 to N is grouped according to the sum of its digits."
},
{
"code": null,
"e": 26128,
"s": 26118,
"text": "Examples:"
},
{
"code": null,
"e": 26380,
"s": 26128,
"text": "Input: N = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according to the sum of its digits of numbers from 1 to 13: [1, 10] [2, 11] [3, 12] [4, 13] [5] [6] [7] [8] [9]. Out of these, 4 groups have the largest size that is 2."
},
{
"code": null,
"e": 26495,
"s": 26380,
"text": "Input: n = 2 Output: 2 Explanation: There are 2 groups in total. [1] [2] and both the groups have largest size 1. "
},
{
"code": null,
"e": 26788,
"s": 26495,
"text": "Approach: To solve the problem mentioned above we need to create a dictionary whose key represents the unique sum of digits of numbers from 1 to N. The values of those keys will keep count how many numbers have the sum equal to its key. Then we will print the highest value among all of them."
},
{
"code": null,
"e": 26840,
"s": 26788,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26844,
"s": 26840,
"text": "C++"
},
{
"code": null,
"e": 26849,
"s": 26844,
"text": "Java"
},
{
"code": null,
"e": 26857,
"s": 26849,
"text": "Python3"
},
{
"code": null,
"e": 26860,
"s": 26857,
"text": "C#"
},
{
"code": "// C++ implementation to Count the// number of groups having the largest// size where groups are according// to the sum of its digits#include <bits/stdc++.h>using namespace std; // function to return sum of digits of iint sumDigits(int n){ int sum = 0; while(n) { sum += n%10; n /= 10; } return sum;} // Create the dictionary of unique summap<int,int> constDict(int n){ // dictionary that contain // unique sum count map<int,int> d; for(int i = 1; i < n + 1; ++i){ // calculate the sum of its digits int sum1 = sumDigits(i); if(d.find(sum1) == d.end()) d[sum1] = 1; else d[sum1] += 1; } return d;} // function to find the// largest size of groupint countLargest(int n){ map<int,int> d = constDict(n); int size = 0; // count of largest size group int count = 0; for(auto it = d.begin(); it != d.end(); ++it){ int k = it->first; int val = it->second; if(val > size){ size = val; count = 1; } else if(val == size) count += 1; } return count;} // Driver codeint main(){ int n = 13; int group = countLargest(n); cout << group << endl; return 0;}",
"e": 28161,
"s": 26860,
"text": null
},
{
"code": "// Java implementation to Count the // number of groups having the largest // size where groups are according // to the sum of its digitsimport java.util.HashMap;import java.util.Map; class GFG{ // Function to return sum of digits of ipublic static int sumDigits(int n){ int sum = 0; while(n != 0) { sum += n % 10; n /= 10; } return sum;} // Create the dictionary of unique sum public static HashMap<Integer, Integer> constDict(int n){ // dictionary that contain // unique sum count HashMap<Integer, Integer> d = new HashMap<>(); for(int i = 1; i < n + 1; ++i) { // Calculate the sum of its digits int sum1 = sumDigits(i); if (!d.containsKey(sum1)) d.put(sum1, 1); else d.put(sum1, d.get(sum1) + 1); } return d;} // Function to find the // largest size of group public static int countLargest(int n){ HashMap<Integer, Integer> d = constDict(n); int size = 0; // Count of largest size group int count = 0; for(Map.Entry<Integer, Integer> it : d.entrySet()) { int k = it.getKey(); int val = it.getValue(); if (val > size) { size = val; count = 1; } else if (val == size) count += 1; } return count;} // Driver codepublic static void main(String[] args){ int n = 13; int group = countLargest(n); System.out.println(group);}} // This code is contributed by divyeshrabadiya07",
"e": 29729,
"s": 28161,
"text": null
},
{
"code": "# Python3 implementation to Count the# number of groups having the largest# size where groups are according# to the sum of its digits # Create the dictionary of unique sumdef constDict(n): # dictionary that contain # unique sum count d ={} for i in range(1, n + 1): # convert each number to string s = str(i) # make list of number digits l = list(s) # calculate the sum of its digits sum1 = sum(map(int, l)) if sum1 not in d: d[sum1] = 1 else: d[sum1] += 1 return d # function to find the# largest size of groupdef countLargest(n): d = constDict(n) size = 0 # count of largest size group count = 0 for k, val in d.items(): if val > size: size = val count = 1 elif val == size: count += 1 return count # Driver Coden = 13group = countLargest(n)print(group) # This code is contributed by Sanjit_Prasad",
"e": 30824,
"s": 29729,
"text": null
},
{
"code": "// C# implementation to Count the // number of groups having the largest // size where groups are according // to the sum of its digitsusing System;using System.Collections.Generic;class GFG { // Function to return sum of digits of i static int sumDigits(int n) { int sum = 0; while(n != 0) { sum += n % 10; n /= 10; } return sum; } // Create the dictionary of unique sum static Dictionary<int, int> constDict(int n) { // dictionary that contain // unique sum count Dictionary<int, int> d = new Dictionary<int, int>(); for(int i = 1; i < n + 1; ++i) { // Calculate the sum of its digits int sum1 = sumDigits(i); if (!d.ContainsKey(sum1)) d.Add(sum1, 1); else d[sum1] += 1; } return d; } // Function to find the // largest size of group static int countLargest(int n) { Dictionary<int, int> d = constDict(n); int size = 0; // Count of largest size group int count = 0; foreach(KeyValuePair<int, int> it in d) { int k = it.Key; int val = it.Value; if (val > size) { size = val; count = 1; } else if (val == size) count += 1; } return count; } // Driver code static void Main() { int n = 13; int group = countLargest(n); Console.WriteLine(group); }} // This code is contributed by divyesh072019",
"e": 32575,
"s": 30824,
"text": null
},
{
"code": null,
"e": 32577,
"s": 32575,
"text": "4"
},
{
"code": null,
"e": 32601,
"s": 32579,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 32624,
"s": 32601,
"text": "Auxiliary Space: O(N) "
},
{
"code": null,
"e": 32638,
"s": 32624,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 32656,
"s": 32638,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 32670,
"s": 32656,
"text": "divyesh072019"
},
{
"code": null,
"e": 32686,
"s": 32670,
"text": "rishavmahato348"
},
{
"code": null,
"e": 32700,
"s": 32686,
"text": "number-digits"
},
{
"code": null,
"e": 32727,
"s": 32700,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 32740,
"s": 32727,
"text": "Mathematical"
},
{
"code": null,
"e": 32753,
"s": 32740,
"text": "Mathematical"
},
{
"code": null,
"e": 32851,
"s": 32753,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32895,
"s": 32851,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 32926,
"s": 32895,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 32951,
"s": 32926,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 32983,
"s": 32951,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 33027,
"s": 32983,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 33060,
"s": 33027,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33102,
"s": 33060,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 33148,
"s": 33102,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 33183,
"s": 33148,
"text": "Count ways to reach the n'th stair"
}
]
|
Sum of squares of Fibonacci numbers - GeeksforGeeks | 14 Sep, 2021
Given a positive integer N. The task is to find the sum of squares of all Fibonacci numbers up to N-th fibonacci number. That is,
f02 + f12 + f22+.......+fn2
where fi indicates i-th fibonacci number.
Fibonacci numbers: f0=0 and f1=1 and fi=fi-1 + fi-2 for all i>=2.Examples:
Input: N = 3
Output: 6
Explanation: 0 + 1 + 1 + 4 = 6
Input: N = 6
Output: 104
Explanation: 0 + 1 + 1 + 4 + 9 + 25 + 64 = 104
Method 1: Find all Fibonacci numbers till N and add up their squares. This method will take O(n) time complexity.Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find sum of// squares of Fibonacci numbers#include <bits/stdc++.h>using namespace std; // Function to calculate sum of// squares of Fibonacci numbersint calculateSquareSum(int n){ if (n <= 0) return 0; int fibo[n + 1]; fibo[0] = 0, fibo[1] = 1; // Initialize result int sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += (fibo[i] * fibo[i]); } return sum;} // Driver program to test above functionint main(){ int n = 6; cout << "Sum of squares of Fibonacci numbers is : " << calculateSquareSum(n) << endl; return 0;}
// Java Program to find sum of// squares of Fibonacci numbers public class Improve { // Function to calculate sum of // squares of Fibonacci numbers static int calculateSquareSum(int n) { if (n <= 0) return 0; int fibo[] = new int[n+1]; fibo[0] = 0 ; fibo[1] = 1 ; // Initialize result int sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += (fibo[i] * fibo[i]); } return sum; } // Driver code public static void main(String args[]) { int n = 6; System.out.println("Sum of squares of Fibonacci numbers is : " + calculateSquareSum(n)); } // This Code is contributed by ANKITRAI1}
# Python3 Program to find sum of# squares of Fibonacci numbers # Function to calculate sum of# squares of Fibonacci numbersdef calculateSquareSum(n): fibo = [0] * (n + 1); if (n <= 0): return 0; fibo[0] = 0; fibo[1] = 1; # Initialize result sum = ((fibo[0] * fibo[0]) + (fibo[1] * fibo[1])); # Add remaining terms for i in range(2, n + 1): fibo[i] = (fibo[i - 1] + fibo[i - 2]); sum += (fibo[i] * fibo[i]); return sum; # Driver Coden = 6; print("Sum of squares of Fibonacci numbers is :", calculateSquareSum(n)); # This Code is contributed by mits
// C# Program to find sum of// squares of Fibonacci numbers using System;public class Improve { // Function to calculate sum of // squares of Fibonacci numbers static int calculateSquareSum(int n) { if (n <= 0) return 0; int[] fibo = new int[n+1]; fibo[0] = 0 ; fibo[1] = 1 ; // Initialize result int sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += (fibo[i] * fibo[i]); } return sum; } // Driver code public static void Main() { int n = 6; Console.Write("Sum of squares of Fibonacci numbers is : " + calculateSquareSum(n)); } }
<?php// PHP Program to find sum of// squares of Fibonacci numbers // Function to calculate sum of// squares of Fibonacci numbersfunction calculateSquareSum($n){ if ($n <= 0) return 0; $fibo[0] = 0; $fibo[1] = 1; // Initialize result $sum = ($fibo[0] * $fibo[0]) + ($fibo[1] * $fibo[1]); // Add remaining terms for ($i = 2; $i <= $n; $i++) { $fibo[$i] = $fibo[$i - 1] + $fibo[$i - 2]; $sum += ($fibo[$i] * $fibo[$i]); } return $sum;} // Driver Code$n = 6; echo "Sum of squares of Fibonacci numbers is : ", calculateSquareSum($n); // This Code is contributed by ajit?>
<script> // Javascript Program to find sum of// squares of Fibonacci numbers // Function to calculate sum of // squares of Fibonacci numbers function calculateSquareSum(n) { if (n <= 0) return 0; var fibo = Array(n + 1).fill(0); fibo[0] = 0; fibo[1] = 1; // Initialize result var sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]); // Add remaining terms for (i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += (fibo[i] * fibo[i]); } return sum; } // Driver code var n = 6; document.write("Sum of squares of Fibonacci numbers is :"+ calculateSquareSum(n)); // This code contributed by gauravrajput1 </script>
Sum of squares of Fibonacci numbers is : 104
Method 2: We know that for i-th fibonacci number,
fi+1 = fi + fi-1 for all i>0
Or, fi = fi+1 - fi-1 for all i>0
Or, fi2 = fifi+1 - fi-1fi
So for any n>0 we see,
f02 + f12 + f22+.......+fn2 = f02 + ( f1f2– f0f1)+(f2f3 – f1f2 ) +.............+ (fnfn+1 – fn-1fn ) = fnfn+1 (Since f0 = 0)
This identity also satisfies for n=0 ( For n=0, f02 = 0 = f0 f1 ) .Therefore, to find the sum, it is only needed to find fn and fn+1. To find fn in O(log n) time. Refer to Method 5 or method 6 of this article.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find sum of squares of// Fibonacci numbers in O(Log n) time.#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Create an array for memoizationint f[MAX] = { 0 }; // Returns n'th Fibonacci number using table f[]int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; int k = (n & 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n];} // Function to calculate sum of// squares of Fibonacci numbersint calculateSumOfSquares(int n){ return fib(n) * fib(n + 1);} // Driver Codeint main(){ int n = 6; cout << "Sum of Squares of Fibonacci numbers is : " << calculateSumOfSquares(n) << endl; return 0;}
// Java Program to find sum of squares of// Fibonacci numbers in O(Log n) time. class gfg { static int[] f = new int[1000];// Create an array for memoization // Returns n'th Fibonacci number using table f[] public static int fib(int n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] > 0) { return f[n]; } int k = ((n & 1) > 0) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = ((n & 1) > 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to calculate sum of// squares of Fibonacci numbers public static int calculateSumOfSquares(int n) { return fib(n) * fib(n + 1); }} // Driver Codeclass geek { public static void main(String[] args) { gfg g = new gfg(); int n = 6; System.out.println("Sum of Squares of Fibonacci numbers is : " + g.calculateSumOfSquares(n)); } }// This code is contributed by PrinciRaj1992
# Python3 program to find sum of squares# of Fibonacci numbers in O(Log n) time.MAX = 1000 # Create an array for memoizationf = [0 for i in range(MAX)] # Returns n'th Fibonacci number using# table f[]def fib(n): # Base cases if n == 0: return 0 if n == 1 or n == 2: return 1 # If fib(n) is already computed if f[n]: return f[n] if n & 1: k = (n + 1) // 2 else: k = n // 2 # Applying above formula[Note value # n & 1 is 1 if n is odd, else 0]. if n & 1: f[n] = (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) else: f[n] = ((2 * fib(k - 1) + fib(k)) * fib(k)) return f[n] # Function to calculate sum of# squares of Fibonacci numbersdef calculateSumOfSquares(n): return fib(n) * fib(n + 1) # Driver Coden = 6print("Sum of Squares of " "Fibonacci numbers is :", calculateSumOfSquares(n)) # This code is contributed by Gaurav Kumar Tailor
// C# Program to find sum of squares of// Fibonacci numbers in O(Log n) time.using System;class gfg{ int []f = new int [1000]; // Create an array for memoization // Returns n'th Fibonacci number using table f[] public int fib(int n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]>0) return f[n]; int k = ((n & 1)>0) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = ((n & 1)>0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to calculate sum of// squares of Fibonacci numberspublic int calculateSumOfSquares(int n) { return fib(n) * fib(n + 1); }} // Driver Codeclass geek{ public static int Main() { gfg g = new gfg(); int n = 6; Console.WriteLine( "Sum of Squares of Fibonacci numbers is : {0}", g.calculateSumOfSquares(n)); return 0; } }
<?php// PHP Program to find sum of squares of// Fibonacci numbers in O(Log n) time. $MAX = 1000;global $f; // Create an array for memoization$f = array_fill(0, $MAX, 0); // Returns n'th Fibonacci number// using table f[]function fib($n){ // Base cases if ($n == 0) return 0; if ($n == 1 || $n == 2) return ($f[$n] = 1); $k = ($n & 1) ? ($n + 1) / 2 : $n / 2; // Applying above formula [Note value // n&1 is 1 if n is odd, else 0]. $f[$n] = ($n & 1) ? (fib($k) * fib($k) + fib($k - 1) * fib($k - 1)) : (2 * fib($k - 1) + fib($k)) * fib($k); return $f[$n];} // Function to calculate sum of// squares of Fibonacci numbersfunction calculateSumOfSquares( $n){ return fib($n) * fib($n + 1);} // Driver Code$n = 6; echo "Sum of Squares of Fibonacci numbers is : ";echo calculateSumOfSquares($n); // This code is contributed by Rajput-Ji?>
<script> // Javascript Program to find sum of squares of // Fibonacci numbers in O(Log n) time. // Create an array for memoization let f = new Array(1000); f.fill(0); // Returns n'th Fibonacci number using table f[] function fib(n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] > 0) { return f[n]; } let k = ((n & 1) > 0) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = ((n & 1) > 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to calculate sum of // squares of Fibonacci numbers function calculateSumOfSquares(n) { return fib(n) * fib(n + 1); } let n = 6; document.write("Sum of Squares of Fibonacci numbers is : " + calculateSumOfSquares(n)); </script>
Sum of Squares of Fibonacci numbers is : 104
ankthon
ukasp
jit_t
SoumikMondal
princiraj1992
Mithun Kumar
Rajput-Ji
gauravtailorthoi
GauravRajput1
suresh07
surindertarika1234
Fibonacci
series
series-sum
Technical Scripter 2018
C++ Programs
Mathematical
Mathematical
series
Fibonacci
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
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)
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 25876,
"s": 25848,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 26008,
"s": 25876,
"text": "Given a positive integer N. The task is to find the sum of squares of all Fibonacci numbers up to N-th fibonacci number. That is, "
},
{
"code": null,
"e": 26080,
"s": 26008,
"text": "f02 + f12 + f22+.......+fn2 \n\nwhere fi indicates i-th fibonacci number."
},
{
"code": null,
"e": 26157,
"s": 26080,
"text": "Fibonacci numbers: f0=0 and f1=1 and fi=fi-1 + fi-2 for all i>=2.Examples: "
},
{
"code": null,
"e": 26284,
"s": 26157,
"text": "Input: N = 3\nOutput: 6\nExplanation: 0 + 1 + 1 + 4 = 6\n\nInput: N = 6\nOutput: 104\nExplanation: 0 + 1 + 1 + 4 + 9 + 25 + 64 = 104"
},
{
"code": null,
"e": 26447,
"s": 26286,
"text": "Method 1: Find all Fibonacci numbers till N and add up their squares. This method will take O(n) time complexity.Below is the implementation of this approach: "
},
{
"code": null,
"e": 26451,
"s": 26447,
"text": "C++"
},
{
"code": null,
"e": 26456,
"s": 26451,
"text": "Java"
},
{
"code": null,
"e": 26464,
"s": 26456,
"text": "Python3"
},
{
"code": null,
"e": 26467,
"s": 26464,
"text": "C#"
},
{
"code": null,
"e": 26471,
"s": 26467,
"text": "PHP"
},
{
"code": null,
"e": 26482,
"s": 26471,
"text": "Javascript"
},
{
"code": "// C++ Program to find sum of// squares of Fibonacci numbers#include <bits/stdc++.h>using namespace std; // Function to calculate sum of// squares of Fibonacci numbersint calculateSquareSum(int n){ if (n <= 0) return 0; int fibo[n + 1]; fibo[0] = 0, fibo[1] = 1; // Initialize result int sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += (fibo[i] * fibo[i]); } return sum;} // Driver program to test above functionint main(){ int n = 6; cout << \"Sum of squares of Fibonacci numbers is : \" << calculateSquareSum(n) << endl; return 0;}",
"e": 27184,
"s": 26482,
"text": null
},
{
"code": "// Java Program to find sum of// squares of Fibonacci numbers public class Improve { // Function to calculate sum of // squares of Fibonacci numbers static int calculateSquareSum(int n) { if (n <= 0) return 0; int fibo[] = new int[n+1]; fibo[0] = 0 ; fibo[1] = 1 ; // Initialize result int sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += (fibo[i] * fibo[i]); } return sum; } // Driver code public static void main(String args[]) { int n = 6; System.out.println(\"Sum of squares of Fibonacci numbers is : \" + calculateSquareSum(n)); } // This Code is contributed by ANKITRAI1}",
"e": 28096,
"s": 27184,
"text": null
},
{
"code": "# Python3 Program to find sum of# squares of Fibonacci numbers # Function to calculate sum of# squares of Fibonacci numbersdef calculateSquareSum(n): fibo = [0] * (n + 1); if (n <= 0): return 0; fibo[0] = 0; fibo[1] = 1; # Initialize result sum = ((fibo[0] * fibo[0]) + (fibo[1] * fibo[1])); # Add remaining terms for i in range(2, n + 1): fibo[i] = (fibo[i - 1] + fibo[i - 2]); sum += (fibo[i] * fibo[i]); return sum; # Driver Coden = 6; print(\"Sum of squares of Fibonacci numbers is :\", calculateSquareSum(n)); # This Code is contributed by mits",
"e": 28756,
"s": 28096,
"text": null
},
{
"code": "// C# Program to find sum of// squares of Fibonacci numbers using System;public class Improve { // Function to calculate sum of // squares of Fibonacci numbers static int calculateSquareSum(int n) { if (n <= 0) return 0; int[] fibo = new int[n+1]; fibo[0] = 0 ; fibo[1] = 1 ; // Initialize result int sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]); // Add remaining terms for (int i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += (fibo[i] * fibo[i]); } return sum; } // Driver code public static void Main() { int n = 6; Console.Write(\"Sum of squares of Fibonacci numbers is : \" + calculateSquareSum(n)); } }",
"e": 29628,
"s": 28756,
"text": null
},
{
"code": "<?php// PHP Program to find sum of// squares of Fibonacci numbers // Function to calculate sum of// squares of Fibonacci numbersfunction calculateSquareSum($n){ if ($n <= 0) return 0; $fibo[0] = 0; $fibo[1] = 1; // Initialize result $sum = ($fibo[0] * $fibo[0]) + ($fibo[1] * $fibo[1]); // Add remaining terms for ($i = 2; $i <= $n; $i++) { $fibo[$i] = $fibo[$i - 1] + $fibo[$i - 2]; $sum += ($fibo[$i] * $fibo[$i]); } return $sum;} // Driver Code$n = 6; echo \"Sum of squares of Fibonacci numbers is : \", calculateSquareSum($n); // This Code is contributed by ajit?>",
"e": 30303,
"s": 29628,
"text": null
},
{
"code": "<script> // Javascript Program to find sum of// squares of Fibonacci numbers // Function to calculate sum of // squares of Fibonacci numbers function calculateSquareSum(n) { if (n <= 0) return 0; var fibo = Array(n + 1).fill(0); fibo[0] = 0; fibo[1] = 1; // Initialize result var sum = (fibo[0] * fibo[0]) + (fibo[1] * fibo[1]); // Add remaining terms for (i = 2; i <= n; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; sum += (fibo[i] * fibo[i]); } return sum; } // Driver code var n = 6; document.write(\"Sum of squares of Fibonacci numbers is :\"+ calculateSquareSum(n)); // This code contributed by gauravrajput1 </script>",
"e": 31089,
"s": 30303,
"text": null
},
{
"code": null,
"e": 31134,
"s": 31089,
"text": "Sum of squares of Fibonacci numbers is : 104"
},
{
"code": null,
"e": 31187,
"s": 31136,
"text": "Method 2: We know that for i-th fibonacci number, "
},
{
"code": null,
"e": 31277,
"s": 31187,
"text": "fi+1 = fi + fi-1 for all i>0\n\nOr, fi = fi+1 - fi-1 for all i>0\nOr, fi2 = fifi+1 - fi-1fi"
},
{
"code": null,
"e": 31301,
"s": 31277,
"text": "So for any n>0 we see, "
},
{
"code": null,
"e": 31427,
"s": 31301,
"text": "f02 + f12 + f22+.......+fn2 = f02 + ( f1f2– f0f1)+(f2f3 – f1f2 ) +.............+ (fnfn+1 – fn-1fn ) = fnfn+1 (Since f0 = 0) "
},
{
"code": null,
"e": 31689,
"s": 31427,
"text": "This identity also satisfies for n=0 ( For n=0, f02 = 0 = f0 f1 ) .Therefore, to find the sum, it is only needed to find fn and fn+1. To find fn in O(log n) time. Refer to Method 5 or method 6 of this article.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31693,
"s": 31689,
"text": "C++"
},
{
"code": null,
"e": 31698,
"s": 31693,
"text": "Java"
},
{
"code": null,
"e": 31706,
"s": 31698,
"text": "Python3"
},
{
"code": null,
"e": 31709,
"s": 31706,
"text": "C#"
},
{
"code": null,
"e": 31713,
"s": 31709,
"text": "PHP"
},
{
"code": null,
"e": 31724,
"s": 31713,
"text": "Javascript"
},
{
"code": "// C++ Program to find sum of squares of// Fibonacci numbers in O(Log n) time.#include <bits/stdc++.h>using namespace std;const int MAX = 1000; // Create an array for memoizationint f[MAX] = { 0 }; // Returns n'th Fibonacci number using table f[]int fib(int n){ // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]) return f[n]; int k = (n & 1) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = (n & 1) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n];} // Function to calculate sum of// squares of Fibonacci numbersint calculateSumOfSquares(int n){ return fib(n) * fib(n + 1);} // Driver Codeint main(){ int n = 6; cout << \"Sum of Squares of Fibonacci numbers is : \" << calculateSumOfSquares(n) << endl; return 0;}",
"e": 32700,
"s": 31724,
"text": null
},
{
"code": "// Java Program to find sum of squares of// Fibonacci numbers in O(Log n) time. class gfg { static int[] f = new int[1000];// Create an array for memoization // Returns n'th Fibonacci number using table f[] public static int fib(int n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] > 0) { return f[n]; } int k = ((n & 1) > 0) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = ((n & 1) > 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to calculate sum of// squares of Fibonacci numbers public static int calculateSumOfSquares(int n) { return fib(n) * fib(n + 1); }} // Driver Codeclass geek { public static void main(String[] args) { gfg g = new gfg(); int n = 6; System.out.println(\"Sum of Squares of Fibonacci numbers is : \" + g.calculateSumOfSquares(n)); } }// This code is contributed by PrinciRaj1992",
"e": 33931,
"s": 32700,
"text": null
},
{
"code": "# Python3 program to find sum of squares# of Fibonacci numbers in O(Log n) time.MAX = 1000 # Create an array for memoizationf = [0 for i in range(MAX)] # Returns n'th Fibonacci number using# table f[]def fib(n): # Base cases if n == 0: return 0 if n == 1 or n == 2: return 1 # If fib(n) is already computed if f[n]: return f[n] if n & 1: k = (n + 1) // 2 else: k = n // 2 # Applying above formula[Note value # n & 1 is 1 if n is odd, else 0]. if n & 1: f[n] = (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) else: f[n] = ((2 * fib(k - 1) + fib(k)) * fib(k)) return f[n] # Function to calculate sum of# squares of Fibonacci numbersdef calculateSumOfSquares(n): return fib(n) * fib(n + 1) # Driver Coden = 6print(\"Sum of Squares of \" \"Fibonacci numbers is :\", calculateSumOfSquares(n)) # This code is contributed by Gaurav Kumar Tailor",
"e": 34903,
"s": 33931,
"text": null
},
{
"code": "// C# Program to find sum of squares of// Fibonacci numbers in O(Log n) time.using System;class gfg{ int []f = new int [1000]; // Create an array for memoization // Returns n'th Fibonacci number using table f[] public int fib(int n) { // Base cases if (n == 0) return 0; if (n == 1 || n == 2) return (f[n] = 1); // If fib(n) is already computed if (f[n]>0) return f[n]; int k = ((n & 1)>0) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = ((n & 1)>0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to calculate sum of// squares of Fibonacci numberspublic int calculateSumOfSquares(int n) { return fib(n) * fib(n + 1); }} // Driver Codeclass geek{ public static int Main() { gfg g = new gfg(); int n = 6; Console.WriteLine( \"Sum of Squares of Fibonacci numbers is : {0}\", g.calculateSumOfSquares(n)); return 0; } }",
"e": 35931,
"s": 34903,
"text": null
},
{
"code": "<?php// PHP Program to find sum of squares of// Fibonacci numbers in O(Log n) time. $MAX = 1000;global $f; // Create an array for memoization$f = array_fill(0, $MAX, 0); // Returns n'th Fibonacci number// using table f[]function fib($n){ // Base cases if ($n == 0) return 0; if ($n == 1 || $n == 2) return ($f[$n] = 1); $k = ($n & 1) ? ($n + 1) / 2 : $n / 2; // Applying above formula [Note value // n&1 is 1 if n is odd, else 0]. $f[$n] = ($n & 1) ? (fib($k) * fib($k) + fib($k - 1) * fib($k - 1)) : (2 * fib($k - 1) + fib($k)) * fib($k); return $f[$n];} // Function to calculate sum of// squares of Fibonacci numbersfunction calculateSumOfSquares( $n){ return fib($n) * fib($n + 1);} // Driver Code$n = 6; echo \"Sum of Squares of Fibonacci numbers is : \";echo calculateSumOfSquares($n); // This code is contributed by Rajput-Ji?>",
"e": 36850,
"s": 35931,
"text": null
},
{
"code": "<script> // Javascript Program to find sum of squares of // Fibonacci numbers in O(Log n) time. // Create an array for memoization let f = new Array(1000); f.fill(0); // Returns n'th Fibonacci number using table f[] function fib(n) { // Base cases if (n == 0) { return 0; } if (n == 1 || n == 2) { return (f[n] = 1); } // If fib(n) is already computed if (f[n] > 0) { return f[n]; } let k = ((n & 1) > 0) ? (n + 1) / 2 : n / 2; // Applying above formula [Note value n&1 is 1 // if n is odd, else 0]. f[n] = ((n & 1) > 0) ? (fib(k) * fib(k) + fib(k - 1) * fib(k - 1)) : (2 * fib(k - 1) + fib(k)) * fib(k); return f[n]; } // Function to calculate sum of // squares of Fibonacci numbers function calculateSumOfSquares(n) { return fib(n) * fib(n + 1); } let n = 6; document.write(\"Sum of Squares of Fibonacci numbers is : \" + calculateSumOfSquares(n)); </script>",
"e": 37947,
"s": 36850,
"text": null
},
{
"code": null,
"e": 37992,
"s": 37947,
"text": "Sum of Squares of Fibonacci numbers is : 104"
},
{
"code": null,
"e": 38002,
"s": 37994,
"text": "ankthon"
},
{
"code": null,
"e": 38008,
"s": 38002,
"text": "ukasp"
},
{
"code": null,
"e": 38014,
"s": 38008,
"text": "jit_t"
},
{
"code": null,
"e": 38027,
"s": 38014,
"text": "SoumikMondal"
},
{
"code": null,
"e": 38041,
"s": 38027,
"text": "princiraj1992"
},
{
"code": null,
"e": 38054,
"s": 38041,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 38064,
"s": 38054,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38081,
"s": 38064,
"text": "gauravtailorthoi"
},
{
"code": null,
"e": 38095,
"s": 38081,
"text": "GauravRajput1"
},
{
"code": null,
"e": 38104,
"s": 38095,
"text": "suresh07"
},
{
"code": null,
"e": 38123,
"s": 38104,
"text": "surindertarika1234"
},
{
"code": null,
"e": 38133,
"s": 38123,
"text": "Fibonacci"
},
{
"code": null,
"e": 38140,
"s": 38133,
"text": "series"
},
{
"code": null,
"e": 38151,
"s": 38140,
"text": "series-sum"
},
{
"code": null,
"e": 38175,
"s": 38151,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 38188,
"s": 38175,
"text": "C++ Programs"
},
{
"code": null,
"e": 38201,
"s": 38188,
"text": "Mathematical"
},
{
"code": null,
"e": 38214,
"s": 38201,
"text": "Mathematical"
},
{
"code": null,
"e": 38221,
"s": 38214,
"text": "series"
},
{
"code": null,
"e": 38231,
"s": 38221,
"text": "Fibonacci"
},
{
"code": null,
"e": 38329,
"s": 38231,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38370,
"s": 38329,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 38429,
"s": 38370,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 38450,
"s": 38429,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 38462,
"s": 38450,
"text": "cout in C++"
},
{
"code": null,
"e": 38483,
"s": 38462,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 38513,
"s": 38483,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38528,
"s": 38513,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38588,
"s": 38528,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38631,
"s": 38588,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
PHP | die() & sleep() functions - GeeksforGeeks | 11 Apr, 2022
die()
The die() is an inbuilt function in PHP. It is used to print message and exit from the current php script. It is equivalent to exit() function in PHP. Syntax :
die($message)
Parameters : This function accepts only one parameter and which is not mandatory to be passed.
$message : This parameter represents the message to printed while exiting from script.
Return Value : It has no return value but prints given message while exiting the script.
Examples :
Input : die("code ends here")
Output : code ends here
Here, die() function ends the
script with a message "code
ends here "
Applicable versions : This function is applicable in all PHP4 and later versions.
Program :
PHP
<?php// blank url of site// so that die() is executed$site = ""; // open url else die (exit)fopen($site, "r")or die("Unable to connect to given site.");?>
Output :
Unable to connect to given site.
sleep()
The sleep() is an inbuilt function in PHP. It is used to delay the execution of the program for given amount of seconds.
Syntax :
int sleep(int $seconds)
Parameters : This function accepts only one parameter and which is mandatory to be passed.
$seconds : This parameter represents the delay time in seconds.
Return Value : It returns zero on success, or FALSE on error. This function returns a non-zero value if the call was interrupted by a signal.
Errors / Exceptions : This function generates E_WARNING when the number of seconds is negative.
Applicable versions : This function is applicable in PHP 4, PHP 5, PHP 7.
Program :
PHP
<?php// initial timingsecho date('h:i:s') . "\n"; // halt for 5 secondssleep(5); // timings after haltecho date('h:i:s');?>
Output :
01:07:16
01:07:21
Note that, Timing after halt (sleep) is 5 seconds more than timings before halt (sleep).
References: http://php.net/manual/en/function.die.php http://php.net/manual/en/function.sleep.php
Let us see both the functions in a Tabular form -:
mayank007rawa
PHP-function
PHP
Web Technologies
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 pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26049,
"s": 26021,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 26055,
"s": 26049,
"text": "die()"
},
{
"code": null,
"e": 26215,
"s": 26055,
"text": "The die() is an inbuilt function in PHP. It is used to print message and exit from the current php script. It is equivalent to exit() function in PHP. Syntax :"
},
{
"code": null,
"e": 26229,
"s": 26215,
"text": "die($message)"
},
{
"code": null,
"e": 26324,
"s": 26229,
"text": "Parameters : This function accepts only one parameter and which is not mandatory to be passed."
},
{
"code": null,
"e": 26411,
"s": 26324,
"text": "$message : This parameter represents the message to printed while exiting from script."
},
{
"code": null,
"e": 26501,
"s": 26411,
"text": "Return Value : It has no return value but prints given message while exiting the script. "
},
{
"code": null,
"e": 26512,
"s": 26501,
"text": "Examples :"
},
{
"code": null,
"e": 26638,
"s": 26512,
"text": "Input : die(\"code ends here\")\nOutput : code ends here\n\nHere, die() function ends the \nscript with a message \"code\nends here \""
},
{
"code": null,
"e": 26721,
"s": 26638,
"text": "Applicable versions : This function is applicable in all PHP4 and later versions. "
},
{
"code": null,
"e": 26732,
"s": 26721,
"text": "Program : "
},
{
"code": null,
"e": 26736,
"s": 26732,
"text": "PHP"
},
{
"code": "<?php// blank url of site// so that die() is executed$site = \"\"; // open url else die (exit)fopen($site, \"r\")or die(\"Unable to connect to given site.\");?>",
"e": 26891,
"s": 26736,
"text": null
},
{
"code": null,
"e": 26900,
"s": 26891,
"text": "Output :"
},
{
"code": null,
"e": 26933,
"s": 26900,
"text": "Unable to connect to given site."
},
{
"code": null,
"e": 26941,
"s": 26933,
"text": "sleep()"
},
{
"code": null,
"e": 27063,
"s": 26941,
"text": "The sleep() is an inbuilt function in PHP. It is used to delay the execution of the program for given amount of seconds. "
},
{
"code": null,
"e": 27072,
"s": 27063,
"text": "Syntax :"
},
{
"code": null,
"e": 27096,
"s": 27072,
"text": "int sleep(int $seconds)"
},
{
"code": null,
"e": 27187,
"s": 27096,
"text": "Parameters : This function accepts only one parameter and which is mandatory to be passed."
},
{
"code": null,
"e": 27251,
"s": 27187,
"text": "$seconds : This parameter represents the delay time in seconds."
},
{
"code": null,
"e": 27394,
"s": 27251,
"text": "Return Value : It returns zero on success, or FALSE on error. This function returns a non-zero value if the call was interrupted by a signal. "
},
{
"code": null,
"e": 27491,
"s": 27394,
"text": "Errors / Exceptions : This function generates E_WARNING when the number of seconds is negative. "
},
{
"code": null,
"e": 27566,
"s": 27491,
"text": "Applicable versions : This function is applicable in PHP 4, PHP 5, PHP 7. "
},
{
"code": null,
"e": 27577,
"s": 27566,
"text": "Program : "
},
{
"code": null,
"e": 27581,
"s": 27577,
"text": "PHP"
},
{
"code": "<?php// initial timingsecho date('h:i:s') . \"\\n\"; // halt for 5 secondssleep(5); // timings after haltecho date('h:i:s');?>",
"e": 27705,
"s": 27581,
"text": null
},
{
"code": null,
"e": 27714,
"s": 27705,
"text": "Output :"
},
{
"code": null,
"e": 27732,
"s": 27714,
"text": "01:07:16\n01:07:21"
},
{
"code": null,
"e": 27822,
"s": 27732,
"text": "Note that, Timing after halt (sleep) is 5 seconds more than timings before halt (sleep). "
},
{
"code": null,
"e": 27920,
"s": 27822,
"text": "References: http://php.net/manual/en/function.die.php http://php.net/manual/en/function.sleep.php"
},
{
"code": null,
"e": 27971,
"s": 27920,
"text": "Let us see both the functions in a Tabular form -:"
},
{
"code": null,
"e": 27985,
"s": 27971,
"text": "mayank007rawa"
},
{
"code": null,
"e": 27998,
"s": 27985,
"text": "PHP-function"
},
{
"code": null,
"e": 28002,
"s": 27998,
"text": "PHP"
},
{
"code": null,
"e": 28019,
"s": 28002,
"text": "Web Technologies"
},
{
"code": null,
"e": 28023,
"s": 28019,
"text": "PHP"
},
{
"code": null,
"e": 28121,
"s": 28023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28161,
"s": 28121,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28206,
"s": 28161,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 28248,
"s": 28206,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 28300,
"s": 28248,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 28333,
"s": 28300,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 28373,
"s": 28333,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28406,
"s": 28373,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28451,
"s": 28406,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28494,
"s": 28451,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Implement Undo and Redo features of a Text Editor - GeeksforGeeks | 27 Aug, 2021
Given an array of strings Q[], consisting of queries of the following types:
“WRITE X”: Write a character X into the document.
“UNDO”: Erases the last change made to the document.
“REDO”: Restores the most recent UNDO operation performed on the document.
“READ”: Reads and prints the contents of the documents.
Examples:
Input: Q = {“WRITE A”, “WRITE B”, “WRITE C”, “UNDO”, “READ”, “REDO”, “READ”}Output: AB ABCExplanation: Perform “WRITE A” on the document. Therefore, the document contains only “A”.Perform “WRITE B” on the document. Therefore, the document contains “AB”.Perform “WRITE C” on the document. Therefore, the document contains “ABC”.Perform “UNDO” on the document. Therefore, the document contains “AB”.Print the contents of the document, i.e. “AB”Perform “REDO” on the document. Therefore, the document contains “ABC”.Print the contents of the document, i.e. “ABC”
Input: Q = {“WRITE x”, “WRITE y”, “UNDO”, “WRITE z”, “READ”, “REDO”, “READ”}Output:xz xzy
Approach: The problem can be solved using Stack. Follow the steps below to solve the problem:
Initialize two stacks, say Undo and Redo.
Traverse the array of strings, Q, and perform the following operations:
If “WRITE” string is encountered, push the character to Undo stack
If “UNDO” string is encountered, pop the top element from Undo stack and push it to Redo stack.
If “REDO” string is encountered, pop the top element of Redo stack and push it into the Undo stack.
If “READ” string is encountered, print all the elements of the Undo stack in reverse order.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to perform// "WRITE X" operationvoid WRITE(stack<char>& Undo, char X){ // Push an element to // the top of stack Undo.push(X);} // Function to perform// "UNDO" operationvoid UNDO(stack<char>& Undo, stack<char>& Redo){ // Stores top element // of the stack char X = Undo.top(); // Erase top element // of the stack Undo.pop(); // Push an element to // the top of stack Redo.push(X);} // Function to perform// "REDO" operationvoid REDO(stack<char>& Undo, stack<char>& Redo){ // Stores the top element // of the stack char X = Redo.top(); // Erase the top element // of the stack Redo.pop(); // Push an element to // the top of the stack Undo.push(X);} // Function to perform// "READ" operationvoid READ(stack<char> Undo){ // Store elements of stack // in reverse order stack<char> revOrder; // Traverse Undo stack while (!Undo.empty()) { // Push an element to // the top of stack revOrder.push(Undo.top()); // Erase top element // of stack Undo.pop(); } while (!revOrder.empty()) { // Print the top element // of the stack cout << revOrder.top(); Undo.push(revOrder.top()); // Erase the top element // of the stack revOrder.pop(); } cout << " ";} // Function to perform the// queries on the documentvoid QUERY(vector<string> Q){ // Stores the history of all // the queries that have been // processed on the document stack<char> Undo; // Stores the elements // of REDO query stack<char> Redo; // Stores total count // of queries int N = Q.size(); // Traverse all the query for (int i = 0; i < N; i++) { if (Q[i] == "UNDO") { UNDO(Undo, Redo); } else if (Q[i] == "REDO") { REDO(Undo, Redo); } else if (Q[i] == "READ") { READ(Undo); } else { WRITE(Undo, Q[i][6]); } }} // Driver Codeint main(){ vector<string> Q = { "WRITE A", "WRITE B", "WRITE C", "UNDO", "READ", "REDO", "READ" }; QUERY(Q); return 0;}
// Java Program to implement the above approachimport java.util.*;public class Main{ // Stores the history of all // the queries that have been // processed on the document static Stack<Character> Undo = new Stack<Character>(); // Stores the elements // of REDO query static Stack<Character> Redo = new Stack<Character>(); // Function to perform // "WRITE X" operation static void WRITE(Stack<Character> Undo, char X) { // Push an element to // the top of stack Undo.push(X); } // Function to perform // "UNDO" operation static void UNDO(Stack<Character> Undo, Stack<Character> Redo) { // Stores top element // of the stack char X = (char)Undo.peek(); // Erase top element // of the stack Undo.pop(); // Push an element to // the top of stack Redo.push(X); } // Function to perform // "REDO" operation static void REDO(Stack<Character> Undo, Stack<Character> Redo) { // Stores the top element // of the stack char X = (char)Redo.peek(); // Erase the top element // of the stack Redo.pop(); // Push an element to // the top of the stack Undo.push(X); } // Function to perform // "READ" operation static void READ(Stack<Character> Undo) { // Store elements of stack // in reverse order Stack<Character> revOrder = new Stack<Character>(); // Traverse Undo stack while (Undo.size() > 0) { // Push an element to // the top of stack revOrder.push(Undo.peek()); // Erase top element // of stack Undo.pop(); } while (revOrder.size() > 0) { // Print the top element // of the stack System.out.print(revOrder.peek()); Undo.push(revOrder.peek()); // Erase the top element // of the stack revOrder.pop(); } System.out.print(" "); } // Function to perform the // queries on the document static void QUERY(String[] Q) { // Stores total count // of queries int N = Q.length; // Traverse all the query for (int i = 0; i < N; i++) { if(Q[i] == "UNDO") { UNDO(Undo, Redo); } else if(Q[i] == "REDO") { REDO(Undo, Redo); } else if(Q[i] == "READ") { READ(Undo); } else { WRITE(Undo, Q[i].charAt(6)); } } } public static void main(String[] args) { String[] Q = { "WRITE A", "WRITE B", "WRITE C", "UNDO", "READ", "REDO", "READ" }; QUERY(Q); }} // This code is contributed by divyeshrabadiya07.
# Python Program to implement# the above approachglobal Undoglobal Redo # Stores the history of all# the queries that have been# processed on the documentUndo = [] # Stores the elements# of REDO queryRedo = [] # Function to perform# "WRITE X" operationdef WRITE(Undo, X): # Push an element to # the top of stack Undo.append(X) # Function to perform# "UNDO" operationdef UNDO(Undo, Redo): # Stores top element # of the stack X = Undo[-1] # Erase top element # of the stack Undo.pop() # Push an element to # the top of stack Redo.append(X) # Function to perform# "REDO" operationdef REDO(Undo, Redo): # Stores the top element # of the stack X = Redo[-1] # Erase the top element # of the stack Redo.pop() # Push an element to # the top of the stack Undo.append(X) # Function to perform# "READ" operationdef READ(Undo): print(*Undo, sep = "", end = " ") # Function to perform the# queries on the documentdef QUERY(Q): # Stores total count # of queries N = len(Q) # Traverse all the query for i in range(N): if(Q[i] == "UNDO"): UNDO(Undo, Redo) elif(Q[i] == "REDO"): REDO(Undo, Redo) elif(Q[i] == "READ"): READ(Undo) else: WRITE(Undo, Q[i][6]) # Driver CodeQ = ["WRITE A", "WRITE B", "WRITE C", "UNDO", "READ", "REDO", "READ"]QUERY(Q) #This code is contributed by avanitrachhadiya2155
// C# Program to implement the above approachusing System;using System.Collections;class GFG { // Stores the history of all // the queries that have been // processed on the document static Stack Undo = new Stack(); // Stores the elements // of REDO query static Stack Redo = new Stack(); // Function to perform // "WRITE X" operation static void WRITE(Stack Undo, char X) { // Push an element to // the top of stack Undo.Push(X); } // Function to perform // "UNDO" operation static void UNDO(Stack Undo, Stack Redo) { // Stores top element // of the stack char X = (char)Undo.Peek(); // Erase top element // of the stack Undo.Pop(); // Push an element to // the top of stack Redo.Push(X); } // Function to perform // "REDO" operation static void REDO(Stack Undo, Stack Redo) { // Stores the top element // of the stack char X = (char)Redo.Peek(); // Erase the top element // of the stack Redo.Pop(); // Push an element to // the top of the stack Undo.Push(X); } // Function to perform // "READ" operation static void READ(Stack Undo) { // Store elements of stack // in reverse order Stack revOrder = new Stack(); // Traverse Undo stack while (Undo.Count > 0) { // Push an element to // the top of stack revOrder.Push(Undo.Peek()); // Erase top element // of stack Undo.Pop(); } while (revOrder.Count > 0) { // Print the top element // of the stack Console.Write(revOrder.Peek()); Undo.Push(revOrder.Peek()); // Erase the top element // of the stack revOrder.Pop(); } Console.Write(" "); } // Function to perform the // queries on the document static void QUERY(string[] Q) { // Stores total count // of queries int N = Q.Length; // Traverse all the query for (int i = 0; i < N; i++) { if(Q[i] == "UNDO") { UNDO(Undo, Redo); } else if(Q[i] == "REDO") { REDO(Undo, Redo); } else if(Q[i] == "READ") { READ(Undo); } else { WRITE(Undo, Q[i][6]); } } } static void Main() { string[] Q = { "WRITE A", "WRITE B", "WRITE C", "UNDO", "READ", "REDO", "READ" }; QUERY(Q); }} // This code is contributed by rameshtravel07
<script> // Javascript Program to implement the above approach // Stores the history of all // the queries that have been // processed on the document let Undo = []; // Stores the elements // of REDO query let Redo = []; // Function to perform // "WRITE X" operation function WRITE(Undo, X) { // Push an element to // the top of stack Undo.push(X) } // Function to perform // "UNDO" operation function UNDO(Undo, Redo) { // Stores top element // of the stack let X = Undo[Undo.length - 1]; // Erase top element // of the stack Undo.pop(); // Push an element to // the top of stack Redo.push(X); } // Function to perform // "REDO" operation function REDO(Undo, Redo) { // Stores the top element // of the stack let X = Redo[Redo.length - 1]; // Erase the top element // of the stack Redo.pop(); // Push an element to // the top of the stack Undo.push(X); } // Function to perform // "READ" operation function READ(Undo) { // Store elements of stack // in reverse order let revOrder = []; // Traverse Undo stack while (Undo.length > 0) { // Push an element to // the top of stack revOrder.push(Undo[Undo.length - 1]); // Erase top element // of stack Undo.pop(); } while (revOrder.length > 0) { // Print the top element // of the stack document.write(revOrder[revOrder.length - 1]); Undo.push(revOrder[revOrder.length - 1]); // Erase the top element // of the stack revOrder.pop(); } document.write(" "); } // Function to perform the // queries on the document function QUERY(Q) { // Stores total count // of queries N = Q.length // Traverse all the query for (let i = 0; i < N; i++) { if(Q[i] == "UNDO") { UNDO(Undo, Redo); } else if(Q[i] == "REDO") { REDO(Undo, Redo); } else if(Q[i] == "READ") { READ(Undo); } else { WRITE(Undo, Q[i][6]); } } } let Q = [ "WRITE A", "WRITE B", "WRITE C", "UNDO", "READ", "REDO", "READ" ]; QUERY(Q); // This code is contributed by suresh07.</script>
AB ABC
Time Complexity:UNDO: O(1)REDO: O(1)WRITE: O(1)READ: (N), where N denotes the size of the Undo stackAuxiliary Space: O(N)
avanitrachhadiya2155
srivastavaharshit848
suresh07
rameshtravel07
divyeshrabadiya07
Amazon
Amazon-Question
cpp-stack
interview-preparation
Arrays
Data Structures
Stack
Strings
Amazon
Data Structures
Arrays
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Introduction to Algorithms | [
{
"code": null,
"e": 26687,
"s": 26659,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 26764,
"s": 26687,
"text": "Given an array of strings Q[], consisting of queries of the following types:"
},
{
"code": null,
"e": 26814,
"s": 26764,
"text": "“WRITE X”: Write a character X into the document."
},
{
"code": null,
"e": 26867,
"s": 26814,
"text": "“UNDO”: Erases the last change made to the document."
},
{
"code": null,
"e": 26942,
"s": 26867,
"text": "“REDO”: Restores the most recent UNDO operation performed on the document."
},
{
"code": null,
"e": 26998,
"s": 26942,
"text": "“READ”: Reads and prints the contents of the documents."
},
{
"code": null,
"e": 27008,
"s": 26998,
"text": "Examples:"
},
{
"code": null,
"e": 27568,
"s": 27008,
"text": "Input: Q = {“WRITE A”, “WRITE B”, “WRITE C”, “UNDO”, “READ”, “REDO”, “READ”}Output: AB ABCExplanation: Perform “WRITE A” on the document. Therefore, the document contains only “A”.Perform “WRITE B” on the document. Therefore, the document contains “AB”.Perform “WRITE C” on the document. Therefore, the document contains “ABC”.Perform “UNDO” on the document. Therefore, the document contains “AB”.Print the contents of the document, i.e. “AB”Perform “REDO” on the document. Therefore, the document contains “ABC”.Print the contents of the document, i.e. “ABC”"
},
{
"code": null,
"e": 27658,
"s": 27568,
"text": "Input: Q = {“WRITE x”, “WRITE y”, “UNDO”, “WRITE z”, “READ”, “REDO”, “READ”}Output:xz xzy"
},
{
"code": null,
"e": 27752,
"s": 27658,
"text": "Approach: The problem can be solved using Stack. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27794,
"s": 27752,
"text": "Initialize two stacks, say Undo and Redo."
},
{
"code": null,
"e": 27866,
"s": 27794,
"text": "Traverse the array of strings, Q, and perform the following operations:"
},
{
"code": null,
"e": 27933,
"s": 27866,
"text": "If “WRITE” string is encountered, push the character to Undo stack"
},
{
"code": null,
"e": 28029,
"s": 27933,
"text": "If “UNDO” string is encountered, pop the top element from Undo stack and push it to Redo stack."
},
{
"code": null,
"e": 28129,
"s": 28029,
"text": "If “REDO” string is encountered, pop the top element of Redo stack and push it into the Undo stack."
},
{
"code": null,
"e": 28221,
"s": 28129,
"text": "If “READ” string is encountered, print all the elements of the Undo stack in reverse order."
},
{
"code": null,
"e": 28272,
"s": 28221,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28276,
"s": 28272,
"text": "C++"
},
{
"code": null,
"e": 28281,
"s": 28276,
"text": "Java"
},
{
"code": null,
"e": 28289,
"s": 28281,
"text": "Python3"
},
{
"code": null,
"e": 28292,
"s": 28289,
"text": "C#"
},
{
"code": null,
"e": 28303,
"s": 28292,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to perform// \"WRITE X\" operationvoid WRITE(stack<char>& Undo, char X){ // Push an element to // the top of stack Undo.push(X);} // Function to perform// \"UNDO\" operationvoid UNDO(stack<char>& Undo, stack<char>& Redo){ // Stores top element // of the stack char X = Undo.top(); // Erase top element // of the stack Undo.pop(); // Push an element to // the top of stack Redo.push(X);} // Function to perform// \"REDO\" operationvoid REDO(stack<char>& Undo, stack<char>& Redo){ // Stores the top element // of the stack char X = Redo.top(); // Erase the top element // of the stack Redo.pop(); // Push an element to // the top of the stack Undo.push(X);} // Function to perform// \"READ\" operationvoid READ(stack<char> Undo){ // Store elements of stack // in reverse order stack<char> revOrder; // Traverse Undo stack while (!Undo.empty()) { // Push an element to // the top of stack revOrder.push(Undo.top()); // Erase top element // of stack Undo.pop(); } while (!revOrder.empty()) { // Print the top element // of the stack cout << revOrder.top(); Undo.push(revOrder.top()); // Erase the top element // of the stack revOrder.pop(); } cout << \" \";} // Function to perform the// queries on the documentvoid QUERY(vector<string> Q){ // Stores the history of all // the queries that have been // processed on the document stack<char> Undo; // Stores the elements // of REDO query stack<char> Redo; // Stores total count // of queries int N = Q.size(); // Traverse all the query for (int i = 0; i < N; i++) { if (Q[i] == \"UNDO\") { UNDO(Undo, Redo); } else if (Q[i] == \"REDO\") { REDO(Undo, Redo); } else if (Q[i] == \"READ\") { READ(Undo); } else { WRITE(Undo, Q[i][6]); } }} // Driver Codeint main(){ vector<string> Q = { \"WRITE A\", \"WRITE B\", \"WRITE C\", \"UNDO\", \"READ\", \"REDO\", \"READ\" }; QUERY(Q); return 0;}",
"e": 30624,
"s": 28303,
"text": null
},
{
"code": "// Java Program to implement the above approachimport java.util.*;public class Main{ // Stores the history of all // the queries that have been // processed on the document static Stack<Character> Undo = new Stack<Character>(); // Stores the elements // of REDO query static Stack<Character> Redo = new Stack<Character>(); // Function to perform // \"WRITE X\" operation static void WRITE(Stack<Character> Undo, char X) { // Push an element to // the top of stack Undo.push(X); } // Function to perform // \"UNDO\" operation static void UNDO(Stack<Character> Undo, Stack<Character> Redo) { // Stores top element // of the stack char X = (char)Undo.peek(); // Erase top element // of the stack Undo.pop(); // Push an element to // the top of stack Redo.push(X); } // Function to perform // \"REDO\" operation static void REDO(Stack<Character> Undo, Stack<Character> Redo) { // Stores the top element // of the stack char X = (char)Redo.peek(); // Erase the top element // of the stack Redo.pop(); // Push an element to // the top of the stack Undo.push(X); } // Function to perform // \"READ\" operation static void READ(Stack<Character> Undo) { // Store elements of stack // in reverse order Stack<Character> revOrder = new Stack<Character>(); // Traverse Undo stack while (Undo.size() > 0) { // Push an element to // the top of stack revOrder.push(Undo.peek()); // Erase top element // of stack Undo.pop(); } while (revOrder.size() > 0) { // Print the top element // of the stack System.out.print(revOrder.peek()); Undo.push(revOrder.peek()); // Erase the top element // of the stack revOrder.pop(); } System.out.print(\" \"); } // Function to perform the // queries on the document static void QUERY(String[] Q) { // Stores total count // of queries int N = Q.length; // Traverse all the query for (int i = 0; i < N; i++) { if(Q[i] == \"UNDO\") { UNDO(Undo, Redo); } else if(Q[i] == \"REDO\") { REDO(Undo, Redo); } else if(Q[i] == \"READ\") { READ(Undo); } else { WRITE(Undo, Q[i].charAt(6)); } } } public static void main(String[] args) { String[] Q = { \"WRITE A\", \"WRITE B\", \"WRITE C\", \"UNDO\", \"READ\", \"REDO\", \"READ\" }; QUERY(Q); }} // This code is contributed by divyeshrabadiya07.",
"e": 33605,
"s": 30624,
"text": null
},
{
"code": "# Python Program to implement# the above approachglobal Undoglobal Redo # Stores the history of all# the queries that have been# processed on the documentUndo = [] # Stores the elements# of REDO queryRedo = [] # Function to perform# \"WRITE X\" operationdef WRITE(Undo, X): # Push an element to # the top of stack Undo.append(X) # Function to perform# \"UNDO\" operationdef UNDO(Undo, Redo): # Stores top element # of the stack X = Undo[-1] # Erase top element # of the stack Undo.pop() # Push an element to # the top of stack Redo.append(X) # Function to perform# \"REDO\" operationdef REDO(Undo, Redo): # Stores the top element # of the stack X = Redo[-1] # Erase the top element # of the stack Redo.pop() # Push an element to # the top of the stack Undo.append(X) # Function to perform# \"READ\" operationdef READ(Undo): print(*Undo, sep = \"\", end = \" \") # Function to perform the# queries on the documentdef QUERY(Q): # Stores total count # of queries N = len(Q) # Traverse all the query for i in range(N): if(Q[i] == \"UNDO\"): UNDO(Undo, Redo) elif(Q[i] == \"REDO\"): REDO(Undo, Redo) elif(Q[i] == \"READ\"): READ(Undo) else: WRITE(Undo, Q[i][6]) # Driver CodeQ = [\"WRITE A\", \"WRITE B\", \"WRITE C\", \"UNDO\", \"READ\", \"REDO\", \"READ\"]QUERY(Q) #This code is contributed by avanitrachhadiya2155",
"e": 35060,
"s": 33605,
"text": null
},
{
"code": "// C# Program to implement the above approachusing System;using System.Collections;class GFG { // Stores the history of all // the queries that have been // processed on the document static Stack Undo = new Stack(); // Stores the elements // of REDO query static Stack Redo = new Stack(); // Function to perform // \"WRITE X\" operation static void WRITE(Stack Undo, char X) { // Push an element to // the top of stack Undo.Push(X); } // Function to perform // \"UNDO\" operation static void UNDO(Stack Undo, Stack Redo) { // Stores top element // of the stack char X = (char)Undo.Peek(); // Erase top element // of the stack Undo.Pop(); // Push an element to // the top of stack Redo.Push(X); } // Function to perform // \"REDO\" operation static void REDO(Stack Undo, Stack Redo) { // Stores the top element // of the stack char X = (char)Redo.Peek(); // Erase the top element // of the stack Redo.Pop(); // Push an element to // the top of the stack Undo.Push(X); } // Function to perform // \"READ\" operation static void READ(Stack Undo) { // Store elements of stack // in reverse order Stack revOrder = new Stack(); // Traverse Undo stack while (Undo.Count > 0) { // Push an element to // the top of stack revOrder.Push(Undo.Peek()); // Erase top element // of stack Undo.Pop(); } while (revOrder.Count > 0) { // Print the top element // of the stack Console.Write(revOrder.Peek()); Undo.Push(revOrder.Peek()); // Erase the top element // of the stack revOrder.Pop(); } Console.Write(\" \"); } // Function to perform the // queries on the document static void QUERY(string[] Q) { // Stores total count // of queries int N = Q.Length; // Traverse all the query for (int i = 0; i < N; i++) { if(Q[i] == \"UNDO\") { UNDO(Undo, Redo); } else if(Q[i] == \"REDO\") { REDO(Undo, Redo); } else if(Q[i] == \"READ\") { READ(Undo); } else { WRITE(Undo, Q[i][6]); } } } static void Main() { string[] Q = { \"WRITE A\", \"WRITE B\", \"WRITE C\", \"UNDO\", \"READ\", \"REDO\", \"READ\" }; QUERY(Q); }} // This code is contributed by rameshtravel07",
"e": 37873,
"s": 35060,
"text": null
},
{
"code": "<script> // Javascript Program to implement the above approach // Stores the history of all // the queries that have been // processed on the document let Undo = []; // Stores the elements // of REDO query let Redo = []; // Function to perform // \"WRITE X\" operation function WRITE(Undo, X) { // Push an element to // the top of stack Undo.push(X) } // Function to perform // \"UNDO\" operation function UNDO(Undo, Redo) { // Stores top element // of the stack let X = Undo[Undo.length - 1]; // Erase top element // of the stack Undo.pop(); // Push an element to // the top of stack Redo.push(X); } // Function to perform // \"REDO\" operation function REDO(Undo, Redo) { // Stores the top element // of the stack let X = Redo[Redo.length - 1]; // Erase the top element // of the stack Redo.pop(); // Push an element to // the top of the stack Undo.push(X); } // Function to perform // \"READ\" operation function READ(Undo) { // Store elements of stack // in reverse order let revOrder = []; // Traverse Undo stack while (Undo.length > 0) { // Push an element to // the top of stack revOrder.push(Undo[Undo.length - 1]); // Erase top element // of stack Undo.pop(); } while (revOrder.length > 0) { // Print the top element // of the stack document.write(revOrder[revOrder.length - 1]); Undo.push(revOrder[revOrder.length - 1]); // Erase the top element // of the stack revOrder.pop(); } document.write(\" \"); } // Function to perform the // queries on the document function QUERY(Q) { // Stores total count // of queries N = Q.length // Traverse all the query for (let i = 0; i < N; i++) { if(Q[i] == \"UNDO\") { UNDO(Undo, Redo); } else if(Q[i] == \"REDO\") { REDO(Undo, Redo); } else if(Q[i] == \"READ\") { READ(Undo); } else { WRITE(Undo, Q[i][6]); } } } let Q = [ \"WRITE A\", \"WRITE B\", \"WRITE C\", \"UNDO\", \"READ\", \"REDO\", \"READ\" ]; QUERY(Q); // This code is contributed by suresh07.</script>",
"e": 40539,
"s": 37873,
"text": null
},
{
"code": null,
"e": 40546,
"s": 40539,
"text": "AB ABC"
},
{
"code": null,
"e": 40670,
"s": 40548,
"text": "Time Complexity:UNDO: O(1)REDO: O(1)WRITE: O(1)READ: (N), where N denotes the size of the Undo stackAuxiliary Space: O(N)"
},
{
"code": null,
"e": 40691,
"s": 40670,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 40712,
"s": 40691,
"text": "srivastavaharshit848"
},
{
"code": null,
"e": 40721,
"s": 40712,
"text": "suresh07"
},
{
"code": null,
"e": 40736,
"s": 40721,
"text": "rameshtravel07"
},
{
"code": null,
"e": 40754,
"s": 40736,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 40761,
"s": 40754,
"text": "Amazon"
},
{
"code": null,
"e": 40777,
"s": 40761,
"text": "Amazon-Question"
},
{
"code": null,
"e": 40787,
"s": 40777,
"text": "cpp-stack"
},
{
"code": null,
"e": 40809,
"s": 40787,
"text": "interview-preparation"
},
{
"code": null,
"e": 40816,
"s": 40809,
"text": "Arrays"
},
{
"code": null,
"e": 40832,
"s": 40816,
"text": "Data Structures"
},
{
"code": null,
"e": 40838,
"s": 40832,
"text": "Stack"
},
{
"code": null,
"e": 40846,
"s": 40838,
"text": "Strings"
},
{
"code": null,
"e": 40853,
"s": 40846,
"text": "Amazon"
},
{
"code": null,
"e": 40869,
"s": 40853,
"text": "Data Structures"
},
{
"code": null,
"e": 40876,
"s": 40869,
"text": "Arrays"
},
{
"code": null,
"e": 40884,
"s": 40876,
"text": "Strings"
},
{
"code": null,
"e": 40890,
"s": 40884,
"text": "Stack"
},
{
"code": null,
"e": 40988,
"s": 40890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41056,
"s": 40988,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 41100,
"s": 41056,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 41148,
"s": 41100,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 41171,
"s": 41148,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 41203,
"s": 41171,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 41252,
"s": 41203,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 41296,
"s": 41252,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 41321,
"s": 41296,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 41377,
"s": 41321,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
]
|
How to Set Text of Tkinter Text Widget With a Button? - GeeksforGeeks | 23 Dec, 2020
Prerequisite: Python GUI – tkinter
Text Widget is used where a user wants to insert multi-line text fields. In this article, we are going to learn the approaches to set the text inside the text fields of the text widget with the help of a button.
Import the Tkinter module.
Create a GUI window.
Create our text widget
Creating the function to set the text with the help of a button. This function contains one insert method and one delete method. The delete method is called first to delete the remaining text inside the text widget. It will delete anything in the given range of 0 to end.
Then the insert method is called to insert the text we want to push into the text widget. It takes in two parameters, one is the position we want to insert and the second is the desired text we want to set in the form of a string.
The button is created and the function is parsed as a command inside it.
Below is the implementation of the above approach
Python3
# Import the tkinter moduleimport tkinter # Creating the GUI window.window = tkinter.Tk()window.title("Welcome to geeksforgeeks")window.geometry("800x100") # Creating our text widget.sample_text = tkinter.Entry(window)sample_text.pack() # Creating the function to set the text # with the help of buttondef set_text_by_button(): # Delete is going to erase anything # in the range of 0 and end of file, # The respective range given here sample_text.delete(0,"end") # Insert method inserts the text at # specified position, Here it is the # begining sample_text.insert(0, "Text set by button") # Setting up the button, set_text_by_button() # is passed as a commandset_up_button = tkinter.Button(window, height=1, width=10, text="Set", command=set_text_by_button) set_up_button.pack() window.mainloop()
Output:
Picked
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 25572,
"s": 25537,
"text": "Prerequisite: Python GUI – tkinter"
},
{
"code": null,
"e": 25784,
"s": 25572,
"text": "Text Widget is used where a user wants to insert multi-line text fields. In this article, we are going to learn the approaches to set the text inside the text fields of the text widget with the help of a button."
},
{
"code": null,
"e": 25811,
"s": 25784,
"text": "Import the Tkinter module."
},
{
"code": null,
"e": 25832,
"s": 25811,
"text": "Create a GUI window."
},
{
"code": null,
"e": 25855,
"s": 25832,
"text": "Create our text widget"
},
{
"code": null,
"e": 26127,
"s": 25855,
"text": "Creating the function to set the text with the help of a button. This function contains one insert method and one delete method. The delete method is called first to delete the remaining text inside the text widget. It will delete anything in the given range of 0 to end."
},
{
"code": null,
"e": 26358,
"s": 26127,
"text": "Then the insert method is called to insert the text we want to push into the text widget. It takes in two parameters, one is the position we want to insert and the second is the desired text we want to set in the form of a string."
},
{
"code": null,
"e": 26431,
"s": 26358,
"text": "The button is created and the function is parsed as a command inside it."
},
{
"code": null,
"e": 26481,
"s": 26431,
"text": "Below is the implementation of the above approach"
},
{
"code": null,
"e": 26489,
"s": 26481,
"text": "Python3"
},
{
"code": "# Import the tkinter moduleimport tkinter # Creating the GUI window.window = tkinter.Tk()window.title(\"Welcome to geeksforgeeks\")window.geometry(\"800x100\") # Creating our text widget.sample_text = tkinter.Entry(window)sample_text.pack() # Creating the function to set the text # with the help of buttondef set_text_by_button(): # Delete is going to erase anything # in the range of 0 and end of file, # The respective range given here sample_text.delete(0,\"end\") # Insert method inserts the text at # specified position, Here it is the # begining sample_text.insert(0, \"Text set by button\") # Setting up the button, set_text_by_button() # is passed as a commandset_up_button = tkinter.Button(window, height=1, width=10, text=\"Set\", command=set_text_by_button) set_up_button.pack() window.mainloop()",
"e": 27346,
"s": 26489,
"text": null
},
{
"code": null,
"e": 27354,
"s": 27346,
"text": "Output:"
},
{
"code": null,
"e": 27361,
"s": 27354,
"text": "Picked"
},
{
"code": null,
"e": 27376,
"s": 27361,
"text": "Python-tkinter"
},
{
"code": null,
"e": 27383,
"s": 27376,
"text": "Python"
},
{
"code": null,
"e": 27481,
"s": 27383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27513,
"s": 27481,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27555,
"s": 27513,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27597,
"s": 27555,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27653,
"s": 27597,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27680,
"s": 27653,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27711,
"s": 27680,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27750,
"s": 27711,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27779,
"s": 27750,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27801,
"s": 27779,
"text": "Defaultdict in Python"
}
]
|
How to Convert Numbers to Dates in R? - GeeksforGeeks | 28 Dec, 2021
In this article, we will discuss how to convert Numbers to Dates in R programming language.
Here we have to consider an integer and then first we have to convert that integer into a character using as.character() function and then convert that character using as.Date() function and finally convert into date using “%Y%m%d” format
Syntax:
as.Date(as.character(integer),format = “%Y%m%d”)
where, an integer is an input number
Example: Convert Numbers to date
R
# declare an integerdata=2021112 # displayprint( as.Date(as.character(data),format = "%Y%m%d")) # declare an integerdata1=20201209 # displayprint( as.Date(as.character(data1),format = "%Y%m%d"))
Output:
[1] "2021-11-02"
[1] "2020-12-09"
strptime() is used to convert into the date from an integer in the “%Y%m%d” format
Syntax:
strptime(integer, format = "%Y%m%d")
Example: Convert Numbers to date
R
# declare an integerdata=2021112 # displayprint( strptime(data, format = "%Y%m%d")) # declare an integerdata1=20201209 # displayprint( strptime(data1, format = "%Y%m%d"))
Output:
[1] "2021-11-02 UTC"
[1] "2020-12-09 UTC"
Here ymd() is used to convert the integer into year, month, and date which is available in lubridate() package
Syntax:
ymd(integer)
Example: Convert Numbers to date
R
# load the packagelibrary("lubridate") # declare an integerdata=2021112 # displayprint(ymd(data)) # declare an integerdata1=20201209 # displayprint(ymd(data1))
Output:
[1] "202-11-12"
[1] "2020-12-09"
surindertarika1234
Picked
R-DateTime
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
Plot mean and standard deviation using ggplot2 in R | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 26579,
"s": 26487,
"text": "In this article, we will discuss how to convert Numbers to Dates in R programming language."
},
{
"code": null,
"e": 26818,
"s": 26579,
"text": "Here we have to consider an integer and then first we have to convert that integer into a character using as.character() function and then convert that character using as.Date() function and finally convert into date using “%Y%m%d” format"
},
{
"code": null,
"e": 26826,
"s": 26818,
"text": "Syntax:"
},
{
"code": null,
"e": 26876,
"s": 26826,
"text": " as.Date(as.character(integer),format = “%Y%m%d”)"
},
{
"code": null,
"e": 26913,
"s": 26876,
"text": "where, an integer is an input number"
},
{
"code": null,
"e": 26946,
"s": 26913,
"text": "Example: Convert Numbers to date"
},
{
"code": null,
"e": 26948,
"s": 26946,
"text": "R"
},
{
"code": "# declare an integerdata=2021112 # displayprint( as.Date(as.character(data),format = \"%Y%m%d\")) # declare an integerdata1=20201209 # displayprint( as.Date(as.character(data1),format = \"%Y%m%d\"))",
"e": 27143,
"s": 26948,
"text": null
},
{
"code": null,
"e": 27153,
"s": 27143,
"text": " Output: "
},
{
"code": null,
"e": 27187,
"s": 27153,
"text": "[1] \"2021-11-02\"\n[1] \"2020-12-09\""
},
{
"code": null,
"e": 27270,
"s": 27187,
"text": "strptime() is used to convert into the date from an integer in the “%Y%m%d” format"
},
{
"code": null,
"e": 27278,
"s": 27270,
"text": "Syntax:"
},
{
"code": null,
"e": 27315,
"s": 27278,
"text": "strptime(integer, format = \"%Y%m%d\")"
},
{
"code": null,
"e": 27348,
"s": 27315,
"text": "Example: Convert Numbers to date"
},
{
"code": null,
"e": 27350,
"s": 27348,
"text": "R"
},
{
"code": "# declare an integerdata=2021112 # displayprint( strptime(data, format = \"%Y%m%d\")) # declare an integerdata1=20201209 # displayprint( strptime(data1, format = \"%Y%m%d\"))",
"e": 27521,
"s": 27350,
"text": null
},
{
"code": null,
"e": 27530,
"s": 27521,
"text": " Output:"
},
{
"code": null,
"e": 27572,
"s": 27530,
"text": "[1] \"2021-11-02 UTC\"\n[1] \"2020-12-09 UTC\""
},
{
"code": null,
"e": 27684,
"s": 27572,
"text": "Here ymd() is used to convert the integer into year, month, and date which is available in lubridate() package "
},
{
"code": null,
"e": 27692,
"s": 27684,
"text": "Syntax:"
},
{
"code": null,
"e": 27705,
"s": 27692,
"text": "ymd(integer)"
},
{
"code": null,
"e": 27738,
"s": 27705,
"text": "Example: Convert Numbers to date"
},
{
"code": null,
"e": 27740,
"s": 27738,
"text": "R"
},
{
"code": "# load the packagelibrary(\"lubridate\") # declare an integerdata=2021112 # displayprint(ymd(data)) # declare an integerdata1=20201209 # displayprint(ymd(data1))",
"e": 27900,
"s": 27740,
"text": null
},
{
"code": null,
"e": 27909,
"s": 27900,
"text": " Output:"
},
{
"code": null,
"e": 27942,
"s": 27909,
"text": "[1] \"202-11-12\"\n[1] \"2020-12-09\""
},
{
"code": null,
"e": 27961,
"s": 27942,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27968,
"s": 27961,
"text": "Picked"
},
{
"code": null,
"e": 27979,
"s": 27968,
"text": "R-DateTime"
},
{
"code": null,
"e": 27990,
"s": 27979,
"text": "R Language"
},
{
"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": 28140,
"s": 28088,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28175,
"s": 28140,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28213,
"s": 28175,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28271,
"s": 28213,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28314,
"s": 28271,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28363,
"s": 28314,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28400,
"s": 28363,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 28417,
"s": 28400,
"text": "R - if statement"
},
{
"code": null,
"e": 28443,
"s": 28417,
"text": "Time Series Analysis in R"
}
]
|
How to convert CSV columns to text in Python? - GeeksforGeeks | 13 Jan, 2021
In this article, we are going to see how to convert CSV columns to text in Python, and we will also see how to convert all CSV column to text.
Approach:
Read .CSV file using pandas dataframe.
Convert particular column to list using list() constructor
Then sequentially convert each element of the list to a string and join them using a specific character or space.
For our program we are going to use the following CSV file:
Code:
Python3
# importing libraryimport pandas as pd # Then loading csv filedf = pd.read_csv('datasets/Fruit.csv') # converting ;FRUIT_NAME' column into lista = list(df['FRUIT_NAME']) # converting list into string and then joining it with spaceb = ' '.join(str(e) for e in a) # printing resultprint(b) # converting 'PRICE' column into listd = list(df['PRICE']) # another way for joining usede = '\n'.join(map(str, d)) # printing resultprint(e)
Output:
Apple Banana JackFruit Orange Pineapple Guava Grapes Mango
100
70
30
120
90
50
80
200
For this, we don’t need to import any library.
Code:
Python3
# reading csv filetext = open("datasets/Fruit.csv", "r") # joining with space content of texttext = ' '.join([i for i in text]) # replacing ',' by spacetext = text.replace(",", " ") #displaying resultprint(text)
Output:
FRUIT_NAME PRICE
Apple 100
Banana 70
JackFruit 30
Orange 120
Pineapple 90
Guava 50
Grapes 80
Mango 200
Picked
python-csv
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": 25537,
"s": 25509,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 25680,
"s": 25537,
"text": "In this article, we are going to see how to convert CSV columns to text in Python, and we will also see how to convert all CSV column to text."
},
{
"code": null,
"e": 25690,
"s": 25680,
"text": "Approach:"
},
{
"code": null,
"e": 25729,
"s": 25690,
"text": "Read .CSV file using pandas dataframe."
},
{
"code": null,
"e": 25788,
"s": 25729,
"text": "Convert particular column to list using list() constructor"
},
{
"code": null,
"e": 25902,
"s": 25788,
"text": "Then sequentially convert each element of the list to a string and join them using a specific character or space."
},
{
"code": null,
"e": 25962,
"s": 25902,
"text": "For our program we are going to use the following CSV file:"
},
{
"code": null,
"e": 25968,
"s": 25962,
"text": "Code:"
},
{
"code": null,
"e": 25976,
"s": 25968,
"text": "Python3"
},
{
"code": "# importing libraryimport pandas as pd # Then loading csv filedf = pd.read_csv('datasets/Fruit.csv') # converting ;FRUIT_NAME' column into lista = list(df['FRUIT_NAME']) # converting list into string and then joining it with spaceb = ' '.join(str(e) for e in a) # printing resultprint(b) # converting 'PRICE' column into listd = list(df['PRICE']) # another way for joining usede = '\\n'.join(map(str, d)) # printing resultprint(e)",
"e": 26413,
"s": 25976,
"text": null
},
{
"code": null,
"e": 26421,
"s": 26413,
"text": "Output:"
},
{
"code": null,
"e": 26508,
"s": 26421,
"text": "Apple Banana JackFruit Orange Pineapple Guava Grapes Mango\n\n100\n70\n30\n120\n90\n50\n80\n200"
},
{
"code": null,
"e": 26555,
"s": 26508,
"text": "For this, we don’t need to import any library."
},
{
"code": null,
"e": 26561,
"s": 26555,
"text": "Code:"
},
{
"code": null,
"e": 26569,
"s": 26561,
"text": "Python3"
},
{
"code": "# reading csv filetext = open(\"datasets/Fruit.csv\", \"r\") # joining with space content of texttext = ' '.join([i for i in text]) # replacing ',' by spacetext = text.replace(\",\", \" \") #displaying resultprint(text)",
"e": 26788,
"s": 26569,
"text": null
},
{
"code": null,
"e": 26796,
"s": 26788,
"text": "Output:"
},
{
"code": null,
"e": 26899,
"s": 26796,
"text": "FRUIT_NAME PRICE\nApple 100\nBanana 70\nJackFruit 30\nOrange 120\nPineapple 90\nGuava 50\nGrapes 80\nMango 200"
},
{
"code": null,
"e": 26906,
"s": 26899,
"text": "Picked"
},
{
"code": null,
"e": 26917,
"s": 26906,
"text": "python-csv"
},
{
"code": null,
"e": 26924,
"s": 26917,
"text": "Python"
},
{
"code": null,
"e": 27022,
"s": 26924,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27054,
"s": 27022,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27096,
"s": 27054,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27138,
"s": 27096,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27194,
"s": 27138,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27221,
"s": 27194,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27252,
"s": 27221,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27291,
"s": 27252,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27320,
"s": 27291,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27342,
"s": 27320,
"text": "Defaultdict in Python"
}
]
|
How to read a CSV file to a Dataframe with custom delimiter in Pandas? - GeeksforGeeks | 31 May, 2021
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. pandas package is one of them and makes importing and analyzing data so much easier.Here, we will discuss how to load a csv file into a Dataframe. It is done using a pandas.read_csv() method. We have to import pandas library to use this method.
Syntax: pd.read_csv(filepath_or_buffer, sep=’, ‘, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=b’.’, lineterminator=None, quotechar='”‘, quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, doublequote=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None)
Some Useful parameters are given below :
This method uses comma ‘, ‘ as a default delimiter but we can also use a custom delimiter or a regular expression as a separator.For downloading the csv files Click HereExample 1 : Using the read_csv() method with default separator i.e. comma(, )
Python3
# Importing pandas libraryimport pandas as pd # Using the function to load# the data of example.csv# into a Dataframe dfdf = pd.read_csv('example1.csv') # Print the Dataframedf
Output:
Example 2: Using the read_csv() method with ‘_’ as a custom delimiter.
Python3
# Importing pandas libraryimport pandas as pd # Load the data of example.csv# with '_' as custom delimiter# into a Dataframe dfdf = pd.read_csv('example2.csv', sep = '_', engine = 'python') # Print the Dataframedf
Output:
Note:While giving a custom specifier we must specify engine=’python’ otherwise we may get a warning like the one given below:
Example 3 : Using the read_csv() method with tab as a custom delimiter.
Python3
# Importing pandas libraryimport pandas as pd # Load the data of example.csv# with tab as custom delimiter# into a Dataframe dfdf = pd.read_csv('example3.csv', sep = '\t', engine = 'python') # Print the Dataframedf
Output:
Example 4 : Using the read_csv() method with regular expression as custom delimiter.Let’s suppose we have a csv file with multiple type of delimiters such as given below.
totalbill_tip, sex:smoker, day_time, size 16.99, 1.01:Female|No, Sun, Dinner, 2 10.34, 1.66, Male, No|Sun:Dinner, 3 21.01:3.5_Male, No:Sun, Dinner, 3 23.68, 3.31, Male|No, Sun_Dinner, 2 24.59:3.61, Female_No, Sun, Dinner, 4 25.29, 4.71|Male, No:Sun, Dinner, 4
To load such file into a dataframe we use regular expression as a separator.
Python3
# Importing pandas libraryimport pandas as pd # Load the data of example.csv# with regular expression as# custom delimiter into a# Dataframe dfdf = pd.read_csv('example4.csv', sep = '[:, |_]', engine = 'python') # Print the Dataframedf
Output:
saurabh1990aror
anikakapoor
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26267,
"s": 26239,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 26629,
"s": 26267,
"text": "Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. pandas package is one of them and makes importing and analyzing data so much easier.Here, we will discuss how to load a csv file into a Dataframe. It is done using a pandas.read_csv() method. We have to import pandas library to use this method. "
},
{
"code": null,
"e": 27497,
"s": 26629,
"text": "Syntax: pd.read_csv(filepath_or_buffer, sep=’, ‘, delimiter=None, header=’infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression=’infer’, thousands=None, decimal=b’.’, lineterminator=None, quotechar='”‘, quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, doublequote=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None) "
},
{
"code": null,
"e": 27539,
"s": 27497,
"text": "Some Useful parameters are given below : "
},
{
"code": null,
"e": 27789,
"s": 27541,
"text": "This method uses comma ‘, ‘ as a default delimiter but we can also use a custom delimiter or a regular expression as a separator.For downloading the csv files Click HereExample 1 : Using the read_csv() method with default separator i.e. comma(, ) "
},
{
"code": null,
"e": 27797,
"s": 27789,
"text": "Python3"
},
{
"code": "# Importing pandas libraryimport pandas as pd # Using the function to load# the data of example.csv# into a Dataframe dfdf = pd.read_csv('example1.csv') # Print the Dataframedf",
"e": 27974,
"s": 27797,
"text": null
},
{
"code": null,
"e": 27984,
"s": 27974,
"text": "Output: "
},
{
"code": null,
"e": 28056,
"s": 27984,
"text": "Example 2: Using the read_csv() method with ‘_’ as a custom delimiter. "
},
{
"code": null,
"e": 28064,
"s": 28056,
"text": "Python3"
},
{
"code": "# Importing pandas libraryimport pandas as pd # Load the data of example.csv# with '_' as custom delimiter# into a Dataframe dfdf = pd.read_csv('example2.csv', sep = '_', engine = 'python') # Print the Dataframedf",
"e": 28314,
"s": 28064,
"text": null
},
{
"code": null,
"e": 28324,
"s": 28314,
"text": "Output: "
},
{
"code": null,
"e": 28452,
"s": 28324,
"text": "Note:While giving a custom specifier we must specify engine=’python’ otherwise we may get a warning like the one given below: "
},
{
"code": null,
"e": 28525,
"s": 28452,
"text": "Example 3 : Using the read_csv() method with tab as a custom delimiter. "
},
{
"code": null,
"e": 28533,
"s": 28525,
"text": "Python3"
},
{
"code": "# Importing pandas libraryimport pandas as pd # Load the data of example.csv# with tab as custom delimiter# into a Dataframe dfdf = pd.read_csv('example3.csv', sep = '\\t', engine = 'python') # Print the Dataframedf",
"e": 28784,
"s": 28533,
"text": null
},
{
"code": null,
"e": 28794,
"s": 28784,
"text": "Output: "
},
{
"code": null,
"e": 28966,
"s": 28794,
"text": "Example 4 : Using the read_csv() method with regular expression as custom delimiter.Let’s suppose we have a csv file with multiple type of delimiters such as given below. "
},
{
"code": null,
"e": 29227,
"s": 28966,
"text": "totalbill_tip, sex:smoker, day_time, size 16.99, 1.01:Female|No, Sun, Dinner, 2 10.34, 1.66, Male, No|Sun:Dinner, 3 21.01:3.5_Male, No:Sun, Dinner, 3 23.68, 3.31, Male|No, Sun_Dinner, 2 24.59:3.61, Female_No, Sun, Dinner, 4 25.29, 4.71|Male, No:Sun, Dinner, 4 "
},
{
"code": null,
"e": 29305,
"s": 29227,
"text": "To load such file into a dataframe we use regular expression as a separator. "
},
{
"code": null,
"e": 29313,
"s": 29305,
"text": "Python3"
},
{
"code": "# Importing pandas libraryimport pandas as pd # Load the data of example.csv# with regular expression as# custom delimiter into a# Dataframe dfdf = pd.read_csv('example4.csv', sep = '[:, |_]', engine = 'python') # Print the Dataframedf",
"e": 29585,
"s": 29313,
"text": null
},
{
"code": null,
"e": 29595,
"s": 29585,
"text": "Output: "
},
{
"code": null,
"e": 29613,
"s": 29597,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 29625,
"s": 29613,
"text": "anikakapoor"
},
{
"code": null,
"e": 29649,
"s": 29625,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 29663,
"s": 29649,
"text": "Python-pandas"
},
{
"code": null,
"e": 29670,
"s": 29663,
"text": "Python"
},
{
"code": null,
"e": 29768,
"s": 29670,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29786,
"s": 29768,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29821,
"s": 29786,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29853,
"s": 29821,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29875,
"s": 29853,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29917,
"s": 29875,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29947,
"s": 29917,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29973,
"s": 29947,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30002,
"s": 29973,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30046,
"s": 30002,
"text": "Reading and Writing to text files in Python"
}
]
|
Find if a given string can be represented from a substring by iterating the substring “n” times - GeeksforGeeks | 09 May, 2022
Given a string ‘str’, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Examples:
Input: str = "abcabcabc"
Output: true
The given string is 3 times repetition of "abc"
Input: str = "abadabad"
Output: true
The given string is 2 times repetition of "abad"
Input: str = "aabaabaabaab"
Output: true
The given string is 4 times repetition of "aab"
Input: str = "abcdabc"
Output: false
Source: Google Interview Question
There can be many solutions to this problem. The challenging part is to solve the problem in O(n) time. Below is a O(n) algorithm.
Let the given string be ‘str’ and length of given string be ‘n’.1) Find the length of the longest proper prefix of ‘str’ which is also a suffix. Let the length of the longest proper prefix suffix be ‘len’. This can be computed in O(n) time using pre-processing step of KMP string matching algorithm.2) If value of ‘n – len’ divides n (or ‘n % (n-len)’ is 0), then return true, else return false.In case of ‘true’ , the substring ‘str[0..n-len-1]’ is the substring that repeats n/(n-len) times.
Let us take few examples.Input: str = “ABCDABCD”, n = 8 (Number of characters in ‘str’) The value of len is 4 (“ABCD” is the longest substring which is both prefix and suffix) Since (n-len) divides n, the answer is true.Input: str = “ABCDABC”, n = 7 (Number of characters in ‘str’) The value of len is 3 (“ABC” is the longest substring which is both prefix and suffix) Since (n-len) doesn’t divides n, the answer is false.Input: str = “ABCABCABCABCABC”, n = 15 (Number of characters in ‘str’) The value of len is 12 (“ABCABCABCABC” is the longest substring which is both prefix and suffix) Since (n-len) divides n, the answer is true.
How does this work? length of longest proper prefix-suffix (or len) is always between 0 to n-1. If len is n-1, then all characters in string are same. For example len is 3 for “AAAA”. If len is n-2 and n is even, then two characters in string repeat n/2 times. For example “ABABABAB”, length of lps is 6. The reason is if the first n-2 characters are same as last n-2 character, the starting from the first pair, every pair of characters is identical to the next pair. The following diagram demonstrates same for substring of length 4.
Following is the implementation of above algorithm:
C++
C
Java
Python3
C#
Javascript
// A C++ program to check if a string is 'n' times// repetition of one of its substrings#include <bits/stdc++.h>using namespace std; // A utility function to fill lps[] or compute prefix// function used in KMP string matching algorithm. Refer// https://www.geeksforgeeks.org/archives/11902 for// detailsvoid computeLPSArray(char str[], int M, int lps[]){ // length of the previous longest prefix suffix int len = 0; int i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the example // AAACAAAA and i = 7. len = lps[len - 1]; // Also, note that we do not increment i // here } else // if (len == 0) { lps[i] = 0; i++; } } }} // Returns true if str is repetition of one of its// substrings else return false.bool isRepeat(char str[]){ // Find length of string and create an array to // store lps values used in KMP int n = strlen(str); int lps[n]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix which is also // prefix of str. int len = lps[n - 1]; // If there exist a suffix which is also prefix AND // Length of the remaining substring divides total // length, then str[0..n-len-1] is the substring that // repeats n/(n-len) times (Readers can print substring // and value of n/(n-len) for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false;} // Driver program to test above functionint main(){ char txt[][100] = { "ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC" }; int n = sizeof(txt) / sizeof(txt[0]); for (int i = 0; i < n; i++) isRepeat(txt[i]) ? cout << "True\n" : cout << "False\n"; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// A C++ program to check if a string is 'n' times// repetition of one of its substrings#include <stdbool.h>#include <stdio.h>#include <string.h> // A utility function to fill lps[] or compute prefix// function used in KMP string matching algorithm. Refer// https://www.geeksforgeeks.org/archives/11902 for// detailsvoid computeLPSArray(char str[], int M, int lps[]){ // length of the previous longest prefix suffix int len = 0; int i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the example // AAACAAAA and i = 7. len = lps[len - 1]; // Also, note that we do not increment i // here } else // if (len == 0) { lps[i] = 0; i++; } } }} // Returns true if str is repetition of one of its// substrings else return false.bool isRepeat(char str[]){ // Find length of string and create an array to // store lps values used in KMP int n = strlen(str); int lps[n]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix which is also // prefix of str. int len = lps[n - 1]; // If there exist a suffix which is also prefix AND // Length of the remaining substring divides total // length, then str[0..n-len-1] is the substring that // repeats n/(n-len) times (Readers can print substring // and value of n/(n-len) for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false;} // Driver program to test above functionint main(){ char txt[][100] = { "ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC" }; int n = sizeof(txt) / sizeof(txt[0]); for (int i = 0; i < n; i++) isRepeat(txt[i]) ? printf("True\n") : printf("False\n"); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to check if a string is 'n'// times repetition of one of its substringsimport java.io.*;class GFG { // A utility function to fill lps[] or compute // prefix function used in KMP string matching // algorithm. Refer // https://www.geeksforgeeks.org/archives/11902 // for details static void computeLPSArray(String str, int M, int lps[]) { // length of the previous // longest prefix suffix int len = 0; int i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] // for i = 1 to M-1 while (i < M) { if (str.charAt(i) == str.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the // example AAACAAAA and i = 7. len = lps[len - 1]; // Also, note that we do // not increment i here } else // if (len == 0) { lps[i] = 0; i++; } } } } // Returns true if str is repetition of // one of its substrings else return false. static boolean isRepeat(String str) { // Find length of string and create // an array to store lps values used in KMP int n = str.length(); int lps[] = new int[n]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix // which is also prefix of str. int len = lps[n - 1]; // If there exist a suffix which is also // prefix AND Length of the remaining substring // divides total length, then str[0..n-len-1] // is the substring that repeats n/(n-len) // times (Readers can print substring and // value of n/(n-len) for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false; } // Driver program to test above function public static void main(String[] args) { String txt[] = { "ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC" }; int n = txt.length; for (int i = 0; i < n; i++) { if (isRepeat(txt[i]) == true) System.out.println("True"); else System.out.println("False"); } }} // This code is contributed by Aditya Kumar (adityakumar129)
# A Python program to check if a string is 'n' times# repetition of one of its substrings # A utility function to fill lps[] or compute prefix function# used in KMP string matching algorithm. Refer# https://www.geeksforgeeks.org/archives/11902 for detailsdef computeLPSArray(string, M, lps): length = 0 # length of the previous longest prefix suffix i = 1 lps[0] = 0 # lps[0] is always 0 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if string[i] == string[length]: length += 1 lps[i] = length i += 1 else: if length != 0: # This is tricky. Consider the example AAACAAAA # and i = 7. length = lps[length-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 # Returns true if string is repetition of one of its substrings# else return false.def isRepeat(string): # Find length of string and create an array to # store lps values used in KMP n = len(string) lps = [0] * n # Preprocess the pattern (calculate lps[] array) computeLPSArray(string, n, lps) # Find length of longest suffix which is also # prefix of str. length = lps[n-1] # If there exist a suffix which is also prefix AND # Length of the remaining substring divides total # length, then str[0..n-len-1] is the substring that # repeats n/(n-len) times (Readers can print substring # and value of n/(n-len) for more clarity. if length > 0 and n%(n-length) == 0: return True else: False # Driver programtxt = ["ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC"]n = len(txt)for i in range(n): if isRepeat(txt[i]): print (True) else: print (False) # This code is contributed by BHAVYA JAIN
// C# program to check if a string is 'n'// times repetition of one of its substringsusing System; class GFG { // A utility function to fill lps[] or // compute prefix function used in KMP // string matching algorithm. Refer // https://www.geeksforgeeks.org/archives/11902 // for details static void computeLPSArray(String str, int M, int []lps) { // length of the previous // longest prefix suffix int len = 0; int i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] // for i = 1 to M-1 while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the // example AAACAAAA and i = 7. len = lps[len-1]; // Also, note that we do // not increment i here } else // if (len == 0) { lps[i] = 0; i++; } } } } // Returns true if str is repetition of // one of its substrings else return false. static bool isRepeat(String str) { // Find length of string and create // an array to store lps values used // in KMP int n = str.Length; int[] lps = new int[n]; // Preprocess the pattern (calculate // lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix // which is also prefix of str. int len = lps[n-1]; // If there exist a suffix which is also // prefix AND Length of the remaining // substring divides total length, then // str[0..n-len-1] is the substring that // repeats n/(n-len) times (Readers can // print substring and value of n/(n-len) // for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false; } // Driver program to test above function public static void Main() { String[] txt = {"ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC"}; int n = txt.Length; for (int i = 0; i < n; i++) { if(isRepeat(txt[i]) == true) Console.WriteLine("True"); else Console.WriteLine("False"); } }} // This code is contributed by Sam007.
<script> // Javascript program to check if a string is 'n' // times repetition of one of its substrings // A utility function to fill lps[] or // compute prefix function used in KMP // string matching algorithm. Refer // https://www.geeksforgeeks.org/archives/11902 // for details function computeLPSArray(str, M, lps) { // length of the previous // longest prefix suffix let len = 0; let i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] // for i = 1 to M-1 while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the // example AAACAAAA and i = 7. len = lps[len-1]; // Also, note that we do // not increment i here } else // if (len == 0) { lps[i] = 0; i++; } } } } // Returns true if str is repetition of // one of its substrings else return false. function isRepeat(str) { // Find length of string and create // an array to store lps values used // in KMP let n = str.length; let lps = new Array(n); lps.fill(0); // Preprocess the pattern (calculate // lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix // which is also prefix of str. let len = lps[n-1]; // If there exist a suffix which is also // prefix AND Length of the remaining // substring divides total length, then // str[0..n-len-1] is the substring that // repeats n/(n-len) times (Readers can // print substring and value of n/(n-len) // for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false; } let txt = ["ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC"]; let n = txt.length; for (let i = 0; i < n; i++) { if(isRepeat(txt[i]) == true) document.write("True" + "</br>"); else document.write("False" + "</br>"); } </script>
Output:
True
True
True
False
True
True
False
Time Complexity: Time complexity of the above solution is O(n) as it uses KMP preprocessing algorithm which is linear time algorithm.
This article is contributed by Harshit Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Another approach:
Above problem can be solved with out using KMP algorithm and extra space.
This approach uses two pointers to check the minimum period of a String as a first step. Period of a String is the length of prefix substring which can be repeated x(x=length/period) times to construct the given string.
for eg: Input string “abcabcabcabc” is having a period 3. which means we can construct the given string by repeating first 3 characters 4 (length/3=4) number of times.
Approach:
1) Initially set first pointer – i at 0th index of given string and second pointer – j at 1st index.
2) check the characters at both index. if both matches, take period as (j-i) and increment i and j.
3) if doesn’t match, Once again check if current character matches with first character at 0th index. if matches, update period as j(j-0=j) and set i to next character.
4)if both characters not matches, set i to 0 and update period to -1.
5) At the end check if the calculated period exactly divides the length of the string. if not, update period to -1. This check eliminates the presence of strings ending with suffix less than the period. for e.g period for the string “GEEKSFORGEEKS” is calculated as 8 but the suffix string(GEEKS) is having 5 characters only and is incomplete.
C++
Java
Python3
Javascript
/*package whatever //do not write package name here */#include <bits/stdc++.h>using namespace std; int findPeriod(string A){ int length = A.size(); // Initially consider there is no period for given // String int period = -1; /*set two pointers one(i) at index 0 and other(j) at index 1. increment j till first character is obtained in the string*/ int i = 0; for (int j = 1; j < length; j++) { int currChar = A[j]; int comparator = A[i]; /*If current character matches with first *character *update period as the difference of j and i*/ if (currChar == comparator) { period = (j - i); i++; } /* if any mismatch occurs in between set i to * zero also check if current character again * matches * with starting character. If matches, update * period*/ else { if (currChar == A[0]) { i = 1; period = j; } else { i = 0; period = -1; } } } /*check if the period is exactly dividing * string if not reset the period to -1 * this eliminates partial substrings like * e.g string -"GEEKSFORGEEKS" */ period = (length % period != 0) ? -1 : period; return period;}int main(){ vector<string> testStrings = { "ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC" }; int n = testStrings.size(); for (int i = 0; i < n; i++) { if (findPeriod(testStrings[i]) == -1) cout << "false\n"; else cout << "True\n"; } return 0;} // This code is contributed by rakeshsahni
/*package whatever //do not write package name here */import java.io.*; class GFG { public static int findPeriod(String A) { int length = A.length(); // Initially consider there is no period for given // String int period = -1; /*set two pointers one(i) at index 0 and other(j) at index 1. increment j till first character is obtained in the string*/ int i = 0; for (int j = 1; j < length; j++) { int currChar = A.charAt(j); int comparator = A.charAt(i); /*If current character matches with first *character *update period as the difference of j and i*/ if (currChar == comparator) { period = (j - i); i++; } /* if any mismatch occurs in between set i to * zero also check if current character again * matches * with starting character. If matches, update * period*/ else { if (currChar == A.charAt(0)) { i = 1; period = j; } else { i = 0; period = -1; } } } /*check if the period is exactly dividing * string if not reset the period to -1 * this eliminates partial substrings like * e.g string -"GEEKSFORGEEKS" */ period = (length % period != 0) ? -1 : period; return period; } public static void main(String[] args) { String[] testStrings = { "ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC" }; int n = testStrings.length; for (int i = 0; i < n; i++) { if (findPeriod(testStrings[i]) == -1) System.out.println("false"); else System.out.println("True"); } }}
def findPeriod(A): length = len(A) # Initially consider there is no period for given # String period = -1 # set two pointers one(i) at # index 0 and other(j) at index 1. increment j till # first character is obtained in the string i = 0 for j in range(1,length): currChar = A[j] comparator = A[i] # If current character matches with first # character # update period as the difference of j and i if (currChar == comparator): period = (j - i) i += 1 # if any mismatch occurs in between set i to # zero also check if current character again # matches # with starting character. If matches, update # period else: if (currChar == A[0]): i = 1 period = j else: i = 0 period = -1 # check if the period is exactly dividing # string if not reset the period to -1 # this eliminates partial substrings like # e.g string -"GEEKSFORGEEKS" period = -1 if (length % period != 0) else period return period testStrings = [ "ABCABC", "ABABAB", "ABCDABCD", "GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC", "ABCDABC" ]n = len(testStrings)for i in range(n): if (findPeriod(testStrings[i]) == -1): print("false") else: print("True") # This code is contributed by shinjanpatra
<script> function findPeriod(A){ let length = A.length; // Initially consider there is no period for given // String let period = -1; /*set two pointers one(i) at index 0 and other(j) at index 1. increment j till first character is obtained in the string*/ let i = 0; for (let j = 1; j < length; j++) { let currChar = A[j]; let comparator = A[i]; /*If current character matches with first *character *update period as the difference of j and i*/ if (currChar == comparator) { period = (j - i); i++; } /* if any mismatch occurs in between set i to * zero also check if current character again * matches * with starting character. If matches, update * period*/ else { if (currChar == A[0]) { i = 1; period = j; } else { i = 0; period = -1; } } } /*check if the period is exactly dividing * string if not reset the period to -1 * this eliminates partial substrings like * e.g string -"GEEKSFORGEEKS" */ period = (length % period != 0) ? -1 : period; return period;}// driver code let testStrings = [ "ABCABC", "ABABAB", "ABCDABCD","GEEKSFORGEEKS", "GEEKGEEK", "AAAACAAAAC","ABCDABC" ];let n = testStrings.length;for (let i = 0; i < n; i++) { if (findPeriod(testStrings[i]) == -1) document.write("false","</br>"); else document.write("True","</br>");} // This code is contributed by shinjanpatra </script>
True
True
True
false
True
True
false
This approach is contributed by Sai Krishna Sribhshyam, please do comment if any thing is incorrect or if you want to share any further info.
Sam007
vaibhavrabadiya117
sumitkumar27022001
sagartomar9927
kashishsoda
amartyaghoshgfg
germanshephered48
saikrishnasribhshyam
rakeshsahni
shinjanpatra
adityakumar129
Amazon
MakeMyTrip
Strings
Amazon
MakeMyTrip
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
Reverse words in a given string
How to split a string in C/C++, Python and Java? | [
{
"code": null,
"e": 26501,
"s": 26473,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 26639,
"s": 26501,
"text": "Given a string ‘str’, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together."
},
{
"code": null,
"e": 26650,
"s": 26639,
"text": "Examples: "
},
{
"code": null,
"e": 26951,
"s": 26650,
"text": "Input: str = \"abcabcabc\"\nOutput: true\nThe given string is 3 times repetition of \"abc\"\n\nInput: str = \"abadabad\"\nOutput: true\nThe given string is 2 times repetition of \"abad\"\n\nInput: str = \"aabaabaabaab\"\nOutput: true\nThe given string is 4 times repetition of \"aab\"\n\nInput: str = \"abcdabc\"\nOutput: false"
},
{
"code": null,
"e": 26986,
"s": 26951,
"text": "Source: Google Interview Question "
},
{
"code": null,
"e": 27117,
"s": 26986,
"text": "There can be many solutions to this problem. The challenging part is to solve the problem in O(n) time. Below is a O(n) algorithm."
},
{
"code": null,
"e": 27611,
"s": 27117,
"text": "Let the given string be ‘str’ and length of given string be ‘n’.1) Find the length of the longest proper prefix of ‘str’ which is also a suffix. Let the length of the longest proper prefix suffix be ‘len’. This can be computed in O(n) time using pre-processing step of KMP string matching algorithm.2) If value of ‘n – len’ divides n (or ‘n % (n-len)’ is 0), then return true, else return false.In case of ‘true’ , the substring ‘str[0..n-len-1]’ is the substring that repeats n/(n-len) times."
},
{
"code": null,
"e": 28246,
"s": 27611,
"text": "Let us take few examples.Input: str = “ABCDABCD”, n = 8 (Number of characters in ‘str’) The value of len is 4 (“ABCD” is the longest substring which is both prefix and suffix) Since (n-len) divides n, the answer is true.Input: str = “ABCDABC”, n = 7 (Number of characters in ‘str’) The value of len is 3 (“ABC” is the longest substring which is both prefix and suffix) Since (n-len) doesn’t divides n, the answer is false.Input: str = “ABCABCABCABCABC”, n = 15 (Number of characters in ‘str’) The value of len is 12 (“ABCABCABCABC” is the longest substring which is both prefix and suffix) Since (n-len) divides n, the answer is true."
},
{
"code": null,
"e": 28782,
"s": 28246,
"text": "How does this work? length of longest proper prefix-suffix (or len) is always between 0 to n-1. If len is n-1, then all characters in string are same. For example len is 3 for “AAAA”. If len is n-2 and n is even, then two characters in string repeat n/2 times. For example “ABABABAB”, length of lps is 6. The reason is if the first n-2 characters are same as last n-2 character, the starting from the first pair, every pair of characters is identical to the next pair. The following diagram demonstrates same for substring of length 4."
},
{
"code": null,
"e": 28835,
"s": 28782,
"text": "Following is the implementation of above algorithm: "
},
{
"code": null,
"e": 28839,
"s": 28835,
"text": "C++"
},
{
"code": null,
"e": 28841,
"s": 28839,
"text": "C"
},
{
"code": null,
"e": 28846,
"s": 28841,
"text": "Java"
},
{
"code": null,
"e": 28854,
"s": 28846,
"text": "Python3"
},
{
"code": null,
"e": 28857,
"s": 28854,
"text": "C#"
},
{
"code": null,
"e": 28868,
"s": 28857,
"text": "Javascript"
},
{
"code": "// A C++ program to check if a string is 'n' times// repetition of one of its substrings#include <bits/stdc++.h>using namespace std; // A utility function to fill lps[] or compute prefix// function used in KMP string matching algorithm. Refer// https://www.geeksforgeeks.org/archives/11902 for// detailsvoid computeLPSArray(char str[], int M, int lps[]){ // length of the previous longest prefix suffix int len = 0; int i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the example // AAACAAAA and i = 7. len = lps[len - 1]; // Also, note that we do not increment i // here } else // if (len == 0) { lps[i] = 0; i++; } } }} // Returns true if str is repetition of one of its// substrings else return false.bool isRepeat(char str[]){ // Find length of string and create an array to // store lps values used in KMP int n = strlen(str); int lps[n]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix which is also // prefix of str. int len = lps[n - 1]; // If there exist a suffix which is also prefix AND // Length of the remaining substring divides total // length, then str[0..n-len-1] is the substring that // repeats n/(n-len) times (Readers can print substring // and value of n/(n-len) for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false;} // Driver program to test above functionint main(){ char txt[][100] = { \"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\" }; int n = sizeof(txt) / sizeof(txt[0]); for (int i = 0; i < n; i++) isRepeat(txt[i]) ? cout << \"True\\n\" : cout << \"False\\n\"; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 31119,
"s": 28868,
"text": null
},
{
"code": "// A C++ program to check if a string is 'n' times// repetition of one of its substrings#include <stdbool.h>#include <stdio.h>#include <string.h> // A utility function to fill lps[] or compute prefix// function used in KMP string matching algorithm. Refer// https://www.geeksforgeeks.org/archives/11902 for// detailsvoid computeLPSArray(char str[], int M, int lps[]){ // length of the previous longest prefix suffix int len = 0; int i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the example // AAACAAAA and i = 7. len = lps[len - 1]; // Also, note that we do not increment i // here } else // if (len == 0) { lps[i] = 0; i++; } } }} // Returns true if str is repetition of one of its// substrings else return false.bool isRepeat(char str[]){ // Find length of string and create an array to // store lps values used in KMP int n = strlen(str); int lps[n]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix which is also // prefix of str. int len = lps[n - 1]; // If there exist a suffix which is also prefix AND // Length of the remaining substring divides total // length, then str[0..n-len-1] is the substring that // repeats n/(n-len) times (Readers can print substring // and value of n/(n-len) for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false;} // Driver program to test above functionint main(){ char txt[][100] = { \"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\" }; int n = sizeof(txt) / sizeof(txt[0]); for (int i = 0; i < n; i++) isRepeat(txt[i]) ? printf(\"True\\n\") : printf(\"False\\n\"); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 33383,
"s": 31119,
"text": null
},
{
"code": "// Java program to check if a string is 'n'// times repetition of one of its substringsimport java.io.*;class GFG { // A utility function to fill lps[] or compute // prefix function used in KMP string matching // algorithm. Refer // https://www.geeksforgeeks.org/archives/11902 // for details static void computeLPSArray(String str, int M, int lps[]) { // length of the previous // longest prefix suffix int len = 0; int i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] // for i = 1 to M-1 while (i < M) { if (str.charAt(i) == str.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the // example AAACAAAA and i = 7. len = lps[len - 1]; // Also, note that we do // not increment i here } else // if (len == 0) { lps[i] = 0; i++; } } } } // Returns true if str is repetition of // one of its substrings else return false. static boolean isRepeat(String str) { // Find length of string and create // an array to store lps values used in KMP int n = str.length(); int lps[] = new int[n]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix // which is also prefix of str. int len = lps[n - 1]; // If there exist a suffix which is also // prefix AND Length of the remaining substring // divides total length, then str[0..n-len-1] // is the substring that repeats n/(n-len) // times (Readers can print substring and // value of n/(n-len) for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false; } // Driver program to test above function public static void main(String[] args) { String txt[] = { \"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\" }; int n = txt.length; for (int i = 0; i < n; i++) { if (isRepeat(txt[i]) == true) System.out.println(\"True\"); else System.out.println(\"False\"); } }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 36097,
"s": 33383,
"text": null
},
{
"code": "# A Python program to check if a string is 'n' times# repetition of one of its substrings # A utility function to fill lps[] or compute prefix function# used in KMP string matching algorithm. Refer# https://www.geeksforgeeks.org/archives/11902 for detailsdef computeLPSArray(string, M, lps): length = 0 # length of the previous longest prefix suffix i = 1 lps[0] = 0 # lps[0] is always 0 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if string[i] == string[length]: length += 1 lps[i] = length i += 1 else: if length != 0: # This is tricky. Consider the example AAACAAAA # and i = 7. length = lps[length-1] # Also, note that we do not increment i here else: lps[i] = 0 i += 1 # Returns true if string is repetition of one of its substrings# else return false.def isRepeat(string): # Find length of string and create an array to # store lps values used in KMP n = len(string) lps = [0] * n # Preprocess the pattern (calculate lps[] array) computeLPSArray(string, n, lps) # Find length of longest suffix which is also # prefix of str. length = lps[n-1] # If there exist a suffix which is also prefix AND # Length of the remaining substring divides total # length, then str[0..n-len-1] is the substring that # repeats n/(n-len) times (Readers can print substring # and value of n/(n-len) for more clarity. if length > 0 and n%(n-length) == 0: return True else: False # Driver programtxt = [\"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\"]n = len(txt)for i in range(n): if isRepeat(txt[i]): print (True) else: print (False) # This code is contributed by BHAVYA JAIN",
"e": 37999,
"s": 36097,
"text": null
},
{
"code": "// C# program to check if a string is 'n'// times repetition of one of its substringsusing System; class GFG { // A utility function to fill lps[] or // compute prefix function used in KMP // string matching algorithm. Refer // https://www.geeksforgeeks.org/archives/11902 // for details static void computeLPSArray(String str, int M, int []lps) { // length of the previous // longest prefix suffix int len = 0; int i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] // for i = 1 to M-1 while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the // example AAACAAAA and i = 7. len = lps[len-1]; // Also, note that we do // not increment i here } else // if (len == 0) { lps[i] = 0; i++; } } } } // Returns true if str is repetition of // one of its substrings else return false. static bool isRepeat(String str) { // Find length of string and create // an array to store lps values used // in KMP int n = str.Length; int[] lps = new int[n]; // Preprocess the pattern (calculate // lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix // which is also prefix of str. int len = lps[n-1]; // If there exist a suffix which is also // prefix AND Length of the remaining // substring divides total length, then // str[0..n-len-1] is the substring that // repeats n/(n-len) times (Readers can // print substring and value of n/(n-len) // for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false; } // Driver program to test above function public static void Main() { String[] txt = {\"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\"}; int n = txt.Length; for (int i = 0; i < n; i++) { if(isRepeat(txt[i]) == true) Console.WriteLine(\"True\"); else Console.WriteLine(\"False\"); } }} // This code is contributed by Sam007.",
"e": 40827,
"s": 37999,
"text": null
},
{
"code": "<script> // Javascript program to check if a string is 'n' // times repetition of one of its substrings // A utility function to fill lps[] or // compute prefix function used in KMP // string matching algorithm. Refer // https://www.geeksforgeeks.org/archives/11902 // for details function computeLPSArray(str, M, lps) { // length of the previous // longest prefix suffix let len = 0; let i; lps[0] = 0; // lps[0] is always 0 i = 1; // the loop calculates lps[i] // for i = 1 to M-1 while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the // example AAACAAAA and i = 7. len = lps[len-1]; // Also, note that we do // not increment i here } else // if (len == 0) { lps[i] = 0; i++; } } } } // Returns true if str is repetition of // one of its substrings else return false. function isRepeat(str) { // Find length of string and create // an array to store lps values used // in KMP let n = str.length; let lps = new Array(n); lps.fill(0); // Preprocess the pattern (calculate // lps[] array) computeLPSArray(str, n, lps); // Find length of longest suffix // which is also prefix of str. let len = lps[n-1]; // If there exist a suffix which is also // prefix AND Length of the remaining // substring divides total length, then // str[0..n-len-1] is the substring that // repeats n/(n-len) times (Readers can // print substring and value of n/(n-len) // for more clarity. return (len > 0 && n % (n - len) == 0) ? true : false; } let txt = [\"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\"]; let n = txt.length; for (let i = 0; i < n; i++) { if(isRepeat(txt[i]) == true) document.write(\"True\" + \"</br>\"); else document.write(\"False\" + \"</br>\"); } </script>",
"e": 43467,
"s": 40827,
"text": null
},
{
"code": null,
"e": 43476,
"s": 43467,
"text": "Output: "
},
{
"code": null,
"e": 43514,
"s": 43476,
"text": "True\nTrue\nTrue\nFalse\nTrue\nTrue\nFalse "
},
{
"code": null,
"e": 43648,
"s": 43514,
"text": "Time Complexity: Time complexity of the above solution is O(n) as it uses KMP preprocessing algorithm which is linear time algorithm."
},
{
"code": null,
"e": 43821,
"s": 43648,
"text": "This article is contributed by Harshit Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 43839,
"s": 43821,
"text": "Another approach:"
},
{
"code": null,
"e": 43913,
"s": 43839,
"text": "Above problem can be solved with out using KMP algorithm and extra space."
},
{
"code": null,
"e": 44134,
"s": 43913,
"text": "This approach uses two pointers to check the minimum period of a String as a first step. Period of a String is the length of prefix substring which can be repeated x(x=length/period) times to construct the given string. "
},
{
"code": null,
"e": 44303,
"s": 44134,
"text": "for eg: Input string “abcabcabcabc” is having a period 3. which means we can construct the given string by repeating first 3 characters 4 (length/3=4) number of times."
},
{
"code": null,
"e": 44313,
"s": 44303,
"text": "Approach:"
},
{
"code": null,
"e": 44414,
"s": 44313,
"text": "1) Initially set first pointer – i at 0th index of given string and second pointer – j at 1st index."
},
{
"code": null,
"e": 44514,
"s": 44414,
"text": "2) check the characters at both index. if both matches, take period as (j-i) and increment i and j."
},
{
"code": null,
"e": 44683,
"s": 44514,
"text": "3) if doesn’t match, Once again check if current character matches with first character at 0th index. if matches, update period as j(j-0=j) and set i to next character."
},
{
"code": null,
"e": 44753,
"s": 44683,
"text": "4)if both characters not matches, set i to 0 and update period to -1."
},
{
"code": null,
"e": 45097,
"s": 44753,
"text": "5) At the end check if the calculated period exactly divides the length of the string. if not, update period to -1. This check eliminates the presence of strings ending with suffix less than the period. for e.g period for the string “GEEKSFORGEEKS” is calculated as 8 but the suffix string(GEEKS) is having 5 characters only and is incomplete."
},
{
"code": null,
"e": 45103,
"s": 45099,
"text": "C++"
},
{
"code": null,
"e": 45108,
"s": 45103,
"text": "Java"
},
{
"code": null,
"e": 45116,
"s": 45108,
"text": "Python3"
},
{
"code": null,
"e": 45127,
"s": 45116,
"text": "Javascript"
},
{
"code": "/*package whatever //do not write package name here */#include <bits/stdc++.h>using namespace std; int findPeriod(string A){ int length = A.size(); // Initially consider there is no period for given // String int period = -1; /*set two pointers one(i) at index 0 and other(j) at index 1. increment j till first character is obtained in the string*/ int i = 0; for (int j = 1; j < length; j++) { int currChar = A[j]; int comparator = A[i]; /*If current character matches with first *character *update period as the difference of j and i*/ if (currChar == comparator) { period = (j - i); i++; } /* if any mismatch occurs in between set i to * zero also check if current character again * matches * with starting character. If matches, update * period*/ else { if (currChar == A[0]) { i = 1; period = j; } else { i = 0; period = -1; } } } /*check if the period is exactly dividing * string if not reset the period to -1 * this eliminates partial substrings like * e.g string -\"GEEKSFORGEEKS\" */ period = (length % period != 0) ? -1 : period; return period;}int main(){ vector<string> testStrings = { \"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\" }; int n = testStrings.size(); for (int i = 0; i < n; i++) { if (findPeriod(testStrings[i]) == -1) cout << \"false\\n\"; else cout << \"True\\n\"; } return 0;} // This code is contributed by rakeshsahni",
"e": 46887,
"s": 45127,
"text": null
},
{
"code": "/*package whatever //do not write package name here */import java.io.*; class GFG { public static int findPeriod(String A) { int length = A.length(); // Initially consider there is no period for given // String int period = -1; /*set two pointers one(i) at index 0 and other(j) at index 1. increment j till first character is obtained in the string*/ int i = 0; for (int j = 1; j < length; j++) { int currChar = A.charAt(j); int comparator = A.charAt(i); /*If current character matches with first *character *update period as the difference of j and i*/ if (currChar == comparator) { period = (j - i); i++; } /* if any mismatch occurs in between set i to * zero also check if current character again * matches * with starting character. If matches, update * period*/ else { if (currChar == A.charAt(0)) { i = 1; period = j; } else { i = 0; period = -1; } } } /*check if the period is exactly dividing * string if not reset the period to -1 * this eliminates partial substrings like * e.g string -\"GEEKSFORGEEKS\" */ period = (length % period != 0) ? -1 : period; return period; } public static void main(String[] args) { String[] testStrings = { \"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\" }; int n = testStrings.length; for (int i = 0; i < n; i++) { if (findPeriod(testStrings[i]) == -1) System.out.println(\"false\"); else System.out.println(\"True\"); } }}",
"e": 48881,
"s": 46887,
"text": null
},
{
"code": "def findPeriod(A): length = len(A) # Initially consider there is no period for given # String period = -1 # set two pointers one(i) at # index 0 and other(j) at index 1. increment j till # first character is obtained in the string i = 0 for j in range(1,length): currChar = A[j] comparator = A[i] # If current character matches with first # character # update period as the difference of j and i if (currChar == comparator): period = (j - i) i += 1 # if any mismatch occurs in between set i to # zero also check if current character again # matches # with starting character. If matches, update # period else: if (currChar == A[0]): i = 1 period = j else: i = 0 period = -1 # check if the period is exactly dividing # string if not reset the period to -1 # this eliminates partial substrings like # e.g string -\"GEEKSFORGEEKS\" period = -1 if (length % period != 0) else period return period testStrings = [ \"ABCABC\", \"ABABAB\", \"ABCDABCD\", \"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\", \"ABCDABC\" ]n = len(testStrings)for i in range(n): if (findPeriod(testStrings[i]) == -1): print(\"false\") else: print(\"True\") # This code is contributed by shinjanpatra",
"e": 50303,
"s": 48881,
"text": null
},
{
"code": "<script> function findPeriod(A){ let length = A.length; // Initially consider there is no period for given // String let period = -1; /*set two pointers one(i) at index 0 and other(j) at index 1. increment j till first character is obtained in the string*/ let i = 0; for (let j = 1; j < length; j++) { let currChar = A[j]; let comparator = A[i]; /*If current character matches with first *character *update period as the difference of j and i*/ if (currChar == comparator) { period = (j - i); i++; } /* if any mismatch occurs in between set i to * zero also check if current character again * matches * with starting character. If matches, update * period*/ else { if (currChar == A[0]) { i = 1; period = j; } else { i = 0; period = -1; } } } /*check if the period is exactly dividing * string if not reset the period to -1 * this eliminates partial substrings like * e.g string -\"GEEKSFORGEEKS\" */ period = (length % period != 0) ? -1 : period; return period;}// driver code let testStrings = [ \"ABCABC\", \"ABABAB\", \"ABCDABCD\",\"GEEKSFORGEEKS\", \"GEEKGEEK\", \"AAAACAAAAC\",\"ABCDABC\" ];let n = testStrings.length;for (let i = 0; i < n; i++) { if (findPeriod(testStrings[i]) == -1) document.write(\"false\",\"</br>\"); else document.write(\"True\",\"</br>\");} // This code is contributed by shinjanpatra </script>",
"e": 51911,
"s": 50303,
"text": null
},
{
"code": null,
"e": 51948,
"s": 51911,
"text": "True\nTrue\nTrue\nfalse\nTrue\nTrue\nfalse"
},
{
"code": null,
"e": 52090,
"s": 51948,
"text": "This approach is contributed by Sai Krishna Sribhshyam, please do comment if any thing is incorrect or if you want to share any further info."
},
{
"code": null,
"e": 52097,
"s": 52090,
"text": "Sam007"
},
{
"code": null,
"e": 52116,
"s": 52097,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 52135,
"s": 52116,
"text": "sumitkumar27022001"
},
{
"code": null,
"e": 52150,
"s": 52135,
"text": "sagartomar9927"
},
{
"code": null,
"e": 52162,
"s": 52150,
"text": "kashishsoda"
},
{
"code": null,
"e": 52178,
"s": 52162,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 52196,
"s": 52178,
"text": "germanshephered48"
},
{
"code": null,
"e": 52217,
"s": 52196,
"text": "saikrishnasribhshyam"
},
{
"code": null,
"e": 52229,
"s": 52217,
"text": "rakeshsahni"
},
{
"code": null,
"e": 52242,
"s": 52229,
"text": "shinjanpatra"
},
{
"code": null,
"e": 52257,
"s": 52242,
"text": "adityakumar129"
},
{
"code": null,
"e": 52264,
"s": 52257,
"text": "Amazon"
},
{
"code": null,
"e": 52275,
"s": 52264,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 52283,
"s": 52275,
"text": "Strings"
},
{
"code": null,
"e": 52290,
"s": 52283,
"text": "Amazon"
},
{
"code": null,
"e": 52301,
"s": 52290,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 52309,
"s": 52301,
"text": "Strings"
},
{
"code": null,
"e": 52407,
"s": 52309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52464,
"s": 52407,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 52517,
"s": 52464,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 52553,
"s": 52517,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 52591,
"s": 52553,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 52621,
"s": 52591,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 52673,
"s": 52621,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 52718,
"s": 52673,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 52779,
"s": 52718,
"text": "Length of the longest substring without repeating characters"
},
{
"code": null,
"e": 52811,
"s": 52779,
"text": "Reverse words in a given string"
}
]
|
Iterators in Python - GeeksforGeeks | 16 Nov, 2020
Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration.
__iter(iterable)__ method that is called for the initialization of an iterator. This returns an iterator objectnext ( __next__ in Python 3) The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object which further uses next() method to iterate over. This method raises a StopIteration to signal the end of the iteration.
__iter(iterable)__ method that is called for the initialization of an iterator. This returns an iterator object
next ( __next__ in Python 3) The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object which further uses next() method to iterate over. This method raises a StopIteration to signal the end of the iteration.
How an iterator really works in python
Python3
# Here is an example of a python inbuilt iterator# value can be anything which can be iterateiterable_value = 'Geeks'iterable_obj = iter(iterable_value) while True: try: # Iterate by calling next item = next(iterable_obj) print(item) except StopIteration: # exception will happen when iteration will over break
Output :
G
e
e
k
s
Below is a simple Python custom iterator that creates iterator type that iterates from 10 to a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14 15. And if the limit is 5, then it prints nothing.
Python3
# A simple Python program to demonstrate# working of iterators using an example type# that iterates from 10 to given value # An iterable user defined typeclass Test: # Constructor def __init__(self, limit): self.limit = limit # Creates iterator object # Called when iteration is initialized def __iter__(self): self.x = 10 return self # To move to next element. In Python 3, # we should replace next with __next__ def __next__(self): # Store current value ofx x = self.x # Stop iteration if limit is reached if x > self.limit: raise StopIteration # Else increment and return old value self.x = x + 1; return x # Prints numbers from 10 to 15for i in Test(15): print(i) # Prints nothingfor i in Test(5): print(i)
Output :
10
11
12
13
14
15
In the following iterations, the for loop is internally(we can’t see it) using iterator object to traverse over the iterables
Python3
# Sample built-in iterators # Iterating over a listprint("List Iteration")l = ["geeks", "for", "geeks"]for i in l: print(i) # Iterating over a tuple (immutable)print("\nTuple Iteration")t = ("geeks", "for", "geeks")for i in t: print(i) # Iterating over a Stringprint("\nString Iteration") s = "Geeks"for i in s : print(i) # Iterating over dictionaryprint("\nDictionary Iteration") d = dict()d['xyz'] = 123d['abc'] = 345for i in d : print("%s %d" %(i, d[i]))
Output :
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
Generators in PythonThis article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Raisul
adnan17326
espinozahg
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python | [
{
"code": null,
"e": 24931,
"s": 24903,
"text": "\n16 Nov, 2020"
},
{
"code": null,
"e": 25148,
"s": 24931,
"text": "Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration. "
},
{
"code": null,
"e": 25585,
"s": 25148,
"text": "__iter(iterable)__ method that is called for the initialization of an iterator. This returns an iterator objectnext ( __next__ in Python 3) The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object which further uses next() method to iterate over. This method raises a StopIteration to signal the end of the iteration."
},
{
"code": null,
"e": 25697,
"s": 25585,
"text": "__iter(iterable)__ method that is called for the initialization of an iterator. This returns an iterator object"
},
{
"code": null,
"e": 26023,
"s": 25697,
"text": "next ( __next__ in Python 3) The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object which further uses next() method to iterate over. This method raises a StopIteration to signal the end of the iteration."
},
{
"code": null,
"e": 26063,
"s": 26023,
"text": "How an iterator really works in python "
},
{
"code": null,
"e": 26071,
"s": 26063,
"text": "Python3"
},
{
"code": "# Here is an example of a python inbuilt iterator# value can be anything which can be iterateiterable_value = 'Geeks'iterable_obj = iter(iterable_value) while True: try: # Iterate by calling next item = next(iterable_obj) print(item) except StopIteration: # exception will happen when iteration will over break",
"e": 26425,
"s": 26071,
"text": null
},
{
"code": null,
"e": 26435,
"s": 26425,
"text": "Output : "
},
{
"code": null,
"e": 27136,
"s": 26435,
"text": "G \ne \ne \nk \ns\n\n\n"
},
{
"code": null,
"e": 27359,
"s": 27136,
"text": "Below is a simple Python custom iterator that creates iterator type that iterates from 10 to a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14 15. And if the limit is 5, then it prints nothing. "
},
{
"code": null,
"e": 27367,
"s": 27359,
"text": "Python3"
},
{
"code": "# A simple Python program to demonstrate# working of iterators using an example type# that iterates from 10 to given value # An iterable user defined typeclass Test: # Constructor def __init__(self, limit): self.limit = limit # Creates iterator object # Called when iteration is initialized def __iter__(self): self.x = 10 return self # To move to next element. In Python 3, # we should replace next with __next__ def __next__(self): # Store current value ofx x = self.x # Stop iteration if limit is reached if x > self.limit: raise StopIteration # Else increment and return old value self.x = x + 1; return x # Prints numbers from 10 to 15for i in Test(15): print(i) # Prints nothingfor i in Test(5): print(i)",
"e": 28195,
"s": 27367,
"text": null
},
{
"code": null,
"e": 28205,
"s": 28195,
"text": "Output : "
},
{
"code": null,
"e": 28226,
"s": 28205,
"text": "10\n11\n12\n13\n14\n15\n\n\n"
},
{
"code": null,
"e": 28354,
"s": 28226,
"text": "In the following iterations, the for loop is internally(we can’t see it) using iterator object to traverse over the iterables "
},
{
"code": null,
"e": 28362,
"s": 28354,
"text": "Python3"
},
{
"code": "# Sample built-in iterators # Iterating over a listprint(\"List Iteration\")l = [\"geeks\", \"for\", \"geeks\"]for i in l: print(i) # Iterating over a tuple (immutable)print(\"\\nTuple Iteration\")t = (\"geeks\", \"for\", \"geeks\")for i in t: print(i) # Iterating over a Stringprint(\"\\nString Iteration\") s = \"Geeks\"for i in s : print(i) # Iterating over dictionaryprint(\"\\nDictionary Iteration\") d = dict()d['xyz'] = 123d['abc'] = 345for i in d : print(\"%s %d\" %(i, d[i]))",
"e": 28848,
"s": 28362,
"text": null
},
{
"code": null,
"e": 28858,
"s": 28848,
"text": "Output : "
},
{
"code": null,
"e": 28993,
"s": 28858,
"text": "List Iteration\ngeeks\nfor\ngeeks\n\nTuple Iteration\ngeeks\nfor\ngeeks\n\nString Iteration\nG\ne\ne\nk\ns\n\nDictionary Iteration\nxyz 123\nabc 345\n\n\n"
},
{
"code": null,
"e": 29189,
"s": 28993,
"text": "Generators in PythonThis article is contributed by Shwetanshu Rohatgi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 29196,
"s": 29189,
"text": "Raisul"
},
{
"code": null,
"e": 29207,
"s": 29196,
"text": "adnan17326"
},
{
"code": null,
"e": 29218,
"s": 29207,
"text": "espinozahg"
},
{
"code": null,
"e": 29225,
"s": 29218,
"text": "Python"
},
{
"code": null,
"e": 29323,
"s": 29225,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29351,
"s": 29323,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29401,
"s": 29351,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29423,
"s": 29401,
"text": "Python map() function"
},
{
"code": null,
"e": 29467,
"s": 29423,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 29490,
"s": 29467,
"text": "Taking input in Python"
},
{
"code": null,
"e": 29525,
"s": 29490,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29557,
"s": 29525,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29579,
"s": 29557,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29621,
"s": 29579,
"text": "Different ways to create Pandas Dataframe"
}
]
|
Drop Collection if already exists in MongoDB using Python - GeeksforGeeks | 26 May, 2020
Using drop() method we can drop collection data if data is already exist. If data is not found then it returns False otherwise it returns True if collection is dropped.
Syntax:
drop()
Example 1:
Sample Database:
Python3
import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") # Database namedb = client["mydatabase"] # Collection namecol = db["gfg"] # drop collection col1print(col.drop())
Output:
Example 2: If collection does not exist.
Python3
import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") # Database namedb = client["mydatabase"] # Collection namecol = db["gfg"] # drop collection col1if col.drop(): print('Deleted')else: print('Not Present')
Output:
Not Present
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 25565,
"s": 25537,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 25735,
"s": 25565,
"text": "Using drop() method we can drop collection data if data is already exist. If data is not found then it returns False otherwise it returns True if collection is dropped. "
},
{
"code": null,
"e": 25744,
"s": 25735,
"text": "Syntax: "
},
{
"code": null,
"e": 25752,
"s": 25744,
"text": "drop()\n"
},
{
"code": null,
"e": 25764,
"s": 25752,
"text": "Example 1: "
},
{
"code": null,
"e": 25781,
"s": 25764,
"text": "Sample Database:"
},
{
"code": null,
"e": 25789,
"s": 25781,
"text": "Python3"
},
{
"code": "import pymongo client = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database namedb = client[\"mydatabase\"] # Collection namecol = db[\"gfg\"] # drop collection col1print(col.drop())",
"e": 25983,
"s": 25789,
"text": null
},
{
"code": null,
"e": 25992,
"s": 25983,
"text": "Output: "
},
{
"code": null,
"e": 26035,
"s": 25992,
"text": "Example 2: If collection does not exist. "
},
{
"code": null,
"e": 26043,
"s": 26035,
"text": "Python3"
},
{
"code": "import pymongo client = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database namedb = client[\"mydatabase\"] # Collection namecol = db[\"gfg\"] # drop collection col1if col.drop(): print('Deleted')else: print('Not Present')",
"e": 26283,
"s": 26043,
"text": null
},
{
"code": null,
"e": 26291,
"s": 26283,
"text": "Output:"
},
{
"code": null,
"e": 26303,
"s": 26291,
"text": "Not Present"
},
{
"code": null,
"e": 26318,
"s": 26303,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 26325,
"s": 26318,
"text": "Python"
},
{
"code": null,
"e": 26423,
"s": 26325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26441,
"s": 26423,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26473,
"s": 26441,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26515,
"s": 26473,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26541,
"s": 26515,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26570,
"s": 26541,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26607,
"s": 26570,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26643,
"s": 26607,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 26685,
"s": 26643,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26710,
"s": 26685,
"text": "sum() function in Python"
}
]
|
PHP | Bitwise Operators - GeeksforGeeks | 05 Dec, 2018
The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then calculation is performed on the operands. The mathematical operations such as addition , subtraction , multiplication etc. can be performed at bit-level for faster processing. In PHP, the operators that works at bit level are:
& (Bitwise AND) : This is a binary operator i.e. it works on two operand. Bitwise AND operator in PHP takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.Syntax:$First & $Second
This will return another number whose bits are
set if both the bit of first and second are set.
Example:Input: $First = 5, $Second = 3
Output: The bitwise & of both these value will be 1.
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise & will be 0001 (i.e. set
if both first and second have their bit set.)
Syntax:
$First & $Second
This will return another number whose bits are
set if both the bit of first and second are set.
Example:
Input: $First = 5, $Second = 3
Output: The bitwise & of both these value will be 1.
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise & will be 0001 (i.e. set
if both first and second have their bit set.)
| (Bitwise OR) : This is also binary operator i.e. works on two operand. Bitwise OR operator takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.Syntax:$First | $Second
This will return another number whose bits are
set if either the bit of first or second are set.
Example:Input: First = 5, Second = 3
Output: The bitwise | of both these value will be 7.
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise | will be 0111 (i.e. set
if either first or second have their bit set.)
Syntax:
$First | $Second
This will return another number whose bits are
set if either the bit of first or second are set.
Example:
Input: First = 5, Second = 3
Output: The bitwise | of both these value will be 7.
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise | will be 0111 (i.e. set
if either first or second have their bit set.)
^ (Bitwise XOR ) : This is also binary operator i.e. works on two operand. This is also known as Exclusive OR operator. Bitwise XOR takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.Syntax:$First ^ $Second
This will return another number whose bits are
set if one of the bit in first or second is
set but not both.
Example:Input: First = 5, Second = 3
Output: The bitwise ^ of both these value will be 6.
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise ^ will be 0110 (i.e. set
if either first or second have their bit set but
not both.)
Syntax:
$First ^ $Second
This will return another number whose bits are
set if one of the bit in first or second is
set but not both.
Example:
Input: First = 5, Second = 3
Output: The bitwise ^ of both these value will be 6.
Explanation:
Binary representation of 5 is 0101 and 3 is 0011.
Therefore their bitwise ^ will be 0110 (i.e. set
if either first or second have their bit set but
not both.)
~ (Bitwise NOT) : This is a unary operator i.e. works on only one operand. Bitwise NOT operator takes one number and inverts all bits of it.Syntax:~$number
This will invert all the bits of $number.
Example:Input: number = 5
Output: The bitwise '~' of this number will be -6.
Explanation:
Binary representation of 5 is 0101. Therefore the
bitwise ~ of this will be 1010 (inverts all the
bits of the input number)
Syntax:
~$number
This will invert all the bits of $number.
Example:
Input: number = 5
Output: The bitwise '~' of this number will be -6.
Explanation:
Binary representation of 5 is 0101. Therefore the
bitwise ~ of this will be 1010 (inverts all the
bits of the input number)
<< (Bitwise Left Shift) : This is a binary operator i.e. works on two operand. Bitwise Left Shift operator takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.Syntax:$First << $Second
This will shift the bits of $First towards the
left. $Second decides the number of time the
bits will be shifted.
Example:Input: First = 5, Second = 1
Output: The bitwise << of both these value will be 10.
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise << will shift the bits of 5 one times
towards the left (i.e. 01010 )
Note: Bitwise left shift with one bit is equivalent to multiplication with 2.
Syntax:
$First << $Second
This will shift the bits of $First towards the
left. $Second decides the number of time the
bits will be shifted.
Example:
Input: First = 5, Second = 1
Output: The bitwise << of both these value will be 10.
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise << will shift the bits of 5 one times
towards the left (i.e. 01010 )
Note: Bitwise left shift with one bit is equivalent to multiplication with 2.
>> (Bitwise Right Shift) : This is also binary operator i.e. works on two operand. Bitwise Right Shift operator takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.Syntax:$First >> $Second
This will shift the bits of $First towards the
right. $Second decides the number of time the
bits will be shifted.
Example:Input: First = 5, Second = 1
Output: The bitwise >> of both these value will be 2.
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise >> will shift the bits of 5 one times
towards the right(i.e. 010)
Note: Bitwise right shift with one bit is equivalent to division with 2.
Syntax:
$First >> $Second
This will shift the bits of $First towards the
right. $Second decides the number of time the
bits will be shifted.
Example:
Input: First = 5, Second = 1
Output: The bitwise >> of both these value will be 2.
Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise >> will shift the bits of 5 one times
towards the right(i.e. 010)
Note: Bitwise right shift with one bit is equivalent to division with 2.
Below is the implementation of Bitwise Operators in PHP:
<?php // PHP code to demonstrate Bitwise Operator. // Bitwise AND $First = 5; $second = 3; $answer = $First & $second; print_r("Bitwise & of 5 and 3 is $answer"); print_r("\n"); // Bitwise OR $answer = $First | $second; print_r("Bitwise | of 5 and 3 is $answer"); print_r("\n"); // Bitwise XOR $answer = $First ^ $second; print_r("Bitwise ^ of 5 and 3 is $answer"); print_r("\n"); // Bitwise NOT $answer = ~$First; print_r("Bitwise ~ of 5 is $answer"); print_r("\n"); // Bitwise Left shift $second = 1; $answer = $First << $second; print_r("5 << 1 will be $answer"); print_r("\n"); // Bitwise Right shift $answer = $First >> $second; print_r("5 >> 1 will be $answer"); print_r("\n");?>
Output:
Bitwise & of 5 and 3 is 1
Bitwise | of 5 and 3 is 7
Bitwise ^ of 5 and 3 is 6
Bitwise ~ of 5 is -6
5 << 1 will be 10
5 >> 1 will be 2
PHP-basics
PHP-Operators
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to pass JavaScript variables to PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25212,
"s": 25184,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 25574,
"s": 25212,
"text": "The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then calculation is performed on the operands. The mathematical operations such as addition , subtraction , multiplication etc. can be performed at bit-level for faster processing. In PHP, the operators that works at bit level are:"
},
{
"code": null,
"e": 26174,
"s": 25574,
"text": "& (Bitwise AND) : This is a binary operator i.e. it works on two operand. Bitwise AND operator in PHP takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.Syntax:$First & $Second\n\nThis will return another number whose bits are \nset if both the bit of first and second are set.\nExample:Input: $First = 5, $Second = 3\n\nOutput: The bitwise & of both these value will be 1. \n\nExplanation:\nBinary representation of 5 is 0101 and 3 is 0011. \nTherefore their bitwise & will be 0001 (i.e. set \nif both first and second have their bit set.)\n"
},
{
"code": null,
"e": 26182,
"s": 26174,
"text": "Syntax:"
},
{
"code": null,
"e": 26298,
"s": 26182,
"text": "$First & $Second\n\nThis will return another number whose bits are \nset if both the bit of first and second are set.\n"
},
{
"code": null,
"e": 26307,
"s": 26298,
"text": "Example:"
},
{
"code": null,
"e": 26556,
"s": 26307,
"text": "Input: $First = 5, $Second = 3\n\nOutput: The bitwise & of both these value will be 1. \n\nExplanation:\nBinary representation of 5 is 0101 and 3 is 0011. \nTherefore their bitwise & will be 0001 (i.e. set \nif both first and second have their bit set.)\n"
},
{
"code": null,
"e": 27144,
"s": 26556,
"text": "| (Bitwise OR) : This is also binary operator i.e. works on two operand. Bitwise OR operator takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.Syntax:$First | $Second\n\nThis will return another number whose bits are \nset if either the bit of first or second are set.\nExample:Input: First = 5, Second = 3\n\nOutput: The bitwise | of both these value will be 7. \n\nExplanation:\nBinary representation of 5 is 0101 and 3 is 0011.\nTherefore their bitwise | will be 0111 (i.e. set \nif either first or second have their bit set.)\n"
},
{
"code": null,
"e": 27152,
"s": 27144,
"text": "Syntax:"
},
{
"code": null,
"e": 27269,
"s": 27152,
"text": "$First | $Second\n\nThis will return another number whose bits are \nset if either the bit of first or second are set.\n"
},
{
"code": null,
"e": 27278,
"s": 27269,
"text": "Example:"
},
{
"code": null,
"e": 27524,
"s": 27278,
"text": "Input: First = 5, Second = 3\n\nOutput: The bitwise | of both these value will be 7. \n\nExplanation:\nBinary representation of 5 is 0101 and 3 is 0011.\nTherefore their bitwise | will be 0111 (i.e. set \nif either first or second have their bit set.)\n"
},
{
"code": null,
"e": 28187,
"s": 27524,
"text": "^ (Bitwise XOR ) : This is also binary operator i.e. works on two operand. This is also known as Exclusive OR operator. Bitwise XOR takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.Syntax:$First ^ $Second\n\nThis will return another number whose bits are \nset if one of the bit in first or second is \nset but not both.\nExample:Input: First = 5, Second = 3 \n\nOutput: The bitwise ^ of both these value will be 6. \n\nExplanation:\nBinary representation of 5 is 0101 and 3 is 0011. \nTherefore their bitwise ^ will be 0110 (i.e. set \nif either first or second have their bit set but \nnot both.)\n"
},
{
"code": null,
"e": 28195,
"s": 28187,
"text": "Syntax:"
},
{
"code": null,
"e": 28325,
"s": 28195,
"text": "$First ^ $Second\n\nThis will return another number whose bits are \nset if one of the bit in first or second is \nset but not both.\n"
},
{
"code": null,
"e": 28334,
"s": 28325,
"text": "Example:"
},
{
"code": null,
"e": 28596,
"s": 28334,
"text": "Input: First = 5, Second = 3 \n\nOutput: The bitwise ^ of both these value will be 6. \n\nExplanation:\nBinary representation of 5 is 0101 and 3 is 0011. \nTherefore their bitwise ^ will be 0110 (i.e. set \nif either first or second have their bit set but \nnot both.)\n"
},
{
"code": null,
"e": 29013,
"s": 28596,
"text": "~ (Bitwise NOT) : This is a unary operator i.e. works on only one operand. Bitwise NOT operator takes one number and inverts all bits of it.Syntax:~$number\n\nThis will invert all the bits of $number.\nExample:Input: number = 5\n\nOutput: The bitwise '~' of this number will be -6.\n\nExplanation:\nBinary representation of 5 is 0101. Therefore the\nbitwise ~ of this will be 1010 (inverts all the \nbits of the input number)\n"
},
{
"code": null,
"e": 29021,
"s": 29013,
"text": "Syntax:"
},
{
"code": null,
"e": 29074,
"s": 29021,
"text": "~$number\n\nThis will invert all the bits of $number.\n"
},
{
"code": null,
"e": 29083,
"s": 29074,
"text": "Example:"
},
{
"code": null,
"e": 29293,
"s": 29083,
"text": "Input: number = 5\n\nOutput: The bitwise '~' of this number will be -6.\n\nExplanation:\nBinary representation of 5 is 0101. Therefore the\nbitwise ~ of this will be 1010 (inverts all the \nbits of the input number)\n"
},
{
"code": null,
"e": 29973,
"s": 29293,
"text": "<< (Bitwise Left Shift) : This is a binary operator i.e. works on two operand. Bitwise Left Shift operator takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.Syntax:$First << $Second\n\nThis will shift the bits of $First towards the \nleft. $Second decides the number of time the\nbits will be shifted.\nExample:Input: First = 5, Second = 1\n\nOutput: The bitwise << of both these value will be 10. \n\nExplanation:\nBinary representation of 5 is 0101 . Therefore, \nbitwise << will shift the bits of 5 one times \ntowards the left (i.e. 01010 )\nNote: Bitwise left shift with one bit is equivalent to multiplication with 2."
},
{
"code": null,
"e": 29981,
"s": 29973,
"text": "Syntax:"
},
{
"code": null,
"e": 30116,
"s": 29981,
"text": "$First << $Second\n\nThis will shift the bits of $First towards the \nleft. $Second decides the number of time the\nbits will be shifted.\n"
},
{
"code": null,
"e": 30125,
"s": 30116,
"text": "Example:"
},
{
"code": null,
"e": 30353,
"s": 30125,
"text": "Input: First = 5, Second = 1\n\nOutput: The bitwise << of both these value will be 10. \n\nExplanation:\nBinary representation of 5 is 0101 . Therefore, \nbitwise << will shift the bits of 5 one times \ntowards the left (i.e. 01010 )\n"
},
{
"code": null,
"e": 30431,
"s": 30353,
"text": "Note: Bitwise left shift with one bit is equivalent to multiplication with 2."
},
{
"code": null,
"e": 31111,
"s": 30431,
"text": ">> (Bitwise Right Shift) : This is also binary operator i.e. works on two operand. Bitwise Right Shift operator takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.Syntax:$First >> $Second\n\nThis will shift the bits of $First towards the \nright. $Second decides the number of time the \nbits will be shifted.\nExample:Input: First = 5, Second = 1 \n\nOutput: The bitwise >> of both these value will be 2. \n\nExplanation:\nBinary representation of 5 is 0101 . Therefore, \nbitwise >> will shift the bits of 5 one times \ntowards the right(i.e. 010)\nNote: Bitwise right shift with one bit is equivalent to division with 2."
},
{
"code": null,
"e": 31119,
"s": 31111,
"text": "Syntax:"
},
{
"code": null,
"e": 31256,
"s": 31119,
"text": "$First >> $Second\n\nThis will shift the bits of $First towards the \nright. $Second decides the number of time the \nbits will be shifted.\n"
},
{
"code": null,
"e": 31265,
"s": 31256,
"text": "Example:"
},
{
"code": null,
"e": 31490,
"s": 31265,
"text": "Input: First = 5, Second = 1 \n\nOutput: The bitwise >> of both these value will be 2. \n\nExplanation:\nBinary representation of 5 is 0101 . Therefore, \nbitwise >> will shift the bits of 5 one times \ntowards the right(i.e. 010)\n"
},
{
"code": null,
"e": 31563,
"s": 31490,
"text": "Note: Bitwise right shift with one bit is equivalent to division with 2."
},
{
"code": null,
"e": 31620,
"s": 31563,
"text": "Below is the implementation of Bitwise Operators in PHP:"
},
{
"code": "<?php // PHP code to demonstrate Bitwise Operator. // Bitwise AND $First = 5; $second = 3; $answer = $First & $second; print_r(\"Bitwise & of 5 and 3 is $answer\"); print_r(\"\\n\"); // Bitwise OR $answer = $First | $second; print_r(\"Bitwise | of 5 and 3 is $answer\"); print_r(\"\\n\"); // Bitwise XOR $answer = $First ^ $second; print_r(\"Bitwise ^ of 5 and 3 is $answer\"); print_r(\"\\n\"); // Bitwise NOT $answer = ~$First; print_r(\"Bitwise ~ of 5 is $answer\"); print_r(\"\\n\"); // Bitwise Left shift $second = 1; $answer = $First << $second; print_r(\"5 << 1 will be $answer\"); print_r(\"\\n\"); // Bitwise Right shift $answer = $First >> $second; print_r(\"5 >> 1 will be $answer\"); print_r(\"\\n\");?>",
"e": 32472,
"s": 31620,
"text": null
},
{
"code": null,
"e": 32480,
"s": 32472,
"text": "Output:"
},
{
"code": null,
"e": 32615,
"s": 32480,
"text": "Bitwise & of 5 and 3 is 1\nBitwise | of 5 and 3 is 7\nBitwise ^ of 5 and 3 is 6\nBitwise ~ of 5 is -6\n5 << 1 will be 10\n5 >> 1 will be 2\n"
},
{
"code": null,
"e": 32626,
"s": 32615,
"text": "PHP-basics"
},
{
"code": null,
"e": 32640,
"s": 32626,
"text": "PHP-Operators"
},
{
"code": null,
"e": 32644,
"s": 32640,
"text": "PHP"
},
{
"code": null,
"e": 32661,
"s": 32644,
"text": "Web Technologies"
},
{
"code": null,
"e": 32665,
"s": 32661,
"text": "PHP"
},
{
"code": null,
"e": 32763,
"s": 32665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32813,
"s": 32763,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 32853,
"s": 32813,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 32898,
"s": 32853,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 32925,
"s": 32898,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 32967,
"s": 32925,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 33007,
"s": 32967,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 33040,
"s": 33007,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33085,
"s": 33040,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33128,
"s": 33085,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
React-Bootstrap Fade and Collapse Component - GeeksforGeeks | 29 Sep, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Fade Component provides a way to add a fade animation to a child component or an element. Collapse Component provides a way to add a collapse toggle animation to a component or an element We can use the following approach in ReactJS to use the react-bootstrap Fade and Collapse Component.
Fade Props:
appear: When the component mounts, it is used to run the fade-in animation.
in: It is used to show the component.
mountOnEnter: It is used to mount the component as it waits until the first enter transition is triggered.
onEnter: It is a callback function that is triggered before the component fades in.
onEntered: It is a callback function that is triggered after the has component faded in.
onEntering: It is a callback function that is triggered after the component starts to fade in.
onExit: It is a callback function that is triggered before the component fades out.
onExited: It is a callback function that is triggered after the component has faded out.
onExiting: It is a callback function that is triggered after the component starts to fade out.
timeout: It is used to denote the duration of fade animation in milliseconds.
unmountOnExit: It is used to unmount the component.
Collapse Props:
appear: When the component mounts, it is used to run the expand animation.
children: It is used to define the children element for this component.
className: It is used to add a class name for the styling of this component.
dimension: It denotes the dimension in the form of height and width.
getDimensionValue: It is a function that returns the width or height of animating DOM node.
in: It is used to show the component.
mountOnEnter: It is used to mount the component as it waits until the first enter transition is triggered.
onEnter: It is a callback function that is triggered before the component expands.
onEntered: It is a callback function that is triggered after the component has expanded.
onEntering: It is a callback function that is triggered after the component starts to expand.
onExit: It is a callback function that is triggered before the component collapses.
onExited: It is a callback function that is triggered after the component has collapsed.
onExiting: It is a callback function that is triggered after the component starts to collapse.
role: It is used to define the ARIA role of collapsible element.
timeout: It is used to denote the duration of collapse animation in milliseconds.
unmountOnExit: It is used to unmount the component.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, 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 react-bootstrap
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Fade Component Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Filename: App.js
Javascript
import React, { useState } from 'react';import 'bootstrap/dist/css/bootstrap.css';import Button from 'react-bootstrap/Button'import Fade from 'react-bootstrap/Fade' export default function App() { const [open, setOpen] = useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Fade Component</h4> <div style={{ width: 660, height: 'auto' }}> <Button variant="link" onClick={() => setOpen(!open)} aria-expanded={open} aria-controls="fadeID" > Click to see Fade Effect! </Button> <Fade in={open}> <div id="fadeID" style={{ width: 300, textAlign: 'justify' }} > Greetings from GeeksforGeeks, How are you? Stay safe Always keep yourself health. Study and work hard. </div> </Fade> </div> </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:
Collapse Component Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Filename: App.js
Javascript
import React, { useState } from 'react';import 'bootstrap/dist/css/bootstrap.css';import Button from 'react-bootstrap/Button'import Collapse from 'react-bootstrap/Collapse' export default function App() { const [open, setOpen] = useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Collapse Component</h4> <div style={{ width: 660, height: 'auto' }}> <Button variant="link" onClick={() => setOpen(!open)} aria-expanded={open} aria-controls="collapseID" > Click to see Collapse Effect! </Button> <Collapse in={open}> <div id="collapseID" style={{ width: 300, textAlign: 'justify' }} > Greetings from GeeksforGeeks, How are you? Stay safe Always keep yourself health. Study and work hard. </div> </Collapse> </div> </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://react-bootstrap.github.io/utilities/transitions/#collapse
https://react-bootstrap.github.io/utilities/transitions/#fade
surindertarika1234
React-Bootstrap
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
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 ?
How to pass data from one component to other component in ReactJS ?
Create a Responsive Navbar using ReactJS | [
{
"code": null,
"e": 26179,
"s": 26151,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 26550,
"s": 26179,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Fade Component provides a way to add a fade animation to a child component or an element. Collapse Component provides a way to add a collapse toggle animation to a component or an element We can use the following approach in ReactJS to use the react-bootstrap Fade and Collapse Component."
},
{
"code": null,
"e": 26562,
"s": 26550,
"text": "Fade Props:"
},
{
"code": null,
"e": 26638,
"s": 26562,
"text": "appear: When the component mounts, it is used to run the fade-in animation."
},
{
"code": null,
"e": 26676,
"s": 26638,
"text": "in: It is used to show the component."
},
{
"code": null,
"e": 26783,
"s": 26676,
"text": "mountOnEnter: It is used to mount the component as it waits until the first enter transition is triggered."
},
{
"code": null,
"e": 26867,
"s": 26783,
"text": "onEnter: It is a callback function that is triggered before the component fades in."
},
{
"code": null,
"e": 26956,
"s": 26867,
"text": "onEntered: It is a callback function that is triggered after the has component faded in."
},
{
"code": null,
"e": 27051,
"s": 26956,
"text": "onEntering: It is a callback function that is triggered after the component starts to fade in."
},
{
"code": null,
"e": 27135,
"s": 27051,
"text": "onExit: It is a callback function that is triggered before the component fades out."
},
{
"code": null,
"e": 27224,
"s": 27135,
"text": "onExited: It is a callback function that is triggered after the component has faded out."
},
{
"code": null,
"e": 27319,
"s": 27224,
"text": "onExiting: It is a callback function that is triggered after the component starts to fade out."
},
{
"code": null,
"e": 27397,
"s": 27319,
"text": "timeout: It is used to denote the duration of fade animation in milliseconds."
},
{
"code": null,
"e": 27449,
"s": 27397,
"text": "unmountOnExit: It is used to unmount the component."
},
{
"code": null,
"e": 27465,
"s": 27449,
"text": "Collapse Props:"
},
{
"code": null,
"e": 27540,
"s": 27465,
"text": "appear: When the component mounts, it is used to run the expand animation."
},
{
"code": null,
"e": 27612,
"s": 27540,
"text": "children: It is used to define the children element for this component."
},
{
"code": null,
"e": 27689,
"s": 27612,
"text": "className: It is used to add a class name for the styling of this component."
},
{
"code": null,
"e": 27758,
"s": 27689,
"text": "dimension: It denotes the dimension in the form of height and width."
},
{
"code": null,
"e": 27850,
"s": 27758,
"text": "getDimensionValue: It is a function that returns the width or height of animating DOM node."
},
{
"code": null,
"e": 27888,
"s": 27850,
"text": "in: It is used to show the component."
},
{
"code": null,
"e": 27995,
"s": 27888,
"text": "mountOnEnter: It is used to mount the component as it waits until the first enter transition is triggered."
},
{
"code": null,
"e": 28078,
"s": 27995,
"text": "onEnter: It is a callback function that is triggered before the component expands."
},
{
"code": null,
"e": 28167,
"s": 28078,
"text": "onEntered: It is a callback function that is triggered after the component has expanded."
},
{
"code": null,
"e": 28261,
"s": 28167,
"text": "onEntering: It is a callback function that is triggered after the component starts to expand."
},
{
"code": null,
"e": 28345,
"s": 28261,
"text": "onExit: It is a callback function that is triggered before the component collapses."
},
{
"code": null,
"e": 28434,
"s": 28345,
"text": "onExited: It is a callback function that is triggered after the component has collapsed."
},
{
"code": null,
"e": 28529,
"s": 28434,
"text": "onExiting: It is a callback function that is triggered after the component starts to collapse."
},
{
"code": null,
"e": 28594,
"s": 28529,
"text": "role: It is used to define the ARIA role of collapsible element."
},
{
"code": null,
"e": 28676,
"s": 28594,
"text": "timeout: It is used to denote the duration of collapse animation in milliseconds."
},
{
"code": null,
"e": 28728,
"s": 28676,
"text": "unmountOnExit: It is used to unmount the component."
},
{
"code": null,
"e": 28778,
"s": 28728,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 28842,
"s": 28778,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 28874,
"s": 28842,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 28975,
"s": 28874,
"text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:"
},
{
"code": null,
"e": 28989,
"s": 28975,
"text": "cd foldername"
},
{
"code": null,
"e": 29094,
"s": 28989,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 29145,
"s": 29094,
"text": "npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 29197,
"s": 29145,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 29215,
"s": 29197,
"text": "Project Structure"
},
{
"code": null,
"e": 29360,
"s": 29215,
"text": "Fade Component 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": 29377,
"s": 29360,
"text": "Filename: App.js"
},
{
"code": null,
"e": 29388,
"s": 29377,
"text": "Javascript"
},
{
"code": "import React, { useState } from 'react';import 'bootstrap/dist/css/bootstrap.css';import Button from 'react-bootstrap/Button'import Fade from 'react-bootstrap/Fade' export default function App() { const [open, setOpen] = useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Fade Component</h4> <div style={{ width: 660, height: 'auto' }}> <Button variant=\"link\" onClick={() => setOpen(!open)} aria-expanded={open} aria-controls=\"fadeID\" > Click to see Fade Effect! </Button> <Fade in={open}> <div id=\"fadeID\" style={{ width: 300, textAlign: 'justify' }} > Greetings from GeeksforGeeks, How are you? Stay safe Always keep yourself health. Study and work hard. </div> </Fade> </div> </div> );}",
"e": 30373,
"s": 29388,
"text": null
},
{
"code": null,
"e": 30486,
"s": 30373,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 30496,
"s": 30486,
"text": "npm start"
},
{
"code": null,
"e": 30595,
"s": 30496,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 30744,
"s": 30595,
"text": "Collapse Component 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": 30761,
"s": 30744,
"text": "Filename: App.js"
},
{
"code": null,
"e": 30772,
"s": 30761,
"text": "Javascript"
},
{
"code": "import React, { useState } from 'react';import 'bootstrap/dist/css/bootstrap.css';import Button from 'react-bootstrap/Button'import Collapse from 'react-bootstrap/Collapse' export default function App() { const [open, setOpen] = useState(false); return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Collapse Component</h4> <div style={{ width: 660, height: 'auto' }}> <Button variant=\"link\" onClick={() => setOpen(!open)} aria-expanded={open} aria-controls=\"collapseID\" > Click to see Collapse Effect! </Button> <Collapse in={open}> <div id=\"collapseID\" style={{ width: 300, textAlign: 'justify' }} > Greetings from GeeksforGeeks, How are you? Stay safe Always keep yourself health. Study and work hard. </div> </Collapse> </div> </div> );}",
"e": 31789,
"s": 30772,
"text": null
},
{
"code": null,
"e": 31902,
"s": 31789,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 31912,
"s": 31902,
"text": "npm start"
},
{
"code": null,
"e": 32011,
"s": 31912,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 32023,
"s": 32011,
"text": "Reference: "
},
{
"code": null,
"e": 32089,
"s": 32023,
"text": "https://react-bootstrap.github.io/utilities/transitions/#collapse"
},
{
"code": null,
"e": 32151,
"s": 32089,
"text": "https://react-bootstrap.github.io/utilities/transitions/#fade"
},
{
"code": null,
"e": 32170,
"s": 32151,
"text": "surindertarika1234"
},
{
"code": null,
"e": 32186,
"s": 32170,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 32197,
"s": 32186,
"text": "JavaScript"
},
{
"code": null,
"e": 32205,
"s": 32197,
"text": "ReactJS"
},
{
"code": null,
"e": 32222,
"s": 32205,
"text": "Web Technologies"
},
{
"code": null,
"e": 32320,
"s": 32222,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32360,
"s": 32320,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32405,
"s": 32360,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32466,
"s": 32405,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32538,
"s": 32466,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 32584,
"s": 32538,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 32627,
"s": 32584,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32672,
"s": 32627,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 32737,
"s": 32672,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 32805,
"s": 32737,
"text": "How to pass data from one component to other component in ReactJS ?"
}
]
|
Python 3 | Program to print double sided stair-case pattern - GeeksforGeeks | 25 Jan, 2018
Below mentioned is the python 3 program to print the double sided stair case pattern.
Examples:
Input : 10
Output :
* *
* *
* * * *
* * * *
* * * * * *
* * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
Note : This code only works for even values of n.
# Python3 Program to demonstrate # staircase pattern # function definitiondef pattern(n): # for loop for rows for i in range(1,n+1): # conditional operator k =i + 1 if(i % 2 != 0) else i # for loop for printing spaces for g in range(k,n): if g>=k: print(end=" ") # according to value of k carry # out further operation for j in range(0,k): if j == k - 1: print(" * ") else: print(" * ", end = " ") # Driver coden = 10pattern(n)
Output:
* *
* *
* * * *
* * * *
* * * * * *
* * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
pattern-printing
Python Programs
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python program to check whether a number is Prime or not
Python Program for Binary Search (Recursive and Iterative)
Python Program for Fibonacci numbers
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 25979,
"s": 25951,
"text": "\n25 Jan, 2018"
},
{
"code": null,
"e": 26065,
"s": 25979,
"text": "Below mentioned is the python 3 program to print the double sided stair case pattern."
},
{
"code": null,
"e": 26075,
"s": 26065,
"text": "Examples:"
},
{
"code": null,
"e": 26418,
"s": 26075,
"text": "Input : 10\nOutput :\n\n * * \n * * \n * * * * \n * * * * \n * * * * * * \n * * * * * * \n * * * * * * * * \n * * * * * * * * \n * * * * * * * * * * \n * * * * * * * * * * \n\n"
},
{
"code": null,
"e": 26468,
"s": 26418,
"text": "Note : This code only works for even values of n."
},
{
"code": "# Python3 Program to demonstrate # staircase pattern # function definitiondef pattern(n): # for loop for rows for i in range(1,n+1): # conditional operator k =i + 1 if(i % 2 != 0) else i # for loop for printing spaces for g in range(k,n): if g>=k: print(end=\" \") # according to value of k carry # out further operation for j in range(0,k): if j == k - 1: print(\" * \") else: print(\" * \", end = \" \") # Driver coden = 10pattern(n)",
"e": 27042,
"s": 26468,
"text": null
},
{
"code": null,
"e": 27050,
"s": 27042,
"text": "Output:"
},
{
"code": null,
"e": 27373,
"s": 27050,
"text": "\n * * \n * * \n * * * * \n * * * * \n * * * * * * \n * * * * * * \n * * * * * * * * \n * * * * * * * * \n * * * * * * * * * * \n * * * * * * * * * * \n\n"
},
{
"code": null,
"e": 27390,
"s": 27373,
"text": "pattern-printing"
},
{
"code": null,
"e": 27406,
"s": 27390,
"text": "Python Programs"
},
{
"code": null,
"e": 27425,
"s": 27406,
"text": "School Programming"
},
{
"code": null,
"e": 27442,
"s": 27425,
"text": "pattern-printing"
},
{
"code": null,
"e": 27540,
"s": 27442,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27578,
"s": 27540,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 27627,
"s": 27578,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 27684,
"s": 27627,
"text": "Python program to check whether a number is Prime or not"
},
{
"code": null,
"e": 27743,
"s": 27684,
"text": "Python Program for Binary Search (Recursive and Iterative)"
},
{
"code": null,
"e": 27780,
"s": 27743,
"text": "Python Program for Fibonacci numbers"
},
{
"code": null,
"e": 27798,
"s": 27780,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27814,
"s": 27798,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 27833,
"s": 27814,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27858,
"s": 27833,
"text": "Reverse a string in Java"
}
]
|
Array of Strings in C++ | Array of strings can be created in C++ using string keyword. Here we are discussing a C++ program by using this approach.
Begin
Initialize the elements of array by string keyword. And take string as input.
Print the array.
End.
Live Demo
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
string Fruit[3] = {"Grape", "Mango", "Orange"};
cout <<"The name of fruits are:"<< "\n";
for (int i = 0; i < 3; i++)
cout<< Fruit[i]<<",";
return 0;
}
The name of fruits are:
Grape, Mango, Orange | [
{
"code": null,
"e": 1184,
"s": 1062,
"text": "Array of strings can be created in C++ using string keyword. Here we are discussing a C++ program by using this approach."
},
{
"code": null,
"e": 1296,
"s": 1184,
"text": "Begin\n Initialize the elements of array by string keyword. And take string as input.\n Print the array.\nEnd."
},
{
"code": null,
"e": 1307,
"s": 1296,
"text": " Live Demo"
},
{
"code": null,
"e": 1553,
"s": 1307,
"text": "#include<iostream>\n#include<bits/stdc++.h>\nusing namespace std;\nint main() {\n string Fruit[3] = {\"Grape\", \"Mango\", \"Orange\"};\n cout <<\"The name of fruits are:\"<< \"\\n\";\n for (int i = 0; i < 3; i++)\n cout<< Fruit[i]<<\",\";\n return 0;\n}"
},
{
"code": null,
"e": 1598,
"s": 1553,
"text": "The name of fruits are:\nGrape, Mango, Orange"
}
]
|
Spring Boot Scheduler Job @EnableScheduling | @Schedule Example | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
The Spring Framework provides abstractions for asynchronous execution and scheduling of tasks with the TaskExecutor and TaskScheduler interfaces, respectively.
In this tutorials, we are going to see how can we use TaskScheduler using Spring Boot Scheduler. And also we will have a discussion on how to use Spring @EnableScheduling and @Scheduled annotations.
To enable scheduling tasks in spring boot applicaiton, we can use the java based @EnableScheduling annotation.
@Configuration
@EnableScheduling
public class SpringBootConfig {
// config details..
}
If you are in xml based configuration, you can directly use <task:annotation-driven> in you config xml.
The scheduler methods should not return any values, that means it should be void.
The scheduler methods should not accept any parameters.
The @Scheduled annotation is used to create a schedule, it can be added to a method along with the data. Here are the different schedules :
@Scheduled(fixedDelay = 6000)
The duration between the end of the end of last task and start of next task is fixed. The next task always waits until the previous one is finished.
package com.onlinetutorialspoint;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedDelay = 6000)
public void reportCurrentTime() {
System.out.println("The time is -: "+ dateFormat.format(new Date()));
}
}
@Scheduled(fixedRate = 6000)
Fixed Rate makes the task on periodic intervals even if the last invocation may still be running.
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("The time is -: "+ dateFormat.format(new Date()));
}
}
@Scheduled(fixedRate = 6000, initialDelay = 1000)
An initial delay can be specified indicating the number of milliseconds to wait before the first execution of the method.
@Component
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 6000, initialDelay = 1000)
public void reportCurrentTime() {
System.out.println("The time is -: "+ dateFormat.format(new Date()));
}
}
Some times these schedulers (delays and rates) are not enough to fulfill our requirement, then a cron expression may be provided.
Let’s take an example, I would like to execute a perticular functionality only on weekdays (MON-FRI). We can define this as following..
@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// do something here..
}
"0 0 * * * *" = the top of every hour of every day.
"*/10 * * * * *" = every ten seconds.
"0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
"0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.
"0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
"0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
"0 0 0 25 12 ?" = every Christmas Day at midnight
You can see more details on cron expresions here.
Happy Learning:)
@Component,@Service,@Repository,@Controller in spring
How to enable Swagger in Spring Boot Application
How to set Spring Boot SetTimeZone
Spring Boot Apache ActiveMq In Memory Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Kafka Producer Example
Spring Boot Actuator Database Health Check
How to get Current UTC Time in Java
Spring Boot Hazelcast Cache Example
Spring Boot Actuator Example
Simple Spring Boot Example
Spring Boot EhCache Example
Spring Boot Kafka Consume JSON Messages Example
Spring Boot MongoDB + Spring Data Example
@Component,@Service,@Repository,@Controller in spring
How to enable Swagger in Spring Boot Application
How to set Spring Boot SetTimeZone
Spring Boot Apache ActiveMq In Memory Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Kafka Producer Example
Spring Boot Actuator Database Health Check
How to get Current UTC Time in Java
Spring Boot Hazelcast Cache Example
Spring Boot Actuator Example
Simple Spring Boot Example
Spring Boot EhCache Example
Spring Boot Kafka Consume JSON Messages Example
Spring Boot MongoDB + Spring Data Example
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 558,
"s": 398,
"text": "The Spring Framework provides abstractions for asynchronous execution and scheduling of tasks with the TaskExecutor and TaskScheduler interfaces, respectively."
},
{
"code": null,
"e": 757,
"s": 558,
"text": "In this tutorials, we are going to see how can we use TaskScheduler using Spring Boot Scheduler. And also we will have a discussion on how to use Spring @EnableScheduling and @Scheduled annotations."
},
{
"code": null,
"e": 868,
"s": 757,
"text": "To enable scheduling tasks in spring boot applicaiton, we can use the java based @EnableScheduling annotation."
},
{
"code": null,
"e": 959,
"s": 868,
"text": "@Configuration\n@EnableScheduling\npublic class SpringBootConfig {\n // config details..\n}"
},
{
"code": null,
"e": 1063,
"s": 959,
"text": "If you are in xml based configuration, you can directly use <task:annotation-driven> in you config xml."
},
{
"code": null,
"e": 1145,
"s": 1063,
"text": "The scheduler methods should not return any values, that means it should be void."
},
{
"code": null,
"e": 1201,
"s": 1145,
"text": "The scheduler methods should not accept any parameters."
},
{
"code": null,
"e": 1341,
"s": 1201,
"text": "The @Scheduled annotation is used to create a schedule, it can be added to a method along with the data. Here are the different schedules :"
},
{
"code": null,
"e": 1371,
"s": 1341,
"text": "@Scheduled(fixedDelay = 6000)"
},
{
"code": null,
"e": 1520,
"s": 1371,
"text": "The duration between the end of the end of last task and start of next task is fixed. The next task always waits until the previous one is finished."
},
{
"code": null,
"e": 2013,
"s": 1520,
"text": "package com.onlinetutorialspoint;\n\nimport org.springframework.scheduling.annotation.Scheduled;\nimport org.springframework.stereotype.Component;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\n@Component\npublic class ScheduledTasks {\n\n private static final SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm:ss\");\n @Scheduled(fixedDelay = 6000)\n public void reportCurrentTime() {\n System.out.println(\"The time is -: \"+ dateFormat.format(new Date()));\n }\n}"
},
{
"code": null,
"e": 2042,
"s": 2013,
"text": "@Scheduled(fixedRate = 6000)"
},
{
"code": null,
"e": 2140,
"s": 2042,
"text": "Fixed Rate makes the task on periodic intervals even if the last invocation may still be running."
},
{
"code": null,
"e": 2428,
"s": 2140,
"text": "@Component\npublic class ScheduledTasks {\n\n private static final SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm:ss\");\n @Scheduled(fixedRate = 6000)\n public void reportCurrentTime() {\n System.out.println(\"The time is -: \"+ dateFormat.format(new Date()));\n }\n}"
},
{
"code": null,
"e": 2478,
"s": 2428,
"text": "@Scheduled(fixedRate = 6000, initialDelay = 1000)"
},
{
"code": null,
"e": 2600,
"s": 2478,
"text": "An initial delay can be specified indicating the number of milliseconds to wait before the first execution of the method."
},
{
"code": null,
"e": 2909,
"s": 2600,
"text": "@Component\npublic class ScheduledTasks {\n\n private static final SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm:ss\");\n @Scheduled(fixedRate = 6000, initialDelay = 1000)\n public void reportCurrentTime() {\n System.out.println(\"The time is -: \"+ dateFormat.format(new Date()));\n }\n}"
},
{
"code": null,
"e": 3039,
"s": 2909,
"text": "Some times these schedulers (delays and rates) are not enough to fulfill our requirement, then a cron expression may be provided."
},
{
"code": null,
"e": 3175,
"s": 3039,
"text": "Let’s take an example, I would like to execute a perticular functionality only on weekdays (MON-FRI). We can define this as following.."
},
{
"code": null,
"e": 3271,
"s": 3175,
"text": "@Scheduled(cron=\"*/5 * * * * MON-FRI\")\npublic void doSomething() {\n // do something here..\n}"
},
{
"code": null,
"e": 3647,
"s": 3271,
"text": "\"0 0 * * * *\" = the top of every hour of every day.\n\"*/10 * * * * *\" = every ten seconds.\n\"0 0 8-10 * * *\" = 8, 9 and 10 o'clock of every day.\n\"0 0 6,19 * * *\" = 6:00 AM and 7:00 PM every day.\n\"0 0/30 8-10 * * *\" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.\n\"0 0 9-17 * * MON-FRI\" = on the hour nine-to-five weekdays\n\"0 0 0 25 12 ?\" = every Christmas Day at midnight\n"
},
{
"code": null,
"e": 3697,
"s": 3647,
"text": "You can see more details on cron expresions here."
},
{
"code": null,
"e": 3714,
"s": 3697,
"text": "Happy Learning:)"
},
{
"code": null,
"e": 4308,
"s": 3714,
"text": "\n@Component,@Service,@Repository,@Controller in spring\nHow to enable Swagger in Spring Boot Application\nHow to set Spring Boot SetTimeZone\nSpring Boot Apache ActiveMq In Memory Example\nHow to change Spring Boot Tomcat Port Number\nHow To Change Spring Boot Context Path\nSpring Boot Kafka Producer Example\nSpring Boot Actuator Database Health Check\nHow to get Current UTC Time in Java\nSpring Boot Hazelcast Cache Example\nSpring Boot Actuator Example\nSimple Spring Boot Example\nSpring Boot EhCache Example\nSpring Boot Kafka Consume JSON Messages Example\nSpring Boot MongoDB + Spring Data Example\n"
},
{
"code": null,
"e": 4362,
"s": 4308,
"text": "@Component,@Service,@Repository,@Controller in spring"
},
{
"code": null,
"e": 4411,
"s": 4362,
"text": "How to enable Swagger in Spring Boot Application"
},
{
"code": null,
"e": 4446,
"s": 4411,
"text": "How to set Spring Boot SetTimeZone"
},
{
"code": null,
"e": 4492,
"s": 4446,
"text": "Spring Boot Apache ActiveMq In Memory Example"
},
{
"code": null,
"e": 4537,
"s": 4492,
"text": "How to change Spring Boot Tomcat Port Number"
},
{
"code": null,
"e": 4576,
"s": 4537,
"text": "How To Change Spring Boot Context Path"
},
{
"code": null,
"e": 4611,
"s": 4576,
"text": "Spring Boot Kafka Producer Example"
},
{
"code": null,
"e": 4654,
"s": 4611,
"text": "Spring Boot Actuator Database Health Check"
},
{
"code": null,
"e": 4690,
"s": 4654,
"text": "How to get Current UTC Time in Java"
},
{
"code": null,
"e": 4726,
"s": 4690,
"text": "Spring Boot Hazelcast Cache Example"
},
{
"code": null,
"e": 4755,
"s": 4726,
"text": "Spring Boot Actuator Example"
},
{
"code": null,
"e": 4782,
"s": 4755,
"text": "Simple Spring Boot Example"
},
{
"code": null,
"e": 4810,
"s": 4782,
"text": "Spring Boot EhCache Example"
},
{
"code": null,
"e": 4858,
"s": 4810,
"text": "Spring Boot Kafka Consume JSON Messages Example"
},
{
"code": null,
"e": 4900,
"s": 4858,
"text": "Spring Boot MongoDB + Spring Data Example"
},
{
"code": null,
"e": 4906,
"s": 4904,
"text": "Δ"
},
{
"code": null,
"e": 4933,
"s": 4906,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 4960,
"s": 4933,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 4994,
"s": 4960,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 5035,
"s": 4994,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 5080,
"s": 5035,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 5118,
"s": 5080,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 5152,
"s": 5118,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 5183,
"s": 5152,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 5217,
"s": 5183,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 5250,
"s": 5217,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 5283,
"s": 5250,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 5323,
"s": 5283,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 5348,
"s": 5323,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 5379,
"s": 5348,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 5403,
"s": 5379,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 5449,
"s": 5403,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 5472,
"s": 5449,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 5499,
"s": 5472,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 5545,
"s": 5499,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 5585,
"s": 5545,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 5614,
"s": 5585,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 5648,
"s": 5614,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 5678,
"s": 5648,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 5714,
"s": 5678,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 5747,
"s": 5714,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 5780,
"s": 5747,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 5824,
"s": 5780,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 5858,
"s": 5824,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 5890,
"s": 5858,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 5918,
"s": 5890,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 5949,
"s": 5918,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 5990,
"s": 5949,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 6024,
"s": 5990,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 6049,
"s": 6024,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 6083,
"s": 6049,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 6119,
"s": 6083,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 6165,
"s": 6119,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 6216,
"s": 6165,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 6258,
"s": 6216,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 6289,
"s": 6258,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 6312,
"s": 6289,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 6342,
"s": 6312,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 6372,
"s": 6342,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 6421,
"s": 6372,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 6455,
"s": 6421,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 6488,
"s": 6455,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 6517,
"s": 6488,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 6549,
"s": 6517,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 6586,
"s": 6549,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 6615,
"s": 6586,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 6644,
"s": 6615,
"text": " Spring Boot – MockMvc JUnit"
}
]
|
Mongoose | countDocuments() Function | 17 Nov, 2020
The countDocuments() function is used to count the number of documents that match the filter in a database collection.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.
npm install mongoose
After installing mongoose module, you can check your mongoose version in the command prompt using the command.
npm version mongoose
After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.
node index.js
Filename: index.js
Javascript
const mongoose = require('mongoose'); // Database Connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); User.countDocuments({age:{$gte:5}}, function (err, count) { if (err){ console.log(err) }else{ console.log("Count :", count) }});
Steps to run the program:
The project structure will look like this:
Make sure you have installed mongoose module using the following command:
npm install mongoose
Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:
node index.js
So this is how you can use the mongoose countDocuments() function which function counts a number of documents matching filter in a database collection.
sarafvikas5
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Aggregation in MongoDB
Upsert in MongoDB
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "The countDocuments() function is used to count the number of documents that match the filter in a database collection."
},
{
"code": null,
"e": 181,
"s": 147,
"text": "Installation of mongoose module: "
},
{
"code": null,
"e": 284,
"s": 181,
"text": "You can visit the link to Install mongoose module. You can install this package by using this command."
},
{
"code": null,
"e": 307,
"s": 284,
"text": "npm install mongoose\n\n"
},
{
"code": null,
"e": 418,
"s": 307,
"text": "After installing mongoose module, you can check your mongoose version in the command prompt using the command."
},
{
"code": null,
"e": 441,
"s": 418,
"text": "npm version mongoose\n\n"
},
{
"code": null,
"e": 577,
"s": 441,
"text": "After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command."
},
{
"code": null,
"e": 594,
"s": 577,
"text": "node index.js\n\n\n"
},
{
"code": null,
"e": 614,
"s": 594,
"text": "Filename: index.js "
},
{
"code": null,
"e": 625,
"s": 614,
"text": "Javascript"
},
{
"code": "const mongoose = require('mongoose'); // Database Connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); User.countDocuments({age:{$gte:5}}, function (err, count) { if (err){ console.log(err) }else{ console.log(\"Count :\", count) }});",
"e": 1087,
"s": 625,
"text": null
},
{
"code": null,
"e": 1114,
"s": 1087,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 1157,
"s": 1114,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 1231,
"s": 1157,
"text": "Make sure you have installed mongoose module using the following command:"
},
{
"code": null,
"e": 1254,
"s": 1231,
"text": "npm install mongoose\n\n"
},
{
"code": null,
"e": 1437,
"s": 1254,
"text": "Below is the sample data in the database before the function is executed. You can use any GUI tool or terminal to see the database like we have used Robo3T GUI tool as shown below: "
},
{
"code": null,
"e": 1476,
"s": 1437,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 1492,
"s": 1476,
"text": "node index.js\n\n"
},
{
"code": null,
"e": 1645,
"s": 1492,
"text": "So this is how you can use the mongoose countDocuments() function which function counts a number of documents matching filter in a database collection. "
},
{
"code": null,
"e": 1657,
"s": 1645,
"text": "sarafvikas5"
},
{
"code": null,
"e": 1666,
"s": 1657,
"text": "Mongoose"
},
{
"code": null,
"e": 1674,
"s": 1666,
"text": "MongoDB"
},
{
"code": null,
"e": 1682,
"s": 1674,
"text": "Node.js"
},
{
"code": null,
"e": 1699,
"s": 1682,
"text": "Web Technologies"
},
{
"code": null,
"e": 1797,
"s": 1699,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1836,
"s": 1797,
"text": "Spring Boot JpaRepository with Example"
},
{
"code": null,
"e": 1863,
"s": 1836,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 1901,
"s": 1863,
"text": "MongoDB - db.collection.Find() Method"
},
{
"code": null,
"e": 1924,
"s": 1901,
"text": "Aggregation in MongoDB"
},
{
"code": null,
"e": 1942,
"s": 1924,
"text": "Upsert in MongoDB"
},
{
"code": null,
"e": 1990,
"s": 1942,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2023,
"s": 1990,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2056,
"s": 2023,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 2086,
"s": 2056,
"text": "Node.js fs.writeFile() Method"
}
]
|
C Program For Sorting An Array Of 0s, 1s and 2s | 16 Dec, 2021
Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:
Input: {0, 1, 2, 0, 1, 2}
Output: {0, 0, 1, 1, 2, 2}
Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}
Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}
A simple solution is discussed in this(Sort an array of 0s, 1s and 2s (Simple Counting)) post.Method:
Approach:The problem is similar to our old post Segregate 0s and 1s in an array, and both of these problems are variation of famous Dutch national flag problem.The problem was posed with three colours, here `0′, `1′ and `2′. The array is divided into four sections:
a[1..Lo-1] zeroes (red)a[Lo..Mid-1] ones (white)a[Mid..Hi] unknowna[Hi+1..N] twos (blue)If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range.Similarly, if the element is 1 then keep it as it is but shrink the unknown range.If the element is 2 then swap it with an element in high range.Algorithm: Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:CC// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); printf("n");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf("array after segregation "); printArray(arr, arr_size); getchar(); return 0;}Output: array after segregation
0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
a[1..Lo-1] zeroes (red)
a[Lo..Mid-1] ones (white)
a[Mid..Hi] unknown
a[Hi+1..N] twos (blue)
If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range.
Similarly, if the element is 1 then keep it as it is but shrink the unknown range.
If the element is 2 then swap it with an element in high range.Algorithm: Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:CC// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); printf("n");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf("array after segregation "); printArray(arr, arr_size); getchar(); return 0;}Output: array after segregation
0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
Algorithm:
Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:CC// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); printf("n");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf("array after segregation "); printArray(arr, arr_size); getchar(); return 0;}Output: array after segregation
0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).
Traverse the array from start to end and mid is less than high. (Loop counter is i)
If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1
If the element is 1 then update mid = mid + 1
If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processed
Print the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:CC// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); printf("n");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf("array after segregation "); printArray(arr, arr_size); getchar(); return 0;}Output: array after segregation
0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes
arrow_drop_upSave
Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:
Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++
Case (1) a[Mid] is white, Mid++
Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–
Continue until Mid>Hi.
Implementation:
C
// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf("%d ", arr[i]); printf("n");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf("array after segregation "); printArray(arr, arr_size); getchar(); return 0;}
Output:
array after segregation
0 0 0 0 0 1 1 1 1 1 2 2
Complexity Analysis:
Time Complexity: O(n). Only one traversal of the array is needed.
Space Complexity: O(1). No extra space is required.
Please refer complete article on Sort an array of 0s, 1s and 2s for more details!
Adobe
Amazon
Hike
MakeMyTrip
MAQ Software
Microsoft
Morgan Stanley
Ola Cabs
Paytm
Qualcomm
SAP Labs
Snapdeal
Walmart
Yatra.com
Arrays
C Programs
Sorting
Paytm
Morgan Stanley
Amazon
Microsoft
Snapdeal
Hike
MakeMyTrip
Ola Cabs
Walmart
MAQ Software
Adobe
Yatra.com
SAP Labs
Qualcomm
Arrays
Sorting
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
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
Header files in C/C++ and its uses
UDP Server-Client implementation in C | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:"
},
{
"code": null,
"e": 356,
"s": 213,
"text": "Input: {0, 1, 2, 0, 1, 2}\nOutput: {0, 0, 1, 1, 2, 2}\n\nInput: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}\nOutput: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}"
},
{
"code": null,
"e": 458,
"s": 356,
"text": "A simple solution is discussed in this(Sort an array of 0s, 1s and 2s (Simple Counting)) post.Method:"
},
{
"code": null,
"e": 725,
"s": 458,
"text": "Approach:The problem is similar to our old post Segregate 0s and 1s in an array, and both of these problems are variation of famous Dutch national flag problem.The problem was posed with three colours, here `0′, `1′ and `2′. The array is divided into four sections: "
},
{
"code": null,
"e": 3663,
"s": 725,
"text": "a[1..Lo-1] zeroes (red)a[Lo..Mid-1] ones (white)a[Mid..Hi] unknowna[Hi+1..N] twos (blue)If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range.Similarly, if the element is 1 then keep it as it is but shrink the unknown range.If the element is 2 then swap it with an element in high range.Algorithm: Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:CC// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf(\"%d \", arr[i]); printf(\"n\");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf(\"array after segregation \"); printArray(arr, arr_size); getchar(); return 0;}Output: array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 3687,
"s": 3663,
"text": "a[1..Lo-1] zeroes (red)"
},
{
"code": null,
"e": 3713,
"s": 3687,
"text": "a[Lo..Mid-1] ones (white)"
},
{
"code": null,
"e": 3732,
"s": 3713,
"text": "a[Mid..Hi] unknown"
},
{
"code": null,
"e": 3755,
"s": 3732,
"text": "a[Hi+1..N] twos (blue)"
},
{
"code": null,
"e": 3853,
"s": 3755,
"text": "If the ith element is 0 then swap the element to the low range, thus shrinking the unknown range."
},
{
"code": null,
"e": 3936,
"s": 3853,
"text": "Similarly, if the element is 1 then keep it as it is but shrink the unknown range."
},
{
"code": null,
"e": 6607,
"s": 3936,
"text": "If the element is 2 then swap it with an element in high range.Algorithm: Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:CC// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf(\"%d \", arr[i]); printf(\"n\");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf(\"array after segregation \"); printArray(arr, arr_size); getchar(); return 0;}Output: array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 6619,
"s": 6607,
"text": "Algorithm: "
},
{
"code": null,
"e": 9216,
"s": 6619,
"text": "Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2).Traverse the array from start to end and mid is less than high. (Loop counter is i)If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1If the element is 1 then update mid = mid + 1If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processedPrint the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:CC// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf(\"%d \", arr[i]); printf(\"n\");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf(\"array after segregation \"); printArray(arr, arr_size); getchar(); return 0;}Output: array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 9456,
"s": 9216,
"text": "Keep three indices low = 1, mid = 1 and high = N and there are four ranges, 1 to low (the range containing 0), low to mid (the range containing 1), mid to high (the range containing unknown elements) and high to N (the range containing 2)."
},
{
"code": null,
"e": 9540,
"s": 9456,
"text": "Traverse the array from start to end and mid is less than high. (Loop counter is i)"
},
{
"code": null,
"e": 9655,
"s": 9540,
"text": "If the element is 0 then swap the element with the element at index low and update low = low + 1 and mid = mid + 1"
},
{
"code": null,
"e": 9701,
"s": 9655,
"text": "If the element is 1 then update mid = mid + 1"
},
{
"code": null,
"e": 9863,
"s": 9701,
"text": "If the element is 2 then swap the element with the element at index high and update high = high – 1 and update i = i – 1. As the swapped element is not processed"
},
{
"code": null,
"e": 11818,
"s": 9863,
"text": "Print the output array.Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ Case (1) a[Mid] is white, Mid++Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–Continue until Mid>Hi.Implementation:CC// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf(\"%d \", arr[i]); printf(\"n\");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf(\"array after segregation \"); printArray(arr, arr_size); getchar(); return 0;}Output: array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed.Space Complexity: O(1). No extra space is required.Please refer complete article on Sort an array of 0s, 1s and 2s for more details!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 12007,
"s": 11818,
"text": "Dry Run: Part way through the process, some red, white and blue elements are known and are in the “right” place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:"
},
{
"code": null,
"e": 12156,
"s": 12007,
"text": "Examine a[Mid]. There are three possibilities: a[Mid] is (0) red, (1) white or (2) blue. Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++ "
},
{
"code": null,
"e": 12188,
"s": 12156,
"text": "Case (1) a[Mid] is white, Mid++"
},
{
"code": null,
"e": 12240,
"s": 12188,
"text": "Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi–"
},
{
"code": null,
"e": 12263,
"s": 12240,
"text": "Continue until Mid>Hi."
},
{
"code": null,
"e": 12279,
"s": 12263,
"text": "Implementation:"
},
{
"code": null,
"e": 12281,
"s": 12279,
"text": "C"
},
{
"code": "// C program to sort an array with // 0, 1 and 2 in a single pass#include <stdio.h> // Function to swap *a and *b void swap(int* a, int* b); // Sort the input array, the array is // assumed to have values in {0, 1, 2}void sort012(int a[], int arr_size){ int lo = 0; int hi = arr_size - 1; int mid = 0; while (mid <= hi) { switch (a[mid]) { case 0: swap(&a[lo++], &a[mid++]); break; case 1: mid++; break; case 2: swap(&a[mid], &a[hi--]); break; } }} // UTILITY FUNCTIONS void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;} /* Utility function to print array arr[] */void printArray(int arr[], int arr_size){ int i; for (i = 0; i < arr_size; i++) printf(\"%d \", arr[i]); printf(\"n\");} // Driver codeint main(){ int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = sizeof(arr) / sizeof(arr[0]); int i; sort012(arr, arr_size); printf(\"array after segregation \"); printArray(arr, arr_size); getchar(); return 0;}",
"e": 13446,
"s": 12281,
"text": null
},
{
"code": null,
"e": 13455,
"s": 13446,
"text": "Output: "
},
{
"code": null,
"e": 13505,
"s": 13455,
"text": "array after segregation\n 0 0 0 0 0 1 1 1 1 1 2 2 "
},
{
"code": null,
"e": 13527,
"s": 13505,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 13593,
"s": 13527,
"text": "Time Complexity: O(n). Only one traversal of the array is needed."
},
{
"code": null,
"e": 13645,
"s": 13593,
"text": "Space Complexity: O(1). No extra space is required."
},
{
"code": null,
"e": 13727,
"s": 13645,
"text": "Please refer complete article on Sort an array of 0s, 1s and 2s for more details!"
},
{
"code": null,
"e": 13733,
"s": 13727,
"text": "Adobe"
},
{
"code": null,
"e": 13740,
"s": 13733,
"text": "Amazon"
},
{
"code": null,
"e": 13745,
"s": 13740,
"text": "Hike"
},
{
"code": null,
"e": 13756,
"s": 13745,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 13769,
"s": 13756,
"text": "MAQ Software"
},
{
"code": null,
"e": 13779,
"s": 13769,
"text": "Microsoft"
},
{
"code": null,
"e": 13794,
"s": 13779,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 13803,
"s": 13794,
"text": "Ola Cabs"
},
{
"code": null,
"e": 13809,
"s": 13803,
"text": "Paytm"
},
{
"code": null,
"e": 13818,
"s": 13809,
"text": "Qualcomm"
},
{
"code": null,
"e": 13827,
"s": 13818,
"text": "SAP Labs"
},
{
"code": null,
"e": 13836,
"s": 13827,
"text": "Snapdeal"
},
{
"code": null,
"e": 13844,
"s": 13836,
"text": "Walmart"
},
{
"code": null,
"e": 13854,
"s": 13844,
"text": "Yatra.com"
},
{
"code": null,
"e": 13861,
"s": 13854,
"text": "Arrays"
},
{
"code": null,
"e": 13872,
"s": 13861,
"text": "C Programs"
},
{
"code": null,
"e": 13880,
"s": 13872,
"text": "Sorting"
},
{
"code": null,
"e": 13886,
"s": 13880,
"text": "Paytm"
},
{
"code": null,
"e": 13901,
"s": 13886,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 13908,
"s": 13901,
"text": "Amazon"
},
{
"code": null,
"e": 13918,
"s": 13908,
"text": "Microsoft"
},
{
"code": null,
"e": 13927,
"s": 13918,
"text": "Snapdeal"
},
{
"code": null,
"e": 13932,
"s": 13927,
"text": "Hike"
},
{
"code": null,
"e": 13943,
"s": 13932,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 13952,
"s": 13943,
"text": "Ola Cabs"
},
{
"code": null,
"e": 13960,
"s": 13952,
"text": "Walmart"
},
{
"code": null,
"e": 13973,
"s": 13960,
"text": "MAQ Software"
},
{
"code": null,
"e": 13979,
"s": 13973,
"text": "Adobe"
},
{
"code": null,
"e": 13989,
"s": 13979,
"text": "Yatra.com"
},
{
"code": null,
"e": 13998,
"s": 13989,
"text": "SAP Labs"
},
{
"code": null,
"e": 14007,
"s": 13998,
"text": "Qualcomm"
},
{
"code": null,
"e": 14014,
"s": 14007,
"text": "Arrays"
},
{
"code": null,
"e": 14022,
"s": 14014,
"text": "Sorting"
},
{
"code": null,
"e": 14120,
"s": 14022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14188,
"s": 14120,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14220,
"s": 14188,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 14234,
"s": 14220,
"text": "Linear Search"
},
{
"code": null,
"e": 14319,
"s": 14234,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 14342,
"s": 14319,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 14355,
"s": 14342,
"text": "Strings in C"
},
{
"code": null,
"e": 14396,
"s": 14355,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 14425,
"s": 14396,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 14460,
"s": 14425,
"text": "Header files in C/C++ and its uses"
}
]
|
Converting Number to String in C++ | 11 Jun, 2022
Converting numbers to string or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. But lack of knowledge of certain essential tools binds us to do so. Some methods to achieve this task are mentioned in this article.
There are 3 major methods to convert a number to a string, which are as follows:
Using string Stream
Using to_string()
Using boost lexical cast
In this method, a string stream declares a stream object which first inserts a number, as a stream into an object and then uses “str()” to follow the internal conversion of a number to a string.
Example:
CPP
// C++ code to demonstrate string stream method// to convert number to string.#include<iostream>#include <sstream> // for string streams#include <string> // for stringusing namespace std;int main(){ int num = 2016; // declaring output string stream ostringstream str1; // Sending a number as a stream into output // string str1 << num; // the str() converts number into string string geek = str1.str(); // Displaying the string cout << "The newly formed string from number is : "; cout << geek << endl; return 0;}
The newly formed string from number is : 2016
Time Complexity: O(n)
Auxiliary Space: O(n)
The function to_string() accepts a number(which can be any data type) and returns the number in the desired string.
CPP
// C++ code to demonstrate "to_string()" method// to convert number to string.#include <iostream>#include <string> // for string and to_string()using namespace std; // Driver Codeint main(){ // Declaring integer int i_val = 20; // Declaring float float f_val = 30.50; // Conversion of int into string using // to_string() string stri = to_string(i_val); // Conversion of float into string using // to_string() string strf = to_string(f_val); // Displaying the converted strings cout << "The integer in string is : "; cout << stri << endl; cout << "The float in string is : "; cout << strf << endl; return 0;}
The integer in string is : 20
The float in string is : 30.500000
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar to string conversion, the ” lexical_cast() ” function remains the same, but in ‘boost lexical cast‘ time argument list modifies to “lexical_cast(numeric_var).
Example:
CPP
// C++ code to demonstrate "lexical_cast()" method// to convert number to string.#include <boost/lexical_cast.hpp> // for lexical_cast()#include <iostream>#include <string> // for stringusing namespace std; // Driver Codeint main(){ // Declaring float float f_val = 10.5; // Declaring int int i_val = 17; // lexical_cast() converts a float into string string strf = boost::lexical_cast<string>(f_val); // lexical_cast() converts a int into string string stri = boost::lexical_cast<string>(i_val); // Displaying string converted numbers cout << "The float value in string is : "; cout << strf << endl; cout << "The int value in string is : "; cout << stri << endl; return 0;}
The float value in string is : 10.5
The int value in string is : 17
Time Complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
SaloniBansal1
simmytarika5
23620uday2021
anshikajain26
harsh_shokeen
surbhikumaridav
CPP-Library
cpp-string
cpp-stringstream
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jun, 2022"
},
{
"code": null,
"e": 427,
"s": 54,
"text": "Converting numbers to string or vice-versa is actually a big paradigm shift in itself. In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. But lack of knowledge of certain essential tools binds us to do so. Some methods to achieve this task are mentioned in this article."
},
{
"code": null,
"e": 508,
"s": 427,
"text": "There are 3 major methods to convert a number to a string, which are as follows:"
},
{
"code": null,
"e": 529,
"s": 508,
"text": "Using string Stream "
},
{
"code": null,
"e": 547,
"s": 529,
"text": "Using to_string()"
},
{
"code": null,
"e": 572,
"s": 547,
"text": "Using boost lexical cast"
},
{
"code": null,
"e": 768,
"s": 572,
"text": "In this method, a string stream declares a stream object which first inserts a number, as a stream into an object and then uses “str()” to follow the internal conversion of a number to a string. "
},
{
"code": null,
"e": 780,
"s": 768,
"text": "Example: "
},
{
"code": null,
"e": 784,
"s": 780,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate string stream method// to convert number to string.#include<iostream>#include <sstream> // for string streams#include <string> // for stringusing namespace std;int main(){ int num = 2016; // declaring output string stream ostringstream str1; // Sending a number as a stream into output // string str1 << num; // the str() converts number into string string geek = str1.str(); // Displaying the string cout << \"The newly formed string from number is : \"; cout << geek << endl; return 0;}",
"e": 1341,
"s": 784,
"text": null
},
{
"code": null,
"e": 1387,
"s": 1341,
"text": "The newly formed string from number is : 2016"
},
{
"code": null,
"e": 1409,
"s": 1387,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 1431,
"s": 1409,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 1549,
"s": 1431,
"text": " The function to_string() accepts a number(which can be any data type) and returns the number in the desired string. "
},
{
"code": null,
"e": 1553,
"s": 1549,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate \"to_string()\" method// to convert number to string.#include <iostream>#include <string> // for string and to_string()using namespace std; // Driver Codeint main(){ // Declaring integer int i_val = 20; // Declaring float float f_val = 30.50; // Conversion of int into string using // to_string() string stri = to_string(i_val); // Conversion of float into string using // to_string() string strf = to_string(f_val); // Displaying the converted strings cout << \"The integer in string is : \"; cout << stri << endl; cout << \"The float in string is : \"; cout << strf << endl; return 0;}",
"e": 2215,
"s": 1553,
"text": null
},
{
"code": null,
"e": 2280,
"s": 2215,
"text": "The integer in string is : 20\nThe float in string is : 30.500000"
},
{
"code": null,
"e": 2302,
"s": 2280,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 2324,
"s": 2302,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 2493,
"s": 2324,
"text": "Similar to string conversion, the ” lexical_cast() ” function remains the same, but in ‘boost lexical cast‘ time argument list modifies to “lexical_cast(numeric_var). "
},
{
"code": null,
"e": 2502,
"s": 2493,
"text": "Example:"
},
{
"code": null,
"e": 2506,
"s": 2502,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate \"lexical_cast()\" method// to convert number to string.#include <boost/lexical_cast.hpp> // for lexical_cast()#include <iostream>#include <string> // for stringusing namespace std; // Driver Codeint main(){ // Declaring float float f_val = 10.5; // Declaring int int i_val = 17; // lexical_cast() converts a float into string string strf = boost::lexical_cast<string>(f_val); // lexical_cast() converts a int into string string stri = boost::lexical_cast<string>(i_val); // Displaying string converted numbers cout << \"The float value in string is : \"; cout << strf << endl; cout << \"The int value in string is : \"; cout << stri << endl; return 0;}",
"e": 3228,
"s": 2506,
"text": null
},
{
"code": null,
"e": 3296,
"s": 3228,
"text": "The float value in string is : 10.5\nThe int value in string is : 17"
},
{
"code": null,
"e": 3318,
"s": 3296,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 3340,
"s": 3318,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 3766,
"s": 3340,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3780,
"s": 3766,
"text": "SaloniBansal1"
},
{
"code": null,
"e": 3793,
"s": 3780,
"text": "simmytarika5"
},
{
"code": null,
"e": 3807,
"s": 3793,
"text": "23620uday2021"
},
{
"code": null,
"e": 3821,
"s": 3807,
"text": "anshikajain26"
},
{
"code": null,
"e": 3835,
"s": 3821,
"text": "harsh_shokeen"
},
{
"code": null,
"e": 3851,
"s": 3835,
"text": "surbhikumaridav"
},
{
"code": null,
"e": 3863,
"s": 3851,
"text": "CPP-Library"
},
{
"code": null,
"e": 3874,
"s": 3863,
"text": "cpp-string"
},
{
"code": null,
"e": 3891,
"s": 3874,
"text": "cpp-stringstream"
},
{
"code": null,
"e": 3902,
"s": 3891,
"text": "C Language"
},
{
"code": null,
"e": 3906,
"s": 3902,
"text": "C++"
},
{
"code": null,
"e": 3910,
"s": 3906,
"text": "CPP"
},
{
"code": null,
"e": 4008,
"s": 3910,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4025,
"s": 4008,
"text": "Substring in C++"
},
{
"code": null,
"e": 4047,
"s": 4025,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 4093,
"s": 4047,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 4138,
"s": 4093,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4163,
"s": 4138,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4181,
"s": 4163,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 4224,
"s": 4181,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4270,
"s": 4224,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 4313,
"s": 4270,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
List out all the Shells Using Linux Commands | 22 Jun, 2020
There are various methods to list all the shells which are installed in our Linux system. A Shell is a software program that acts as an interface between the user and the operating system(OS). It can also be thought of as a command interpreter that is used to execute another program.
Method 1: Using cat command
Example:
cat /etc/shells
Using ‘cat’ command
Explanation: The list of all the shells which are currently installed in our Linux system is stored in the ‘shells’ file which is present in /etc folder of the system. It has read-only access by default and is modified automatically whenever we install a new shell in our system. As we can see, the cat command displays the various installed shells along with their installation paths.
Method 2: Use of grep command with Regular Expressions.
Example:
grep '^[^#]' /etc/shells
Using ‘grep’ command
Explanation: Regular Expressions are one of the most powerful tools that come in handy when handling complex expressions. We can use regular expressions with grep command to display all the shells installed in our system as shown above.
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
screen command in Linux with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 313,
"s": 28,
"text": "There are various methods to list all the shells which are installed in our Linux system. A Shell is a software program that acts as an interface between the user and the operating system(OS). It can also be thought of as a command interpreter that is used to execute another program."
},
{
"code": null,
"e": 341,
"s": 313,
"text": "Method 1: Using cat command"
},
{
"code": null,
"e": 350,
"s": 341,
"text": "Example:"
},
{
"code": null,
"e": 366,
"s": 350,
"text": "cat /etc/shells"
},
{
"code": null,
"e": 386,
"s": 366,
"text": "Using ‘cat’ command"
},
{
"code": null,
"e": 772,
"s": 386,
"text": "Explanation: The list of all the shells which are currently installed in our Linux system is stored in the ‘shells’ file which is present in /etc folder of the system. It has read-only access by default and is modified automatically whenever we install a new shell in our system. As we can see, the cat command displays the various installed shells along with their installation paths."
},
{
"code": null,
"e": 828,
"s": 772,
"text": "Method 2: Use of grep command with Regular Expressions."
},
{
"code": null,
"e": 837,
"s": 828,
"text": "Example:"
},
{
"code": null,
"e": 862,
"s": 837,
"text": "grep '^[^#]' /etc/shells"
},
{
"code": null,
"e": 883,
"s": 862,
"text": "Using ‘grep’ command"
},
{
"code": null,
"e": 1120,
"s": 883,
"text": "Explanation: Regular Expressions are one of the most powerful tools that come in handy when handling complex expressions. We can use regular expressions with grep command to display all the shells installed in our system as shown above."
},
{
"code": null,
"e": 1127,
"s": 1120,
"text": "Picked"
},
{
"code": null,
"e": 1138,
"s": 1127,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1236,
"s": 1138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1262,
"s": 1236,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1297,
"s": 1262,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1334,
"s": 1297,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1363,
"s": 1334,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1402,
"s": 1363,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 1439,
"s": 1402,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1479,
"s": 1439,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 1513,
"s": 1479,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1550,
"s": 1513,
"text": "chmod command in Linux with examples"
}
]
|
Java Swing | JTextArea | 10 May, 2022
JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit the text . JTextArea inherits JComponent class. The text in JTextArea can be set to different available fonts and can be appended to new text . A text area can be customized to the need of user .Constructors of JTextArea are:
JTextArea() : constructs a new blank text area . JTextArea(String s) : constructs a new text area with a given initial text. JTextArea(int row, int column) : constructs a new text area with a given number of rows and columns. JTextArea(String s, int row, int column) : constructs a new text area with a given number of rows and columns and a given initial text.
JTextArea() : constructs a new blank text area .
JTextArea(String s) : constructs a new text area with a given initial text.
JTextArea(int row, int column) : constructs a new text area with a given number of rows and columns.
JTextArea(String s, int row, int column) : constructs a new text area with a given number of rows and columns and a given initial text.
Commonly used methods :
append(String s) : appends the given string to the text of the text area. getLineCount() : get number of lines in the text of text area. setFont(Font f) : sets the font of text area to the given font. setColumns(int c) : sets the number of columns of the text area to given integer. setRows(int r) : sets the number of rows of the text area to given integer. getColumns() : get the number of columns of text area. getRows() : get the number of rows of text area.
append(String s) : appends the given string to the text of the text area.
getLineCount() : get number of lines in the text of text area.
setFont(Font f) : sets the font of text area to the given font.
setColumns(int c) : sets the number of columns of the text area to given integer.
setRows(int r) : sets the number of rows of the text area to given integer.
getColumns() : get the number of columns of text area.
getRows() : get the number of rows of text area.
1. Program to create a simple JTextArea
Java
// Java Program to create a simple JTextAreaimport java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame implements ActionListener { // JFrame static JFrame f; // JButton static JButton b; // label to display text static JLabel l; // text area static JTextArea jt; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("textfield"); // create a label to display text l = new JLabel("nothing entered"); // create a new button b = new JButton("submit"); // create a object of the text class text te = new text(); // addActionListener to button b.addActionListener(te); // create a text area, specifying the rows and columns jt = new JTextArea(10, 10); JPanel p = new JPanel(); // add the text area and button to panel p.add(jt); p.add(b); p.add(l); f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("submit")) { // set the text of the label to the text of the field l.setText(jt.getText()); } }}
Output:
2. Program to create a JTextArea and set a initial text and add buttons to change the font of text area.
Java
// Java Program to create a JTextArea and// set a initial text and add buttons to change// the font of text area.import java.awt.event.*;import java.awt.*;import javax.swing.*;class text11 extends JFrame implements ActionListener { // JFrame static JFrame f; // JButton static JButton b, b1, b2, b3; // label to display text static JLabel l, l1; // text area static JTextArea jt; // default constructor text11() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("textfield"); // create a label to display text l = new JLabel("nothing entered"); l1 = new JLabel("0 lines"); // create a new buttons b = new JButton("submit"); b1 = new JButton("plain"); b2 = new JButton("italic"); b3 = new JButton("bold"); // create a object of the text class text11 te = new text11(); // addActionListener to button b.addActionListener(te); b1.addActionListener(te); b2.addActionListener(te); b3.addActionListener(te); // create a text area, specifying the rows and columns jt = new JTextArea("please write something ", 10, 10); JPanel p = new JPanel(); // add the text area and button to panel p.add(jt); p.add(b); p.add(b1); p.add(b2); p.add(b3); p.add(l); p.add(l1); f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("submit")) { // set the text of the label to the text of the field l.setText(jt.getText() + ", "); l1.setText(jt.getLineCount() + " lines"); } else if (s.equals("bold")) { // set bold font Font f = new Font("Serif", Font.BOLD, 15); jt.setFont(f); } else if (s.equals("italic")) { // set italic font Font f = new Font("Serif", Font.ITALIC, 15); jt.setFont(f); } else if (s.equals("plain")) { // set plain font Font f = new Font("Serif", Font.PLAIN, 15); jt.setFont(f); } }}
Output :
Note : The following program might not run in an online compiler please use an offline IDE
nidhi_biet
Akanksha_Rai
sagar0719kumar
sweetyty
java-swing
Java
Java Programs
Misc
Programming Language
Misc
Misc
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 394,
"s": 52,
"text": "JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit the text . JTextArea inherits JComponent class. The text in JTextArea can be set to different available fonts and can be appended to new text . A text area can be customized to the need of user .Constructors of JTextArea are: "
},
{
"code": null,
"e": 757,
"s": 394,
"text": "JTextArea() : constructs a new blank text area . JTextArea(String s) : constructs a new text area with a given initial text. JTextArea(int row, int column) : constructs a new text area with a given number of rows and columns. JTextArea(String s, int row, int column) : constructs a new text area with a given number of rows and columns and a given initial text. "
},
{
"code": null,
"e": 807,
"s": 757,
"text": "JTextArea() : constructs a new blank text area . "
},
{
"code": null,
"e": 884,
"s": 807,
"text": "JTextArea(String s) : constructs a new text area with a given initial text. "
},
{
"code": null,
"e": 986,
"s": 884,
"text": "JTextArea(int row, int column) : constructs a new text area with a given number of rows and columns. "
},
{
"code": null,
"e": 1123,
"s": 986,
"text": "JTextArea(String s, int row, int column) : constructs a new text area with a given number of rows and columns and a given initial text. "
},
{
"code": null,
"e": 1148,
"s": 1123,
"text": "Commonly used methods : "
},
{
"code": null,
"e": 1613,
"s": 1148,
"text": "append(String s) : appends the given string to the text of the text area. getLineCount() : get number of lines in the text of text area. setFont(Font f) : sets the font of text area to the given font. setColumns(int c) : sets the number of columns of the text area to given integer. setRows(int r) : sets the number of rows of the text area to given integer. getColumns() : get the number of columns of text area. getRows() : get the number of rows of text area. "
},
{
"code": null,
"e": 1688,
"s": 1613,
"text": "append(String s) : appends the given string to the text of the text area. "
},
{
"code": null,
"e": 1752,
"s": 1688,
"text": "getLineCount() : get number of lines in the text of text area. "
},
{
"code": null,
"e": 1818,
"s": 1752,
"text": "setFont(Font f) : sets the font of text area to the given font. "
},
{
"code": null,
"e": 1901,
"s": 1818,
"text": "setColumns(int c) : sets the number of columns of the text area to given integer. "
},
{
"code": null,
"e": 1978,
"s": 1901,
"text": "setRows(int r) : sets the number of rows of the text area to given integer. "
},
{
"code": null,
"e": 2034,
"s": 1978,
"text": "getColumns() : get the number of columns of text area. "
},
{
"code": null,
"e": 2084,
"s": 2034,
"text": "getRows() : get the number of rows of text area. "
},
{
"code": null,
"e": 2126,
"s": 2084,
"text": "1. Program to create a simple JTextArea "
},
{
"code": null,
"e": 2131,
"s": 2126,
"text": "Java"
},
{
"code": "// Java Program to create a simple JTextAreaimport java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame implements ActionListener { // JFrame static JFrame f; // JButton static JButton b; // label to display text static JLabel l; // text area static JTextArea jt; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"textfield\"); // create a label to display text l = new JLabel(\"nothing entered\"); // create a new button b = new JButton(\"submit\"); // create a object of the text class text te = new text(); // addActionListener to button b.addActionListener(te); // create a text area, specifying the rows and columns jt = new JTextArea(10, 10); JPanel p = new JPanel(); // add the text area and button to panel p.add(jt); p.add(b); p.add(l); f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"submit\")) { // set the text of the label to the text of the field l.setText(jt.getText()); } }}",
"e": 3559,
"s": 2131,
"text": null
},
{
"code": null,
"e": 3569,
"s": 3559,
"text": "Output: "
},
{
"code": null,
"e": 3676,
"s": 3569,
"text": "2. Program to create a JTextArea and set a initial text and add buttons to change the font of text area. "
},
{
"code": null,
"e": 3681,
"s": 3676,
"text": "Java"
},
{
"code": "// Java Program to create a JTextArea and// set a initial text and add buttons to change// the font of text area.import java.awt.event.*;import java.awt.*;import javax.swing.*;class text11 extends JFrame implements ActionListener { // JFrame static JFrame f; // JButton static JButton b, b1, b2, b3; // label to display text static JLabel l, l1; // text area static JTextArea jt; // default constructor text11() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"textfield\"); // create a label to display text l = new JLabel(\"nothing entered\"); l1 = new JLabel(\"0 lines\"); // create a new buttons b = new JButton(\"submit\"); b1 = new JButton(\"plain\"); b2 = new JButton(\"italic\"); b3 = new JButton(\"bold\"); // create a object of the text class text11 te = new text11(); // addActionListener to button b.addActionListener(te); b1.addActionListener(te); b2.addActionListener(te); b3.addActionListener(te); // create a text area, specifying the rows and columns jt = new JTextArea(\"please write something \", 10, 10); JPanel p = new JPanel(); // add the text area and button to panel p.add(jt); p.add(b); p.add(b1); p.add(b2); p.add(b3); p.add(l); p.add(l1); f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"submit\")) { // set the text of the label to the text of the field l.setText(jt.getText() + \", \"); l1.setText(jt.getLineCount() + \" lines\"); } else if (s.equals(\"bold\")) { // set bold font Font f = new Font(\"Serif\", Font.BOLD, 15); jt.setFont(f); } else if (s.equals(\"italic\")) { // set italic font Font f = new Font(\"Serif\", Font.ITALIC, 15); jt.setFont(f); } else if (s.equals(\"plain\")) { // set plain font Font f = new Font(\"Serif\", Font.PLAIN, 15); jt.setFont(f); } }}",
"e": 6068,
"s": 3681,
"text": null
},
{
"code": null,
"e": 6079,
"s": 6068,
"text": "Output : "
},
{
"code": null,
"e": 6176,
"s": 6083,
"text": "Note : The following program might not run in an online compiler please use an offline IDE "
},
{
"code": null,
"e": 6187,
"s": 6176,
"text": "nidhi_biet"
},
{
"code": null,
"e": 6200,
"s": 6187,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 6215,
"s": 6200,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 6224,
"s": 6215,
"text": "sweetyty"
},
{
"code": null,
"e": 6235,
"s": 6224,
"text": "java-swing"
},
{
"code": null,
"e": 6240,
"s": 6235,
"text": "Java"
},
{
"code": null,
"e": 6254,
"s": 6240,
"text": "Java Programs"
},
{
"code": null,
"e": 6259,
"s": 6254,
"text": "Misc"
},
{
"code": null,
"e": 6280,
"s": 6259,
"text": "Programming Language"
},
{
"code": null,
"e": 6285,
"s": 6280,
"text": "Misc"
},
{
"code": null,
"e": 6290,
"s": 6285,
"text": "Misc"
},
{
"code": null,
"e": 6295,
"s": 6290,
"text": "Java"
},
{
"code": null,
"e": 6393,
"s": 6295,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6444,
"s": 6393,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6475,
"s": 6444,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 6494,
"s": 6475,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6524,
"s": 6494,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 6542,
"s": 6524,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6570,
"s": 6542,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 6596,
"s": 6570,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6640,
"s": 6596,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 6674,
"s": 6640,
"text": "Convert Double to Integer in Java"
}
]
|
Change an HTML5 input placeholder color with CSS | 08 Nov, 2021
The placeholder selector in the CSS pseudo-element is used to design the placeholder text by changing the text color and it allows to modify the style of the text. In most of the browsers, the placeholder (inside the input tag) is of grey color. In order to change the color of this placeholder, non-standard ::placeholder selectors can be used, which implements the color attribute in that particular selector. This selector varies from browser to browser. For eg, for Google Chrome, Mozilla Firefox, and Opera Browsers, etc, the selectors can be implemented as:
Syntax:
::placeholder
For Internet Explorer::-ms-input-placeholder
For Internet Explorer:
:-ms-input-placeholder
For Microsoft Edge:::-ms-input-placeholder
For Microsoft Edge:
::-ms-input-placeholder
Example 1: This code shows the use of ::placeholder selectors in different browsers.
HTML
<!DOCTYPE html><html> <head> <title>Change Placeholder Color</title> <style> ::placeholder { /* Firefox, Chrome, Opera */ color: blue; } :-ms-input-placeholder { /* Internet Explorer 10-11 */ color: red; } ::-ms-input-placeholder { /* Microsoft Edge */ color: orange; } </style></head> <body> <p>Change Placeholder Color</p> <input type="text" placeholder="Enter your Text"></body> </html>
Output:
In Google Chrome:
In Google Chrome:
In Microsoft Edge:
In Microsoft Edge:
In Internet Explorer:
In Internet Explorer:
Note: The placeholder selector is no longer supported by Internet Explorer.
Example 2: This code implements a placeholder selector in the email attribute of the input tag. Placeholder selectors can be applied to any attributes (text, tel, password, and etc) of the input tag, to highlight changes in color in any different attributes.
HTML
<!DOCTYPE html><html> <head> <title>Change Placeholder Color</title> <style> input[type="email"]::placeholder { /* Firefox, Chrome, Opera */ color: blue; } input[type="email"]:-ms-input-placeholder { /* Internet Explorer 10-11 */ color: red; } input[type="email"]::-ms-input-placeholder { /* Microsoft Edge */ color: orange; } </style></head> <body> <p>Change Placeholder Color</p> <input type="email" placeholder="Enter your Email"></body> </html>
Output:
ysachin2314
bhaskargeeksforgeeks
CSS-Misc
HTML5
Picked
Technical Scripter 2018
CSS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Nov, 2021"
},
{
"code": null,
"e": 617,
"s": 53,
"text": "The placeholder selector in the CSS pseudo-element is used to design the placeholder text by changing the text color and it allows to modify the style of the text. In most of the browsers, the placeholder (inside the input tag) is of grey color. In order to change the color of this placeholder, non-standard ::placeholder selectors can be used, which implements the color attribute in that particular selector. This selector varies from browser to browser. For eg, for Google Chrome, Mozilla Firefox, and Opera Browsers, etc, the selectors can be implemented as:"
},
{
"code": null,
"e": 626,
"s": 617,
"text": "Syntax: "
},
{
"code": null,
"e": 640,
"s": 626,
"text": "::placeholder"
},
{
"code": null,
"e": 685,
"s": 640,
"text": "For Internet Explorer::-ms-input-placeholder"
},
{
"code": null,
"e": 708,
"s": 685,
"text": "For Internet Explorer:"
},
{
"code": null,
"e": 731,
"s": 708,
"text": ":-ms-input-placeholder"
},
{
"code": null,
"e": 774,
"s": 731,
"text": "For Microsoft Edge:::-ms-input-placeholder"
},
{
"code": null,
"e": 794,
"s": 774,
"text": "For Microsoft Edge:"
},
{
"code": null,
"e": 818,
"s": 794,
"text": "::-ms-input-placeholder"
},
{
"code": null,
"e": 903,
"s": 818,
"text": "Example 1: This code shows the use of ::placeholder selectors in different browsers."
},
{
"code": null,
"e": 908,
"s": 903,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Change Placeholder Color</title> <style> ::placeholder { /* Firefox, Chrome, Opera */ color: blue; } :-ms-input-placeholder { /* Internet Explorer 10-11 */ color: red; } ::-ms-input-placeholder { /* Microsoft Edge */ color: orange; } </style></head> <body> <p>Change Placeholder Color</p> <input type=\"text\" placeholder=\"Enter your Text\"></body> </html>",
"e": 1416,
"s": 908,
"text": null
},
{
"code": null,
"e": 1424,
"s": 1416,
"text": "Output:"
},
{
"code": null,
"e": 1442,
"s": 1424,
"text": "In Google Chrome:"
},
{
"code": null,
"e": 1460,
"s": 1442,
"text": "In Google Chrome:"
},
{
"code": null,
"e": 1479,
"s": 1460,
"text": "In Microsoft Edge:"
},
{
"code": null,
"e": 1498,
"s": 1479,
"text": "In Microsoft Edge:"
},
{
"code": null,
"e": 1520,
"s": 1498,
"text": "In Internet Explorer:"
},
{
"code": null,
"e": 1542,
"s": 1520,
"text": "In Internet Explorer:"
},
{
"code": null,
"e": 1618,
"s": 1542,
"text": "Note: The placeholder selector is no longer supported by Internet Explorer."
},
{
"code": null,
"e": 1878,
"s": 1618,
"text": "Example 2: This code implements a placeholder selector in the email attribute of the input tag. Placeholder selectors can be applied to any attributes (text, tel, password, and etc) of the input tag, to highlight changes in color in any different attributes. "
},
{
"code": null,
"e": 1883,
"s": 1878,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Change Placeholder Color</title> <style> input[type=\"email\"]::placeholder { /* Firefox, Chrome, Opera */ color: blue; } input[type=\"email\"]:-ms-input-placeholder { /* Internet Explorer 10-11 */ color: red; } input[type=\"email\"]::-ms-input-placeholder { /* Microsoft Edge */ color: orange; } </style></head> <body> <p>Change Placeholder Color</p> <input type=\"email\" placeholder=\"Enter your Email\"></body> </html>",
"e": 2456,
"s": 1883,
"text": null
},
{
"code": null,
"e": 2464,
"s": 2456,
"text": "Output:"
},
{
"code": null,
"e": 2476,
"s": 2464,
"text": "ysachin2314"
},
{
"code": null,
"e": 2497,
"s": 2476,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 2506,
"s": 2497,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2512,
"s": 2506,
"text": "HTML5"
},
{
"code": null,
"e": 2519,
"s": 2512,
"text": "Picked"
},
{
"code": null,
"e": 2543,
"s": 2519,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2547,
"s": 2543,
"text": "CSS"
},
{
"code": null,
"e": 2566,
"s": 2547,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2583,
"s": 2566,
"text": "Web Technologies"
}
]
|
Convert list of lists to dataframe in R | 30 May, 2021
In this article, we will discuss how to convert a list of lists to dataframe in R Programming Language. We will convert a list of lists to a data frame both by row and by column.
Example 1: R program to create three lists inside a list with numeric and character type and convert into dataframe by column.
Syntax as.data.frame(do.call(cbind, list_name))
Parameters: Where cbind is to convert list to dataframe by column and list_name is the input list which is list of lists
Code:
R
# create list and create 3 lists # inside this listlists = list(list1 = list(1, 2, 3, 4, 5), list2 = list('a', 'b', 'c', 'd', 'e'), list3 = list(2, 3, 4, 5, 6)) # convert list of lists into dataframe# by columnprint(as.data.frame(do.call(cbind, lists)))
Output:
list1 list2 list3
1 1 a 2
2 2 b 3
3 3 c 4
4 4 d 5
5 5 e 6
Example 2: R program to create two lists inside a list with numeric and character type and convert into dataframe by column
R
# create list and create 2 lists # inside this listlists = list(list1 = list(1, 2, 3, 4, 5), list2 = list('a', 'b', 'c', 'd', 'e')) # convert list of lists into# dataframe by columnprint(as.data.frame(do.call(cbind, lists)))
Output:
list1 list2
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
Example 3: R program to create three lists inside a list with numeric and character type and convert into dataframe by column.
Syntax: as.data.frame(do.call(rbind,list_name))
Parameters: Where rbind is to convert list to dataframe by row and list_name is the input list which is list of lists
R
# create list and create 3 lists # inside this listlists = list(list1 = list(1, 2, 3, 4, 5), list2 = list('a', 'b', 'c', 'd', 'e'), list3 = list(2, 3, 4, 5, 6)) # convert list of lists into dataframe # by rowprint(as.data.frame(do.call(rbind, lists)))
Output:
V1 V2 V3 V4 V5
list1 1 2 3 4 5
list2 a b c d e
list3 2 3 4 5 6
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
Extract specific column from a DataFrame using column name in R | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 207,
"s": 28,
"text": "In this article, we will discuss how to convert a list of lists to dataframe in R Programming Language. We will convert a list of lists to a data frame both by row and by column."
},
{
"code": null,
"e": 334,
"s": 207,
"text": "Example 1: R program to create three lists inside a list with numeric and character type and convert into dataframe by column."
},
{
"code": null,
"e": 382,
"s": 334,
"text": "Syntax as.data.frame(do.call(cbind, list_name))"
},
{
"code": null,
"e": 504,
"s": 382,
"text": "Parameters: Where cbind is to convert list to dataframe by column and list_name is the input list which is list of lists"
},
{
"code": null,
"e": 510,
"s": 504,
"text": "Code:"
},
{
"code": null,
"e": 512,
"s": 510,
"text": "R"
},
{
"code": "# create list and create 3 lists # inside this listlists = list(list1 = list(1, 2, 3, 4, 5), list2 = list('a', 'b', 'c', 'd', 'e'), list3 = list(2, 3, 4, 5, 6)) # convert list of lists into dataframe# by columnprint(as.data.frame(do.call(cbind, lists)))",
"e": 791,
"s": 512,
"text": null
},
{
"code": null,
"e": 799,
"s": 791,
"text": "Output:"
},
{
"code": null,
"e": 919,
"s": 799,
"text": " list1 list2 list3\n1 1 a 2\n2 2 b 3\n3 3 c 4\n4 4 d 5\n5 5 e 6"
},
{
"code": null,
"e": 1043,
"s": 919,
"text": "Example 2: R program to create two lists inside a list with numeric and character type and convert into dataframe by column"
},
{
"code": null,
"e": 1045,
"s": 1043,
"text": "R"
},
{
"code": "# create list and create 2 lists # inside this listlists = list(list1 = list(1, 2, 3, 4, 5), list2 = list('a', 'b', 'c', 'd', 'e')) # convert list of lists into# dataframe by columnprint(as.data.frame(do.call(cbind, lists)))",
"e": 1283,
"s": 1045,
"text": null
},
{
"code": null,
"e": 1291,
"s": 1283,
"text": "Output:"
},
{
"code": null,
"e": 1375,
"s": 1291,
"text": " list1 list2\n1 1 a\n2 2 b\n3 3 c\n4 4 d\n5 5 e"
},
{
"code": null,
"e": 1502,
"s": 1375,
"text": "Example 3: R program to create three lists inside a list with numeric and character type and convert into dataframe by column."
},
{
"code": null,
"e": 1550,
"s": 1502,
"text": "Syntax: as.data.frame(do.call(rbind,list_name))"
},
{
"code": null,
"e": 1669,
"s": 1550,
"text": "Parameters: Where rbind is to convert list to dataframe by row and list_name is the input list which is list of lists"
},
{
"code": null,
"e": 1671,
"s": 1669,
"text": "R"
},
{
"code": "# create list and create 3 lists # inside this listlists = list(list1 = list(1, 2, 3, 4, 5), list2 = list('a', 'b', 'c', 'd', 'e'), list3 = list(2, 3, 4, 5, 6)) # convert list of lists into dataframe # by rowprint(as.data.frame(do.call(rbind, lists)))",
"e": 1948,
"s": 1671,
"text": null
},
{
"code": null,
"e": 1956,
"s": 1948,
"text": "Output:"
},
{
"code": null,
"e": 2040,
"s": 1956,
"text": " V1 V2 V3 V4 V5\nlist1 1 2 3 4 5\nlist2 a b c d e\nlist3 2 3 4 5 6"
},
{
"code": null,
"e": 2047,
"s": 2040,
"text": "Picked"
},
{
"code": null,
"e": 2068,
"s": 2047,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 2080,
"s": 2068,
"text": "R-DataFrame"
},
{
"code": null,
"e": 2091,
"s": 2080,
"text": "R Language"
},
{
"code": null,
"e": 2102,
"s": 2091,
"text": "R Programs"
},
{
"code": null,
"e": 2200,
"s": 2102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2235,
"s": 2200,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2293,
"s": 2235,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2342,
"s": 2293,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2394,
"s": 2342,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2432,
"s": 2394,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2490,
"s": 2432,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2539,
"s": 2490,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2582,
"s": 2539,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2615,
"s": 2582,
"text": "Convert Matrix to Dataframe in R"
}
]
|
Loop Software Testing | 20 Jun, 2019
Loop Testing is a type of software testing type that is performed to validate the loops. It is one of the type of Control Structure Testing. Loop testing is a white box testing technique and is used to test loops in the program.
Objectives of Loop Testing:The objective of Loop Testing is:
To fix the infinite loop repetition problem.
To know the performance.
To identify the loop initialization problems.
To determine the uninitialized variables.
Types of Loop Testing:Loop testing is classified on the basis of the types of the loops:
Simple Loop Testing:Testing performed in a simple loop is known as Simple loop testing. Simple loop is basically a normal “for”, “while” or “do-while” in which a condition is given and loop runs and terminates according to true and false occurrence of the condition respectively. This type of testing is performed basically to test the condition of the loop whether the condition is sufficient to terminate loop after some point of time.Example:while(condition)
{
statement(s);
} Nested Loop Testing:Testing performed in a nested loop in known as Nested loop testing. Nested loop is basically one loop inside the another loop. In nested loop there can be finite number of loops inside a loop and there a nest is made. It may be either of any of three loops i.e., for, while or do-while.Example:while(condition 1)
{
while(condition 2)
{
statement(s);
}
} Concatenated Loop Testing:Testing performed in a concatenated loop is known as Concatenated loop testing. It is performed on the concatenated loops. Concatenated loops are loops after the loop. It is a series of loops. Difference between nested and concatenated is that in nested loop is inside the loop but here loop is after the loop.Example:while(condition 1)
{
statement(s);
}
while(condition 2)
{
statement(s);
} Unstructured Loop Testing:Testing performed in an unstructured loop is known as Unstructured loop testing. Unstructured loop is the combination of nested and concatenated loops. It is basically a group of loops that are in no order.Example:while()
{
for()
{}
while()
{}
}
Simple Loop Testing:Testing performed in a simple loop is known as Simple loop testing. Simple loop is basically a normal “for”, “while” or “do-while” in which a condition is given and loop runs and terminates according to true and false occurrence of the condition respectively. This type of testing is performed basically to test the condition of the loop whether the condition is sufficient to terminate loop after some point of time.Example:while(condition)
{
statement(s);
}
Example:
while(condition)
{
statement(s);
}
Nested Loop Testing:Testing performed in a nested loop in known as Nested loop testing. Nested loop is basically one loop inside the another loop. In nested loop there can be finite number of loops inside a loop and there a nest is made. It may be either of any of three loops i.e., for, while or do-while.Example:while(condition 1)
{
while(condition 2)
{
statement(s);
}
}
Example:
while(condition 1)
{
while(condition 2)
{
statement(s);
}
}
Concatenated Loop Testing:Testing performed in a concatenated loop is known as Concatenated loop testing. It is performed on the concatenated loops. Concatenated loops are loops after the loop. It is a series of loops. Difference between nested and concatenated is that in nested loop is inside the loop but here loop is after the loop.Example:while(condition 1)
{
statement(s);
}
while(condition 2)
{
statement(s);
}
Example:
while(condition 1)
{
statement(s);
}
while(condition 2)
{
statement(s);
}
Unstructured Loop Testing:Testing performed in an unstructured loop is known as Unstructured loop testing. Unstructured loop is the combination of nested and concatenated loops. It is basically a group of loops that are in no order.Example:while()
{
for()
{}
while()
{}
}
Example:
while()
{
for()
{}
while()
{}
}
Advantages of Loop Testing:The advantages of Loop testing are:
Loop testing limits the number of iterations of loop.
Loop testing ensures that program doesn’t go into infinite loop process.
Loop testing endures initialization of every used variable inside the loop.
Loop testing helps in identification of different problems inside the loop.
Loop testing helps in determination of capacity.
Disadvantages of Loop Testing:The disadvantages of Loop testing are:
Loop testing is mostly effective in bug detection in low-level software.
Loop testing is not useful in bug detection.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unit Testing | Software Testing
Software Engineering | Black box testing
System Testing
Software Engineering | Integration Testing
Equivalence Partitioning Method
What is DFD(Data Flow Diagram)?
Software Engineering | Calculation of Function Point (FP)
Software Development Life Cycle (SDLC)
Software Processes in Software Engineering
Software Measurement and Metrics | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2019"
},
{
"code": null,
"e": 257,
"s": 28,
"text": "Loop Testing is a type of software testing type that is performed to validate the loops. It is one of the type of Control Structure Testing. Loop testing is a white box testing technique and is used to test loops in the program."
},
{
"code": null,
"e": 318,
"s": 257,
"text": "Objectives of Loop Testing:The objective of Loop Testing is:"
},
{
"code": null,
"e": 363,
"s": 318,
"text": "To fix the infinite loop repetition problem."
},
{
"code": null,
"e": 388,
"s": 363,
"text": "To know the performance."
},
{
"code": null,
"e": 434,
"s": 388,
"text": "To identify the loop initialization problems."
},
{
"code": null,
"e": 476,
"s": 434,
"text": "To determine the uninitialized variables."
},
{
"code": null,
"e": 565,
"s": 476,
"text": "Types of Loop Testing:Loop testing is classified on the basis of the types of the loops:"
},
{
"code": null,
"e": 2167,
"s": 565,
"text": "Simple Loop Testing:Testing performed in a simple loop is known as Simple loop testing. Simple loop is basically a normal “for”, “while” or “do-while” in which a condition is given and loop runs and terminates according to true and false occurrence of the condition respectively. This type of testing is performed basically to test the condition of the loop whether the condition is sufficient to terminate loop after some point of time.Example:while(condition)\n {\n statement(s);\n } Nested Loop Testing:Testing performed in a nested loop in known as Nested loop testing. Nested loop is basically one loop inside the another loop. In nested loop there can be finite number of loops inside a loop and there a nest is made. It may be either of any of three loops i.e., for, while or do-while.Example:while(condition 1)\n {\n while(condition 2)\n {\n statement(s);\n }\n } Concatenated Loop Testing:Testing performed in a concatenated loop is known as Concatenated loop testing. It is performed on the concatenated loops. Concatenated loops are loops after the loop. It is a series of loops. Difference between nested and concatenated is that in nested loop is inside the loop but here loop is after the loop.Example:while(condition 1)\n {\n statement(s);\n }\n while(condition 2)\n {\n statement(s);\n } Unstructured Loop Testing:Testing performed in an unstructured loop is known as Unstructured loop testing. Unstructured loop is the combination of nested and concatenated loops. It is basically a group of loops that are in no order.Example:while()\n {\n for()\n {}\n while()\n {}\n } "
},
{
"code": null,
"e": 2655,
"s": 2167,
"text": "Simple Loop Testing:Testing performed in a simple loop is known as Simple loop testing. Simple loop is basically a normal “for”, “while” or “do-while” in which a condition is given and loop runs and terminates according to true and false occurrence of the condition respectively. This type of testing is performed basically to test the condition of the loop whether the condition is sufficient to terminate loop after some point of time.Example:while(condition)\n {\n statement(s);\n } "
},
{
"code": null,
"e": 2664,
"s": 2655,
"text": "Example:"
},
{
"code": null,
"e": 2707,
"s": 2664,
"text": "while(condition)\n {\n statement(s);\n } "
},
{
"code": null,
"e": 3102,
"s": 2707,
"text": "Nested Loop Testing:Testing performed in a nested loop in known as Nested loop testing. Nested loop is basically one loop inside the another loop. In nested loop there can be finite number of loops inside a loop and there a nest is made. It may be either of any of three loops i.e., for, while or do-while.Example:while(condition 1)\n {\n while(condition 2)\n {\n statement(s);\n }\n } "
},
{
"code": null,
"e": 3111,
"s": 3102,
"text": "Example:"
},
{
"code": null,
"e": 3192,
"s": 3111,
"text": "while(condition 1)\n {\n while(condition 2)\n {\n statement(s);\n }\n } "
},
{
"code": null,
"e": 3623,
"s": 3192,
"text": "Concatenated Loop Testing:Testing performed in a concatenated loop is known as Concatenated loop testing. It is performed on the concatenated loops. Concatenated loops are loops after the loop. It is a series of loops. Difference between nested and concatenated is that in nested loop is inside the loop but here loop is after the loop.Example:while(condition 1)\n {\n statement(s);\n }\n while(condition 2)\n {\n statement(s);\n } "
},
{
"code": null,
"e": 3632,
"s": 3623,
"text": "Example:"
},
{
"code": null,
"e": 3719,
"s": 3632,
"text": "while(condition 1)\n {\n statement(s);\n }\n while(condition 2)\n {\n statement(s);\n } "
},
{
"code": null,
"e": 4010,
"s": 3719,
"text": "Unstructured Loop Testing:Testing performed in an unstructured loop is known as Unstructured loop testing. Unstructured loop is the combination of nested and concatenated loops. It is basically a group of loops that are in no order.Example:while()\n {\n for()\n {}\n while()\n {}\n } "
},
{
"code": null,
"e": 4019,
"s": 4010,
"text": "Example:"
},
{
"code": null,
"e": 4070,
"s": 4019,
"text": "while()\n {\n for()\n {}\n while()\n {}\n } "
},
{
"code": null,
"e": 4133,
"s": 4070,
"text": "Advantages of Loop Testing:The advantages of Loop testing are:"
},
{
"code": null,
"e": 4187,
"s": 4133,
"text": "Loop testing limits the number of iterations of loop."
},
{
"code": null,
"e": 4260,
"s": 4187,
"text": "Loop testing ensures that program doesn’t go into infinite loop process."
},
{
"code": null,
"e": 4336,
"s": 4260,
"text": "Loop testing endures initialization of every used variable inside the loop."
},
{
"code": null,
"e": 4412,
"s": 4336,
"text": "Loop testing helps in identification of different problems inside the loop."
},
{
"code": null,
"e": 4461,
"s": 4412,
"text": "Loop testing helps in determination of capacity."
},
{
"code": null,
"e": 4530,
"s": 4461,
"text": "Disadvantages of Loop Testing:The disadvantages of Loop testing are:"
},
{
"code": null,
"e": 4603,
"s": 4530,
"text": "Loop testing is mostly effective in bug detection in low-level software."
},
{
"code": null,
"e": 4648,
"s": 4603,
"text": "Loop testing is not useful in bug detection."
},
{
"code": null,
"e": 4665,
"s": 4648,
"text": "Software Testing"
},
{
"code": null,
"e": 4686,
"s": 4665,
"text": "Software Engineering"
},
{
"code": null,
"e": 4784,
"s": 4686,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4816,
"s": 4784,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 4857,
"s": 4816,
"text": "Software Engineering | Black box testing"
},
{
"code": null,
"e": 4872,
"s": 4857,
"text": "System Testing"
},
{
"code": null,
"e": 4915,
"s": 4872,
"text": "Software Engineering | Integration Testing"
},
{
"code": null,
"e": 4947,
"s": 4915,
"text": "Equivalence Partitioning Method"
},
{
"code": null,
"e": 4979,
"s": 4947,
"text": "What is DFD(Data Flow Diagram)?"
},
{
"code": null,
"e": 5037,
"s": 4979,
"text": "Software Engineering | Calculation of Function Point (FP)"
},
{
"code": null,
"e": 5076,
"s": 5037,
"text": "Software Development Life Cycle (SDLC)"
},
{
"code": null,
"e": 5119,
"s": 5076,
"text": "Software Processes in Software Engineering"
}
]
|
Python | __import__() function | 28 Jan, 2022
While writing a code, there might be a need for some specific modules. So we import those modules by using a single line code in Python.
But what if the name of the module needed is known to us only during runtime? How can we import that module? One can use the Python’s inbuilt __import__() function. It helps to import modules in runtime also.
Syntax: __import__(name, globals, locals, fromlist, level)
Parameters:name : Name of the module to be importedglobals and locals : Interpret namesformlist : Objects or submodules to be imported (as a list)level : Specifies whether to use absolute or relative imports. Default is -1(absolute and relative).
Example #1 :
# importing numpy module# it is equivalent to "import numpy as np"np = __import__('numpy', globals(), locals(), [], 0) # array from numpya = np.array([1, 2, 3]) # prints the typeprint(type(a))
Output :
<class 'numpy.ndarray'>
Example #2 :Both the following statements has same meaning and does the same work.
# from numpy import complex as comp, array as arrnp = __import__('numpy', globals(), locals(), ['complex', 'array'], 0) comp = np.complexarr = np.array
Application :__import__() is not really necessary in everyday Python programming. Its direct use is rare. But sometimes, when there is a need of importing modules during the runtime, this function comes quite handy.
boscoitehooligan10
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Taking input in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 191,
"s": 54,
"text": "While writing a code, there might be a need for some specific modules. So we import those modules by using a single line code in Python."
},
{
"code": null,
"e": 400,
"s": 191,
"text": "But what if the name of the module needed is known to us only during runtime? How can we import that module? One can use the Python’s inbuilt __import__() function. It helps to import modules in runtime also."
},
{
"code": null,
"e": 459,
"s": 400,
"text": "Syntax: __import__(name, globals, locals, fromlist, level)"
},
{
"code": null,
"e": 706,
"s": 459,
"text": "Parameters:name : Name of the module to be importedglobals and locals : Interpret namesformlist : Objects or submodules to be imported (as a list)level : Specifies whether to use absolute or relative imports. Default is -1(absolute and relative)."
},
{
"code": null,
"e": 719,
"s": 706,
"text": "Example #1 :"
},
{
"code": "# importing numpy module# it is equivalent to \"import numpy as np\"np = __import__('numpy', globals(), locals(), [], 0) # array from numpya = np.array([1, 2, 3]) # prints the typeprint(type(a))",
"e": 914,
"s": 719,
"text": null
},
{
"code": null,
"e": 923,
"s": 914,
"text": "Output :"
},
{
"code": null,
"e": 947,
"s": 923,
"text": "<class 'numpy.ndarray'>"
},
{
"code": null,
"e": 1031,
"s": 947,
"text": " Example #2 :Both the following statements has same meaning and does the same work."
},
{
"code": "# from numpy import complex as comp, array as arrnp = __import__('numpy', globals(), locals(), ['complex', 'array'], 0) comp = np.complexarr = np.array",
"e": 1184,
"s": 1031,
"text": null
},
{
"code": null,
"e": 1401,
"s": 1184,
"text": " Application :__import__() is not really necessary in everyday Python programming. Its direct use is rare. But sometimes, when there is a need of importing modules during the runtime, this function comes quite handy."
},
{
"code": null,
"e": 1420,
"s": 1401,
"text": "boscoitehooligan10"
},
{
"code": null,
"e": 1437,
"s": 1420,
"text": "Python-Functions"
},
{
"code": null,
"e": 1444,
"s": 1437,
"text": "Python"
},
{
"code": null,
"e": 1542,
"s": 1444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1570,
"s": 1542,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1620,
"s": 1570,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1642,
"s": 1620,
"text": "Python map() function"
},
{
"code": null,
"e": 1686,
"s": 1642,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 1704,
"s": 1686,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1746,
"s": 1704,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1768,
"s": 1746,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Taking input in Python"
},
{
"code": null,
"e": 1826,
"s": 1791,
"text": "Read a file line by line in Python"
}
]
|
Iterators in C# | 04 Feb, 2021
An iterator is a method in C# which is used in an array or in collections like the list, etc. to retrieve elements one by one. Or in other words, we can say that an iterator is used to perform an iteration over the collections. This feature is introduced in C# 2.0. It uses the yield return statement to return the element from the collection at a time and it always remembers the current location of the iterator, so when the next iteration takes place it will return the next element of the given collection. If you want to stop the iteration you will use the yield break statement.
The return type of this method is IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>. Which means by using iterator compiler will automatically create IEnumerable or IEnumerator interface for you there is no need to implement IEnumerable or IEnumerator interface in your class for using a foreach loop. When the compiler identifies an iterator in your class it will automatically create the current, MoveNext and dispose of the method of IEnumerable or IEnumerator interface.
Important Points:
Iterator can be used as a method, or as a property.
Iterator method is also known as get accessor.
You can use iterator as a method or get accessor.
You cannot use iterator in an events instance constructor, static constructor, or static finalizer.
An iterator method does not contain ref, or out parameters.
Here, yield is not reserved word, but when you use yield with return or break statement, then yield have special meaning.
You are allowed to use multiple yield statements.
It is generally used with generic or non-generic collections.
When you are working with iterator it is necessary to add System.Collections.Generic namespace in your program.
Example 1:
C#
// C# program to illustrate the concept// of iterator using list collectionusing System;using System.Collections.Generic; class GFG { public static IEnumerable<string> GetMyList() { // Creating and adding elements in list List<string> my_list = new List<string>() { "Cat", "Goat", "Dog", "Cow" }; // Iterating the elements of my_list foreach(var items in my_list) { // Returning the element after every iteration yield return items; } } // Main Method static public void Main() { // Storing the elements of GetMyList IEnumerable<string> my_slist = GetMyList(); // Display the elements return from iteration foreach(var i in my_slist) { Console.WriteLine(i); } }}
Cat
Goat
Dog
Cow
Example 2:
C#
// C# program to illustrate the concept// of iterator using arrayusing System;using System.Collections.Generic; class GFG { public static IEnumerable<string> GetMyArray() { string[] myarray = new string[] {"Geeks", "geeks123", "1234geeks"}; // Iterating the elements of myarray foreach(var items in myarray) { // Returning the element after every iteration yield return items.ToString(); } } // Main Method static public void Main() { // Storing the elements of GetMyArray IEnumerable<string> myitems = GetMyArray(); // Display the elements return from iteration foreach(var i in myitems) { Console.WriteLine(i); } }}
Geeks
geeks123
1234geeks
debashish saha
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
Extension Method in C#
C# | Replace() Method | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Feb, 2021"
},
{
"code": null,
"e": 640,
"s": 54,
"text": "An iterator is a method in C# which is used in an array or in collections like the list, etc. to retrieve elements one by one. Or in other words, we can say that an iterator is used to perform an iteration over the collections. This feature is introduced in C# 2.0. It uses the yield return statement to return the element from the collection at a time and it always remembers the current location of the iterator, so when the next iteration takes place it will return the next element of the given collection. If you want to stop the iteration you will use the yield break statement. "
},
{
"code": null,
"e": 1125,
"s": 640,
"text": "The return type of this method is IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>. Which means by using iterator compiler will automatically create IEnumerable or IEnumerator interface for you there is no need to implement IEnumerable or IEnumerator interface in your class for using a foreach loop. When the compiler identifies an iterator in your class it will automatically create the current, MoveNext and dispose of the method of IEnumerable or IEnumerator interface."
},
{
"code": null,
"e": 1144,
"s": 1125,
"text": "Important Points: "
},
{
"code": null,
"e": 1196,
"s": 1144,
"text": "Iterator can be used as a method, or as a property."
},
{
"code": null,
"e": 1243,
"s": 1196,
"text": "Iterator method is also known as get accessor."
},
{
"code": null,
"e": 1293,
"s": 1243,
"text": "You can use iterator as a method or get accessor."
},
{
"code": null,
"e": 1393,
"s": 1293,
"text": "You cannot use iterator in an events instance constructor, static constructor, or static finalizer."
},
{
"code": null,
"e": 1453,
"s": 1393,
"text": "An iterator method does not contain ref, or out parameters."
},
{
"code": null,
"e": 1575,
"s": 1453,
"text": "Here, yield is not reserved word, but when you use yield with return or break statement, then yield have special meaning."
},
{
"code": null,
"e": 1625,
"s": 1575,
"text": "You are allowed to use multiple yield statements."
},
{
"code": null,
"e": 1687,
"s": 1625,
"text": "It is generally used with generic or non-generic collections."
},
{
"code": null,
"e": 1799,
"s": 1687,
"text": "When you are working with iterator it is necessary to add System.Collections.Generic namespace in your program."
},
{
"code": null,
"e": 1810,
"s": 1799,
"text": "Example 1:"
},
{
"code": null,
"e": 1813,
"s": 1810,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept// of iterator using list collectionusing System;using System.Collections.Generic; class GFG { public static IEnumerable<string> GetMyList() { // Creating and adding elements in list List<string> my_list = new List<string>() { \"Cat\", \"Goat\", \"Dog\", \"Cow\" }; // Iterating the elements of my_list foreach(var items in my_list) { // Returning the element after every iteration yield return items; } } // Main Method static public void Main() { // Storing the elements of GetMyList IEnumerable<string> my_slist = GetMyList(); // Display the elements return from iteration foreach(var i in my_slist) { Console.WriteLine(i); } }}",
"e": 2648,
"s": 1813,
"text": null
},
{
"code": null,
"e": 2665,
"s": 2648,
"text": "Cat\nGoat\nDog\nCow"
},
{
"code": null,
"e": 2678,
"s": 2667,
"text": "Example 2:"
},
{
"code": null,
"e": 2681,
"s": 2678,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept// of iterator using arrayusing System;using System.Collections.Generic; class GFG { public static IEnumerable<string> GetMyArray() { string[] myarray = new string[] {\"Geeks\", \"geeks123\", \"1234geeks\"}; // Iterating the elements of myarray foreach(var items in myarray) { // Returning the element after every iteration yield return items.ToString(); } } // Main Method static public void Main() { // Storing the elements of GetMyArray IEnumerable<string> myitems = GetMyArray(); // Display the elements return from iteration foreach(var i in myitems) { Console.WriteLine(i); } }}",
"e": 3459,
"s": 2681,
"text": null
},
{
"code": null,
"e": 3484,
"s": 3459,
"text": "Geeks\ngeeks123\n1234geeks"
},
{
"code": null,
"e": 3501,
"s": 3486,
"text": "debashish saha"
},
{
"code": null,
"e": 3504,
"s": 3501,
"text": "C#"
},
{
"code": null,
"e": 3602,
"s": 3504,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3633,
"s": 3602,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 3648,
"s": 3633,
"text": "C# | Delegates"
},
{
"code": null,
"e": 3691,
"s": 3648,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 3740,
"s": 3691,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 3756,
"s": 3740,
"text": "C# | Data Types"
},
{
"code": null,
"e": 3796,
"s": 3756,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 3814,
"s": 3796,
"text": "C# | Constructors"
},
{
"code": null,
"e": 3836,
"s": 3814,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 3859,
"s": 3836,
"text": "Extension Method in C#"
}
]
|
Merging PDFs using Java - GeeksforGeeks | 08 Dec, 2020
Merging multiple PDF documents into a single PDF document is done using the PDFMergerUtility class. This class will take a list of PDF documents and merge them, the result will be saved to the new document. The prerequisite of this topic is that you have already installed apache library
Follow these steps to merge multiple PDF documents:
First we have to instantiate the PDFMergerUtility class.Second we have to set the destination file using the setDestinationFileName() method.Now we have to set the source files using the addSource() method.Final step we have to merge the documents using the mergeDocuments() method of the PDFMergerUtility class.
First we have to instantiate the PDFMergerUtility class.
Second we have to set the destination file using the setDestinationFileName() method.
Now we have to set the source files using the addSource() method.
Final step we have to merge the documents using the mergeDocuments() method of the PDFMergerUtility class.
Example:
Input : PDF1 = Alice.pdf, PDF2 = Bob.pdf
Output: newMerged.pdf // merged pdf of pdf1 and pdf2
Implementation:
Java
// Merging multiple pdf documents here import org.apache.pdfbox.multipdf.PDFMergerUtility;import org.apache.pdfbox.pdmodel.PDDocument; import java.io.File;import java.io.IOException; public class GFG { public static void main(String[] args) throws IOException { // loading all the pdf files we wish to merge File file1 = new File( "/Users/piyushkumar/Desktop/Merging Pdfs/file1.pdf"); File file2 = new File( "/Users/piyushkumar/Desktop/Merging Pdfs/file2.pdf"); // Instantiating PDFMergerUtility class PDFMergerUtility obj = new PDFMergerUtility(); // Setting the destination file path obj.setDestinationFileName( "/Users/piyushkumar/Desktop/Merging Pdfs/newMerged.pdf"); // Add all source files, to be merged obj.addSource(file1); obj.addSource(file2); // Merging documents obj.mergeDocuments(); System.out.println( "PDF Documents merged to a single file"); }}
Before the execution of the code :
After the execution of the code :
If you check the specified path, you will see that a PDF document named newMerged.pdf has been generated which contains the pages of both the original documents.
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 25867,
"s": 25839,
"text": "\n08 Dec, 2020"
},
{
"code": null,
"e": 26156,
"s": 25867,
"text": "Merging multiple PDF documents into a single PDF document is done using the PDFMergerUtility class. This class will take a list of PDF documents and merge them, the result will be saved to the new document. The prerequisite of this topic is that you have already installed apache library "
},
{
"code": null,
"e": 26208,
"s": 26156,
"text": "Follow these steps to merge multiple PDF documents:"
},
{
"code": null,
"e": 26521,
"s": 26208,
"text": "First we have to instantiate the PDFMergerUtility class.Second we have to set the destination file using the setDestinationFileName() method.Now we have to set the source files using the addSource() method.Final step we have to merge the documents using the mergeDocuments() method of the PDFMergerUtility class."
},
{
"code": null,
"e": 26578,
"s": 26521,
"text": "First we have to instantiate the PDFMergerUtility class."
},
{
"code": null,
"e": 26664,
"s": 26578,
"text": "Second we have to set the destination file using the setDestinationFileName() method."
},
{
"code": null,
"e": 26730,
"s": 26664,
"text": "Now we have to set the source files using the addSource() method."
},
{
"code": null,
"e": 26837,
"s": 26730,
"text": "Final step we have to merge the documents using the mergeDocuments() method of the PDFMergerUtility class."
},
{
"code": null,
"e": 26846,
"s": 26837,
"text": "Example:"
},
{
"code": null,
"e": 26941,
"s": 26846,
"text": "Input : PDF1 = Alice.pdf, PDF2 = Bob.pdf\nOutput: newMerged.pdf // merged pdf of pdf1 and pdf2 "
},
{
"code": null,
"e": 26957,
"s": 26941,
"text": "Implementation:"
},
{
"code": null,
"e": 26962,
"s": 26957,
"text": "Java"
},
{
"code": "// Merging multiple pdf documents here import org.apache.pdfbox.multipdf.PDFMergerUtility;import org.apache.pdfbox.pdmodel.PDDocument; import java.io.File;import java.io.IOException; public class GFG { public static void main(String[] args) throws IOException { // loading all the pdf files we wish to merge File file1 = new File( \"/Users/piyushkumar/Desktop/Merging Pdfs/file1.pdf\"); File file2 = new File( \"/Users/piyushkumar/Desktop/Merging Pdfs/file2.pdf\"); // Instantiating PDFMergerUtility class PDFMergerUtility obj = new PDFMergerUtility(); // Setting the destination file path obj.setDestinationFileName( \"/Users/piyushkumar/Desktop/Merging Pdfs/newMerged.pdf\"); // Add all source files, to be merged obj.addSource(file1); obj.addSource(file2); // Merging documents obj.mergeDocuments(); System.out.println( \"PDF Documents merged to a single file\"); }}",
"e": 28002,
"s": 26962,
"text": null
},
{
"code": null,
"e": 28039,
"s": 28004,
"text": "Before the execution of the code :"
},
{
"code": null,
"e": 28075,
"s": 28041,
"text": "After the execution of the code :"
},
{
"code": null,
"e": 28237,
"s": 28075,
"text": "If you check the specified path, you will see that a PDF document named newMerged.pdf has been generated which contains the pages of both the original documents."
},
{
"code": null,
"e": 28244,
"s": 28237,
"text": "Picked"
},
{
"code": null,
"e": 28249,
"s": 28244,
"text": "Java"
},
{
"code": null,
"e": 28263,
"s": 28249,
"text": "Java Programs"
},
{
"code": null,
"e": 28268,
"s": 28263,
"text": "Java"
},
{
"code": null,
"e": 28366,
"s": 28268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28417,
"s": 28366,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28447,
"s": 28417,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28462,
"s": 28447,
"text": "Stream In Java"
},
{
"code": null,
"e": 28481,
"s": 28462,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28512,
"s": 28481,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28540,
"s": 28512,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 28584,
"s": 28540,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 28610,
"s": 28584,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28644,
"s": 28610,
"text": "Convert Double to Integer in Java"
}
]
|
upper_bound in C++ - GeeksforGeeks | 28 Nov, 2018
upper_bound() is a standard library function in C++ defined in the header . It returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found. The elements in the range shall already be sorted or at least partitioned with respect to val.
Template :
Syntax 1:ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val);Syntax 2:ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);
first, last: The range used is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
val: Value of the upper bound to search for in the range.
comp: Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, and the second, always val), and returns a value convertible to bool. The function shall not modify any of its arguments. This can either be a function pointeror a function object.
Return type : An iterator to the upper bound of val in the range. If all the element in the range compare less than val, the function returns last.
Examples :
Input : 10 20 30 30 40 50
Output : upper_bound for element 30 is at index 4
Input : 10 20 30 40 50
Output : upper_bound for element 45 is at index 4
Input : 10 20 30 40 50
Output : upper_bound for element 60 is at index 5
Below are some C++ programs to illustrate the use of std::upper_bound :
// CPP program to illustrate using // std :: upper_bound with vectors#include <bits/stdc++.h> // Driver codeint main(){ std::vector<int> v{ 10, 20, 30, 40, 50 }; // Print vector std::cout << "Vector contains :"; for (int i = 0; i < v.size(); i++) std::cout << " " << v[i]; std::cout << "\n"; std::vector<int>::iterator upper1, upper2; // std :: upper_bound upper1 = std::upper_bound(v.begin(), v.end(), 35); upper2 = std::upper_bound(v.begin(), v.end(), 45); std::cout << "\nupper_bound for element 35 is at position : " << (upper1 - v.begin()); std::cout << "\nupper_bound for element 45 is at position : " << (upper2 - v.begin()); return 0;}
Output:
Vector contains : 10 20 30 40 50
upper_bound for element 35 is at position : 3
upper_bound for element 45 is at position : 4
// CPP program to illustrate using // std :: upper_bound with arrays#include <bits/stdc++.h>using namespace std; // Main Functionint main(){ int arr[] = { 10, 20, 30, 40, 50 }; // Print elements of array cout << "Array contains :"; for (int i = 0; i < 5; i++) cout << " " << arr[i]; cout << "\n"; // using upper_bound int upper1 = upper_bound(arr, arr+5, 35) - arr; int upper2 = upper_bound(arr, arr+5, 45) - arr; cout << "\nupper_bound for element 35 is at position : " << (upper1); cout << "\nupper_bound for element 45 is at position : " << (upper2); return 0;}
Output:
Array contains : 10 20 30 40 50
upper_bound for element 35 is at position : 3
upper_bound for element 45 is at position : 4
Time Complexity : The number of comparisons performed is logarithmic in the distance between first and last. i.e, (at most log2(last – first) + O(1) comparisons).
Important Points
std::upper_bound() returns an iterator to the upper bound of the value passed to it.
std::upper_bound() works only with sorted sequences. i.e. vector with sorted elements or array with sorted elements.
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Copy Constructor in C++ | [
{
"code": null,
"e": 25821,
"s": 25793,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 26137,
"s": 25821,
"text": "upper_bound() is a standard library function in C++ defined in the header . It returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found. The elements in the range shall already be sorted or at least partitioned with respect to val."
},
{
"code": null,
"e": 26148,
"s": 26137,
"text": "Template :"
},
{
"code": null,
"e": 26357,
"s": 26148,
"text": "Syntax 1:ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val);Syntax 2:ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);"
},
{
"code": null,
"e": 26535,
"s": 26357,
"text": "first, last: The range used is [first, last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last."
},
{
"code": null,
"e": 26593,
"s": 26535,
"text": "val: Value of the upper bound to search for in the range."
},
{
"code": null,
"e": 26874,
"s": 26593,
"text": "comp: Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, and the second, always val), and returns a value convertible to bool. The function shall not modify any of its arguments. This can either be a function pointeror a function object."
},
{
"code": null,
"e": 27022,
"s": 26874,
"text": "Return type : An iterator to the upper bound of val in the range. If all the element in the range compare less than val, the function returns last."
},
{
"code": null,
"e": 27033,
"s": 27022,
"text": "Examples :"
},
{
"code": null,
"e": 27258,
"s": 27033,
"text": "Input : 10 20 30 30 40 50\nOutput : upper_bound for element 30 is at index 4\n\nInput : 10 20 30 40 50\nOutput : upper_bound for element 45 is at index 4\n\nInput : 10 20 30 40 50\nOutput : upper_bound for element 60 is at index 5\n"
},
{
"code": null,
"e": 27330,
"s": 27258,
"text": "Below are some C++ programs to illustrate the use of std::upper_bound :"
},
{
"code": "// CPP program to illustrate using // std :: upper_bound with vectors#include <bits/stdc++.h> // Driver codeint main(){ std::vector<int> v{ 10, 20, 30, 40, 50 }; // Print vector std::cout << \"Vector contains :\"; for (int i = 0; i < v.size(); i++) std::cout << \" \" << v[i]; std::cout << \"\\n\"; std::vector<int>::iterator upper1, upper2; // std :: upper_bound upper1 = std::upper_bound(v.begin(), v.end(), 35); upper2 = std::upper_bound(v.begin(), v.end(), 45); std::cout << \"\\nupper_bound for element 35 is at position : \" << (upper1 - v.begin()); std::cout << \"\\nupper_bound for element 45 is at position : \" << (upper2 - v.begin()); return 0;}",
"e": 28055,
"s": 27330,
"text": null
},
{
"code": null,
"e": 28063,
"s": 28055,
"text": "Output:"
},
{
"code": null,
"e": 28189,
"s": 28063,
"text": "Vector contains : 10 20 30 40 50\nupper_bound for element 35 is at position : 3\nupper_bound for element 45 is at position : 4\n"
},
{
"code": "// CPP program to illustrate using // std :: upper_bound with arrays#include <bits/stdc++.h>using namespace std; // Main Functionint main(){ int arr[] = { 10, 20, 30, 40, 50 }; // Print elements of array cout << \"Array contains :\"; for (int i = 0; i < 5; i++) cout << \" \" << arr[i]; cout << \"\\n\"; // using upper_bound int upper1 = upper_bound(arr, arr+5, 35) - arr; int upper2 = upper_bound(arr, arr+5, 45) - arr; cout << \"\\nupper_bound for element 35 is at position : \" << (upper1); cout << \"\\nupper_bound for element 45 is at position : \" << (upper2); return 0;}",
"e": 28830,
"s": 28189,
"text": null
},
{
"code": null,
"e": 28838,
"s": 28830,
"text": "Output:"
},
{
"code": null,
"e": 28963,
"s": 28838,
"text": "Array contains : 10 20 30 40 50\nupper_bound for element 35 is at position : 3\nupper_bound for element 45 is at position : 4\n"
},
{
"code": null,
"e": 29126,
"s": 28963,
"text": "Time Complexity : The number of comparisons performed is logarithmic in the distance between first and last. i.e, (at most log2(last – first) + O(1) comparisons)."
},
{
"code": null,
"e": 29143,
"s": 29126,
"text": "Important Points"
},
{
"code": null,
"e": 29228,
"s": 29143,
"text": "std::upper_bound() returns an iterator to the upper bound of the value passed to it."
},
{
"code": null,
"e": 29345,
"s": 29228,
"text": "std::upper_bound() works only with sorted sequences. i.e. vector with sorted elements or array with sorted elements."
},
{
"code": null,
"e": 29648,
"s": 29345,
"text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29773,
"s": 29648,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29795,
"s": 29773,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 29799,
"s": 29795,
"text": "STL"
},
{
"code": null,
"e": 29803,
"s": 29799,
"text": "C++"
},
{
"code": null,
"e": 29807,
"s": 29803,
"text": "STL"
},
{
"code": null,
"e": 29811,
"s": 29807,
"text": "CPP"
},
{
"code": null,
"e": 29909,
"s": 29811,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29928,
"s": 29909,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29952,
"s": 29928,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 29979,
"s": 29952,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 30003,
"s": 29979,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 30034,
"s": 30003,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 30054,
"s": 30034,
"text": "Constructors in C++"
},
{
"code": null,
"e": 30082,
"s": 30054,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30110,
"s": 30082,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 30145,
"s": 30110,
"text": "Object Oriented Programming in C++"
}
]
|
Argument Modes in PL/SQL - GeeksforGeeks | 23 Oct, 2020
Argument modes are basically used to describe the behavior of the formal parameters. There are three types of argument modes which are used in the sub-program, which are as follows –
IN ModeOUT ModeIN OUT Mode
IN Mode
OUT Mode
IN OUT Mode
Representation of how modes interact with calling environment
IN Mode :It is the default argument mode in subprogram. This mode passes a constant value from the calling environment into the subprogram.Example –The following example illustrates the working of IN Mode argument –SQL> CREATE OR REPLACE PROCEDURE PR1(X IN NUMBER, Y IN NUMBER)
S NUMBER;
BEGIN
S:=X+Y;
DBMS_OUTPUT.PUT_LINE('SUM IS : '||S);
END PR1;Output –Procedure created.SQL> DECLARE
N1 NUMBER:=10;
N2 NUMBER:=20;
BEGIN
PR1(N1, N2);
END;Output –SUM IS : 30
PL/SQL procedure successfully completed.
SQL>
Example –The following example illustrates the working of IN Mode argument –
SQL> CREATE OR REPLACE PROCEDURE PR1(X IN NUMBER, Y IN NUMBER)
S NUMBER;
BEGIN
S:=X+Y;
DBMS_OUTPUT.PUT_LINE('SUM IS : '||S);
END PR1;
Output –
Procedure created.
SQL> DECLARE
N1 NUMBER:=10;
N2 NUMBER:=20;
BEGIN
PR1(N1, N2);
END;
Output –
SUM IS : 30
PL/SQL procedure successfully completed.
SQL>
OUT Mode :This mode passes a value from the subprogram to the calling environment.Example –The following example illustrates the working of OUT Mode argument –SQL> CREATE OR REPLACE PROCEDURE PR2(2 OUT NUMBER) AS
X NUMBER:=11;
Y NUMBER:=22;
BEGIN
Z:=X+Y;
END;Output –Procedure created.SQL> DECLARE
R NUMBER;
BEGIN
PR2(R);
DBMS_OUTPUT.PUT_LINE('RESULT IS: '||R);
END;Output –RESULT IS : 33
PL/SQL procedure successfully completed.
SQL>
Example –The following example illustrates the working of OUT Mode argument –
SQL> CREATE OR REPLACE PROCEDURE PR2(2 OUT NUMBER) AS
X NUMBER:=11;
Y NUMBER:=22;
BEGIN
Z:=X+Y;
END;
Output –
Procedure created.
SQL> DECLARE
R NUMBER;
BEGIN
PR2(R);
DBMS_OUTPUT.PUT_LINE('RESULT IS: '||R);
END;
Output –
RESULT IS : 33
PL/SQL procedure successfully completed.
SQL>
IN OUT Mode :This mode is a mixture of both IN n=and OUT mode. Just like IN mode it passes a value from the calling environment in subprogram and like a OUT mode it possibly pass different value from the subprogram back to the calling environment using the same parameter.Example –The following example illustrates the working of OUT Mode argument –SQL> CREATE OR REPLACE PROCEDURE PR3(2 OUT NUMBER) AS
A NUMBER:=11;
BEGIN
B:=A+B;
END;Output –Procedure created.SQL> DECLARE
R NUMBER:=22;
BEGIN
PR3(R);
DBMS_OUTPUT.PUT_LINE('RESULT IS: '||R);
END;Output –RESULT IS : 33
PL/SQL procedure successfully completed.
SQL>
Example –The following example illustrates the working of OUT Mode argument –
SQL> CREATE OR REPLACE PROCEDURE PR3(2 OUT NUMBER) AS
A NUMBER:=11;
BEGIN
B:=A+B;
END;
Output –
Procedure created.
SQL> DECLARE
R NUMBER:=22;
BEGIN
PR3(R);
DBMS_OUTPUT.PUT_LINE('RESULT IS: '||R);
END;
Output –
RESULT IS : 33
PL/SQL procedure successfully completed.
SQL>
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
SQL Trigger | Student Database
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
SQL | Views
Difference between DDL and DML in DBMS
SQL | GROUP BY
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function | [
{
"code": null,
"e": 25693,
"s": 25665,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 25876,
"s": 25693,
"text": "Argument modes are basically used to describe the behavior of the formal parameters. There are three types of argument modes which are used in the sub-program, which are as follows –"
},
{
"code": null,
"e": 25903,
"s": 25876,
"text": "IN ModeOUT ModeIN OUT Mode"
},
{
"code": null,
"e": 25911,
"s": 25903,
"text": "IN Mode"
},
{
"code": null,
"e": 25920,
"s": 25911,
"text": "OUT Mode"
},
{
"code": null,
"e": 25932,
"s": 25920,
"text": "IN OUT Mode"
},
{
"code": null,
"e": 25994,
"s": 25932,
"text": "Representation of how modes interact with calling environment"
},
{
"code": null,
"e": 26500,
"s": 25994,
"text": "IN Mode :It is the default argument mode in subprogram. This mode passes a constant value from the calling environment into the subprogram.Example –The following example illustrates the working of IN Mode argument –SQL> CREATE OR REPLACE PROCEDURE PR1(X IN NUMBER, Y IN NUMBER)\nS NUMBER;\nBEGIN\nS:=X+Y;\nDBMS_OUTPUT.PUT_LINE('SUM IS : '||S);\nEND PR1;Output –Procedure created.SQL> DECLARE\nN1 NUMBER:=10;\nN2 NUMBER:=20;\nBEGIN\nPR1(N1, N2);\nEND;Output –SUM IS : 30\nPL/SQL procedure successfully completed.\nSQL>"
},
{
"code": null,
"e": 26577,
"s": 26500,
"text": "Example –The following example illustrates the working of IN Mode argument –"
},
{
"code": null,
"e": 26711,
"s": 26577,
"text": "SQL> CREATE OR REPLACE PROCEDURE PR1(X IN NUMBER, Y IN NUMBER)\nS NUMBER;\nBEGIN\nS:=X+Y;\nDBMS_OUTPUT.PUT_LINE('SUM IS : '||S);\nEND PR1;"
},
{
"code": null,
"e": 26720,
"s": 26711,
"text": "Output –"
},
{
"code": null,
"e": 26739,
"s": 26720,
"text": "Procedure created."
},
{
"code": null,
"e": 26806,
"s": 26739,
"text": "SQL> DECLARE\nN1 NUMBER:=10;\nN2 NUMBER:=20;\nBEGIN\nPR1(N1, N2);\nEND;"
},
{
"code": null,
"e": 26815,
"s": 26806,
"text": "Output –"
},
{
"code": null,
"e": 26873,
"s": 26815,
"text": "SUM IS : 30\nPL/SQL procedure successfully completed.\nSQL>"
},
{
"code": null,
"e": 27308,
"s": 26873,
"text": "OUT Mode :This mode passes a value from the subprogram to the calling environment.Example –The following example illustrates the working of OUT Mode argument –SQL> CREATE OR REPLACE PROCEDURE PR2(2 OUT NUMBER) AS\nX NUMBER:=11;\nY NUMBER:=22;\nBEGIN\nZ:=X+Y;\nEND;Output –Procedure created.SQL> DECLARE\nR NUMBER;\nBEGIN\nPR2(R);\nDBMS_OUTPUT.PUT_LINE('RESULT IS: '||R);\nEND;Output –RESULT IS : 33\nPL/SQL procedure successfully completed.\nSQL>"
},
{
"code": null,
"e": 27386,
"s": 27308,
"text": "Example –The following example illustrates the working of OUT Mode argument –"
},
{
"code": null,
"e": 27487,
"s": 27386,
"text": "SQL> CREATE OR REPLACE PROCEDURE PR2(2 OUT NUMBER) AS\nX NUMBER:=11;\nY NUMBER:=22;\nBEGIN\nZ:=X+Y;\nEND;"
},
{
"code": null,
"e": 27496,
"s": 27487,
"text": "Output –"
},
{
"code": null,
"e": 27515,
"s": 27496,
"text": "Procedure created."
},
{
"code": null,
"e": 27597,
"s": 27515,
"text": "SQL> DECLARE\nR NUMBER;\nBEGIN\nPR2(R);\nDBMS_OUTPUT.PUT_LINE('RESULT IS: '||R);\nEND;"
},
{
"code": null,
"e": 27606,
"s": 27597,
"text": "Output –"
},
{
"code": null,
"e": 27667,
"s": 27606,
"text": "RESULT IS : 33\nPL/SQL procedure successfully completed.\nSQL>"
},
{
"code": null,
"e": 28282,
"s": 27667,
"text": "IN OUT Mode :This mode is a mixture of both IN n=and OUT mode. Just like IN mode it passes a value from the calling environment in subprogram and like a OUT mode it possibly pass different value from the subprogram back to the calling environment using the same parameter.Example –The following example illustrates the working of OUT Mode argument –SQL> CREATE OR REPLACE PROCEDURE PR3(2 OUT NUMBER) AS\nA NUMBER:=11;\nBEGIN\nB:=A+B;\nEND;Output –Procedure created.SQL> DECLARE\nR NUMBER:=22;\nBEGIN\nPR3(R);\nDBMS_OUTPUT.PUT_LINE('RESULT IS: '||R);\nEND;Output –RESULT IS : 33\nPL/SQL procedure successfully completed.\nSQL>"
},
{
"code": null,
"e": 28360,
"s": 28282,
"text": "Example –The following example illustrates the working of OUT Mode argument –"
},
{
"code": null,
"e": 28447,
"s": 28360,
"text": "SQL> CREATE OR REPLACE PROCEDURE PR3(2 OUT NUMBER) AS\nA NUMBER:=11;\nBEGIN\nB:=A+B;\nEND;"
},
{
"code": null,
"e": 28456,
"s": 28447,
"text": "Output –"
},
{
"code": null,
"e": 28475,
"s": 28456,
"text": "Procedure created."
},
{
"code": null,
"e": 28561,
"s": 28475,
"text": "SQL> DECLARE\nR NUMBER:=22;\nBEGIN\nPR3(R);\nDBMS_OUTPUT.PUT_LINE('RESULT IS: '||R);\nEND;"
},
{
"code": null,
"e": 28570,
"s": 28561,
"text": "Output –"
},
{
"code": null,
"e": 28631,
"s": 28570,
"text": "RESULT IS : 33\nPL/SQL procedure successfully completed.\nSQL>"
},
{
"code": null,
"e": 28640,
"s": 28631,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 28644,
"s": 28640,
"text": "SQL"
},
{
"code": null,
"e": 28648,
"s": 28644,
"text": "SQL"
},
{
"code": null,
"e": 28746,
"s": 28648,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28770,
"s": 28746,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 28801,
"s": 28770,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 28812,
"s": 28801,
"text": "CTE in SQL"
},
{
"code": null,
"e": 28878,
"s": 28812,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28911,
"s": 28878,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 28923,
"s": 28911,
"text": "SQL | Views"
},
{
"code": null,
"e": 28962,
"s": 28923,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 28977,
"s": 28962,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 29022,
"s": 28977,
"text": "Difference between DELETE, DROP and TRUNCATE"
}
]
|
Tensorflow.js tf.split() Function - GeeksforGeeks | 10 May, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js.
The tf.split() function is used to split a tf.tensors into sub tensors.
Syntax:
tf.split (x, numOrSizeSplits, axis?)
Parameters:
x: The input tensor to split.
numOrSizeSplits: It can be a number indicating the number of splits or can be the array in which sizes are provided for each output tensor
axis: It is an axis of the dimension along which to split.
Return Value: It returns tf.Tensor[].
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" const x = tf.tensor2d([10, 20, 50, 60, 30, 40, 70, 80], [2, 4]); // Split the tensorconst [gfg, geeks] = tf.split(x, 2, 1); gfg.print(); geeks.print();
Output:
Tensor
[[10, 20],
[30, 40]]
Tensor
[[50, 60],
[70, 80]]
Example 2: In this example, making the split with axis as the 2nd parameter as an array.
Javascript
const x = tf.tensor2d([10, 30, 50, 70, 20, 40, 60, 80], [2, 4]); const [gfg, gfg1, geeks] = tf.split(x, [1, 2, 1], 1); gfg.print(); gfg1.print(); geeks.print();
Output:
Tensor
[[10],
[20]]
Tensor
[[30, 50],
[40, 60]]
Tensor
[[70],
[80]]
Reference: https://js.tensorflow.org/api/latest/#split
Picked
Tensorflow.js
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": "\n10 May, 2021"
},
{
"code": null,
"e": 26838,
"s": 26545,
"text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js."
},
{
"code": null,
"e": 26910,
"s": 26838,
"text": "The tf.split() function is used to split a tf.tensors into sub tensors."
},
{
"code": null,
"e": 26918,
"s": 26910,
"text": "Syntax:"
},
{
"code": null,
"e": 26955,
"s": 26918,
"text": "tf.split (x, numOrSizeSplits, axis?)"
},
{
"code": null,
"e": 26967,
"s": 26955,
"text": "Parameters:"
},
{
"code": null,
"e": 26997,
"s": 26967,
"text": "x: The input tensor to split."
},
{
"code": null,
"e": 27136,
"s": 26997,
"text": "numOrSizeSplits: It can be a number indicating the number of splits or can be the array in which sizes are provided for each output tensor"
},
{
"code": null,
"e": 27195,
"s": 27136,
"text": "axis: It is an axis of the dimension along which to split."
},
{
"code": null,
"e": 27233,
"s": 27195,
"text": "Return Value: It returns tf.Tensor[]."
},
{
"code": null,
"e": 27244,
"s": 27233,
"text": "Example 1:"
},
{
"code": null,
"e": 27255,
"s": 27244,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" const x = tf.tensor2d([10, 20, 50, 60, 30, 40, 70, 80], [2, 4]); // Split the tensorconst [gfg, geeks] = tf.split(x, 2, 1); gfg.print(); geeks.print();",
"e": 27510,
"s": 27255,
"text": null
},
{
"code": null,
"e": 27518,
"s": 27510,
"text": "Output:"
},
{
"code": null,
"e": 27592,
"s": 27518,
"text": "Tensor\n [[10, 20],\n [30, 40]]\nTensor\n [[50, 60],\n [70, 80]]"
},
{
"code": null,
"e": 27681,
"s": 27592,
"text": "Example 2: In this example, making the split with axis as the 2nd parameter as an array."
},
{
"code": null,
"e": 27692,
"s": 27681,
"text": "Javascript"
},
{
"code": "const x = tf.tensor2d([10, 30, 50, 70, 20, 40, 60, 80], [2, 4]); const [gfg, gfg1, geeks] = tf.split(x, [1, 2, 1], 1); gfg.print(); gfg1.print(); geeks.print();",
"e": 27857,
"s": 27692,
"text": null
},
{
"code": null,
"e": 27865,
"s": 27857,
"text": "Output:"
},
{
"code": null,
"e": 27960,
"s": 27865,
"text": "Tensor\n [[10],\n [20]]\nTensor\n [[30, 50],\n [40, 60]]\nTensor\n [[70],\n [80]]"
},
{
"code": null,
"e": 28015,
"s": 27960,
"text": "Reference: https://js.tensorflow.org/api/latest/#split"
},
{
"code": null,
"e": 28022,
"s": 28015,
"text": "Picked"
},
{
"code": null,
"e": 28036,
"s": 28022,
"text": "Tensorflow.js"
},
{
"code": null,
"e": 28047,
"s": 28036,
"text": "JavaScript"
},
{
"code": null,
"e": 28064,
"s": 28047,
"text": "Web Technologies"
},
{
"code": null,
"e": 28162,
"s": 28064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28202,
"s": 28162,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28263,
"s": 28202,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28304,
"s": 28263,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28326,
"s": 28304,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28380,
"s": 28326,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28420,
"s": 28380,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28453,
"s": 28420,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28496,
"s": 28453,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28546,
"s": 28496,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
reflect.DeepEqual() Function in Golang with Examples - GeeksforGeeks | 15 Jul, 2021
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.DeepEqual() Function in Golang is used to check whether x and y are “deeply equal” or not. To access this function, one needs to imports the reflect package in the program.
Syntax:
func DeepEqual(x, y interface{}) bool
Parameters: This function takes two parameters with value of any type, i.e. x, y.Return Value: This function returns the boolean value.
Below examples illustrate the use of the above method in Golang:
Example 1:
Go
// Golang program to illustrate// reflect.DeepEqual() Function package main import ( "fmt" "reflect") // Main functionfunc main() { map_1 := map[int]string{ 200: "Anita", 201: "Neha", 203: "Suman", 204: "Robin", 205: "Rohit", } map_2 := map[int]string{ 200: "Anita", 201: "Neha", 203: "Suman", 204: "Robin", 205: "Rohit", } // DeepEqual is used to check // two interfaces are equal or not res1 := reflect.DeepEqual(map_1, map_2) fmt.Println("Is Map 1 is equal to Map 2: ", res1)}
Output:
Is Map 1 is equal to Map 2: true
Example 2:
Go
// Golang program to illustrate// reflect.DeepEqual() Function package main import ( "fmt" "reflect") // Main functionfunc main() { src := reflect.ValueOf([]int{10, 20, 32}) dest := reflect.ValueOf([]int{1, 2, 3}) cnt := reflect.Copy(dest, src) cnt+=1 // DeepEqual is used to check // two interfaces are equal or not res1 := reflect.DeepEqual(src, dest ) fmt.Println("Is dest is equal to src: ", res1)}
Output:
Is dest is equal to src: false
singghakshay
Golang-reflect
Go Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 25703,
"s": 25675,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 26063,
"s": 25703,
"text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.DeepEqual() Function in Golang is used to check whether x and y are “deeply equal” or not. To access this function, one needs to imports the reflect package in the program."
},
{
"code": null,
"e": 26072,
"s": 26063,
"text": "Syntax: "
},
{
"code": null,
"e": 26110,
"s": 26072,
"text": "func DeepEqual(x, y interface{}) bool"
},
{
"code": null,
"e": 26248,
"s": 26110,
"text": "Parameters: This function takes two parameters with value of any type, i.e. x, y.Return Value: This function returns the boolean value. "
},
{
"code": null,
"e": 26313,
"s": 26248,
"text": "Below examples illustrate the use of the above method in Golang:"
},
{
"code": null,
"e": 26325,
"s": 26313,
"text": "Example 1: "
},
{
"code": null,
"e": 26328,
"s": 26325,
"text": "Go"
},
{
"code": "// Golang program to illustrate// reflect.DeepEqual() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { map_1 := map[int]string{ 200: \"Anita\", 201: \"Neha\", 203: \"Suman\", 204: \"Robin\", 205: \"Rohit\", } map_2 := map[int]string{ 200: \"Anita\", 201: \"Neha\", 203: \"Suman\", 204: \"Robin\", 205: \"Rohit\", } // DeepEqual is used to check // two interfaces are equal or not res1 := reflect.DeepEqual(map_1, map_2) fmt.Println(\"Is Map 1 is equal to Map 2: \", res1)}",
"e": 26921,
"s": 26328,
"text": null
},
{
"code": null,
"e": 26930,
"s": 26921,
"text": "Output: "
},
{
"code": null,
"e": 26964,
"s": 26930,
"text": "Is Map 1 is equal to Map 2: true"
},
{
"code": null,
"e": 26976,
"s": 26964,
"text": "Example 2: "
},
{
"code": null,
"e": 26979,
"s": 26976,
"text": "Go"
},
{
"code": "// Golang program to illustrate// reflect.DeepEqual() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { src := reflect.ValueOf([]int{10, 20, 32}) dest := reflect.ValueOf([]int{1, 2, 3}) cnt := reflect.Copy(dest, src) cnt+=1 // DeepEqual is used to check // two interfaces are equal or not res1 := reflect.DeepEqual(src, dest ) fmt.Println(\"Is dest is equal to src: \", res1)}",
"e": 27424,
"s": 26979,
"text": null
},
{
"code": null,
"e": 27433,
"s": 27424,
"text": "Output: "
},
{
"code": null,
"e": 27465,
"s": 27433,
"text": "Is dest is equal to src: false"
},
{
"code": null,
"e": 27480,
"s": 27467,
"text": "singghakshay"
},
{
"code": null,
"e": 27495,
"s": 27480,
"text": "Golang-reflect"
},
{
"code": null,
"e": 27507,
"s": 27495,
"text": "Go Language"
},
{
"code": null,
"e": 27523,
"s": 27507,
"text": "Write From Home"
},
{
"code": null,
"e": 27621,
"s": 27523,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27667,
"s": 27621,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 27680,
"s": 27667,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27731,
"s": 27680,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 27778,
"s": 27731,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 27811,
"s": 27778,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 27847,
"s": 27811,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27883,
"s": 27847,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 27944,
"s": 27883,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27960,
"s": 27944,
"text": "Python infinity"
}
]
|
Histograms in R language - GeeksforGeeks | 09 Dec, 2021
A histogram contains a rectangular area to display the statistical information which is proportional to the frequency of a variable and its width in successive numerical intervals. A graphical representation that manages a group of data points into different specified ranges. It has a special feature which shows no gaps between the bars and is similar to a vertical bar graph.
We can create histogram in R Programming Language using hist() function.
Syntax: hist(v, main, xlab, xlim, ylim, breaks, col, border)
Parameters:
v: This parameter contains numerical values used in histogram.
main: This parameter main is the title of the chart.
col: This parameter is used to set color of the bars.
xlab: This parameter is the label for horizontal axis.
border: This parameter is used to set border color of each bar.
xlim: This parameter is used for plotting values of x-axis.
ylim: This parameter is used for plotting values of y-axis.
breaks: This parameter is used as width of each bar.
Creating a simple histogram chart by using the above parameter. This vector v is plot using hist().
Example:
R
# Create data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39) # Create the histogram.hist(v, xlab = "No.of Articles ", col = "green", border = "black")
Output:
To describe the range of values we need to do the following steps:
We can use the xlim and ylim parameter in X-axis and Y-axis.Take all parameters which are required to make histogram chart.
We can use the xlim and ylim parameter in X-axis and Y-axis.
Take all parameters which are required to make histogram chart.
Example
R
# Create data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39) # Create the histogram.hist(v, xlab = "No.of Articles", col = "green", border = "black", xlim = c(0, 50), ylim = c(0, 5), breaks = 5)
Output:
To create a histogram return value chart.
R
# Creating data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39, 120, 40, 70, 90) # Creating the histogram.m<-hist(v, xlab = "Weight", ylab ="Frequency", col = "darkmagenta", border = "pink", breaks = 5) # Setting labelstext(m$mids, m$counts, labels = m$counts, adj = c(0.5, -0.5))
Output:
Creating different width histogram charts, by using the above parameters, we created histogram using non-uniform width.
Example
R
# Creating data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39, 120, 40, 70, 90) # Creating the histogram.hist(v, xlab = "Weight", ylab ="Frequency", xlim = c(50, 100), col = "darkmagenta", border = "pink", breaks = c(5, 55, 60, 70, 75, 80, 100, 140))
Output:
kumar_satyam
Picked
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Convert Factor to Numeric and Numeric to Factor in R Programming
Group by function in R using Dplyr
How to Change Axis Scales in R Plots? | [
{
"code": null,
"e": 30289,
"s": 30261,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 30668,
"s": 30289,
"text": "A histogram contains a rectangular area to display the statistical information which is proportional to the frequency of a variable and its width in successive numerical intervals. A graphical representation that manages a group of data points into different specified ranges. It has a special feature which shows no gaps between the bars and is similar to a vertical bar graph."
},
{
"code": null,
"e": 30741,
"s": 30668,
"text": "We can create histogram in R Programming Language using hist() function."
},
{
"code": null,
"e": 30802,
"s": 30741,
"text": "Syntax: hist(v, main, xlab, xlim, ylim, breaks, col, border)"
},
{
"code": null,
"e": 30815,
"s": 30802,
"text": "Parameters: "
},
{
"code": null,
"e": 30878,
"s": 30815,
"text": "v: This parameter contains numerical values used in histogram."
},
{
"code": null,
"e": 30931,
"s": 30878,
"text": "main: This parameter main is the title of the chart."
},
{
"code": null,
"e": 30985,
"s": 30931,
"text": "col: This parameter is used to set color of the bars."
},
{
"code": null,
"e": 31040,
"s": 30985,
"text": "xlab: This parameter is the label for horizontal axis."
},
{
"code": null,
"e": 31104,
"s": 31040,
"text": "border: This parameter is used to set border color of each bar."
},
{
"code": null,
"e": 31164,
"s": 31104,
"text": "xlim: This parameter is used for plotting values of x-axis."
},
{
"code": null,
"e": 31224,
"s": 31164,
"text": "ylim: This parameter is used for plotting values of y-axis."
},
{
"code": null,
"e": 31277,
"s": 31224,
"text": "breaks: This parameter is used as width of each bar."
},
{
"code": null,
"e": 31377,
"s": 31277,
"text": "Creating a simple histogram chart by using the above parameter. This vector v is plot using hist()."
},
{
"code": null,
"e": 31387,
"s": 31377,
"text": "Example: "
},
{
"code": null,
"e": 31389,
"s": 31387,
"text": "R"
},
{
"code": "# Create data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39) # Create the histogram.hist(v, xlab = \"No.of Articles \", col = \"green\", border = \"black\")",
"e": 31567,
"s": 31389,
"text": null
},
{
"code": null,
"e": 31575,
"s": 31567,
"text": "Output:"
},
{
"code": null,
"e": 31643,
"s": 31575,
"text": "To describe the range of values we need to do the following steps: "
},
{
"code": null,
"e": 31767,
"s": 31643,
"text": "We can use the xlim and ylim parameter in X-axis and Y-axis.Take all parameters which are required to make histogram chart."
},
{
"code": null,
"e": 31828,
"s": 31767,
"text": "We can use the xlim and ylim parameter in X-axis and Y-axis."
},
{
"code": null,
"e": 31892,
"s": 31828,
"text": "Take all parameters which are required to make histogram chart."
},
{
"code": null,
"e": 31901,
"s": 31892,
"text": "Example "
},
{
"code": null,
"e": 31903,
"s": 31901,
"text": "R"
},
{
"code": "# Create data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39) # Create the histogram.hist(v, xlab = \"No.of Articles\", col = \"green\", border = \"black\", xlim = c(0, 50), ylim = c(0, 5), breaks = 5) ",
"e": 32125,
"s": 31903,
"text": null
},
{
"code": null,
"e": 32134,
"s": 32125,
"text": "Output: "
},
{
"code": null,
"e": 32176,
"s": 32134,
"text": "To create a histogram return value chart."
},
{
"code": null,
"e": 32178,
"s": 32176,
"text": "R"
},
{
"code": "# Creating data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39, 120, 40, 70, 90) # Creating the histogram.m<-hist(v, xlab = \"Weight\", ylab =\"Frequency\", col = \"darkmagenta\", border = \"pink\", breaks = 5) # Setting labelstext(m$mids, m$counts, labels = m$counts, adj = c(0.5, -0.5)) ",
"e": 32502,
"s": 32178,
"text": null
},
{
"code": null,
"e": 32510,
"s": 32502,
"text": "Output:"
},
{
"code": null,
"e": 32630,
"s": 32510,
"text": "Creating different width histogram charts, by using the above parameters, we created histogram using non-uniform width."
},
{
"code": null,
"e": 32639,
"s": 32630,
"text": "Example "
},
{
"code": null,
"e": 32641,
"s": 32639,
"text": "R"
},
{
"code": "# Creating data for the graph.v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39, 120, 40, 70, 90) # Creating the histogram.hist(v, xlab = \"Weight\", ylab =\"Frequency\", xlim = c(50, 100), col = \"darkmagenta\", border = \"pink\", breaks = c(5, 55, 60, 70, 75, 80, 100, 140))",
"e": 32943,
"s": 32641,
"text": null
},
{
"code": null,
"e": 32951,
"s": 32943,
"text": "Output:"
},
{
"code": null,
"e": 32964,
"s": 32951,
"text": "kumar_satyam"
},
{
"code": null,
"e": 32971,
"s": 32964,
"text": "Picked"
},
{
"code": null,
"e": 32979,
"s": 32971,
"text": "R-plots"
},
{
"code": null,
"e": 32990,
"s": 32979,
"text": "R Language"
},
{
"code": null,
"e": 33088,
"s": 32990,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33133,
"s": 33088,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 33191,
"s": 33133,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 33243,
"s": 33191,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 33275,
"s": 33243,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 33338,
"s": 33275,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 33382,
"s": 33338,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 33434,
"s": 33382,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 33499,
"s": 33434,
"text": "Convert Factor to Numeric and Numeric to Factor in R Programming"
},
{
"code": null,
"e": 33534,
"s": 33499,
"text": "Group by function in R using Dplyr"
}
]
|
Check if a numeric value falls between a range in R Programming - between() function - GeeksforGeeks | 26 May, 2020
between() function in R Language is used to check that whether a numeric value falls in a specific range or not.A lower bound and an upper bound is specified and checked if the value falls in it.
Syntax: between(x, left, right)
Parameters:
x: A numeric vectorleft, right: Boundary values
Example 1: Values in Range
# R program to illustrate# between function # Install dplyr packageinstall.packages("dplyr") # Load dplyr package library("dplyr") # Define valuex1 <- 7 # Define lower bound left1 <- 1 # Define upper bound right1 <- 10 # Apply between functionbetween(x1, left1, right1)
Output:
TRUE
Here in the above code, we have defined value to 7 to x1 and defined upper and lower bound 1 and 10 respectively.As we have given the value 7 falls in range 1 to 10. So the Output is “TRUE”.
Example 2: Value not in Range
# R program to illustrate# between function # Install dplyr packageinstall.packages("dplyr") # Load dplyr package library("dplyr") # Define valuex2 <- 11 # Define lower range left2 <- 1 # Define upper range right2 <- 10 # Apply between functionbetween(x2, left2, right2)
Output:
FALSE
Here in the above code, we have assigned a value 11 to x2 and defined upper and lower bound to 1 and 10 respectively.And clearly the value 11 does not fall in a given range from 1 to 10.So the answer is FALSE.
R-Functions
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Programming Languages to Learn in 2022
Kotlin Array
C# | Data Types
Difference between Shallow and Deep copy of a class
Advantages and Disadvantages of OOP
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method | [
{
"code": null,
"e": 26255,
"s": 26227,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 26451,
"s": 26255,
"text": "between() function in R Language is used to check that whether a numeric value falls in a specific range or not.A lower bound and an upper bound is specified and checked if the value falls in it."
},
{
"code": null,
"e": 26483,
"s": 26451,
"text": "Syntax: between(x, left, right)"
},
{
"code": null,
"e": 26495,
"s": 26483,
"text": "Parameters:"
},
{
"code": null,
"e": 26543,
"s": 26495,
"text": "x: A numeric vectorleft, right: Boundary values"
},
{
"code": null,
"e": 26570,
"s": 26543,
"text": "Example 1: Values in Range"
},
{
"code": "# R program to illustrate# between function # Install dplyr packageinstall.packages(\"dplyr\") # Load dplyr package library(\"dplyr\") # Define valuex1 <- 7 # Define lower bound left1 <- 1 # Define upper bound right1 <- 10 # Apply between functionbetween(x1, left1, right1) ",
"e": 26933,
"s": 26570,
"text": null
},
{
"code": null,
"e": 26941,
"s": 26933,
"text": "Output:"
},
{
"code": null,
"e": 26946,
"s": 26941,
"text": "TRUE"
},
{
"code": null,
"e": 27137,
"s": 26946,
"text": "Here in the above code, we have defined value to 7 to x1 and defined upper and lower bound 1 and 10 respectively.As we have given the value 7 falls in range 1 to 10. So the Output is “TRUE”."
},
{
"code": null,
"e": 27167,
"s": 27137,
"text": "Example 2: Value not in Range"
},
{
"code": "# R program to illustrate# between function # Install dplyr packageinstall.packages(\"dplyr\") # Load dplyr package library(\"dplyr\") # Define valuex2 <- 11 # Define lower range left2 <- 1 # Define upper range right2 <- 10 # Apply between functionbetween(x2, left2, right2) ",
"e": 27521,
"s": 27167,
"text": null
},
{
"code": null,
"e": 27529,
"s": 27521,
"text": "Output:"
},
{
"code": null,
"e": 27535,
"s": 27529,
"text": "FALSE"
},
{
"code": null,
"e": 27745,
"s": 27535,
"text": "Here in the above code, we have assigned a value 11 to x2 and defined upper and lower bound to 1 and 10 respectively.And clearly the value 11 does not fall in a given range from 1 to 10.So the answer is FALSE."
},
{
"code": null,
"e": 27757,
"s": 27745,
"text": "R-Functions"
},
{
"code": null,
"e": 27778,
"s": 27757,
"text": "Programming Language"
},
{
"code": null,
"e": 27789,
"s": 27778,
"text": "R Language"
},
{
"code": null,
"e": 27887,
"s": 27789,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27933,
"s": 27887,
"text": "Top 10 Programming Languages to Learn in 2022"
},
{
"code": null,
"e": 27946,
"s": 27933,
"text": "Kotlin Array"
},
{
"code": null,
"e": 27962,
"s": 27946,
"text": "C# | Data Types"
},
{
"code": null,
"e": 28014,
"s": 27962,
"text": "Difference between Shallow and Deep copy of a class"
},
{
"code": null,
"e": 28050,
"s": 28014,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 28095,
"s": 28050,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 28153,
"s": 28095,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 28205,
"s": 28153,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 28237,
"s": 28205,
"text": "Loops in R (for, while, repeat)"
}
]
|
How to convert date and time with different timezones in Python? - GeeksforGeeks | 22 Apr, 2021
In this article, we will discuss how to convert date and time with different timezones in Python. To do this we will use one of the modules of python pytz . This module brings the Olson tz database into Python and this library allows accurate and cross-platform timezone calculations using Python. The method pytz.timezone() generates the current timezone of a particular region.
Syntax:
pytz.timezone(“name of the time zone”)
Ex: pytz.timezone(“Asia/Kolkata”)
Example 1:
In the below program the current UTC time is converted according to Asia/Kolkata timezone.
Python3
from datetime import datetimeimport pytz # get the standard UTC timeUTC = pytz.utc # it will get the time zone# of the specified locationIST = pytz.timezone('Asia/Kolkata') # print the date and time in# standard formatprint("UTC in Default Format : ", datetime.now(UTC)) print("IST in Default Format : ", datetime.now(IST)) # print the date and time in# specified formatdatetime_utc = datetime.now(UTC)print("Date & Time in UTC : ", datetime_utc.strftime('%Y:%m:%d %H:%M:%S %Z %z')) datetime_ist = datetime.now(IST)print("Date & Time in IST : ", datetime_ist.strftime('%Y:%m:%d %H:%M:%S %Z %z'))
Output:
Example 2:
Here is another program where the current Asia/Kolkata timezone is converted to US/Eastern timezone.
Python3
from datetime import datetimeimport pytz # get the standard UTC timeoriginal = pytz.timezone('Asia/Kolkata') # it will get the time zone# of the specified locationconverted = pytz.timezone('US/Eastern') # print the date and time in# specified formatdateTimeObj = datetime.now(original)print("Original Date & Time: ", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z')) # converteddateTimeObj = datetime.now(converted )print("Converted Date & Time: ", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z'))
Output:
One can get all timezone values present in the pytz by executing the below code:
for timezone in pytz.all_timezones:
print(timezone)
Below is a program to convert a particular timezone to multiple timezones of the Indian region:
Python3
from datetime import datetimeimport pytz # get the standard UTC timeoriginal = pytz.utc # create datetime objectdateTimeObj = datetime.now(original)print("Original Date & Time: ", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z')) # it will get the time zone# of the specified locationfor timeZone in pytz.all_timezones: if 'Indian/' in timeZone: dateTimeObj = datetime.now(pytz.timezone(timeZone)) print(timeZone,":",dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z'))
Output:
Picked
Python datetime-program
Python-datetime
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 | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 25943,
"s": 25563,
"text": "In this article, we will discuss how to convert date and time with different timezones in Python. To do this we will use one of the modules of python pytz . This module brings the Olson tz database into Python and this library allows accurate and cross-platform timezone calculations using Python. The method pytz.timezone() generates the current timezone of a particular region."
},
{
"code": null,
"e": 25951,
"s": 25943,
"text": "Syntax:"
},
{
"code": null,
"e": 25990,
"s": 25951,
"text": "pytz.timezone(“name of the time zone”)"
},
{
"code": null,
"e": 26024,
"s": 25990,
"text": "Ex: pytz.timezone(“Asia/Kolkata”)"
},
{
"code": null,
"e": 26035,
"s": 26024,
"text": "Example 1:"
},
{
"code": null,
"e": 26126,
"s": 26035,
"text": "In the below program the current UTC time is converted according to Asia/Kolkata timezone."
},
{
"code": null,
"e": 26134,
"s": 26126,
"text": "Python3"
},
{
"code": "from datetime import datetimeimport pytz # get the standard UTC timeUTC = pytz.utc # it will get the time zone# of the specified locationIST = pytz.timezone('Asia/Kolkata') # print the date and time in# standard formatprint(\"UTC in Default Format : \", datetime.now(UTC)) print(\"IST in Default Format : \", datetime.now(IST)) # print the date and time in# specified formatdatetime_utc = datetime.now(UTC)print(\"Date & Time in UTC : \", datetime_utc.strftime('%Y:%m:%d %H:%M:%S %Z %z')) datetime_ist = datetime.now(IST)print(\"Date & Time in IST : \", datetime_ist.strftime('%Y:%m:%d %H:%M:%S %Z %z'))",
"e": 26756,
"s": 26134,
"text": null
},
{
"code": null,
"e": 26764,
"s": 26756,
"text": "Output:"
},
{
"code": null,
"e": 26775,
"s": 26764,
"text": "Example 2:"
},
{
"code": null,
"e": 26876,
"s": 26775,
"text": "Here is another program where the current Asia/Kolkata timezone is converted to US/Eastern timezone."
},
{
"code": null,
"e": 26884,
"s": 26876,
"text": "Python3"
},
{
"code": "from datetime import datetimeimport pytz # get the standard UTC timeoriginal = pytz.timezone('Asia/Kolkata') # it will get the time zone# of the specified locationconverted = pytz.timezone('US/Eastern') # print the date and time in# specified formatdateTimeObj = datetime.now(original)print(\"Original Date & Time: \", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z')) # converteddateTimeObj = datetime.now(converted )print(\"Converted Date & Time: \", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z'))",
"e": 27395,
"s": 26884,
"text": null
},
{
"code": null,
"e": 27403,
"s": 27395,
"text": "Output:"
},
{
"code": null,
"e": 27484,
"s": 27403,
"text": "One can get all timezone values present in the pytz by executing the below code:"
},
{
"code": null,
"e": 27542,
"s": 27484,
"text": "for timezone in pytz.all_timezones:\n print(timezone) "
},
{
"code": null,
"e": 27638,
"s": 27542,
"text": "Below is a program to convert a particular timezone to multiple timezones of the Indian region:"
},
{
"code": null,
"e": 27646,
"s": 27638,
"text": "Python3"
},
{
"code": "from datetime import datetimeimport pytz # get the standard UTC timeoriginal = pytz.utc # create datetime objectdateTimeObj = datetime.now(original)print(\"Original Date & Time: \", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z')) # it will get the time zone# of the specified locationfor timeZone in pytz.all_timezones: if 'Indian/' in timeZone: dateTimeObj = datetime.now(pytz.timezone(timeZone)) print(timeZone,\":\",dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z'))",
"e": 28136,
"s": 27646,
"text": null
},
{
"code": null,
"e": 28144,
"s": 28136,
"text": "Output:"
},
{
"code": null,
"e": 28151,
"s": 28144,
"text": "Picked"
},
{
"code": null,
"e": 28175,
"s": 28151,
"text": "Python datetime-program"
},
{
"code": null,
"e": 28191,
"s": 28175,
"text": "Python-datetime"
},
{
"code": null,
"e": 28198,
"s": 28191,
"text": "Python"
},
{
"code": null,
"e": 28296,
"s": 28198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28328,
"s": 28296,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28370,
"s": 28328,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28412,
"s": 28370,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28468,
"s": 28412,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28495,
"s": 28468,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28534,
"s": 28495,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28565,
"s": 28534,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28587,
"s": 28565,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28616,
"s": 28587,
"text": "Create a directory in Python"
}
]
|
Python - Extract ith Key's Value of K's Maximum value dictionary - GeeksforGeeks | 01 Aug, 2020
Given Dictionary List, extract i’th keys value depending upon Kth key’s maximum value.
Input : test_list = [{“Gfg” : 3, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 19}, {“Gfg” : 9, “is” : 16, “best” : 1}], K = “best”, i = “is”Output : 11Explanation : best is max at 19, its corresponding “is” value is 11.
Input : test_list = [{“Gfg” : 3, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 19}, {“Gfg” : 9, “is” : 16, “best” : 1}], K = “Gfg”, i = “is”Output : 16Explanation : Gfg is max at 9, its corresponding “is” value is 16.
Method #1 : Using max() + lambda
The combination of above functions can be used to solve this problem. In this, we extract max of kth key using max() and lambda. Then ith key is extracted from extracted dictionary.
Python3
# Python3 code to demonstrate working of # Extract ith Key's Value of K's Maximum value dictionary# Using max() + lambda # initializing liststest_list = [{"Gfg" : 3, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 9, "is" : 16, "best" : 1}] # printing original listprint("The original list : " + str(test_list)) # initializing K K = "best" # initializing i i = "Gfg" # using get() to handle missing key, assigning lowest valueres = max(test_list, key = lambda ele : ele.get(K, 0))[i] # printing result print("The required value : " + str(res))
The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]
The required value : 8
Method #2 : Using max() + external function
This is yet another way to solve this problem. This computes in similar way as above method, just the difference being of usage of custom comparator rather than lambda function.
Python3
# Python3 code to demonstrate working of # Extract ith Key's Value of K's Maximum value dictionary# Using max() + external function # custom function as comparatordef cust_fnc(ele): return ele.get(K, 0) # initializing liststest_list = [{"Gfg" : 3, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 9, "is" : 16, "best" : 1}] # printing original listprint("The original list : " + str(test_list)) # initializing K K = "best" # initializing i i = "Gfg" # using get() to handle missing key, assigning lowest valueres = max(test_list, key = cust_fnc)[i] # printing result print("The required value : " + str(res))
The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]
The required value : 8
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25877,
"s": 25849,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 25964,
"s": 25877,
"text": "Given Dictionary List, extract i’th keys value depending upon Kth key’s maximum value."
},
{
"code": null,
"e": 26195,
"s": 25964,
"text": "Input : test_list = [{“Gfg” : 3, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 19}, {“Gfg” : 9, “is” : 16, “best” : 1}], K = “best”, i = “is”Output : 11Explanation : best is max at 19, its corresponding “is” value is 11."
},
{
"code": null,
"e": 26423,
"s": 26195,
"text": "Input : test_list = [{“Gfg” : 3, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 19}, {“Gfg” : 9, “is” : 16, “best” : 1}], K = “Gfg”, i = “is”Output : 16Explanation : Gfg is max at 9, its corresponding “is” value is 16."
},
{
"code": null,
"e": 26456,
"s": 26423,
"text": "Method #1 : Using max() + lambda"
},
{
"code": null,
"e": 26638,
"s": 26456,
"text": "The combination of above functions can be used to solve this problem. In this, we extract max of kth key using max() and lambda. Then ith key is extracted from extracted dictionary."
},
{
"code": null,
"e": 26646,
"s": 26638,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract ith Key's Value of K's Maximum value dictionary# Using max() + lambda # initializing liststest_list = [{\"Gfg\" : 3, \"is\" : 9, \"best\" : 10}, {\"Gfg\" : 8, \"is\" : 11, \"best\" : 19}, {\"Gfg\" : 9, \"is\" : 16, \"best\" : 1}] # printing original listprint(\"The original list : \" + str(test_list)) # initializing K K = \"best\" # initializing i i = \"Gfg\" # using get() to handle missing key, assigning lowest valueres = max(test_list, key = lambda ele : ele.get(K, 0))[i] # printing result print(\"The required value : \" + str(res))",
"e": 27247,
"s": 26646,
"text": null
},
{
"code": null,
"e": 27392,
"s": 27247,
"text": "The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]\nThe required value : 8\n"
},
{
"code": null,
"e": 27436,
"s": 27392,
"text": "Method #2 : Using max() + external function"
},
{
"code": null,
"e": 27614,
"s": 27436,
"text": "This is yet another way to solve this problem. This computes in similar way as above method, just the difference being of usage of custom comparator rather than lambda function."
},
{
"code": null,
"e": 27622,
"s": 27614,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract ith Key's Value of K's Maximum value dictionary# Using max() + external function # custom function as comparatordef cust_fnc(ele): return ele.get(K, 0) # initializing liststest_list = [{\"Gfg\" : 3, \"is\" : 9, \"best\" : 10}, {\"Gfg\" : 8, \"is\" : 11, \"best\" : 19}, {\"Gfg\" : 9, \"is\" : 16, \"best\" : 1}] # printing original listprint(\"The original list : \" + str(test_list)) # initializing K K = \"best\" # initializing i i = \"Gfg\" # using get() to handle missing key, assigning lowest valueres = max(test_list, key = cust_fnc)[i] # printing result print(\"The required value : \" + str(res))",
"e": 28292,
"s": 27622,
"text": null
},
{
"code": null,
"e": 28437,
"s": 28292,
"text": "The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]\nThe required value : 8\n"
},
{
"code": null,
"e": 28464,
"s": 28437,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 28485,
"s": 28464,
"text": "Python list-programs"
},
{
"code": null,
"e": 28492,
"s": 28485,
"text": "Python"
},
{
"code": null,
"e": 28508,
"s": 28492,
"text": "Python Programs"
},
{
"code": null,
"e": 28606,
"s": 28508,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28624,
"s": 28606,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28659,
"s": 28624,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28691,
"s": 28659,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28713,
"s": 28691,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28755,
"s": 28713,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28798,
"s": 28755,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28820,
"s": 28798,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28866,
"s": 28820,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28904,
"s": 28866,
"text": "Python | Convert a list to dictionary"
}
]
|
LocalDateTime getMonth() method in Java with Examples - GeeksforGeeks | 29 Nov, 2018
The getMonth() method of an LocalDateTime class is used to return month-of-year field. This field is returned using the Month enum. The enum can provide the primitive int value.
Syntax:
public Month getMonth()
Parameter: This method does not accept any parameter.
Returns: This method returns the enum Month for the month of this LocalDateTime.
Below programs illustrate the LocalDateTime.getMonth() method:
Program 1:
// Java program to demonstrate// LocalDateTime.getMonth() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDateTime Object LocalDateTime local = LocalDateTime.parse("2007-12-02T22:48:29"); // get Month enum value field Month month = local.getMonth(); // print result System.out.println("Month: " + month); }}
Month: DECEMBER
Program 2:
// Java program to demonstrate// LocalDateTime.getMonth() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDateTime Object LocalDateTime local = LocalDateTime.parse("2017-07-22T09:32:42"); // get Month enum value field Month month = local.getMonth(); // print result System.out.println("Month: " + month); }}
Month: JULY
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#getMonth()
Java-Functions
Java-LocalDateTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 25403,
"s": 25225,
"text": "The getMonth() method of an LocalDateTime class is used to return month-of-year field. This field is returned using the Month enum. The enum can provide the primitive int value."
},
{
"code": null,
"e": 25411,
"s": 25403,
"text": "Syntax:"
},
{
"code": null,
"e": 25436,
"s": 25411,
"text": "public Month getMonth()\n"
},
{
"code": null,
"e": 25490,
"s": 25436,
"text": "Parameter: This method does not accept any parameter."
},
{
"code": null,
"e": 25571,
"s": 25490,
"text": "Returns: This method returns the enum Month for the month of this LocalDateTime."
},
{
"code": null,
"e": 25634,
"s": 25571,
"text": "Below programs illustrate the LocalDateTime.getMonth() method:"
},
{
"code": null,
"e": 25645,
"s": 25634,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// LocalDateTime.getMonth() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDateTime Object LocalDateTime local = LocalDateTime.parse(\"2007-12-02T22:48:29\"); // get Month enum value field Month month = local.getMonth(); // print result System.out.println(\"Month: \" + month); }}",
"e": 26105,
"s": 25645,
"text": null
},
{
"code": null,
"e": 26122,
"s": 26105,
"text": "Month: DECEMBER\n"
},
{
"code": null,
"e": 26133,
"s": 26122,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// LocalDateTime.getMonth() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDateTime Object LocalDateTime local = LocalDateTime.parse(\"2017-07-22T09:32:42\"); // get Month enum value field Month month = local.getMonth(); // print result System.out.println(\"Month: \" + month); }}",
"e": 26593,
"s": 26133,
"text": null
},
{
"code": null,
"e": 26606,
"s": 26593,
"text": "Month: JULY\n"
},
{
"code": null,
"e": 26700,
"s": 26606,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#getMonth()"
},
{
"code": null,
"e": 26715,
"s": 26700,
"text": "Java-Functions"
},
{
"code": null,
"e": 26734,
"s": 26715,
"text": "Java-LocalDateTime"
},
{
"code": null,
"e": 26752,
"s": 26734,
"text": "Java-time package"
},
{
"code": null,
"e": 26757,
"s": 26752,
"text": "Java"
},
{
"code": null,
"e": 26762,
"s": 26757,
"text": "Java"
},
{
"code": null,
"e": 26860,
"s": 26762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26875,
"s": 26860,
"text": "Stream In Java"
},
{
"code": null,
"e": 26896,
"s": 26875,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26915,
"s": 26896,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26945,
"s": 26915,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 26991,
"s": 26945,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27008,
"s": 26991,
"text": "Generics in Java"
},
{
"code": null,
"e": 27029,
"s": 27008,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27072,
"s": 27029,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27108,
"s": 27072,
"text": "Internal Working of HashMap in Java"
}
]
|
jQuery - position( ) Method | The position( ) method gets the top and left position of an element relative to its offset parent.
The returned object contains two Integer properties, top and left. For accurate calculations make sure to use pixel values for margins, borders and padding. This method only works with visible elements.
Here is the simple syntax to use this method −
selector.position( )
Here is the description of all the parameters used by this method −
NA
NA
Following is a simple example a simple showing the usage of this method −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function () {
var position = $(this).position();
$("#lresult").html("left position: <span>" + position.left + "</span>.");
$("#tresult").html("top position: <span>" + position.top + "</span>.");
});
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left; }
</style>
</head>
<body>
<p>Click on any square:</p>
<span id = "lresult"> </span>
<span id = "tresult"> </span>
<div style = "background-color:blue;"></div>
<div style = "background-color:pink;"></div>
<div style = "background-color:#123456;"></div>
<div style = "background-color:#f11;"></div>
</body>
</html>
This will produce following result −
Click on any square −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2421,
"s": 2322,
"text": "The position( ) method gets the top and left position of an element relative to its offset parent."
},
{
"code": null,
"e": 2624,
"s": 2421,
"text": "The returned object contains two Integer properties, top and left. For accurate calculations make sure to use pixel values for margins, borders and padding. This method only works with visible elements."
},
{
"code": null,
"e": 2671,
"s": 2624,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 2693,
"s": 2671,
"text": "selector.position( )\n"
},
{
"code": null,
"e": 2761,
"s": 2693,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2764,
"s": 2761,
"text": "NA"
},
{
"code": null,
"e": 2767,
"s": 2764,
"text": "NA"
},
{
"code": null,
"e": 2841,
"s": 2767,
"text": "Following is a simple example a simple showing the usage of this method −"
},
{
"code": null,
"e": 3925,
"s": 2841,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n\t\t\t\n $(\"div\").click(function () {\n var position = $(this).position();\n $(\"#lresult\").html(\"left position: <span>\" + position.left + \"</span>.\");\n $(\"#tresult\").html(\"top position: <span>\" + position.top + \"</span>.\");\n });\n\t\t\t\t\n });\n </script>\n\t\t\n <style>\n div { width:60px; height:60px; margin:5px; float:left; }\n </style>\n </head>\n\t\n <body>\n <p>Click on any square:</p>\n <span id = \"lresult\"> </span>\n <span id = \"tresult\"> </span>\n\t\t\n <div style = \"background-color:blue;\"></div>\n <div style = \"background-color:pink;\"></div>\n <div style = \"background-color:#123456;\"></div>\n <div style = \"background-color:#f11;\"></div>\n </body>\n</html>"
},
{
"code": null,
"e": 3962,
"s": 3925,
"text": "This will produce following result −"
},
{
"code": null,
"e": 3984,
"s": 3962,
"text": "Click on any square −"
},
{
"code": null,
"e": 4017,
"s": 3984,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4031,
"s": 4017,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 4066,
"s": 4031,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4080,
"s": 4066,
"text": " Pratik Singh"
},
{
"code": null,
"e": 4115,
"s": 4080,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4132,
"s": 4115,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4165,
"s": 4132,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4193,
"s": 4165,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4226,
"s": 4193,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4247,
"s": 4226,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4279,
"s": 4247,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4296,
"s": 4279,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4303,
"s": 4296,
"text": " Print"
},
{
"code": null,
"e": 4314,
"s": 4303,
"text": " Add Notes"
}
]
|
COVID-19 Testing. What are your chances? | by Rob Harrand | Towards Data Science | Note: I am not a medical professional and this blog is just my take on what I believe are statistical ideas pertinent to diagnostic testing.
Testing for COVID-19You need no introduction to COVID-19, the coronovirus that’s now spread to every country on Earth and is wreaking havoc on economies, health systems and people’s lives.
Beyond social distancing, one of the priorities for governments the world over is to test as many of its citizens as possible, both to see who currently has the virus (the antigen test) and to see who has already had it (the antibody test). Note that in this blog post, I’ll be using ‘positive’ to mean that an antibody is detected and the person has had COVID-19.
So far, so good. You roll out the tests and assess the population, then certain people can return to work.
Evaluating a yes/no diagnostic testThe problem comes when you look down at the test cartridge (typically a point-of-care lateral flow device, similar to how a home pregnancy test works) and see the result. These tests give a ‘positive’ or a ‘negative’ result, and we often hear that such tests are evaluated by their accuracy. We hear it on the news all the time. You run a test that’s 99% accurate, get a positive result, so it’s easy to assume that probability of you having had COVID-19 is 99%, right?
Not quite.
Accuracy is the number of cases, positive or negative, that a test correctly identified during some sort of evaluation. The problem with this way of quoting how good a positive/negative test is, is that it doesn’t distinguish between the positives that it got right and the negatives that it got right.
Imagine you have a test that fundamentally doesn’t work. It just says ‘positive’ every single time you run it, regardless of the patient, the condition, etc. You test it on a random group of medical staff, 98 of whom are known to have had COVID-19 and 2 who haven’t. Your bogus test, diagnosing everyone as positive, would end up with an accuracy of 98%!
Thankfully, there are better ways to summarise the effectiveness of such tests, the most common being sensitivity and specificity. These are defined as follows,
Notice the denominators. For sensitivity, we have ‘true positives’, which are of course positives, and ‘false negatives’, which are also positives. So, sensitivity only deals with positive cases, and the logic is the same with specificity for negative cases. The result is that sensitivity is a measure of the probability of getting a positive result out of all the positive cases, and that specificity is a measure of the probability of getting a negative result out of all the negative cases.
Another way of phrasing this is that sensitivity is the probability of getting a positive result, given that you have had the disease, which is written as P(+ve result|Disease)
However, in practice, we’re interested in the opposite of this, namely the probability of having had the disease, given a positive test result, i.e. P(Disease|+ve result). So, in practice, how do we do this flip?
Enter Reverend BayesThomas Bayes was born in England in 1701. He spent most of his life focused on the Church and only published a single work on mathematics. In later life he developed an interest in probability, possibly motivated by wishing to refute David Hume’s argument against taking personal testimonials as evidence of miracles.
After his death, a friend found and handed in manuscripts on probability to the Royal Society, to which Bayes had been elected a fellow in 1742. One of the essays contained within, titled ‘An Essay towards solving a Problem in the Doctrine of Chances’, led to what is today known as Bayes’ theorem, defined as,
Note the first term on the left and the first on the right. Here we can see the ‘flip’ that we’re after, i.e. obtaining P(Disease|+ve result) when we know P(+ve result|Disease), along with a few other terms which we’ll get to soon. This theorem in turn (after refinement by Pierre-Simon Laplace) led to what is today known as Bayesian statistics.
The prevailing type of statistics and that used in many applications is known as frequentist statistics. This approach assigns probabilities based upon the frequency of events that occur in a sample. In contrast, in the Bayesian mindset, probabilities are related to our current level of knowledge about an event. This latter approach allows the introduction of something called a prior or pretest probability (explained in more detail below), which is a probability assigned before data is collected on an event. This pre-test probability is combined with new evidence to give a posterior or post-test probability.
In the Bayes’ theorem, P(A) is the probability of having had the disease and P(B) is the probability of getting a positive result. What are these values? P(A) is the pre-test probability (mentioned above), for which local disease prevalence is often used. Alternatively, a pre-test probability can also be estimated from a detailed medical examination, a review of a patient’s records, etc. P(B) is the combination of all the ways a positive result could be obtained, i.e. the patient could have had the disease and received a positive result or the patient could not have had the disease and received a positive result. Specifically,
In practice, such calculations are usually done using something called likelihood ratios. These are defined as,
Where LR+ is the positive likelihood ratio and LR- is the negative likelihood ratio. They allow you to go from a pre-test probability to a post-test probability using a graphical tool called a Fagan nomogram. Alternatively, the calculation can be quickly performed using a computer. They also give you an indication of the effectiveness of a test, as they tell you how much your pre-test probability will be affected by either a positive or negative result (see table below).
The exact calculation involves switching from probabilities to odds using,
Taking a look at some of the COVID-19 tests that are being used around the world, values for sensitivity seem to be around 91% and specificity around 99%. That gives us a LR+ of 91 and a LR- of 0.09. Pretty impressive.
We now have all the pieces of the puzzle to work out, given a positive result, what the probability of having had COVID-19 is for a given individual. First, let’s assume you run the test in an area that has a prevalence of 1% and get a positive result. What is the post-test probability?
There we have it. The probability that an individual has had COVID-19 after a positive result from a fantastic test is less than 50%.
Now, imagine if Tom Hanks had suspected COVID-19. No, not the real Tom Hanks, who did actually get COVID-19. I mean Chuck Noland, the character Tom Hanks plays in the film Castaway. If, via a highly convoluted turn of events, Chuck Noland, stranded for years on a desert island, found a COVID-19 rapid point-of-care test washed up on the beach and decided to run it because he had had a bit of a cough, what would it mean if it gave him a positive result? Well, the pre-test probability is zero, which means the post-test probability is also zero. Running the test is a complete waste of time! (not that that is much of an issue when you’re stuck on a desert island).
Now let’s flip it the other way. You run the test on medical staff who have been working endless hours in an emergency COVID-19 shelter, without sufficient personal protective equipment. They’ve all had symptoms but have since recovered. The patients that they’ve been treating all had severe symptoms. They’re were all struggling to breathe. They all had a fever. They’ve all had contact with family members that were themselves confirmed cases. It’s the middle of summer, with very low rates of the common cold and the flu. It’s hard to say what the prevalence is, so you use the method of using (past) clinical symptoms and patient history. You estimate a pre-test probability for each staff member to be 0.95. Here are the numbers,
You’ve gone from a pre-test probability of 0.95 to a post-test probability of, effectively, 1. Not particularly surprising. Again, this test was arguably a waste of time.
Triaging TestsThe conclusion from this is that, given you’re likely to have a shortage of tests, does it make sense to test people who have an extremely low or an extremely high pre-test probability? After all, at the end of the day, what you do after you’ve run the test probably won’t change. If you’re pretty sure someone has had COVID-19 and the plan is to allow them to leave isolation, using up a precious test which comes back positive isn’t going to change things. Even if someone has a pre-test probability of 0.95 and they get a negative result, that doesn’t change things dramatically either (based upon the LR- above),
We get a post-test probability of 0.63. If in the doctor’s mind they’re thinking “I’ll allow a member of the team return to work if they have a post-test probability over 0.5 or above”, this negative result doesn’t change anything. They would have been allowed to return before the test. They’ll be allowed to return after it, too.
This ‘treatment threshold’ is easier to see with a plot. Below is a Python function that works out the post-test probability for a given pre-test probability, with given values for sensitivity and specificity.
def diagnostic_posttest(pretest,sens,spec): lr_pos = sens / (1 - spec) lr_neg = (1 - sens) / spec pretest_odds = pretest / (1-pretest) posttest_odds_pos = pretest_odds * lr_pos posttest_odds_neg = pretest_odds * lr_neg posttest_pos = posttest_odds_pos / (1+posttest_odds_pos) posttest_neg = posttest_odds_neg / (1+posttest_odds_neg) return(posttest_pos, posttest_neg)
We can use this function along with sensitivity and specificity values similar to those in the real-world to create a plot of pre-test probability vs post-test probability,
import numpy as npimport matplotlib.pyplot as pltpost = list()prev_options = np.arange(0.0, 1.0, 0.01)for i in prev_options: post_temp = diagnostic_posttest(i,0.91,0.99)[0] post.append(post_temp)fig, ax = plt.subplots()ax.plot(prev_options, post)plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.0])plt.rcParams['font.size'] = 12plt.title('Pretest vs Posttest Probability (sens = 0.91, spec = 0.99)')plt.xlabel('Pretest Probability')plt.ylabel('Posttest Probability')
Here is what we get for a positive test result,
And for a negative test result,
As you can see for a positive result, as the pre-test probability increases the post-test probability shoots up rapidly. For a negative result, you need a very high pre-test probability for the post-test probability to also be high.
How Confident?There’s one more aspect to all of this. The numbers typically quoted for COVID-19 tests do not often include confidence intervals.
Confidence intervals are a range of values around some number, such as a sensitivity value, that show you the possible range of values that are compatible with your data. They’re a way to indicate where you may find your result if you were to repeat your experiment. Such information is critical, because if you’re basing key decisions on a particular number which might actually be different in reality, you could end up with serious problems.
Let’s take an example. Let’s say a COVID-19 test is quoted with a sensitivity and specificity of 88% and 90%, respectively. Given the number of cases which fell into each category during testing (true positives, false positive, true negatives and false negatives), we could calculate the confidence intervals.
Let’s say we do this and end up with a sensitivity of 88% (85% to 92%, 95% CI) and a specificity of 90% (84% to 95%, , 95% CI), where the ‘95% CI’ indicates it’s a 95% confidence interval (see more on this in this blog post).
In essence, this COVID–19 could have a sensitivity as low as 85% and a specificity as low as 84%. That gives us an LR+ of 5.3 and an LR- of 0.18. What does this mean in practice?
Let’s say your estimated pre-test probability is 0.1. A positive test result in this case would give you a post-test probability of around 0.38, which is still low (see image below). Do you remain in isolation with a probability of 0.38? What if you have a critical job? Has the test really achieved anything?
Likewise, in a previous example dealing with front-line member of medical staff, their pre-test probability might be estimated to be 0.95. If this test gives you a negative result, the resulting post-test probability is 0.78 (see image below). Still very high.
Closing thoughtsWe’ve seen that the results of rapid, point-of-care yes/no diagnostic tests, which are never perfect, can be placed into a meaningful context using Bayesian statistics and the concept of a pre-test probability. A positive result does not necessarily mean that the person has had COVID-19, especially if they’re in an isolated hamlet in the Scottish Highlights (for the purpose of this illustration, please ignore the fact that people are flocking to the highlands to self-isolate). Likewise, a negative result does not necessary mean that the person has not had COVID-19, especially if they’re just spent 4 weeks on the front-line treating hundreds of patients with the virus.
Context matters, and in these frantic times of testing, such details may be important.
As stated at the start, this article is just an example of some statistical ideas and is in no way meant to offer any sort of guidance with regards to COVID-19. | [
{
"code": null,
"e": 312,
"s": 171,
"text": "Note: I am not a medical professional and this blog is just my take on what I believe are statistical ideas pertinent to diagnostic testing."
},
{
"code": null,
"e": 501,
"s": 312,
"text": "Testing for COVID-19You need no introduction to COVID-19, the coronovirus that’s now spread to every country on Earth and is wreaking havoc on economies, health systems and people’s lives."
},
{
"code": null,
"e": 866,
"s": 501,
"text": "Beyond social distancing, one of the priorities for governments the world over is to test as many of its citizens as possible, both to see who currently has the virus (the antigen test) and to see who has already had it (the antibody test). Note that in this blog post, I’ll be using ‘positive’ to mean that an antibody is detected and the person has had COVID-19."
},
{
"code": null,
"e": 973,
"s": 866,
"text": "So far, so good. You roll out the tests and assess the population, then certain people can return to work."
},
{
"code": null,
"e": 1478,
"s": 973,
"text": "Evaluating a yes/no diagnostic testThe problem comes when you look down at the test cartridge (typically a point-of-care lateral flow device, similar to how a home pregnancy test works) and see the result. These tests give a ‘positive’ or a ‘negative’ result, and we often hear that such tests are evaluated by their accuracy. We hear it on the news all the time. You run a test that’s 99% accurate, get a positive result, so it’s easy to assume that probability of you having had COVID-19 is 99%, right?"
},
{
"code": null,
"e": 1489,
"s": 1478,
"text": "Not quite."
},
{
"code": null,
"e": 1792,
"s": 1489,
"text": "Accuracy is the number of cases, positive or negative, that a test correctly identified during some sort of evaluation. The problem with this way of quoting how good a positive/negative test is, is that it doesn’t distinguish between the positives that it got right and the negatives that it got right."
},
{
"code": null,
"e": 2147,
"s": 1792,
"text": "Imagine you have a test that fundamentally doesn’t work. It just says ‘positive’ every single time you run it, regardless of the patient, the condition, etc. You test it on a random group of medical staff, 98 of whom are known to have had COVID-19 and 2 who haven’t. Your bogus test, diagnosing everyone as positive, would end up with an accuracy of 98%!"
},
{
"code": null,
"e": 2308,
"s": 2147,
"text": "Thankfully, there are better ways to summarise the effectiveness of such tests, the most common being sensitivity and specificity. These are defined as follows,"
},
{
"code": null,
"e": 2803,
"s": 2308,
"text": "Notice the denominators. For sensitivity, we have ‘true positives’, which are of course positives, and ‘false negatives’, which are also positives. So, sensitivity only deals with positive cases, and the logic is the same with specificity for negative cases. The result is that sensitivity is a measure of the probability of getting a positive result out of all the positive cases, and that specificity is a measure of the probability of getting a negative result out of all the negative cases."
},
{
"code": null,
"e": 2980,
"s": 2803,
"text": "Another way of phrasing this is that sensitivity is the probability of getting a positive result, given that you have had the disease, which is written as P(+ve result|Disease)"
},
{
"code": null,
"e": 3193,
"s": 2980,
"text": "However, in practice, we’re interested in the opposite of this, namely the probability of having had the disease, given a positive test result, i.e. P(Disease|+ve result). So, in practice, how do we do this flip?"
},
{
"code": null,
"e": 3531,
"s": 3193,
"text": "Enter Reverend BayesThomas Bayes was born in England in 1701. He spent most of his life focused on the Church and only published a single work on mathematics. In later life he developed an interest in probability, possibly motivated by wishing to refute David Hume’s argument against taking personal testimonials as evidence of miracles."
},
{
"code": null,
"e": 3842,
"s": 3531,
"text": "After his death, a friend found and handed in manuscripts on probability to the Royal Society, to which Bayes had been elected a fellow in 1742. One of the essays contained within, titled ‘An Essay towards solving a Problem in the Doctrine of Chances’, led to what is today known as Bayes’ theorem, defined as,"
},
{
"code": null,
"e": 4189,
"s": 3842,
"text": "Note the first term on the left and the first on the right. Here we can see the ‘flip’ that we’re after, i.e. obtaining P(Disease|+ve result) when we know P(+ve result|Disease), along with a few other terms which we’ll get to soon. This theorem in turn (after refinement by Pierre-Simon Laplace) led to what is today known as Bayesian statistics."
},
{
"code": null,
"e": 4805,
"s": 4189,
"text": "The prevailing type of statistics and that used in many applications is known as frequentist statistics. This approach assigns probabilities based upon the frequency of events that occur in a sample. In contrast, in the Bayesian mindset, probabilities are related to our current level of knowledge about an event. This latter approach allows the introduction of something called a prior or pretest probability (explained in more detail below), which is a probability assigned before data is collected on an event. This pre-test probability is combined with new evidence to give a posterior or post-test probability."
},
{
"code": null,
"e": 5440,
"s": 4805,
"text": "In the Bayes’ theorem, P(A) is the probability of having had the disease and P(B) is the probability of getting a positive result. What are these values? P(A) is the pre-test probability (mentioned above), for which local disease prevalence is often used. Alternatively, a pre-test probability can also be estimated from a detailed medical examination, a review of a patient’s records, etc. P(B) is the combination of all the ways a positive result could be obtained, i.e. the patient could have had the disease and received a positive result or the patient could not have had the disease and received a positive result. Specifically,"
},
{
"code": null,
"e": 5552,
"s": 5440,
"text": "In practice, such calculations are usually done using something called likelihood ratios. These are defined as,"
},
{
"code": null,
"e": 6028,
"s": 5552,
"text": "Where LR+ is the positive likelihood ratio and LR- is the negative likelihood ratio. They allow you to go from a pre-test probability to a post-test probability using a graphical tool called a Fagan nomogram. Alternatively, the calculation can be quickly performed using a computer. They also give you an indication of the effectiveness of a test, as they tell you how much your pre-test probability will be affected by either a positive or negative result (see table below)."
},
{
"code": null,
"e": 6103,
"s": 6028,
"text": "The exact calculation involves switching from probabilities to odds using,"
},
{
"code": null,
"e": 6322,
"s": 6103,
"text": "Taking a look at some of the COVID-19 tests that are being used around the world, values for sensitivity seem to be around 91% and specificity around 99%. That gives us a LR+ of 91 and a LR- of 0.09. Pretty impressive."
},
{
"code": null,
"e": 6610,
"s": 6322,
"text": "We now have all the pieces of the puzzle to work out, given a positive result, what the probability of having had COVID-19 is for a given individual. First, let’s assume you run the test in an area that has a prevalence of 1% and get a positive result. What is the post-test probability?"
},
{
"code": null,
"e": 6744,
"s": 6610,
"text": "There we have it. The probability that an individual has had COVID-19 after a positive result from a fantastic test is less than 50%."
},
{
"code": null,
"e": 7412,
"s": 6744,
"text": "Now, imagine if Tom Hanks had suspected COVID-19. No, not the real Tom Hanks, who did actually get COVID-19. I mean Chuck Noland, the character Tom Hanks plays in the film Castaway. If, via a highly convoluted turn of events, Chuck Noland, stranded for years on a desert island, found a COVID-19 rapid point-of-care test washed up on the beach and decided to run it because he had had a bit of a cough, what would it mean if it gave him a positive result? Well, the pre-test probability is zero, which means the post-test probability is also zero. Running the test is a complete waste of time! (not that that is much of an issue when you’re stuck on a desert island)."
},
{
"code": null,
"e": 8148,
"s": 7412,
"text": "Now let’s flip it the other way. You run the test on medical staff who have been working endless hours in an emergency COVID-19 shelter, without sufficient personal protective equipment. They’ve all had symptoms but have since recovered. The patients that they’ve been treating all had severe symptoms. They’re were all struggling to breathe. They all had a fever. They’ve all had contact with family members that were themselves confirmed cases. It’s the middle of summer, with very low rates of the common cold and the flu. It’s hard to say what the prevalence is, so you use the method of using (past) clinical symptoms and patient history. You estimate a pre-test probability for each staff member to be 0.95. Here are the numbers,"
},
{
"code": null,
"e": 8319,
"s": 8148,
"text": "You’ve gone from a pre-test probability of 0.95 to a post-test probability of, effectively, 1. Not particularly surprising. Again, this test was arguably a waste of time."
},
{
"code": null,
"e": 8950,
"s": 8319,
"text": "Triaging TestsThe conclusion from this is that, given you’re likely to have a shortage of tests, does it make sense to test people who have an extremely low or an extremely high pre-test probability? After all, at the end of the day, what you do after you’ve run the test probably won’t change. If you’re pretty sure someone has had COVID-19 and the plan is to allow them to leave isolation, using up a precious test which comes back positive isn’t going to change things. Even if someone has a pre-test probability of 0.95 and they get a negative result, that doesn’t change things dramatically either (based upon the LR- above),"
},
{
"code": null,
"e": 9282,
"s": 8950,
"text": "We get a post-test probability of 0.63. If in the doctor’s mind they’re thinking “I’ll allow a member of the team return to work if they have a post-test probability over 0.5 or above”, this negative result doesn’t change anything. They would have been allowed to return before the test. They’ll be allowed to return after it, too."
},
{
"code": null,
"e": 9492,
"s": 9282,
"text": "This ‘treatment threshold’ is easier to see with a plot. Below is a Python function that works out the post-test probability for a given pre-test probability, with given values for sensitivity and specificity."
},
{
"code": null,
"e": 9896,
"s": 9492,
"text": "def diagnostic_posttest(pretest,sens,spec): lr_pos = sens / (1 - spec) lr_neg = (1 - sens) / spec pretest_odds = pretest / (1-pretest) posttest_odds_pos = pretest_odds * lr_pos posttest_odds_neg = pretest_odds * lr_neg posttest_pos = posttest_odds_pos / (1+posttest_odds_pos) posttest_neg = posttest_odds_neg / (1+posttest_odds_neg) return(posttest_pos, posttest_neg)"
},
{
"code": null,
"e": 10069,
"s": 9896,
"text": "We can use this function along with sensitivity and specificity values similar to those in the real-world to create a plot of pre-test probability vs post-test probability,"
},
{
"code": null,
"e": 10530,
"s": 10069,
"text": "import numpy as npimport matplotlib.pyplot as pltpost = list()prev_options = np.arange(0.0, 1.0, 0.01)for i in prev_options: post_temp = diagnostic_posttest(i,0.91,0.99)[0] post.append(post_temp)fig, ax = plt.subplots()ax.plot(prev_options, post)plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.0])plt.rcParams['font.size'] = 12plt.title('Pretest vs Posttest Probability (sens = 0.91, spec = 0.99)')plt.xlabel('Pretest Probability')plt.ylabel('Posttest Probability')"
},
{
"code": null,
"e": 10578,
"s": 10530,
"text": "Here is what we get for a positive test result,"
},
{
"code": null,
"e": 10610,
"s": 10578,
"text": "And for a negative test result,"
},
{
"code": null,
"e": 10843,
"s": 10610,
"text": "As you can see for a positive result, as the pre-test probability increases the post-test probability shoots up rapidly. For a negative result, you need a very high pre-test probability for the post-test probability to also be high."
},
{
"code": null,
"e": 10988,
"s": 10843,
"text": "How Confident?There’s one more aspect to all of this. The numbers typically quoted for COVID-19 tests do not often include confidence intervals."
},
{
"code": null,
"e": 11433,
"s": 10988,
"text": "Confidence intervals are a range of values around some number, such as a sensitivity value, that show you the possible range of values that are compatible with your data. They’re a way to indicate where you may find your result if you were to repeat your experiment. Such information is critical, because if you’re basing key decisions on a particular number which might actually be different in reality, you could end up with serious problems."
},
{
"code": null,
"e": 11743,
"s": 11433,
"text": "Let’s take an example. Let’s say a COVID-19 test is quoted with a sensitivity and specificity of 88% and 90%, respectively. Given the number of cases which fell into each category during testing (true positives, false positive, true negatives and false negatives), we could calculate the confidence intervals."
},
{
"code": null,
"e": 11969,
"s": 11743,
"text": "Let’s say we do this and end up with a sensitivity of 88% (85% to 92%, 95% CI) and a specificity of 90% (84% to 95%, , 95% CI), where the ‘95% CI’ indicates it’s a 95% confidence interval (see more on this in this blog post)."
},
{
"code": null,
"e": 12148,
"s": 11969,
"text": "In essence, this COVID–19 could have a sensitivity as low as 85% and a specificity as low as 84%. That gives us an LR+ of 5.3 and an LR- of 0.18. What does this mean in practice?"
},
{
"code": null,
"e": 12458,
"s": 12148,
"text": "Let’s say your estimated pre-test probability is 0.1. A positive test result in this case would give you a post-test probability of around 0.38, which is still low (see image below). Do you remain in isolation with a probability of 0.38? What if you have a critical job? Has the test really achieved anything?"
},
{
"code": null,
"e": 12719,
"s": 12458,
"text": "Likewise, in a previous example dealing with front-line member of medical staff, their pre-test probability might be estimated to be 0.95. If this test gives you a negative result, the resulting post-test probability is 0.78 (see image below). Still very high."
},
{
"code": null,
"e": 13412,
"s": 12719,
"text": "Closing thoughtsWe’ve seen that the results of rapid, point-of-care yes/no diagnostic tests, which are never perfect, can be placed into a meaningful context using Bayesian statistics and the concept of a pre-test probability. A positive result does not necessarily mean that the person has had COVID-19, especially if they’re in an isolated hamlet in the Scottish Highlights (for the purpose of this illustration, please ignore the fact that people are flocking to the highlands to self-isolate). Likewise, a negative result does not necessary mean that the person has not had COVID-19, especially if they’re just spent 4 weeks on the front-line treating hundreds of patients with the virus."
},
{
"code": null,
"e": 13499,
"s": 13412,
"text": "Context matters, and in these frantic times of testing, such details may be important."
}
]
|
Copy all rows of a table to another table in MySQL? | To copy all rows of a table to another table, use the below syntax −
insert into yourTableName2(yourColumnName1,...N) select yourColumnName1,..N from yourTableName1;
Let us first create a table −
mysql> create table DemoTable1(FirstName varchar(100));
Query OK, 0 rows affected (1.11 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values('John');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values('Bob');
Query OK, 1 row affected (0.40 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| John |
| Chris |
| Bob |
+-----------+
3 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2 (EmployeeName varchar(100));
Query OK, 0 rows affected (0.78 sec)
Following is the query to copy all rows of a table to another table −
mysql> insert into DemoTable2(EmployeeName) select FirstName from DemoTable1;
Query OK, 3 rows affected (0.52 sec)
Records: 3 Duplicates: 0 Warnings: 0
Let us now check the records of the 2nd table, wherein we have set the records of 1st table −
mysql> select *from DemoTable2;
This will produce the following output −
+--------------+
| EmployeeName |
+--------------+
| John |
| Chris |
| Bob |
+--------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To copy all rows of a table to another table, use the below syntax −"
},
{
"code": null,
"e": 1228,
"s": 1131,
"text": "insert into yourTableName2(yourColumnName1,...N) select yourColumnName1,..N from yourTableName1;"
},
{
"code": null,
"e": 1258,
"s": 1228,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1351,
"s": 1258,
"text": "mysql> create table DemoTable1(FirstName varchar(100));\nQuery OK, 0 rows affected (1.11 sec)"
},
{
"code": null,
"e": 1407,
"s": 1351,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1653,
"s": 1407,
"text": "mysql> insert into DemoTable1 values('John');\nQuery OK, 1 row affected (0.31 sec)\nmysql> insert into DemoTable1 values('Chris');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1 values('Bob');\nQuery OK, 1 row affected (0.40 sec)"
},
{
"code": null,
"e": 1713,
"s": 1653,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1745,
"s": 1713,
"text": "mysql> select *from DemoTable1;"
},
{
"code": null,
"e": 1786,
"s": 1745,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1909,
"s": 1786,
"text": "+-----------+\n| FirstName |\n+-----------+\n| John |\n| Chris |\n| Bob |\n+-----------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1957,
"s": 1909,
"text": "Following is the query to create second table −"
},
{
"code": null,
"e": 2054,
"s": 1957,
"text": "mysql> create table DemoTable2 (EmployeeName varchar(100));\nQuery OK, 0 rows affected (0.78 sec)"
},
{
"code": null,
"e": 2124,
"s": 2054,
"text": "Following is the query to copy all rows of a table to another table −"
},
{
"code": null,
"e": 2276,
"s": 2124,
"text": "mysql> insert into DemoTable2(EmployeeName) select FirstName from DemoTable1;\nQuery OK, 3 rows affected (0.52 sec)\nRecords: 3 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2370,
"s": 2276,
"text": "Let us now check the records of the 2nd table, wherein we have set the records of 1st table −"
},
{
"code": null,
"e": 2402,
"s": 2370,
"text": "mysql> select *from DemoTable2;"
},
{
"code": null,
"e": 2443,
"s": 2402,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2587,
"s": 2443,
"text": "+--------------+\n| EmployeeName |\n+--------------+\n| John |\n| Chris |\n| Bob |\n+--------------+\n3 rows in set (0.00 sec)"
}
]
|
Aptitude - Boats & Streams Online Quiz | Following quiz provides Multiple Choice Questions (MCQs) related to Boats & Streams. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz.
Q 1 - A man columns 30 km downstream and 18 km upstream, taking 5 hours every time. Every time what is the speed of the current?
A - 1.2 km/hr
B - 1 km/hr
C - 2 km/hr
D - 1.5 km/hr
Speed downstream = 30/5 km/hr = 6km/hr`Speed upstream = 18/5 km/hr = 3.6 km/hr`Speed of the current = 1/2 (6-3.6) km/hr = 2.4/2 km/hr = 1.2 km/hr
Q 2 - A man can push 30km upstream and 44km downstream in 10 hours. Additionally, he can push 40km upstream and 55km downstream in 13 hours. Discover the rate of flow and the current of the man in still water.
A - 4,5 km/hr
B - 5,6 km/hr
C - 3,8 km/hr
D - 7,9 km/hr
Let speed upstream be x km/hr and the velocity downstream be y km/hr`At that point, 30/x+44/y=10 ... (i) and 40/x+55/y=13 ... (ii)`Increasing (ii) by 4, (i) by 5 and subtracting, we get: 10/x=2=>x=5.`Putting x=5in (i) we get 4y=44=> y=11.`∴ Speed upstream =5km/hr, speed downstream=11km/hr.`Velocity of the current =1/2(11-5) km/hr=3km/hr.`Velocity of man in still water =1/2(11+5) km/hr=8km.
Q 3 - A boat running downstream covers 24kms in 4 hours, while for covering the same separation upstream it takes 6 hours. What is the velocity of the watercraft in still water?
A - 3.5 km/hr
B - 5 km/hr
C - 6.5 km/hr
D - 7 km/hr.
Speed downstream =24/4km/hr=6 km/hr.`Speed upstream =24/6 km/hr=6 km/hr.`Speed of the boat in still water=1/2(6+4) km/hr=5 km/hr.
Q 4 - A watercraft covers a separation of 30km in 5/2 hrs running downstream. While returning, it covers the same separation 15/4hrs .What is the velocity of the watercraft in still water?
A - 8 km/hr
B - 12 km/hr
C - 14 km/hr
D - 10 km/hr.
Speed downstream = (30*2/5) km/hr=12km/hr.`Speed upstream= (30*4/15) km/hr=8 km/hr.`Speed of boat in still water=1/2(12+8) km/hr=10 km/hr.
Q 5 - The velocity of a speedboat is that of the flow of water as 36:5. The vessel obliges the current in 5 hours 10min. It will return:
A - 5 hrs 50 min
B - 6 hours
C - 6 hours 50 min
D - 12 hrs 10 min
Let the speed of motorboat be 36x km/hr and that of the current of water be 5x km/hr.`Speed downstream = (36x+ 5x) km/hr=41x km/hr,`Speed upstream = (36x-5x) km/hr=31x km/hr.`Distance covers downstream = (41x*31/6) km.`Distance upstream= [(41*31) x/6 * 1/31x] hrs = 41/6 hrs = 6 hrs 50 min.
Q 6 - Aman can push at 5 km/hr in still Water. It the stream is running at 1km/hr, it takes him 75 min. to line to a spot and back. How far is the spot?
A - 2.5 km
B - 3 km
C - 4 km
D - 5 km
Speed downstream = (5+1) km/hr=6 km/hr`Speed upstream = (5-1) km/hr=4 km/hr.`Let the required distance be x km. Then,`x/6+ x/4=75/60 = 5/4 => (2x+3x) =15 => 5x = 15 => x=3.`Required distance =3km.
Q 7 - A vessel goes 6 km in an hour in still water. It requires thrice as much investment in covering the same separation against the current. Velocity of the current is:
A - 16 km/hr
B - 18 km/hr
C - 24 km/hr
D - 28 km/hr.
Let the speed of the steamer in still water be x km/hr.`Speed downstream = (x +2) km/hr, speed upstream = (x-2) km/hr.`Then 4 (x+2) = 5 (x-2) => x = 18.`Hence, the speed of the streamer in still water is 18 km/hr.
Q 8 - Aman can push 15/2 kms an hour in still water and he finds that it takes him twice as long to down the stream. The rate of the stream is:
A - 2.4 km/hr
B - 2.5 km/hr
C - 3.4 km/hr
D - 3.5 km/hr
Let the rate of stream be x km/hr. Then,`Speed downstream = (15/2 +x) km/hr, Speed upstream = (15/2 - x) km/hr`(15/2 +x) = 2 (15/2 -x) => 3x =15/2 => x = 15/2*3 = 5/2 = 2.5`∴ Rate of stream=2.5 km/hr
Q 9 - A boatman goes 2km against the current of stream in 40 min. what's more, comes back to the same spot in 30 min. What is his rate of paddling in still water?
A - 5 km/hr
B - 6 km/hr
C - 7 km/hr
D - 8 km/hr
Distance covered upstream in 40min = 4 km.`Distance covered upstream in 60 min = (4/40*60) km= 6 km`Distance covered downstream a in 30 min = 4 km`Distance covered downstream in 60 min = (4/30 * 60) km = 8 km.`Speed upstream =3 km/hr, speed downstream =4 km/hr.`Speed in still water = 1/2 (6 +8) km/hr=7 km /hr.
Q 10 - The current of a stream keeps running at 1 km/hr .A speedboat goes 35km upstream and back again to the beginning stage in 12 hours . The rate of the speedboat in still water is:
A - 6 km/hr
B - 7 km/hr
C - 8.5 km/hr
D - 8 km/hr
Let the still water be x km/hr.`Speed downstream =(x+1) km/hr Speed upstream =(x-1) km/hr.`35/(x-1) + 35/(x+1) = 12 =>35[(x+1) + (x-1)] = 12 (x2-1)`=> 12x2 -70x -12=0=> 12x2-72x + 2x -12=0`=> 12x (x- 6) +2 (x - 6) = 0 =>(x-6) (12x + 2) = 0 => x=6`∴ Speed of boat in still water is 6 km/hr.
87 Lectures
22.5 hours
Programming Line
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 4221,
"s": 3892,
"text": "Following quiz provides Multiple Choice Questions (MCQs) related to Boats & Streams. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz."
},
{
"code": null,
"e": 4350,
"s": 4221,
"text": "Q 1 - A man columns 30 km downstream and 18 km upstream, taking 5 hours every time. Every time what is the speed of the current?"
},
{
"code": null,
"e": 4365,
"s": 4350,
"text": "A - 1.2 km/hr "
},
{
"code": null,
"e": 4378,
"s": 4365,
"text": "B - 1 km/hr "
},
{
"code": null,
"e": 4391,
"s": 4378,
"text": "C - 2 km/hr "
},
{
"code": null,
"e": 4406,
"s": 4391,
"text": "D - 1.5 km/hr "
},
{
"code": null,
"e": 4552,
"s": 4406,
"text": "Speed downstream = 30/5 km/hr = 6km/hr`Speed upstream = 18/5 km/hr = 3.6 km/hr`Speed of the current = 1/2 (6-3.6) km/hr = 2.4/2 km/hr = 1.2 km/hr"
},
{
"code": null,
"e": 4762,
"s": 4552,
"text": "Q 2 - A man can push 30km upstream and 44km downstream in 10 hours. Additionally, he can push 40km upstream and 55km downstream in 13 hours. Discover the rate of flow and the current of the man in still water."
},
{
"code": null,
"e": 4776,
"s": 4762,
"text": "A - 4,5 km/hr"
},
{
"code": null,
"e": 4790,
"s": 4776,
"text": "B - 5,6 km/hr"
},
{
"code": null,
"e": 4804,
"s": 4790,
"text": "C - 3,8 km/hr"
},
{
"code": null,
"e": 4818,
"s": 4804,
"text": "D - 7,9 km/hr"
},
{
"code": null,
"e": 5211,
"s": 4818,
"text": "Let speed upstream be x km/hr and the velocity downstream be y km/hr`At that point, 30/x+44/y=10 ... (i) and 40/x+55/y=13 ... (ii)`Increasing (ii) by 4, (i) by 5 and subtracting, we get: 10/x=2=>x=5.`Putting x=5in (i) we get 4y=44=> y=11.`∴ Speed upstream =5km/hr, speed downstream=11km/hr.`Velocity of the current =1/2(11-5) km/hr=3km/hr.`Velocity of man in still water =1/2(11+5) km/hr=8km."
},
{
"code": null,
"e": 5389,
"s": 5211,
"text": "Q 3 - A boat running downstream covers 24kms in 4 hours, while for covering the same separation upstream it takes 6 hours. What is the velocity of the watercraft in still water?"
},
{
"code": null,
"e": 5403,
"s": 5389,
"text": "A - 3.5 km/hr"
},
{
"code": null,
"e": 5415,
"s": 5403,
"text": "B - 5 km/hr"
},
{
"code": null,
"e": 5429,
"s": 5415,
"text": "C - 6.5 km/hr"
},
{
"code": null,
"e": 5442,
"s": 5429,
"text": "D - 7 km/hr."
},
{
"code": null,
"e": 5572,
"s": 5442,
"text": "Speed downstream =24/4km/hr=6 km/hr.`Speed upstream =24/6 km/hr=6 km/hr.`Speed of the boat in still water=1/2(6+4) km/hr=5 km/hr."
},
{
"code": null,
"e": 5761,
"s": 5572,
"text": "Q 4 - A watercraft covers a separation of 30km in 5/2 hrs running downstream. While returning, it covers the same separation 15/4hrs .What is the velocity of the watercraft in still water?"
},
{
"code": null,
"e": 5773,
"s": 5761,
"text": "A - 8 km/hr"
},
{
"code": null,
"e": 5786,
"s": 5773,
"text": "B - 12 km/hr"
},
{
"code": null,
"e": 5799,
"s": 5786,
"text": "C - 14 km/hr"
},
{
"code": null,
"e": 5813,
"s": 5799,
"text": "D - 10 km/hr."
},
{
"code": null,
"e": 5952,
"s": 5813,
"text": "Speed downstream = (30*2/5) km/hr=12km/hr.`Speed upstream= (30*4/15) km/hr=8 km/hr.`Speed of boat in still water=1/2(12+8) km/hr=10 km/hr."
},
{
"code": null,
"e": 6089,
"s": 5952,
"text": "Q 5 - The velocity of a speedboat is that of the flow of water as 36:5. The vessel obliges the current in 5 hours 10min. It will return:"
},
{
"code": null,
"e": 6106,
"s": 6089,
"text": "A - 5 hrs 50 min"
},
{
"code": null,
"e": 6118,
"s": 6106,
"text": "B - 6 hours"
},
{
"code": null,
"e": 6137,
"s": 6118,
"text": "C - 6 hours 50 min"
},
{
"code": null,
"e": 6155,
"s": 6137,
"text": "D - 12 hrs 10 min"
},
{
"code": null,
"e": 6446,
"s": 6155,
"text": "Let the speed of motorboat be 36x km/hr and that of the current of water be 5x km/hr.`Speed downstream = (36x+ 5x) km/hr=41x km/hr,`Speed upstream = (36x-5x) km/hr=31x km/hr.`Distance covers downstream = (41x*31/6) km.`Distance upstream= [(41*31) x/6 * 1/31x] hrs = 41/6 hrs = 6 hrs 50 min."
},
{
"code": null,
"e": 6599,
"s": 6446,
"text": "Q 6 - Aman can push at 5 km/hr in still Water. It the stream is running at 1km/hr, it takes him 75 min. to line to a spot and back. How far is the spot?"
},
{
"code": null,
"e": 6611,
"s": 6599,
"text": "A - 2.5 km "
},
{
"code": null,
"e": 6620,
"s": 6611,
"text": "B - 3 km"
},
{
"code": null,
"e": 6629,
"s": 6620,
"text": "C - 4 km"
},
{
"code": null,
"e": 6638,
"s": 6629,
"text": "D - 5 km"
},
{
"code": null,
"e": 6835,
"s": 6638,
"text": "Speed downstream = (5+1) km/hr=6 km/hr`Speed upstream = (5-1) km/hr=4 km/hr.`Let the required distance be x km. Then,`x/6+ x/4=75/60 = 5/4 => (2x+3x) =15 => 5x = 15 => x=3.`Required distance =3km."
},
{
"code": null,
"e": 7006,
"s": 6835,
"text": "Q 7 - A vessel goes 6 km in an hour in still water. It requires thrice as much investment in covering the same separation against the current. Velocity of the current is:"
},
{
"code": null,
"e": 7019,
"s": 7006,
"text": "A - 16 km/hr"
},
{
"code": null,
"e": 7032,
"s": 7019,
"text": "B - 18 km/hr"
},
{
"code": null,
"e": 7045,
"s": 7032,
"text": "C - 24 km/hr"
},
{
"code": null,
"e": 7059,
"s": 7045,
"text": "D - 28 km/hr."
},
{
"code": null,
"e": 7273,
"s": 7059,
"text": "Let the speed of the steamer in still water be x km/hr.`Speed downstream = (x +2) km/hr, speed upstream = (x-2) km/hr.`Then 4 (x+2) = 5 (x-2) => x = 18.`Hence, the speed of the streamer in still water is 18 km/hr."
},
{
"code": null,
"e": 7417,
"s": 7273,
"text": "Q 8 - Aman can push 15/2 kms an hour in still water and he finds that it takes him twice as long to down the stream. The rate of the stream is:"
},
{
"code": null,
"e": 7431,
"s": 7417,
"text": "A - 2.4 km/hr"
},
{
"code": null,
"e": 7445,
"s": 7431,
"text": "B - 2.5 km/hr"
},
{
"code": null,
"e": 7459,
"s": 7445,
"text": "C - 3.4 km/hr"
},
{
"code": null,
"e": 7473,
"s": 7459,
"text": "D - 3.5 km/hr"
},
{
"code": null,
"e": 7673,
"s": 7473,
"text": "Let the rate of stream be x km/hr. Then,`Speed downstream = (15/2 +x) km/hr, Speed upstream = (15/2 - x) km/hr`(15/2 +x) = 2 (15/2 -x) => 3x =15/2 => x = 15/2*3 = 5/2 = 2.5`∴ Rate of stream=2.5 km/hr"
},
{
"code": null,
"e": 7836,
"s": 7673,
"text": "Q 9 - A boatman goes 2km against the current of stream in 40 min. what's more, comes back to the same spot in 30 min. What is his rate of paddling in still water?"
},
{
"code": null,
"e": 7848,
"s": 7836,
"text": "A - 5 km/hr"
},
{
"code": null,
"e": 7860,
"s": 7848,
"text": "B - 6 km/hr"
},
{
"code": null,
"e": 7872,
"s": 7860,
"text": "C - 7 km/hr"
},
{
"code": null,
"e": 7884,
"s": 7872,
"text": "D - 8 km/hr"
},
{
"code": null,
"e": 8196,
"s": 7884,
"text": "Distance covered upstream in 40min = 4 km.`Distance covered upstream in 60 min = (4/40*60) km= 6 km`Distance covered downstream a in 30 min = 4 km`Distance covered downstream in 60 min = (4/30 * 60) km = 8 km.`Speed upstream =3 km/hr, speed downstream =4 km/hr.`Speed in still water = 1/2 (6 +8) km/hr=7 km /hr."
},
{
"code": null,
"e": 8381,
"s": 8196,
"text": "Q 10 - The current of a stream keeps running at 1 km/hr .A speedboat goes 35km upstream and back again to the beginning stage in 12 hours . The rate of the speedboat in still water is:"
},
{
"code": null,
"e": 8393,
"s": 8381,
"text": "A - 6 km/hr"
},
{
"code": null,
"e": 8405,
"s": 8393,
"text": "B - 7 km/hr"
},
{
"code": null,
"e": 8419,
"s": 8405,
"text": "C - 8.5 km/hr"
},
{
"code": null,
"e": 8431,
"s": 8419,
"text": "D - 8 km/hr"
},
{
"code": null,
"e": 8724,
"s": 8431,
"text": "Let the still water be x km/hr.`Speed downstream =(x+1) km/hr Speed upstream =(x-1) km/hr.`35/(x-1) + 35/(x+1) = 12 =>35[(x+1) + (x-1)] = 12 (x2-1)`=> 12x2 -70x -12=0=> 12x2-72x + 2x -12=0`=> 12x (x- 6) +2 (x - 6) = 0 =>(x-6) (12x + 2) = 0 => x=6`∴ Speed of boat in still water is 6 km/hr."
},
{
"code": null,
"e": 8760,
"s": 8724,
"text": "\n 87 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 8778,
"s": 8760,
"text": " Programming Line"
},
{
"code": null,
"e": 8785,
"s": 8778,
"text": " Print"
},
{
"code": null,
"e": 8796,
"s": 8785,
"text": " Add Notes"
}
]
|
Binary Heap in Data Structure | Heap or Binary Heap is a special case of balanced binary tree data structure. This is complete binary tree structure. So up to l-1 levels it is full, and at l level, all nodes are from left. Here the root-node key is compared with its children and arranged accordingly. If a has child node b then −
key(a) ≥ key(b)
As the value of parent is greater than that of child, this property generates Max Heap. Based on this criteria, a heap can be of two types the Max Heap and the Min Heap.
These are examples of Max and Min Heap respectively − | [
{
"code": null,
"e": 1361,
"s": 1062,
"text": "Heap or Binary Heap is a special case of balanced binary tree data structure. This is complete binary tree structure. So up to l-1 levels it is full, and at l level, all nodes are from left. Here the root-node key is compared with its children and arranged accordingly. If a has child node b then −"
},
{
"code": null,
"e": 1377,
"s": 1361,
"text": "key(a) ≥ key(b)"
},
{
"code": null,
"e": 1547,
"s": 1377,
"text": "As the value of parent is greater than that of child, this property generates Max Heap. Based on this criteria, a heap can be of two types the Max Heap and the Min Heap."
},
{
"code": null,
"e": 1601,
"s": 1547,
"text": "These are examples of Max and Min Heap respectively −"
}
]
|
Bootstrap complex form layout for combined vertical/inline fields with HTML | Bootstrap form for combined vertical/ inline fields −
<div class="row">
<div class="col-md-8">
<div class="row">
<div class="col-md-3">
Left side
</div>
<div class="col-md-9">
Right side
<div class="row">
<div class="col-md-12">
longer forms
</div>
</div>
<div class="row">
<div class="col-md-3">
shorter forms
</div>
<div class="col-md-3">
shorter forms
</div>
<div class="col-md-3">
shorter forms
</div>
<div class="col-md-3">
shorter forms
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
Right
</div>
</div> | [
{
"code": null,
"e": 1116,
"s": 1062,
"text": "Bootstrap form for combined vertical/ inline fields −"
},
{
"code": null,
"e": 1961,
"s": 1116,
"text": "<div class=\"row\">\n <div class=\"col-md-8\">\n <div class=\"row\">\n <div class=\"col-md-3\">\n Left side\n </div>\n <div class=\"col-md-9\">\n Right side\n <div class=\"row\">\n <div class=\"col-md-12\">\n longer forms\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-md-3\">\n shorter forms\n </div>\n <div class=\"col-md-3\">\n shorter forms\n </div>\n <div class=\"col-md-3\">\n shorter forms\n </div>\n <div class=\"col-md-3\">\n shorter forms\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class=\"col-md-4\">\n Right\n </div>\n</div>"
}
]
|
Numbers with exactly 3 divisors | 28 May, 2022
Given a number N, print all numbers in the range from 1 to N having exactly 3 divisors.
Examples:
Input : N = 16
Output : 4 9
4 and 9 have exactly three divisors.
Divisor
Input : N = 49
Output : 4 9 25 49
4, 9, 25 and 49 have exactly three divisors.
After having a close look at the examples mentioned above, you have noticed that all the required numbers are perfect squares and that too are only of primes numbers. The logic behind this is, such numbers can have only three numbers as their divisor and also that includes 1 and that number itself resulting into just a single divisor other than a number, so we can easily conclude that required are those numbers which are squares of prime numbers so that they can have only three divisors (1, the number itself and sqrt(number)). So all primes i, such that i*i is less than equal to N are three-prime numbers.
Note: We can generate all primes within a set using any sieve method efficiently and then we should all primes i, such that i*i <=N.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print all// three-primes smaller than// or equal to n using Sieve// of Eratosthenes#include <bits/stdc++.h>using namespace std; // Generates all primes upto n and// prints their squaresvoid numbersWith3Divisors(int n){ bool prime[n+1]; memset(prime, true, sizeof(prime)); prime[0] = prime[1] = 0; for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= n; i += p) prime[i] = false; } } // print squares of primes upto n. cout << "Numbers with 3 divisors :\n"; for (int i=0; i*i <= n ; i++) if (prime[i]) cout << i*i << " ";} // Driver programint main(){ // sieve(); int n = 96; numbersWith3Divisors(n); return 0;}
// Java program to print all// three-primes smaller than// or equal to n using Sieve// of Eratosthenesimport java.io.*;import java.util.*; class GFG{ // Generates all primes upto n // and prints their squares static void numbersWith3Divisors(int n) { boolean[] prime = new boolean[n+1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // print squares of primes upto n System.out.println("Numbers with 3 divisors : "); for (int i=0; i*i <= n ; i++) if (prime[i]) System.out.print(i*i + " "); } // Driver program public static void main (String[] args) { int n = 96; numbersWith3Divisors(n); }} // Contributed by Pramod Kumar
# Python3 program to print# all three-primes smaller than# or equal to n using Sieve# of Eratosthenes # Generates all primes upto n# and prints their squaresdef numbersWith3Divisors(n): prime=[True]*(n+1); prime[0] = prime[1] = False; p=2; while (p*p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p*2,n+1,p): prime[i] = False; p+=1; # print squares of primes upto n. print("Numbers with 3 divisors :"); i=0; while (i*i <= n): if (prime[i]): print(i*i,end=" "); i+=1; # Driver program n = 96;numbersWith3Divisors(n); # This code is contributed by mits
// C# program to print all// three-primes smaller than// or equal to n using Sieve// of Eratosthenes class GFG{ // Generates all primes upto n // and prints their squares static void numbersWith3Divisors(int n) { bool[] prime = new bool[n+1]; prime[0] = prime[1] = true; for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == false) { // Update all multiples of p for (int i = p*2; i <= n; i += p) prime[i] = true; } } // print squares of primes upto n System.Console.WriteLine("Numbers with 3 divisors : "); for (int i=0; i*i <= n ; i++) if (!prime[i]) System.Console.Write(i*i + " "); } // Driver program public static void Main() { int n = 96; numbersWith3Divisors(n); }} // This code is Contributed by mits
<?php// PHP program to print all three-primes// smaller than or equal to n using Sieve// of Eratosthenes // Generates all primes upto n and// prints their squaresfunction numbersWith3Divisors($n){ $prime = array_fill(0, $n + 1, true); $prime[0] = $prime[1] = false; for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // print squares of primes upto n. echo "Numbers with 3 divisors :\n"; for ($i = 0; $i * $i <= $n ; $i++) if ($prime[$i]) echo $i * $i . " ";} // Driver Code$n = 96;numbersWith3Divisors($n); // This code is contributed by mits?>
<script> // Javascript program to print all // three-primes smaller than // or equal to n using Sieve // of Eratosthenes // Generates all primes upto n and // prints their squares function numbersWith3Divisors(n) { let prime = new Array(n+1); prime.fill(true); prime[0] = prime[1] = 0; for (let p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p*2; i <= n; i += p) prime[i] = false; } } // print squares of primes upto n. document.write("Numbers with 3 divisors :" + "</br>"); for (let i = 0; i*i <= n ; i++) if (prime[i]) document.write(i*i + " "); } // sieve(); let n = 96; numbersWith3Divisors(n); // This code is contributed by mukesh07.</script>
Output:
Numbers with 3 divisors :
4 9 25 49
Time Complexity: O(sqrt(n))
Auxiliary Space: O(n)
Another Approach:
To print all numbers in the range from 1 to N having exactly 3 divisors, the main calculation is to find those which are squares of prime numbers and less than or equal to the number. We can do this as follows:
Start a loop for integer i from 2 to n.Check if i is prime or not, which can be done easily using the isPrime(n) method.If i is prime, check if its square is less than or equal to the given number. This will be checked only for squares of prime numbers, therefore reducing the number of checks.If the above condition is satisfied, the number will be printed and the loop will continue till i<=n.
Start a loop for integer i from 2 to n.
Check if i is prime or not, which can be done easily using the isPrime(n) method.
If i is prime, check if its square is less than or equal to the given number. This will be checked only for squares of prime numbers, therefore reducing the number of checks.
If the above condition is satisfied, the number will be printed and the loop will continue till i<=n.
In this way, no extra space will be required to store anything.
Here is an implementation of the above logic without using extra space;
C++
Java
Python3
C#
Javascript
// C++ program to print all// three-primes smaller than// or equal to n without using// extra space#include <bits/stdc++.h>using namespace std; void numbersWith3Divisors(int);bool isPrime(int); // Generates all primes upto n and// prints their squaresvoid numbersWith3Divisors(int n){ cout << "Numbers with 3 divisors : " << endl; for(int i = 2; i * i <= n; i++) { // Check prime if (isPrime(i)) { if (i * i <= n) { // Print numbers in // the order of // occurrence cout << i * i << " "; } } }} // Check if a number is prime or notbool isPrime(int n){ for(int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true;} // Driver codeint main(){ int n = 122; numbersWith3Divisors(n); return 0;} // This code is contributed by vishu2908
// Java program to print all// three-primes smaller than// or equal to n without using// extra spaceimport java.util.*; class GFG{ // 3 divisor logic implementation // check if a number is // prime or not // if it is a prime then // check if its square // is less than or equal to // the given number static void numbersWith3Divisors(int n) { System.out.println("Numbers with 3 divisors : "); for (int i = 2; i * i <= n; i++) { // Check prime if (isPrime(i)) { if (i * i <= n) { // Print numbers in // the order of // occurrence System.out.print(i * i + " "); } } } } // Check if a number is prime or not public static boolean isPrime(int n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } // Driver program public static void main(String[] args) { int n = 122; numbersWith3Divisors(n); }} // Contributed by Parag Pallav Singh
# Python3 program to print all# three-primes smaller than# or equal to n without using# extra space # 3 divisor logic implementation# check if a number is prime or# not if it is a prime then check# if its square is less than or# equal to the given numberdef numbersWith3Divisors(n): print("Numbers with 3 divisors : ") i = 2 while i * i <= n: # Check prime if (isPrime(i)): if (i * i <= n): # Print numbers in the order # of occurrence print(i * i, end = " ") i += 1 # Check if a number is prime or notdef isPrime(n): i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True # Driver coden = 122 numbersWith3Divisors(n) # This code is contributed by divyesh072019
// C# program to print all// three-primes smaller than// or equal to n without using// extra spaceusing System; class GFG{ // 3 divisor logic implementation// check if a number is prime or// not if it is a prime then check// if its square is less than or// equal to the given numberstatic void numbersWith3Divisors(int n){ Console.WriteLine("Numbers with 3 divisors : "); for(int i = 2; i * i <= n; i++) { // Check prime if (isPrime(i)) { if (i * i <= n) { // Print numbers in the order // of occurrence Console.Write(i * i + " "); } } }} // Check if a number is prime or notpublic static bool isPrime(int n){ for(int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true;} // Driver codestatic void Main(){ int n = 122; numbersWith3Divisors(n);}} // This code is contributed by divyeshrabadiya07
<script> // Javascript program to print all // three-primes smaller than // or equal to n without using // extra space // 3 divisor logic implementation // check if a number is prime or // not if it is a prime then check // if its square is less than or // equal to the given number function numbersWith3Divisors(n) { document.write("Numbers with 3 divisors : "); for(let i = 2; i * i <= n; i++) { // Check prime if (isPrime(i)) { if (i * i <= n) { // Print numbers in the order // of occurrence document.write(i * i + " "); } } } } // Check if a number is prime or not function isPrime(n) { if (n == 0 || n == 1) return false; for(let i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } let n = 122; numbersWith3Divisors(n); // This code is contributed by suresh07.</script>
Output:
Numbers with 3 divisors :
4 9 25 49 121
Time Complexity: O(sqrtN2)
Auxiliary Space: O(1)
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
ParagPallavSingh1
vishu2908
divyeshrabadiya07
divyesh072019
mukesh07
suresh07
harshgupta597
surinderdawra388
shivamanandrj9
divisors
Prime Number
prime-factor
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 May, 2022"
},
{
"code": null,
"e": 143,
"s": 54,
"text": "Given a number N, print all numbers in the range from 1 to N having exactly 3 divisors. "
},
{
"code": null,
"e": 154,
"s": 143,
"text": "Examples: "
},
{
"code": null,
"e": 307,
"s": 154,
"text": "Input : N = 16\nOutput : 4 9\n4 and 9 have exactly three divisors.\nDivisor\n\nInput : N = 49\nOutput : 4 9 25 49\n4, 9, 25 and 49 have exactly three divisors."
},
{
"code": null,
"e": 921,
"s": 307,
"text": "After having a close look at the examples mentioned above, you have noticed that all the required numbers are perfect squares and that too are only of primes numbers. The logic behind this is, such numbers can have only three numbers as their divisor and also that includes 1 and that number itself resulting into just a single divisor other than a number, so we can easily conclude that required are those numbers which are squares of prime numbers so that they can have only three divisors (1, the number itself and sqrt(number)). So all primes i, such that i*i is less than equal to N are three-prime numbers. "
},
{
"code": null,
"e": 1055,
"s": 921,
"text": "Note: We can generate all primes within a set using any sieve method efficiently and then we should all primes i, such that i*i <=N. "
},
{
"code": null,
"e": 1106,
"s": 1055,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1110,
"s": 1106,
"text": "C++"
},
{
"code": null,
"e": 1115,
"s": 1110,
"text": "Java"
},
{
"code": null,
"e": 1123,
"s": 1115,
"text": "Python3"
},
{
"code": null,
"e": 1126,
"s": 1123,
"text": "C#"
},
{
"code": null,
"e": 1130,
"s": 1126,
"text": "PHP"
},
{
"code": null,
"e": 1141,
"s": 1130,
"text": "Javascript"
},
{
"code": "// C++ program to print all// three-primes smaller than// or equal to n using Sieve// of Eratosthenes#include <bits/stdc++.h>using namespace std; // Generates all primes upto n and// prints their squaresvoid numbersWith3Divisors(int n){ bool prime[n+1]; memset(prime, true, sizeof(prime)); prime[0] = prime[1] = 0; for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p*2; i <= n; i += p) prime[i] = false; } } // print squares of primes upto n. cout << \"Numbers with 3 divisors :\\n\"; for (int i=0; i*i <= n ; i++) if (prime[i]) cout << i*i << \" \";} // Driver programint main(){ // sieve(); int n = 96; numbersWith3Divisors(n); return 0;}",
"e": 2006,
"s": 1141,
"text": null
},
{
"code": "// Java program to print all// three-primes smaller than// or equal to n using Sieve// of Eratosthenesimport java.io.*;import java.util.*; class GFG{ // Generates all primes upto n // and prints their squares static void numbersWith3Divisors(int n) { boolean[] prime = new boolean[n+1]; Arrays.fill(prime, true); prime[0] = prime[1] = false; for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // print squares of primes upto n System.out.println(\"Numbers with 3 divisors : \"); for (int i=0; i*i <= n ; i++) if (prime[i]) System.out.print(i*i + \" \"); } // Driver program public static void main (String[] args) { int n = 96; numbersWith3Divisors(n); }} // Contributed by Pramod Kumar",
"e": 3091,
"s": 2006,
"text": null
},
{
"code": "# Python3 program to print# all three-primes smaller than# or equal to n using Sieve# of Eratosthenes # Generates all primes upto n# and prints their squaresdef numbersWith3Divisors(n): prime=[True]*(n+1); prime[0] = prime[1] = False; p=2; while (p*p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p*2,n+1,p): prime[i] = False; p+=1; # print squares of primes upto n. print(\"Numbers with 3 divisors :\"); i=0; while (i*i <= n): if (prime[i]): print(i*i,end=\" \"); i+=1; # Driver program n = 96;numbersWith3Divisors(n); # This code is contributed by mits",
"e": 3859,
"s": 3091,
"text": null
},
{
"code": "// C# program to print all// three-primes smaller than// or equal to n using Sieve// of Eratosthenes class GFG{ // Generates all primes upto n // and prints their squares static void numbersWith3Divisors(int n) { bool[] prime = new bool[n+1]; prime[0] = prime[1] = true; for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == false) { // Update all multiples of p for (int i = p*2; i <= n; i += p) prime[i] = true; } } // print squares of primes upto n System.Console.WriteLine(\"Numbers with 3 divisors : \"); for (int i=0; i*i <= n ; i++) if (!prime[i]) System.Console.Write(i*i + \" \"); } // Driver program public static void Main() { int n = 96; numbersWith3Divisors(n); }} // This code is Contributed by mits",
"e": 4869,
"s": 3859,
"text": null
},
{
"code": "<?php// PHP program to print all three-primes// smaller than or equal to n using Sieve// of Eratosthenes // Generates all primes upto n and// prints their squaresfunction numbersWith3Divisors($n){ $prime = array_fill(0, $n + 1, true); $prime[0] = $prime[1] = false; for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } // print squares of primes upto n. echo \"Numbers with 3 divisors :\\n\"; for ($i = 0; $i * $i <= $n ; $i++) if ($prime[$i]) echo $i * $i . \" \";} // Driver Code$n = 96;numbersWith3Divisors($n); // This code is contributed by mits?>",
"e": 5670,
"s": 4869,
"text": null
},
{
"code": "<script> // Javascript program to print all // three-primes smaller than // or equal to n using Sieve // of Eratosthenes // Generates all primes upto n and // prints their squares function numbersWith3Divisors(n) { let prime = new Array(n+1); prime.fill(true); prime[0] = prime[1] = 0; for (let p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p*2; i <= n; i += p) prime[i] = false; } } // print squares of primes upto n. document.write(\"Numbers with 3 divisors :\" + \"</br>\"); for (let i = 0; i*i <= n ; i++) if (prime[i]) document.write(i*i + \" \"); } // sieve(); let n = 96; numbersWith3Divisors(n); // This code is contributed by mukesh07.</script>",
"e": 6656,
"s": 5670,
"text": null
},
{
"code": null,
"e": 6665,
"s": 6656,
"text": "Output: "
},
{
"code": null,
"e": 6702,
"s": 6665,
"text": "Numbers with 3 divisors :\n4 9 25 49 "
},
{
"code": null,
"e": 6730,
"s": 6702,
"text": "Time Complexity: O(sqrt(n))"
},
{
"code": null,
"e": 6752,
"s": 6730,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 6770,
"s": 6752,
"text": "Another Approach:"
},
{
"code": null,
"e": 6981,
"s": 6770,
"text": "To print all numbers in the range from 1 to N having exactly 3 divisors, the main calculation is to find those which are squares of prime numbers and less than or equal to the number. We can do this as follows:"
},
{
"code": null,
"e": 7377,
"s": 6981,
"text": "Start a loop for integer i from 2 to n.Check if i is prime or not, which can be done easily using the isPrime(n) method.If i is prime, check if its square is less than or equal to the given number. This will be checked only for squares of prime numbers, therefore reducing the number of checks.If the above condition is satisfied, the number will be printed and the loop will continue till i<=n."
},
{
"code": null,
"e": 7417,
"s": 7377,
"text": "Start a loop for integer i from 2 to n."
},
{
"code": null,
"e": 7499,
"s": 7417,
"text": "Check if i is prime or not, which can be done easily using the isPrime(n) method."
},
{
"code": null,
"e": 7674,
"s": 7499,
"text": "If i is prime, check if its square is less than or equal to the given number. This will be checked only for squares of prime numbers, therefore reducing the number of checks."
},
{
"code": null,
"e": 7776,
"s": 7674,
"text": "If the above condition is satisfied, the number will be printed and the loop will continue till i<=n."
},
{
"code": null,
"e": 7840,
"s": 7776,
"text": "In this way, no extra space will be required to store anything."
},
{
"code": null,
"e": 7912,
"s": 7840,
"text": "Here is an implementation of the above logic without using extra space;"
},
{
"code": null,
"e": 7916,
"s": 7912,
"text": "C++"
},
{
"code": null,
"e": 7921,
"s": 7916,
"text": "Java"
},
{
"code": null,
"e": 7929,
"s": 7921,
"text": "Python3"
},
{
"code": null,
"e": 7932,
"s": 7929,
"text": "C#"
},
{
"code": null,
"e": 7943,
"s": 7932,
"text": "Javascript"
},
{
"code": "// C++ program to print all// three-primes smaller than// or equal to n without using// extra space#include <bits/stdc++.h>using namespace std; void numbersWith3Divisors(int);bool isPrime(int); // Generates all primes upto n and// prints their squaresvoid numbersWith3Divisors(int n){ cout << \"Numbers with 3 divisors : \" << endl; for(int i = 2; i * i <= n; i++) { // Check prime if (isPrime(i)) { if (i * i <= n) { // Print numbers in // the order of // occurrence cout << i * i << \" \"; } } }} // Check if a number is prime or notbool isPrime(int n){ for(int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true;} // Driver codeint main(){ int n = 122; numbersWith3Divisors(n); return 0;} // This code is contributed by vishu2908",
"e": 8900,
"s": 7943,
"text": null
},
{
"code": "// Java program to print all// three-primes smaller than// or equal to n without using// extra spaceimport java.util.*; class GFG{ // 3 divisor logic implementation // check if a number is // prime or not // if it is a prime then // check if its square // is less than or equal to // the given number static void numbersWith3Divisors(int n) { System.out.println(\"Numbers with 3 divisors : \"); for (int i = 2; i * i <= n; i++) { // Check prime if (isPrime(i)) { if (i * i <= n) { // Print numbers in // the order of // occurrence System.out.print(i * i + \" \"); } } } } // Check if a number is prime or not public static boolean isPrime(int n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } // Driver program public static void main(String[] args) { int n = 122; numbersWith3Divisors(n); }} // Contributed by Parag Pallav Singh",
"e": 10143,
"s": 8900,
"text": null
},
{
"code": "# Python3 program to print all# three-primes smaller than# or equal to n without using# extra space # 3 divisor logic implementation# check if a number is prime or# not if it is a prime then check# if its square is less than or# equal to the given numberdef numbersWith3Divisors(n): print(\"Numbers with 3 divisors : \") i = 2 while i * i <= n: # Check prime if (isPrime(i)): if (i * i <= n): # Print numbers in the order # of occurrence print(i * i, end = \" \") i += 1 # Check if a number is prime or notdef isPrime(n): i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True # Driver coden = 122 numbersWith3Divisors(n) # This code is contributed by divyesh072019",
"e": 11012,
"s": 10143,
"text": null
},
{
"code": "// C# program to print all// three-primes smaller than// or equal to n without using// extra spaceusing System; class GFG{ // 3 divisor logic implementation// check if a number is prime or// not if it is a prime then check// if its square is less than or// equal to the given numberstatic void numbersWith3Divisors(int n){ Console.WriteLine(\"Numbers with 3 divisors : \"); for(int i = 2; i * i <= n; i++) { // Check prime if (isPrime(i)) { if (i * i <= n) { // Print numbers in the order // of occurrence Console.Write(i * i + \" \"); } } }} // Check if a number is prime or notpublic static bool isPrime(int n){ for(int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true;} // Driver codestatic void Main(){ int n = 122; numbersWith3Divisors(n);}} // This code is contributed by divyeshrabadiya07",
"e": 12039,
"s": 11012,
"text": null
},
{
"code": "<script> // Javascript program to print all // three-primes smaller than // or equal to n without using // extra space // 3 divisor logic implementation // check if a number is prime or // not if it is a prime then check // if its square is less than or // equal to the given number function numbersWith3Divisors(n) { document.write(\"Numbers with 3 divisors : \"); for(let i = 2; i * i <= n; i++) { // Check prime if (isPrime(i)) { if (i * i <= n) { // Print numbers in the order // of occurrence document.write(i * i + \" \"); } } } } // Check if a number is prime or not function isPrime(n) { if (n == 0 || n == 1) return false; for(let i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } let n = 122; numbersWith3Divisors(n); // This code is contributed by suresh07.</script>",
"e": 13159,
"s": 12039,
"text": null
},
{
"code": null,
"e": 13167,
"s": 13159,
"text": "Output:"
},
{
"code": null,
"e": 13207,
"s": 13167,
"text": "Numbers with 3 divisors :\n4 9 25 49 121"
},
{
"code": null,
"e": 13234,
"s": 13207,
"text": "Time Complexity: O(sqrtN2)"
},
{
"code": null,
"e": 13256,
"s": 13234,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13691,
"s": 13256,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 13704,
"s": 13691,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 13722,
"s": 13704,
"text": "ParagPallavSingh1"
},
{
"code": null,
"e": 13732,
"s": 13722,
"text": "vishu2908"
},
{
"code": null,
"e": 13750,
"s": 13732,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 13764,
"s": 13750,
"text": "divyesh072019"
},
{
"code": null,
"e": 13773,
"s": 13764,
"text": "mukesh07"
},
{
"code": null,
"e": 13782,
"s": 13773,
"text": "suresh07"
},
{
"code": null,
"e": 13796,
"s": 13782,
"text": "harshgupta597"
},
{
"code": null,
"e": 13813,
"s": 13796,
"text": "surinderdawra388"
},
{
"code": null,
"e": 13828,
"s": 13813,
"text": "shivamanandrj9"
},
{
"code": null,
"e": 13837,
"s": 13828,
"text": "divisors"
},
{
"code": null,
"e": 13850,
"s": 13837,
"text": "Prime Number"
},
{
"code": null,
"e": 13863,
"s": 13850,
"text": "prime-factor"
},
{
"code": null,
"e": 13869,
"s": 13863,
"text": "sieve"
},
{
"code": null,
"e": 13882,
"s": 13869,
"text": "Mathematical"
},
{
"code": null,
"e": 13895,
"s": 13882,
"text": "Mathematical"
},
{
"code": null,
"e": 13908,
"s": 13895,
"text": "Prime Number"
},
{
"code": null,
"e": 13914,
"s": 13908,
"text": "sieve"
}
]
|
MVP (Model View Presenter) Architecture Pattern in Android with Example | 29 Oct, 2020
In the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing mechanism. Further, it causes difficulties in the maintenance and scaling of such mobile applications. To avoid such problems in maintainability, readability, scalability, and refactoring of applications, developers prefer to define well-separated layers of code. By applying software architecture patterns, one can organize the code of the application to separate the concerns. MVP (Model — View — Presenter) architecture is one of the most popular architecture patterns and is valid in organizing the project.
MVP (Model — View — Presenter) comes into the picture as an alternative to the traditional MVC (Model — View — Controller) architecture pattern. Using MVC as the software architecture, developers end up with the following difficulties:
Most of the core business logic resides in Controller. During the lifetime of an application, this file grows bigger and it becomes difficult to maintain the code.
Because of tightly-coupled UI and data access mechanisms, both Controller and View layer falls in the same activity or fragment. This cause problem in making changes in the features of the application.
It becomes hard to carry out Unit testing of the different layer as most of the part which are under testing needs Android SDK components.
MVP pattern overcomes these challenges of MVC and provides an easy way to structure the project codes. The reason why MVP is widely accepted is that it provides modularity, testability, and a more clean and maintainable codebase. It is composed of the following three components:
Model: Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.
View: UI(User Interface) layer. It provides the visualization of the data and keep a track of the user’s action in order to notify the Presenter.
Presenter: Fetch the data from the model and applies the UI logic to decide what to display. It manages the state of the View and takes actions according to the user’s input notification from the View.
Communication between View-Presenter and Presenter-Model happens via an interface(also called Contract).One Presenter class manages one View at a time i.e., there is a one-to-one relationship between Presenter and View.Model and View class doesn’t have knowledge about each other’s existence.
Communication between View-Presenter and Presenter-Model happens via an interface(also called Contract).
One Presenter class manages one View at a time i.e., there is a one-to-one relationship between Presenter and View.
Model and View class doesn’t have knowledge about each other’s existence.
To show the implementation of the MVP architecture pattern on projects, here is an example of a single activity android application. The application will display some strings on the View(Activity) by doing a random selection from the Model. The role of the Presenter class is to keep the business logic of the application away from the activity. Below is the complete step-by-step implementation of this android application. Note that we are going to implement the project using both Java and Kotlin language.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create a new project
Click on File, then New => New Project.Choose Empty activitySelect language as Java/KotlinSelect the minimum SDK as per your need.
Click on File, then New => New Project.
Choose Empty activity
Select language as Java/Kotlin
Select the minimum SDK as per your need.
Step 2: Modify String.xml file
All the strings which are used in the activity are listed in this file.
XML
<resources> <string name="app_name">GfG | MVP Architecture</string> <string name="buttonText">Display Next Course</string> <string name="heading">MVP Architecture Pattern</string> <string name="subHeading">GeeksforGeeks Computer Science Online Courses</string> <string name="description">Course Description</string></resources>
Step 3: Working with the activity_main.xml file
Open the activity_main.xml file and add a Button, a TextView to display the string, and a Progress Bar to give a dynamic feel to the application. Below is the code for designing a proper activity layout.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout 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="#168BC34A" tools:context=".MainActivity"> <!-- TextView to display heading of the activity --> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/heading" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="30sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.060000002" /> <!-- TextView to display sub heading of the activity --> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:text="@string/subHeading" android:textAlignment="center" android:textColor="@android:color/holo_green_dark" android:textSize="24sp" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@+id/button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.356" /> <!-- TextView to display the random string --> <TextView android:id="@+id/textView" android:layout_width="411dp" android:layout_height="wrap_content" android:fontFamily="@font/roboto" android:gravity="center" android:padding="8dp" android:text="@string/description" android:textAlignment="center" android:textAppearance="?android:attr/textAppearanceSearchResultTitle" app:layout_constraintBottom_toTopOf="@+id/button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" app:layout_constraintVertical_bias="0.508" /> <!-- Button to display next random string --> <Button android:id="@+id/button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="@android:dimen/notification_large_icon_height" android:background="#4CAF50" android:text="@string/buttonText" android:textAllCaps="true" android:textColor="@android:color/background_light" android:textSize="20sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.79" /> <!-- Progress Bar to be displayed before displaying next string --> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/button" app:layout_constraintVertical_bias="1.0" app:srcCompat="@drawable/banner" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Defining the Contract Interface file for the Model, View, and Presenter
To establish communication between View-Presenter and Presenter-Model, an interface is needed. This interface class will contain all abstract methods which will be defined later in the View, Model, and Presenter class.
Java
Kotlin
public interface Contract { interface View { // method to display progress bar // when next random course details // is being fetched void showProgress(); // method to hide progress bar // when next random course details // is being fetched void hideProgress(); // method to set random // text on the TextView void setString(String string); } interface Model { // nested interface to be interface OnFinishedListener { // function to be called // once the Handler of Model class // completes its execution void onFinished(String string); } void getNextCourse(Contract.Model.OnFinishedListener onFinishedListener); } interface Presenter { // method to be called when // the button is clicked void onButtonClick(); // method to destroy // lifecycle of MainActivity void onDestroy(); }}
interface Contract { interface View { // method to display progress bar // when next random course details // is being fetched fun showProgress() // method to hide progress bar // when next random course details // is being fetched fun hideProgress() // method to set random // text on the TextView fun setString(string: String?) } interface Model { // nested interface to be interface OnFinishedListener { // function to be called // once the Handler of Model class // completes its execution fun onFinished(string: String?) } fun getNextCourse(onFinishedListener: OnFinishedListener?) } interface Presenter { // method to be called when // the button is clicked fun onButtonClick() // method to destroy // lifecycle of MainActivity fun onDestroy() }}
Step 5: Creating the Model class
Create a new class named Model to separate all string data and the methods to fetch those data. This class will not know the existence of View Class.
Java
Kotlin
import android.os.Handler; import java.util.Arrays;import java.util.List;import java.util.Random; public class Model implements Contract.Model { // array list of strings from which // random strings will be selected // to display in the activity private List<String> arrayList = Arrays.asList( "DSA Self Paced: Master the basics of Data Structures and Algorithms to solve complex problems efficiently. ", "Placement 100: This course will guide you for placement with theory,lecture videos, weekly assignments " + "contests and doubt assistance.", "Amazon SDE Test Series: Test your skill & give the final touch to your preparation before applying for " + "product based against like Amazon, Microsoft, etc.", "Complete Interview Preparation: Cover all the important concepts and topics required for the interviews. " + "Get placement ready before the interviews begin", "Low Level Design for SDE 1 Interview: Learn Object-oriented Analysis and Design to prepare for " + "SDE 1 Interviews in top companies" ); @Override // this method will invoke when // user clicks on the button // and it will take a delay of // 1200 milliseconds to display next course detail public void getNextCourse(final OnFinishedListener listener) { new Handler().postDelayed(new Runnable() { @Override public void run() { listener.onFinished(getRandomString()); } }, 1200); } // method to select random // string from the list of strings private String getRandomString() { Random random = new Random(); int index = random.nextInt(arrayList.size()); return arrayList.get(index); }}
import android.os.Handlerimport java.util.* class Model : Contract.Model { // array list of strings from which // random strings will be selected // to display in the activity private val arrayList = Arrays.asList( "DSA Self Paced: Master the basics of Data Structures and Algorithms to solve complex problems efficiently. ", "Placement 100: This course will guide you for placement with theory,lecture videos, weekly assignments " + "contests and doubt assistance.", "Amazon SDE Test Series: Test your skill & give the final touch to your preparation before applying for " + "product based against like Amazon, Microsoft, etc.", "Complete Interview Preparation: Cover all the important concepts and topics required for the interviews. " + "Get placement ready before the interviews begin", "Low Level Design for SDE 1 Interview: Learn Object-oriented Analysis and Design to prepare for " + "SDE 1 Interviews in top companies" ) // this method will invoke when // user clicks on the button // and it will take a delay of // 1200 milliseconds to display next course detail override fun getNextCourse(onFinishedListener: Contract.Model.OnFinishedListener?) { Handler().postDelayed({ onFinishedListener!!.onFinished(getRandomString) }, 1200) } // method to select random // string from the list of strings private val getRandomString: String private get() { val random = Random() val index = random.nextInt(arrayList.size) return arrayList[index] }}
Step 6: Creating the Presenter class
The methods of this class contain core business logic which will decide what to display and how to display. It triggers the View class to make the necessary changes to the UI.
Java
Kotlin
public class Presenter implements Contract.Presenter, Contract.Model.OnFinishedListener { // creating object of View Interface private Contract.View mainView; // creating object of Model Interface private Contract.Model model; // instantiating the objects of View and Model Interface public Presenter(Contract.View mainView, Contract.Model model) { this.mainView = mainView; this.model = model; } @Override // operations to be performed // on button click public void onButtonClick() { if (mainView != null) { mainView.showProgress(); } model.getNextCourse(this); } @Override public void onDestroy() { mainView = null; } @Override // method to return the string // which will be displayed in the // Course Detail TextView public void onFinished(String string) { if (mainView != null) { mainView.setString(string); mainView.hideProgress(); } }}
// instantiating the objects of View and Model Interface// creating object of View Interface// creating object of Model Interfaceclass Presenter( private var mainView: Contract.View?, private val model: Contract.Model) : Contract.Presenter, Contract.Model.OnFinishedListener { // operations to be performed // on button click override fun onButtonClick() { if (mainView != null) { mainView!!.showProgress() } model.getNextCourse(this) } override fun onDestroy() { mainView = null } // method to return the string // which will be displayed in the // Course Detail TextView override fun onFinished(string: String?) { if (mainView != null) { mainView!!.setString(string) mainView!!.hideProgress() } } }
Step 7: Define functionalities of View in the MainActivity file
The View class is responsible for updating the UI according to the changes triggered by the Presenter layer. The data provided by the Model will be used by View and the appropriate changes will be made in the activity.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView; import static android.view.View.GONE; public class MainActivity extends AppCompatActivity implements Contract.View { // creating object of TextView class private TextView textView; // creating object of Button class private Button button; // creating object of ProgressBar class private ProgressBar progressBar; // creating object of Presenter interface in Contract Contract.Presenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assigning ID of the TextView textView = findViewById(R.id.textView); // assigning ID of the Button button = findViewById(R.id.button); // assigning ID of the ProgressBar progressBar = findViewById(R.id.progressBar); // instantiating object of Presenter Interface presenter = new Presenter(this, new Model()); // operations to be performed when // user clicks the button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { presenter.onButtonClick(); } }); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); presenter.onDestroy(); } @Override // method to display the Course Detail TextView public void showProgress() { progressBar.setVisibility(View.VISIBLE); textView.setVisibility(View.INVISIBLE); } @Override // method to hide the Course Detail TextView public void hideProgress() { progressBar.setVisibility(GONE); textView.setVisibility(View.VISIBLE); } @Override // method to set random string // in the Course Detail TextView public void setString(String string) { textView.setText(string); }}
import android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.ProgressBarimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity(), Contract.View { // creating object of TextView class private var textView: TextView? = null // creating object of Button class private var button: Button? = null // creating object of ProgressBar class private var progressBar: ProgressBar? = null // creating object of Presenter interface in Contract var presenter: Presenter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning ID of the TextView textView = findViewById(R.id.textView) // assigning ID of the Button button = findViewById(R.id.button) // assigning ID of the ProgressBar progressBar = findViewById(R.id.progressBar) // instantiating object of Presenter Interface presenter = Presenter(this, Model()) // operations to be performed when // user clicks the button this.button!!.setOnClickListener(View.OnClickListener { presenter!!.onButtonClick() }) } override fun onResume() { super.onResume() } override fun onDestroy() { super.onDestroy() presenter!!.onDestroy() } // method to display the Course Detail TextView override fun showProgress() { progressBar!!.visibility = View.VISIBLE textView!!.visibility = View.INVISIBLE } // method to hide the Course Detail TextView override fun hideProgress() { progressBar!!.visibility = View.GONE textView!!.visibility = View.VISIBLE } // method to set random string // in the Course Detail TextView override fun setString(string: String?) { textView!!.text = string }}
No conceptual relationship in android components
Easy code maintenance and testing as the application’s model, view, and presenter layer are separated.
If the developer does not follow the single responsibility principle to break the code then the Presenter layer tends to expand to a huge all-knowing class.
android
Technical Scripter 2020
Android
Java
Kotlin
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 914,
"s": 52,
"text": "In the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing mechanism. Further, it causes difficulties in the maintenance and scaling of such mobile applications. To avoid such problems in maintainability, readability, scalability, and refactoring of applications, developers prefer to define well-separated layers of code. By applying software architecture patterns, one can organize the code of the application to separate the concerns. MVP (Model — View — Presenter) architecture is one of the most popular architecture patterns and is valid in organizing the project."
},
{
"code": null,
"e": 1150,
"s": 914,
"text": "MVP (Model — View — Presenter) comes into the picture as an alternative to the traditional MVC (Model — View — Controller) architecture pattern. Using MVC as the software architecture, developers end up with the following difficulties:"
},
{
"code": null,
"e": 1314,
"s": 1150,
"text": "Most of the core business logic resides in Controller. During the lifetime of an application, this file grows bigger and it becomes difficult to maintain the code."
},
{
"code": null,
"e": 1516,
"s": 1314,
"text": "Because of tightly-coupled UI and data access mechanisms, both Controller and View layer falls in the same activity or fragment. This cause problem in making changes in the features of the application."
},
{
"code": null,
"e": 1655,
"s": 1516,
"text": "It becomes hard to carry out Unit testing of the different layer as most of the part which are under testing needs Android SDK components."
},
{
"code": null,
"e": 1935,
"s": 1655,
"text": "MVP pattern overcomes these challenges of MVC and provides an easy way to structure the project codes. The reason why MVP is widely accepted is that it provides modularity, testability, and a more clean and maintainable codebase. It is composed of the following three components:"
},
{
"code": null,
"e": 2097,
"s": 1935,
"text": "Model: Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers."
},
{
"code": null,
"e": 2243,
"s": 2097,
"text": "View: UI(User Interface) layer. It provides the visualization of the data and keep a track of the user’s action in order to notify the Presenter."
},
{
"code": null,
"e": 2445,
"s": 2243,
"text": "Presenter: Fetch the data from the model and applies the UI logic to decide what to display. It manages the state of the View and takes actions according to the user’s input notification from the View."
},
{
"code": null,
"e": 2738,
"s": 2445,
"text": "Communication between View-Presenter and Presenter-Model happens via an interface(also called Contract).One Presenter class manages one View at a time i.e., there is a one-to-one relationship between Presenter and View.Model and View class doesn’t have knowledge about each other’s existence."
},
{
"code": null,
"e": 2843,
"s": 2738,
"text": "Communication between View-Presenter and Presenter-Model happens via an interface(also called Contract)."
},
{
"code": null,
"e": 2959,
"s": 2843,
"text": "One Presenter class manages one View at a time i.e., there is a one-to-one relationship between Presenter and View."
},
{
"code": null,
"e": 3033,
"s": 2959,
"text": "Model and View class doesn’t have knowledge about each other’s existence."
},
{
"code": null,
"e": 3543,
"s": 3033,
"text": "To show the implementation of the MVP architecture pattern on projects, here is an example of a single activity android application. The application will display some strings on the View(Activity) by doing a random selection from the Model. The role of the Presenter class is to keep the business logic of the application away from the activity. Below is the complete step-by-step implementation of this android application. Note that we are going to implement the project using both Java and Kotlin language."
},
{
"code": null,
"e": 3609,
"s": 3543,
"text": "Note: Following steps are performed on Android Studio version 4.0"
},
{
"code": null,
"e": 3638,
"s": 3609,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 3769,
"s": 3638,
"text": "Click on File, then New => New Project.Choose Empty activitySelect language as Java/KotlinSelect the minimum SDK as per your need."
},
{
"code": null,
"e": 3809,
"s": 3769,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 3831,
"s": 3809,
"text": "Choose Empty activity"
},
{
"code": null,
"e": 3862,
"s": 3831,
"text": "Select language as Java/Kotlin"
},
{
"code": null,
"e": 3903,
"s": 3862,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 3934,
"s": 3903,
"text": "Step 2: Modify String.xml file"
},
{
"code": null,
"e": 4006,
"s": 3934,
"text": "All the strings which are used in the activity are listed in this file."
},
{
"code": null,
"e": 4010,
"s": 4006,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">GfG | MVP Architecture</string> <string name=\"buttonText\">Display Next Course</string> <string name=\"heading\">MVP Architecture Pattern</string> <string name=\"subHeading\">GeeksforGeeks Computer Science Online Courses</string> <string name=\"description\">Course Description</string></resources>",
"e": 4353,
"s": 4010,
"text": null
},
{
"code": null,
"e": 4401,
"s": 4353,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 4605,
"s": 4401,
"text": "Open the activity_main.xml file and add a Button, a TextView to display the string, and a Progress Bar to give a dynamic feel to the application. Below is the code for designing a proper activity layout."
},
{
"code": null,
"e": 4609,
"s": 4605,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout 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=\"#168BC34A\" tools:context=\".MainActivity\"> <!-- TextView to display heading of the activity --> <TextView android:id=\"@+id/textView3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/heading\" android:textAlignment=\"center\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"30sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.498\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.060000002\" /> <!-- TextView to display sub heading of the activity --> <TextView android:id=\"@+id/textView2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:text=\"@string/subHeading\" android:textAlignment=\"center\" android:textColor=\"@android:color/holo_green_dark\" android:textSize=\"24sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toTopOf=\"@+id/button\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"1.0\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.356\" /> <!-- TextView to display the random string --> <TextView android:id=\"@+id/textView\" android:layout_width=\"411dp\" android:layout_height=\"wrap_content\" android:fontFamily=\"@font/roboto\" android:gravity=\"center\" android:padding=\"8dp\" android:text=\"@string/description\" android:textAlignment=\"center\" android:textAppearance=\"?android:attr/textAppearanceSearchResultTitle\" app:layout_constraintBottom_toTopOf=\"@+id/button\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView2\" app:layout_constraintVertical_bias=\"0.508\" /> <!-- Button to display next random string --> <Button android:id=\"@+id/button\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_margin=\"@android:dimen/notification_large_icon_height\" android:background=\"#4CAF50\" android:text=\"@string/buttonText\" android:textAllCaps=\"true\" android:textColor=\"@android:color/background_light\" android:textSize=\"20sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.79\" /> <!-- Progress Bar to be displayed before displaying next string --> <ProgressBar android:id=\"@+id/progressBar\" style=\"?android:attr/progressBarStyleLarge\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:visibility=\"gone\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/button\" app:layout_constraintVertical_bias=\"1.0\" app:srcCompat=\"@drawable/banner\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 8968,
"s": 4609,
"text": null
},
{
"code": null,
"e": 9048,
"s": 8968,
"text": "Step 4: Defining the Contract Interface file for the Model, View, and Presenter"
},
{
"code": null,
"e": 9267,
"s": 9048,
"text": "To establish communication between View-Presenter and Presenter-Model, an interface is needed. This interface class will contain all abstract methods which will be defined later in the View, Model, and Presenter class."
},
{
"code": null,
"e": 9272,
"s": 9267,
"text": "Java"
},
{
"code": null,
"e": 9279,
"s": 9272,
"text": "Kotlin"
},
{
"code": "public interface Contract { interface View { // method to display progress bar // when next random course details // is being fetched void showProgress(); // method to hide progress bar // when next random course details // is being fetched void hideProgress(); // method to set random // text on the TextView void setString(String string); } interface Model { // nested interface to be interface OnFinishedListener { // function to be called // once the Handler of Model class // completes its execution void onFinished(String string); } void getNextCourse(Contract.Model.OnFinishedListener onFinishedListener); } interface Presenter { // method to be called when // the button is clicked void onButtonClick(); // method to destroy // lifecycle of MainActivity void onDestroy(); }}",
"e": 10287,
"s": 9279,
"text": null
},
{
"code": "interface Contract { interface View { // method to display progress bar // when next random course details // is being fetched fun showProgress() // method to hide progress bar // when next random course details // is being fetched fun hideProgress() // method to set random // text on the TextView fun setString(string: String?) } interface Model { // nested interface to be interface OnFinishedListener { // function to be called // once the Handler of Model class // completes its execution fun onFinished(string: String?) } fun getNextCourse(onFinishedListener: OnFinishedListener?) } interface Presenter { // method to be called when // the button is clicked fun onButtonClick() // method to destroy // lifecycle of MainActivity fun onDestroy() }}",
"e": 11261,
"s": 10287,
"text": null
},
{
"code": null,
"e": 11294,
"s": 11261,
"text": "Step 5: Creating the Model class"
},
{
"code": null,
"e": 11444,
"s": 11294,
"text": "Create a new class named Model to separate all string data and the methods to fetch those data. This class will not know the existence of View Class."
},
{
"code": null,
"e": 11449,
"s": 11444,
"text": "Java"
},
{
"code": null,
"e": 11456,
"s": 11449,
"text": "Kotlin"
},
{
"code": "import android.os.Handler; import java.util.Arrays;import java.util.List;import java.util.Random; public class Model implements Contract.Model { // array list of strings from which // random strings will be selected // to display in the activity private List<String> arrayList = Arrays.asList( \"DSA Self Paced: Master the basics of Data Structures and Algorithms to solve complex problems efficiently. \", \"Placement 100: This course will guide you for placement with theory,lecture videos, weekly assignments \" + \"contests and doubt assistance.\", \"Amazon SDE Test Series: Test your skill & give the final touch to your preparation before applying for \" + \"product based against like Amazon, Microsoft, etc.\", \"Complete Interview Preparation: Cover all the important concepts and topics required for the interviews. \" + \"Get placement ready before the interviews begin\", \"Low Level Design for SDE 1 Interview: Learn Object-oriented Analysis and Design to prepare for \" + \"SDE 1 Interviews in top companies\" ); @Override // this method will invoke when // user clicks on the button // and it will take a delay of // 1200 milliseconds to display next course detail public void getNextCourse(final OnFinishedListener listener) { new Handler().postDelayed(new Runnable() { @Override public void run() { listener.onFinished(getRandomString()); } }, 1200); } // method to select random // string from the list of strings private String getRandomString() { Random random = new Random(); int index = random.nextInt(arrayList.size()); return arrayList.get(index); }}",
"e": 13283,
"s": 11456,
"text": null
},
{
"code": "import android.os.Handlerimport java.util.* class Model : Contract.Model { // array list of strings from which // random strings will be selected // to display in the activity private val arrayList = Arrays.asList( \"DSA Self Paced: Master the basics of Data Structures and Algorithms to solve complex problems efficiently. \", \"Placement 100: This course will guide you for placement with theory,lecture videos, weekly assignments \" + \"contests and doubt assistance.\", \"Amazon SDE Test Series: Test your skill & give the final touch to your preparation before applying for \" + \"product based against like Amazon, Microsoft, etc.\", \"Complete Interview Preparation: Cover all the important concepts and topics required for the interviews. \" + \"Get placement ready before the interviews begin\", \"Low Level Design for SDE 1 Interview: Learn Object-oriented Analysis and Design to prepare for \" + \"SDE 1 Interviews in top companies\" ) // this method will invoke when // user clicks on the button // and it will take a delay of // 1200 milliseconds to display next course detail override fun getNextCourse(onFinishedListener: Contract.Model.OnFinishedListener?) { Handler().postDelayed({ onFinishedListener!!.onFinished(getRandomString) }, 1200) } // method to select random // string from the list of strings private val getRandomString: String private get() { val random = Random() val index = random.nextInt(arrayList.size) return arrayList[index] }}",
"e": 14977,
"s": 13283,
"text": null
},
{
"code": null,
"e": 15014,
"s": 14977,
"text": "Step 6: Creating the Presenter class"
},
{
"code": null,
"e": 15190,
"s": 15014,
"text": "The methods of this class contain core business logic which will decide what to display and how to display. It triggers the View class to make the necessary changes to the UI."
},
{
"code": null,
"e": 15195,
"s": 15190,
"text": "Java"
},
{
"code": null,
"e": 15202,
"s": 15195,
"text": "Kotlin"
},
{
"code": "public class Presenter implements Contract.Presenter, Contract.Model.OnFinishedListener { // creating object of View Interface private Contract.View mainView; // creating object of Model Interface private Contract.Model model; // instantiating the objects of View and Model Interface public Presenter(Contract.View mainView, Contract.Model model) { this.mainView = mainView; this.model = model; } @Override // operations to be performed // on button click public void onButtonClick() { if (mainView != null) { mainView.showProgress(); } model.getNextCourse(this); } @Override public void onDestroy() { mainView = null; } @Override // method to return the string // which will be displayed in the // Course Detail TextView public void onFinished(String string) { if (mainView != null) { mainView.setString(string); mainView.hideProgress(); } }}",
"e": 16210,
"s": 15202,
"text": null
},
{
"code": "// instantiating the objects of View and Model Interface// creating object of View Interface// creating object of Model Interfaceclass Presenter( private var mainView: Contract.View?, private val model: Contract.Model) : Contract.Presenter, Contract.Model.OnFinishedListener { // operations to be performed // on button click override fun onButtonClick() { if (mainView != null) { mainView!!.showProgress() } model.getNextCourse(this) } override fun onDestroy() { mainView = null } // method to return the string // which will be displayed in the // Course Detail TextView override fun onFinished(string: String?) { if (mainView != null) { mainView!!.setString(string) mainView!!.hideProgress() } } }",
"e": 17035,
"s": 16210,
"text": null
},
{
"code": null,
"e": 17099,
"s": 17035,
"text": "Step 7: Define functionalities of View in the MainActivity file"
},
{
"code": null,
"e": 17319,
"s": 17099,
"text": "The View class is responsible for updating the UI according to the changes triggered by the Presenter layer. The data provided by the Model will be used by View and the appropriate changes will be made in the activity. "
},
{
"code": null,
"e": 17324,
"s": 17319,
"text": "Java"
},
{
"code": null,
"e": 17331,
"s": 17324,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView; import static android.view.View.GONE; public class MainActivity extends AppCompatActivity implements Contract.View { // creating object of TextView class private TextView textView; // creating object of Button class private Button button; // creating object of ProgressBar class private ProgressBar progressBar; // creating object of Presenter interface in Contract Contract.Presenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assigning ID of the TextView textView = findViewById(R.id.textView); // assigning ID of the Button button = findViewById(R.id.button); // assigning ID of the ProgressBar progressBar = findViewById(R.id.progressBar); // instantiating object of Presenter Interface presenter = new Presenter(this, new Model()); // operations to be performed when // user clicks the button button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { presenter.onButtonClick(); } }); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); presenter.onDestroy(); } @Override // method to display the Course Detail TextView public void showProgress() { progressBar.setVisibility(View.VISIBLE); textView.setVisibility(View.INVISIBLE); } @Override // method to hide the Course Detail TextView public void hideProgress() { progressBar.setVisibility(GONE); textView.setVisibility(View.VISIBLE); } @Override // method to set random string // in the Course Detail TextView public void setString(String string) { textView.setText(string); }}",
"e": 19496,
"s": 17331,
"text": null
},
{
"code": "import android.os.Bundleimport android.view.Viewimport android.widget.Buttonimport android.widget.ProgressBarimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity(), Contract.View { // creating object of TextView class private var textView: TextView? = null // creating object of Button class private var button: Button? = null // creating object of ProgressBar class private var progressBar: ProgressBar? = null // creating object of Presenter interface in Contract var presenter: Presenter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // assigning ID of the TextView textView = findViewById(R.id.textView) // assigning ID of the Button button = findViewById(R.id.button) // assigning ID of the ProgressBar progressBar = findViewById(R.id.progressBar) // instantiating object of Presenter Interface presenter = Presenter(this, Model()) // operations to be performed when // user clicks the button this.button!!.setOnClickListener(View.OnClickListener { presenter!!.onButtonClick() }) } override fun onResume() { super.onResume() } override fun onDestroy() { super.onDestroy() presenter!!.onDestroy() } // method to display the Course Detail TextView override fun showProgress() { progressBar!!.visibility = View.VISIBLE textView!!.visibility = View.INVISIBLE } // method to hide the Course Detail TextView override fun hideProgress() { progressBar!!.visibility = View.GONE textView!!.visibility = View.VISIBLE } // method to set random string // in the Course Detail TextView override fun setString(string: String?) { textView!!.text = string }}",
"e": 21444,
"s": 19496,
"text": null
},
{
"code": null,
"e": 21493,
"s": 21444,
"text": "No conceptual relationship in android components"
},
{
"code": null,
"e": 21596,
"s": 21493,
"text": "Easy code maintenance and testing as the application’s model, view, and presenter layer are separated."
},
{
"code": null,
"e": 21753,
"s": 21596,
"text": "If the developer does not follow the single responsibility principle to break the code then the Presenter layer tends to expand to a huge all-knowing class."
},
{
"code": null,
"e": 21761,
"s": 21753,
"text": "android"
},
{
"code": null,
"e": 21785,
"s": 21761,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 21793,
"s": 21785,
"text": "Android"
},
{
"code": null,
"e": 21798,
"s": 21793,
"text": "Java"
},
{
"code": null,
"e": 21805,
"s": 21798,
"text": "Kotlin"
},
{
"code": null,
"e": 21824,
"s": 21805,
"text": "Technical Scripter"
},
{
"code": null,
"e": 21829,
"s": 21824,
"text": "Java"
},
{
"code": null,
"e": 21837,
"s": 21829,
"text": "Android"
}
]
|
Split a Circular Linked List into two halves | 24 Jun, 2022
Original Linked List
Result Linked List 1
Result Linked List 2
If there are odd number of nodes, then first list should contain one extra.
Thanks to Geek4u for suggesting the algorithm. 1) Store the mid and last pointers of the circular linked list using tortoise and hare algorithm. 2) Make the second half circular. 3) Make the first half circular. 4) Set head (or start) pointers of the two linked lists.In the below implementation, if there are odd nodes in the given circular linked list then the first result list has 1 more node than the second result list.
C++
C
Java
Python3
C#
Javascript
// Program to split a circular linked list// into two halves #include <bits/stdc++.h>using namespace std; /* structure for a node */class Node { public: int data; Node *next; }; /* Function to split a list (starting with head) into two lists. head1_ref and head2_ref are references to head nodes of the two resultant linked lists */void splitList(Node *head, Node **head1_ref, Node **head2_ref) { Node *slow_ptr = head; Node *fast_ptr = head; if(head == NULL) return; /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while(fast_ptr->next != head && fast_ptr->next->next != head) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } /* If there are even elements in list then move fast_ptr */ if(fast_ptr->next->next == head) fast_ptr = fast_ptr->next; /* Set the head pointer of first half */ *head1_ref = head; /* Set the head pointer of second half */ if(head->next != head) *head2_ref = slow_ptr->next; /* Make second half circular */ fast_ptr->next = slow_ptr->next; /* Make first half circular */ slow_ptr->next = head; } /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of a Circular linked list */void push(Node **head_ref, int data) { Node *ptr1 = new Node(); Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; /* If linked list is not NULL then set the next of last node */ if(*head_ref != NULL) { while(temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; /*For the first node */ *head_ref = ptr1; } /* Function to print nodes in a given Circular linked list */void printList(Node *head) { Node *temp = head; if(head != NULL) { cout << endl; do { cout << temp->data << " "; temp = temp->next; } while(temp != head); } } // Driver Codeint main() { int list_size, i; /* Initialize lists as empty */ Node *head = NULL; Node *head1 = NULL; Node *head2 = NULL; /* Created linked list will be 12->56->2->11 */ push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); cout << "Original Circular Linked List"; printList(head); /* Split the list */ splitList(head, &head1, &head2); cout << "\nFirst Circular Linked List"; printList(head1); cout << "\nSecond Circular Linked List"; printList(head2); return 0; } // This code is contributed by rathbhupendra
/* Program to split a circular linked list into two halves */#include<stdio.h> #include<stdlib.h> /* structure for a node */struct Node{ int data; struct Node *next;}; /* Function to split a list (starting with head) into two lists. head1_ref and head2_ref are references to head nodes of the two resultant linked lists */void splitList(struct Node *head, struct Node **head1_ref, struct Node **head2_ref){ struct Node *slow_ptr = head; struct Node *fast_ptr = head; if(head == NULL) return; /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while(fast_ptr->next != head && fast_ptr->next->next != head) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } /* If there are even elements in list then move fast_ptr */ if(fast_ptr->next->next == head) fast_ptr = fast_ptr->next; /* Set the head pointer of first half */ *head1_ref = head; /* Set the head pointer of second half */ if(head->next != head) *head2_ref = slow_ptr->next; /* Make second half circular */ fast_ptr->next = slow_ptr->next; /* Make first half circular */ slow_ptr->next = head; } /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of a Circular linked list */void push(struct Node **head_ref, int data){ struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node)); struct Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; /* If linked list is not NULL then set the next of last node */ if(*head_ref != NULL) { while(temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; /*For the first node */ *head_ref = ptr1; } /* Function to print nodes in a given Circular linked list */void printList(struct Node *head){ struct Node *temp = head; if(head != NULL) { printf("\n"); do { printf("%d ", temp->data); temp = temp->next; } while(temp != head); }} /* Driver program to test above functions */int main(){ int list_size, i; /* Initialize lists as empty */ struct Node *head = NULL; struct Node *head1 = NULL; struct Node *head2 = NULL; /* Created linked list will be 12->56->2->11 */ push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); printf("Original Circular Linked List"); printList(head); /* Split the list */ splitList(head, &head1, &head2); printf("\nFirst Circular Linked List"); printList(head1); printf("\nSecond Circular Linked List"); printList(head2); getchar(); return 0;}
// Java program to delete a node from doubly linked list class LinkedList { static Node head, head1, head2; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } /* Function to split a list (starting with head) into two lists. head1_ref and head2_ref are references to head nodes of the two resultant linked lists */ void splitList() { Node slow_ptr = head; Node fast_ptr = head; if (head == null) { return; } /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while (fast_ptr.next != head && fast_ptr.next.next != head) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } /* If there are even elements in list then move fast_ptr */ if (fast_ptr.next.next == head) { fast_ptr = fast_ptr.next; } /* Set the head pointer of first half */ head1 = head; /* Set the head pointer of second half */ if (head.next != head) { head2 = slow_ptr.next; } /* Make second half circular */ fast_ptr.next = slow_ptr.next; /* Make first half circular */ slow_ptr.next = head; } /* Function to print nodes in a given singly linked list */ void printList(Node node) { Node temp = node; if (node != null) { do { System.out.print(temp.data + " "); temp = temp.next; } while (temp != node); } } public static void main(String[] args) { LinkedList list = new LinkedList(); //Created linked list will be 12->56->2->11 list.head = new Node(12); list.head.next = new Node(56); list.head.next.next = new Node(2); list.head.next.next.next = new Node(11); list.head.next.next.next.next = list.head; System.out.println("Original Circular Linked list "); list.printList(head); // Split the list list.splitList(); System.out.println(""); System.out.println("First Circular List "); list.printList(head1); System.out.println(""); System.out.println("Second Circular List "); list.printList(head2); }} // This code has been contributed by Mayank Jaiswal
# Python program to split circular linked list into two halves # A node structureclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # Class to create a new Circular Linked listclass CircularLinkedList: # Constructor to create a empty circular linked list def __init__(self): self.head = None # Function to insert a node at the beginning of a # circular linked list def push(self, data): ptr1 = Node(data) temp = self.head ptr1.next = self.head # If linked list is not None then set the next of # last node if self.head is not None: while(temp.next != self.head): temp = temp.next temp.next = ptr1 else: ptr1.next = ptr1 # For the first node self.head = ptr1 # Function to print nodes in a given circular linked list def printList(self): temp = self.head if self.head is not None: while(True): print ("%d" %(temp.data),end=' ') temp = temp.next if (temp == self.head): break # Function to split a list (starting with head) into # two lists. head1 and head2 are the head nodes of the # two resultant linked lists def splitList(self, head1, head2): slow_ptr = self.head fast_ptr = self.head if self.head is None: return # If there are odd nodes in the circular list then # fast_ptr->next becomes head and for even nodes # fast_ptr->next->next becomes head while(fast_ptr.next != self.head and fast_ptr.next.next != self.head ): fast_ptr = fast_ptr.next.next slow_ptr = slow_ptr.next # If there are even elements in list then # move fast_ptr if fast_ptr.next.next == self.head: fast_ptr = fast_ptr.next # Set the head pointer of first half head1.head = self.head # Set the head pointer of second half if self.head.next != self.head: head2.head = slow_ptr.next # Make second half circular fast_ptr.next = slow_ptr.next # Make first half circular slow_ptr.next = self.head # Driver program to test above functions # Initialize lists as emptyhead = CircularLinkedList() head1 = CircularLinkedList()head2 = CircularLinkedList() head.push(12)head.push(56)head.push(2)head.push(11) print ("Original Circular Linked List")head.printList() # Split the list head.splitList(head1 , head2) print ("\nFirst Circular Linked List")head1.printList() print ("\nSecond Circular Linked List")head2.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program to delete a node// from doubly linked listusing System;class GFG{ public Node head, head1, head2; public class Node { public int data; public Node next, prev; public Node(int d) { data = d; next = prev = null; } } /* Function to split a list (starting with head) into two lists. head1_ref and head2_ref are references to head nodes of the two resultant linked lists */ void splitList() { Node slow_ptr = head; Node fast_ptr = head; if (head == null) { return; } /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while (fast_ptr.next != head && fast_ptr.next.next != head) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } /* If there are even elements in list then move fast_ptr */ if (fast_ptr.next.next == head) { fast_ptr = fast_ptr.next; } /* Set the head pointer of first half */ head1 = head; /* Set the head pointer of second half */ if (head.next != head) { head2 = slow_ptr.next; } /* Make second half circular */ fast_ptr.next = slow_ptr.next; /* Make first half circular */ slow_ptr.next = head; } /* Function to print nodes in a given singly linked list */ void printList(Node node) { Node temp = node; if (node != null) { do { Console.Write(temp.data + " "); temp = temp.next; } while (temp != node); } } public static void Main(String[] args) { GFG list = new GFG(); // Created linked list will be 12->56->2->11 list.head = new Node(12); list.head.next = new Node(56); list.head.next.next = new Node(2); list.head.next.next.next = new Node(11); list.head.next.next.next.next = list.head; Console.WriteLine("Original Circular Linked list "); list.printList(list.head); // Split the list list.splitList(); Console.WriteLine(""); Console.WriteLine("First Circular List "); list.printList(list.head1); Console.WriteLine(""); Console.WriteLine("Second Circular List "); list.printList(list.head2); }} // This code is contributed by PrinciRaj1992
<script> class Node{ constructor(d) { this.data = d; this.next = this.prev = null; }} let head, head1, head2; function splitList(){ let slow_ptr = head; let fast_ptr = head; if (head == null) { return; } /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while (fast_ptr.next != head && fast_ptr.next.next != head) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } /* If there are even elements in list then move fast_ptr */ if (fast_ptr.next.next == head) { fast_ptr = fast_ptr.next; } /* Set the head pointer of first half */ head1 = head; /* Set the head pointer of second half */ if (head.next != head) { head2 = slow_ptr.next; } /* Make second half circular */ fast_ptr.next = slow_ptr.next; /* Make first half circular */ slow_ptr.next = head; } /* Function to print nodes in a given singly linked list */ function printList(node) { let temp = node; if (node != null) { do { document.write(temp.data + " "); temp = temp.next; } while (temp != node); } } //Created linked list will be 12->56->2->11head = new Node(12);head.next = new Node(56);head.next.next = new Node(2);head.next.next.next = new Node(11);head.next.next.next.next = head; document.write("Original Circular Linked list <br>");printList(head); // Split the listsplitList();document.write("<br>");document.write("First Circular List <br>");printList(head1);document.write("<br>");document.write("Second Circular List <br>");printList(head2); // This code is contributed by avanitrachhadiya2155</script>
Output:
Original Circular Linked List
11 2 56 12
First Circular Linked List
11 2
Second Circular Linked List
56 12
Time Complexity: O(n) As we are only moving once through the list
Auxiliary Space: O(1) As no extra space is usedPlease write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem
shubham_singh
rathbhupendra
princiraj1992
aditosh007
avanitrachhadiya2155
amartyaghoshgfg
simmytarika5
abhijeet19403
circular linked list
Yahoo
Linked List
Yahoo
Linked List
circular linked list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Introduction to Data Structures
Doubly Linked List | Set 1 (Introduction and Insertion)
Detect loop in a linked list
Merge two sorted linked lists
What is Data Structure: Types, Classifications and Applications
Find the middle of a given linked list
Linked List vs Array
Merge Sort for Linked Lists
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 100,
"s": 52,
"text": " Original Linked List "
},
{
"code": null,
"e": 148,
"s": 100,
"text": " Result Linked List 1 "
},
{
"code": null,
"e": 196,
"s": 148,
"text": " Result Linked List 2 "
},
{
"code": null,
"e": 273,
"s": 196,
"text": "If there are odd number of nodes, then first list should contain one extra. "
},
{
"code": null,
"e": 701,
"s": 273,
"text": "Thanks to Geek4u for suggesting the algorithm. 1) Store the mid and last pointers of the circular linked list using tortoise and hare algorithm. 2) Make the second half circular. 3) Make the first half circular. 4) Set head (or start) pointers of the two linked lists.In the below implementation, if there are odd nodes in the given circular linked list then the first result list has 1 more node than the second result list. "
},
{
"code": null,
"e": 705,
"s": 701,
"text": "C++"
},
{
"code": null,
"e": 707,
"s": 705,
"text": "C"
},
{
"code": null,
"e": 712,
"s": 707,
"text": "Java"
},
{
"code": null,
"e": 720,
"s": 712,
"text": "Python3"
},
{
"code": null,
"e": 723,
"s": 720,
"text": "C#"
},
{
"code": null,
"e": 734,
"s": 723,
"text": "Javascript"
},
{
"code": "// Program to split a circular linked list// into two halves #include <bits/stdc++.h>using namespace std; /* structure for a node */class Node { public: int data; Node *next; }; /* Function to split a list (starting with head) into two lists. head1_ref and head2_ref are references to head nodes of the two resultant linked lists */void splitList(Node *head, Node **head1_ref, Node **head2_ref) { Node *slow_ptr = head; Node *fast_ptr = head; if(head == NULL) return; /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while(fast_ptr->next != head && fast_ptr->next->next != head) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } /* If there are even elements in list then move fast_ptr */ if(fast_ptr->next->next == head) fast_ptr = fast_ptr->next; /* Set the head pointer of first half */ *head1_ref = head; /* Set the head pointer of second half */ if(head->next != head) *head2_ref = slow_ptr->next; /* Make second half circular */ fast_ptr->next = slow_ptr->next; /* Make first half circular */ slow_ptr->next = head; } /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of a Circular linked list */void push(Node **head_ref, int data) { Node *ptr1 = new Node(); Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; /* If linked list is not NULL then set the next of last node */ if(*head_ref != NULL) { while(temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; /*For the first node */ *head_ref = ptr1; } /* Function to print nodes in a given Circular linked list */void printList(Node *head) { Node *temp = head; if(head != NULL) { cout << endl; do { cout << temp->data << \" \"; temp = temp->next; } while(temp != head); } } // Driver Codeint main() { int list_size, i; /* Initialize lists as empty */ Node *head = NULL; Node *head1 = NULL; Node *head2 = NULL; /* Created linked list will be 12->56->2->11 */ push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); cout << \"Original Circular Linked List\"; printList(head); /* Split the list */ splitList(head, &head1, &head2); cout << \"\\nFirst Circular Linked List\"; printList(head1); cout << \"\\nSecond Circular Linked List\"; printList(head2); return 0; } // This code is contributed by rathbhupendra",
"e": 3578,
"s": 734,
"text": null
},
{
"code": "/* Program to split a circular linked list into two halves */#include<stdio.h> #include<stdlib.h> /* structure for a node */struct Node{ int data; struct Node *next;}; /* Function to split a list (starting with head) into two lists. head1_ref and head2_ref are references to head nodes of the two resultant linked lists */void splitList(struct Node *head, struct Node **head1_ref, struct Node **head2_ref){ struct Node *slow_ptr = head; struct Node *fast_ptr = head; if(head == NULL) return; /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while(fast_ptr->next != head && fast_ptr->next->next != head) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } /* If there are even elements in list then move fast_ptr */ if(fast_ptr->next->next == head) fast_ptr = fast_ptr->next; /* Set the head pointer of first half */ *head1_ref = head; /* Set the head pointer of second half */ if(head->next != head) *head2_ref = slow_ptr->next; /* Make second half circular */ fast_ptr->next = slow_ptr->next; /* Make first half circular */ slow_ptr->next = head; } /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of a Circular linked list */void push(struct Node **head_ref, int data){ struct Node *ptr1 = (struct Node *)malloc(sizeof(struct Node)); struct Node *temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; /* If linked list is not NULL then set the next of last node */ if(*head_ref != NULL) { while(temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; /*For the first node */ *head_ref = ptr1; } /* Function to print nodes in a given Circular linked list */void printList(struct Node *head){ struct Node *temp = head; if(head != NULL) { printf(\"\\n\"); do { printf(\"%d \", temp->data); temp = temp->next; } while(temp != head); }} /* Driver program to test above functions */int main(){ int list_size, i; /* Initialize lists as empty */ struct Node *head = NULL; struct Node *head1 = NULL; struct Node *head2 = NULL; /* Created linked list will be 12->56->2->11 */ push(&head, 12); push(&head, 56); push(&head, 2); push(&head, 11); printf(\"Original Circular Linked List\"); printList(head); /* Split the list */ splitList(head, &head1, &head2); printf(\"\\nFirst Circular Linked List\"); printList(head1); printf(\"\\nSecond Circular Linked List\"); printList(head2); getchar(); return 0;} ",
"e": 6324,
"s": 3578,
"text": null
},
{
"code": "// Java program to delete a node from doubly linked list class LinkedList { static Node head, head1, head2; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } /* Function to split a list (starting with head) into two lists. head1_ref and head2_ref are references to head nodes of the two resultant linked lists */ void splitList() { Node slow_ptr = head; Node fast_ptr = head; if (head == null) { return; } /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while (fast_ptr.next != head && fast_ptr.next.next != head) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } /* If there are even elements in list then move fast_ptr */ if (fast_ptr.next.next == head) { fast_ptr = fast_ptr.next; } /* Set the head pointer of first half */ head1 = head; /* Set the head pointer of second half */ if (head.next != head) { head2 = slow_ptr.next; } /* Make second half circular */ fast_ptr.next = slow_ptr.next; /* Make first half circular */ slow_ptr.next = head; } /* Function to print nodes in a given singly linked list */ void printList(Node node) { Node temp = node; if (node != null) { do { System.out.print(temp.data + \" \"); temp = temp.next; } while (temp != node); } } public static void main(String[] args) { LinkedList list = new LinkedList(); //Created linked list will be 12->56->2->11 list.head = new Node(12); list.head.next = new Node(56); list.head.next.next = new Node(2); list.head.next.next.next = new Node(11); list.head.next.next.next.next = list.head; System.out.println(\"Original Circular Linked list \"); list.printList(head); // Split the list list.splitList(); System.out.println(\"\"); System.out.println(\"First Circular List \"); list.printList(head1); System.out.println(\"\"); System.out.println(\"Second Circular List \"); list.printList(head2); }} // This code has been contributed by Mayank Jaiswal",
"e": 8826,
"s": 6324,
"text": null
},
{
"code": "# Python program to split circular linked list into two halves # A node structureclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # Class to create a new Circular Linked listclass CircularLinkedList: # Constructor to create a empty circular linked list def __init__(self): self.head = None # Function to insert a node at the beginning of a # circular linked list def push(self, data): ptr1 = Node(data) temp = self.head ptr1.next = self.head # If linked list is not None then set the next of # last node if self.head is not None: while(temp.next != self.head): temp = temp.next temp.next = ptr1 else: ptr1.next = ptr1 # For the first node self.head = ptr1 # Function to print nodes in a given circular linked list def printList(self): temp = self.head if self.head is not None: while(True): print (\"%d\" %(temp.data),end=' ') temp = temp.next if (temp == self.head): break # Function to split a list (starting with head) into # two lists. head1 and head2 are the head nodes of the # two resultant linked lists def splitList(self, head1, head2): slow_ptr = self.head fast_ptr = self.head if self.head is None: return # If there are odd nodes in the circular list then # fast_ptr->next becomes head and for even nodes # fast_ptr->next->next becomes head while(fast_ptr.next != self.head and fast_ptr.next.next != self.head ): fast_ptr = fast_ptr.next.next slow_ptr = slow_ptr.next # If there are even elements in list then # move fast_ptr if fast_ptr.next.next == self.head: fast_ptr = fast_ptr.next # Set the head pointer of first half head1.head = self.head # Set the head pointer of second half if self.head.next != self.head: head2.head = slow_ptr.next # Make second half circular fast_ptr.next = slow_ptr.next # Make first half circular slow_ptr.next = self.head # Driver program to test above functions # Initialize lists as emptyhead = CircularLinkedList() head1 = CircularLinkedList()head2 = CircularLinkedList() head.push(12)head.push(56)head.push(2)head.push(11) print (\"Original Circular Linked List\")head.printList() # Split the list head.splitList(head1 , head2) print (\"\\nFirst Circular Linked List\")head1.printList() print (\"\\nSecond Circular Linked List\")head2.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 11666,
"s": 8826,
"text": null
},
{
"code": "// C# program to delete a node// from doubly linked listusing System;class GFG{ public Node head, head1, head2; public class Node { public int data; public Node next, prev; public Node(int d) { data = d; next = prev = null; } } /* Function to split a list (starting with head) into two lists. head1_ref and head2_ref are references to head nodes of the two resultant linked lists */ void splitList() { Node slow_ptr = head; Node fast_ptr = head; if (head == null) { return; } /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while (fast_ptr.next != head && fast_ptr.next.next != head) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } /* If there are even elements in list then move fast_ptr */ if (fast_ptr.next.next == head) { fast_ptr = fast_ptr.next; } /* Set the head pointer of first half */ head1 = head; /* Set the head pointer of second half */ if (head.next != head) { head2 = slow_ptr.next; } /* Make second half circular */ fast_ptr.next = slow_ptr.next; /* Make first half circular */ slow_ptr.next = head; } /* Function to print nodes in a given singly linked list */ void printList(Node node) { Node temp = node; if (node != null) { do { Console.Write(temp.data + \" \"); temp = temp.next; } while (temp != node); } } public static void Main(String[] args) { GFG list = new GFG(); // Created linked list will be 12->56->2->11 list.head = new Node(12); list.head.next = new Node(56); list.head.next.next = new Node(2); list.head.next.next.next = new Node(11); list.head.next.next.next.next = list.head; Console.WriteLine(\"Original Circular Linked list \"); list.printList(list.head); // Split the list list.splitList(); Console.WriteLine(\"\"); Console.WriteLine(\"First Circular List \"); list.printList(list.head1); Console.WriteLine(\"\"); Console.WriteLine(\"Second Circular List \"); list.printList(list.head2); }} // This code is contributed by PrinciRaj1992",
"e": 14264,
"s": 11666,
"text": null
},
{
"code": "<script> class Node{ constructor(d) { this.data = d; this.next = this.prev = null; }} let head, head1, head2; function splitList(){ let slow_ptr = head; let fast_ptr = head; if (head == null) { return; } /* If there are odd nodes in the circular list then fast_ptr->next becomes head and for even nodes fast_ptr->next->next becomes head */ while (fast_ptr.next != head && fast_ptr.next.next != head) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } /* If there are even elements in list then move fast_ptr */ if (fast_ptr.next.next == head) { fast_ptr = fast_ptr.next; } /* Set the head pointer of first half */ head1 = head; /* Set the head pointer of second half */ if (head.next != head) { head2 = slow_ptr.next; } /* Make second half circular */ fast_ptr.next = slow_ptr.next; /* Make first half circular */ slow_ptr.next = head; } /* Function to print nodes in a given singly linked list */ function printList(node) { let temp = node; if (node != null) { do { document.write(temp.data + \" \"); temp = temp.next; } while (temp != node); } } //Created linked list will be 12->56->2->11head = new Node(12);head.next = new Node(56);head.next.next = new Node(2);head.next.next.next = new Node(11);head.next.next.next.next = head; document.write(\"Original Circular Linked list <br>\");printList(head); // Split the listsplitList();document.write(\"<br>\");document.write(\"First Circular List <br>\");printList(head1);document.write(\"<br>\");document.write(\"Second Circular List <br>\");printList(head2); // This code is contributed by avanitrachhadiya2155</script>",
"e": 16206,
"s": 14264,
"text": null
},
{
"code": null,
"e": 16216,
"s": 16206,
"text": "Output: "
},
{
"code": null,
"e": 16326,
"s": 16216,
"text": "Original Circular Linked List\n11 2 56 12 \nFirst Circular Linked List\n11 2 \nSecond Circular Linked List\n56 12 "
},
{
"code": null,
"e": 16392,
"s": 16326,
"text": "Time Complexity: O(n) As we are only moving once through the list"
},
{
"code": null,
"e": 16552,
"s": 16392,
"text": "Auxiliary Space: O(1) As no extra space is usedPlease write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem "
},
{
"code": null,
"e": 16566,
"s": 16552,
"text": "shubham_singh"
},
{
"code": null,
"e": 16580,
"s": 16566,
"text": "rathbhupendra"
},
{
"code": null,
"e": 16594,
"s": 16580,
"text": "princiraj1992"
},
{
"code": null,
"e": 16605,
"s": 16594,
"text": "aditosh007"
},
{
"code": null,
"e": 16626,
"s": 16605,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 16642,
"s": 16626,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 16655,
"s": 16642,
"text": "simmytarika5"
},
{
"code": null,
"e": 16669,
"s": 16655,
"text": "abhijeet19403"
},
{
"code": null,
"e": 16690,
"s": 16669,
"text": "circular linked list"
},
{
"code": null,
"e": 16696,
"s": 16690,
"text": "Yahoo"
},
{
"code": null,
"e": 16708,
"s": 16696,
"text": "Linked List"
},
{
"code": null,
"e": 16714,
"s": 16708,
"text": "Yahoo"
},
{
"code": null,
"e": 16726,
"s": 16714,
"text": "Linked List"
},
{
"code": null,
"e": 16747,
"s": 16726,
"text": "circular linked list"
},
{
"code": null,
"e": 16845,
"s": 16747,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16864,
"s": 16845,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 16896,
"s": 16864,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 16952,
"s": 16896,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 16981,
"s": 16952,
"text": "Detect loop in a linked list"
},
{
"code": null,
"e": 17011,
"s": 16981,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 17075,
"s": 17011,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 17114,
"s": 17075,
"text": "Find the middle of a given linked list"
},
{
"code": null,
"e": 17135,
"s": 17114,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 17163,
"s": 17135,
"text": "Merge Sort for Linked Lists"
}
]
|
Gradient Descent algorithm and its variants | 02 Jun, 2020
Gradient Descent is an optimization algorithm used for minimizing the cost function in various machine learning algorithms. It is basically used for updating the parameters of the learning model.
Types of gradient Descent:
Batch Gradient Descent: This is a type of gradient descent which processes all the training examples for each iteration of gradient descent. But if the number of training examples is large, then batch gradient descent is computationally very expensive. Hence if the number of training examples is large, then batch gradient descent is not preferred. Instead, we prefer to use stochastic gradient descent or mini-batch gradient descent.Stochastic Gradient Descent: This is a type of gradient descent which processes 1 training example per iteration. Hence, the parameters are being updated even after one iteration in which only a single example has been processed. Hence this is quite faster than batch gradient descent. But again, when the number of training examples is large, even then it processes only one example which can be additional overhead for the system as the number of iterations will be quite large.Mini Batch gradient descent: This is a type of gradient descent which works faster than both batch gradient descent and stochastic gradient descent. Here b examples where b<m are processed per iteration. So even if the number of training examples is large, it is processed in batches of b training examples in one go. Thus, it works for larger training examples and that too with lesser number of iterations. Variables used:Let m be the number of training examples.Let n be the number of features.Note: if b == m, then mini batch gradient descent will behave similarly to batch gradient descent.Algorithm for batch gradient descent :Let hθ(x) be the hypothesis for linear regression. Then, the cost function is given by:Let Σ represents the sum of all training examples from i=1 to m.Jtrain(θ) = (1/2m) Σ( hθ(x(i)) - y(i))2
Repeat {
θj = θj – (learning rate/m) * Σ( hθ(x(i)) - y(i))xj(i)
For every j =0 ...n
}Where xj(i) Represents the jth feature of the ith training example. So if m is very large(e.g. 5 million training samples), then it takes hours or even days to converge to the global minimum.That’s why for large datasets, it is not recommended to use batch gradient descent as it slows down the learning. Algorithm for stochastic gradient descent:1) Randomly shuffle the data set so that the parameters can be trained evenly for each type of data.2) As mentioned above, it takes into consideration one example per iteration.Hence,
Let (x(i),y(i)) be the training example
Cost(θ, (x(i),y(i))) = (1/2) Σ( hθ(x(i)) - y(i))2
Jtrain(θ) = (1/m) Σ Cost(θ, (x(i),y(i)))
Repeat {
For i=1 to m{
θj = θj – (learning rate) * Σ( hθ(x(i)) - y(i))xj(i)
For every j =0 ...n
}
} Algorithm for mini batch gradient descent:Say b be the no of examples in one batch, where b < m.Assume b = 10, m = 100;Note: However we can adjust the batch size. It is generally kept as power of 2. The reason behind it is because some hardware such as GPUs achieve better run time with common batch sizes such as power of 2.Repeat {
For i=1,11, 21,.....,91
Let Σ be the summation from i to i+9 represented by k.
θj = θj – (learning rate/size of (b) ) * Σ( hθ(x(k)) - y(k))xj(k)
For every j =0 ...n
}
Convergence trends in different variants of Gradient Descents:In case of Batch Gradient Descent, the algorithm follows a straight path towards the minimum. If the cost function is convex, then it converges to a global minimum and if the cost function is not convex, then it converges to a local minimum. Here the learning rate is typically held constant.In case of stochastic gradient Descent and mini-batch gradient descent, the algorithm does not converge but keeps on fluctuating around the global minimum. Therefore in order to make it converge, we have to slowly change the learning rate. However the convergence of Stochastic gradient descent is much noisier as in one iteration, it processes only one training example.My Personal Notes
arrow_drop_upSave
Batch Gradient Descent: This is a type of gradient descent which processes all the training examples for each iteration of gradient descent. But if the number of training examples is large, then batch gradient descent is computationally very expensive. Hence if the number of training examples is large, then batch gradient descent is not preferred. Instead, we prefer to use stochastic gradient descent or mini-batch gradient descent.
Stochastic Gradient Descent: This is a type of gradient descent which processes 1 training example per iteration. Hence, the parameters are being updated even after one iteration in which only a single example has been processed. Hence this is quite faster than batch gradient descent. But again, when the number of training examples is large, even then it processes only one example which can be additional overhead for the system as the number of iterations will be quite large.
Mini Batch gradient descent: This is a type of gradient descent which works faster than both batch gradient descent and stochastic gradient descent. Here b examples where b<m are processed per iteration. So even if the number of training examples is large, it is processed in batches of b training examples in one go. Thus, it works for larger training examples and that too with lesser number of iterations.
Variables used:Let m be the number of training examples.Let n be the number of features.
Note: if b == m, then mini batch gradient descent will behave similarly to batch gradient descent.
Algorithm for batch gradient descent :Let hθ(x) be the hypothesis for linear regression. Then, the cost function is given by:Let Σ represents the sum of all training examples from i=1 to m.
Jtrain(θ) = (1/2m) Σ( hθ(x(i)) - y(i))2
Repeat {
θj = θj – (learning rate/m) * Σ( hθ(x(i)) - y(i))xj(i)
For every j =0 ...n
}
Where xj(i) Represents the jth feature of the ith training example. So if m is very large(e.g. 5 million training samples), then it takes hours or even days to converge to the global minimum.That’s why for large datasets, it is not recommended to use batch gradient descent as it slows down the learning.
Algorithm for stochastic gradient descent:1) Randomly shuffle the data set so that the parameters can be trained evenly for each type of data.2) As mentioned above, it takes into consideration one example per iteration.
Hence,
Let (x(i),y(i)) be the training example
Cost(θ, (x(i),y(i))) = (1/2) Σ( hθ(x(i)) - y(i))2
Jtrain(θ) = (1/m) Σ Cost(θ, (x(i),y(i)))
Repeat {
For i=1 to m{
θj = θj – (learning rate) * Σ( hθ(x(i)) - y(i))xj(i)
For every j =0 ...n
}
}
Algorithm for mini batch gradient descent:Say b be the no of examples in one batch, where b < m.Assume b = 10, m = 100;
Note: However we can adjust the batch size. It is generally kept as power of 2. The reason behind it is because some hardware such as GPUs achieve better run time with common batch sizes such as power of 2.
Repeat {
For i=1,11, 21,.....,91
Let Σ be the summation from i to i+9 represented by k.
θj = θj – (learning rate/size of (b) ) * Σ( hθ(x(k)) - y(k))xj(k)
For every j =0 ...n
}
Convergence trends in different variants of Gradient Descents:
In case of Batch Gradient Descent, the algorithm follows a straight path towards the minimum. If the cost function is convex, then it converges to a global minimum and if the cost function is not convex, then it converges to a local minimum. Here the learning rate is typically held constant.
In case of stochastic gradient Descent and mini-batch gradient descent, the algorithm does not converge but keeps on fluctuating around the global minimum. Therefore in order to make it converge, we have to slowly change the learning rate. However the convergence of Stochastic gradient descent is much noisier as in one iteration, it processes only one training example.
letsCplusPlus
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Getting started with Machine Learning
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
Random Forest Regression in Python
ML | Underfitting and Overfitting
Running Python script on GPU.
Association Rule
Clustering in Machine Learning
Elbow Method for optimal value of k in KMeans
Python | Decision tree implementation | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 248,
"s": 52,
"text": "Gradient Descent is an optimization algorithm used for minimizing the cost function in various machine learning algorithms. It is basically used for updating the parameters of the learning model."
},
{
"code": null,
"e": 275,
"s": 248,
"text": "Types of gradient Descent:"
},
{
"code": null,
"e": 4196,
"s": 275,
"text": "Batch Gradient Descent: This is a type of gradient descent which processes all the training examples for each iteration of gradient descent. But if the number of training examples is large, then batch gradient descent is computationally very expensive. Hence if the number of training examples is large, then batch gradient descent is not preferred. Instead, we prefer to use stochastic gradient descent or mini-batch gradient descent.Stochastic Gradient Descent: This is a type of gradient descent which processes 1 training example per iteration. Hence, the parameters are being updated even after one iteration in which only a single example has been processed. Hence this is quite faster than batch gradient descent. But again, when the number of training examples is large, even then it processes only one example which can be additional overhead for the system as the number of iterations will be quite large.Mini Batch gradient descent: This is a type of gradient descent which works faster than both batch gradient descent and stochastic gradient descent. Here b examples where b<m are processed per iteration. So even if the number of training examples is large, it is processed in batches of b training examples in one go. Thus, it works for larger training examples and that too with lesser number of iterations. Variables used:Let m be the number of training examples.Let n be the number of features.Note: if b == m, then mini batch gradient descent will behave similarly to batch gradient descent.Algorithm for batch gradient descent :Let hθ(x) be the hypothesis for linear regression. Then, the cost function is given by:Let Σ represents the sum of all training examples from i=1 to m.Jtrain(θ) = (1/2m) Σ( hθ(x(i)) - y(i))2\n\nRepeat {\n θj = θj – (learning rate/m) * Σ( hθ(x(i)) - y(i))xj(i)\n For every j =0 ...n \n}Where xj(i) Represents the jth feature of the ith training example. So if m is very large(e.g. 5 million training samples), then it takes hours or even days to converge to the global minimum.That’s why for large datasets, it is not recommended to use batch gradient descent as it slows down the learning. Algorithm for stochastic gradient descent:1) Randomly shuffle the data set so that the parameters can be trained evenly for each type of data.2) As mentioned above, it takes into consideration one example per iteration.Hence,\nLet (x(i),y(i)) be the training example\nCost(θ, (x(i),y(i))) = (1/2) Σ( hθ(x(i)) - y(i))2\n\nJtrain(θ) = (1/m) Σ Cost(θ, (x(i),y(i)))\n\nRepeat {\n\nFor i=1 to m{\n\n θj = θj – (learning rate) * Σ( hθ(x(i)) - y(i))xj(i)\n For every j =0 ...n\n\n } \n} Algorithm for mini batch gradient descent:Say b be the no of examples in one batch, where b < m.Assume b = 10, m = 100;Note: However we can adjust the batch size. It is generally kept as power of 2. The reason behind it is because some hardware such as GPUs achieve better run time with common batch sizes such as power of 2.Repeat {\n For i=1,11, 21,.....,91\n\n Let Σ be the summation from i to i+9 represented by k. \n\n θj = θj – (learning rate/size of (b) ) * Σ( hθ(x(k)) - y(k))xj(k)\n For every j =0 ...n\n\n}\n Convergence trends in different variants of Gradient Descents:In case of Batch Gradient Descent, the algorithm follows a straight path towards the minimum. If the cost function is convex, then it converges to a global minimum and if the cost function is not convex, then it converges to a local minimum. Here the learning rate is typically held constant.In case of stochastic gradient Descent and mini-batch gradient descent, the algorithm does not converge but keeps on fluctuating around the global minimum. Therefore in order to make it converge, we have to slowly change the learning rate. However the convergence of Stochastic gradient descent is much noisier as in one iteration, it processes only one training example.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4632,
"s": 4196,
"text": "Batch Gradient Descent: This is a type of gradient descent which processes all the training examples for each iteration of gradient descent. But if the number of training examples is large, then batch gradient descent is computationally very expensive. Hence if the number of training examples is large, then batch gradient descent is not preferred. Instead, we prefer to use stochastic gradient descent or mini-batch gradient descent."
},
{
"code": null,
"e": 5113,
"s": 4632,
"text": "Stochastic Gradient Descent: This is a type of gradient descent which processes 1 training example per iteration. Hence, the parameters are being updated even after one iteration in which only a single example has been processed. Hence this is quite faster than batch gradient descent. But again, when the number of training examples is large, even then it processes only one example which can be additional overhead for the system as the number of iterations will be quite large."
},
{
"code": null,
"e": 5522,
"s": 5113,
"text": "Mini Batch gradient descent: This is a type of gradient descent which works faster than both batch gradient descent and stochastic gradient descent. Here b examples where b<m are processed per iteration. So even if the number of training examples is large, it is processed in batches of b training examples in one go. Thus, it works for larger training examples and that too with lesser number of iterations."
},
{
"code": null,
"e": 5612,
"s": 5522,
"text": " Variables used:Let m be the number of training examples.Let n be the number of features."
},
{
"code": null,
"e": 5711,
"s": 5612,
"text": "Note: if b == m, then mini batch gradient descent will behave similarly to batch gradient descent."
},
{
"code": null,
"e": 5901,
"s": 5711,
"text": "Algorithm for batch gradient descent :Let hθ(x) be the hypothesis for linear regression. Then, the cost function is given by:Let Σ represents the sum of all training examples from i=1 to m."
},
{
"code": null,
"e": 6036,
"s": 5901,
"text": "Jtrain(θ) = (1/2m) Σ( hθ(x(i)) - y(i))2\n\nRepeat {\n θj = θj – (learning rate/m) * Σ( hθ(x(i)) - y(i))xj(i)\n For every j =0 ...n \n}"
},
{
"code": null,
"e": 6341,
"s": 6036,
"text": "Where xj(i) Represents the jth feature of the ith training example. So if m is very large(e.g. 5 million training samples), then it takes hours or even days to converge to the global minimum.That’s why for large datasets, it is not recommended to use batch gradient descent as it slows down the learning."
},
{
"code": null,
"e": 6562,
"s": 6341,
"text": " Algorithm for stochastic gradient descent:1) Randomly shuffle the data set so that the parameters can be trained evenly for each type of data.2) As mentioned above, it takes into consideration one example per iteration."
},
{
"code": null,
"e": 6841,
"s": 6562,
"text": "Hence,\nLet (x(i),y(i)) be the training example\nCost(θ, (x(i),y(i))) = (1/2) Σ( hθ(x(i)) - y(i))2\n\nJtrain(θ) = (1/m) Σ Cost(θ, (x(i),y(i)))\n\nRepeat {\n\nFor i=1 to m{\n\n θj = θj – (learning rate) * Σ( hθ(x(i)) - y(i))xj(i)\n For every j =0 ...n\n\n } \n}"
},
{
"code": null,
"e": 6962,
"s": 6841,
"text": " Algorithm for mini batch gradient descent:Say b be the no of examples in one batch, where b < m.Assume b = 10, m = 100;"
},
{
"code": null,
"e": 7169,
"s": 6962,
"text": "Note: However we can adjust the batch size. It is generally kept as power of 2. The reason behind it is because some hardware such as GPUs achieve better run time with common batch sizes such as power of 2."
},
{
"code": null,
"e": 7368,
"s": 7169,
"text": "Repeat {\n For i=1,11, 21,.....,91\n\n Let Σ be the summation from i to i+9 represented by k. \n\n θj = θj – (learning rate/size of (b) ) * Σ( hθ(x(k)) - y(k))xj(k)\n For every j =0 ...n\n\n}\n"
},
{
"code": null,
"e": 7433,
"s": 7370,
"text": "Convergence trends in different variants of Gradient Descents:"
},
{
"code": null,
"e": 7726,
"s": 7433,
"text": "In case of Batch Gradient Descent, the algorithm follows a straight path towards the minimum. If the cost function is convex, then it converges to a global minimum and if the cost function is not convex, then it converges to a local minimum. Here the learning rate is typically held constant."
},
{
"code": null,
"e": 8098,
"s": 7726,
"text": "In case of stochastic gradient Descent and mini-batch gradient descent, the algorithm does not converge but keeps on fluctuating around the global minimum. Therefore in order to make it converge, we have to slowly change the learning rate. However the convergence of Stochastic gradient descent is much noisier as in one iteration, it processes only one training example."
},
{
"code": null,
"e": 8112,
"s": 8098,
"text": "letsCplusPlus"
},
{
"code": null,
"e": 8129,
"s": 8112,
"text": "Machine Learning"
},
{
"code": null,
"e": 8146,
"s": 8129,
"text": "Machine Learning"
},
{
"code": null,
"e": 8244,
"s": 8146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8282,
"s": 8244,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 8315,
"s": 8282,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 8356,
"s": 8315,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 8391,
"s": 8356,
"text": "Random Forest Regression in Python"
},
{
"code": null,
"e": 8425,
"s": 8391,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 8455,
"s": 8425,
"text": "Running Python script on GPU."
},
{
"code": null,
"e": 8472,
"s": 8455,
"text": "Association Rule"
},
{
"code": null,
"e": 8503,
"s": 8472,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 8549,
"s": 8503,
"text": "Elbow Method for optimal value of k in KMeans"
}
]
|
Python | Decimal from_float() method | 23 May, 2022
Decimal#from_float() : from_float() is a Decimal class method which converts a float to a decimal number, exactly.
Syntax: Decimal.from_float() Parameter: Decimal values Return: converts a float to a decimal number, exactly.
Code #1 : Example for from_float() method
Python3
# Python Program explaining# from_float() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.from_float() methodprint ("\n\nDecimal a with from_float() method : ", a.from_float(0.1)) print ("Decimal b with from_float() method : ", b.from_float(float('nan')))
Output :
Decimal value a : -1
Decimal value b : 0.142857
Decimal a with from_float() method : 0.1000000000000000055511151231257827021181583404541015625
Decimal b with from_float() method : NaN
Code #2 : Example for from_float() method
Python3
# Python Program explaining# from_float() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.from_float() methodprint ("\n\nDecimal a with from_float() method : ", a.from_float(0.02)) print ("Decimal b with from_float() method : ", b.from_float(float('-inf')))
Output :
Decimal value a : -3.14
Decimal value b : 3.21E+7
Decimal a with from_float() method : 0.0200000000000000004163336342344337026588618755340576171875
Decimal b with from_float() method : -Infinity
sweetyty
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 144,
"s": 28,
"text": "Decimal#from_float() : from_float() is a Decimal class method which converts a float to a decimal number, exactly."
},
{
"code": null,
"e": 255,
"s": 144,
"text": "Syntax: Decimal.from_float() Parameter: Decimal values Return: converts a float to a decimal number, exactly."
},
{
"code": null,
"e": 298,
"s": 255,
"text": "Code #1 : Example for from_float() method "
},
{
"code": null,
"e": 306,
"s": 298,
"text": "Python3"
},
{
"code": "# Python Program explaining# from_float() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.from_float() methodprint (\"\\n\\nDecimal a with from_float() method : \", a.from_float(0.1)) print (\"Decimal b with from_float() method : \", b.from_float(float('nan')))",
"e": 744,
"s": 306,
"text": null
},
{
"code": null,
"e": 753,
"s": 744,
"text": "Output :"
},
{
"code": null,
"e": 943,
"s": 753,
"text": "Decimal value a : -1\nDecimal value b : 0.142857\n\n\nDecimal a with from_float() method : 0.1000000000000000055511151231257827021181583404541015625\nDecimal b with from_float() method : NaN"
},
{
"code": null,
"e": 986,
"s": 943,
"text": "Code #2 : Example for from_float() method "
},
{
"code": null,
"e": 994,
"s": 986,
"text": "Python3"
},
{
"code": "# Python Program explaining# from_float() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.from_float() methodprint (\"\\n\\nDecimal a with from_float() method : \", a.from_float(0.02)) print (\"Decimal b with from_float() method : \", b.from_float(float('-inf')))",
"e": 1439,
"s": 994,
"text": null
},
{
"code": null,
"e": 1448,
"s": 1439,
"text": "Output :"
},
{
"code": null,
"e": 1649,
"s": 1448,
"text": "Decimal value a : -3.14\nDecimal value b : 3.21E+7\n\n\nDecimal a with from_float() method : 0.0200000000000000004163336342344337026588618755340576171875\nDecimal b with from_float() method : -Infinity"
},
{
"code": null,
"e": 1658,
"s": 1649,
"text": "sweetyty"
},
{
"code": null,
"e": 1665,
"s": 1658,
"text": "Python"
},
{
"code": null,
"e": 1763,
"s": 1665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1795,
"s": 1763,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1822,
"s": 1795,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1843,
"s": 1822,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1866,
"s": 1843,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1922,
"s": 1866,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1953,
"s": 1922,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1995,
"s": 1953,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2037,
"s": 1995,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2076,
"s": 2037,
"text": "Python | Get unique values from a list"
}
]
|
Output of C programs | Set 39 (Pre Increment and Post Increment) | 24 Sep, 2021
Prerequisite : Pre-increment and Post increment Question 1
C
#include <stdio.h> int main(){ char* p = "mayhem"; char c; int i; for (i = 0; i < 3; i++) { c = *p++; } printf("%c", c); return 0;}
yhea
y
h
e
a
Answer : y
Explanation: The pointer ‘p’ points at the third location of the character array. The reason is that in the ‘for’ loop iteration, the value of the character pointer ‘p’ has been incremented thrice.Question 2
CPP
#include<stdio.h>void test(char c[]){ c=c+2; c--; printf("%c",*c);}int main(){ char ch[5]={'p','o','u','r'}; test(ch); return 0;}
What is the output of the above program?
pour
p
o
u
r
Answer: o
Explanation: When the character array ‘ch’ is passed as an argument to the function ‘test()’, the base address of the array ‘ch[]’ is passed. The variable ‘c’ in the function ‘test()’ points at the second location of the array. And then it decrements by 1 pointing to ‘o’.Question 3
C
#include<stdio.h>int main(){ int i; char ch[] = {'x', 'y', 'z'}; char *ptr, *str1; ptr = ch; str1 = ch; i = (*ptr-- + ++*str1) - 10; printf("%d", i); return 0;}
What is the output of the above program if the ASCII values of characters ‘x’=120, ‘y’=121, ‘z’=122?
231233232363
231
233
232
363
Answer : 231
Explanation: The pointer ptr points to ‘x’. Step1: Since, it is a post-decrement operation, hence the value remains 120 and is decremented later. Step2 :The pointer str1 points at ‘x’. Since ++ and * have same precedence level evaluation starts from Right to Left. For the expression ++*str1, Firstly *str1 is evaluated which gives 120 i.e. ASCII Equivalent of x. Next we evaluate the prefix increment ++120 = 121. Hence the final result is (120+121)-10=131
Question 4 – What will be the output of following Program?
CPP
#include<stdio.h> int main(void){ char *ptr = "Linux"; printf("\n [%c] \n", *ptr++); printf("\n [%c] \n", *ptr); return 0;}
Output :
[L]
[i]
Explanation : Since the priority of both ‘++’ and ‘*’ are same so processing of ‘*ptr++’ takes place from right to left. Going by this logic, ptr++ is evaluated first and then *ptr. So both these operations result in ‘L’. Now since a postfix ‘++’ was applied on ptr so the next printf() would print ‘i’.Question 5 – What will be the output of following Program?
CPP
#include <stdio.h>int main(){ int num1 = 5; int num2 = 3; int num3 = 2; num1 = num2++; num2 = --num3; printf("%d %d %d", num1, num2, num3); return 0;}
231311327321
231
311
327
321
Answer:311
This article is contributed by Brahmani Sai. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
DhineshJ
chenosebu
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of C++ programs | Set 44
Runtime Errors
Different ways to copy a string in C/C++
Output of C++ Program | Set 1
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Output of Java Programs | Set 12
Output of Java program | Set 5
Output of Java Program | Set 6
Output of Java program | Set 15 (Inner Classes)
Output of Java Programs | Set 48 (Static keyword) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 113,
"s": 52,
"text": "Prerequisite : Pre-increment and Post increment Question 1 "
},
{
"code": null,
"e": 115,
"s": 113,
"text": "C"
},
{
"code": "#include <stdio.h> int main(){ char* p = \"mayhem\"; char c; int i; for (i = 0; i < 3; i++) { c = *p++; } printf(\"%c\", c); return 0;}",
"e": 276,
"s": 115,
"text": null
},
{
"code": null,
"e": 281,
"s": 276,
"text": "yhea"
},
{
"code": null,
"e": 283,
"s": 281,
"text": "y"
},
{
"code": null,
"e": 285,
"s": 283,
"text": "h"
},
{
"code": null,
"e": 287,
"s": 285,
"text": "e"
},
{
"code": null,
"e": 289,
"s": 287,
"text": "a"
},
{
"code": null,
"e": 301,
"s": 289,
"text": "Answer : y "
},
{
"code": null,
"e": 511,
"s": 301,
"text": "Explanation: The pointer ‘p’ points at the third location of the character array. The reason is that in the ‘for’ loop iteration, the value of the character pointer ‘p’ has been incremented thrice.Question 2 "
},
{
"code": null,
"e": 515,
"s": 511,
"text": "CPP"
},
{
"code": "#include<stdio.h>void test(char c[]){ c=c+2; c--; printf(\"%c\",*c);}int main(){ char ch[5]={'p','o','u','r'}; test(ch); return 0;}",
"e": 668,
"s": 515,
"text": null
},
{
"code": null,
"e": 711,
"s": 668,
"text": "What is the output of the above program? "
},
{
"code": null,
"e": 716,
"s": 711,
"text": "pour"
},
{
"code": null,
"e": 718,
"s": 716,
"text": "p"
},
{
"code": null,
"e": 720,
"s": 718,
"text": "o"
},
{
"code": null,
"e": 722,
"s": 720,
"text": "u"
},
{
"code": null,
"e": 724,
"s": 722,
"text": "r"
},
{
"code": null,
"e": 737,
"s": 726,
"text": "Answer: o "
},
{
"code": null,
"e": 1022,
"s": 737,
"text": "Explanation: When the character array ‘ch’ is passed as an argument to the function ‘test()’, the base address of the array ‘ch[]’ is passed. The variable ‘c’ in the function ‘test()’ points at the second location of the array. And then it decrements by 1 pointing to ‘o’.Question 3 "
},
{
"code": null,
"e": 1024,
"s": 1022,
"text": "C"
},
{
"code": "#include<stdio.h>int main(){ int i; char ch[] = {'x', 'y', 'z'}; char *ptr, *str1; ptr = ch; str1 = ch; i = (*ptr-- + ++*str1) - 10; printf(\"%d\", i); return 0;}",
"e": 1214,
"s": 1024,
"text": null
},
{
"code": null,
"e": 1317,
"s": 1214,
"text": "What is the output of the above program if the ASCII values of characters ‘x’=120, ‘y’=121, ‘z’=122? "
},
{
"code": null,
"e": 1330,
"s": 1317,
"text": "231233232363"
},
{
"code": null,
"e": 1334,
"s": 1330,
"text": "231"
},
{
"code": null,
"e": 1338,
"s": 1334,
"text": "233"
},
{
"code": null,
"e": 1342,
"s": 1338,
"text": "232"
},
{
"code": null,
"e": 1346,
"s": 1342,
"text": "363"
},
{
"code": null,
"e": 1361,
"s": 1348,
"text": "Answer : 231"
},
{
"code": null,
"e": 1819,
"s": 1361,
"text": "Explanation: The pointer ptr points to ‘x’. Step1: Since, it is a post-decrement operation, hence the value remains 120 and is decremented later. Step2 :The pointer str1 points at ‘x’. Since ++ and * have same precedence level evaluation starts from Right to Left. For the expression ++*str1, Firstly *str1 is evaluated which gives 120 i.e. ASCII Equivalent of x. Next we evaluate the prefix increment ++120 = 121. Hence the final result is (120+121)-10=131"
},
{
"code": null,
"e": 1880,
"s": 1819,
"text": "Question 4 – What will be the output of following Program? "
},
{
"code": null,
"e": 1884,
"s": 1880,
"text": "CPP"
},
{
"code": "#include<stdio.h> int main(void){ char *ptr = \"Linux\"; printf(\"\\n [%c] \\n\", *ptr++); printf(\"\\n [%c] \\n\", *ptr); return 0;}",
"e": 2021,
"s": 1884,
"text": null
},
{
"code": null,
"e": 2032,
"s": 2021,
"text": "Output : "
},
{
"code": null,
"e": 2050,
"s": 2032,
"text": " [L] \n\n [i]"
},
{
"code": null,
"e": 2414,
"s": 2050,
"text": "Explanation : Since the priority of both ‘++’ and ‘*’ are same so processing of ‘*ptr++’ takes place from right to left. Going by this logic, ptr++ is evaluated first and then *ptr. So both these operations result in ‘L’. Now since a postfix ‘++’ was applied on ptr so the next printf() would print ‘i’.Question 5 – What will be the output of following Program? "
},
{
"code": null,
"e": 2418,
"s": 2414,
"text": "CPP"
},
{
"code": "#include <stdio.h>int main(){ int num1 = 5; int num2 = 3; int num3 = 2; num1 = num2++; num2 = --num3; printf(\"%d %d %d\", num1, num2, num3); return 0;}",
"e": 2618,
"s": 2418,
"text": null
},
{
"code": null,
"e": 2631,
"s": 2618,
"text": "231311327321"
},
{
"code": null,
"e": 2635,
"s": 2631,
"text": "231"
},
{
"code": null,
"e": 2639,
"s": 2635,
"text": "311"
},
{
"code": null,
"e": 2643,
"s": 2639,
"text": "327"
},
{
"code": null,
"e": 2647,
"s": 2643,
"text": "321"
},
{
"code": null,
"e": 2659,
"s": 2647,
"text": "Answer:311 "
},
{
"code": null,
"e": 3080,
"s": 2659,
"text": "This article is contributed by Brahmani Sai. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3089,
"s": 3080,
"text": "DhineshJ"
},
{
"code": null,
"e": 3099,
"s": 3089,
"text": "chenosebu"
},
{
"code": null,
"e": 3108,
"s": 3099,
"text": "C-Output"
},
{
"code": null,
"e": 3123,
"s": 3108,
"text": "Program Output"
},
{
"code": null,
"e": 3221,
"s": 3123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3253,
"s": 3221,
"text": "Output of C++ programs | Set 44"
},
{
"code": null,
"e": 3268,
"s": 3253,
"text": "Runtime Errors"
},
{
"code": null,
"e": 3309,
"s": 3268,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 3339,
"s": 3309,
"text": "Output of C++ Program | Set 1"
},
{
"code": null,
"e": 3435,
"s": 3339,
"text": "error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++"
},
{
"code": null,
"e": 3468,
"s": 3435,
"text": "Output of Java Programs | Set 12"
},
{
"code": null,
"e": 3499,
"s": 3468,
"text": "Output of Java program | Set 5"
},
{
"code": null,
"e": 3530,
"s": 3499,
"text": "Output of Java Program | Set 6"
},
{
"code": null,
"e": 3578,
"s": 3530,
"text": "Output of Java program | Set 15 (Inner Classes)"
}
]
|
Semantic-UI | Forms | 23 Nov, 2021
Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements.A form is the section of a document that contains a number of input fields such as text field, password, and checkbox, etc.Example 1: This example creating a simple Log In Form.
html
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></head> <body> <div class="ui container"> <h2>Log In</h2> <form class="ui form"> <div class="field"> <label>Username</label> <input type="text" name="Username" placeholder="Username"> </div> <div class="field"> <label>Password</label> <input type="password" name="password" placeholder="Password"> </div> <div class="field"> <div class="ui checkbox"> <input type="checkbox" tabindex="0" class="hidden"> <label>Remember Me</label> </div> </div> <button class="ui button" type="submit"> Log In </button> </form> </div> <script> $('.ui.checkbox').checkbox(); </script></body> </html>
Output:
Example 2: This example creating a form that contains input fields placing parallelly.
html
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></head> <body> <div class="ui container"> <div class="ui form"> <div class="fields"> <div class="field"> <label>Name</label> <input type="text" placeholder="Name"> </div> <div class="field"> <label>E-mail</label> <input type="email" placeholder="E-mail"> </div> <div class="field"> <label>Password</label> <input type="password" placeholder="Password"> </div> </div> </div> </div></body> </html>
Output:
Example 3: This example creating a Text Area.
html
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></head> <body> <div class="ui container"> <div class="ui form"> <div class="field"> <label>Enter Text</label> <textarea rows="6"></textarea> </div> </div> </div></body> </html>
Note: You can skip the rows attribute and get standard size textarea. Output:
Example 4: This example creating the Checkbox. There are a variety of checkbox styles present in semantic-ui, like the standard checkbox, toggle, and slide. And for this, you need the jQuery library imported.
$('.ui.checkbox').checkbox();
html
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script></head> <body> <div class="ui container"> <div class="ui form"> <h2>Checkbox</h2> <div class="inline field"> <div class="ui checkbox"> <input type="checkbox" tabindex="0" class="hidden"> <label>Checkbox</label> </div> </div> <h2>Toggle</h2> <div class="inline field"> <div class="ui toggle checkbox"> <input type="checkbox" tabindex="0" class="hidden"> <label>Toggle</label> </div> </div> <h2>Slider</h2> <div class="inline field"> <div class="ui slider checkbox"> <input type="checkbox" tabindex="0" class="hidden"> <label>Slider</label> </div> <label></label> </div> </div> </div> <script> $('.ui.checkbox').checkbox(); </script></body> </html>
Output:
Example 5: This example creating the Radio Button. For this, you need a jQuery library imported.
$('.ui.radio.checkbox').checkbox();
Complete Code:
html
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div style="margin-top: 20px;" class="ui container"> <div class="ui form"> <h2>Inline Radio Button</h2> <div class="inline fields"> <label for="gender">Gender</label> <div class="field"> <div class="ui radio checkbox"> <input type="radio" name="gender" checked="" tabindex="0" class="hidden"> <label>Male</label> </div> </div> <div class="field"> <div class="ui radio checkbox"> <input type="radio" name="gender" tabindex="0" class="hidden"> <label>Female</label> </div> </div> <div class="field"> <div class="ui radio checkbox"> <input type="radio" name="gender" tabindex="0" class="hidden"> <label>Rather not Say</label> </div> </div> </div> <h2>Grouped Radio Button </h2> <div class="grouped fields"> <label for="branch">Select your Branch</label> <div class="field"> <div class="ui radio checkbox"> <input type="radio" name="branch" checked="" tabindex="0" class="hidden"> <label>CSE</label> </div> </div> <div class="field"> <div class="ui radio checkbox"> <input type="radio" name="branch" tabindex="0" class="hidden"> <label>IT</label> </div> </div> <div class="field"> <div class="ui radio checkbox"> <input type="radio" name="branch" tabindex="0" class="hidden"> <label>ECE</label> </div> </div> <div class="field"> <div class="ui radio checkbox"> <input type="radio" name="branch" tabindex="0" class="hidden"> <label>ME</label> </div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $('.ui.radio.checkbox').checkbox(); </script> </body></html>
Output:
Example 6: This example creating a Dropdown list. For this, you need to import the jQuery library.
$(function() {
$('.ui.dropdown').dropdown();
});
Complete Code:
html
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div style="margin-top: 20px;" class="ui container"> <label>Choose Language</label> <div class="ui selection dropdown"> <input type="hidden" name="language"> <i class="dropdown icon"></i> <div class="default text">Choose Language</div> <div class="menu"> <div class="item" data-value="0">C++</div> <div class="item" data-value="1">Java</div> <div class="item" data-value="2">Python3</div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $(function() { $('.ui.dropdown').dropdown(); }); </script> </body></html>
Output:
Example 7: This example creating the Multiple Select dropdown menu. For this, you need to import the jQuery library.
$(function() {
$('.ui.dropdown').dropdown();
});
Complete Code:
html
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div style="margin-top: 50px;" class="ui container"> <div class="field"> <label>Programming Language</label> <select multiple="" class="ui dropdown"> <option value="">Select Programming Language</option> <option value="cpp">C++</option> <option value="java">Java</option> <option value="py3">Python3</option> <option value="php">PHP</option> <option value="ruby">Ruby</option> <option value="js">JavaScript</option> </select> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> <script> $(function() { $('.ui.dropdown').dropdown(); }); </script> </body></html>
Output:
Example 8: This example creating the status of statement. The state can be any like success, error, warning.
html
<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet" /> </head> <body> <div style="margin-top: 20px;" class="ui container"> <h2>State</h2> <div class="ui form success"> <div class="field"> <label>Enter email to get latest news</label> <input type="email" placeholder="[email protected]"> </div> <div class="ui success message"> <div class="header">Success</div> <p>You're all signed up for the newsletter.</p> </div> <div class="ui submit button">Submit</div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"> </script> </body></html>
Output:
Note:
You can replace success with error or warning to show that state.
You can use a tiny, small, large, medium, huge class to change the size of the form.
kashishsoda
Semantic-UI
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 461,
"s": 28,
"text": "Semantic UI is an open-source framework that uses CSS and jQuery to build great user interfaces. It is same as a bootstrap for use and has great different elements to use to make your website look more amazing. It uses a class to add CSS to the elements.A form is the section of a document that contains a number of input fields such as text field, password, and checkbox, etc.Example 1: This example creating a simple Log In Form. "
},
{
"code": null,
"e": 466,
"s": 461,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></head> <body> <div class=\"ui container\"> <h2>Log In</h2> <form class=\"ui form\"> <div class=\"field\"> <label>Username</label> <input type=\"text\" name=\"Username\" placeholder=\"Username\"> </div> <div class=\"field\"> <label>Password</label> <input type=\"password\" name=\"password\" placeholder=\"Password\"> </div> <div class=\"field\"> <div class=\"ui checkbox\"> <input type=\"checkbox\" tabindex=\"0\" class=\"hidden\"> <label>Remember Me</label> </div> </div> <button class=\"ui button\" type=\"submit\"> Log In </button> </form> </div> <script> $('.ui.checkbox').checkbox(); </script></body> </html>",
"e": 1956,
"s": 466,
"text": null
},
{
"code": null,
"e": 1965,
"s": 1956,
"text": "Output: "
},
{
"code": null,
"e": 2052,
"s": 1965,
"text": "Example 2: This example creating a form that contains input fields placing parallelly."
},
{
"code": null,
"e": 2057,
"s": 2052,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></head> <body> <div class=\"ui container\"> <div class=\"ui form\"> <div class=\"fields\"> <div class=\"field\"> <label>Name</label> <input type=\"text\" placeholder=\"Name\"> </div> <div class=\"field\"> <label>E-mail</label> <input type=\"email\" placeholder=\"E-mail\"> </div> <div class=\"field\"> <label>Password</label> <input type=\"password\" placeholder=\"Password\"> </div> </div> </div> </div></body> </html>",
"e": 3048,
"s": 2057,
"text": null
},
{
"code": null,
"e": 3057,
"s": 3048,
"text": "Output: "
},
{
"code": null,
"e": 3103,
"s": 3057,
"text": "Example 3: This example creating a Text Area."
},
{
"code": null,
"e": 3108,
"s": 3103,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></head> <body> <div class=\"ui container\"> <div class=\"ui form\"> <div class=\"field\"> <label>Enter Text</label> <textarea rows=\"6\"></textarea> </div> </div> </div></body> </html>",
"e": 3637,
"s": 3108,
"text": null
},
{
"code": null,
"e": 3716,
"s": 3637,
"text": "Note: You can skip the rows attribute and get standard size textarea. Output: "
},
{
"code": null,
"e": 3926,
"s": 3716,
"text": "Example 4: This example creating the Checkbox. There are a variety of checkbox styles present in semantic-ui, like the standard checkbox, toggle, and slide. And for this, you need the jQuery library imported. "
},
{
"code": null,
"e": 3956,
"s": 3926,
"text": "$('.ui.checkbox').checkbox();"
},
{
"code": null,
"e": 3961,
"s": 3956,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script></head> <body> <div class=\"ui container\"> <div class=\"ui form\"> <h2>Checkbox</h2> <div class=\"inline field\"> <div class=\"ui checkbox\"> <input type=\"checkbox\" tabindex=\"0\" class=\"hidden\"> <label>Checkbox</label> </div> </div> <h2>Toggle</h2> <div class=\"inline field\"> <div class=\"ui toggle checkbox\"> <input type=\"checkbox\" tabindex=\"0\" class=\"hidden\"> <label>Toggle</label> </div> </div> <h2>Slider</h2> <div class=\"inline field\"> <div class=\"ui slider checkbox\"> <input type=\"checkbox\" tabindex=\"0\" class=\"hidden\"> <label>Slider</label> </div> <label></label> </div> </div> </div> <script> $('.ui.checkbox').checkbox(); </script></body> </html>",
"e": 5484,
"s": 3961,
"text": null
},
{
"code": null,
"e": 5493,
"s": 5484,
"text": "Output: "
},
{
"code": null,
"e": 5592,
"s": 5493,
"text": "Example 5: This example creating the Radio Button. For this, you need a jQuery library imported. "
},
{
"code": null,
"e": 5628,
"s": 5592,
"text": "$('.ui.radio.checkbox').checkbox();"
},
{
"code": null,
"e": 5644,
"s": 5628,
"text": "Complete Code: "
},
{
"code": null,
"e": 5649,
"s": 5644,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 20px;\" class=\"ui container\"> <div class=\"ui form\"> <h2>Inline Radio Button</h2> <div class=\"inline fields\"> <label for=\"gender\">Gender</label> <div class=\"field\"> <div class=\"ui radio checkbox\"> <input type=\"radio\" name=\"gender\" checked=\"\" tabindex=\"0\" class=\"hidden\"> <label>Male</label> </div> </div> <div class=\"field\"> <div class=\"ui radio checkbox\"> <input type=\"radio\" name=\"gender\" tabindex=\"0\" class=\"hidden\"> <label>Female</label> </div> </div> <div class=\"field\"> <div class=\"ui radio checkbox\"> <input type=\"radio\" name=\"gender\" tabindex=\"0\" class=\"hidden\"> <label>Rather not Say</label> </div> </div> </div> <h2>Grouped Radio Button </h2> <div class=\"grouped fields\"> <label for=\"branch\">Select your Branch</label> <div class=\"field\"> <div class=\"ui radio checkbox\"> <input type=\"radio\" name=\"branch\" checked=\"\" tabindex=\"0\" class=\"hidden\"> <label>CSE</label> </div> </div> <div class=\"field\"> <div class=\"ui radio checkbox\"> <input type=\"radio\" name=\"branch\" tabindex=\"0\" class=\"hidden\"> <label>IT</label> </div> </div> <div class=\"field\"> <div class=\"ui radio checkbox\"> <input type=\"radio\" name=\"branch\" tabindex=\"0\" class=\"hidden\"> <label>ECE</label> </div> </div> <div class=\"field\"> <div class=\"ui radio checkbox\"> <input type=\"radio\" name=\"branch\" tabindex=\"0\" class=\"hidden\"> <label>ME</label> </div> </div> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $('.ui.radio.checkbox').checkbox(); </script> </body></html>",
"e": 8598,
"s": 5649,
"text": null
},
{
"code": null,
"e": 8607,
"s": 8598,
"text": "Output: "
},
{
"code": null,
"e": 8707,
"s": 8607,
"text": "Example 6: This example creating a Dropdown list. For this, you need to import the jQuery library. "
},
{
"code": null,
"e": 8760,
"s": 8707,
"text": "$(function() {\n $('.ui.dropdown').dropdown();\n}); "
},
{
"code": null,
"e": 8776,
"s": 8760,
"text": "Complete Code: "
},
{
"code": null,
"e": 8781,
"s": 8776,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 20px;\" class=\"ui container\"> <label>Choose Language</label> <div class=\"ui selection dropdown\"> <input type=\"hidden\" name=\"language\"> <i class=\"dropdown icon\"></i> <div class=\"default text\">Choose Language</div> <div class=\"menu\"> <div class=\"item\" data-value=\"0\">C++</div> <div class=\"item\" data-value=\"1\">Java</div> <div class=\"item\" data-value=\"2\">Python3</div> </div> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $(function() { $('.ui.dropdown').dropdown(); }); </script> </body></html>",
"e": 9996,
"s": 8781,
"text": null
},
{
"code": null,
"e": 10005,
"s": 9996,
"text": "Output: "
},
{
"code": null,
"e": 10123,
"s": 10005,
"text": "Example 7: This example creating the Multiple Select dropdown menu. For this, you need to import the jQuery library. "
},
{
"code": null,
"e": 10176,
"s": 10123,
"text": "$(function() {\n $('.ui.dropdown').dropdown();\n}); "
},
{
"code": null,
"e": 10192,
"s": 10176,
"text": "Complete Code: "
},
{
"code": null,
"e": 10197,
"s": 10192,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 50px;\" class=\"ui container\"> <div class=\"field\"> <label>Programming Language</label> <select multiple=\"\" class=\"ui dropdown\"> <option value=\"\">Select Programming Language</option> <option value=\"cpp\">C++</option> <option value=\"java\">Java</option> <option value=\"py3\">Python3</option> <option value=\"php\">PHP</option> <option value=\"ruby\">Ruby</option> <option value=\"js\">JavaScript</option> </select> </div> </div> <script src=\"https://code.jquery.com/jquery-3.1.1.min.js\" integrity=\"sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> <script> $(function() { $('.ui.dropdown').dropdown(); }); </script> </body></html>",
"e": 11486,
"s": 10197,
"text": null
},
{
"code": null,
"e": 11495,
"s": 11486,
"text": "Output: "
},
{
"code": null,
"e": 11604,
"s": 11495,
"text": "Example 8: This example creating the status of statement. The state can be any like success, error, warning."
},
{
"code": null,
"e": 11609,
"s": 11604,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Semantic UI</title> <link href=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css\" rel=\"stylesheet\" /> </head> <body> <div style=\"margin-top: 20px;\" class=\"ui container\"> <h2>State</h2> <div class=\"ui form success\"> <div class=\"field\"> <label>Enter email to get latest news</label> <input type=\"email\" placeholder=\"[email protected]\"> </div> <div class=\"ui success message\"> <div class=\"header\">Success</div> <p>You're all signed up for the newsletter.</p> </div> <div class=\"ui submit button\">Submit</div> </div> </div> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js\"> </script> </body></html>",
"e": 12509,
"s": 11609,
"text": null
},
{
"code": null,
"e": 12518,
"s": 12509,
"text": "Output: "
},
{
"code": null,
"e": 12525,
"s": 12518,
"text": "Note: "
},
{
"code": null,
"e": 12591,
"s": 12525,
"text": "You can replace success with error or warning to show that state."
},
{
"code": null,
"e": 12676,
"s": 12591,
"text": "You can use a tiny, small, large, medium, huge class to change the size of the form."
},
{
"code": null,
"e": 12688,
"s": 12676,
"text": "kashishsoda"
},
{
"code": null,
"e": 12700,
"s": 12688,
"text": "Semantic-UI"
},
{
"code": null,
"e": 12704,
"s": 12700,
"text": "CSS"
},
{
"code": null,
"e": 12721,
"s": 12704,
"text": "Web Technologies"
}
]
|
Nested Structure in C with Examples | 07 Jan, 2022
Pre-requisite: Structures in C
A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure.
Syntax:
struct name_1{ member1; member2; . . membern;
struct name_2 { member_1; member_2; . . member_n; }, var1} var2;
The member of a nested structure can be accessed using the following syntax:
Variable name of Outer_Structure.Variable name of Nested_Structure.data member to access
Example:
Consider there are two structures Employee (depended structure) and another structure called Organisation(Outer structure).
The structure Organisation has the data members like organisation_name,organisation_number.
The Employee structure is nested inside the structure Organisation and it has the data members like employee_id, name, salary.
For accessing the members of Organisation and Employee following syntax will be used:
org.emp.employee_id;org.emp.name;org.emp.salary;
org.organisation_name;org.organisation_number;
Here, org is the structure variable of the outer structure Organisation and emp is the structure variable of the inner structure Employee.
Different ways of nesting structure
The structure can be nested in the following different ways:
By separate nested structureBy embedded nested structure.
By separate nested structure
By embedded nested structure.
1. By separate nested structure: In this method, the two structures are created, but the dependent structure(Employee) should be used inside the main structure(Organisation) as a member. Below is the C program to implement the approach:
C
// C program to implement // the above approach#include <stdio.h>#include <string.h> // Declaration of the // dependent structurestruct Employee{ int employee_id; char name[20]; int salary;}; // Declaration of the // Outer structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Dependent structure is used // as a member inside the main // structure for implementing // nested structure struct Employee emp; }; // Driver codeint main(){ // Structure variable struct Organisation org; // Print the size of organisation // structure printf("The size of structure organisation : %ld\n", sizeof(org)); org.emp.employee_id = 101; strcpy(org.emp.name, "Robert"); org.emp.salary = 400000; strcpy(org.organisation_name, "GeeksforGeeks"); strcpy(org.org_number, "GFG123768"); // Printing the details printf("Organisation Name : %s\n", org.organisation_name); printf("Organisation Number : %s\n", org.org_number); printf("Employee id : %d\n", org.emp.employee_id); printf("Employee name : %s\n", org.emp.name); printf("Employee Salary : %d\n", org.emp.salary); }
Output:
The size of structure organisation : 68Organisation Name : GeeksforGeeksOrganisation Number : GFG123768Employee id : 101Employee name : RobertEmployee Salary : 400000
2. By Embedded nested structure: Using this method, allows to declare structure inside a structure and it requires fewer lines of code.
Case 1: Error will occur if the structure is present but the structure variable is missing.
C
// C program to implement // the above approach#include <stdio.h> // Declaration of the outer// structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Declaration of the employee // structure struct Employee { int employee_id; char name[20]; int salary; // This line will cause error because // datatype struct Employee is present , // but Structure variable is missing. }; }; // Driver codeint main(){ // Structure variable of organisation struct Organisation org; printf("%ld", sizeof(org));}
Output:
Note:
Whenever an embedded nested structure is created, the variable declaration is compulsory at the end of the inner structure, which acts as a member of the outer structure. It is compulsory that the structure variable is created at the end of the inner structure.
Case 2: When the structure variable of the inner structure is declared at the end of the inner structure. Below is the C program to implement this approach:
C
// C program to implement// the above approach#include <stdio.h>#include <string.h> // Declaration of the main// structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Declaration of the dependent // structure struct Employee { int employee_id; char name[20]; int salary; // variable is created which acts // as member to Organisation structure. } emp; }; // Driver codeint main(){ struct Organisation org; // Print the size of organisation // structure printf("The size of structure organisation : %ld\n", sizeof(org)); org.emp.employee_id = 101; strcpy(org.emp.name, "Robert"); org.emp.salary = 400000; strcpy(org.organisation_name, "GeeksforGeeks"); strcpy(org.org_number, "GFG123768"); // Printing the details printf("Organisation Name : %s\n", org.organisation_name); printf("Organisation Number : %s\n", org.org_number); printf("Employee id : %d\n", org.emp.employee_id); printf("Employee name : %s\n", org.emp.name); printf("Employee Salary : %d\n", org.emp.salary); }
Output:
The size of structure organisation : 68Organisation Name : GeeksforGeeksOrganisation Number : GFG123768Employee id : 101Employee name : RobertEmployee Salary : 400000
Drawback of Nested Structure
The drawback in nested structures are:
Independent existence not possible: It is important to note that structure Employee doesn’t exist on its own. One can’t declare structure variable of type struct Employee anywhere else in the program.
Cannot be used in multiple data structures: The nested structure cannot be used in multiple structures due to the limitation of declaring structure variables within the main structure. So, the most recommended way is to use a separate structure and it can be used in multiple data structures
C Nested Structure Example
Below is another example of a C nested structure.
C
// C program to implement // the nested structure#include <stdio.h>#include <string.h> // Declaration of Outer structurestruct College { char college_name[20]; int ranking; // Declaration of Inner structure struct Student { int student_id; char name[20]; int roll_no; // Inner structure variable } student1;}; // Driver codeint main(){ struct College c1 = {"GeeksforGeeks", 7, {111, "Paul", 278}}; printf("College name : %s\n", c1.college_name); printf("Ranking : %d\n", c1.ranking); printf("Student id : %d\n", c1.student1.student_id); printf("Student name : %s\n", c1.student1.name); printf("Roll no : %d\n", c1.student1.roll_no); return 0;}
Output:
College name : GeeksforGeeksRanking : 7Student id : 111Student name : PaulRoll no : 278
Note:
Nesting of structure within itself is not allowed.
Example:
struct student{
char name[50];
char address[100];
int roll_no;
struct student geek; // Invalid
}
Passing nested structure to function
A nested structure can be passed into the function in two ways:
Pass the nested structure variable at once.Pass the nested structure members as an argument into the function.
Pass the nested structure variable at once.
Pass the nested structure members as an argument into the function.
Let’s discuss each of these ways in detail.
1. Pass the nested structure variable at once: Just like other variables, a nested structure variable can also be passed to the function. Below is the C program to implement this concept:
C
// C program to implement// the above approach#include <stdio.h> // Declaration of the inner // structurestruct Employee { int employee_id; char name[20]; int salary;}; // Declaration of the Outer // structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Nested structure struct Employee emp; }; // Function show is expecting // variable of outer structurevoid show(struct Organisation); // Driver codeint main(){ struct Organisation org = {"GeeksforGeeks", "GFG111", {278, "Paul",5000}}; // Organisation structure variable // is passed to function show show(org);} // Function shoe definitionvoid show(struct Organisation org ){ // Printing the details printf("Printing the Details :\n"); printf("Organisation Name : %s\n", org.organisation_name); printf("Organisation Number : %s\n", org.org_number); printf("Employee id : %d\n", org.emp.employee_id); printf("Employee name : %s\n", org.emp.name); printf("Employee Salary : %d\n", org.emp.salary); }
Output:
Printing the Details :Organisation Name : GeeksforGeeksOrganisation Number : GFG111Employee id : 278Employee name : PaulEmployee Salary : 5000
2. Pass the nested structure members as arguments into the function: Consider the following example to pass the structure member of the employee to a function display() which is used to display the details of an employee.
C
// C program to implement// the above approach#include <stdio.h> // Declaration of the inner // structurestruct Employee { int employee_id; char name[20]; int salary;}; // Declaration of the Outer // structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Nested structure struct Employee emp; }; // Function show is expecting // members of both structuresvoid show(char organisation_name[], char org_number[], int employee_id, char name[], int salary); // Driver codeint main(){ struct Organisation org = {"GeeksforGeeks", "GFG111", {278, "Paul",5000}}; // Data members of both the structures // are passed to the function show show(org.organisation_name, org.org_number, org.emp.employee_id, org.emp.name, org.emp.salary);} // Function show definitionvoid show(char organisation_name[], char org_number[], int employee_id, char name[], int salary){ // Printing the details printf("Printing the Details :\n"); printf("Organisation Name : %s\n", organisation_name); printf("Organisation Number : %s\n", org_number); printf("Employee id : %d\n", employee_id); printf("Employee name : %s\n", name); printf("Employee Salary : %d\n", salary); }
Output:
Printing the Details :Organisation Name : GeeksforGeeksOrganisation Number : GFG111Employee id : 278Employee name : PaulEmployee Salary : 5000
Accessing Nested Structure
Nested Structure can be accessed in two ways:
Using Normal variable.Using Pointer variable.
Using Normal variable.
Using Pointer variable.
Let’s discuss each of these methods in detail.
1. Using Normal variable: Outer and inner structure variables are declared as normal variables and the data members of the outer structure are accessed using a single dot(.) and the data members of the inner structure are accessed using the two dots. Below is the C program to implement this concept:
C
// C program to implement// the above approach#include <stdio.h>#include <string.h> // Declaration of inner structurestruct college_details{ int college_id; char college_name[50]; }; // Declaration of Outer structurestruct student_detail{ int student_id; char student_name[20]; float cgpa; // Inner structure variable struct college_details clg;} stu; // Driver codeint main(){ struct student_detail stu = {12, "Kathy", 7.8, {14567, "GeeksforGeeks"}}; // Printing the details printf("College ID : %d \n", stu.clg.college_id); printf("College Name : %s \n", stu.clg.college_name); printf("Student ID : %d \n", stu.student_id); printf("Student Name : %s \n", stu.student_name); printf("Student CGPA : %f \n", stu.cgpa); return 0;}
Output:
College ID : 14567 College Name : GeeksforGeeks Student ID : 12 Student Name : Kathy Student CGPA : 7.800000
2. Using Pointer variable: One normal variable and one pointer variable of the structure are declared to explain the difference between the two. In the case of the pointer variable, a combination of dot(.) and arrow(->) will be used to access the data members. Below is the C program to implement the above approach:
C
// C program to implement// the above approach#include <stdio.h>#include <string.h> // Declaration of inner structurestruct college_details{ int college_id; char college_name[50]; }; // Declaration of Outer structurestruct student_detail{ int student_id; char student_name[20]; float cgpa; // Inner structure variable struct college_details clg;} stu, *stu_ptr; // Driver codeint main(){ struct student_detail stu = {12, "Kathy", 7.8, {14567, "GeeksforGeeks"}}; stu_ptr = &stu; // Printing the details printf("College ID : %d \n", stu_ptr->clg.college_id); printf("College Name : %s \n", stu_ptr->clg.college_name); printf("Student ID : %d \n", stu_ptr->student_id); printf("Student Name : %s \n", stu_ptr->student_name); printf("Student CGPA : %f \n", stu_ptr->cgpa); return 0;}
Output:
College ID : 14567 College Name : GeeksforGeeks Student ID : 12 Student Name : Kathy Student CGPA : 7.800000
A nested structure will allow the creation of complex data types according to the requirements of the program.
sweetyty
surindertarika1234
sagar0719kumar
simmytarika5
C-Structure & Union
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
'this' pointer in C++
Storage Classes in C
Ways to copy a vector in C++
Understanding "extern" keyword in C | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 59,
"s": 28,
"text": "Pre-requisite: Structures in C"
},
{
"code": null,
"e": 238,
"s": 59,
"text": "A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure."
},
{
"code": null,
"e": 246,
"s": 238,
"text": "Syntax:"
},
{
"code": null,
"e": 303,
"s": 246,
"text": "struct name_1{ member1; member2; . . membern;"
},
{
"code": null,
"e": 404,
"s": 303,
"text": " struct name_2 { member_1; member_2; . . member_n; }, var1} var2;"
},
{
"code": null,
"e": 481,
"s": 404,
"text": "The member of a nested structure can be accessed using the following syntax:"
},
{
"code": null,
"e": 571,
"s": 481,
"text": "Variable name of Outer_Structure.Variable name of Nested_Structure.data member to access "
},
{
"code": null,
"e": 580,
"s": 571,
"text": "Example:"
},
{
"code": null,
"e": 704,
"s": 580,
"text": "Consider there are two structures Employee (depended structure) and another structure called Organisation(Outer structure)."
},
{
"code": null,
"e": 796,
"s": 704,
"text": "The structure Organisation has the data members like organisation_name,organisation_number."
},
{
"code": null,
"e": 923,
"s": 796,
"text": "The Employee structure is nested inside the structure Organisation and it has the data members like employee_id, name, salary."
},
{
"code": null,
"e": 1009,
"s": 923,
"text": "For accessing the members of Organisation and Employee following syntax will be used:"
},
{
"code": null,
"e": 1058,
"s": 1009,
"text": "org.emp.employee_id;org.emp.name;org.emp.salary;"
},
{
"code": null,
"e": 1105,
"s": 1058,
"text": "org.organisation_name;org.organisation_number;"
},
{
"code": null,
"e": 1244,
"s": 1105,
"text": "Here, org is the structure variable of the outer structure Organisation and emp is the structure variable of the inner structure Employee."
},
{
"code": null,
"e": 1280,
"s": 1244,
"text": "Different ways of nesting structure"
},
{
"code": null,
"e": 1341,
"s": 1280,
"text": "The structure can be nested in the following different ways:"
},
{
"code": null,
"e": 1399,
"s": 1341,
"text": "By separate nested structureBy embedded nested structure."
},
{
"code": null,
"e": 1428,
"s": 1399,
"text": "By separate nested structure"
},
{
"code": null,
"e": 1458,
"s": 1428,
"text": "By embedded nested structure."
},
{
"code": null,
"e": 1695,
"s": 1458,
"text": "1. By separate nested structure: In this method, the two structures are created, but the dependent structure(Employee) should be used inside the main structure(Organisation) as a member. Below is the C program to implement the approach:"
},
{
"code": null,
"e": 1697,
"s": 1695,
"text": "C"
},
{
"code": "// C program to implement // the above approach#include <stdio.h>#include <string.h> // Declaration of the // dependent structurestruct Employee{ int employee_id; char name[20]; int salary;}; // Declaration of the // Outer structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Dependent structure is used // as a member inside the main // structure for implementing // nested structure struct Employee emp; }; // Driver codeint main(){ // Structure variable struct Organisation org; // Print the size of organisation // structure printf(\"The size of structure organisation : %ld\\n\", sizeof(org)); org.emp.employee_id = 101; strcpy(org.emp.name, \"Robert\"); org.emp.salary = 400000; strcpy(org.organisation_name, \"GeeksforGeeks\"); strcpy(org.org_number, \"GFG123768\"); // Printing the details printf(\"Organisation Name : %s\\n\", org.organisation_name); printf(\"Organisation Number : %s\\n\", org.org_number); printf(\"Employee id : %d\\n\", org.emp.employee_id); printf(\"Employee name : %s\\n\", org.emp.name); printf(\"Employee Salary : %d\\n\", org.emp.salary); }",
"e": 2911,
"s": 1697,
"text": null
},
{
"code": null,
"e": 2919,
"s": 2911,
"text": "Output:"
},
{
"code": null,
"e": 3086,
"s": 2919,
"text": "The size of structure organisation : 68Organisation Name : GeeksforGeeksOrganisation Number : GFG123768Employee id : 101Employee name : RobertEmployee Salary : 400000"
},
{
"code": null,
"e": 3223,
"s": 3086,
"text": "2. By Embedded nested structure: Using this method, allows to declare structure inside a structure and it requires fewer lines of code. "
},
{
"code": null,
"e": 3315,
"s": 3223,
"text": "Case 1: Error will occur if the structure is present but the structure variable is missing."
},
{
"code": null,
"e": 3317,
"s": 3315,
"text": "C"
},
{
"code": "// C program to implement // the above approach#include <stdio.h> // Declaration of the outer// structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Declaration of the employee // structure struct Employee { int employee_id; char name[20]; int salary; // This line will cause error because // datatype struct Employee is present , // but Structure variable is missing. }; }; // Driver codeint main(){ // Structure variable of organisation struct Organisation org; printf(\"%ld\", sizeof(org));}",
"e": 3876,
"s": 3317,
"text": null
},
{
"code": null,
"e": 3884,
"s": 3876,
"text": "Output:"
},
{
"code": null,
"e": 3890,
"s": 3884,
"text": "Note:"
},
{
"code": null,
"e": 4153,
"s": 3890,
"text": "Whenever an embedded nested structure is created, the variable declaration is compulsory at the end of the inner structure, which acts as a member of the outer structure. It is compulsory that the structure variable is created at the end of the inner structure. "
},
{
"code": null,
"e": 4310,
"s": 4153,
"text": "Case 2: When the structure variable of the inner structure is declared at the end of the inner structure. Below is the C program to implement this approach:"
},
{
"code": null,
"e": 4312,
"s": 4310,
"text": "C"
},
{
"code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Declaration of the main// structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Declaration of the dependent // structure struct Employee { int employee_id; char name[20]; int salary; // variable is created which acts // as member to Organisation structure. } emp; }; // Driver codeint main(){ struct Organisation org; // Print the size of organisation // structure printf(\"The size of structure organisation : %ld\\n\", sizeof(org)); org.emp.employee_id = 101; strcpy(org.emp.name, \"Robert\"); org.emp.salary = 400000; strcpy(org.organisation_name, \"GeeksforGeeks\"); strcpy(org.org_number, \"GFG123768\"); // Printing the details printf(\"Organisation Name : %s\\n\", org.organisation_name); printf(\"Organisation Number : %s\\n\", org.org_number); printf(\"Employee id : %d\\n\", org.emp.employee_id); printf(\"Employee name : %s\\n\", org.emp.name); printf(\"Employee Salary : %d\\n\", org.emp.salary); }",
"e": 5460,
"s": 4312,
"text": null
},
{
"code": null,
"e": 5468,
"s": 5460,
"text": "Output:"
},
{
"code": null,
"e": 5635,
"s": 5468,
"text": "The size of structure organisation : 68Organisation Name : GeeksforGeeksOrganisation Number : GFG123768Employee id : 101Employee name : RobertEmployee Salary : 400000"
},
{
"code": null,
"e": 5664,
"s": 5635,
"text": "Drawback of Nested Structure"
},
{
"code": null,
"e": 5703,
"s": 5664,
"text": "The drawback in nested structures are:"
},
{
"code": null,
"e": 5904,
"s": 5703,
"text": "Independent existence not possible: It is important to note that structure Employee doesn’t exist on its own. One can’t declare structure variable of type struct Employee anywhere else in the program."
},
{
"code": null,
"e": 6196,
"s": 5904,
"text": "Cannot be used in multiple data structures: The nested structure cannot be used in multiple structures due to the limitation of declaring structure variables within the main structure. So, the most recommended way is to use a separate structure and it can be used in multiple data structures"
},
{
"code": null,
"e": 6223,
"s": 6196,
"text": "C Nested Structure Example"
},
{
"code": null,
"e": 6273,
"s": 6223,
"text": "Below is another example of a C nested structure."
},
{
"code": null,
"e": 6275,
"s": 6273,
"text": "C"
},
{
"code": "// C program to implement // the nested structure#include <stdio.h>#include <string.h> // Declaration of Outer structurestruct College { char college_name[20]; int ranking; // Declaration of Inner structure struct Student { int student_id; char name[20]; int roll_no; // Inner structure variable } student1;}; // Driver codeint main(){ struct College c1 = {\"GeeksforGeeks\", 7, {111, \"Paul\", 278}}; printf(\"College name : %s\\n\", c1.college_name); printf(\"Ranking : %d\\n\", c1.ranking); printf(\"Student id : %d\\n\", c1.student1.student_id); printf(\"Student name : %s\\n\", c1.student1.name); printf(\"Roll no : %d\\n\", c1.student1.roll_no); return 0;}",
"e": 7031,
"s": 6275,
"text": null
},
{
"code": null,
"e": 7039,
"s": 7031,
"text": "Output:"
},
{
"code": null,
"e": 7127,
"s": 7039,
"text": "College name : GeeksforGeeksRanking : 7Student id : 111Student name : PaulRoll no : 278"
},
{
"code": null,
"e": 7133,
"s": 7127,
"text": "Note:"
},
{
"code": null,
"e": 7185,
"s": 7133,
"text": "Nesting of structure within itself is not allowed. "
},
{
"code": null,
"e": 7194,
"s": 7185,
"text": "Example:"
},
{
"code": null,
"e": 7210,
"s": 7194,
"text": "struct student{"
},
{
"code": null,
"e": 7229,
"s": 7210,
"text": " char name[50];"
},
{
"code": null,
"e": 7252,
"s": 7229,
"text": " char address[100];"
},
{
"code": null,
"e": 7269,
"s": 7252,
"text": " int roll_no;"
},
{
"code": null,
"e": 7305,
"s": 7269,
"text": " struct student geek; // Invalid"
},
{
"code": null,
"e": 7307,
"s": 7305,
"text": "}"
},
{
"code": null,
"e": 7344,
"s": 7307,
"text": "Passing nested structure to function"
},
{
"code": null,
"e": 7408,
"s": 7344,
"text": "A nested structure can be passed into the function in two ways:"
},
{
"code": null,
"e": 7519,
"s": 7408,
"text": "Pass the nested structure variable at once.Pass the nested structure members as an argument into the function."
},
{
"code": null,
"e": 7563,
"s": 7519,
"text": "Pass the nested structure variable at once."
},
{
"code": null,
"e": 7631,
"s": 7563,
"text": "Pass the nested structure members as an argument into the function."
},
{
"code": null,
"e": 7675,
"s": 7631,
"text": "Let’s discuss each of these ways in detail."
},
{
"code": null,
"e": 7863,
"s": 7675,
"text": "1. Pass the nested structure variable at once: Just like other variables, a nested structure variable can also be passed to the function. Below is the C program to implement this concept:"
},
{
"code": null,
"e": 7865,
"s": 7863,
"text": "C"
},
{
"code": "// C program to implement// the above approach#include <stdio.h> // Declaration of the inner // structurestruct Employee { int employee_id; char name[20]; int salary;}; // Declaration of the Outer // structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Nested structure struct Employee emp; }; // Function show is expecting // variable of outer structurevoid show(struct Organisation); // Driver codeint main(){ struct Organisation org = {\"GeeksforGeeks\", \"GFG111\", {278, \"Paul\",5000}}; // Organisation structure variable // is passed to function show show(org);} // Function shoe definitionvoid show(struct Organisation org ){ // Printing the details printf(\"Printing the Details :\\n\"); printf(\"Organisation Name : %s\\n\", org.organisation_name); printf(\"Organisation Number : %s\\n\", org.org_number); printf(\"Employee id : %d\\n\", org.emp.employee_id); printf(\"Employee name : %s\\n\", org.emp.name); printf(\"Employee Salary : %d\\n\", org.emp.salary); }",
"e": 8964,
"s": 7865,
"text": null
},
{
"code": null,
"e": 8972,
"s": 8964,
"text": "Output:"
},
{
"code": null,
"e": 9115,
"s": 8972,
"text": "Printing the Details :Organisation Name : GeeksforGeeksOrganisation Number : GFG111Employee id : 278Employee name : PaulEmployee Salary : 5000"
},
{
"code": null,
"e": 9337,
"s": 9115,
"text": "2. Pass the nested structure members as arguments into the function: Consider the following example to pass the structure member of the employee to a function display() which is used to display the details of an employee."
},
{
"code": null,
"e": 9339,
"s": 9337,
"text": "C"
},
{
"code": "// C program to implement// the above approach#include <stdio.h> // Declaration of the inner // structurestruct Employee { int employee_id; char name[20]; int salary;}; // Declaration of the Outer // structurestruct Organisation { char organisation_name[20]; char org_number[20]; // Nested structure struct Employee emp; }; // Function show is expecting // members of both structuresvoid show(char organisation_name[], char org_number[], int employee_id, char name[], int salary); // Driver codeint main(){ struct Organisation org = {\"GeeksforGeeks\", \"GFG111\", {278, \"Paul\",5000}}; // Data members of both the structures // are passed to the function show show(org.organisation_name, org.org_number, org.emp.employee_id, org.emp.name, org.emp.salary);} // Function show definitionvoid show(char organisation_name[], char org_number[], int employee_id, char name[], int salary){ // Printing the details printf(\"Printing the Details :\\n\"); printf(\"Organisation Name : %s\\n\", organisation_name); printf(\"Organisation Number : %s\\n\", org_number); printf(\"Employee id : %d\\n\", employee_id); printf(\"Employee name : %s\\n\", name); printf(\"Employee Salary : %d\\n\", salary); }",
"e": 10695,
"s": 9339,
"text": null
},
{
"code": null,
"e": 10703,
"s": 10695,
"text": "Output:"
},
{
"code": null,
"e": 10846,
"s": 10703,
"text": "Printing the Details :Organisation Name : GeeksforGeeksOrganisation Number : GFG111Employee id : 278Employee name : PaulEmployee Salary : 5000"
},
{
"code": null,
"e": 10873,
"s": 10846,
"text": "Accessing Nested Structure"
},
{
"code": null,
"e": 10919,
"s": 10873,
"text": "Nested Structure can be accessed in two ways:"
},
{
"code": null,
"e": 10965,
"s": 10919,
"text": "Using Normal variable.Using Pointer variable."
},
{
"code": null,
"e": 10988,
"s": 10965,
"text": "Using Normal variable."
},
{
"code": null,
"e": 11012,
"s": 10988,
"text": "Using Pointer variable."
},
{
"code": null,
"e": 11059,
"s": 11012,
"text": "Let’s discuss each of these methods in detail."
},
{
"code": null,
"e": 11360,
"s": 11059,
"text": "1. Using Normal variable: Outer and inner structure variables are declared as normal variables and the data members of the outer structure are accessed using a single dot(.) and the data members of the inner structure are accessed using the two dots. Below is the C program to implement this concept:"
},
{
"code": null,
"e": 11362,
"s": 11360,
"text": "C"
},
{
"code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Declaration of inner structurestruct college_details{ int college_id; char college_name[50]; }; // Declaration of Outer structurestruct student_detail{ int student_id; char student_name[20]; float cgpa; // Inner structure variable struct college_details clg;} stu; // Driver codeint main(){ struct student_detail stu = {12, \"Kathy\", 7.8, {14567, \"GeeksforGeeks\"}}; // Printing the details printf(\"College ID : %d \\n\", stu.clg.college_id); printf(\"College Name : %s \\n\", stu.clg.college_name); printf(\"Student ID : %d \\n\", stu.student_id); printf(\"Student Name : %s \\n\", stu.student_name); printf(\"Student CGPA : %f \\n\", stu.cgpa); return 0;}",
"e": 12150,
"s": 11362,
"text": null
},
{
"code": null,
"e": 12158,
"s": 12150,
"text": "Output:"
},
{
"code": null,
"e": 12272,
"s": 12158,
"text": "College ID : 14567 College Name : GeeksforGeeks Student ID : 12 Student Name : Kathy Student CGPA : 7.800000 "
},
{
"code": null,
"e": 12589,
"s": 12272,
"text": "2. Using Pointer variable: One normal variable and one pointer variable of the structure are declared to explain the difference between the two. In the case of the pointer variable, a combination of dot(.) and arrow(->) will be used to access the data members. Below is the C program to implement the above approach:"
},
{
"code": null,
"e": 12591,
"s": 12589,
"text": "C"
},
{
"code": "// C program to implement// the above approach#include <stdio.h>#include <string.h> // Declaration of inner structurestruct college_details{ int college_id; char college_name[50]; }; // Declaration of Outer structurestruct student_detail{ int student_id; char student_name[20]; float cgpa; // Inner structure variable struct college_details clg;} stu, *stu_ptr; // Driver codeint main(){ struct student_detail stu = {12, \"Kathy\", 7.8, {14567, \"GeeksforGeeks\"}}; stu_ptr = &stu; // Printing the details printf(\"College ID : %d \\n\", stu_ptr->clg.college_id); printf(\"College Name : %s \\n\", stu_ptr->clg.college_name); printf(\"Student ID : %d \\n\", stu_ptr->student_id); printf(\"Student Name : %s \\n\", stu_ptr->student_name); printf(\"Student CGPA : %f \\n\", stu_ptr->cgpa); return 0;}",
"e": 13435,
"s": 12591,
"text": null
},
{
"code": null,
"e": 13443,
"s": 13435,
"text": "Output:"
},
{
"code": null,
"e": 13557,
"s": 13443,
"text": "College ID : 14567 College Name : GeeksforGeeks Student ID : 12 Student Name : Kathy Student CGPA : 7.800000 "
},
{
"code": null,
"e": 13668,
"s": 13557,
"text": "A nested structure will allow the creation of complex data types according to the requirements of the program."
},
{
"code": null,
"e": 13677,
"s": 13668,
"text": "sweetyty"
},
{
"code": null,
"e": 13696,
"s": 13677,
"text": "surindertarika1234"
},
{
"code": null,
"e": 13711,
"s": 13696,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 13724,
"s": 13711,
"text": "simmytarika5"
},
{
"code": null,
"e": 13744,
"s": 13724,
"text": "C-Structure & Union"
},
{
"code": null,
"e": 13755,
"s": 13744,
"text": "C Language"
},
{
"code": null,
"e": 13853,
"s": 13755,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13901,
"s": 13853,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 13922,
"s": 13901,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 13948,
"s": 13922,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 13993,
"s": 13948,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 14031,
"s": 13993,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 14073,
"s": 14031,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 14095,
"s": 14073,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 14116,
"s": 14095,
"text": "Storage Classes in C"
},
{
"code": null,
"e": 14145,
"s": 14116,
"text": "Ways to copy a vector in C++"
}
]
|
What does symbol tilde (~) denotes in CSS ? | 17 Oct, 2019
In CSS, the symbol tilde(~) is know as Subsequent-sibling Combinator (also known as tilde or squiggle or twiddle or general-sibling selector). As the name suggests it is made of the “tilde” (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree. It is used to select all the second sequences which are preceded by the first sequence (not necessarily immediately) or in simple words selects all elements that are siblings of a specified element.
Syntax:
first-sequence ~ second-sequence {
/* property:value; */
}
Example:
<!DOCTYPE html><html> <head> <title>CSS ~ Selector</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <style> h1{ color:green; text-align: center; } hr ~ p { text-align: justify; background-color: powderblue; font-size: 130%; } </style></head> <body> <div class="container"> <h1>GeeksforGeeks</h1> <p> Sudo Placement is back to help you this placement season. Prepare for the Recruitment drive of product-based companies like Microsoft, Amazon, Adobe, etc with our free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <hr/> <p> Sudo Placement is back to help you this placement season. Prepare for the Recruitment drive of product-based companies like Microsoft, Amazon, Adobe, etc with our free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div></body> </html>
Output:
shubhamr238
CSS-Selectors
Picked
CSS
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Oct, 2019"
},
{
"code": null,
"e": 579,
"s": 28,
"text": "In CSS, the symbol tilde(~) is know as Subsequent-sibling Combinator (also known as tilde or squiggle or twiddle or general-sibling selector). As the name suggests it is made of the “tilde” (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree. It is used to select all the second sequences which are preceded by the first sequence (not necessarily immediately) or in simple words selects all elements that are siblings of a specified element."
},
{
"code": null,
"e": 587,
"s": 579,
"text": "Syntax:"
},
{
"code": null,
"e": 651,
"s": 587,
"text": "first-sequence ~ second-sequence {\n /* property:value; */\n}\n"
},
{
"code": null,
"e": 660,
"s": 651,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS ~ Selector</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <style> h1{ color:green; text-align: center; } hr ~ p { text-align: justify; background-color: powderblue; font-size: 130%; } </style></head> <body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <p> Sudo Placement is back to help you this placement season. Prepare for the Recruitment drive of product-based companies like Microsoft, Amazon, Adobe, etc with our free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> <hr/> <p> Sudo Placement is back to help you this placement season. Prepare for the Recruitment drive of product-based companies like Microsoft, Amazon, Adobe, etc with our free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. </p> </div></body> </html>",
"e": 2229,
"s": 660,
"text": null
},
{
"code": null,
"e": 2237,
"s": 2229,
"text": "Output:"
},
{
"code": null,
"e": 2249,
"s": 2237,
"text": "shubhamr238"
},
{
"code": null,
"e": 2263,
"s": 2249,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 2270,
"s": 2263,
"text": "Picked"
},
{
"code": null,
"e": 2274,
"s": 2270,
"text": "CSS"
},
{
"code": null,
"e": 2293,
"s": 2274,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2310,
"s": 2293,
"text": "Web Technologies"
},
{
"code": null,
"e": 2337,
"s": 2310,
"text": "Web technologies Questions"
}
]
|
Queue of Pairs in C++ STL with Examples | 28 Jul, 2021
Queue in STL are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement where elements are inserted at the back (end) and are deleted from the front. Queue of pair can be very efficient in designing complex data structures. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).Syntax:
Queue<pair<datatype, datatype>> queue_of_pair;
Below are the images to show the working of Queue of Pairs:
Below is an example to show the Queue of Pairs:
CPP
// C++ program to demonstrate// the working of STL queue of pairs #include <bits/stdc++.h>using namespace std; // Print the current pairvoid printPair(pair<int, int> p){ // Gives first element from queue pair int f = p.first; // Gives second element from queue pair int s = p.second; cout << "(" << f << ", " << s << ") ";} // Print the Queue of Pairsvoid showQueue(queue<pair<int, int> > gq){ // Print element until the // queue is not empty while (!gq.empty()) { printPair(gq.front()); gq.pop(); } cout << '\n';} // Driver codeint main(){ queue<pair<int, int> > gq; // Pushing elements inside // the queue container gq.push({ 10, 20 }); gq.push({ 15, 5 }); gq.push({ 1, 5 }); gq.push({ 5, 10 }); gq.push({ 7, 9 }); cout << "Queue of Pairs: "; showQueue(gq); // Prints size of queue cout << "\nSize of Queue of Pairs: " << gq.size(); // Prints first element // of queue container cout << "\nFront of Queue of Pairs: "; printPair(gq.front()); // Prints last element // of queue container cout << "\nBack of Queue of Pairs: "; printPair(gq.back()); cout << "\n\nRemoving the Front pair\n"; gq.pop(); cout << "Current Queue of Pairs: "; showQueue(gq); return 0;}
Queue of Pairs: (10, 20) (15, 5) (1, 5) (5, 10) (7, 9)
Size of Queue of Pairs: 5
Front of Queue of Pairs: (10, 20)
Back of Queue of Pairs: (7, 9)
Removing the Front pair
Current Queue of Pairs: (15, 5) (1, 5) (5, 10) (7, 9)
akshaysingh98088
cpp-pair
STL
C++ Programs
Data Structures
Queue
Data Structures
Queue
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert data in the map of strings?
Passing a function as a parameter in C++
string::npos in C++ with Examples
Reason of runtime error in C/C++
Program to delete Nth digit of a Number
SDE SHEET - A Complete Guide for SDE Preparation
Doubly Linked List | Set 1 (Introduction and Insertion)
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
What is Priority Queue | Introduction to Priority Queue | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 442,
"s": 52,
"text": "Queue in STL are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement where elements are inserted at the back (end) and are deleted from the front. Queue of pair can be very efficient in designing complex data structures. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second).Syntax: "
},
{
"code": null,
"e": 491,
"s": 442,
"text": "Queue<pair<datatype, datatype>> queue_of_pair; "
},
{
"code": null,
"e": 553,
"s": 491,
"text": "Below are the images to show the working of Queue of Pairs: "
},
{
"code": null,
"e": 604,
"s": 555,
"text": "Below is an example to show the Queue of Pairs: "
},
{
"code": null,
"e": 608,
"s": 604,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate// the working of STL queue of pairs #include <bits/stdc++.h>using namespace std; // Print the current pairvoid printPair(pair<int, int> p){ // Gives first element from queue pair int f = p.first; // Gives second element from queue pair int s = p.second; cout << \"(\" << f << \", \" << s << \") \";} // Print the Queue of Pairsvoid showQueue(queue<pair<int, int> > gq){ // Print element until the // queue is not empty while (!gq.empty()) { printPair(gq.front()); gq.pop(); } cout << '\\n';} // Driver codeint main(){ queue<pair<int, int> > gq; // Pushing elements inside // the queue container gq.push({ 10, 20 }); gq.push({ 15, 5 }); gq.push({ 1, 5 }); gq.push({ 5, 10 }); gq.push({ 7, 9 }); cout << \"Queue of Pairs: \"; showQueue(gq); // Prints size of queue cout << \"\\nSize of Queue of Pairs: \" << gq.size(); // Prints first element // of queue container cout << \"\\nFront of Queue of Pairs: \"; printPair(gq.front()); // Prints last element // of queue container cout << \"\\nBack of Queue of Pairs: \"; printPair(gq.back()); cout << \"\\n\\nRemoving the Front pair\\n\"; gq.pop(); cout << \"Current Queue of Pairs: \"; showQueue(gq); return 0;}",
"e": 1912,
"s": 608,
"text": null
},
{
"code": null,
"e": 2141,
"s": 1912,
"text": "Queue of Pairs: (10, 20) (15, 5) (1, 5) (5, 10) (7, 9) \n\nSize of Queue of Pairs: 5\nFront of Queue of Pairs: (10, 20) \nBack of Queue of Pairs: (7, 9) \n\nRemoving the Front pair\nCurrent Queue of Pairs: (15, 5) (1, 5) (5, 10) (7, 9)"
},
{
"code": null,
"e": 2160,
"s": 2143,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 2169,
"s": 2160,
"text": "cpp-pair"
},
{
"code": null,
"e": 2173,
"s": 2169,
"text": "STL"
},
{
"code": null,
"e": 2186,
"s": 2173,
"text": "C++ Programs"
},
{
"code": null,
"e": 2202,
"s": 2186,
"text": "Data Structures"
},
{
"code": null,
"e": 2208,
"s": 2202,
"text": "Queue"
},
{
"code": null,
"e": 2224,
"s": 2208,
"text": "Data Structures"
},
{
"code": null,
"e": 2230,
"s": 2224,
"text": "Queue"
},
{
"code": null,
"e": 2234,
"s": 2230,
"text": "STL"
},
{
"code": null,
"e": 2332,
"s": 2234,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2374,
"s": 2332,
"text": "How to insert data in the map of strings?"
},
{
"code": null,
"e": 2415,
"s": 2374,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 2449,
"s": 2415,
"text": "string::npos in C++ with Examples"
},
{
"code": null,
"e": 2482,
"s": 2449,
"text": "Reason of runtime error in C/C++"
},
{
"code": null,
"e": 2522,
"s": 2482,
"text": "Program to delete Nth digit of a Number"
},
{
"code": null,
"e": 2571,
"s": 2522,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 2627,
"s": 2571,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 2671,
"s": 2627,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 2696,
"s": 2671,
"text": "DSA Sheet by Love Babbar"
}
]
|
Python | Numpy numpy.resize() | 05 Mar, 2019
With the help of Numpy numpy.resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing.
Parameters:new_shape : [tuple of ints, or n ints] Shape of resized arrayrefcheck : [bool, optional] This parameter is used to check the reference counter. By Default it is True.
Returns: None
Most of you are now thinking that what is the difference between reshape and resize. When we talk about reshape then an array changes it’s shape as temporary but when we talk about resize then the changes made permanently.
Example #1:In this example we can see that with the help of .resize() method, we have changed the shape of an array from 1×6 to 2×3.
# importing the python module numpyimport numpy as np # Making a random arraygfg = np.array([1, 2, 3, 4, 5, 6]) # Reshape the array permanentlygfg.resize(2, 3) print(gfg)
[[1 2 3]
[4 5 6]]
Example #2:In this example we can see that, we are trying to resize the array of that shape which is type of out of bound values. But numpy handles this situation to append the zeros when values are not existed in the array.
# importing the python module numpyimport numpy as np # Making a random arraygfg = np.array([1, 2, 3, 4, 5, 6]) # Required values 12, existing values 6gfg.resize(3, 4) print(gfg)
[[1 2 3 4]
[5 6 0 0]
[0 0 0 0]]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Mar, 2019"
},
{
"code": null,
"e": 306,
"s": 53,
"text": "With the help of Numpy numpy.resize(), we can resize the size of an array. Array can be of any shape but to resize it we just need the size i.e (2, 2), (2, 3) and many more. During resizing numpy append zeros if values at a particular place is missing."
},
{
"code": null,
"e": 484,
"s": 306,
"text": "Parameters:new_shape : [tuple of ints, or n ints] Shape of resized arrayrefcheck : [bool, optional] This parameter is used to check the reference counter. By Default it is True."
},
{
"code": null,
"e": 498,
"s": 484,
"text": "Returns: None"
},
{
"code": null,
"e": 721,
"s": 498,
"text": "Most of you are now thinking that what is the difference between reshape and resize. When we talk about reshape then an array changes it’s shape as temporary but when we talk about resize then the changes made permanently."
},
{
"code": null,
"e": 854,
"s": 721,
"text": "Example #1:In this example we can see that with the help of .resize() method, we have changed the shape of an array from 1×6 to 2×3."
},
{
"code": "# importing the python module numpyimport numpy as np # Making a random arraygfg = np.array([1, 2, 3, 4, 5, 6]) # Reshape the array permanentlygfg.resize(2, 3) print(gfg)",
"e": 1028,
"s": 854,
"text": null
},
{
"code": null,
"e": 1048,
"s": 1028,
"text": "[[1 2 3]\n [4 5 6]]\n"
},
{
"code": null,
"e": 1273,
"s": 1048,
"text": "Example #2:In this example we can see that, we are trying to resize the array of that shape which is type of out of bound values. But numpy handles this situation to append the zeros when values are not existed in the array."
},
{
"code": "# importing the python module numpyimport numpy as np # Making a random arraygfg = np.array([1, 2, 3, 4, 5, 6]) # Required values 12, existing values 6gfg.resize(3, 4) print(gfg)",
"e": 1455,
"s": 1273,
"text": null
},
{
"code": null,
"e": 1490,
"s": 1455,
"text": "[[1 2 3 4]\n [5 6 0 0]\n [0 0 0 0]]\n"
},
{
"code": null,
"e": 1503,
"s": 1490,
"text": "Python-numpy"
},
{
"code": null,
"e": 1510,
"s": 1503,
"text": "Python"
},
{
"code": null,
"e": 1608,
"s": 1510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1626,
"s": 1608,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1668,
"s": 1626,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1690,
"s": 1668,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1725,
"s": 1690,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1751,
"s": 1725,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1783,
"s": 1751,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1812,
"s": 1783,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1839,
"s": 1812,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1869,
"s": 1839,
"text": "Iterate over a list in Python"
}
]
|
Find power of power under mod of a prime | 05 Jul, 2022
Given four numbers A, B, C and M, where M is prime number. Our task is to find ABC (mod M).Example:
Input : A = 2, B = 4, C = 3, M = 23
Output : 6
43 = 64 so,
2^64(mod 23) = 6
A Naive Approach is to calculate res = BC and then calculate Ares % M by modular exponential. The problem of this approach is that we can’t apply directly mod M on BC, so we have to calculate this value without mod M. But if we solve it directly then we will come up with the large value of exponent of A which will definitely overflow in final answer.An Efficient approach is to reduce the BC to a smaller value by using the Fermat’s Little Theorem, and then apply Modular exponential.
According the Fermat's little
a(M - 1) = 1 (mod M) if M is a prime.
So if we rewrite BC as x*(M-1) + y, then the
task of computing ABC becomes Ax*(M-1) + y
which can be written as Ax*(M-1)*Ay.
From Fermat's little theorem, we know Ax*(M-1) = 1.
So task of computing ABC reduces to computing Ay
What is the value of y?
From BC = x * (M - 1) + y,
y can be written as BC % (M-1)
We can easily use the above theorem such that we can get
A ^ (B ^ C) % M = (A ^ y ) % M
Now we only need to find two things as:-
1. y = (B ^ C) % (M - 1)
2. Ans = (A ^ y) % M
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find (a^b) mod m for a large 'a'#include<bits/stdc++.h>using namespace std; // Iterative Function to calculate (x^y)%p in O(log y)unsigned int power(unsigned int x, unsigned int y, unsigned int p){ unsigned int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} unsigned int Calculate(unsigned int A, unsigned int B, unsigned int C, unsigned int M){ unsigned int res, ans; // Calculate B ^ C (mod M - 1) res = power(B, C, M-1); // Calculate A ^ res ( mod M ) ans = power(A, res, M); return ans;} // Driver program to run the caseint main(){ // M must be a Prime Number unsigned int A = 3, B = 9, C = 4, M = 19; cout << Calculate(A, B, C, M); return 0;}
// Java program to find (a^b)// mod m for a large 'a'import java.util.*; class GFG { // Iterative Function to// calculate (x^y)%p in O(log y)static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} static int Calculate(int A, int B, int C, int M) { int res, ans; // Calculate B ^ C (mod M - 1) res = power(B, C, M - 1); // Calculate A ^ res ( mod M ) ans = power(A, res, M); return ans;} // Driver codepublic static void main(String[] args) { // M must be a Prime Number int A = 3, B = 9, C = 4, M = 19; System.out.print(Calculate(A, B, C, M));}} // This code is contributed by Anant Agarwal.
# Python program to calculate the ansdef calculate(A, B, C, M): # Calculate B ^ C (mod M - 1) res = pow(B, C, M-1) # Calculate A ^ res ( mod M ) ans = pow(A, res, M) return ans # Driver program to run the caseA = 3B = 9C = 4 # M must be Prime NumberM = 19print( calculate(A, B, C, M) )
// C# program to find (a^b) mod m for// a large 'a'using System; class GFG { // Iterative Function to calculate // (x^y)%p in O(log y) static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static int Calculate(int A, int B, int C, int M) { int res, ans; // Calculate B ^ C (mod M - 1) res = power(B, C, M - 1); // Calculate A ^ res ( mod M ) ans = power(A, res, M); return ans; } // Driver code public static void Main() { // M must be be a Prime Number int A = 3, B = 9, C = 4, M = 19; Console.Write(Calculate(A, B, C, M)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find// (a^b) mod m for a// large 'a' // Iterative Function// to calculate (x^y)%p// in O(log y)function power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it // is more than or // equal to p while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} function Calculate($A, $B, $C, $M){ $res; $ans; // Calculate B ^ C // (mod M - 1) $res = power($B, $C, $M - 1); // Calculate A ^ // res ( mod M ) $ans = power($A, $res, $M); return $ans;} // Driver Code // M must be be// a Prime Number$A = 3; $B = 9;$C = 4; $M = 19; echo Calculate($A, $B, $C, $M); // This code is contributed// by ajit?>
<script> // Javascript program to find (a^b)// mod m for a large 'a' // Iterative Function to // calculate (x^y)%p in O(log y)function power(x, y, p) { // Initialize result let res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} function Calculate(A, B, C, M) { let res, ans; // Calculate B ^ C (mod M - 1) res = power(B, C, M - 1); // Calculate A ^ res ( mod M ) ans = power(A, res, M); return ans;} // Driver Code // M must be be a Prime Number let A = 3, B = 9, C = 4, M = 19; document.write(Calculate(A, B, C, M)); </script>
Output:
18
Time Complexity: O(log(B) + log(C)) Auxiliary space: O(1)This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
jit_t
code_hunt
hr_007
amartyaghoshgfg
mitalibhola94
Modular Arithmetic
number-theory
Mathematical
number-theory
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number
Program to print prime numbers from 1 to N. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 154,
"s": 52,
"text": "Given four numbers A, B, C and M, where M is prime number. Our task is to find ABC (mod M).Example: "
},
{
"code": null,
"e": 232,
"s": 154,
"text": "Input : A = 2, B = 4, C = 3, M = 23\nOutput : 6\n43 = 64 so,\n2^64(mod 23) = 6 "
},
{
"code": null,
"e": 722,
"s": 234,
"text": "A Naive Approach is to calculate res = BC and then calculate Ares % M by modular exponential. The problem of this approach is that we can’t apply directly mod M on BC, so we have to calculate this value without mod M. But if we solve it directly then we will come up with the large value of exponent of A which will definitely overflow in final answer.An Efficient approach is to reduce the BC to a smaller value by using the Fermat’s Little Theorem, and then apply Modular exponential. "
},
{
"code": null,
"e": 1278,
"s": 722,
"text": "According the Fermat's little\na(M - 1) = 1 (mod M) if M is a prime.\n\nSo if we rewrite BC as x*(M-1) + y, then the\ntask of computing ABC becomes Ax*(M-1) + y\nwhich can be written as Ax*(M-1)*Ay.\nFrom Fermat's little theorem, we know Ax*(M-1) = 1.\nSo task of computing ABC reduces to computing Ay\n\nWhat is the value of y?\nFrom BC = x * (M - 1) + y,\ny can be written as BC % (M-1)\n\nWe can easily use the above theorem such that we can get\nA ^ (B ^ C) % M = (A ^ y ) % M\n\nNow we only need to find two things as:-\n1. y = (B ^ C) % (M - 1)\n2. Ans = (A ^ y) % M"
},
{
"code": null,
"e": 1284,
"s": 1280,
"text": "C++"
},
{
"code": null,
"e": 1289,
"s": 1284,
"text": "Java"
},
{
"code": null,
"e": 1297,
"s": 1289,
"text": "Python3"
},
{
"code": null,
"e": 1300,
"s": 1297,
"text": "C#"
},
{
"code": null,
"e": 1304,
"s": 1300,
"text": "PHP"
},
{
"code": null,
"e": 1315,
"s": 1304,
"text": "Javascript"
},
{
"code": "// C++ program to find (a^b) mod m for a large 'a'#include<bits/stdc++.h>using namespace std; // Iterative Function to calculate (x^y)%p in O(log y)unsigned int power(unsigned int x, unsigned int y, unsigned int p){ unsigned int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res*x) % p; // y must be even now y = y>>1; // y = y/2 x = (x*x) % p; } return res;} unsigned int Calculate(unsigned int A, unsigned int B, unsigned int C, unsigned int M){ unsigned int res, ans; // Calculate B ^ C (mod M - 1) res = power(B, C, M-1); // Calculate A ^ res ( mod M ) ans = power(A, res, M); return ans;} // Driver program to run the caseint main(){ // M must be a Prime Number unsigned int A = 3, B = 9, C = 4, M = 19; cout << Calculate(A, B, C, M); return 0;}",
"e": 2360,
"s": 1315,
"text": null
},
{
"code": "// Java program to find (a^b)// mod m for a large 'a'import java.util.*; class GFG { // Iterative Function to// calculate (x^y)%p in O(log y)static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} static int Calculate(int A, int B, int C, int M) { int res, ans; // Calculate B ^ C (mod M - 1) res = power(B, C, M - 1); // Calculate A ^ res ( mod M ) ans = power(A, res, M); return ans;} // Driver codepublic static void main(String[] args) { // M must be a Prime Number int A = 3, B = 9, C = 4, M = 19; System.out.print(Calculate(A, B, C, M));}} // This code is contributed by Anant Agarwal.",
"e": 3301,
"s": 2360,
"text": null
},
{
"code": "# Python program to calculate the ansdef calculate(A, B, C, M): # Calculate B ^ C (mod M - 1) res = pow(B, C, M-1) # Calculate A ^ res ( mod M ) ans = pow(A, res, M) return ans # Driver program to run the caseA = 3B = 9C = 4 # M must be Prime NumberM = 19print( calculate(A, B, C, M) )",
"e": 3605,
"s": 3301,
"text": null
},
{
"code": "// C# program to find (a^b) mod m for// a large 'a'using System; class GFG { // Iterative Function to calculate // (x^y)%p in O(log y) static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static int Calculate(int A, int B, int C, int M) { int res, ans; // Calculate B ^ C (mod M - 1) res = power(B, C, M - 1); // Calculate A ^ res ( mod M ) ans = power(A, res, M); return ans; } // Driver code public static void Main() { // M must be be a Prime Number int A = 3, B = 9, C = 4, M = 19; Console.Write(Calculate(A, B, C, M)); }} // This code is contributed by nitin mittal.",
"e": 4776,
"s": 3605,
"text": null
},
{
"code": "<?php// PHP program to find// (a^b) mod m for a// large 'a' // Iterative Function// to calculate (x^y)%p// in O(log y)function power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it // is more than or // equal to p while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} function Calculate($A, $B, $C, $M){ $res; $ans; // Calculate B ^ C // (mod M - 1) $res = power($B, $C, $M - 1); // Calculate A ^ // res ( mod M ) $ans = power($A, $res, $M); return $ans;} // Driver Code // M must be be// a Prime Number$A = 3; $B = 9;$C = 4; $M = 19; echo Calculate($A, $B, $C, $M); // This code is contributed// by ajit?>",
"e": 5687,
"s": 4776,
"text": null
},
{
"code": "<script> // Javascript program to find (a^b)// mod m for a large 'a' // Iterative Function to // calculate (x^y)%p in O(log y)function power(x, y, p) { // Initialize result let res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y % 2 != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} function Calculate(A, B, C, M) { let res, ans; // Calculate B ^ C (mod M - 1) res = power(B, C, M - 1); // Calculate A ^ res ( mod M ) ans = power(A, res, M); return ans;} // Driver Code // M must be be a Prime Number let A = 3, B = 9, C = 4, M = 19; document.write(Calculate(A, B, C, M)); </script>",
"e": 6527,
"s": 5687,
"text": null
},
{
"code": null,
"e": 6536,
"s": 6527,
"text": "Output: "
},
{
"code": null,
"e": 6539,
"s": 6536,
"text": "18"
},
{
"code": null,
"e": 7019,
"s": 6539,
"text": "Time Complexity: O(log(B) + log(C)) Auxiliary space: O(1)This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7032,
"s": 7019,
"text": "nitin mittal"
},
{
"code": null,
"e": 7038,
"s": 7032,
"text": "jit_t"
},
{
"code": null,
"e": 7048,
"s": 7038,
"text": "code_hunt"
},
{
"code": null,
"e": 7055,
"s": 7048,
"text": "hr_007"
},
{
"code": null,
"e": 7071,
"s": 7055,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 7085,
"s": 7071,
"text": "mitalibhola94"
},
{
"code": null,
"e": 7104,
"s": 7085,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 7118,
"s": 7104,
"text": "number-theory"
},
{
"code": null,
"e": 7131,
"s": 7118,
"text": "Mathematical"
},
{
"code": null,
"e": 7145,
"s": 7131,
"text": "number-theory"
},
{
"code": null,
"e": 7158,
"s": 7145,
"text": "Mathematical"
},
{
"code": null,
"e": 7177,
"s": 7158,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 7275,
"s": 7177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7296,
"s": 7275,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 7310,
"s": 7296,
"text": "Prime Numbers"
},
{
"code": null,
"e": 7363,
"s": 7310,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 7400,
"s": 7363,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 7432,
"s": 7400,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 7475,
"s": 7432,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 7502,
"s": 7475,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 7545,
"s": 7502,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 7579,
"s": 7545,
"text": "Program for factorial of a number"
}
]
|
Programs for printing different patterns in Bash | 10 Jun, 2022
Given the number N which represents the number of rows and columns, print the different following patterns in Bash.
Pattern-1:
Input: 6
Output:
#
##
###
####
#####
######
Use nested loop to print the given pattern. The first loop represents the row and the second loop represents the column.
BASH
# Program to print the# given pattern # Static input for NN=5 # variable used for# while loopi=0j=0 while [ $i -le `expr $N - 1` ]do j=0 while [ $j -le `expr $N - 1` ] do if [ `expr $N - 1` -le `expr $i + $j` ] then # Print the pattern echo -ne "#" else # Print the spaces required echo -ne " " fi j=`expr $j + 1` done # For next line echo i=`expr $i + 1`done
Output:
#
##
###
####
#####
Pattern-2:
Input: 3
Output:
#
###
#####
Use nested loops to print the left part and right part of the pattern. The details are explained in the code:
BASH
# Program in Bash to# print pyramid # Static input to the# numberp=7; for((m=1; m<=p; m++))do # This loop print spaces # required for((a=m; a<=p; a++)) do echo -ne " "; done # This loop print the left # side of the pyramid for((n=1; n<=m; n++)) do echo -ne "#"; done # This loop print right # side of the pyramid. for((i=1; i<m; i++)) do echo -ne "#"; done # New line echo;done
Output:
#
###
#####
#######
#########
###########
#############
Akanksha_Rai
coderu
simmytarika5
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 170,
"s": 52,
"text": "Given the number N which represents the number of rows and columns, print the different following patterns in Bash. "
},
{
"code": null,
"e": 182,
"s": 170,
"text": "Pattern-1: "
},
{
"code": null,
"e": 241,
"s": 182,
"text": "Input: 6\nOutput:\n #\n ##\n ###\n ####\n #####\n######"
},
{
"code": null,
"e": 363,
"s": 241,
"text": "Use nested loop to print the given pattern. The first loop represents the row and the second loop represents the column. "
},
{
"code": null,
"e": 368,
"s": 363,
"text": "BASH"
},
{
"code": "# Program to print the# given pattern # Static input for NN=5 # variable used for# while loopi=0j=0 while [ $i -le `expr $N - 1` ]do j=0 while [ $j -le `expr $N - 1` ] do if [ `expr $N - 1` -le `expr $i + $j` ] then # Print the pattern echo -ne \"#\" else # Print the spaces required echo -ne \" \" fi j=`expr $j + 1` done # For next line echo i=`expr $i + 1`done",
"e": 839,
"s": 368,
"text": null
},
{
"code": null,
"e": 848,
"s": 839,
"text": "Output: "
},
{
"code": null,
"e": 878,
"s": 848,
"text": " #\n ##\n ###\n ####\n#####"
},
{
"code": null,
"e": 890,
"s": 878,
"text": "Pattern-2: "
},
{
"code": null,
"e": 928,
"s": 890,
"text": "Input: 3\nOutput:\n #\n ###\n #####"
},
{
"code": null,
"e": 1039,
"s": 928,
"text": "Use nested loops to print the left part and right part of the pattern. The details are explained in the code: "
},
{
"code": null,
"e": 1044,
"s": 1039,
"text": "BASH"
},
{
"code": "# Program in Bash to# print pyramid # Static input to the# numberp=7; for((m=1; m<=p; m++))do # This loop print spaces # required for((a=m; a<=p; a++)) do echo -ne \" \"; done # This loop print the left # side of the pyramid for((n=1; n<=m; n++)) do echo -ne \"#\"; done # This loop print right # side of the pyramid. for((i=1; i<m; i++)) do echo -ne \"#\"; done # New line echo;done",
"e": 1495,
"s": 1044,
"text": null
},
{
"code": null,
"e": 1504,
"s": 1495,
"text": "Output: "
},
{
"code": null,
"e": 1595,
"s": 1504,
"text": " #\n ###\n #####\n #######\n #########\n ###########\n #############"
},
{
"code": null,
"e": 1610,
"s": 1597,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1617,
"s": 1610,
"text": "coderu"
},
{
"code": null,
"e": 1630,
"s": 1617,
"text": "simmytarika5"
},
{
"code": null,
"e": 1643,
"s": 1630,
"text": "Shell Script"
},
{
"code": null,
"e": 1654,
"s": 1643,
"text": "Linux-Unix"
}
]
|
Method Overloading In Ruby | 01 Apr, 2020
What is method overloading?Method overloading is a feature that allows a class to have more than one method with same name but different method signature ie. different number of arguments, order of arguments and different types of parameters. Return type is not included in method signature, thus overloaded methods can have different return type. Method overloading is an example of static binding or compile time polymorphism.
Ruby does not support method overloadingMethod overloading is a feature of statically typed language in which binding of methods takes place during compile time. But Ruby being a dynamically typed language, it does not support static binding at all. Also it is difficult to determine which method will be invoked in case of dynamic argument-based dispatch in a language with optional arguments and variable-length argument lists. In addition, the implementing language of Ruby is C which itself does not support method overloading. The most recent version of the method is considered while ignoring the previously defined versions of the method.Example below shows Ruby does not support usual approach of method overloadingExample #1:
class Test def self.sum(a,b) puts(a+b) end def self.sum(a,b,c) puts(a+b+c) end endTest.sum(1,2)
Output:
main.rb:13:in `sum': wrong number of arguments (2 for 3) (ArgumentError)
from main.rb:18:in `'
In Ruby, when a second method is defined with the same name it completely overrides the previously existing method. The previous method is no longer accessible and hence throws error when we try to access it.
Example #2:
class Test def self.sum(a,b) puts(a+b) end def self.sum(a,b,c) puts(a+b+c) end endTest.sum(1,2,7)
Output:
10
The second method overwrites the previous method and hence it works absolutely fine when we call the method with three arguments. Implementing method overloading in RubyA possible approach to implement overloading in Ruby can be by varying the number of arguments of the method. However, overloading methods using different types of arguments is possible but it becomes really difficult to keep a trace of the code.Both the approaches are demonstrated below:Method overloading by varying the number of arguments
Using Class MethodsExample :class Test def self.display(*args) case args.size when 1 puts "1: Hello #{args[0]}" when 2 puts "2: Hello #{args[0]} #{args[1]}" when 3 puts "3: Hello #{args[0]} #{args[1]} Welcome to #{args[2]} language." end endend puts "Overloading using Class Method"Test.display"Geeks!!" Test.display"Geeks!!", "Hope you doing great."Test.display"Geeks!!", "Hope you doing great.", "Ruby"OutputOverloading using Class Method
1: Hello Geeks!!
2: Hello Geeks!! Hope you doing great.
3: Hello Geeks!! Hope you doing great. Welcome to Ruby language.
The display() method is a class method. In Ruby, a class method provides functionality to the class itself. Hence we call the method directly using the class name followed by the dot operator and method name. Class methods are public by default.
class Test def self.display(*args) case args.size when 1 puts "1: Hello #{args[0]}" when 2 puts "2: Hello #{args[0]} #{args[1]}" when 3 puts "3: Hello #{args[0]} #{args[1]} Welcome to #{args[2]} language." end endend puts "Overloading using Class Method"Test.display"Geeks!!" Test.display"Geeks!!", "Hope you doing great."Test.display"Geeks!!", "Hope you doing great.", "Ruby"
Output
Overloading using Class Method
1: Hello Geeks!!
2: Hello Geeks!! Hope you doing great.
3: Hello Geeks!! Hope you doing great. Welcome to Ruby language.
The display() method is a class method. In Ruby, a class method provides functionality to the class itself. Hence we call the method directly using the class name followed by the dot operator and method name. Class methods are public by default.
Using Instance MethodsExample :class Test def display(*args) case args.size when 1 puts "1: Hello #{args[0]}" when 2 puts "2: Hello #{args[0]} #{args[1]}" when 3 puts "3: Hello #{args[0]} #{args[1]} Welcome to #{args[2]} language." end endend ob1 = Test.newob2 = Test.newob3 = Test.newputs "Overloading using Instance Method" ob1.display"Geeks!!" ob2.display"Geeks!!", "Hope you doing great."ob3.display"Geeks!!", "Hope you doing great.", "Ruby"OutputOverloading using Instance Method
1: Hello Geeks!!
2: Hello Geeks!! Hope you doing great.
3: Hello Geeks!! Hope you doing great. Welcome to Ruby language.
The instance method display() provides functionality to the instances of the class. We need to create instances of the class to call the instance method of the class. An instance method cannot be called directly using the class name.
class Test def display(*args) case args.size when 1 puts "1: Hello #{args[0]}" when 2 puts "2: Hello #{args[0]} #{args[1]}" when 3 puts "3: Hello #{args[0]} #{args[1]} Welcome to #{args[2]} language." end endend ob1 = Test.newob2 = Test.newob3 = Test.newputs "Overloading using Instance Method" ob1.display"Geeks!!" ob2.display"Geeks!!", "Hope you doing great."ob3.display"Geeks!!", "Hope you doing great.", "Ruby"
Output
Overloading using Instance Method
1: Hello Geeks!!
2: Hello Geeks!! Hope you doing great.
3: Hello Geeks!! Hope you doing great. Welcome to Ruby language.
The instance method display() provides functionality to the instances of the class. We need to create instances of the class to call the instance method of the class. An instance method cannot be called directly using the class name.
Method overloading by varying the number of arguments and types of argumentsExample :def sum(*args) case args.size when 2 if args[0].is_a?(Integer) && args[1].is_a?(Integer) puts "Int addition: #{args[0].to_i + args[1].to_i}" elsif args[0].is_a?(Integer) && args[1].is_a?(Float) puts "Int and Float addition: #{args[0].to_i + args[1].to_f}" elsif args[0].is_a?(Float) && args[1].is_a?(Integer) puts "Float and Int addition: #{args[0].to_f + args[1].to_i}" end when 3 if args[0].is_a?(Integer) && args[1].is_a?(Integer) && args[2].is_a?(Integer) puts "Int addition: #{args[0].to_i + args[1].to_i + args[2].to_i}" elsif args[0].is_a?(Integer) && args[1].is_a?(Float) && args[2].is_a?(Integer) puts "Int, Float and Int addition: #{args[0].to_i + args[1].to_f + args[2].to_i}" elsif args[0].is_a?(Float) && args[1].is_a?(Integer) && args[2].is_a?(Float) puts "Float, Int, Float addition: #{args[0].to_f + args[1].to_i + args[2].to_f}" end endend sum 5, 7sum 2.0, 6sum 4, 5.2sum 2, 3, 5sum 4.5, 5, 3.5sum 1, 2.5, 3OutputInt addition: 12
Float and Int addition: 8.0
Int and Float addition: 9.2
Int addition: 10
Float, Int, Float addition: 13.0
Int, Float and Int addition: 6.5
As the number of argument increases the code becomes complex. However we can keep increasing the number of cases to handle varying number of arguments.
def sum(*args) case args.size when 2 if args[0].is_a?(Integer) && args[1].is_a?(Integer) puts "Int addition: #{args[0].to_i + args[1].to_i}" elsif args[0].is_a?(Integer) && args[1].is_a?(Float) puts "Int and Float addition: #{args[0].to_i + args[1].to_f}" elsif args[0].is_a?(Float) && args[1].is_a?(Integer) puts "Float and Int addition: #{args[0].to_f + args[1].to_i}" end when 3 if args[0].is_a?(Integer) && args[1].is_a?(Integer) && args[2].is_a?(Integer) puts "Int addition: #{args[0].to_i + args[1].to_i + args[2].to_i}" elsif args[0].is_a?(Integer) && args[1].is_a?(Float) && args[2].is_a?(Integer) puts "Int, Float and Int addition: #{args[0].to_i + args[1].to_f + args[2].to_i}" elsif args[0].is_a?(Float) && args[1].is_a?(Integer) && args[2].is_a?(Float) puts "Float, Int, Float addition: #{args[0].to_f + args[1].to_i + args[2].to_f}" end endend sum 5, 7sum 2.0, 6sum 4, 5.2sum 2, 3, 5sum 4.5, 5, 3.5sum 1, 2.5, 3
Output
Int addition: 12
Float and Int addition: 8.0
Int and Float addition: 9.2
Int addition: 10
Float, Int, Float addition: 13.0
Int, Float and Int addition: 6.5
As the number of argument increases the code becomes complex. However we can keep increasing the number of cases to handle varying number of arguments.
Picked
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Apr, 2020"
},
{
"code": null,
"e": 457,
"s": 28,
"text": "What is method overloading?Method overloading is a feature that allows a class to have more than one method with same name but different method signature ie. different number of arguments, order of arguments and different types of parameters. Return type is not included in method signature, thus overloaded methods can have different return type. Method overloading is an example of static binding or compile time polymorphism."
},
{
"code": null,
"e": 1192,
"s": 457,
"text": "Ruby does not support method overloadingMethod overloading is a feature of statically typed language in which binding of methods takes place during compile time. But Ruby being a dynamically typed language, it does not support static binding at all. Also it is difficult to determine which method will be invoked in case of dynamic argument-based dispatch in a language with optional arguments and variable-length argument lists. In addition, the implementing language of Ruby is C which itself does not support method overloading. The most recent version of the method is considered while ignoring the previously defined versions of the method.Example below shows Ruby does not support usual approach of method overloadingExample #1:"
},
{
"code": "class Test def self.sum(a,b) puts(a+b) end def self.sum(a,b,c) puts(a+b+c) end endTest.sum(1,2)",
"e": 1319,
"s": 1192,
"text": null
},
{
"code": null,
"e": 1327,
"s": 1319,
"text": "Output:"
},
{
"code": null,
"e": 1495,
"s": 1327,
"text": "main.rb:13:in `sum': wrong number of arguments (2 for 3) (ArgumentError) \n from main.rb:18:in `' "
},
{
"code": null,
"e": 1704,
"s": 1495,
"text": "In Ruby, when a second method is defined with the same name it completely overrides the previously existing method. The previous method is no longer accessible and hence throws error when we try to access it."
},
{
"code": null,
"e": 1716,
"s": 1704,
"text": "Example #2:"
},
{
"code": "class Test def self.sum(a,b) puts(a+b) end def self.sum(a,b,c) puts(a+b+c) end endTest.sum(1,2,7)",
"e": 1845,
"s": 1716,
"text": null
},
{
"code": null,
"e": 1853,
"s": 1845,
"text": "Output:"
},
{
"code": null,
"e": 1856,
"s": 1853,
"text": "10"
},
{
"code": null,
"e": 2368,
"s": 1856,
"text": "The second method overwrites the previous method and hence it works absolutely fine when we call the method with three arguments. Implementing method overloading in RubyA possible approach to implement overloading in Ruby can be by varying the number of arguments of the method. However, overloading methods using different types of arguments is possible but it becomes really difficult to keep a trace of the code.Both the approaches are demonstrated below:Method overloading by varying the number of arguments"
},
{
"code": null,
"e": 3274,
"s": 2368,
"text": "Using Class MethodsExample :class Test def self.display(*args) case args.size when 1 puts \"1: Hello #{args[0]}\" when 2 puts \"2: Hello #{args[0]} #{args[1]}\" when 3 puts \"3: Hello #{args[0]} #{args[1]} Welcome to #{args[2]} language.\" end endend puts \"Overloading using Class Method\"Test.display\"Geeks!!\" Test.display\"Geeks!!\", \"Hope you doing great.\"Test.display\"Geeks!!\", \"Hope you doing great.\", \"Ruby\"OutputOverloading using Class Method\n1: Hello Geeks!!\n2: Hello Geeks!! Hope you doing great.\n3: Hello Geeks!! Hope you doing great. Welcome to Ruby language.\nThe display() method is a class method. In Ruby, a class method provides functionality to the class itself. Hence we call the method directly using the class name followed by the dot operator and method name. Class methods are public by default."
},
{
"code": "class Test def self.display(*args) case args.size when 1 puts \"1: Hello #{args[0]}\" when 2 puts \"2: Hello #{args[0]} #{args[1]}\" when 3 puts \"3: Hello #{args[0]} #{args[1]} Welcome to #{args[2]} language.\" end endend puts \"Overloading using Class Method\"Test.display\"Geeks!!\" Test.display\"Geeks!!\", \"Hope you doing great.\"Test.display\"Geeks!!\", \"Hope you doing great.\", \"Ruby\"",
"e": 3749,
"s": 3274,
"text": null
},
{
"code": null,
"e": 3756,
"s": 3749,
"text": "Output"
},
{
"code": null,
"e": 3909,
"s": 3756,
"text": "Overloading using Class Method\n1: Hello Geeks!!\n2: Hello Geeks!! Hope you doing great.\n3: Hello Geeks!! Hope you doing great. Welcome to Ruby language.\n"
},
{
"code": null,
"e": 4155,
"s": 3909,
"text": "The display() method is a class method. In Ruby, a class method provides functionality to the class itself. Hence we call the method directly using the class name followed by the dot operator and method name. Class methods are public by default."
},
{
"code": null,
"e": 5098,
"s": 4157,
"text": "Using Instance MethodsExample :class Test def display(*args) case args.size when 1 puts \"1: Hello #{args[0]}\" when 2 puts \"2: Hello #{args[0]} #{args[1]}\" when 3 puts \"3: Hello #{args[0]} #{args[1]} Welcome to #{args[2]} language.\" end endend ob1 = Test.newob2 = Test.newob3 = Test.newputs \"Overloading using Instance Method\" ob1.display\"Geeks!!\" ob2.display\"Geeks!!\", \"Hope you doing great.\"ob3.display\"Geeks!!\", \"Hope you doing great.\", \"Ruby\"OutputOverloading using Instance Method\n1: Hello Geeks!!\n2: Hello Geeks!! Hope you doing great.\n3: Hello Geeks!! Hope you doing great. Welcome to Ruby language.\nThe instance method display() provides functionality to the instances of the class. We need to create instances of the class to call the instance method of the class. An instance method cannot be called directly using the class name."
},
{
"code": "class Test def display(*args) case args.size when 1 puts \"1: Hello #{args[0]}\" when 2 puts \"2: Hello #{args[0]} #{args[1]}\" when 3 puts \"3: Hello #{args[0]} #{args[1]} Welcome to #{args[2]} language.\" end endend ob1 = Test.newob2 = Test.newob3 = Test.newputs \"Overloading using Instance Method\" ob1.display\"Geeks!!\" ob2.display\"Geeks!!\", \"Hope you doing great.\"ob3.display\"Geeks!!\", \"Hope you doing great.\", \"Ruby\"",
"e": 5614,
"s": 5098,
"text": null
},
{
"code": null,
"e": 5621,
"s": 5614,
"text": "Output"
},
{
"code": null,
"e": 5777,
"s": 5621,
"text": "Overloading using Instance Method\n1: Hello Geeks!!\n2: Hello Geeks!! Hope you doing great.\n3: Hello Geeks!! Hope you doing great. Welcome to Ruby language.\n"
},
{
"code": null,
"e": 6011,
"s": 5777,
"text": "The instance method display() provides functionality to the instances of the class. We need to create instances of the class to call the instance method of the class. An instance method cannot be called directly using the class name."
},
{
"code": null,
"e": 7589,
"s": 6013,
"text": "Method overloading by varying the number of arguments and types of argumentsExample :def sum(*args) case args.size when 2 if args[0].is_a?(Integer) && args[1].is_a?(Integer) puts \"Int addition: #{args[0].to_i + args[1].to_i}\" elsif args[0].is_a?(Integer) && args[1].is_a?(Float) puts \"Int and Float addition: #{args[0].to_i + args[1].to_f}\" elsif args[0].is_a?(Float) && args[1].is_a?(Integer) puts \"Float and Int addition: #{args[0].to_f + args[1].to_i}\" end when 3 if args[0].is_a?(Integer) && args[1].is_a?(Integer) && args[2].is_a?(Integer) puts \"Int addition: #{args[0].to_i + args[1].to_i + args[2].to_i}\" elsif args[0].is_a?(Integer) && args[1].is_a?(Float) && args[2].is_a?(Integer) puts \"Int, Float and Int addition: #{args[0].to_i + args[1].to_f + args[2].to_i}\" elsif args[0].is_a?(Float) && args[1].is_a?(Integer) && args[2].is_a?(Float) puts \"Float, Int, Float addition: #{args[0].to_f + args[1].to_i + args[2].to_f}\" end endend sum 5, 7sum 2.0, 6sum 4, 5.2sum 2, 3, 5sum 4.5, 5, 3.5sum 1, 2.5, 3OutputInt addition: 12\nFloat and Int addition: 8.0\nInt and Float addition: 9.2\nInt addition: 10\nFloat, Int, Float addition: 13.0\nInt, Float and Int addition: 6.5\nAs the number of argument increases the code becomes complex. However we can keep increasing the number of cases to handle varying number of arguments."
},
{
"code": "def sum(*args) case args.size when 2 if args[0].is_a?(Integer) && args[1].is_a?(Integer) puts \"Int addition: #{args[0].to_i + args[1].to_i}\" elsif args[0].is_a?(Integer) && args[1].is_a?(Float) puts \"Int and Float addition: #{args[0].to_i + args[1].to_f}\" elsif args[0].is_a?(Float) && args[1].is_a?(Integer) puts \"Float and Int addition: #{args[0].to_f + args[1].to_i}\" end when 3 if args[0].is_a?(Integer) && args[1].is_a?(Integer) && args[2].is_a?(Integer) puts \"Int addition: #{args[0].to_i + args[1].to_i + args[2].to_i}\" elsif args[0].is_a?(Integer) && args[1].is_a?(Float) && args[2].is_a?(Integer) puts \"Int, Float and Int addition: #{args[0].to_i + args[1].to_f + args[2].to_i}\" elsif args[0].is_a?(Float) && args[1].is_a?(Integer) && args[2].is_a?(Float) puts \"Float, Int, Float addition: #{args[0].to_f + args[1].to_i + args[2].to_f}\" end endend sum 5, 7sum 2.0, 6sum 4, 5.2sum 2, 3, 5sum 4.5, 5, 3.5sum 1, 2.5, 3",
"e": 8767,
"s": 7589,
"text": null
},
{
"code": null,
"e": 8774,
"s": 8767,
"text": "Output"
},
{
"code": null,
"e": 8931,
"s": 8774,
"text": "Int addition: 12\nFloat and Int addition: 8.0\nInt and Float addition: 9.2\nInt addition: 10\nFloat, Int, Float addition: 13.0\nInt, Float and Int addition: 6.5\n"
},
{
"code": null,
"e": 9083,
"s": 8931,
"text": "As the number of argument increases the code becomes complex. However we can keep increasing the number of cases to handle varying number of arguments."
},
{
"code": null,
"e": 9090,
"s": 9083,
"text": "Picked"
},
{
"code": null,
"e": 9103,
"s": 9090,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 9108,
"s": 9103,
"text": "Ruby"
},
{
"code": null,
"e": 9206,
"s": 9108,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9252,
"s": 9206,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 9283,
"s": 9252,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 9313,
"s": 9283,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 9340,
"s": 9313,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 9364,
"s": 9340,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 9395,
"s": 9364,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 9438,
"s": 9395,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 9460,
"s": 9438,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 9504,
"s": 9460,
"text": "Ruby | unless Statement and unless Modifier"
}
]
|
Python | Pandas Series.dt.dayofweek | 20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.dayofweek attribute return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6.
Syntax: Series.dt.dayofweek
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)
Output :
Now we will use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# return the day of weekresult = sr.dt.dayofweek # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.dayofweek attribute has successfully accessed and returned the day of week in the underlying data of the given series object. Example #2 : Use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'M')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)
Output :
Now we will use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object.
# return the day of weekresult = sr.dt.dayofweek # print the resultprint(result)
Output :As we can see in the output, the Series.dt.dayofweek attribute has successfully accessed and returned the day of week in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.dayofweek attribute return the day of the week. It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6."
},
{
"code": null,
"e": 330,
"s": 302,
"text": "Syntax: Series.dt.dayofweek"
},
{
"code": null,
"e": 347,
"s": 330,
"text": "Parameter : None"
},
{
"code": null,
"e": 369,
"s": 347,
"text": "Returns : numpy array"
},
{
"code": null,
"e": 515,
"s": 369,
"text": "Example #1: Use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Convert the underlying data to datetime sr = pd.to_datetime(sr) # Print the seriesprint(sr)",
"e": 908,
"s": 515,
"text": null
},
{
"code": null,
"e": 917,
"s": 908,
"text": "Output :"
},
{
"code": null,
"e": 1063,
"s": 917,
"text": "Now we will use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object."
},
{
"code": "# return the day of weekresult = sr.dt.dayofweek # print the resultprint(result)",
"e": 1145,
"s": 1063,
"text": null
},
{
"code": null,
"e": 1154,
"s": 1145,
"text": "Output :"
},
{
"code": null,
"e": 1470,
"s": 1154,
"text": "As we can see in the output, the Series.dt.dayofweek attribute has successfully accessed and returned the day of week in the underlying data of the given series object. Example #2 : Use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12', periods = 5, freq = 'M')) # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set the indexsr.index = idx # Print the seriesprint(sr)",
"e": 1744,
"s": 1470,
"text": null
},
{
"code": null,
"e": 1753,
"s": 1744,
"text": "Output :"
},
{
"code": null,
"e": 1899,
"s": 1753,
"text": "Now we will use Series.dt.dayofweek attribute to return the day of week for the given datetime in the underlying data of the given Series object."
},
{
"code": "# return the day of weekresult = sr.dt.dayofweek # print the resultprint(result)",
"e": 1981,
"s": 1899,
"text": null
},
{
"code": null,
"e": 2158,
"s": 1981,
"text": "Output :As we can see in the output, the Series.dt.dayofweek attribute has successfully accessed and returned the day of week in the underlying data of the given series object."
},
{
"code": null,
"e": 2188,
"s": 2158,
"text": "Python pandas-series-datetime"
},
{
"code": null,
"e": 2202,
"s": 2188,
"text": "Python-pandas"
},
{
"code": null,
"e": 2209,
"s": 2202,
"text": "Python"
},
{
"code": null,
"e": 2307,
"s": 2209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2339,
"s": 2307,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2366,
"s": 2339,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2387,
"s": 2366,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2410,
"s": 2387,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2466,
"s": 2410,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2497,
"s": 2466,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2539,
"s": 2497,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2581,
"s": 2539,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2620,
"s": 2581,
"text": "Python | Get unique values from a list"
}
]
|
Using Pylint to write clean Python code | by Vishal Sharma | Towards Data Science | A code linter is basically a program that inspects your code and gives feedback. A linter can tell you the issues in your program and also, a way to resolve them. You can run it anytime to ensure that your code is matching standard quality.
Linters look at aspects of code and detect lints:
Logical Lint: tells about code errors, dangerous code patternsStatistical Lint: looks at formatting issues
Logical Lint: tells about code errors, dangerous code patterns
Statistical Lint: looks at formatting issues
There are many Python linters like Flake8, Pylint, Pylama, and many others. In this article, I will be talking about Pylint because it handles both logical and statistical lint.
Install Pylint
If you want to install Pylint from the terminal, this is a one-line command to do that.
pip install pylint
I have installed Pylint in my code editor, PyCharm. For that, you can go to Preferences > Plugins and search for the “Pylint” plugin. Install and Download it from the window and restart the IDE.
Then you can set up the Exec path for the plugin so that Pycharm can execute Pylint every time user needs to inspect the code. For that, go to Settings/Preferences, click Other Settings, and then Pylint. Enter the PATH environment variable there and you are good to go.
Now, you are done! Every time you run a code now, you can use Pylint to look for refactoring, convention, and other little warning signs.
For my code, you can see I have got many display convention issues. At the lower left, you might see 4 symbols (red, yellow, blue, red ), these symbols tell the user about “Errors”, “Warnings”, “Display Conventions”, and “Refactoring” issues in the code.
I have got many blue ones which means I am having many display convention issues in my code. You can improve the code and then again turn on the linter to look at your code quality.
For people on Terminal
You can simply use the following command to inspect the code.
pylint example.py
Pylint is an amazing linter that you must have in your coding arsenal. Because code quality matters!
For feedbacks and discussions, find me at my Linkedin! | [
{
"code": null,
"e": 412,
"s": 171,
"text": "A code linter is basically a program that inspects your code and gives feedback. A linter can tell you the issues in your program and also, a way to resolve them. You can run it anytime to ensure that your code is matching standard quality."
},
{
"code": null,
"e": 462,
"s": 412,
"text": "Linters look at aspects of code and detect lints:"
},
{
"code": null,
"e": 569,
"s": 462,
"text": "Logical Lint: tells about code errors, dangerous code patternsStatistical Lint: looks at formatting issues"
},
{
"code": null,
"e": 632,
"s": 569,
"text": "Logical Lint: tells about code errors, dangerous code patterns"
},
{
"code": null,
"e": 677,
"s": 632,
"text": "Statistical Lint: looks at formatting issues"
},
{
"code": null,
"e": 855,
"s": 677,
"text": "There are many Python linters like Flake8, Pylint, Pylama, and many others. In this article, I will be talking about Pylint because it handles both logical and statistical lint."
},
{
"code": null,
"e": 870,
"s": 855,
"text": "Install Pylint"
},
{
"code": null,
"e": 958,
"s": 870,
"text": "If you want to install Pylint from the terminal, this is a one-line command to do that."
},
{
"code": null,
"e": 977,
"s": 958,
"text": "pip install pylint"
},
{
"code": null,
"e": 1172,
"s": 977,
"text": "I have installed Pylint in my code editor, PyCharm. For that, you can go to Preferences > Plugins and search for the “Pylint” plugin. Install and Download it from the window and restart the IDE."
},
{
"code": null,
"e": 1442,
"s": 1172,
"text": "Then you can set up the Exec path for the plugin so that Pycharm can execute Pylint every time user needs to inspect the code. For that, go to Settings/Preferences, click Other Settings, and then Pylint. Enter the PATH environment variable there and you are good to go."
},
{
"code": null,
"e": 1580,
"s": 1442,
"text": "Now, you are done! Every time you run a code now, you can use Pylint to look for refactoring, convention, and other little warning signs."
},
{
"code": null,
"e": 1835,
"s": 1580,
"text": "For my code, you can see I have got many display convention issues. At the lower left, you might see 4 symbols (red, yellow, blue, red ), these symbols tell the user about “Errors”, “Warnings”, “Display Conventions”, and “Refactoring” issues in the code."
},
{
"code": null,
"e": 2017,
"s": 1835,
"text": "I have got many blue ones which means I am having many display convention issues in my code. You can improve the code and then again turn on the linter to look at your code quality."
},
{
"code": null,
"e": 2040,
"s": 2017,
"text": "For people on Terminal"
},
{
"code": null,
"e": 2102,
"s": 2040,
"text": "You can simply use the following command to inspect the code."
},
{
"code": null,
"e": 2120,
"s": 2102,
"text": "pylint example.py"
},
{
"code": null,
"e": 2221,
"s": 2120,
"text": "Pylint is an amazing linter that you must have in your coding arsenal. Because code quality matters!"
}
]
|
How to create a tree view with CSS and JavaScript? | To create a tree view with CSS and JavaScript, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
ul, #treeUL {
list-style-type: none;
}
#treeUL {
margin: 0;
padding: 0;
}
.rootTree {
cursor: pointer;
user-select: none;
font-size: 18px;
font-weight: bold;
color: blue;
}
li {
font-size: 16px;
color: crimson;
font-weight: 500;
}
.rootTree::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
}
.rootTree-down::before {
transform: rotate(90deg);
}
.children {
display: none;
}
.active {
display: block;
}
</style>
</head>
<body>
<h1>Tree view example</h1>
<ul id="treeUL">
<li>
<span class="rootTree">Root</span>
<ul class="children">
<li>/bin</li>
<li>/etc</li>
<li>
<span class="rootTree">/home</span>
<ul class="children">
<li>/home/Downloads</li>
<li>/home/Pictures/</li>
<li>
<span class="rootTree">/home/Desktop</span>
<ul class="children">
<li>/home/Desktop/file.txt</li>
<li>/home/Desktop/file1.mp3</li>
<li>/home/Desktop/file1.mp4</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<script>
debugger;
console.log('wow');
var toggler = document.querySelectorAll(".rootTree");
Array.from(toggler).forEach(item => {
item.addEventListener("click", () => {
item.parentElement .querySelector(".children") .classList.toggle("active");
item.classList.toggle("rootTree-down");
});
});
</script>
</body>
</html>
The above code will produce the following output −
On expanding the tree by clicking on the caret − | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "To create a tree view with CSS and JavaScript, the code is as follows −"
},
{
"code": null,
"e": 1145,
"s": 1134,
"text": " Live Demo"
},
{
"code": null,
"e": 2777,
"s": 1145,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n ul, #treeUL {\n list-style-type: none;\n }\n #treeUL {\n margin: 0;\n padding: 0;\n }\n .rootTree {\n cursor: pointer;\n user-select: none;\n font-size: 18px;\n font-weight: bold;\n color: blue;\n }\n li {\n font-size: 16px;\n color: crimson;\n font-weight: 500;\n }\n .rootTree::before {\n content: \"\\25B6\";\n color: black;\n display: inline-block;\n margin-right: 6px;\n }\n .rootTree-down::before {\n transform: rotate(90deg);\n }\n .children {\n display: none;\n }\n .active {\n display: block;\n }\n</style>\n</head>\n<body>\n<h1>Tree view example</h1>\n<ul id=\"treeUL\">\n<li>\n<span class=\"rootTree\">Root</span>\n<ul class=\"children\">\n<li>/bin</li>\n<li>/etc</li>\n<li>\n<span class=\"rootTree\">/home</span>\n<ul class=\"children\">\n<li>/home/Downloads</li>\n<li>/home/Pictures/</li>\n<li>\n<span class=\"rootTree\">/home/Desktop</span>\n<ul class=\"children\">\n<li>/home/Desktop/file.txt</li>\n<li>/home/Desktop/file1.mp3</li>\n<li>/home/Desktop/file1.mp4</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<script>\n debugger;\n console.log('wow');\n var toggler = document.querySelectorAll(\".rootTree\");\n Array.from(toggler).forEach(item => {\n item.addEventListener(\"click\", () => {\n item.parentElement .querySelector(\".children\") .classList.toggle(\"active\");\n item.classList.toggle(\"rootTree-down\");\n });\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2828,
"s": 2777,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2877,
"s": 2828,
"text": "On expanding the tree by clicking on the caret −"
}
]
|
Bayes Theorem for Conditional Probability in C/C++ | Conditional probability denoted by P(A|B) is the probability of occurrence of an event ‘A’ given that event ‘B’ has already occurred.
Formula for conditional probability −
P(A|B) = P( A⋂B ) / P(B)
It is the formula that shows the relation between probabilities of occurrences of mutually dependent events i.e. it given the relation between their conditional probabilities.
Given an event A and another event B, according to bayes’ theorem,
P(A/B) = {P(B/A) * P(A)} / P(B)
Lets derive the formula for Bayes’ theorem,
For this we will use the formula for conditional probability,
P(A|B) = P( A?B ) / P(B) —— 1
P(B|A) = P( B?A ) / P(A) —— 2
We know that A⋂B and B⋂A are the same, hence we can substitute the value of B⋂A with A⋂B equation 2.
P(B/A) = P(A⋂B) / P(A)
P(B/A) * P(A) = P(A⋂B) —- 3
Now, using this value for A?B in equation 1, we will get the bayes’ theorem formula.
P(A/B) = {P(B/A) * P(A)} / P(B)
Some derivations for the Bayes’ Theorem,
depicted in equation 3, it says that the probability of both the events to occur in the same trials is equal to the product of conditional probability of the event and the probability of occurrence of evidence event.
P(A?B) = P(A/B) * P(B)
From this rule we can derive two important formulas −
If A⊆B i.e. A is the subset of B which means all the elements of set A are in set B, then
P(A⋂B) = P(A), then P(A/B) = P(A) / P(B)
If B⊆A i.e. B is the subset of A which means all the elements of set B are in set A, then
P(A⋂B) = P(B), then P(A/B) = 1
Bayes’ Theorem form more than three events −
If we have more that three mutually dependent events, their conditional probability will have the following relation,
P(X1/Y) = (P(X1)*P(Y/X1) / [P(X1 * P(Y/X1)) + P(X2 * P(Y/X2)) + P(X3 * P(Y/X3)) + ...] | [
{
"code": null,
"e": 1196,
"s": 1062,
"text": "Conditional probability denoted by P(A|B) is the probability of occurrence of an event ‘A’ given that event ‘B’ has already occurred."
},
{
"code": null,
"e": 1234,
"s": 1196,
"text": "Formula for conditional probability −"
},
{
"code": null,
"e": 1259,
"s": 1234,
"text": "P(A|B) = P( A⋂B ) / P(B)"
},
{
"code": null,
"e": 1435,
"s": 1259,
"text": "It is the formula that shows the relation between probabilities of occurrences of mutually dependent events i.e. it given the relation between their conditional probabilities."
},
{
"code": null,
"e": 1502,
"s": 1435,
"text": "Given an event A and another event B, according to bayes’ theorem,"
},
{
"code": null,
"e": 1534,
"s": 1502,
"text": "P(A/B) = {P(B/A) * P(A)} / P(B)"
},
{
"code": null,
"e": 1578,
"s": 1534,
"text": "Lets derive the formula for Bayes’ theorem,"
},
{
"code": null,
"e": 1640,
"s": 1578,
"text": "For this we will use the formula for conditional probability,"
},
{
"code": null,
"e": 1700,
"s": 1640,
"text": "P(A|B) = P( A?B ) / P(B) —— 1\nP(B|A) = P( B?A ) / P(A) —— 2"
},
{
"code": null,
"e": 1801,
"s": 1700,
"text": "We know that A⋂B and B⋂A are the same, hence we can substitute the value of B⋂A with A⋂B equation 2."
},
{
"code": null,
"e": 1852,
"s": 1801,
"text": "P(B/A) = P(A⋂B) / P(A)\nP(B/A) * P(A) = P(A⋂B) —- 3"
},
{
"code": null,
"e": 1937,
"s": 1852,
"text": "Now, using this value for A?B in equation 1, we will get the bayes’ theorem formula."
},
{
"code": null,
"e": 1969,
"s": 1937,
"text": "P(A/B) = {P(B/A) * P(A)} / P(B)"
},
{
"code": null,
"e": 2010,
"s": 1969,
"text": "Some derivations for the Bayes’ Theorem,"
},
{
"code": null,
"e": 2227,
"s": 2010,
"text": "depicted in equation 3, it says that the probability of both the events to occur in the same trials is equal to the product of conditional probability of the event and the probability of occurrence of evidence event."
},
{
"code": null,
"e": 2250,
"s": 2227,
"text": "P(A?B) = P(A/B) * P(B)"
},
{
"code": null,
"e": 2304,
"s": 2250,
"text": "From this rule we can derive two important formulas −"
},
{
"code": null,
"e": 2394,
"s": 2304,
"text": "If A⊆B i.e. A is the subset of B which means all the elements of set A are in set B, then"
},
{
"code": null,
"e": 2435,
"s": 2394,
"text": "P(A⋂B) = P(A), then P(A/B) = P(A) / P(B)"
},
{
"code": null,
"e": 2525,
"s": 2435,
"text": "If B⊆A i.e. B is the subset of A which means all the elements of set B are in set A, then"
},
{
"code": null,
"e": 2556,
"s": 2525,
"text": "P(A⋂B) = P(B), then P(A/B) = 1"
},
{
"code": null,
"e": 2601,
"s": 2556,
"text": "Bayes’ Theorem form more than three events −"
},
{
"code": null,
"e": 2719,
"s": 2601,
"text": "If we have more that three mutually dependent events, their conditional probability will have the following relation,"
},
{
"code": null,
"e": 2806,
"s": 2719,
"text": "P(X1/Y) = (P(X1)*P(Y/X1) / [P(X1 * P(Y/X1)) + P(X2 * P(Y/X2)) + P(X3 * P(Y/X3)) + ...]"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.